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 baseLoc, 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 for (int i = 0; i < calleeParamList.size(); i++) {
905 CompositeLocation calleeParamLoc = calleeParamList.get(i);
906 if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
907 // callee parameter location has field information
908 CompositeLocation argLocation =
909 translateCallerLocToCallee(md, calleeThisLoc, callerArgList.get(i),errorMsg);
911 if (!CompositeLattice.isGreaterThan(argLocation, calleeParamLoc, errorMsg)) {
912 throw new Error("Caller argument '" + min.getArg(i).printNode(0)
913 + "' should be higher than corresponding callee's parameter at " + errorMsg);
921 private CompositeLocation translateCallerLocToCallee(MethodDescriptor md, Location calleeThisLoc,
922 CompositeLocation callerArgLoc,String errorMsg) {
924 ClassDescriptor calleeClassDesc = md.getClassDesc();
925 CompositeLocation translate = new CompositeLocation();
928 for (int i = 0; i < callerArgLoc.getSize(); i++) {
929 if (callerArgLoc.get(i).getDescriptor().equals(calleeClassDesc)) {
935 // caller arg location doesn't have field information
936 throw new Error("Caller argument location " + callerArgLoc
937 + " does not contain field information while callee has ordering constraints on field at "+errorMsg);
940 translate.addLocation(calleeThisLoc);
942 for (int i = startIdx + 1; i < callerArgLoc.getSize(); i++) {
943 translate.addLocation(callerArgLoc.get(i));
946 System.out.println("TRANSLATED=" + translate + " from callerArgLoc=" + callerArgLoc);
951 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
952 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
953 CompositeLocation constraint) {
954 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
956 // by default, method has a THIS parameter
957 argList.add(baseLocation);
959 for (int i = 0; i < min.numArgs(); i++) {
960 ExpressionNode en = min.getArg(i);
961 CompositeLocation callerArg =
962 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
964 argList.add(callerArg);
967 System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
968 CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
969 DeltaLocation delta = new DeltaLocation(compLoc, 1);
970 System.out.println("##computeReturnLocation=" + delta);
976 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
977 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
979 MethodDescriptor calleemd = min.getMethod();
981 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
982 CompositeLocation calleeThisLoc =
983 new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
985 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
986 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
988 if (min.numArgs() > 0) {
989 // caller needs to guarantee that it passes arguments in regarding to
990 // callee's hierarchy
992 // setup caller args set
993 // first, add caller's base(this) location
994 callerArgList.add(callerBaseLoc);
995 // second, add caller's arguments
996 for (int i = 0; i < min.numArgs(); i++) {
997 ExpressionNode en = min.getArg(i);
998 CompositeLocation callerArgLoc =
999 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1001 callerArgList.add(callerArgLoc);
1004 // setup callee params set
1005 // first, add callee's this location
1006 calleeParamList.add(calleeThisLoc);
1007 // second, add callee's parameters
1008 for (int i = 0; i < calleemd.numParameters(); i++) {
1009 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1010 CompositeLocation calleeLoc = d2loc.get(calleevd);
1011 calleeParamList.add(calleeLoc);
1014 // here, check if ordering relations among caller's args respect
1015 // ordering relations in-between callee's args
1016 CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1017 CompositeLocation calleeLoc1 = calleeParamList.get(i);
1018 CompositeLocation callerLoc1 = callerArgList.get(i);
1020 for (int j = 0; j < calleeParamList.size(); j++) {
1022 CompositeLocation calleeLoc2 = calleeParamList.get(j);
1023 CompositeLocation callerLoc2 = callerArgList.get(j);
1025 if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1026 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1031 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1032 generateErrorMessage(md.getClassDesc(), min));
1034 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1035 generateErrorMessage(md.getClassDesc(), min));
1037 if (calleeResult == ComparisonResult.GREATER
1038 && callerResult != ComparisonResult.GREATER) {
1039 // If calleeLoc1 is higher than calleeLoc2
1040 // then, caller should have same ordering relation in-bet
1041 // callerLoc1 & callerLoc2
1043 String paramName1, paramName2;
1046 paramName1 = "'THIS'";
1048 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1052 paramName2 = "'THIS'";
1054 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1058 "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1059 + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1060 + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1071 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1072 SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1074 ClassDescriptor cd = md.getClassDesc();
1076 CompositeLocation arrayLoc =
1077 checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1078 new CompositeLocation(), constraint, isLHS);
1079 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1080 CompositeLocation indexLoc =
1081 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1083 // addTypeLocation(aan.getIndex().getType(), indexLoc);
1086 if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1087 throw new Error("Array index value is not higher than array location at "
1088 + generateErrorMessage(cd, aan));
1092 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1093 inputGLB.add(arrayLoc);
1094 inputGLB.add(indexLoc);
1095 return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1100 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1101 SymbolTable nametable, CreateObjectNode con) {
1103 ClassDescriptor cd = md.getClassDesc();
1105 CompositeLocation compLoc = new CompositeLocation();
1106 compLoc.addLocation(Location.createTopLocation(md));
1111 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1112 OpNode on, CompositeLocation constraint) {
1114 ClassDescriptor cd = md.getClassDesc();
1115 CompositeLocation leftLoc = new CompositeLocation();
1117 checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1118 // addTypeLocation(on.getLeft().getType(), leftLoc);
1120 CompositeLocation rightLoc = new CompositeLocation();
1121 if (on.getRight() != null) {
1123 checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1124 // addTypeLocation(on.getRight().getType(), rightLoc);
1127 System.out.println("\n# OP NODE=" + on.printNode(0));
1128 System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
1129 if (on.getRight() != null) {
1130 System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
1133 Operation op = on.getOp();
1135 switch (op.getOp()) {
1137 case Operation.UNARYPLUS:
1138 case Operation.UNARYMINUS:
1139 case Operation.LOGIC_NOT:
1143 case Operation.LOGIC_OR:
1144 case Operation.LOGIC_AND:
1145 case Operation.COMP:
1146 case Operation.BIT_OR:
1147 case Operation.BIT_XOR:
1148 case Operation.BIT_AND:
1149 case Operation.ISAVAILABLE:
1150 case Operation.EQUAL:
1151 case Operation.NOTEQUAL:
1158 case Operation.MULT:
1161 case Operation.LEFTSHIFT:
1162 case Operation.RIGHTSHIFT:
1163 case Operation.URIGHTSHIFT:
1165 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1166 inputSet.add(leftLoc);
1167 inputSet.add(rightLoc);
1168 CompositeLocation glbCompLoc =
1169 CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1170 System.out.println("# glbCompLoc=" + glbCompLoc);
1174 throw new Error(op.toString());
1179 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1180 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1182 // literal value has the top location so that value can be flowed into any
1184 Location literalLoc = Location.createTopLocation(md);
1185 loc.addLocation(literalLoc);
1190 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1191 NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1193 NameDescriptor nd = nn.getName();
1194 if (nd.getBase() != null) {
1196 checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1198 String varname = nd.toString();
1199 if (varname.equals("this")) {
1201 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1202 String thisLocId = methodLattice.getThisLoc();
1203 if (thisLocId == null) {
1204 throw new Error("The location for 'this' is not defined at "
1205 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1207 Location locElement = new Location(md, thisLocId);
1208 loc.addLocation(locElement);
1213 Descriptor d = (Descriptor) nametable.get(varname);
1215 // CompositeLocation localLoc = null;
1216 if (d instanceof VarDescriptor) {
1217 VarDescriptor vd = (VarDescriptor) d;
1218 // localLoc = d2loc.get(vd);
1219 // the type of var descriptor has a composite location!
1220 loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1221 } else if (d instanceof FieldDescriptor) {
1222 // the type of field descriptor has a location!
1223 FieldDescriptor fd = (FieldDescriptor) d;
1224 if (fd.isStatic()) {
1226 // if it is 'static final', the location has TOP since no one can
1228 loc.addLocation(Location.createTopLocation(md));
1231 // if 'static', the location has pre-assigned global loc
1232 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1233 String globalLocId = localLattice.getGlobalLoc();
1234 if (globalLocId == null) {
1235 throw new Error("Global location element is not defined in the method " + md);
1237 Location globalLoc = new Location(md, globalLocId);
1239 loc.addLocation(globalLoc);
1242 // the location of field access starts from this, followed by field
1244 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1245 Location thisLoc = new Location(md, localLattice.getThisLoc());
1246 loc.addLocation(thisLoc);
1249 Location fieldLoc = (Location) fd.getType().getExtension();
1250 loc.addLocation(fieldLoc);
1251 } else if (d == null) {
1252 // access static field
1253 ClassDescriptor cd = nn.getClassDesc();
1255 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1256 String globalLocId = localLattice.getGlobalLoc();
1257 if (globalLocId == null) {
1258 throw new Error("Method lattice does not define global variable location at "
1259 + generateErrorMessage(md.getClassDesc(), nn));
1261 loc.addLocation(new Location(md, globalLocId));
1269 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1270 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1271 CompositeLocation constraint) {
1273 ExpressionNode left = fan.getExpression();
1274 TypeDescriptor ltd = left.getType();
1276 FieldDescriptor fd = fan.getField();
1278 String varName = null;
1279 if (left.kind() == Kind.NameNode) {
1280 NameDescriptor nd = ((NameNode) left).getName();
1281 varName = nd.toString();
1284 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1285 // using a class name directly or access using this
1286 if (fd.isStatic() && fd.isFinal()) {
1287 loc.addLocation(Location.createTopLocation(md));
1292 loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1293 if (!left.getType().isPrimitive()) {
1294 Location fieldLoc = getFieldLocation(fd);
1295 loc.addLocation(fieldLoc);
1301 private Location getFieldLocation(FieldDescriptor fd) {
1303 Location fieldLoc = (Location) fd.getType().getExtension();
1305 // handle the case that method annotation checking skips checking field
1307 if (fieldLoc == null) {
1308 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1315 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1316 SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1318 System.out.println("\n# ASSIGNMENTNODE=" + an.printNode(0));
1320 ClassDescriptor cd = md.getClassDesc();
1322 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1324 boolean postinc = true;
1325 if (an.getOperation().getBaseOp() == null
1326 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1327 .getBaseOp().getOp() != Operation.POSTDEC))
1330 // if LHS is array access node, need to check if array index is higher
1331 // than array itself
1332 CompositeLocation destLocation =
1333 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1336 CompositeLocation rhsLocation;
1337 CompositeLocation srcLocation;
1341 checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1344 System.out.println("dstLocation=" + destLocation);
1345 System.out.println("rhsLocation=" + rhsLocation);
1346 System.out.println("constraint=" + constraint);
1348 srcLocation = rhsLocation;
1350 if (!rhsLocation.get(rhsLocation.getSize() - 1).isTop()) {
1351 if (constraint != null) {
1352 inputGLBSet.add(rhsLocation);
1353 inputGLBSet.add(constraint);
1354 srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1358 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1359 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1360 + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1361 + cd.getSourceFileName() + "::" + an.getNumLine());
1367 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1370 if (constraint != null) {
1371 inputGLBSet.add(rhsLocation);
1372 inputGLBSet.add(constraint);
1373 srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1375 srcLocation = rhsLocation;
1378 System.out.println("srcLocation=" + srcLocation);
1379 System.out.println("rhsLocation=" + rhsLocation);
1380 System.out.println("constraint=" + constraint);
1382 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1383 throw new Error("Location " + destLocation
1384 + " is not allowed to have the value flow that moves within the same location at "
1385 + cd.getSourceFileName() + "::" + an.getNumLine());
1390 return destLocation;
1393 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1394 SymbolTable nametable, TreeNode n) {
1396 ClassDescriptor cd = md.getClassDesc();
1397 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1399 // currently enforce every variable to have corresponding location
1400 if (annotationVec.size() == 0) {
1401 throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1402 + md.getSymbol() + " of the class " + cd.getSymbol());
1405 if (annotationVec.size() > 1) { // variable can have at most one location
1406 throw new Error(vd.getSymbol() + " has more than one location.");
1409 AnnotationDescriptor ad = annotationVec.elementAt(0);
1411 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1413 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1414 String locDec = ad.getValue(); // check if location is defined
1416 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1417 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1418 d2loc.put(vd, deltaLoc);
1419 addLocationType(vd.getType(), deltaLoc);
1421 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1423 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1424 if (ssjava.isSharedLocation(lastElement)) {
1425 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1428 d2loc.put(vd, compLoc);
1429 addLocationType(vd.getType(), compLoc);
1437 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1440 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1443 int beginIdx = dIdx + 6;
1444 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1445 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1448 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1449 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1454 private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1456 int idx = decl.indexOf(".");
1458 String className = decl.substring(0, idx);
1459 String fieldName = decl.substring(idx + 1);
1461 className.replaceAll(" ", "");
1462 fieldName.replaceAll(" ", "");
1464 Descriptor d = state.getClassSymbolTable().get(className);
1467 System.out.println("state.getClassSymbolTable()=" + state.getClassSymbolTable());
1468 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1472 assert (d instanceof ClassDescriptor);
1473 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1474 if (!lattice.containsKey(fieldName)) {
1475 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1476 + className + "' at " + msg);
1479 return new Location(d, fieldName);
1482 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1484 CompositeLocation compLoc = new CompositeLocation();
1486 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1487 List<String> locIdList = new ArrayList<String>();
1488 while (tokenizer.hasMoreTokens()) {
1489 String locId = tokenizer.nextToken();
1490 locIdList.add(locId);
1493 // at least,one location element needs to be here!
1494 assert (locIdList.size() > 0);
1496 // assume that loc with idx 0 comes from the local lattice
1497 // loc with idx 1 comes from the field lattice
1499 String localLocId = locIdList.get(0);
1500 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1501 Location localLoc = new Location(md, localLocId);
1502 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1503 System.out.println("locDec=" + locDec);
1504 throw new Error("Location " + localLocId
1505 + " is not defined in the local variable lattice at "
1506 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1508 compLoc.addLocation(localLoc);
1510 for (int i = 1; i < locIdList.size(); i++) {
1511 String locName = locIdList.get(i);
1514 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1515 compLoc.addLocation(fieldLoc);
1516 } catch (Exception e) {
1517 throw new Error("The location declaration '" + locName + "' is wrong at "
1518 + generateErrorMessage(md.getClassDesc(), n));
1526 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1527 VarDescriptor vd = dn.getVarDescriptor();
1528 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1531 private void checkDeclarationInClass(ClassDescriptor cd) {
1532 // Check to see that fields are okay
1533 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1534 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1536 if (!(fd.isFinal() && fd.isStatic())) {
1537 checkFieldDeclaration(cd, fd);
1539 // for static final, assign top location by default
1540 Location loc = Location.createTopLocation(cd);
1541 addLocationType(fd.getType(), loc);
1546 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1548 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1550 // currently enforce every field to have corresponding location
1551 if (annotationVec.size() == 0) {
1552 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1553 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1556 if (annotationVec.size() > 1) {
1557 // variable can have at most one location
1558 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1559 + " has more than one location.");
1562 AnnotationDescriptor ad = annotationVec.elementAt(0);
1563 Location loc = null;
1565 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1566 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1567 String locationID = ad.getValue();
1568 // check if location is defined
1569 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1570 if (lattice == null || (!lattice.containsKey(locationID))) {
1571 throw new Error("Location " + locationID
1572 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1573 + cd.getSourceFileName() + ".");
1575 loc = new Location(cd, locationID);
1577 if (ssjava.isSharedLocation(loc)) {
1578 ssjava.mapSharedLocation2Descriptor(loc, fd);
1581 addLocationType(fd.getType(), loc);
1589 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1591 type.setExtension(loc);
1595 private void addLocationType(TypeDescriptor type, Location loc) {
1597 type.setExtension(loc);
1601 static class CompositeLattice {
1603 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1605 System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1606 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1607 if (baseCompareResult == ComparisonResult.EQUAL) {
1608 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1613 } else if (baseCompareResult == ComparisonResult.GREATER) {
1621 public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1624 System.out.println("compare=" + loc1 + " " + loc2);
1625 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1627 if (baseCompareResult == ComparisonResult.EQUAL) {
1628 return compareDelta(loc1, loc2);
1630 return baseCompareResult;
1635 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1637 int deltaCount1 = 0;
1638 int deltaCount2 = 0;
1639 if (dLoc1 instanceof DeltaLocation) {
1640 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1643 if (dLoc2 instanceof DeltaLocation) {
1644 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1646 if (deltaCount1 < deltaCount2) {
1647 return ComparisonResult.GREATER;
1648 } else if (deltaCount1 == deltaCount2) {
1649 return ComparisonResult.EQUAL;
1651 return ComparisonResult.LESS;
1656 private static int compareBaseLocationSet(CompositeLocation compLoc1,
1657 CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
1659 // if compLoc1 is greater than compLoc2, return true
1660 // else return false;
1662 // compare one by one in according to the order of the tuple
1664 for (int i = 0; i < compLoc1.getSize(); i++) {
1665 Location loc1 = compLoc1.get(i);
1666 if (i >= compLoc2.getSize()) {
1668 return ComparisonResult.INCOMPARABLE;
1670 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1671 + " because they are not comparable at " + msg);
1674 Location loc2 = compLoc2.get(i);
1676 Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
1677 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1679 // check if the shared location is appeared only at the end of the
1680 // composite location
1681 if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1682 if (i != (compLoc1.getSize() - 1)) {
1683 throw new Error("The shared location " + loc1.getLocIdentifier()
1684 + " cannot be appeared in the middle of composite location at" + msg);
1688 if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
1689 if (i != (compLoc2.getSize() - 1)) {
1690 throw new Error("The shared location " + loc2.getLocIdentifier()
1691 + " cannot be appeared in the middle of composite location at " + msg);
1695 // if (!lattice1.equals(lattice2)) {
1696 // throw new Error("Failed to compare two locations of " + compLoc1 +
1697 // " and " + compLoc2
1698 // + " because they are not comparable at " + msg);
1701 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1703 // check if the current location is the spinning location
1704 // note that the spinning location only can be appeared in the last
1705 // part of the composite location
1706 if (awareSharedLoc && numOfTie == compLoc1.getSize()
1707 && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1708 return ComparisonResult.GREATER;
1711 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1712 return ComparisonResult.GREATER;
1714 return ComparisonResult.LESS;
1719 if (numOfTie == compLoc1.getSize()) {
1721 if (numOfTie != compLoc2.getSize()) {
1724 return ComparisonResult.INCOMPARABLE;
1726 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1727 + " because they are not comparable at " + msg);
1732 return ComparisonResult.EQUAL;
1735 return ComparisonResult.LESS;
1739 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
1741 System.out.println("Calculating GLB=" + inputSet);
1742 CompositeLocation glbCompLoc = new CompositeLocation();
1744 // calculate GLB of the first(priority) element
1745 Set<String> priorityLocIdentifierSet = new HashSet<String>();
1746 Descriptor priorityDescriptor = null;
1748 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1749 new Hashtable<String, Set<CompositeLocation>>();
1750 // mapping from the priority loc ID to its full representation by the
1751 // composite location
1753 int maxTupleSize = 0;
1754 CompositeLocation maxCompLoc = null;
1756 Location prevPriorityLoc = null;
1757 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1758 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1759 if (compLoc.getSize() > maxTupleSize) {
1760 maxTupleSize = compLoc.getSize();
1761 maxCompLoc = compLoc;
1763 Location priorityLoc = compLoc.get(0);
1764 String priorityLocId = priorityLoc.getLocIdentifier();
1765 priorityLocIdentifierSet.add(priorityLocId);
1767 if (locId2CompLocSet.containsKey(priorityLocId)) {
1768 locId2CompLocSet.get(priorityLocId).add(compLoc);
1770 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1771 newSet.add(compLoc);
1772 locId2CompLocSet.put(priorityLocId, newSet);
1775 // check if priority location are coming from the same lattice
1776 if (priorityDescriptor == null) {
1777 priorityDescriptor = priorityLoc.getDescriptor();
1779 priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
1781 prevPriorityLoc = priorityLoc;
1782 // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1783 // throw new Error("Failed to calculate GLB of " + inputSet
1784 // + " because they are from different lattices.");
1788 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1789 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1791 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1792 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1794 if (compSet == null) {
1795 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1796 // mean that the result is already lower than <x1,y1> and <x2,y2>
1797 // assign TOP to the rest of the location elements
1799 // in this case, do not take care about delta
1800 // CompositeLocation inputComp = inputSet.iterator().next();
1801 for (int i = 1; i < maxTupleSize; i++) {
1802 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1806 // here find out composite location that has a maximum length tuple
1807 // if we have three input set: [A], [A,B], [A,B,C]
1808 // maximum length tuple will be [A,B,C]
1810 CompositeLocation maxFromCompSet = null;
1811 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1812 CompositeLocation c = (CompositeLocation) iterator.next();
1813 if (c.getSize() > max) {
1819 if (compSet.size() == 1) {
1820 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1821 CompositeLocation comp = compSet.iterator().next();
1822 for (int i = 1; i < comp.getSize(); i++) {
1823 glbCompLoc.addLocation(comp.get(i));
1826 // if input location corresponding to glb is a delta, need to apply
1827 // delta to glb result
1828 if (comp instanceof DeltaLocation) {
1829 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1833 // when GLB(x1,x2)==x1 and x2 : GLB case 1
1834 // if more than one location shares the same priority GLB
1835 // need to calculate the rest of GLB loc
1837 // setup input set starting from the second tuple item
1838 Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
1839 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1840 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1841 CompositeLocation innerCompLoc = new CompositeLocation();
1842 for (int idx = 1; idx < compLoc.getSize(); idx++) {
1843 innerCompLoc.addLocation(compLoc.get(idx));
1845 if (innerCompLoc.getSize() > 0) {
1846 innerGLBInput.add(innerCompLoc);
1850 if (innerGLBInput.size() > 0) {
1851 CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
1852 for (int idx = 0; idx < innerGLB.getSize(); idx++) {
1853 glbCompLoc.addLocation(innerGLB.get(idx));
1857 // if input location corresponding to glb is a delta, need to apply
1858 // delta to glb result
1860 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1861 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1862 if (compLoc instanceof DeltaLocation) {
1863 if (glbCompLoc.equals(compLoc)) {
1864 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1873 System.out.println("GLB=" + glbCompLoc);
1878 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1880 SSJavaLattice<String> lattice = null;
1882 if (d instanceof ClassDescriptor) {
1883 lattice = ssjava.getCd2lattice().get(d);
1884 } else if (d instanceof MethodDescriptor) {
1885 if (ssjava.getMd2lattice().containsKey(d)) {
1886 lattice = ssjava.getMd2lattice().get(d);
1888 // use default lattice for the method
1889 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1896 static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
1898 Descriptor d1 = loc1.getDescriptor();
1899 Descriptor d2 = loc2.getDescriptor();
1901 Descriptor descriptor;
1903 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1905 if (d1.equals(d2)) {
1908 // identifying which one is parent class
1909 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1910 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1912 if (d1 == null && d2 == null) {
1913 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1914 + " because they are not comparable at " + msg);
1915 } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1917 } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1920 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1921 + " because they are not comparable at " + msg);
1925 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1927 if (d1.equals(d2)) {
1931 // identifying which one is parent class
1932 MethodDescriptor md1 = (MethodDescriptor) d1;
1933 MethodDescriptor md2 = (MethodDescriptor) d2;
1935 if (!md1.matches(md2)) {
1936 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1937 + " because they are not comparable at " + msg);
1940 Set<Descriptor> d1SubClassesSet =
1941 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1942 Set<Descriptor> d2SubClassesSet =
1943 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1945 if (d1 == null && d2 == null) {
1946 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1947 + " because they are not comparable at " + msg);
1948 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1950 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1953 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1954 + " because they are not comparable at " + msg);
1959 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1960 + " because they are not comparable at " + msg);
1969 class ComparisonResult {
1971 public static final int GREATER = 0;
1972 public static final int EQUAL = 1;
1973 public static final int LESS = 2;
1974 public static final int INCOMPARABLE = 3;
1981 class ReturnLocGenerator {
1983 public static final int PARAMISHIGHER = 0;
1984 public static final int PARAMISSAME = 1;
1985 public static final int IGNORE = 2;
1987 private Hashtable<Integer, Integer> paramIdx2paramType;
1989 private CompositeLocation declaredReturnLoc = null;
1991 public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
1992 List<CompositeLocation> params, String msg) {
1994 CompositeLocation thisLoc = params.get(0);
1995 if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
1996 // if the declared return location consists of THIS and field location,
1997 // return location for the caller's side has to have same field element
1998 this.declaredReturnLoc = returnLoc;
2000 // creating mappings
2001 paramIdx2paramType = new Hashtable<Integer, Integer>();
2002 for (int i = 0; i < params.size(); i++) {
2003 CompositeLocation param = params.get(i);
2004 int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2007 if (compareResult == ComparisonResult.GREATER) {
2009 } else if (compareResult == ComparisonResult.EQUAL) {
2014 paramIdx2paramType.put(new Integer(i), new Integer(type));
2020 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2022 if (declaredReturnLoc != null) {
2023 // when developer specify that the return value is [THIS,field]
2024 // needs to translate to the caller's location
2025 CompositeLocation callerLoc = new CompositeLocation();
2026 CompositeLocation callerBaseLocation = args.get(0);
2028 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2029 callerLoc.addLocation(callerBaseLocation.get(i));
2031 for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2032 callerLoc.addLocation(declaredReturnLoc.get(i));
2036 // compute the highest possible location in caller's side
2037 assert paramIdx2paramType.keySet().size() == args.size();
2039 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2040 for (int i = 0; i < args.size(); i++) {
2041 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2042 CompositeLocation argLoc = args.get(i);
2043 if (type == PARAMISHIGHER) {
2044 // return loc is lower than param
2045 DeltaLocation delta = new DeltaLocation(argLoc, 1);
2046 inputGLB.add(delta);
2047 } else if (type == PARAMISSAME) {
2048 // return loc is equal or lower than param
2049 inputGLB.add(argLoc);
2053 // compute GLB of arguments subset that are same or higher than return
2055 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");