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 String rtrStr = ssjava.getMethodLattice(md).getReturnLoc();
310 if (rtrStr != null) {
311 returnLocComp = new CompositeLocation(new Location(md, rtrStr));
313 if (methodAnnotations != null) {
314 for (int i = 0; i < methodAnnotations.size(); i++) {
315 AnnotationDescriptor an = methodAnnotations.elementAt(i);
316 if (an.getMarker().equals(ssjava.RETURNLOC)) {
317 // this case, developer explicitly defines method lattice
318 String returnLocDeclaration = an.getValue();
319 returnLocComp = parseLocationDeclaration(md, null, returnLocDeclaration);
323 // if developer does not define method lattice
324 // search return location in the method default lattice
325 if (returnLocComp == null) {
326 MethodLattice<String> methodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
327 if (methodDefaultLattice.getReturnLoc() != null) {
329 parseLocationDeclaration(md, null, methodDefaultLattice.getReturnLoc());
335 if (returnLocComp == null) {
336 throw new Error("Return location is not specified for the method " + md + " at "
337 + cd.getSourceFileName());
340 md2ReturnLoc.put(md, returnLocComp);
342 // check this location
343 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
344 String thisLocId = methodLattice.getThisLoc();
345 if (thisLocId == null) {
346 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
347 + md.getClassDesc().getSourceFileName());
349 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
350 paramList.add(0, thisLoc);
352 System.out.println("### ReturnLocGenerator=" + md);
353 System.out.println("### md2ReturnLoc.get(md)=" + md2ReturnLoc.get(md));
354 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), paramList, md + " of "
355 + cd.getSourceFileName()));
358 // fourth, check declarations inside of method
360 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
364 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
365 bn.getVarTable().setParent(nametable);
366 for (int i = 0; i < bn.size(); i++) {
367 BlockStatementNode bsn = bn.get(i);
368 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
372 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
373 BlockStatementNode bsn) {
375 switch (bsn.kind()) {
376 case Kind.SubBlockNode:
377 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
380 case Kind.DeclarationNode:
381 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
385 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
388 case Kind.IfStatementNode:
389 checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
392 case Kind.SwitchStatementNode:
393 checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
396 case Kind.SynchronizedNode:
397 checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
403 private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
404 SynchronizedNode sbn) {
405 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
408 private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
409 SwitchStatementNode ssn) {
410 BlockNode sbn = ssn.getSwitchBody();
411 for (int i = 0; i < sbn.size(); i++) {
412 SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
413 checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
417 private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
418 IfStatementNode isn) {
419 checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
420 if (isn.getFalseBlock() != null)
421 checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
424 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
426 if (ln.getType() == LoopNode.FORLOOP) {
427 // check for loop case
428 ClassDescriptor cd = md.getClassDesc();
429 BlockNode bn = ln.getInitializer();
430 for (int i = 0; i < bn.size(); i++) {
431 BlockStatementNode bsn = bn.get(i);
432 checkDeclarationInBlockStatementNode(md, nametable, bsn);
437 checkDeclarationInBlockNode(md, nametable, ln.getBody());
440 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md) {
441 BlockNode bn = state.getMethodBody(md);
442 checkLocationFromBlockNode(md, md.getParameterTable(), bn, null);
445 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
447 return cd.getSourceFileName() + "::" + tn.getNumLine();
449 return cd.getSourceFileName();
454 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
455 BlockNode bn, CompositeLocation constraint) {
457 bn.getVarTable().setParent(nametable);
458 for (int i = 0; i < bn.size(); i++) {
459 BlockStatementNode bsn = bn.get(i);
460 checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
462 return new CompositeLocation();
466 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
467 SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
469 CompositeLocation compLoc = null;
470 switch (bsn.kind()) {
471 case Kind.BlockExpressionNode:
473 checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
476 case Kind.DeclarationNode:
477 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
480 case Kind.IfStatementNode:
481 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
485 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
488 case Kind.ReturnNode:
489 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
492 case Kind.SubBlockNode:
493 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
496 case Kind.ContinueBreakNode:
497 compLoc = new CompositeLocation();
500 case Kind.SwitchStatementNode:
502 checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
508 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
509 SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
511 ClassDescriptor cd = md.getClassDesc();
512 CompositeLocation condLoc =
513 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
515 BlockNode sbn = ssn.getSwitchBody();
517 constraint = generateNewConstraint(constraint, condLoc);
519 for (int i = 0; i < sbn.size(); i++) {
520 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
522 return new CompositeLocation();
525 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
526 SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
528 CompositeLocation blockLoc =
529 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
535 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
536 ReturnNode rn, CompositeLocation constraint) {
538 ExpressionNode returnExp = rn.getReturnExpression();
540 CompositeLocation returnValueLoc;
541 if (returnExp != null) {
543 checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
546 // if this return statement is inside branch, return value has an implicit
547 // flow from conditional location
548 if (constraint != null) {
549 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
550 inputGLB.add(returnValueLoc);
551 inputGLB.add(constraint);
553 CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), rn));
556 // check if return value is equal or higher than RETRUNLOC of method
557 // declaration annotation
558 CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
561 CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
562 generateErrorMessage(md.getClassDesc(), rn));
564 if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
566 "Return value location is not equal or higher than the declaraed return location at "
567 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
571 return new CompositeLocation();
574 private boolean hasOnlyLiteralValue(ExpressionNode en) {
575 if (en.kind() == Kind.LiteralNode) {
582 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
583 LoopNode ln, CompositeLocation constraint) {
585 ClassDescriptor cd = md.getClassDesc();
586 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
588 CompositeLocation condLoc =
589 checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
590 new CompositeLocation(), constraint, false);
591 addLocationType(ln.getCondition().getType(), (condLoc));
593 constraint = generateNewConstraint(constraint, condLoc);
594 checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
596 return new CompositeLocation();
599 // check 'for loop' case
600 BlockNode bn = ln.getInitializer();
601 bn.getVarTable().setParent(nametable);
603 // calculate glb location of condition and update statements
604 CompositeLocation condLoc =
605 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
606 new CompositeLocation(), constraint, false);
607 addLocationType(ln.getCondition().getType(), condLoc);
609 constraint = generateNewConstraint(constraint, condLoc);
611 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
612 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
614 return new CompositeLocation();
620 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
621 SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
622 CompositeLocation compLoc =
623 checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
627 private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
628 CompositeLocation newCon) {
630 if (currentCon == null) {
633 // compute GLB of current constraint and new constraint
634 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
635 inputSet.add(currentCon);
636 inputSet.add(newCon);
637 return CompositeLattice.calculateGLB(inputSet, "");
642 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
643 SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
645 CompositeLocation condLoc =
646 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
649 addLocationType(isn.getCondition().getType(), condLoc);
651 constraint = generateNewConstraint(constraint, condLoc);
652 checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
654 if (isn.getFalseBlock() != null) {
655 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
658 return new CompositeLocation();
661 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
662 SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
664 VarDescriptor vd = dn.getVarDescriptor();
666 CompositeLocation destLoc = d2loc.get(vd);
668 if (dn.getExpression() != null) {
669 CompositeLocation expressionLoc =
670 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
671 new CompositeLocation(), constraint, false);
672 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
674 if (expressionLoc != null) {
675 // checking location order
676 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
677 generateErrorMessage(md.getClassDesc(), dn))) {
678 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
679 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
680 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
683 return expressionLoc;
687 return new CompositeLocation();
693 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
695 checkDeclarationInBlockNode(md, nametable.getParent(), sbn.getBlockNode());
698 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
699 SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
700 CompositeLocation compLoc =
701 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
702 // addTypeLocation(ben.getExpression().getType(), compLoc);
706 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
707 SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
708 CompositeLocation constraint, boolean isLHS) {
710 CompositeLocation compLoc = null;
713 case Kind.AssignmentNode:
715 checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
718 case Kind.FieldAccessNode:
720 checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
724 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
728 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
731 case Kind.CreateObjectNode:
732 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
735 case Kind.ArrayAccessNode:
737 checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
740 case Kind.LiteralNode:
741 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
744 case Kind.MethodInvokeNode:
746 checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
749 case Kind.TertiaryNode:
750 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
754 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
757 // case Kind.InstanceOfNode:
758 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
761 // case Kind.ArrayInitializerNode:
762 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
766 // case Kind.ClassTypeNode:
767 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
770 // case Kind.OffsetNode:
771 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
778 // addTypeLocation(en.getType(), compLoc);
783 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
784 CastNode cn, CompositeLocation constraint) {
786 ExpressionNode en = cn.getExpression();
787 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
792 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
793 SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
794 ClassDescriptor cd = md.getClassDesc();
796 CompositeLocation condLoc =
797 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
799 addLocationType(tn.getCond().getType(), condLoc);
800 CompositeLocation trueLoc =
801 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
803 addLocationType(tn.getTrueExpr().getType(), trueLoc);
804 CompositeLocation falseLoc =
805 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
807 addLocationType(tn.getFalseExpr().getType(), falseLoc);
809 // locations from true/false branches can be TOP when there are only literal
811 // in this case, we don't need to check flow down rule!
813 // check if condLoc is higher than trueLoc & falseLoc
814 if (!trueLoc.get(0).isTop()
815 && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
817 "The location of the condition expression is lower than the true expression at "
818 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
821 if (!falseLoc.get(0).isTop()
822 && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
823 generateErrorMessage(cd, tn.getCond()))) {
825 "The location of the condition expression is lower than the true expression at "
826 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
829 // then, return glb of trueLoc & falseLoc
830 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
831 glbInputSet.add(trueLoc);
832 glbInputSet.add(falseLoc);
834 return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
837 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
838 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
839 CompositeLocation constraint) {
841 CompositeLocation baseLocation = null;
842 if (min.getExpression() != null) {
844 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
845 new CompositeLocation(), constraint, false);
848 if (min.getMethod().isStatic()) {
849 String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
850 if (globalLocId == null) {
851 throw new Error("Method lattice does not define global variable location at "
852 + generateErrorMessage(md.getClassDesc(), min));
854 baseLocation = new CompositeLocation(new Location(md, globalLocId));
856 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
857 baseLocation = new CompositeLocation(new Location(md, thisLocId));
861 checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
863 if (!min.getMethod().getReturnType().isVoid()) {
864 // If method has a return value, compute the highest possible return
865 // location in the caller's perspective
866 CompositeLocation ceilingLoc =
867 computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
871 return new CompositeLocation();
875 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
876 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
877 CompositeLocation constraint) {
878 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
880 // by default, method has a THIS parameter
881 argList.add(baseLocation);
883 for (int i = 0; i < min.numArgs(); i++) {
884 ExpressionNode en = min.getArg(i);
885 CompositeLocation callerArg =
886 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
888 argList.add(callerArg);
891 System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
892 CompositeLocation compLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
893 DeltaLocation delta = new DeltaLocation(compLoc, 1);
894 System.out.println("##computeReturnLocation=" + delta);
900 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
901 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
903 MethodDescriptor calleemd = min.getMethod();
905 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
906 CompositeLocation calleeThisLoc =
907 new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
909 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
910 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
912 if (min.numArgs() > 0) {
913 // caller needs to guarantee that it passes arguments in regarding to
914 // callee's hierarchy
916 // setup caller args set
917 // first, add caller's base(this) location
918 callerArgList.add(callerBaseLoc);
919 // second, add caller's arguments
920 for (int i = 0; i < min.numArgs(); i++) {
921 ExpressionNode en = min.getArg(i);
922 CompositeLocation callerArgLoc =
923 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
925 callerArgList.add(callerArgLoc);
928 // setup callee params set
929 // first, add callee's this location
930 calleeParamList.add(calleeThisLoc);
931 // second, add callee's parameters
932 for (int i = 0; i < calleemd.numParameters(); i++) {
933 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
934 CompositeLocation calleeLoc = d2loc.get(calleevd);
935 calleeParamList.add(calleeLoc);
938 // here, check if ordering relations among caller's args respect
939 // ordering relations in-between callee's args
940 CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
941 CompositeLocation calleeLoc1 = calleeParamList.get(i);
942 CompositeLocation callerLoc1 = callerArgList.get(i);
944 for (int j = 0; j < calleeParamList.size(); j++) {
946 CompositeLocation calleeLoc2 = calleeParamList.get(j);
947 CompositeLocation callerLoc2 = callerArgList.get(j);
949 if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
950 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
955 CompositeLattice.compare(callerLoc1, callerLoc2, true,
956 generateErrorMessage(md.getClassDesc(), min));
958 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
959 generateErrorMessage(md.getClassDesc(), min));
961 if (calleeResult == ComparisonResult.GREATER
962 && callerResult != ComparisonResult.GREATER) {
963 // If calleeLoc1 is higher than calleeLoc2
964 // then, caller should have same ordering relation in-bet
965 // callerLoc1 & callerLoc2
967 String paramName1, paramName2;
970 paramName1 = "'THIS'";
972 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
976 paramName2 = "'THIS'";
978 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
982 "Caller doesn't respect an ordering relation among method arguments: callee expects that "
983 + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
984 + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
995 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
996 SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
998 ClassDescriptor cd = md.getClassDesc();
1000 CompositeLocation arrayLoc =
1001 checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1002 new CompositeLocation(), constraint, isLHS);
1003 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1004 CompositeLocation indexLoc =
1005 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1007 // addTypeLocation(aan.getIndex().getType(), indexLoc);
1010 if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1011 throw new Error("Array index value is not higher than array location at "
1012 + generateErrorMessage(cd, aan));
1016 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1017 inputGLB.add(arrayLoc);
1018 inputGLB.add(indexLoc);
1019 return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1024 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1025 SymbolTable nametable, CreateObjectNode con) {
1027 ClassDescriptor cd = md.getClassDesc();
1029 CompositeLocation compLoc = new CompositeLocation();
1030 compLoc.addLocation(Location.createTopLocation(md));
1035 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1036 OpNode on, CompositeLocation constraint) {
1038 ClassDescriptor cd = md.getClassDesc();
1039 CompositeLocation leftLoc = new CompositeLocation();
1041 checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1042 // addTypeLocation(on.getLeft().getType(), leftLoc);
1044 CompositeLocation rightLoc = new CompositeLocation();
1045 if (on.getRight() != null) {
1047 checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1048 // addTypeLocation(on.getRight().getType(), rightLoc);
1051 System.out.println("\n# OP NODE=" + on.printNode(0));
1052 System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
1053 if (on.getRight() != null) {
1054 System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
1057 Operation op = on.getOp();
1059 switch (op.getOp()) {
1061 case Operation.UNARYPLUS:
1062 case Operation.UNARYMINUS:
1063 case Operation.LOGIC_NOT:
1067 case Operation.LOGIC_OR:
1068 case Operation.LOGIC_AND:
1069 case Operation.COMP:
1070 case Operation.BIT_OR:
1071 case Operation.BIT_XOR:
1072 case Operation.BIT_AND:
1073 case Operation.ISAVAILABLE:
1074 case Operation.EQUAL:
1075 case Operation.NOTEQUAL:
1082 case Operation.MULT:
1085 case Operation.LEFTSHIFT:
1086 case Operation.RIGHTSHIFT:
1087 case Operation.URIGHTSHIFT:
1089 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1090 inputSet.add(leftLoc);
1091 inputSet.add(rightLoc);
1092 CompositeLocation glbCompLoc =
1093 CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1094 System.out.println("# glbCompLoc=" + glbCompLoc);
1098 throw new Error(op.toString());
1103 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1104 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1106 // literal value has the top location so that value can be flowed into any
1108 Location literalLoc = Location.createTopLocation(md);
1109 loc.addLocation(literalLoc);
1114 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1115 NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1117 NameDescriptor nd = nn.getName();
1118 if (nd.getBase() != null) {
1120 checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1122 String varname = nd.toString();
1123 if (varname.equals("this")) {
1125 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1126 String thisLocId = methodLattice.getThisLoc();
1127 if (thisLocId == null) {
1128 throw new Error("The location for 'this' is not defined at "
1129 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1131 Location locElement = new Location(md, thisLocId);
1132 loc.addLocation(locElement);
1137 Descriptor d = (Descriptor) nametable.get(varname);
1139 // CompositeLocation localLoc = null;
1140 if (d instanceof VarDescriptor) {
1141 VarDescriptor vd = (VarDescriptor) d;
1142 // localLoc = d2loc.get(vd);
1143 // the type of var descriptor has a composite location!
1144 loc = ((CompositeLocation) vd.getType().getExtension()).clone();
1145 } else if (d instanceof FieldDescriptor) {
1146 // the type of field descriptor has a location!
1147 FieldDescriptor fd = (FieldDescriptor) d;
1148 if (fd.isStatic()) {
1150 // if it is 'static final', the location has TOP since no one can
1152 loc.addLocation(Location.createTopLocation(md));
1155 // if 'static', the location has pre-assigned global loc
1156 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1157 String globalLocId = localLattice.getGlobalLoc();
1158 if (globalLocId == null) {
1159 throw new Error("Global location element is not defined in the method " + md);
1161 Location globalLoc = new Location(md, globalLocId);
1163 loc.addLocation(globalLoc);
1166 // the location of field access starts from this, followed by field
1168 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1169 Location thisLoc = new Location(md, localLattice.getThisLoc());
1170 loc.addLocation(thisLoc);
1173 Location fieldLoc = (Location) fd.getType().getExtension();
1174 loc.addLocation(fieldLoc);
1175 } else if (d == null) {
1176 // access static field
1177 ClassDescriptor cd = nn.getClassDesc();
1179 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1180 String globalLocId = localLattice.getGlobalLoc();
1181 if (globalLocId == null) {
1182 throw new Error("Method lattice does not define global variable location at "
1183 + generateErrorMessage(md.getClassDesc(), nn));
1185 loc.addLocation(new Location(md, globalLocId));
1193 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1194 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1195 CompositeLocation constraint) {
1197 ExpressionNode left = fan.getExpression();
1198 TypeDescriptor ltd = left.getType();
1200 FieldDescriptor fd = fan.getField();
1202 String varName = null;
1203 if (left.kind() == Kind.NameNode) {
1204 NameDescriptor nd = ((NameNode) left).getName();
1205 varName = nd.toString();
1208 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1209 // using a class name directly or access using this
1210 if (fd.isStatic() && fd.isFinal()) {
1211 loc.addLocation(Location.createTopLocation(md));
1216 loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1217 if (!left.getType().isPrimitive()) {
1218 Location fieldLoc = getFieldLocation(fd);
1219 loc.addLocation(fieldLoc);
1225 private Location getFieldLocation(FieldDescriptor fd) {
1227 Location fieldLoc = (Location) fd.getType().getExtension();
1229 // handle the case that method annotation checking skips checking field
1231 if (fieldLoc == null) {
1232 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1239 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1240 SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1242 System.out.println("\n# ASSIGNMENTNODE=" + an.printNode(0));
1244 ClassDescriptor cd = md.getClassDesc();
1246 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1248 boolean postinc = true;
1249 if (an.getOperation().getBaseOp() == null
1250 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1251 .getBaseOp().getOp() != Operation.POSTDEC))
1254 // if LHS is array access node, need to check if array index is higher
1255 // than array itself
1256 CompositeLocation destLocation =
1257 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1260 CompositeLocation rhsLocation;
1261 CompositeLocation srcLocation;
1265 checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1268 System.out.println("dstLocation=" + destLocation);
1269 System.out.println("rhsLocation=" + rhsLocation);
1270 System.out.println("constraint=" + constraint);
1272 srcLocation = rhsLocation;
1274 if (!rhsLocation.get(rhsLocation.getSize() - 1).isTop()) {
1275 if (constraint != null) {
1276 inputGLBSet.add(rhsLocation);
1277 inputGLBSet.add(constraint);
1278 srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1282 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1283 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1284 + " does not respect location hierarchy on the assignment " + an.printNode(0) + " at "
1285 + cd.getSourceFileName() + "::" + an.getNumLine());
1291 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1294 if (constraint != null) {
1295 inputGLBSet.add(rhsLocation);
1296 inputGLBSet.add(constraint);
1297 srcLocation = CompositeLattice.calculateGLB(inputGLBSet, generateErrorMessage(cd, an));
1299 srcLocation = rhsLocation;
1302 System.out.println("srcLocation=" + srcLocation);
1303 System.out.println("rhsLocation=" + rhsLocation);
1304 System.out.println("constraint=" + constraint);
1306 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1307 throw new Error("Location " + destLocation
1308 + " is not allowed to have the value flow that moves within the same location at "
1309 + cd.getSourceFileName() + "::" + an.getNumLine());
1314 return destLocation;
1317 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1318 SymbolTable nametable, TreeNode n) {
1320 ClassDescriptor cd = md.getClassDesc();
1321 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1323 // currently enforce every variable to have corresponding location
1324 if (annotationVec.size() == 0) {
1325 throw new Error("Location is not assigned to variable " + vd.getSymbol() + " in the method "
1326 + md.getSymbol() + " of the class " + cd.getSymbol());
1329 if (annotationVec.size() > 1) { // variable can have at most one location
1330 throw new Error(vd.getSymbol() + " has more than one location.");
1333 AnnotationDescriptor ad = annotationVec.elementAt(0);
1335 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1337 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1338 String locDec = ad.getValue(); // check if location is defined
1340 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1341 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1342 d2loc.put(vd, deltaLoc);
1343 addLocationType(vd.getType(), deltaLoc);
1345 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1347 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1348 if (ssjava.isSharedLocation(lastElement)) {
1349 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1352 d2loc.put(vd, compLoc);
1353 addLocationType(vd.getType(), compLoc);
1361 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1364 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1367 int beginIdx = dIdx + 6;
1368 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1369 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1372 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1373 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1378 private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1380 int idx = decl.indexOf(".");
1382 String className = decl.substring(0, idx);
1383 String fieldName = decl.substring(idx + 1);
1385 className.replaceAll(" ", "");
1386 fieldName.replaceAll(" ", "");
1388 Descriptor d = state.getClassSymbolTable().get(className);
1391 System.out.println("state.getClassSymbolTable()=" + state.getClassSymbolTable());
1392 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1396 assert (d instanceof ClassDescriptor);
1397 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1398 if (!lattice.containsKey(fieldName)) {
1399 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1400 + className + "' at " + msg);
1403 return new Location(d, fieldName);
1406 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1408 CompositeLocation compLoc = new CompositeLocation();
1410 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1411 List<String> locIdList = new ArrayList<String>();
1412 while (tokenizer.hasMoreTokens()) {
1413 String locId = tokenizer.nextToken();
1414 locIdList.add(locId);
1417 // at least,one location element needs to be here!
1418 assert (locIdList.size() > 0);
1420 // assume that loc with idx 0 comes from the local lattice
1421 // loc with idx 1 comes from the field lattice
1423 String localLocId = locIdList.get(0);
1424 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1425 Location localLoc = new Location(md, localLocId);
1426 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1427 System.out.println("locDec=" + locDec);
1428 throw new Error("Location " + localLocId
1429 + " is not defined in the local variable lattice at "
1430 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1432 compLoc.addLocation(localLoc);
1434 for (int i = 1; i < locIdList.size(); i++) {
1435 String locName = locIdList.get(i);
1438 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1439 compLoc.addLocation(fieldLoc);
1440 } catch (Exception e) {
1441 throw new Error("The location declaration '" + locName + "' is wrong at "
1442 + generateErrorMessage(md.getClassDesc(), n));
1450 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1451 VarDescriptor vd = dn.getVarDescriptor();
1452 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1455 private void checkDeclarationInClass(ClassDescriptor cd) {
1456 // Check to see that fields are okay
1457 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1458 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1460 if (!(fd.isFinal() && fd.isStatic())) {
1461 checkFieldDeclaration(cd, fd);
1463 // for static final, assign top location by default
1464 Location loc = Location.createTopLocation(cd);
1465 addLocationType(fd.getType(), loc);
1470 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1472 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1474 // currently enforce every field to have corresponding location
1475 if (annotationVec.size() == 0) {
1476 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1477 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1480 if (annotationVec.size() > 1) {
1481 // variable can have at most one location
1482 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1483 + " has more than one location.");
1486 AnnotationDescriptor ad = annotationVec.elementAt(0);
1487 Location loc = null;
1489 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1490 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1491 String locationID = ad.getValue();
1492 // check if location is defined
1493 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1494 if (lattice == null || (!lattice.containsKey(locationID))) {
1495 throw new Error("Location " + locationID
1496 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1497 + cd.getSourceFileName() + ".");
1499 loc = new Location(cd, locationID);
1501 if (ssjava.isSharedLocation(loc)) {
1502 ssjava.mapSharedLocation2Descriptor(loc, fd);
1505 addLocationType(fd.getType(), loc);
1513 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1515 type.setExtension(loc);
1519 private void addLocationType(TypeDescriptor type, Location loc) {
1521 type.setExtension(loc);
1525 static class CompositeLattice {
1527 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1529 System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" + msg);
1530 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1531 if (baseCompareResult == ComparisonResult.EQUAL) {
1532 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1537 } else if (baseCompareResult == ComparisonResult.GREATER) {
1545 public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1548 System.out.println("compare=" + loc1 + " " + loc2);
1549 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1551 if (baseCompareResult == ComparisonResult.EQUAL) {
1552 return compareDelta(loc1, loc2);
1554 return baseCompareResult;
1559 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1561 int deltaCount1 = 0;
1562 int deltaCount2 = 0;
1563 if (dLoc1 instanceof DeltaLocation) {
1564 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1567 if (dLoc2 instanceof DeltaLocation) {
1568 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1570 if (deltaCount1 < deltaCount2) {
1571 return ComparisonResult.GREATER;
1572 } else if (deltaCount1 == deltaCount2) {
1573 return ComparisonResult.EQUAL;
1575 return ComparisonResult.LESS;
1580 private static int compareBaseLocationSet(CompositeLocation compLoc1,
1581 CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
1583 // if compLoc1 is greater than compLoc2, return true
1584 // else return false;
1586 // compare one by one in according to the order of the tuple
1588 for (int i = 0; i < compLoc1.getSize(); i++) {
1589 Location loc1 = compLoc1.get(i);
1590 if (i >= compLoc2.getSize()) {
1592 return ComparisonResult.INCOMPARABLE;
1594 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1595 + " because they are not comparable at " + msg);
1598 Location loc2 = compLoc2.get(i);
1600 Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
1601 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
1603 // check if the shared location is appeared only at the end of the
1604 // composite location
1605 if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1606 if (i != (compLoc1.getSize() - 1)) {
1607 throw new Error("The shared location " + loc1.getLocIdentifier()
1608 + " cannot be appeared in the middle of composite location at" + msg);
1612 if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
1613 if (i != (compLoc2.getSize() - 1)) {
1614 throw new Error("The shared location " + loc2.getLocIdentifier()
1615 + " cannot be appeared in the middle of composite location at " + msg);
1619 // if (!lattice1.equals(lattice2)) {
1620 // throw new Error("Failed to compare two locations of " + compLoc1 +
1621 // " and " + compLoc2
1622 // + " because they are not comparable at " + msg);
1625 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
1627 // check if the current location is the spinning location
1628 // note that the spinning location only can be appeared in the last
1629 // part of the composite location
1630 if (awareSharedLoc && numOfTie == compLoc1.getSize()
1631 && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
1632 return ComparisonResult.GREATER;
1635 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
1636 return ComparisonResult.GREATER;
1638 return ComparisonResult.LESS;
1643 if (numOfTie == compLoc1.getSize()) {
1645 if (numOfTie != compLoc2.getSize()) {
1648 return ComparisonResult.INCOMPARABLE;
1650 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
1651 + " because they are not comparable at " + msg);
1656 return ComparisonResult.EQUAL;
1659 return ComparisonResult.LESS;
1663 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
1665 System.out.println("Calculating GLB=" + inputSet);
1666 CompositeLocation glbCompLoc = new CompositeLocation();
1668 // calculate GLB of the first(priority) element
1669 Set<String> priorityLocIdentifierSet = new HashSet<String>();
1670 Descriptor priorityDescriptor = null;
1672 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
1673 new Hashtable<String, Set<CompositeLocation>>();
1674 // mapping from the priority loc ID to its full representation by the
1675 // composite location
1677 int maxTupleSize = 0;
1678 CompositeLocation maxCompLoc = null;
1680 Location prevPriorityLoc = null;
1681 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
1682 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1683 if (compLoc.getSize() > maxTupleSize) {
1684 maxTupleSize = compLoc.getSize();
1685 maxCompLoc = compLoc;
1687 Location priorityLoc = compLoc.get(0);
1688 String priorityLocId = priorityLoc.getLocIdentifier();
1689 priorityLocIdentifierSet.add(priorityLocId);
1691 if (locId2CompLocSet.containsKey(priorityLocId)) {
1692 locId2CompLocSet.get(priorityLocId).add(compLoc);
1694 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
1695 newSet.add(compLoc);
1696 locId2CompLocSet.put(priorityLocId, newSet);
1699 // check if priority location are coming from the same lattice
1700 if (priorityDescriptor == null) {
1701 priorityDescriptor = priorityLoc.getDescriptor();
1703 priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
1705 prevPriorityLoc = priorityLoc;
1706 // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
1707 // throw new Error("Failed to calculate GLB of " + inputSet
1708 // + " because they are from different lattices.");
1712 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
1713 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
1715 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
1716 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
1718 if (compSet == null) {
1719 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
1720 // mean that the result is already lower than <x1,y1> and <x2,y2>
1721 // assign TOP to the rest of the location elements
1723 // in this case, do not take care about delta
1724 // CompositeLocation inputComp = inputSet.iterator().next();
1725 for (int i = 1; i < maxTupleSize; i++) {
1726 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
1730 // here find out composite location that has a maximum length tuple
1731 // if we have three input set: [A], [A,B], [A,B,C]
1732 // maximum length tuple will be [A,B,C]
1734 CompositeLocation maxFromCompSet = null;
1735 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1736 CompositeLocation c = (CompositeLocation) iterator.next();
1737 if (c.getSize() > max) {
1743 if (compSet.size() == 1) {
1744 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
1745 CompositeLocation comp = compSet.iterator().next();
1746 for (int i = 1; i < comp.getSize(); i++) {
1747 glbCompLoc.addLocation(comp.get(i));
1750 // if input location corresponding to glb is a delta, need to apply
1751 // delta to glb result
1752 if (comp instanceof DeltaLocation) {
1753 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1757 // when GLB(x1,x2)==x1 and x2 : GLB case 1
1758 // if more than one location shares the same priority GLB
1759 // need to calculate the rest of GLB loc
1761 // setup input set starting from the second tuple item
1762 Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
1763 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1764 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1765 CompositeLocation innerCompLoc = new CompositeLocation();
1766 for (int idx = 1; idx < compLoc.getSize(); idx++) {
1767 innerCompLoc.addLocation(compLoc.get(idx));
1769 if (innerCompLoc.getSize() > 0) {
1770 innerGLBInput.add(innerCompLoc);
1774 if (innerGLBInput.size() > 0) {
1775 CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
1776 for (int idx = 0; idx < innerGLB.getSize(); idx++) {
1777 glbCompLoc.addLocation(innerGLB.get(idx));
1781 // if input location corresponding to glb is a delta, need to apply
1782 // delta to glb result
1784 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
1785 CompositeLocation compLoc = (CompositeLocation) iterator.next();
1786 if (compLoc instanceof DeltaLocation) {
1787 if (glbCompLoc.equals(compLoc)) {
1788 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
1797 System.out.println("GLB=" + glbCompLoc);
1802 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
1804 SSJavaLattice<String> lattice = null;
1806 if (d instanceof ClassDescriptor) {
1807 lattice = ssjava.getCd2lattice().get(d);
1808 } else if (d instanceof MethodDescriptor) {
1809 if (ssjava.getMd2lattice().containsKey(d)) {
1810 lattice = ssjava.getMd2lattice().get(d);
1812 // use default lattice for the method
1813 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
1820 static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
1822 Descriptor d1 = loc1.getDescriptor();
1823 Descriptor d2 = loc2.getDescriptor();
1825 Descriptor descriptor;
1827 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
1829 if (d1.equals(d2)) {
1832 // identifying which one is parent class
1833 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
1834 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
1836 if (d1 == null && d2 == null) {
1837 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1838 + " because they are not comparable at " + msg);
1839 } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
1841 } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
1844 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1845 + " because they are not comparable at " + msg);
1849 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
1851 if (d1.equals(d2)) {
1855 // identifying which one is parent class
1856 MethodDescriptor md1 = (MethodDescriptor) d1;
1857 MethodDescriptor md2 = (MethodDescriptor) d2;
1859 if (!md1.matches(md2)) {
1860 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1861 + " because they are not comparable at " + msg);
1864 Set<Descriptor> d1SubClassesSet =
1865 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
1866 Set<Descriptor> d2SubClassesSet =
1867 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
1869 if (d1 == null && d2 == null) {
1870 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1871 + " because they are not comparable at " + msg);
1872 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
1874 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
1877 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1878 + " because they are not comparable at " + msg);
1883 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
1884 + " because they are not comparable at " + msg);
1893 class ComparisonResult {
1895 public static final int GREATER = 0;
1896 public static final int EQUAL = 1;
1897 public static final int LESS = 2;
1898 public static final int INCOMPARABLE = 3;
1905 class ReturnLocGenerator {
1907 public static final int PARAMISHIGHER = 0;
1908 public static final int PARAMISSAME = 1;
1909 public static final int IGNORE = 2;
1911 Hashtable<Integer, Integer> paramIdx2paramType;
1913 public ReturnLocGenerator(CompositeLocation returnLoc, List<CompositeLocation> params, String msg) {
1914 // creating mappings
1915 paramIdx2paramType = new Hashtable<Integer, Integer>();
1916 for (int i = 0; i < params.size(); i++) {
1917 CompositeLocation param = params.get(i);
1918 int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
1921 if (compareResult == ComparisonResult.GREATER) {
1923 } else if (compareResult == ComparisonResult.EQUAL) {
1928 paramIdx2paramType.put(new Integer(i), new Integer(type));
1933 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
1935 // compute the highest possible location in caller's side
1936 assert paramIdx2paramType.keySet().size() == args.size();
1938 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1939 for (int i = 0; i < args.size(); i++) {
1940 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
1941 CompositeLocation argLoc = args.get(i);
1942 if (type == PARAMISHIGHER) {
1943 // return loc is lower than param
1944 DeltaLocation delta = new DeltaLocation(argLoc, 1);
1945 inputGLB.add(delta);
1946 } else if (type == PARAMISSAME) {
1947 // return loc is equal or lower than param
1948 inputGLB.add(argLoc);
1952 // compute GLB of arguments subset that are same or higher than return
1954 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");