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));
303 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
305 // second, check return location annotation
306 if (!md.getReturnType().isVoid()) {
307 CompositeLocation returnLocComp = null;
309 boolean hasReturnLocDeclaration = false;
310 if (methodAnnotations != null) {
311 for (int i = 0; i < methodAnnotations.size(); i++) {
312 AnnotationDescriptor an = methodAnnotations.elementAt(i);
313 if (an.getMarker().equals(ssjava.RETURNLOC)) {
314 // this case, developer explicitly defines method lattice
315 String returnLocDeclaration = an.getValue();
316 returnLocComp = parseLocationDeclaration(md, null, returnLocDeclaration);
317 hasReturnLocDeclaration = true;
322 if (!hasReturnLocDeclaration) {
323 // if developer does not define method lattice
324 // search return location in the method default lattice
325 String rtrStr = ssjava.getMethodLattice(md).getReturnLoc();
326 returnLocComp = new CompositeLocation(new Location(md, rtrStr));
329 if (returnLocComp == null) {
330 throw new Error("Return location is not specified for the method " + md + " at "
331 + cd.getSourceFileName());
334 md2ReturnLoc.put(md, returnLocComp);
336 // check this location
337 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
338 String thisLocId = methodLattice.getThisLoc();
339 if (thisLocId == null) {
340 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
341 + md.getClassDesc().getSourceFileName());
343 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
344 paramList.add(0, thisLoc);
346 System.out.println("### ReturnLocGenerator=" + md);
347 System.out.println("### md2ReturnLoc.get(md)=" + md2ReturnLoc.get(md));
348 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), md, paramList, md
349 + " of " + cd.getSourceFileName()));
352 // fourth, check declarations inside of method
354 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
358 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
359 bn.getVarTable().setParent(nametable);
360 for (int i = 0; i < bn.size(); i++) {
361 BlockStatementNode bsn = bn.get(i);
362 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
366 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
367 BlockStatementNode bsn) {
369 switch (bsn.kind()) {
370 case Kind.SubBlockNode:
371 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
374 case Kind.DeclarationNode:
375 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
379 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
382 case Kind.IfStatementNode:
383 checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
386 case Kind.SwitchStatementNode:
387 checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
390 case Kind.SynchronizedNode:
391 checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
397 private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
398 SynchronizedNode sbn) {
399 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
402 private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
403 SwitchStatementNode ssn) {
404 BlockNode sbn = ssn.getSwitchBody();
405 for (int i = 0; i < sbn.size(); i++) {
406 SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
407 checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
411 private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
412 IfStatementNode isn) {
413 checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
414 if (isn.getFalseBlock() != null)
415 checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
418 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
420 if (ln.getType() == LoopNode.FORLOOP) {
421 // check for loop case
422 ClassDescriptor cd = md.getClassDesc();
423 BlockNode bn = ln.getInitializer();
424 for (int i = 0; i < bn.size(); i++) {
425 BlockStatementNode bsn = bn.get(i);
426 checkDeclarationInBlockStatementNode(md, nametable, bsn);
431 checkDeclarationInBlockNode(md, nametable, ln.getBody());
434 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
435 BlockNode bn = state.getMethodBody(md);
436 checkLocationFromBlockNode(md, md.getParameterTable(), bn, null);
439 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
441 return cd.getSourceFileName() + "::" + tn.getNumLine();
443 return cd.getSourceFileName();
448 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
449 BlockNode bn, CompositeLocation constraint) {
451 bn.getVarTable().setParent(nametable);
452 for (int i = 0; i < bn.size(); i++) {
453 BlockStatementNode bsn = bn.get(i);
454 checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
456 return new CompositeLocation();
460 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
461 SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
463 CompositeLocation compLoc = null;
464 switch (bsn.kind()) {
465 case Kind.BlockExpressionNode:
467 checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
470 case Kind.DeclarationNode:
471 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
474 case Kind.IfStatementNode:
475 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
479 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
482 case Kind.ReturnNode:
483 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
486 case Kind.SubBlockNode:
487 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
490 case Kind.ContinueBreakNode:
491 compLoc = new CompositeLocation();
494 case Kind.SwitchStatementNode:
496 checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
502 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
503 SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
505 ClassDescriptor cd = md.getClassDesc();
506 CompositeLocation condLoc =
507 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
509 BlockNode sbn = ssn.getSwitchBody();
511 constraint = generateNewConstraint(constraint, condLoc);
513 for (int i = 0; i < sbn.size(); i++) {
514 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
516 return new CompositeLocation();
519 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
520 SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
522 CompositeLocation blockLoc =
523 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
529 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
530 ReturnNode rn, CompositeLocation constraint) {
532 ExpressionNode returnExp = rn.getReturnExpression();
534 CompositeLocation returnValueLoc;
535 if (returnExp != null) {
537 checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
540 // if this return statement is inside branch, return value has an implicit
541 // flow from conditional location
542 if (constraint != null) {
543 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
544 inputGLB.add(returnValueLoc);
545 inputGLB.add(constraint);
547 CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), rn));
550 // check if return value is equal or higher than RETRUNLOC of method
551 // declaration annotation
552 CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
555 CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
556 generateErrorMessage(md.getClassDesc(), rn));
558 if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
560 "Return value location is not equal or higher than the declaraed return location at "
561 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
565 return new CompositeLocation();
568 private boolean hasOnlyLiteralValue(ExpressionNode en) {
569 if (en.kind() == Kind.LiteralNode) {
576 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
577 LoopNode ln, CompositeLocation constraint) {
579 ClassDescriptor cd = md.getClassDesc();
580 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
582 CompositeLocation condLoc =
583 checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
584 new CompositeLocation(), constraint, false);
585 // addLocationType(ln.getCondition().getType(), (condLoc));
587 constraint = generateNewConstraint(constraint, condLoc);
588 checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
590 return new CompositeLocation();
593 // check 'for loop' case
594 BlockNode bn = ln.getInitializer();
595 bn.getVarTable().setParent(nametable);
597 // calculate glb location of condition and update statements
598 CompositeLocation condLoc =
599 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
600 new CompositeLocation(), constraint, false);
601 // addLocationType(ln.getCondition().getType(), condLoc);
603 constraint = generateNewConstraint(constraint, condLoc);
605 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
606 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
608 return new CompositeLocation();
614 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
615 SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
616 CompositeLocation compLoc =
617 checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
621 private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
622 CompositeLocation newCon) {
624 if (currentCon == null) {
627 // compute GLB of current constraint and new constraint
628 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
629 inputSet.add(currentCon);
630 inputSet.add(newCon);
631 return CompositeLattice.calculateGLB(inputSet, "");
636 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
637 SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
639 CompositeLocation condLoc =
640 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
643 // addLocationType(isn.getCondition().getType(), condLoc);
645 constraint = generateNewConstraint(constraint, condLoc);
646 checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
648 if (isn.getFalseBlock() != null) {
649 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
652 return new CompositeLocation();
655 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
656 SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
658 VarDescriptor vd = dn.getVarDescriptor();
660 CompositeLocation destLoc = d2loc.get(vd);
662 if (dn.getExpression() != null) {
663 CompositeLocation expressionLoc =
664 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
665 new CompositeLocation(), constraint, false);
666 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
668 if (expressionLoc != null) {
669 // checking location order
670 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
671 generateErrorMessage(md.getClassDesc(), dn))) {
672 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
673 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
674 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
677 return expressionLoc;
681 return new CompositeLocation();
687 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
689 checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
692 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
693 SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
694 CompositeLocation compLoc =
695 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
696 // addTypeLocation(ben.getExpression().getType(), compLoc);
700 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
701 SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
702 CompositeLocation constraint, boolean isLHS) {
704 CompositeLocation compLoc = null;
707 case Kind.AssignmentNode:
709 checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
712 case Kind.FieldAccessNode:
714 checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
718 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
722 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
725 case Kind.CreateObjectNode:
726 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
729 case Kind.ArrayAccessNode:
731 checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
734 case Kind.LiteralNode:
735 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
738 case Kind.MethodInvokeNode:
740 checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
743 case Kind.TertiaryNode:
744 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
748 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
751 // case Kind.InstanceOfNode:
752 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
755 // case Kind.ArrayInitializerNode:
756 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
760 // case Kind.ClassTypeNode:
761 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
764 // case Kind.OffsetNode:
765 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
772 // addTypeLocation(en.getType(), compLoc);
777 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
778 CastNode cn, CompositeLocation constraint) {
780 ExpressionNode en = cn.getExpression();
781 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
786 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
787 SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
788 ClassDescriptor cd = md.getClassDesc();
790 CompositeLocation condLoc =
791 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
793 // addLocationType(tn.getCond().getType(), condLoc);
794 CompositeLocation trueLoc =
795 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
797 // addLocationType(tn.getTrueExpr().getType(), trueLoc);
798 CompositeLocation falseLoc =
799 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
801 // addLocationType(tn.getFalseExpr().getType(), falseLoc);
803 // locations from true/false branches can be TOP when there are only literal
805 // in this case, we don't need to check flow down rule!
807 // check if condLoc is higher than trueLoc & falseLoc
808 if (!trueLoc.get(0).isTop()
809 && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
811 "The location of the condition expression is lower than the true expression at "
812 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
815 if (!falseLoc.get(0).isTop()
816 && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
817 generateErrorMessage(cd, tn.getCond()))) {
819 "The location of the condition expression is lower than the true expression at "
820 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
823 // then, return glb of trueLoc & falseLoc
824 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
825 glbInputSet.add(trueLoc);
826 glbInputSet.add(falseLoc);
828 return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
831 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
832 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
833 CompositeLocation constraint) {
835 CompositeLocation baseLocation = null;
836 if (min.getExpression() != null) {
838 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
839 new CompositeLocation(), constraint, false);
842 if (min.getMethod().isStatic()) {
843 String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
844 if (globalLocId == null) {
845 throw new Error("Method lattice does not define global variable location at "
846 + generateErrorMessage(md.getClassDesc(), min));
848 baseLocation = new CompositeLocation(new Location(md, globalLocId));
850 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
851 baseLocation = new CompositeLocation(new Location(md, thisLocId));
855 checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
857 checkCallerArgumentLocationConstraints(md, nametable, min, baseLocation, constraint);
859 if (!min.getMethod().getReturnType().isVoid()) {
860 // If method has a return value, compute the highest possible return
861 // location in the caller's perspective
862 CompositeLocation ceilingLoc =
863 computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
867 return new CompositeLocation();
871 private void checkCallerArgumentLocationConstraints(MethodDescriptor md, SymbolTable nametable,
872 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
873 // if parameter location consists of THIS and FIELD location,
874 // caller should pass an argument that is comparable to the declared
875 // parameter location
876 // and is not lower than the declared parameter location in the field
879 MethodDescriptor calleemd = min.getMethod();
881 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
882 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
884 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
885 Location calleeThisLoc = new Location(calleemd, calleeLattice.getThisLoc());
887 for (int i = 0; i < min.numArgs(); i++) {
888 ExpressionNode en = min.getArg(i);
889 CompositeLocation callerArgLoc =
890 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
892 callerArgList.add(callerArgLoc);
895 // setup callee params set
896 for (int i = 0; i < calleemd.numParameters(); i++) {
897 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
898 CompositeLocation calleeLoc = d2loc.get(calleevd);
899 calleeParamList.add(calleeLoc);
902 String errorMsg = generateErrorMessage(md.getClassDesc(), min);
904 System.out.println("checkCallerArgumentLocationConstraints=" + min.printNode(0));
905 System.out.println("base location=" + callerBaseLoc);
907 for (int i = 0; i < calleeParamList.size(); i++) {
908 CompositeLocation calleeParamLoc = calleeParamList.get(i);
909 if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
911 // callee parameter location has field information
912 CompositeLocation callerArgLoc = callerArgList.get(i);
914 CompositeLocation paramLocation =
915 translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
917 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
918 if (constraint != null) {
919 inputGLBSet.add(callerArgLoc);
920 inputGLBSet.add(constraint);
922 CompositeLattice.calculateGLB(inputGLBSet,
923 generateErrorMessage(md.getClassDesc(), min));
926 if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
927 throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
928 + "' should be higher than corresponding callee's parameter : " + paramLocation
929 + " at " + errorMsg);
937 private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
938 CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
940 CompositeLocation translate = new CompositeLocation();
942 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
943 translate.addLocation(callerBaseLocation.get(i));
946 for (int i = 1; i < calleeParamLoc.getSize(); i++) {
947 translate.addLocation(calleeParamLoc.get(i));
950 System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" + calleeParamLoc);
955 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
956 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
957 CompositeLocation constraint) {
958 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
960 // by default, method has a THIS parameter
961 argList.add(baseLocation);
963 for (int i = 0; i < min.numArgs(); i++) {
964 ExpressionNode en = min.getArg(i);
965 CompositeLocation callerArg =
966 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
968 argList.add(callerArg);
971 System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
972 CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
973 DeltaLocation delta = new DeltaLocation(compLoc, 1);
974 System.out.println("##computeReturnLocation=" + delta);
980 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
981 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
983 MethodDescriptor calleemd = min.getMethod();
985 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
986 CompositeLocation calleeThisLoc =
987 new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
989 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
990 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
992 if (min.numArgs() > 0) {
993 // caller needs to guarantee that it passes arguments in regarding to
994 // callee's hierarchy
996 // setup caller args set
997 // first, add caller's base(this) location
998 callerArgList.add(callerBaseLoc);
999 // second, add caller's arguments
1000 for (int i = 0; i < min.numArgs(); i++) {
1001 ExpressionNode en = min.getArg(i);
1002 CompositeLocation callerArgLoc =
1003 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1005 callerArgList.add(callerArgLoc);
1008 // setup callee params set
1009 // first, add callee's this location
1010 calleeParamList.add(calleeThisLoc);
1011 // second, add callee's parameters
1012 for (int i = 0; i < calleemd.numParameters(); i++) {
1013 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1014 CompositeLocation calleeLoc = d2loc.get(calleevd);
1015 calleeParamList.add(calleeLoc);
1018 // here, check if ordering relations among caller's args respect
1019 // ordering relations in-between callee's args
1020 CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1021 CompositeLocation calleeLoc1 = calleeParamList.get(i);
1022 CompositeLocation callerLoc1 = callerArgList.get(i);
1024 for (int j = 0; j < calleeParamList.size(); j++) {
1026 CompositeLocation calleeLoc2 = calleeParamList.get(j);
1027 CompositeLocation callerLoc2 = callerArgList.get(j);
1029 if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1030 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1035 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1036 generateErrorMessage(md.getClassDesc(), min));
1038 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1039 generateErrorMessage(md.getClassDesc(), min));
1041 if (calleeResult == ComparisonResult.GREATER
1042 && callerResult != ComparisonResult.GREATER) {
1043 // If calleeLoc1 is higher than calleeLoc2
1044 // then, caller should have same ordering relation in-bet
1045 // callerLoc1 & callerLoc2
1047 String paramName1, paramName2;
1050 paramName1 = "'THIS'";
1052 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1056 paramName2 = "'THIS'";
1058 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1062 "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1063 + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1064 + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1075 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1076 SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1078 ClassDescriptor cd = md.getClassDesc();
1080 CompositeLocation arrayLoc =
1081 checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1082 new CompositeLocation(), constraint, isLHS);
1083 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1084 CompositeLocation indexLoc =
1085 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1087 // addTypeLocation(aan.getIndex().getType(), indexLoc);
1090 if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1091 throw new Error("Array index value is not higher than array location at "
1092 + generateErrorMessage(cd, aan));
1096 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1097 inputGLB.add(arrayLoc);
1098 inputGLB.add(indexLoc);
1099 return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1104 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1105 SymbolTable nametable, CreateObjectNode con) {
1107 ClassDescriptor cd = md.getClassDesc();
1109 CompositeLocation compLoc = new CompositeLocation();
1110 compLoc.addLocation(Location.createTopLocation(md));
1115 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1116 OpNode on, CompositeLocation constraint) {
1118 ClassDescriptor cd = md.getClassDesc();
1119 CompositeLocation leftLoc = new CompositeLocation();
1121 checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1122 // addTypeLocation(on.getLeft().getType(), leftLoc);
1124 CompositeLocation rightLoc = new CompositeLocation();
1125 if (on.getRight() != null) {
1127 checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1128 // addTypeLocation(on.getRight().getType(), rightLoc);
1131 System.out.println("\n# OP NODE=" + on.printNode(0));
1132 System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
1133 if (on.getRight() != null) {
1134 System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
1137 Operation op = on.getOp();
1139 switch (op.getOp()) {
1141 case Operation.UNARYPLUS:
1142 case Operation.UNARYMINUS:
1143 case Operation.LOGIC_NOT:
1147 case Operation.LOGIC_OR:
1148 case Operation.LOGIC_AND:
1149 case Operation.COMP:
1150 case Operation.BIT_OR:
1151 case Operation.BIT_XOR:
1152 case Operation.BIT_AND:
1153 case Operation.ISAVAILABLE:
1154 case Operation.EQUAL:
1155 case Operation.NOTEQUAL:
1162 case Operation.MULT:
1165 case Operation.LEFTSHIFT:
1166 case Operation.RIGHTSHIFT:
1167 case Operation.URIGHTSHIFT:
1169 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1170 inputSet.add(leftLoc);
1171 inputSet.add(rightLoc);
1172 CompositeLocation glbCompLoc =
1173 CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1174 System.out.println("# glbCompLoc=" + glbCompLoc);
1178 throw new Error(op.toString());
1183 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1184 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1186 // literal value has the top location so that value can be flowed into any
1188 Location literalLoc = Location.createTopLocation(md);
1189 loc.addLocation(literalLoc);
1194 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1195 NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1197 NameDescriptor nd = nn.getName();
1198 if (nd.getBase() != null) {
1200 checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1202 String varname = nd.toString();
1203 if (varname.equals("this")) {
1205 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1206 String thisLocId = methodLattice.getThisLoc();
1207 if (thisLocId == null) {
1208 throw new Error("The location for 'this' is not defined at "
1209 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1211 Location locElement = new Location(md, thisLocId);
1212 loc.addLocation(locElement);
1217 Descriptor d = (Descriptor) nametable.get(varname);
1219 // CompositeLocation localLoc = null;
1220 if (d instanceof VarDescriptor) {
1221 VarDescriptor vd = (VarDescriptor) d;
1222 // localLoc = d2loc.get(vd);
1223 // the type of var descriptor has a composite location!
1224 loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1225 } else if (d instanceof FieldDescriptor) {
1226 // the type of field descriptor has a location!
1227 FieldDescriptor fd = (FieldDescriptor) d;
1228 if (fd.isStatic()) {
1230 // if it is 'static final', the location has TOP since no one can
1232 loc.addLocation(Location.createTopLocation(md));
1235 // if 'static', the location has pre-assigned global loc
1236 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1237 String globalLocId = localLattice.getGlobalLoc();
1238 if (globalLocId == null) {
1239 throw new Error("Global location element is not defined in the method " + md);
1241 Location globalLoc = new Location(md, globalLocId);
1243 loc.addLocation(globalLoc);
1246 // the location of field access starts from this, followed by field
1248 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1249 Location thisLoc = new Location(md, localLattice.getThisLoc());
1250 loc.addLocation(thisLoc);
1253 Location fieldLoc = (Location) fd.getType().getExtension();
1254 loc.addLocation(fieldLoc);
1255 } else if (d == null) {
1256 // access static field
1257 ClassDescriptor cd = nn.getClassDesc();
1259 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1260 String globalLocId = localLattice.getGlobalLoc();
1261 if (globalLocId == null) {
1262 throw new Error("Method lattice does not define global variable location at "
1263 + generateErrorMessage(md.getClassDesc(), nn));
1265 loc.addLocation(new Location(md, globalLocId));
1273 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1274 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1275 CompositeLocation constraint) {
1277 ExpressionNode left = fan.getExpression();
1278 TypeDescriptor ltd = left.getType();
1280 FieldDescriptor fd = fan.getField();
1282 String varName = null;
1283 if (left.kind() == Kind.NameNode) {
1284 NameDescriptor nd = ((NameNode) left).getName();
1285 varName = nd.toString();
1288 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1289 // using a class name directly or access using this
1290 if (fd.isStatic() && fd.isFinal()) {
1291 loc.addLocation(Location.createTopLocation(md));
1296 loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1297 System.out.println("### checkLocationFromFieldAccessNode=" + fan.printNode(0));
1298 System.out.println("### left=" + left.printNode(0));
1299 if (!left.getType().isPrimitive()) {
1300 Location fieldLoc = getFieldLocation(fd);
1301 loc.addLocation(fieldLoc);
1307 private Location getFieldLocation(FieldDescriptor fd) {
1309 System.out.println("### getFieldLocation=" + fd);
1310 System.out.println("### fd.getType().getExtension()=" + fd.getType().getExtension());
1312 Location fieldLoc = (Location) fd.getType().getExtension();
1314 // handle the case that method annotation checking skips checking field
1316 if (fieldLoc == null) {
1317 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1324 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1325 SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1327 System.out.println("\n# ASSIGNMENTNODE=" + an.printNode(0));
1329 ClassDescriptor cd = md.getClassDesc();
1331 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1333 boolean postinc = true;
1334 if (an.getOperation().getBaseOp() == null
1335 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1336 .getBaseOp().getOp() != Operation.POSTDEC))
1339 // if LHS is array access node, need to check if array index is higher
1340 // than array itself
1341 CompositeLocation destLocation =
1342 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1345 CompositeLocation rhsLocation;
1346 CompositeLocation srcLocation;
1350 checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1353 System.out.println("dstLocation=" + destLocation);
1354 System.out.println("rhsLocation=" + rhsLocation);
1355 System.out.println("constraint=" + constraint);
1357 srcLocation = rhsLocation;
1359 if (!rhsLocation.get(rhsLocation.getSize() - 1).isTop()) {
1360 if (constraint != null) {
1361 inputGLBSet.add(rhsLocation);
1362 inputGLBSet.add(constraint);
1363 srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1367 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1368 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1369 + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1370 + cd.getSourceFileName() + "::" + an.getNumLine());
1376 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1379 if (constraint != null) {
1380 inputGLBSet.add(rhsLocation);
1381 inputGLBSet.add(constraint);
1382 srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1384 srcLocation = rhsLocation;
1387 System.out.println("srcLocation=" + srcLocation);
1388 System.out.println("rhsLocation=" + rhsLocation);
1389 System.out.println("constraint=" + constraint);
1391 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1393 if (srcLocation.equals(destLocation)) {
1394 throw new Error("Location " + srcLocation
1395 + " is not allowed to have the value flow that moves within the same location at '"
1396 + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1398 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1399 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1400 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1407 return destLocation;
1410 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1411 SymbolTable nametable, TreeNode n) {
1413 ClassDescriptor cd = md.getClassDesc();
1414 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1416 // currently enforce every variable to have corresponding location
1417 if (annotationVec.size() == 0) {
1418 throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1419 + md.getSymbol() + " of the class " + cd.getSymbol());
1422 if (annotationVec.size() > 1) { // variable can have at most one location
1423 throw new Error(vd.getSymbol() + " has more than one location.");
1426 AnnotationDescriptor ad = annotationVec.elementAt(0);
1428 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1430 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1431 String locDec = ad.getValue(); // check if location is defined
1433 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1434 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1435 d2loc.put(vd, deltaLoc);
1436 addLocationType(vd.getType(), deltaLoc);
1438 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1440 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1441 if (ssjava.isSharedLocation(lastElement)) {
1442 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1445 d2loc.put(vd, compLoc);
1446 addLocationType(vd.getType(), compLoc);
1454 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1457 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1460 int beginIdx = dIdx + 6;
1461 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1462 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1465 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1466 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1471 private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1473 int idx = decl.indexOf(".");
1475 String className = decl.substring(0, idx);
1476 String fieldName = decl.substring(idx + 1);
1478 className.replaceAll(" ", "");
1479 fieldName.replaceAll(" ", "");
1481 Descriptor d = state.getClassSymbolTable().get(className);
1484 System.out.println("state.getClassSymbolTable()=" + state.getClassSymbolTable());
1485 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1489 assert (d instanceof ClassDescriptor);
1490 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1491 if (!lattice.containsKey(fieldName)) {
1492 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1493 + className + "' at " + msg);
1496 return new Location(d, fieldName);
1499 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1501 CompositeLocation compLoc = new CompositeLocation();
1503 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1504 List<String> locIdList = new ArrayList<String>();
1505 while (tokenizer.hasMoreTokens()) {
1506 String locId = tokenizer.nextToken();
1507 locIdList.add(locId);
1510 // at least,one location element needs to be here!
1511 assert (locIdList.size() > 0);
1513 // assume that loc with idx 0 comes from the local lattice
1514 // loc with idx 1 comes from the field lattice
1516 String localLocId = locIdList.get(0);
1517 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1518 Location localLoc = new Location(md, localLocId);
1519 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1520 System.out.println("locDec=" + locDec);
1521 throw new Error("Location " + localLocId
1522 + " is not defined in the local variable lattice at "
1523 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1525 compLoc.addLocation(localLoc);
1527 for (int i = 1; i < locIdList.size(); i++) {
1528 String locName = locIdList.get(i);
1531 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1532 compLoc.addLocation(fieldLoc);
1533 } catch (Exception e) {
1534 throw new Error("The location declaration '" + locName + "' is wrong at "
1535 + generateErrorMessage(md.getClassDesc(), n));
1543 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1544 VarDescriptor vd = dn.getVarDescriptor();
1545 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1548 private void checkDeclarationInClass(ClassDescriptor cd) {
1549 // Check to see that fields are okay
1550 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1551 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1553 if (!(fd.isFinal() && fd.isStatic())) {
1554 checkFieldDeclaration(cd, fd);
1556 // for static final, assign top location by default
1557 Location loc = Location.createTopLocation(cd);
1558 addLocationType(fd.getType(), loc);
1563 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1565 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1567 // currently enforce every field to have corresponding location
1568 if (annotationVec.size() == 0) {
1569 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1570 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1573 if (annotationVec.size() > 1) {
1574 // variable can have at most one location
1575 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1576 + " has more than one location.");
1579 AnnotationDescriptor ad = annotationVec.elementAt(0);
1580 Location loc = null;
1582 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1583 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1584 String locationID = ad.getValue();
1585 // check if location is defined
1586 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1587 if (lattice == null || (!lattice.containsKey(locationID))) {
1588 throw new Error("Location " + locationID
1589 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1590 + cd.getSourceFileName() + ".");
1592 loc = new Location(cd, locationID);
1594 if (ssjava.isSharedLocation(loc)) {
1595 ssjava.mapSharedLocation2Descriptor(loc, fd);
1598 addLocationType(fd.getType(), loc);
1606 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1608 type.setExtension(loc);
1612 private void addLocationType(TypeDescriptor type, Location loc) {
1614 type.setExtension(loc);
1618 static class CompositeLattice {
1620 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1622 System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1623 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1624 if (baseCompareResult == ComparisonResult.EQUAL) {
1625 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1630 } else if (baseCompareResult == ComparisonResult.GREATER) {
1638 public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1641 System.out.println("compare=" + loc1 + " " + loc2);
1642 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1644 if (baseCompareResult == ComparisonResult.EQUAL) {
1645 return compareDelta(loc1, loc2);
1647 return baseCompareResult;
1652 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1654 int deltaCount1 = 0;
1655 int deltaCount2 = 0;
1656 if (dLoc1 instanceof DeltaLocation) {
1657 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1660 if (dLoc2 instanceof DeltaLocation) {
1661 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1663 if (deltaCount1 < deltaCount2) {
1664 return ComparisonResult.GREATER;
1665 } else if (deltaCount1 == deltaCount2) {
1666 return ComparisonResult.EQUAL;
1668 return ComparisonResult.LESS;
1673 private static int compareBaseLocationSet(CompositeLocation compLoc1,
1674 CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
1676 // if compLoc1 is greater than compLoc2, return true
1677 // else return false;
1679 // compare one by one in according to the order of the tuple
1681 for (int i = 0; i < compLoc1.getSize(); i++) {
1682 Location loc1 = compLoc1.get(i);
1683 if (i >= compLoc2.getSize()) {
1685 return ComparisonResult.INCOMPARABLE;
1687 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1688 + " because they are not comparable at " + msg);
1691 Location loc2 = compLoc2.get(i);
1693 Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
1694 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1696 // check if the shared location is appeared only at the end of the
1697 // composite location
1698 if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1699 if (i != (compLoc1.getSize() - 1)) {
1700 throw new Error("The shared location " + loc1.getLocIdentifier()
1701 + " cannot be appeared in the middle of composite location at" + msg);
1705 if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
1706 if (i != (compLoc2.getSize() - 1)) {
1707 throw new Error("The shared location " + loc2.getLocIdentifier()
1708 + " cannot be appeared in the middle of composite location at " + msg);
1712 // if (!lattice1.equals(lattice2)) {
1713 // throw new Error("Failed to compare two locations of " + compLoc1 +
1714 // " and " + compLoc2
1715 // + " because they are not comparable at " + msg);
1718 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1720 // check if the current location is the spinning location
1721 // note that the spinning location only can be appeared in the last
1722 // part of the composite location
1723 if (awareSharedLoc && numOfTie == compLoc1.getSize()
1724 && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1725 return ComparisonResult.GREATER;
1728 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1729 return ComparisonResult.GREATER;
1731 return ComparisonResult.LESS;
1736 if (numOfTie == compLoc1.getSize()) {
1738 if (numOfTie != compLoc2.getSize()) {
1741 return ComparisonResult.INCOMPARABLE;
1743 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1744 + " because they are not comparable at " + msg);
1749 return ComparisonResult.EQUAL;
1752 return ComparisonResult.LESS;
1756 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
1758 System.out.println("Calculating GLB=" + inputSet);
1759 CompositeLocation glbCompLoc = new CompositeLocation();
1761 // calculate GLB of the first(priority) element
1762 Set<String> priorityLocIdentifierSet = new HashSet<String>();
1763 Descriptor priorityDescriptor = null;
1765 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1766 new Hashtable<String, Set<CompositeLocation>>();
1767 // mapping from the priority loc ID to its full representation by the
1768 // composite location
1770 int maxTupleSize = 0;
1771 CompositeLocation maxCompLoc = null;
1773 Location prevPriorityLoc = null;
1774 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1775 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1776 if (compLoc.getSize() > maxTupleSize) {
1777 maxTupleSize = compLoc.getSize();
1778 maxCompLoc = compLoc;
1780 Location priorityLoc = compLoc.get(0);
1781 String priorityLocId = priorityLoc.getLocIdentifier();
1782 priorityLocIdentifierSet.add(priorityLocId);
1784 if (locId2CompLocSet.containsKey(priorityLocId)) {
1785 locId2CompLocSet.get(priorityLocId).add(compLoc);
1787 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1788 newSet.add(compLoc);
1789 locId2CompLocSet.put(priorityLocId, newSet);
1792 // check if priority location are coming from the same lattice
1793 if (priorityDescriptor == null) {
1794 priorityDescriptor = priorityLoc.getDescriptor();
1796 priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
1798 prevPriorityLoc = priorityLoc;
1799 // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1800 // throw new Error("Failed to calculate GLB of " + inputSet
1801 // + " because they are from different lattices.");
1805 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1806 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1808 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1809 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1811 if (compSet == null) {
1812 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1813 // mean that the result is already lower than <x1,y1> and <x2,y2>
1814 // assign TOP to the rest of the location elements
1816 // in this case, do not take care about delta
1817 // CompositeLocation inputComp = inputSet.iterator().next();
1818 for (int i = 1; i < maxTupleSize; i++) {
1819 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1823 // here find out composite location that has a maximum length tuple
1824 // if we have three input set: [A], [A,B], [A,B,C]
1825 // maximum length tuple will be [A,B,C]
1827 CompositeLocation maxFromCompSet = null;
1828 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1829 CompositeLocation c = (CompositeLocation) iterator.next();
1830 if (c.getSize() > max) {
1836 if (compSet.size() == 1) {
1837 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1838 CompositeLocation comp = compSet.iterator().next();
1839 for (int i = 1; i < comp.getSize(); i++) {
1840 glbCompLoc.addLocation(comp.get(i));
1843 // if input location corresponding to glb is a delta, need to apply
1844 // delta to glb result
1845 if (comp instanceof DeltaLocation) {
1846 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1850 // when GLB(x1,x2)==x1 and x2 : GLB case 1
1851 // if more than one location shares the same priority GLB
1852 // need to calculate the rest of GLB loc
1854 // setup input set starting from the second tuple item
1855 Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
1856 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1857 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1858 CompositeLocation innerCompLoc = new CompositeLocation();
1859 for (int idx = 1; idx < compLoc.getSize(); idx++) {
1860 innerCompLoc.addLocation(compLoc.get(idx));
1862 if (innerCompLoc.getSize() > 0) {
1863 innerGLBInput.add(innerCompLoc);
1867 if (innerGLBInput.size() > 0) {
1868 CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
1869 for (int idx = 0; idx < innerGLB.getSize(); idx++) {
1870 glbCompLoc.addLocation(innerGLB.get(idx));
1874 // if input location corresponding to glb is a delta, need to apply
1875 // delta to glb result
1877 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1878 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1879 if (compLoc instanceof DeltaLocation) {
1880 if (glbCompLoc.equals(compLoc)) {
1881 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1890 System.out.println("GLB=" + glbCompLoc);
1895 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1897 SSJavaLattice<String> lattice = null;
1899 if (d instanceof ClassDescriptor) {
1900 lattice = ssjava.getCd2lattice().get(d);
1901 } else if (d instanceof MethodDescriptor) {
1902 if (ssjava.getMd2lattice().containsKey(d)) {
1903 lattice = ssjava.getMd2lattice().get(d);
1905 // use default lattice for the method
1906 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1913 static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
1915 Descriptor d1 = loc1.getDescriptor();
1916 Descriptor d2 = loc2.getDescriptor();
1918 Descriptor descriptor;
1920 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1922 if (d1.equals(d2)) {
1925 // identifying which one is parent class
1926 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1927 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1929 if (d1 == null && d2 == null) {
1930 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1931 + " because they are not comparable at " + msg);
1932 } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1934 } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1937 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1938 + " because they are not comparable at " + msg);
1942 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1944 if (d1.equals(d2)) {
1948 // identifying which one is parent class
1949 MethodDescriptor md1 = (MethodDescriptor) d1;
1950 MethodDescriptor md2 = (MethodDescriptor) d2;
1952 if (!md1.matches(md2)) {
1953 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1954 + " because they are not comparable at " + msg);
1957 Set<Descriptor> d1SubClassesSet =
1958 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1959 Set<Descriptor> d2SubClassesSet =
1960 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1962 if (d1 == null && d2 == null) {
1963 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1964 + " because they are not comparable at " + msg);
1965 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1967 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1970 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1971 + " because they are not comparable at " + msg);
1976 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1977 + " because they are not comparable at " + msg);
1986 class ComparisonResult {
1988 public static final int GREATER = 0;
1989 public static final int EQUAL = 1;
1990 public static final int LESS = 2;
1991 public static final int INCOMPARABLE = 3;
1998 class ReturnLocGenerator {
2000 public static final int PARAMISHIGHER = 0;
2001 public static final int PARAMISSAME = 1;
2002 public static final int IGNORE = 2;
2004 private Hashtable<Integer, Integer> paramIdx2paramType;
2006 private CompositeLocation declaredReturnLoc = null;
2008 public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2009 List<CompositeLocation> params, String msg) {
2011 CompositeLocation thisLoc = params.get(0);
2012 if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2013 // if the declared return location consists of THIS and field location,
2014 // return location for the caller's side has to have same field element
2015 this.declaredReturnLoc = returnLoc;
2017 // creating mappings
2018 paramIdx2paramType = new Hashtable<Integer, Integer>();
2019 for (int i = 0; i < params.size(); i++) {
2020 CompositeLocation param = params.get(i);
2021 int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2024 if (compareResult == ComparisonResult.GREATER) {
2026 } else if (compareResult == ComparisonResult.EQUAL) {
2031 paramIdx2paramType.put(new Integer(i), new Integer(type));
2037 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2039 if (declaredReturnLoc != null) {
2040 // when developer specify that the return value is [THIS,field]
2041 // needs to translate to the caller's location
2042 CompositeLocation callerLoc = new CompositeLocation();
2043 CompositeLocation callerBaseLocation = args.get(0);
2045 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2046 callerLoc.addLocation(callerBaseLocation.get(i));
2048 for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2049 callerLoc.addLocation(declaredReturnLoc.get(i));
2053 // compute the highest possible location in caller's side
2054 assert paramIdx2paramType.keySet().size() == args.size();
2056 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2057 for (int i = 0; i < args.size(); i++) {
2058 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2059 CompositeLocation argLoc = args.get(i);
2060 if (type == PARAMISHIGHER) {
2061 // return loc is lower than param
2062 DeltaLocation delta = new DeltaLocation(argLoc, 1);
2063 inputGLB.add(delta);
2064 } else if (type == PARAMISSAME) {
2065 // return loc is equal or lower than param
2066 inputGLB.add(argLoc);
2070 // compute GLB of arguments subset that are same or higher than return
2072 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");