1 package Analysis.SSJava;
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.HashSet;
7 import java.util.Hashtable;
8 import java.util.Iterator;
11 import java.util.StringTokenizer;
12 import java.util.Vector;
14 import Analysis.SSJava.FlowDownCheck.ComparisonResult;
15 import Analysis.SSJava.FlowDownCheck.CompositeLattice;
16 import IR.AnnotationDescriptor;
17 import IR.ClassDescriptor;
19 import IR.FieldDescriptor;
20 import IR.MethodDescriptor;
21 import IR.NameDescriptor;
24 import IR.SymbolTable;
25 import IR.TypeDescriptor;
26 import IR.VarDescriptor;
27 import IR.Tree.ArrayAccessNode;
28 import IR.Tree.AssignmentNode;
29 import IR.Tree.BlockExpressionNode;
30 import IR.Tree.BlockNode;
31 import IR.Tree.BlockStatementNode;
32 import IR.Tree.CastNode;
33 import IR.Tree.CreateObjectNode;
34 import IR.Tree.DeclarationNode;
35 import IR.Tree.ExpressionNode;
36 import IR.Tree.FieldAccessNode;
37 import IR.Tree.IfStatementNode;
39 import IR.Tree.LiteralNode;
40 import IR.Tree.LoopNode;
41 import IR.Tree.MethodInvokeNode;
42 import IR.Tree.NameNode;
43 import IR.Tree.OpNode;
44 import IR.Tree.ReturnNode;
45 import IR.Tree.SubBlockNode;
46 import IR.Tree.SwitchBlockNode;
47 import IR.Tree.SwitchStatementNode;
48 import IR.Tree.SynchronizedNode;
49 import IR.Tree.TertiaryNode;
50 import IR.Tree.TreeNode;
53 public class FlowDownCheck {
56 static SSJavaAnalysis ssjava;
58 Set<ClassDescriptor> toanalyze;
59 List<ClassDescriptor> toanalyzeList;
61 Set<MethodDescriptor> toanalyzeMethod;
62 List<MethodDescriptor> toanalyzeMethodList;
64 // mapping from 'descriptor' to 'composite location'
65 Hashtable<Descriptor, CompositeLocation> d2loc;
67 Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
68 Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
70 // mapping from 'locID' to 'class descriptor'
71 Hashtable<String, ClassDescriptor> fieldLocName2cd;
73 boolean deterministic = true;
75 public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
79 this.toanalyzeList = new ArrayList<ClassDescriptor>();
81 this.toanalyze = new HashSet<ClassDescriptor>();
84 this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
86 this.toanalyzeMethod = new HashSet<MethodDescriptor>();
88 this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
89 this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
90 this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
91 this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
96 // construct mapping from the location name to the class descriptor
97 // assume that the location name is unique through the whole program
99 Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
100 for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
101 ClassDescriptor cd = (ClassDescriptor) iterator.next();
102 SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
103 Set<String> fieldLocNameSet = lattice.getKeySet();
105 for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
106 String fieldLocName = (String) iterator2.next();
107 fieldLocName2cd.put(fieldLocName, cd);
114 public boolean toAnalyzeIsEmpty() {
116 return toanalyzeList.isEmpty();
118 return toanalyze.isEmpty();
122 public ClassDescriptor toAnalyzeNext() {
124 return toanalyzeList.remove(0);
126 ClassDescriptor cd = toanalyze.iterator().next();
127 toanalyze.remove(cd);
132 public void setupToAnalyze() {
133 SymbolTable classtable = state.getClassSymbolTable();
135 toanalyzeList.clear();
136 toanalyzeList.addAll(classtable.getValueSet());
137 Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
138 public int compare(ClassDescriptor o1, ClassDescriptor o2) {
139 return o1.getClassName().compareTo(o2.getClassName());
144 toanalyze.addAll(classtable.getValueSet());
148 public void setupToAnalazeMethod(ClassDescriptor cd) {
150 SymbolTable methodtable = cd.getMethodTable();
152 toanalyzeMethodList.clear();
153 toanalyzeMethodList.addAll(methodtable.getValueSet());
154 Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
155 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
156 return o1.getSymbol().compareTo(o2.getSymbol());
160 toanalyzeMethod.clear();
161 toanalyzeMethod.addAll(methodtable.getValueSet());
165 public boolean toAnalyzeMethodIsEmpty() {
167 return toanalyzeMethodList.isEmpty();
169 return toanalyzeMethod.isEmpty();
173 public MethodDescriptor toAnalyzeMethodNext() {
175 return toanalyzeMethodList.remove(0);
177 MethodDescriptor md = toanalyzeMethod.iterator().next();
178 toanalyzeMethod.remove(md);
183 public void flowDownCheck() {
185 // phase 1 : checking declaration node and creating mapping of 'type
186 // desciptor' & 'location'
189 while (!toAnalyzeIsEmpty()) {
190 ClassDescriptor cd = toAnalyzeNext();
192 if (ssjava.needToBeAnnoated(cd)) {
194 ClassDescriptor superDesc = cd.getSuperDesc();
196 if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
197 checkOrderingInheritance(superDesc, cd);
200 checkDeclarationInClass(cd);
202 setupToAnalazeMethod(cd);
203 while (!toAnalyzeMethodIsEmpty()) {
204 MethodDescriptor md = toAnalyzeMethodNext();
205 if (ssjava.needTobeAnnotated(md)) {
206 checkDeclarationInMethodBody(cd, md);
214 // phase2 : checking assignments
217 while (!toAnalyzeIsEmpty()) {
218 ClassDescriptor cd = toAnalyzeNext();
220 setupToAnalazeMethod(cd);
221 while (!toAnalyzeMethodIsEmpty()) {
222 MethodDescriptor md = toAnalyzeMethodNext();
223 if (ssjava.needTobeAnnotated(md)) {
224 System.out.println("SSJAVA: Checking assignments: " + md);
225 checkMethodBody(cd, md);
232 private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
233 // here, we're going to check that sub class keeps same relative orderings
234 // in respect to super class
236 SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
237 SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
239 if (superLattice != null) {
240 // if super class doesn't define lattice, then we don't need to check its
242 if (subLattice == null) {
243 throw new Error("If a parent class '" + superCd
244 + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
247 Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
248 Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
250 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
251 Pair<String, String> pair = (Pair<String, String>) iterator.next();
253 if (!subPairSet.contains(pair)) {
254 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
255 + pair.getSecond() + " < " + pair.getFirst()
256 + "' that is defined by its superclass '" + superCd + "'.");
261 MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
262 MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
264 if (superMethodDefaultLattice != null) {
265 if (subMethodDefaultLattice == null) {
266 throw new Error("When a parent class '" + superCd
267 + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
270 Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
271 Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
273 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
274 Pair<String, String> pair = (Pair<String, String>) iterator.next();
276 if (!subPairSet.contains(pair)) {
277 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
278 + pair.getSecond() + " < " + pair.getFirst()
279 + "' that is defined by its superclass '" + superCd
280 + "' in the method default lattice.");
288 public Hashtable getMap() {
292 private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
293 BlockNode bn = state.getMethodBody(md);
295 // first, check annotations on method parameters
296 List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
297 for (int i = 0; i < md.numParameters(); i++) {
298 // process annotations on method parameters
299 VarDescriptor vd = (VarDescriptor) md.getParameter(i);
300 assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), bn);
301 paramList.add(d2loc.get(vd));
304 // second, check return location annotation
305 if (!md.getReturnType().isVoid()) {
306 CompositeLocation returnLocComp = null;
307 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
308 if (methodAnnotations != null) {
309 for (int i = 0; i < methodAnnotations.size(); i++) {
310 AnnotationDescriptor an = methodAnnotations.elementAt(i);
311 if (an.getMarker().equals(ssjava.RETURNLOC)) {
312 // developer explicitly defines method lattice
313 String returnLocDeclaration = an.getValue();
314 returnLocComp = parseLocationDeclaration(md, null, returnLocDeclaration);
315 md2ReturnLoc.put(md, returnLocComp);
319 if (returnLocComp == null) {
320 MethodLattice<String> methodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
321 if (methodDefaultLattice.getReturnLoc() != null) {
322 returnLocComp = parseLocationDeclaration(md, null, methodDefaultLattice.getReturnLoc());
323 md2ReturnLoc.put(md, returnLocComp);
327 if (!md2ReturnLoc.containsKey(md)) {
328 throw new Error("Return location is not specified for the method " + md + " at "
329 + cd.getSourceFileName());
332 // check this location
333 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
334 String thisLocId = methodLattice.getThisLoc();
335 if (thisLocId == null) {
336 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
337 + md.getClassDesc().getSourceFileName());
339 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
340 paramList.add(0, thisLoc);
342 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList,
343 generateErrorMessage(cd, null)));
346 // third, check declarations inside of method
348 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
352 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
353 bn.getVarTable().setParent(nametable);
354 for (int i = 0; i < bn.size(); i++) {
355 BlockStatementNode bsn = bn.get(i);
356 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
360 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
361 BlockStatementNode bsn) {
363 switch (bsn.kind()) {
364 case Kind.SubBlockNode:
365 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
368 case Kind.DeclarationNode:
369 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
373 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
376 case Kind.IfStatementNode:
377 checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
380 case Kind.SwitchStatementNode:
381 checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
384 case Kind.SynchronizedNode:
385 checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
391 private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
392 SynchronizedNode sbn) {
393 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
396 private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
397 SwitchStatementNode ssn) {
398 BlockNode sbn = ssn.getSwitchBody();
399 for (int i = 0; i < sbn.size(); i++) {
400 SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
401 checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
405 private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
406 IfStatementNode isn) {
407 checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
408 if (isn.getFalseBlock() != null)
409 checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
412 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
414 if (ln.getType() == LoopNode.FORLOOP) {
415 // check for loop case
416 ClassDescriptor cd = md.getClassDesc();
417 BlockNode bn = ln.getInitializer();
418 for (int i = 0; i < bn.size(); i++) {
419 BlockStatementNode bsn = bn.get(i);
420 checkDeclarationInBlockStatementNode(md, nametable, bsn);
425 checkDeclarationInBlockNode(md, nametable, ln.getBody());
428 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
429 BlockNode bn = state.getMethodBody(md);
430 checkLocationFromBlockNode(md, md.getParameterTable(), bn, null);
433 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
435 return cd.getSourceFileName() + "::" + tn.getNumLine();
437 return cd.getSourceFileName();
442 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
443 BlockNode bn, CompositeLocation constraint) {
445 bn.getVarTable().setParent(nametable);
446 for (int i = 0; i < bn.size(); i++) {
447 BlockStatementNode bsn = bn.get(i);
448 checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
450 return new CompositeLocation();
454 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
455 SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
457 CompositeLocation compLoc = null;
458 switch (bsn.kind()) {
459 case Kind.BlockExpressionNode:
461 checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
464 case Kind.DeclarationNode:
465 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
468 case Kind.IfStatementNode:
469 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
473 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
476 case Kind.ReturnNode:
477 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
480 case Kind.SubBlockNode:
481 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
484 case Kind.ContinueBreakNode:
485 compLoc = new CompositeLocation();
488 case Kind.SwitchStatementNode:
490 checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
496 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
497 SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
499 ClassDescriptor cd = md.getClassDesc();
500 CompositeLocation condLoc =
501 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
503 BlockNode sbn = ssn.getSwitchBody();
505 constraint = generateNewConstraint(constraint, condLoc);
507 for (int i = 0; i < sbn.size(); i++) {
508 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
510 return new CompositeLocation();
513 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
514 SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
516 CompositeLocation blockLoc =
517 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
523 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
524 ReturnNode rn, CompositeLocation constraint) {
526 ExpressionNode returnExp = rn.getReturnExpression();
528 CompositeLocation returnValueLoc;
529 if (returnExp != null) {
531 checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
534 // if this return statement is inside branch, return value has an implicit
535 // flow from conditional location
536 if (constraint != null) {
537 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
538 inputGLB.add(returnValueLoc);
539 inputGLB.add(constraint);
541 CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), rn));
544 // check if return value is equal or higher than RETRUNLOC of method
545 // declaration annotation
546 CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
549 CompositeLattice.compare(returnValueLoc, declaredReturnLoc,
550 generateErrorMessage(md.getClassDesc(), rn));
552 if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
554 "Return value location is not equal or higher than the declaraed return location at "
555 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
559 return new CompositeLocation();
562 private boolean hasOnlyLiteralValue(ExpressionNode en) {
563 if (en.kind() == Kind.LiteralNode) {
570 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
571 LoopNode ln, CompositeLocation constraint) {
573 ClassDescriptor cd = md.getClassDesc();
574 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
576 CompositeLocation condLoc =
577 checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
578 new CompositeLocation(), constraint, false);
579 addLocationType(ln.getCondition().getType(), (condLoc));
581 constraint = generateNewConstraint(constraint, condLoc);
582 checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
584 return new CompositeLocation();
587 // check 'for loop' case
588 BlockNode bn = ln.getInitializer();
589 bn.getVarTable().setParent(nametable);
591 // calculate glb location of condition and update statements
592 CompositeLocation condLoc =
593 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
594 new CompositeLocation(), constraint, false);
595 addLocationType(ln.getCondition().getType(), condLoc);
597 constraint = generateNewConstraint(constraint, condLoc);
599 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
600 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
602 return new CompositeLocation();
608 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
609 SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
610 CompositeLocation compLoc =
611 checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
615 private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
616 CompositeLocation newCon) {
618 if (currentCon == null) {
621 // compute GLB of current constraint and new constraint
622 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
623 inputSet.add(currentCon);
624 inputSet.add(newCon);
625 return CompositeLattice.calculateGLB(inputSet, "");
630 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
631 SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
633 CompositeLocation condLoc =
634 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
637 addLocationType(isn.getCondition().getType(), condLoc);
639 constraint = generateNewConstraint(constraint, condLoc);
640 checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
642 if (isn.getFalseBlock() != null) {
643 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
646 return new CompositeLocation();
649 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
650 SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
652 VarDescriptor vd = dn.getVarDescriptor();
654 CompositeLocation destLoc = d2loc.get(vd);
656 if (dn.getExpression() != null) {
657 CompositeLocation expressionLoc =
658 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
659 new CompositeLocation(), constraint, false);
660 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
662 if (expressionLoc != null) {
663 // checking location order
664 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
665 generateErrorMessage(md.getClassDesc(), dn))) {
666 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
667 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
668 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
671 return expressionLoc;
675 return new CompositeLocation();
681 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
683 checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
686 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
687 SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
688 CompositeLocation compLoc =
689 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
690 // addTypeLocation(ben.getExpression().getType(), compLoc);
694 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
695 SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
696 CompositeLocation constraint, boolean isLHS) {
698 CompositeLocation compLoc = null;
701 case Kind.AssignmentNode:
703 checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
706 case Kind.FieldAccessNode:
708 checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
712 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
716 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
719 case Kind.CreateObjectNode:
720 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
723 case Kind.ArrayAccessNode:
725 checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
728 case Kind.LiteralNode:
729 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
732 case Kind.MethodInvokeNode:
734 checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
737 case Kind.TertiaryNode:
738 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
742 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
745 // case Kind.InstanceOfNode:
746 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
749 // case Kind.ArrayInitializerNode:
750 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
754 // case Kind.ClassTypeNode:
755 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
758 // case Kind.OffsetNode:
759 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
766 // addTypeLocation(en.getType(), compLoc);
771 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
772 CastNode cn, CompositeLocation constraint) {
774 ExpressionNode en = cn.getExpression();
775 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
780 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
781 SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
782 ClassDescriptor cd = md.getClassDesc();
784 CompositeLocation condLoc =
785 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
787 addLocationType(tn.getCond().getType(), condLoc);
788 CompositeLocation trueLoc =
789 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
791 addLocationType(tn.getTrueExpr().getType(), trueLoc);
792 CompositeLocation falseLoc =
793 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
795 addLocationType(tn.getFalseExpr().getType(), falseLoc);
797 // locations from true/false branches can be TOP when there are only literal
799 // in this case, we don't need to check flow down rule!
801 // check if condLoc is higher than trueLoc & falseLoc
802 if (!trueLoc.get(0).isTop()
803 && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
805 "The location of the condition expression is lower than the true expression at "
806 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
809 if (!falseLoc.get(0).isTop()
810 && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
811 generateErrorMessage(cd, tn.getCond()))) {
813 "The location of the condition expression is lower than the true expression at "
814 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
817 // then, return glb of trueLoc & falseLoc
818 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
819 glbInputSet.add(trueLoc);
820 glbInputSet.add(falseLoc);
822 return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
825 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
826 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
827 CompositeLocation constraint) {
829 checkCalleeConstraints(md, nametable, min, constraint);
831 CompositeLocation baseLocation = null;
832 if (min.getExpression() != null) {
834 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
835 new CompositeLocation(), constraint, false);
837 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
838 baseLocation = new CompositeLocation(new Location(md, thisLocId));
841 if (!min.getMethod().getReturnType().isVoid()) {
842 // If method has a return value, compute the highest possible return
843 // location in the caller's perspective
844 CompositeLocation ceilingLoc =
845 computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
849 return new CompositeLocation();
853 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
854 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
855 CompositeLocation constraint) {
856 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
858 // by default, method has a THIS parameter
859 argList.add(baseLocation);
861 for (int i = 0; i < min.numArgs(); i++) {
862 ExpressionNode en = min.getArg(i);
863 CompositeLocation callerArg =
864 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
866 argList.add(callerArg);
869 System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
870 CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
871 DeltaLocation delta = new DeltaLocation(compLoc, 1);
872 System.out.println("##computeReturnLocation=" + delta);
878 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
879 MethodInvokeNode min, CompositeLocation constraint) {
881 if (min.numArgs() > 1) {
882 // caller needs to guarantee that it passes arguments in regarding to
883 // callee's hierarchy
884 for (int i = 0; i < min.numArgs(); i++) {
885 ExpressionNode en = min.getArg(i);
886 CompositeLocation callerArg1 =
887 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
890 VarDescriptor calleevd = (VarDescriptor) min.getMethod().getParameter(i);
891 CompositeLocation calleeLoc1 = d2loc.get(calleevd);
893 if (!callerArg1.get(0).isTop()) {
894 // here, check if ordering relations among caller's args respect
895 // ordering relations in-between callee's args
896 for (int currentIdx = 0; currentIdx < min.numArgs(); currentIdx++) {
897 if (currentIdx != i) { // skip itself
898 ExpressionNode argExp = min.getArg(currentIdx);
900 CompositeLocation callerArg2 =
901 checkLocationFromExpressionNode(md, nametable, argExp, new CompositeLocation(),
904 VarDescriptor calleevd2 = (VarDescriptor) min.getMethod().getParameter(currentIdx);
905 CompositeLocation calleeLoc2 = d2loc.get(calleevd2);
908 CompositeLattice.compare(callerArg1, callerArg2,
909 generateErrorMessage(md.getClassDesc(), min));
911 CompositeLattice.compare(calleeLoc1, calleeLoc2,
912 generateErrorMessage(md.getClassDesc(), min));
914 if (calleeResult == ComparisonResult.GREATER
915 && callerResult != ComparisonResult.GREATER) {
916 // If calleeLoc1 is higher than calleeLoc2
917 // then, caller should have same ordering relation in-bet
918 // callerLoc1 & callerLoc2
920 throw new Error("Caller doesn't respect ordering relations among method arguments:"
921 + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
934 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
935 SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
937 ClassDescriptor cd = md.getClassDesc();
939 CompositeLocation arrayLoc =
940 checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
941 new CompositeLocation(), constraint, isLHS);
942 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
943 CompositeLocation indexLoc =
944 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
946 // addTypeLocation(aan.getIndex().getType(), indexLoc);
949 if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
950 throw new Error("Array index value is not higher than array location at "
951 + generateErrorMessage(cd, aan));
955 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
956 inputGLB.add(arrayLoc);
957 inputGLB.add(indexLoc);
958 return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
963 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
964 SymbolTable nametable, CreateObjectNode con) {
966 ClassDescriptor cd = md.getClassDesc();
968 CompositeLocation compLoc = new CompositeLocation();
969 compLoc.addLocation(Location.createTopLocation(md));
974 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
975 OpNode on, CompositeLocation constraint) {
977 ClassDescriptor cd = md.getClassDesc();
978 CompositeLocation leftLoc = new CompositeLocation();
980 checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
981 // addTypeLocation(on.getLeft().getType(), leftLoc);
983 CompositeLocation rightLoc = new CompositeLocation();
984 if (on.getRight() != null) {
986 checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
987 // addTypeLocation(on.getRight().getType(), rightLoc);
990 System.out.println("\n# OP NODE=" + on.printNode(0));
991 System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
992 if (on.getRight() != null) {
993 System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
996 Operation op = on.getOp();
998 switch (op.getOp()) {
1000 case Operation.UNARYPLUS:
1001 case Operation.UNARYMINUS:
1002 case Operation.LOGIC_NOT:
1006 case Operation.LOGIC_OR:
1007 case Operation.LOGIC_AND:
1008 case Operation.COMP:
1009 case Operation.BIT_OR:
1010 case Operation.BIT_XOR:
1011 case Operation.BIT_AND:
1012 case Operation.ISAVAILABLE:
1013 case Operation.EQUAL:
1014 case Operation.NOTEQUAL:
1021 case Operation.MULT:
1024 case Operation.LEFTSHIFT:
1025 case Operation.RIGHTSHIFT:
1026 case Operation.URIGHTSHIFT:
1028 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1029 inputSet.add(leftLoc);
1030 inputSet.add(rightLoc);
1031 CompositeLocation glbCompLoc =
1032 CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1033 System.out.println("# glbCompLoc=" + glbCompLoc);
1037 throw new Error(op.toString());
1042 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1043 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1045 // literal value has the top location so that value can be flowed into any
1047 Location literalLoc = Location.createTopLocation(md);
1048 loc.addLocation(literalLoc);
1053 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1054 NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1056 NameDescriptor nd = nn.getName();
1057 if (nd.getBase() != null) {
1059 checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1061 String varname = nd.toString();
1062 if (varname.equals("this")) {
1064 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1065 String thisLocId = methodLattice.getThisLoc();
1066 if (thisLocId == null) {
1067 throw new Error("The location for 'this' is not defined at "
1068 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1070 Location locElement = new Location(md, thisLocId);
1071 loc.addLocation(locElement);
1075 Descriptor d = (Descriptor) nametable.get(varname);
1077 // CompositeLocation localLoc = null;
1078 if (d instanceof VarDescriptor) {
1079 VarDescriptor vd = (VarDescriptor) d;
1080 // localLoc = d2loc.get(vd);
1081 // the type of var descriptor has a composite location!
1082 loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1083 } else if (d instanceof FieldDescriptor) {
1084 // the type of field descriptor has a location!
1085 FieldDescriptor fd = (FieldDescriptor) d;
1086 if (fd.isStatic()) {
1088 // if it is 'static final', the location has TOP since no one can
1090 loc.addLocation(Location.createTopLocation(md));
1093 // if 'static', the location has pre-assigned global loc
1094 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1095 String globalLocId = localLattice.getGlobalLoc();
1096 if (globalLocId == null) {
1097 throw new Error("Global location element is not defined in the method " + md);
1099 Location globalLoc = new Location(md, globalLocId);
1101 loc.addLocation(globalLoc);
1104 // the location of field access starts from this, followed by field
1106 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1107 Location thisLoc = new Location(md, localLattice.getThisLoc());
1108 loc.addLocation(thisLoc);
1111 Location fieldLoc = (Location) fd.getType().getExtension();
1112 loc.addLocation(fieldLoc);
1113 } else if (d == null) {
1115 // check if the var is a static field of the class
1116 FieldDescriptor fd = nn.getField();
1117 ClassDescriptor cd = nn.getClassDesc();
1119 if (fd != null && cd != null) {
1121 if (fd.isStatic() && fd.isFinal()) {
1122 loc.addLocation(Location.createTopLocation(md));
1125 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1126 Location fieldLoc = new Location(md, localLattice.getThisLoc());
1127 loc.addLocation(fieldLoc);
1136 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1137 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1138 CompositeLocation constraint) {
1140 ExpressionNode left = fan.getExpression();
1141 TypeDescriptor ltd = left.getType();
1143 FieldDescriptor fd = fan.getField();
1145 String varName = null;
1146 if (left.kind() == Kind.NameNode) {
1147 NameDescriptor nd = ((NameNode) left).getName();
1148 varName = nd.toString();
1151 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1152 // using a class name directly or access using this
1153 if (fd.isStatic() && fd.isFinal()) {
1154 loc.addLocation(Location.createTopLocation(md));
1159 loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1160 if (!left.getType().isPrimitive()) {
1161 Location fieldLoc = getFieldLocation(fd);
1162 loc.addLocation(fieldLoc);
1168 private Location getFieldLocation(FieldDescriptor fd) {
1170 Location fieldLoc = (Location) fd.getType().getExtension();
1172 // handle the case that method annotation checking skips checking field
1174 if (fieldLoc == null) {
1175 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1182 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1183 SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1185 System.out.println("\n# ASSIGNMENTNODE=" + an.printNode(0));
1187 ClassDescriptor cd = md.getClassDesc();
1189 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1191 boolean postinc = true;
1192 if (an.getOperation().getBaseOp() == null
1193 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1194 .getBaseOp().getOp() != Operation.POSTDEC))
1197 // if LHS is array access node, need to check if array index is higher
1198 // than array itself
1199 CompositeLocation destLocation =
1200 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1203 CompositeLocation rhsLocation;
1204 CompositeLocation srcLocation;
1208 checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1211 System.out.println("dstLocation=" + destLocation);
1212 System.out.println("rhsLocation=" + rhsLocation);
1213 System.out.println("constraint=" + constraint);
1215 if (constraint != null) {
1216 inputGLBSet.add(rhsLocation);
1217 inputGLBSet.add(constraint);
1218 srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1220 srcLocation = rhsLocation;
1223 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1224 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1225 + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1226 + cd.getSourceFileName() + "::" + an.getNumLine());
1232 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1235 if (constraint != null) {
1236 inputGLBSet.add(rhsLocation);
1237 inputGLBSet.add(constraint);
1238 srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1240 srcLocation = rhsLocation;
1243 System.out.println("srcLocation=" + srcLocation);
1244 System.out.println("rhsLocation=" + rhsLocation);
1245 System.out.println("constraint=" + constraint);
1247 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1248 throw new Error("Location " + destLocation
1249 + " is not allowed to have the value flow that moves within the same location at "
1250 + cd.getSourceFileName() + "::" + an.getNumLine());
1255 return destLocation;
1258 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1259 SymbolTable nametable, TreeNode n) {
1261 ClassDescriptor cd = md.getClassDesc();
1262 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1264 // currently enforce every variable to have corresponding location
1265 if (annotationVec.size() == 0) {
1266 throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1267 + md.getSymbol() + " of the class " + cd.getSymbol());
1270 if (annotationVec.size() > 1) { // variable can have at most one location
1271 throw new Error(vd.getSymbol() + " has more than one location.");
1274 AnnotationDescriptor ad = annotationVec.elementAt(0);
1276 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1278 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1279 String locDec = ad.getValue(); // check if location is defined
1281 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1282 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1283 d2loc.put(vd, deltaLoc);
1284 addLocationType(vd.getType(), deltaLoc);
1286 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1288 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1289 if (ssjava.isSharedLocation(lastElement)) {
1290 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1293 d2loc.put(vd, compLoc);
1294 addLocationType(vd.getType(), compLoc);
1302 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1305 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1308 int beginIdx = dIdx + 6;
1309 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1310 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1313 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1314 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1319 private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1321 int idx = decl.indexOf(".");
1323 String className = decl.substring(0, idx);
1324 String fieldName = decl.substring(idx + 1);
1326 className.replaceAll(" ", "");
1327 fieldName.replaceAll(" ", "");
1329 Descriptor d = state.getClassSymbolTable().get(className);
1332 System.out.println("state.getClassSymbolTable()=" + state.getClassSymbolTable());
1333 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1337 assert (d instanceof ClassDescriptor);
1338 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1339 if (!lattice.containsKey(fieldName)) {
1340 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1341 + className + "' at " + msg);
1344 return new Location(d, fieldName);
1347 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1349 CompositeLocation compLoc = new CompositeLocation();
1351 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1352 List<String> locIdList = new ArrayList<String>();
1353 while (tokenizer.hasMoreTokens()) {
1354 String locId = tokenizer.nextToken();
1355 locIdList.add(locId);
1358 // at least,one location element needs to be here!
1359 assert (locIdList.size() > 0);
1361 // assume that loc with idx 0 comes from the local lattice
1362 // loc with idx 1 comes from the field lattice
1364 String localLocId = locIdList.get(0);
1365 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1366 Location localLoc = new Location(md, localLocId);
1367 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1368 System.out.println("locDec=" + locDec);
1369 throw new Error("Location " + localLocId
1370 + " is not defined in the local variable lattice at "
1371 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1373 compLoc.addLocation(localLoc);
1375 for (int i = 1; i < locIdList.size(); i++) {
1376 String locName = locIdList.get(i);
1379 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1380 compLoc.addLocation(fieldLoc);
1381 } catch (Exception e) {
1382 throw new Error("The location declaration '" + locName + "' is wrong at "
1383 + generateErrorMessage(md.getClassDesc(), n));
1391 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1392 VarDescriptor vd = dn.getVarDescriptor();
1393 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1396 private void checkDeclarationInClass(ClassDescriptor cd) {
1397 // Check to see that fields are okay
1398 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1399 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1401 if (!(fd.isFinal() && fd.isStatic())) {
1402 checkFieldDeclaration(cd, fd);
1404 // for static final, assign top location by default
1405 Location loc = Location.createTopLocation(cd);
1406 addLocationType(fd.getType(), loc);
1411 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1413 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1415 // currently enforce every field to have corresponding location
1416 if (annotationVec.size() == 0) {
1417 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1418 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1421 if (annotationVec.size() > 1) {
1422 // variable can have at most one location
1423 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1424 + " has more than one location.");
1427 AnnotationDescriptor ad = annotationVec.elementAt(0);
1428 Location loc = null;
1430 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1431 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1432 String locationID = ad.getValue();
1433 // check if location is defined
1434 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1435 if (lattice == null || (!lattice.containsKey(locationID))) {
1436 throw new Error("Location " + locationID
1437 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1438 + cd.getSourceFileName() + ".");
1440 loc = new Location(cd, locationID);
1442 if (ssjava.isSharedLocation(loc)) {
1443 ssjava.mapSharedLocation2Descriptor(loc, fd);
1446 addLocationType(fd.getType(), loc);
1454 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1456 type.setExtension(loc);
1460 private void addLocationType(TypeDescriptor type, Location loc) {
1462 type.setExtension(loc);
1466 static class CompositeLattice {
1468 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1470 System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1471 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, msg);
1472 if (baseCompareResult == ComparisonResult.EQUAL) {
1473 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1478 } else if (baseCompareResult == ComparisonResult.GREATER) {
1486 public static int compare(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1488 System.out.println("compare=" + loc1 + " " + loc2);
1489 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, msg);
1491 if (baseCompareResult == ComparisonResult.EQUAL) {
1492 return compareDelta(loc1, loc2);
1494 return baseCompareResult;
1499 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1501 int deltaCount1 = 0;
1502 int deltaCount2 = 0;
1503 if (dLoc1 instanceof DeltaLocation) {
1504 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1507 if (dLoc2 instanceof DeltaLocation) {
1508 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1510 if (deltaCount1 < deltaCount2) {
1511 return ComparisonResult.GREATER;
1512 } else if (deltaCount1 == deltaCount2) {
1513 return ComparisonResult.EQUAL;
1515 return ComparisonResult.LESS;
1520 private static int compareBaseLocationSet(CompositeLocation compLoc1,
1521 CompositeLocation compLoc2, boolean awareSharedLoc, String msg) {
1523 // if compLoc1 is greater than compLoc2, return true
1524 // else return false;
1526 // compare one by one in according to the order of the tuple
1528 for (int i = 0; i < compLoc1.getSize(); i++) {
1529 Location loc1 = compLoc1.get(i);
1530 if (i >= compLoc2.getSize()) {
1531 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1532 + " because they are not comparable at " + msg);
1534 Location loc2 = compLoc2.get(i);
1536 Descriptor d1 = loc1.getDescriptor();
1537 Descriptor d2 = loc2.getDescriptor();
1539 Descriptor descriptor;
1541 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1543 if (d1.equals(d2)) {
1546 // identifying which one is parent class
1547 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1548 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1550 if (d1 == null && d2 == null) {
1551 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1552 + " because they are not comparable at " + msg);
1553 } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1555 } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1558 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1559 + " because they are not comparable at " + msg);
1563 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1565 if (d1.equals(d2)) {
1569 // identifying which one is parent class
1570 MethodDescriptor md1 = (MethodDescriptor) d1;
1571 MethodDescriptor md2 = (MethodDescriptor) d2;
1573 if (!md1.matches(md2)) {
1574 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1575 + " because they are not comparable at " + msg);
1578 Set<Descriptor> d1SubClassesSet =
1579 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1580 Set<Descriptor> d2SubClassesSet =
1581 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1583 if (d1 == null && d2 == null) {
1584 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1585 + " because they are not comparable at " + msg);
1586 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1588 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1591 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1592 + " because they are not comparable at " + msg);
1597 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1598 + " because they are not comparable at " + msg);
1601 // SSJavaLattice<String> lattice1 = getLatticeByDescriptor(d1);
1602 // SSJavaLattice<String> lattice2 = getLatticeByDescriptor(d2);
1604 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1606 // check if the spin location is appeared only at the end of the
1607 // composite location
1608 if (lattice.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1609 if (i != (compLoc1.getSize() - 1)) {
1610 throw new Error("The shared location " + loc1.getLocIdentifier()
1611 + " cannot be appeared in the middle of composite location at" + msg);
1615 if (lattice.getSpinLocSet().contains(loc2.getLocIdentifier())) {
1616 if (i != (compLoc2.getSize() - 1)) {
1617 throw new Error("The spin location " + loc2.getLocIdentifier()
1618 + " cannot be appeared in the middle of composite location at " + msg);
1622 // if (!lattice1.equals(lattice2)) {
1623 // throw new Error("Failed to compare two locations of " + compLoc1 +
1624 // " and " + compLoc2
1625 // + " because they are not comparable at " + msg);
1628 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1630 // check if the current location is the spinning location
1631 // note that the spinning location only can be appeared in the last
1632 // part of the composite location
1633 if (awareSharedLoc && numOfTie == compLoc1.getSize()
1634 && lattice.getSpinLocSet().contains(loc1.getLocIdentifier())) {
1635 return ComparisonResult.GREATER;
1638 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1639 return ComparisonResult.GREATER;
1641 return ComparisonResult.LESS;
1646 if (numOfTie == compLoc1.getSize()) {
1648 if (numOfTie != compLoc2.getSize()) {
1649 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1650 + " because they are not comparable at " + msg);
1653 return ComparisonResult.EQUAL;
1656 return ComparisonResult.LESS;
1660 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
1662 System.out.println("Calculating GLB=" + inputSet);
1663 CompositeLocation glbCompLoc = new CompositeLocation();
1665 // calculate GLB of the first(priority) element
1666 Set<String> priorityLocIdentifierSet = new HashSet<String>();
1667 Descriptor priorityDescriptor = null;
1669 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1670 new Hashtable<String, Set<CompositeLocation>>();
1671 // mapping from the priority loc ID to its full representation by the
1672 // composite location
1674 int maxTupleSize = 0;
1675 CompositeLocation maxCompLoc = null;
1677 Location prevPriorityLoc = null;
1678 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1679 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1680 if (compLoc.getSize() > maxTupleSize) {
1681 maxTupleSize = compLoc.getSize();
1682 maxCompLoc = compLoc;
1684 Location priorityLoc = compLoc.get(0);
1685 String priorityLocId = priorityLoc.getLocIdentifier();
1686 priorityLocIdentifierSet.add(priorityLocId);
1688 if (locId2CompLocSet.containsKey(priorityLocId)) {
1689 locId2CompLocSet.get(priorityLocId).add(compLoc);
1691 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1692 newSet.add(compLoc);
1693 locId2CompLocSet.put(priorityLocId, newSet);
1696 // check if priority location are coming from the same lattice
1697 if (priorityDescriptor == null) {
1698 priorityDescriptor = priorityLoc.getDescriptor();
1700 priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
1702 prevPriorityLoc = priorityLoc;
1703 // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1704 // throw new Error("Failed to calculate GLB of " + inputSet
1705 // + " because they are from different lattices.");
1709 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1710 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1712 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1713 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1715 if (compSet == null) {
1716 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1717 // mean that the result is already lower than <x1,y1> and <x2,y2>
1718 // assign TOP to the rest of the location elements
1720 // in this case, do not take care about delta
1721 // CompositeLocation inputComp = inputSet.iterator().next();
1722 for (int i = 1; i < maxTupleSize; i++) {
1723 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1727 // here find out composite location that has a maximum length tuple
1728 // if we have three input set: [A], [A,B], [A,B,C]
1729 // maximum length tuple will be [A,B,C]
1731 CompositeLocation maxFromCompSet = null;
1732 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1733 CompositeLocation c = (CompositeLocation) iterator.next();
1734 if (c.getSize() > max) {
1740 if (compSet.size() == 1) {
1741 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1742 CompositeLocation comp = compSet.iterator().next();
1743 for (int i = 1; i < comp.getSize(); i++) {
1744 glbCompLoc.addLocation(comp.get(i));
1747 // if input location corresponding to glb is a delta, need to apply
1748 // delta to glb result
1749 if (comp instanceof DeltaLocation) {
1750 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1754 // when GLB(x1,x2)==x1 and x2 : GLB case 1
1755 // if more than one location shares the same priority GLB
1756 // need to calculate the rest of GLB loc
1758 // setup input set starting from the second tuple item
1759 Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
1760 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1761 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1762 CompositeLocation innerCompLoc = new CompositeLocation();
1763 for (int idx = 1; idx < compLoc.getSize(); idx++) {
1764 innerCompLoc.addLocation(compLoc.get(idx));
1766 if (innerCompLoc.getSize() > 0) {
1767 innerGLBInput.add(innerCompLoc);
1771 if (innerGLBInput.size() > 0) {
1772 CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
1773 for (int idx = 0; idx < innerGLB.getSize(); idx++) {
1774 glbCompLoc.addLocation(innerGLB.get(idx));
1778 // if input location corresponding to glb is a delta, need to apply
1779 // delta to glb result
1781 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1782 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1783 if (compLoc instanceof DeltaLocation) {
1784 if (glbCompLoc.equals(compLoc)) {
1785 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1794 System.out.println("GLB=" + glbCompLoc);
1799 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1801 SSJavaLattice<String> lattice = null;
1803 if (d instanceof ClassDescriptor) {
1804 lattice = ssjava.getCd2lattice().get(d);
1805 } else if (d instanceof MethodDescriptor) {
1806 if (ssjava.getMd2lattice().containsKey(d)) {
1807 lattice = ssjava.getMd2lattice().get(d);
1809 // use default lattice for the method
1810 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1817 static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
1819 Descriptor d1 = loc1.getDescriptor();
1820 Descriptor d2 = loc2.getDescriptor();
1822 Descriptor descriptor;
1824 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1826 if (d1.equals(d2)) {
1829 // identifying which one is parent class
1830 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1831 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1833 if (d1 == null && d2 == null) {
1834 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1835 + " because they are not comparable at " + msg);
1836 } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1838 } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1841 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1842 + " because they are not comparable at " + msg);
1846 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1848 if (d1.equals(d2)) {
1852 // identifying which one is parent class
1853 MethodDescriptor md1 = (MethodDescriptor) d1;
1854 MethodDescriptor md2 = (MethodDescriptor) d2;
1856 if (!md1.matches(md2)) {
1857 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1858 + " because they are not comparable at " + msg);
1861 Set<Descriptor> d1SubClassesSet =
1862 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1863 Set<Descriptor> d2SubClassesSet =
1864 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1866 if (d1 == null && d2 == null) {
1867 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1868 + " because they are not comparable at " + msg);
1869 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1871 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1874 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1875 + " because they are not comparable at " + msg);
1880 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1881 + " because they are not comparable at " + msg);
1890 class ComparisonResult {
1892 public static final int GREATER = 0;
1893 public static final int EQUAL = 1;
1894 public static final int LESS = 2;
1895 public static final int INCOMPARABLE = 3;
1902 class ReturnLocGenerator {
1904 public static final int PARAMISHIGHER = 0;
1905 public static final int PARAMISSAME = 1;
1906 public static final int IGNORE = 2;
1908 Hashtable<Integer, Integer> paramIdx2paramType;
1910 public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params, String msg) {
1911 // creating mappings
1912 paramIdx2paramType = new Hashtable<Integer, Integer>();
1913 for (int i = 0; i < params.size(); i++) {
1914 CompositeLocation param = params.get(i);
1915 int compareResult = CompositeLattice.compare(param, returnLoc, msg);
1918 if (compareResult == ComparisonResult.GREATER) {
1920 } else if (compareResult == ComparisonResult.EQUAL) {
1925 paramIdx2paramType.put(new Integer(i), new Integer(type));
1930 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1932 // compute the highest possible location in caller's side
1933 assert paramIdx2paramType.keySet().size() == args.size();
1935 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1936 for (int i = 0; i < args.size(); i++) {
1937 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1938 CompositeLocation argLoc = args.get(i);
1939 if (type == PARAMISHIGHER) {
1940 // return loc is lower than param
1941 DeltaLocation delta = new DeltaLocation(argLoc, 1);
1942 inputGLB.add(delta);
1943 } else if (type == PARAMISSAME) {
1944 // return loc is equal or lower than param
1945 inputGLB.add(argLoc);
1949 // compute GLB of arguments subset that are same or higher than return
1951 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");