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.TypeExtension;
27 import IR.VarDescriptor;
28 import IR.Flat.FlatNode;
29 import IR.Tree.ArrayAccessNode;
30 import IR.Tree.AssignmentNode;
31 import IR.Tree.BlockExpressionNode;
32 import IR.Tree.BlockNode;
33 import IR.Tree.BlockStatementNode;
34 import IR.Tree.CastNode;
35 import IR.Tree.CreateObjectNode;
36 import IR.Tree.DeclarationNode;
37 import IR.Tree.ExpressionNode;
38 import IR.Tree.FieldAccessNode;
39 import IR.Tree.IfStatementNode;
41 import IR.Tree.LiteralNode;
42 import IR.Tree.LoopNode;
43 import IR.Tree.MethodInvokeNode;
44 import IR.Tree.NameNode;
45 import IR.Tree.OpNode;
46 import IR.Tree.ReturnNode;
47 import IR.Tree.SubBlockNode;
48 import IR.Tree.SwitchBlockNode;
49 import IR.Tree.SwitchStatementNode;
50 import IR.Tree.SynchronizedNode;
51 import IR.Tree.TertiaryNode;
52 import IR.Tree.TreeNode;
55 public class FlowDownCheck {
58 static SSJavaAnalysis ssjava;
60 Set<ClassDescriptor> toanalyze;
61 List<ClassDescriptor> toanalyzeList;
63 Set<MethodDescriptor> toanalyzeMethod;
64 List<MethodDescriptor> toanalyzeMethodList;
66 // mapping from 'descriptor' to 'composite location'
67 Hashtable<Descriptor, CompositeLocation> d2loc;
69 Hashtable<MethodDescriptor, CompositeLocation> md2ReturnLoc;
70 Hashtable<MethodDescriptor, ReturnLocGenerator> md2ReturnLocGen;
72 // mapping from 'locID' to 'class descriptor'
73 Hashtable<String, ClassDescriptor> fieldLocName2cd;
75 boolean deterministic = true;
77 public FlowDownCheck(SSJavaAnalysis ssjava, State state) {
81 this.toanalyzeList = new ArrayList<ClassDescriptor>();
83 this.toanalyze = new HashSet<ClassDescriptor>();
86 this.toanalyzeMethodList = new ArrayList<MethodDescriptor>();
88 this.toanalyzeMethod = new HashSet<MethodDescriptor>();
90 this.d2loc = new Hashtable<Descriptor, CompositeLocation>();
91 this.fieldLocName2cd = new Hashtable<String, ClassDescriptor>();
92 this.md2ReturnLoc = new Hashtable<MethodDescriptor, CompositeLocation>();
93 this.md2ReturnLocGen = new Hashtable<MethodDescriptor, ReturnLocGenerator>();
98 // construct mapping from the location name to the class descriptor
99 // assume that the location name is unique through the whole program
101 Set<ClassDescriptor> cdSet = ssjava.getCd2lattice().keySet();
102 for (Iterator iterator = cdSet.iterator(); iterator.hasNext();) {
103 ClassDescriptor cd = (ClassDescriptor) iterator.next();
104 SSJavaLattice<String> lattice = ssjava.getCd2lattice().get(cd);
105 Set<String> fieldLocNameSet = lattice.getKeySet();
107 for (Iterator iterator2 = fieldLocNameSet.iterator(); iterator2.hasNext();) {
108 String fieldLocName = (String) iterator2.next();
109 fieldLocName2cd.put(fieldLocName, cd);
116 public boolean toAnalyzeIsEmpty() {
118 return toanalyzeList.isEmpty();
120 return toanalyze.isEmpty();
124 public ClassDescriptor toAnalyzeNext() {
126 return toanalyzeList.remove(0);
128 ClassDescriptor cd = toanalyze.iterator().next();
129 toanalyze.remove(cd);
134 public void setupToAnalyze() {
135 SymbolTable classtable = state.getClassSymbolTable();
137 toanalyzeList.clear();
138 toanalyzeList.addAll(classtable.getValueSet());
139 Collections.sort(toanalyzeList, new Comparator<ClassDescriptor>() {
140 public int compare(ClassDescriptor o1, ClassDescriptor o2) {
141 return o1.getClassName().compareToIgnoreCase(o2.getClassName());
146 toanalyze.addAll(classtable.getValueSet());
150 public void setupToAnalazeMethod(ClassDescriptor cd) {
152 SymbolTable methodtable = cd.getMethodTable();
154 toanalyzeMethodList.clear();
155 toanalyzeMethodList.addAll(methodtable.getValueSet());
156 Collections.sort(toanalyzeMethodList, new Comparator<MethodDescriptor>() {
157 public int compare(MethodDescriptor o1, MethodDescriptor o2) {
158 return o1.getSymbol().compareToIgnoreCase(o2.getSymbol());
162 toanalyzeMethod.clear();
163 toanalyzeMethod.addAll(methodtable.getValueSet());
167 public boolean toAnalyzeMethodIsEmpty() {
169 return toanalyzeMethodList.isEmpty();
171 return toanalyzeMethod.isEmpty();
175 public MethodDescriptor toAnalyzeMethodNext() {
177 return toanalyzeMethodList.remove(0);
179 MethodDescriptor md = toanalyzeMethod.iterator().next();
180 toanalyzeMethod.remove(md);
185 public void flowDownCheck() {
187 // phase 1 : checking declaration node and creating mapping of 'type
188 // desciptor' & 'location'
191 while (!toAnalyzeIsEmpty()) {
192 ClassDescriptor cd = toAnalyzeNext();
194 if (ssjava.needToBeAnnoated(cd)) {
196 ClassDescriptor superDesc = cd.getSuperDesc();
198 if (superDesc != null && (!superDesc.getSymbol().equals("Object"))) {
199 checkOrderingInheritance(superDesc, cd);
202 checkDeclarationInClass(cd);
204 setupToAnalazeMethod(cd);
205 while (!toAnalyzeMethodIsEmpty()) {
206 MethodDescriptor md = toAnalyzeMethodNext();
207 if (ssjava.needTobeAnnotated(md)) {
208 checkDeclarationInMethodBody(cd, md);
216 // phase2 : checking assignments
219 while (!toAnalyzeIsEmpty()) {
220 ClassDescriptor cd = toAnalyzeNext();
222 setupToAnalazeMethod(cd);
223 while (!toAnalyzeMethodIsEmpty()) {
224 MethodDescriptor md = toAnalyzeMethodNext();
225 if (ssjava.needTobeAnnotated(md)) {
226 if (state.SSJAVADEBUG) {
227 System.out.println("SSJAVA: Checking Flow-down Rules: " + md);
229 CompositeLocation calleePCLOC = ssjava.getPCLocation(md);
230 checkMethodBody(cd, md, calleePCLOC);
237 private void checkOrderingInheritance(ClassDescriptor superCd, ClassDescriptor cd) {
238 // here, we're going to check that sub class keeps same relative orderings
239 // in respect to super class
241 SSJavaLattice<String> superLattice = ssjava.getClassLattice(superCd);
242 SSJavaLattice<String> subLattice = ssjava.getClassLattice(cd);
244 if (superLattice != null) {
245 // if super class doesn't define lattice, then we don't need to check its
247 if (subLattice == null) {
248 throw new Error("If a parent class '" + superCd
249 + "' has a ordering lattice, its subclass '" + cd + "' should have one.");
252 Set<Pair<String, String>> superPairSet = superLattice.getOrderingPairSet();
253 Set<Pair<String, String>> subPairSet = subLattice.getOrderingPairSet();
255 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
256 Pair<String, String> pair = (Pair<String, String>) iterator.next();
258 if (!subPairSet.contains(pair)) {
259 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
260 + pair.getSecond() + " < " + pair.getFirst()
261 + "' that is defined by its superclass '" + superCd + "'.");
266 MethodLattice<String> superMethodDefaultLattice = ssjava.getMethodDefaultLattice(superCd);
267 MethodLattice<String> subMethodDefaultLattice = ssjava.getMethodDefaultLattice(cd);
269 if (superMethodDefaultLattice != null) {
270 if (subMethodDefaultLattice == null) {
271 throw new Error("When a parent class '" + superCd
272 + "' defines a default method lattice, its subclass '" + cd + "' should define one.");
275 Set<Pair<String, String>> superPairSet = superMethodDefaultLattice.getOrderingPairSet();
276 Set<Pair<String, String>> subPairSet = subMethodDefaultLattice.getOrderingPairSet();
278 for (Iterator iterator = superPairSet.iterator(); iterator.hasNext();) {
279 Pair<String, String> pair = (Pair<String, String>) iterator.next();
281 if (!subPairSet.contains(pair)) {
282 throw new Error("Subclass '" + cd + "' does not have the relative ordering '"
283 + pair.getSecond() + " < " + pair.getFirst()
284 + "' that is defined by its superclass '" + superCd
285 + "' in the method default lattice.");
293 public Hashtable getMap() {
297 private void checkDeclarationInMethodBody(ClassDescriptor cd, MethodDescriptor md) {
298 BlockNode bn = state.getMethodBody(md);
300 // first, check annotations on method parameters
301 List<CompositeLocation> paramList = new ArrayList<CompositeLocation>();
302 for (int i = 0; i < md.numParameters(); i++) {
303 // process annotations on method parameters
304 VarDescriptor vd = (VarDescriptor) md.getParameter(i);
305 assignLocationOfVarDescriptor(vd, md, md.getParameterTable(), null);
306 paramList.add(d2loc.get(vd));
308 Vector<AnnotationDescriptor> methodAnnotations = md.getModifiers().getAnnotations();
310 CompositeLocation returnLocComp = null;
312 boolean hasReturnLocDeclaration = false;
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);
320 hasReturnLocDeclaration = true;
321 } else if (an.getMarker().equals(ssjava.THISLOC)) {
322 String thisLoc = an.getValue();
323 ssjava.getMethodLattice(md).setThisLoc(thisLoc);
324 } else if (an.getMarker().equals(ssjava.GLOBALLOC)) {
325 String globalLoc = an.getValue();
326 ssjava.getMethodLattice(md).setGlobalLoc(globalLoc);
327 } else if (an.getMarker().equals(ssjava.PCLOC)) {
328 String pcLocDeclaration = an.getValue();
329 ssjava.setPCLocation(md, parseLocationDeclaration(md, null, pcLocDeclaration));
334 // second, check return location annotation
335 if (!md.getReturnType().isVoid() && !ssjava.getMethodContainingSSJavaLoop().equals(md)) {
336 if (!hasReturnLocDeclaration) {
337 // if developer does not define method lattice
338 // search return location in the method default lattice
339 String rtrStr = ssjava.getMethodLattice(md).getReturnLoc();
340 if (rtrStr != null) {
341 returnLocComp = new CompositeLocation(new Location(md, rtrStr));
345 if (returnLocComp == null) {
346 throw new Error("Return location is not specified for the method " + md + " at "
347 + cd.getSourceFileName());
350 md2ReturnLoc.put(md, returnLocComp);
354 if (!md.getReturnType().isVoid() && !ssjava.getMethodContainingSSJavaLoop().equals(md)) {
355 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
356 String thisLocId = methodLattice.getThisLoc();
357 if ((!md.isStatic())) {
359 if (thisLocId == null) {
360 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
361 + md.getClassDesc().getSourceFileName());
364 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
365 paramList.add(0, thisLoc);
369 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), md, paramList, md
370 + " of " + cd.getSourceFileName()));
374 // fourth, check declarations inside of method
376 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
380 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
381 bn.getVarTable().setParent(nametable);
382 for (int i = 0; i < bn.size(); i++) {
383 BlockStatementNode bsn = bn.get(i);
384 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
388 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
389 BlockStatementNode bsn) {
391 switch (bsn.kind()) {
392 case Kind.SubBlockNode:
393 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
396 case Kind.DeclarationNode:
397 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
401 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
404 case Kind.IfStatementNode:
405 checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
408 case Kind.SwitchStatementNode:
409 checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
412 case Kind.SynchronizedNode:
413 checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
419 private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
420 SynchronizedNode sbn) {
421 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
424 private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
425 SwitchStatementNode ssn) {
426 BlockNode sbn = ssn.getSwitchBody();
427 for (int i = 0; i < sbn.size(); i++) {
428 SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
429 checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
433 private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
434 IfStatementNode isn) {
435 checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
436 if (isn.getFalseBlock() != null)
437 checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
440 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
442 if (ln.getType() == LoopNode.FORLOOP) {
443 // check for loop case
444 ClassDescriptor cd = md.getClassDesc();
445 BlockNode bn = ln.getInitializer();
446 for (int i = 0; i < bn.size(); i++) {
447 BlockStatementNode bsn = bn.get(i);
448 checkDeclarationInBlockStatementNode(md, nametable, bsn);
453 checkDeclarationInBlockNode(md, nametable, ln.getBody());
456 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md,
457 CompositeLocation constraints) {
458 BlockNode bn = state.getMethodBody(md);
459 checkLocationFromBlockNode(md, md.getParameterTable(), bn, constraints);
462 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
464 return cd.getSourceFileName() + "::" + tn.getNumLine();
466 return cd.getSourceFileName();
471 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
472 BlockNode bn, CompositeLocation constraint) {
474 bn.getVarTable().setParent(nametable);
475 for (int i = 0; i < bn.size(); i++) {
476 BlockStatementNode bsn = bn.get(i);
477 checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
479 return new CompositeLocation();
483 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
484 SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
486 CompositeLocation compLoc = null;
487 switch (bsn.kind()) {
488 case Kind.BlockExpressionNode:
490 checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
493 case Kind.DeclarationNode:
494 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
497 case Kind.IfStatementNode:
498 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
502 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
505 case Kind.ReturnNode:
506 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
509 case Kind.SubBlockNode:
510 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
513 case Kind.ContinueBreakNode:
514 compLoc = new CompositeLocation();
517 case Kind.SwitchStatementNode:
519 checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
525 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
526 SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
528 ClassDescriptor cd = md.getClassDesc();
529 CompositeLocation condLoc =
530 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
532 BlockNode sbn = ssn.getSwitchBody();
534 constraint = generateNewConstraint(constraint, condLoc);
536 for (int i = 0; i < sbn.size(); i++) {
537 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
539 return new CompositeLocation();
542 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
543 SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
545 CompositeLocation blockLoc =
546 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
552 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
553 ReturnNode rn, CompositeLocation constraint) {
555 if (ssjava.getMethodContainingSSJavaLoop().equals(md)) {
556 return new CompositeLocation();
559 ExpressionNode returnExp = rn.getReturnExpression();
561 CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
563 CompositeLocation returnValueLoc;
564 if (returnExp != null) {
566 checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
569 // System.out.println("# RETURN VALUE LOC=" + returnValueLoc +
570 // " with constraint=" + constraint);
572 // TODO: do we need to check here?
573 // if this return statement is inside branch, return value has an implicit
574 // flow from conditional location
575 // if (constraint != null) {
576 // Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
577 // inputGLB.add(returnValueLoc);
578 // inputGLB.add(constraint);
580 // CompositeLattice.calculateGLB(inputGLB,
581 // generateErrorMessage(md.getClassDesc(), rn));
584 if (constraint != null) {
586 // Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
587 // inputGLB.add(returnValueLoc);
588 // inputGLB.add(constraint);
590 // CompositeLattice.calculateGLB(inputGLB,
591 // generateErrorMessage(md.getClassDesc(), rn));
593 // if (!returnValueLoc.get(returnValueLoc.getSize() - 1).isTop()) {
594 // if (!CompositeLattice.isGreaterThan(constraint, returnValueLoc,
595 // generateErrorMessage(md.getClassDesc(), rn))) {
596 // System.out.println("returnValueLoc.get(returnValueLoc.getSize() - 1).isTop()="
597 // + returnValueLoc.get(returnValueLoc.getSize() - 1).isTop());
598 // throw new Error("The value flow from " + constraint + " to " +
600 // + " does not respect location hierarchy on the assignment " +
602 // + " at " + md.getClassDesc().getSourceFileName() + "::" +
607 if (!CompositeLattice.isGreaterThan(constraint, declaredReturnLoc,
608 generateErrorMessage(md.getClassDesc(), rn))) {
609 throw new Error("The value flow from " + constraint + " to " + declaredReturnLoc
610 + " does not respect location hierarchy on the assignment " + rn.printNode(0)
611 + " at " + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
616 // check if return value is equal or higher than RETRUNLOC of method
617 // declaration annotation
620 CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
621 generateErrorMessage(md.getClassDesc(), rn));
623 if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
625 "Return value location is not equal or higher than the declaraed return location at "
626 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
630 return new CompositeLocation();
633 private boolean hasOnlyLiteralValue(ExpressionNode en) {
634 if (en.kind() == Kind.LiteralNode) {
641 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
642 LoopNode ln, CompositeLocation constraint) {
644 ClassDescriptor cd = md.getClassDesc();
645 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
647 CompositeLocation condLoc =
648 checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
649 new CompositeLocation(), constraint, false);
650 // addLocationType(ln.getCondition().getType(), (condLoc));
652 constraint = generateNewConstraint(constraint, condLoc);
653 checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
655 return new CompositeLocation();
658 // check 'for loop' case
659 BlockNode bn = ln.getInitializer();
660 bn.getVarTable().setParent(nametable);
661 // need to check initialization node
662 // checkLocationFromBlockNode(md, bn.getVarTable(), bn, constraint);
663 for (int i = 0; i < bn.size(); i++) {
664 BlockStatementNode bsn = bn.get(i);
665 checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
668 // calculate glb location of condition and update statements
669 CompositeLocation condLoc =
670 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
671 new CompositeLocation(), constraint, false);
672 // addLocationType(ln.getCondition().getType(), condLoc);
674 constraint = generateNewConstraint(constraint, condLoc);
676 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
677 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
679 return new CompositeLocation();
685 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
686 SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
687 CompositeLocation compLoc =
688 checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
692 private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
693 CompositeLocation newCon) {
695 if (currentCon == null) {
698 // compute GLB of current constraint and new constraint
699 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
700 inputSet.add(currentCon);
701 inputSet.add(newCon);
702 return CompositeLattice.calculateGLB(inputSet, "");
707 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
708 SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
710 System.out.println("\n\ncheckLocationFromIfStatementNode=" + isn.printNode(0));
711 CompositeLocation condLoc =
712 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
715 System.out.println("-######old constraint=" + constraint);
716 constraint = generateNewConstraint(constraint, condLoc);
717 System.out.println("-######new constraint=" + constraint);
718 checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
720 if (isn.getFalseBlock() != null) {
721 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
724 return new CompositeLocation();
727 private void checkOwnership(MethodDescriptor md, TreeNode tn, ExpressionNode srcExpNode) {
729 if (srcExpNode.kind() == Kind.NameNode || srcExpNode.kind() == Kind.FieldAccessNode) {
730 if (srcExpNode.getType().isPtr() && !srcExpNode.getType().isNull()) {
731 // first, check the linear type
732 // RHS reference should be owned by the current method
733 FieldDescriptor fd = getFieldDescriptorFromExpressionNode(srcExpNode);
737 isOwned = ((SSJavaType) srcExpNode.getType().getExtension()).isOwned();
740 isOwned = ssjava.isOwnedByMethod(md, fd);
744 "It is not allowed to create the reference alias from the reference not owned by the method at "
745 + generateErrorMessage(md.getClassDesc(), tn));
753 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
754 SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
756 VarDescriptor vd = dn.getVarDescriptor();
758 CompositeLocation destLoc = d2loc.get(vd);
760 if (dn.getExpression() != null) {
762 checkOwnership(md, dn, dn.getExpression());
764 CompositeLocation expressionLoc =
765 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
766 new CompositeLocation(), constraint, false);
767 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
769 if (expressionLoc != null) {
771 // checking location order
772 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
773 generateErrorMessage(md.getClassDesc(), dn))) {
774 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
775 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
776 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
779 return expressionLoc;
783 return new CompositeLocation();
789 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
791 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
794 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
795 SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
797 CompositeLocation compLoc =
798 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
799 // addTypeLocation(ben.getExpression().getType(), compLoc);
803 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
804 SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
805 CompositeLocation constraint, boolean isLHS) {
807 CompositeLocation compLoc = null;
810 case Kind.AssignmentNode:
812 checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
815 case Kind.FieldAccessNode:
817 checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
821 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
825 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
828 case Kind.CreateObjectNode:
829 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
832 case Kind.ArrayAccessNode:
834 checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
837 case Kind.LiteralNode:
838 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
841 case Kind.MethodInvokeNode:
843 checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
846 case Kind.TertiaryNode:
847 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
851 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
854 // case Kind.InstanceOfNode:
855 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
858 // case Kind.ArrayInitializerNode:
859 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
863 // case Kind.ClassTypeNode:
864 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
867 // case Kind.OffsetNode:
868 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
875 // addTypeLocation(en.getType(), compLoc);
880 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
881 CastNode cn, CompositeLocation constraint) {
883 ExpressionNode en = cn.getExpression();
884 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
889 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
890 SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
891 ClassDescriptor cd = md.getClassDesc();
893 CompositeLocation condLoc =
894 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
896 // addLocationType(tn.getCond().getType(), condLoc);
897 CompositeLocation trueLoc =
898 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
900 // addLocationType(tn.getTrueExpr().getType(), trueLoc);
901 CompositeLocation falseLoc =
902 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
904 // addLocationType(tn.getFalseExpr().getType(), falseLoc);
906 // locations from true/false branches can be TOP when there are only literal
908 // in this case, we don't need to check flow down rule!
910 // System.out.println("\n#tertiary cond=" + tn.getCond().printNode(0) +
911 // " Loc=" + condLoc);
912 // System.out.println("# true=" + tn.getTrueExpr().printNode(0) + " Loc=" +
914 // System.out.println("# false=" + tn.getFalseExpr().printNode(0) + " Loc="
917 // we don't need to check that condLoc is higher than trueLoc & falseLoc
918 // if (!trueLoc.get(0).isTop()
919 // && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
921 // "The location of the condition expression is lower than the true expression at "
922 // + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
925 // if (!falseLoc.get(0).isTop()
926 // && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
927 // generateErrorMessage(cd, tn.getCond()))) {
929 // "The location of the condition expression is lower than the false expression at "
930 // + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
933 // then, return glb of trueLoc & falseLoc
934 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
935 glbInputSet.add(condLoc);
936 glbInputSet.add(trueLoc);
937 glbInputSet.add(falseLoc);
939 if (glbInputSet.size() == 1) {
942 return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
947 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
948 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
949 CompositeLocation constraint) {
951 ClassDescriptor cd = md.getClassDesc();
952 MethodDescriptor calleeMethodDesc = min.getMethod();
954 NameDescriptor baseName = min.getBaseName();
955 boolean isSystemout = false;
956 if (baseName != null) {
957 isSystemout = baseName.getSymbol().equals("System.out");
960 if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
961 && !ssjava.isTrustMethod(calleeMethodDesc) && !calleeMethodDesc.getModifiers().isNative()
964 CompositeLocation baseLocation = null;
965 if (min.getExpression() != null) {
967 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
968 new CompositeLocation(), constraint, false);
970 if (min.getMethod().isStatic()) {
971 String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
972 if (globalLocId == null) {
973 throw new Error("Method lattice does not define global variable location at "
974 + generateErrorMessage(md.getClassDesc(), min));
976 baseLocation = new CompositeLocation(new Location(md, globalLocId));
978 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
979 baseLocation = new CompositeLocation(new Location(md, thisLocId));
983 // System.out.println("\n#checkLocationFromMethodInvokeNode=" +
985 // + " baseLocation=" + baseLocation + " constraint=" + constraint);
987 // setup the location list of caller's arguments
988 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
990 // setup the location list of callee's parameters
991 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleeMethodDesc);
992 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
994 if (min.numArgs() > 0) {
995 if (!calleeMethodDesc.isStatic()) {
996 callerArgList.add(baseLocation);
998 for (int i = 0; i < min.numArgs(); i++) {
999 ExpressionNode en = min.getArg(i);
1000 CompositeLocation callerArgLoc =
1001 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(),
1003 callerArgList.add(callerArgLoc);
1006 if (!calleeMethodDesc.isStatic()) {
1007 CompositeLocation calleeThisLoc =
1008 new CompositeLocation(new Location(calleeMethodDesc, calleeLattice.getThisLoc()));
1009 calleeParamList.add(calleeThisLoc);
1012 for (int i = 0; i < calleeMethodDesc.numParameters(); i++) {
1013 VarDescriptor calleevd = (VarDescriptor) calleeMethodDesc.getParameter(i);
1014 CompositeLocation calleeLoc = d2loc.get(calleevd);
1015 calleeParamList.add(calleeLoc);
1019 if (constraint != null) {
1020 // check whether the PC location is lower than one of the
1021 // argument locations. If it is lower, the callee has to have @PCLOC
1022 // annotation that declares the program counter that is higher than
1023 // corresponding parameter
1025 CompositeLocation calleePCLOC = ssjava.getPCLocation(calleeMethodDesc);
1027 for (int idx = 0; idx < callerArgList.size(); idx++) {
1028 CompositeLocation argLocation = callerArgList.get(idx);
1030 // if the PC location is lower than an argument location
1031 // then, need to check that the callee's the initial location for the PC is also lower
1032 // than the corresponding parameter location
1034 if (!argLocation.get(0).isTop()
1035 && CompositeLattice.compare(argLocation, constraint, true,
1036 generateErrorMessage(cd, min)) == ComparisonResult.GREATER) {
1038 CompositeLocation paramLocation = calleeParamList.get(idx);
1040 int paramCompareResult =
1041 CompositeLattice.compare(paramLocation, calleePCLOC, true,
1042 generateErrorMessage(cd, min));
1043 // CompositeLattice.compare(calleePCLOC, paramLocation, true,
1044 // generateErrorMessage(cd, min));
1046 System.out.println("-CHECKPCLOC:");
1047 System.out.println("---ARG LOC="
1052 + CompositeLattice.compare(argLocation, constraint, true,
1053 generateErrorMessage(cd, min)));
1054 System.out.println("---PARAM LOC=" + paramLocation + " calleePCLOC=" + calleePCLOC
1055 + " paramCompareResult=" + paramCompareResult);
1057 if (!(paramLocation.get(0).equals(calleePCLOC.get(0)) && calleePCLOC.getSize() > 1)
1058 && paramCompareResult == ComparisonResult.LESS) {
1064 + "is higher than the caller program counter location "
1066 + ". Need to specify that the initial PC location of the callee, which is currently set to "
1067 + calleePCLOC + ", is not higher than " + paramLocation + " in the method "
1068 + calleeMethodDesc.getSymbol() + ":" + min.getNumLine());
1077 checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1079 checkCallerArgumentLocationConstraints(md, nametable, min, baseLocation, constraint);
1081 if (!min.getMethod().getReturnType().isVoid()) {
1082 // If method has a return value, compute the highest possible return
1083 // location in the caller's perspective
1084 CompositeLocation ceilingLoc =
1085 computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
1087 if (ceilingLoc == null) {
1088 return new CompositeLocation(Location.createTopLocation(md));
1094 return new CompositeLocation(Location.createTopLocation(md));
1098 private CompositeLocation translateCallerLocToCalleeLoc(MethodDescriptor calleeMD,
1099 CompositeLocation calleeBaseLoc, CompositeLocation constraint) {
1101 CompositeLocation calleeConstraint = new CompositeLocation();
1103 // if (constraint.startsWith(calleeBaseLoc)) {
1104 // if the first part of constraint loc is matched with callee base loc
1105 Location thisLoc = new Location(calleeMD, ssjava.getMethodLattice(calleeMD).getThisLoc());
1106 calleeConstraint.addLocation(thisLoc);
1107 for (int i = calleeBaseLoc.getSize(); i < constraint.getSize(); i++) {
1108 calleeConstraint.addLocation(constraint.get(i));
1113 return calleeConstraint;
1116 private void checkCallerArgumentLocationConstraints(MethodDescriptor md, SymbolTable nametable,
1117 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1118 // if parameter location consists of THIS and FIELD location,
1119 // caller should pass an argument that is comparable to the declared
1120 // parameter location
1121 // and is not lower than the declared parameter location in the field
1124 MethodDescriptor calleemd = min.getMethod();
1126 if (calleemd.isStatic()) {
1130 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1131 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1133 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1134 Location calleeThisLoc = new Location(calleemd, calleeLattice.getThisLoc());
1136 for (int i = 0; i < min.numArgs(); i++) {
1137 ExpressionNode en = min.getArg(i);
1138 CompositeLocation callerArgLoc =
1139 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1141 callerArgList.add(callerArgLoc);
1144 // setup callee params set
1145 for (int i = 0; i < calleemd.numParameters(); i++) {
1146 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1147 CompositeLocation calleeLoc = d2loc.get(calleevd);
1148 calleeParamList.add(calleeLoc);
1151 String errorMsg = generateErrorMessage(md.getClassDesc(), min);
1153 // System.out.println("checkCallerArgumentLocationConstraints=" +
1154 // min.printNode(0));
1155 // System.out.println("base location=" + callerBaseLoc + " constraint=" +
1158 System.out.println("calleeParamList=" + calleeParamList);
1160 if (!md.isStatic()) {
1163 for (int i = offset; i < calleeParamList.size(); i++) {
1164 CompositeLocation calleeParamLoc = calleeParamList.get(i);
1165 if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
1167 // callee parameter location has field information
1168 CompositeLocation callerArgLoc = callerArgList.get(i);
1170 CompositeLocation paramLocation =
1171 translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
1173 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1174 if (constraint != null) {
1175 inputGLBSet.add(callerArgLoc);
1176 inputGLBSet.add(constraint);
1178 CompositeLattice.calculateGLB(inputGLBSet,
1179 generateErrorMessage(md.getClassDesc(), min));
1182 Location argLastLoc = callerArgLoc.get(callerArgLoc.getSize() - 1);
1183 Location paramLastLoc = paramLocation.get(paramLocation.getSize() - 1);
1185 if (argLastLoc.equals(paramLastLoc) && ssjava.isSharedLocation(argLastLoc)
1186 && ssjava.isSharedLocation(paramLastLoc)) {
1190 System.out.println("---idx=" + i + " callerArgLoc=" + callerArgLoc + " paramLocation="
1192 // if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
1193 if (CompositeLattice.compare(callerArgLoc, paramLocation, true, errorMsg) == ComparisonResult.LESS) {
1194 throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
1195 + "' should be higher than corresponding callee's parameter : " + paramLocation
1196 + " at " + errorMsg);
1204 private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
1205 CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
1207 CompositeLocation translate = new CompositeLocation();
1209 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
1210 translate.addLocation(callerBaseLocation.get(i));
1213 for (int i = 1; i < calleeParamLoc.getSize(); i++) {
1214 translate.addLocation(calleeParamLoc.get(i));
1217 // System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" +
1223 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
1224 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
1225 CompositeLocation constraint) {
1226 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
1228 // by default, method has a THIS parameter
1229 if (!min.getMethod().isStatic()) {
1230 argList.add(baseLocation);
1233 for (int i = 0; i < min.numArgs(); i++) {
1234 ExpressionNode en = min.getArg(i);
1235 CompositeLocation callerArg =
1236 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1238 argList.add(callerArg);
1241 // System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
1242 CompositeLocation ceilLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
1243 // System.out.println("## ReturnLocation=" + ceilLoc);
1249 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
1250 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1252 MethodDescriptor calleemd = min.getMethod();
1254 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1256 System.out.println("checkCalleeConstraints=" + calleemd + " calleeLattice.getThisLoc()="
1257 + calleeLattice.getThisLoc());
1259 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1260 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1262 if (min.numArgs() > 0) {
1263 // caller needs to guarantee that it passes arguments in regarding to
1264 // callee's hierarchy
1266 // setup caller args set
1267 // first, add caller's base(this) location
1268 if (!calleemd.isStatic())
1269 callerArgList.add(callerBaseLoc);
1270 // second, add caller's arguments
1271 for (int i = 0; i < min.numArgs(); i++) {
1272 ExpressionNode en = min.getArg(i);
1273 CompositeLocation callerArgLoc =
1274 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1276 callerArgList.add(callerArgLoc);
1279 // setup callee params set
1280 // first, add callee's this location
1281 if (!calleemd.isStatic()) {
1282 CompositeLocation calleeThisLoc =
1283 new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
1284 calleeParamList.add(calleeThisLoc);
1286 // second, add callee's parameters
1287 for (int i = 0; i < calleemd.numParameters(); i++) {
1288 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1289 CompositeLocation calleeLoc = d2loc.get(calleevd);
1290 // System.out.println("calleevd=" + calleevd + " loc=" + calleeLoc);
1291 calleeParamList.add(calleeLoc);
1294 // here, check if ordering relations among caller's args respect
1295 // ordering relations in-between callee's args
1296 CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1297 CompositeLocation calleeLoc1 = calleeParamList.get(i);
1298 CompositeLocation callerLoc1 = callerArgList.get(i);
1300 for (int j = 0; j < calleeParamList.size(); j++) {
1302 CompositeLocation calleeLoc2 = calleeParamList.get(j);
1303 CompositeLocation callerLoc2 = callerArgList.get(j);
1305 if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1306 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1310 // System.out.println("calleeLoc1=" + calleeLoc1);
1311 // System.out.println("calleeLoc2=" + calleeLoc2 +
1312 // "calleeParamList=" + calleeParamList);
1315 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1316 generateErrorMessage(md.getClassDesc(), min));
1317 // System.out.println("callerResult=" + callerResult);
1319 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1320 generateErrorMessage(md.getClassDesc(), min));
1321 // System.out.println("calleeResult=" + calleeResult);
1323 if (callerResult == ComparisonResult.EQUAL) {
1324 if (ssjava.isSharedLocation(callerLoc1.get(callerLoc1.getSize() - 1))
1325 && ssjava.isSharedLocation(callerLoc2.get(callerLoc2.getSize() - 1))) {
1326 // if both of them are shared locations, promote them to
1327 // "GREATER relation"
1328 callerResult = ComparisonResult.GREATER;
1332 if (calleeResult == ComparisonResult.GREATER
1333 && callerResult != ComparisonResult.GREATER) {
1334 // If calleeLoc1 is higher than calleeLoc2
1335 // then, caller should have same ordering relation in-bet
1336 // callerLoc1 & callerLoc2
1338 String paramName1, paramName2;
1340 if (!calleemd.isStatic()) {
1342 paramName1 = "'THIS'";
1344 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1347 paramName1 = "'parameter " + calleemd.getParamName(i) + "'";
1350 if (!calleemd.isStatic()) {
1351 if (j == 0 && !calleemd.isStatic()) {
1352 paramName2 = "'THIS'";
1354 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1357 paramName2 = "'parameter " + calleemd.getParamName(j) + "'";
1361 "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1362 + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1363 + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1374 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1375 SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1376 System.out.println("aan=" + aan.printNode(0) + " line#=" + aan.getNumLine());
1377 ClassDescriptor cd = md.getClassDesc();
1378 System.out.println("aan.getExpression()=" + aan.getExpression().getClass());
1379 CompositeLocation arrayLoc =
1380 checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1381 new CompositeLocation(), constraint, isLHS);
1382 System.out.println("HERE?");
1383 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1384 CompositeLocation indexLoc =
1385 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1387 // addTypeLocation(aan.getIndex().getType(), indexLoc);
1388 System.out.println("HERE2?");
1391 if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1392 throw new Error("Array index value is not higher than array location at "
1393 + generateErrorMessage(cd, aan));
1397 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1398 inputGLB.add(arrayLoc);
1399 inputGLB.add(indexLoc);
1400 System.out.println("arrayLoc=" + arrayLoc + " indexLoc=" + indexLoc);
1401 CompositeLocation comp =
1402 CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1403 System.out.println("---aan=" + aan.printNode(0) + " compLoc=" + comp);
1409 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1410 SymbolTable nametable, CreateObjectNode con) {
1412 ClassDescriptor cd = md.getClassDesc();
1414 CompositeLocation compLoc = new CompositeLocation();
1415 compLoc.addLocation(Location.createTopLocation(md));
1420 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1421 OpNode on, CompositeLocation constraint) {
1423 ClassDescriptor cd = md.getClassDesc();
1424 CompositeLocation leftLoc = new CompositeLocation();
1426 checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1427 // addTypeLocation(on.getLeft().getType(), leftLoc);
1429 CompositeLocation rightLoc = new CompositeLocation();
1430 if (on.getRight() != null) {
1432 checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1433 // addTypeLocation(on.getRight().getType(), rightLoc);
1436 // System.out.println("# left loc=" + leftLoc + " from " + on.getLeft().getClass());
1437 // if (on.getRight() != null) {
1438 // System.out.println("# right loc=" + rightLoc + " from " + on.getRight().getClass());
1441 Operation op = on.getOp();
1443 switch (op.getOp()) {
1445 case Operation.UNARYPLUS:
1446 case Operation.UNARYMINUS:
1447 case Operation.LOGIC_NOT:
1451 case Operation.LOGIC_OR:
1452 case Operation.LOGIC_AND:
1453 case Operation.COMP:
1454 case Operation.BIT_OR:
1455 case Operation.BIT_XOR:
1456 case Operation.BIT_AND:
1457 case Operation.ISAVAILABLE:
1458 case Operation.EQUAL:
1459 case Operation.NOTEQUAL:
1466 case Operation.MULT:
1469 case Operation.LEFTSHIFT:
1470 case Operation.RIGHTSHIFT:
1471 case Operation.URIGHTSHIFT:
1473 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1474 inputSet.add(leftLoc);
1475 inputSet.add(rightLoc);
1476 CompositeLocation glbCompLoc =
1477 CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1481 throw new Error(op.toString());
1486 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1487 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1489 // literal value has the top location so that value can be flowed into any
1491 Location literalLoc = Location.createTopLocation(md);
1492 loc.addLocation(literalLoc);
1497 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1498 NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1500 // System.out.println("checkLocationFromNameNode nn=" + nn.printNode(0));
1501 NameDescriptor nd = nn.getName();
1502 if (nd.getBase() != null) {
1504 checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1506 String varname = nd.toString();
1507 if (varname.equals("this")) {
1509 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1510 String thisLocId = methodLattice.getThisLoc();
1511 if (thisLocId == null) {
1512 throw new Error("The location for 'this' is not defined at "
1513 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1515 Location locElement = new Location(md, thisLocId);
1516 loc.addLocation(locElement);
1521 Descriptor d = (Descriptor) nametable.get(varname);
1523 // CompositeLocation localLoc = null;
1524 if (d instanceof VarDescriptor) {
1525 VarDescriptor vd = (VarDescriptor) d;
1526 // localLoc = d2loc.get(vd);
1527 // the type of var descriptor has a composite location!
1528 loc = ((SSJavaType) vd.getType().getExtension()).getCompLoc().clone();
1529 } else if (d instanceof FieldDescriptor) {
1530 // the type of field descriptor has a location!
1531 FieldDescriptor fd = (FieldDescriptor) d;
1532 // System.out.println("fd=" + fd);
1533 if (fd.isStatic()) {
1535 // if it is 'static final', the location has TOP since no one can
1537 loc.addLocation(Location.createTopLocation(md));
1541 // if 'static', the location has pre-assigned global loc
1542 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1543 String globalLocId = localLattice.getGlobalLoc();
1544 if (globalLocId == null) {
1545 throw new Error("Global location element is not defined in the method " + md);
1547 Location globalLoc = new Location(md, globalLocId);
1548 System.out.println("static=" + globalLoc);
1549 loc.addLocation(globalLoc);
1552 // the location of field access starts from this, followed by field
1554 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1555 Location thisLoc = new Location(md, localLattice.getThisLoc());
1556 loc.addLocation(thisLoc);
1559 Location fieldLoc = (Location) fd.getType().getExtension();
1560 loc.addLocation(fieldLoc);
1561 } else if (d == null) {
1562 // access static field
1563 FieldDescriptor fd = nn.getField();
1565 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1566 String globalLocId = localLattice.getGlobalLoc();
1567 if (globalLocId == null) {
1568 throw new Error("Method lattice does not define global variable location at "
1569 + generateErrorMessage(md.getClassDesc(), nn));
1571 loc.addLocation(new Location(md, globalLocId));
1573 Location fieldLoc = (Location) fd.getType().getExtension();
1574 loc.addLocation(fieldLoc);
1584 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1585 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1586 CompositeLocation constraint) {
1588 ExpressionNode left = fan.getExpression();
1589 TypeDescriptor ltd = left.getType();
1591 FieldDescriptor fd = fan.getField();
1593 String varName = null;
1594 if (left.kind() == Kind.NameNode) {
1595 NameDescriptor nd = ((NameNode) left).getName();
1596 varName = nd.toString();
1599 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1600 // using a class name directly or access using this
1601 if (fd.isStatic() && fd.isFinal()) {
1602 loc.addLocation(Location.createTopLocation(md));
1607 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1608 if (left instanceof ArrayAccessNode) {
1609 ArrayAccessNode aan = (ArrayAccessNode) left;
1610 CompositeLocation indexLoc =
1611 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), loc, constraint, false);
1612 inputGLB.add(indexLoc);
1615 loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1617 if (!left.getType().isPrimitive()) {
1619 if (!fd.getSymbol().equals("length")) {
1620 // array.length access, return the location of the array
1621 Location fieldLoc = getFieldLocation(fd);
1622 loc.addLocation(fieldLoc);
1628 loc = CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), fan));
1633 private Location getFieldLocation(FieldDescriptor fd) {
1635 // System.out.println("### getFieldLocation=" + fd);
1636 // System.out.println("### fd.getType().getExtension()=" +
1637 // fd.getType().getExtension());
1639 Location fieldLoc = (Location) fd.getType().getExtension();
1641 // handle the case that method annotation checking skips checking field
1643 if (fieldLoc == null) {
1644 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1651 private FieldDescriptor getFieldDescriptorFromExpressionNode(ExpressionNode en) {
1653 if (en.kind() == Kind.NameNode) {
1654 NameNode nn = (NameNode) en;
1655 if (nn.getField() != null) {
1656 return nn.getField();
1659 if (nn.getName() != null && nn.getName().getBase() != null) {
1660 return getFieldDescriptorFromExpressionNode(nn.getExpression());
1663 } else if (en.kind() == Kind.FieldAccessNode) {
1664 FieldAccessNode fan = (FieldAccessNode) en;
1665 return fan.getField();
1671 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1672 SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1674 System.out.println("\n\ncheckLocationFromAssignmentNode=" + an.printNode(0));
1676 ClassDescriptor cd = md.getClassDesc();
1678 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1680 boolean postinc = true;
1681 if (an.getOperation().getBaseOp() == null
1682 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1683 .getBaseOp().getOp() != Operation.POSTDEC))
1686 // if LHS is array access node, need to check if array index is higher
1687 // than array itself
1688 CompositeLocation destLocation =
1689 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1692 CompositeLocation rhsLocation;
1693 CompositeLocation srcLocation;
1697 checkOwnership(md, an, an.getSrc());
1700 checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1703 if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
1704 // if assignment contains OP+EQ operator, need to merge location types
1705 // of LHS & RHS into the RHS
1706 Set<CompositeLocation> srcGLBSet = new HashSet<CompositeLocation>();
1707 srcGLBSet.add(rhsLocation);
1708 srcGLBSet.add(destLocation);
1709 srcLocation = CompositeLattice.calculateGLB(srcGLBSet, generateErrorMessage(cd, an));
1711 srcLocation = rhsLocation;
1714 if (constraint != null) {
1716 if (!CompositeLattice.isGreaterThan(constraint, destLocation, generateErrorMessage(cd, an))) {
1717 throw new Error("The value flow from " + constraint + " to " + destLocation
1718 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1719 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1721 // inputGLBSet.add(srcLocation);
1722 // inputGLBSet.add(constraint);
1723 // srcLocation = CompositeLattice.calculateGLB(inputGLBSet,
1724 // generateErrorMessage(cd, an));
1727 System.out.println("src=" + srcLocation + " dest=" + destLocation + " const=" + constraint);
1729 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1731 String context = "";
1732 if (constraint != null) {
1733 context = " and the current context constraint is " + constraint;
1736 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1737 + " does not respect location hierarchy on the assignment " + an.printNode(0) + context
1738 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1741 if (srcLocation.equals(destLocation)) {
1742 // keep it for definitely written analysis
1743 Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1744 for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1745 FlatNode fn = (FlatNode) iterator.next();
1746 System.out.println("SAMEHEIGHT!");
1747 ssjava.addSameHeightWriteFlatNode(fn);
1751 System.out.println("NOT SAME HEIGHT!");
1757 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1760 if (constraint != null) {
1762 if (!CompositeLattice.isGreaterThan(constraint, destLocation, generateErrorMessage(cd, an))) {
1763 throw new Error("The value flow from " + constraint + " to " + destLocation
1764 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1765 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1767 // inputGLBSet.add(rhsLocation);
1768 // inputGLBSet.add(constraint);
1769 // srcLocation = CompositeLattice.calculateGLB(inputGLBSet,
1770 // generateErrorMessage(cd, an));
1771 srcLocation = rhsLocation;
1773 srcLocation = rhsLocation;
1776 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1778 if (srcLocation.equals(destLocation)) {
1779 throw new Error("Location " + srcLocation
1780 + " is not allowed to have the value flow that moves within the same location at '"
1781 + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1783 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1784 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1785 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1790 if (srcLocation.equals(destLocation)) {
1791 // keep it for definitely written analysis
1792 Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1793 for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1794 FlatNode fn = (FlatNode) iterator.next();
1795 ssjava.addSameHeightWriteFlatNode(fn);
1801 return destLocation;
1804 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1805 SymbolTable nametable, TreeNode n) {
1807 ClassDescriptor cd = md.getClassDesc();
1808 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1810 // currently enforce every variable to have corresponding location
1811 if (annotationVec.size() == 0) {
1812 throw new Error("Location is not assigned to variable '" + vd.getSymbol()
1813 + "' in the method '" + md + "' of the class " + cd.getSymbol() + " at "
1814 + generateErrorMessage(cd, n));
1817 int locDecCount = 0;
1818 for (int i = 0; i < annotationVec.size(); i++) {
1819 AnnotationDescriptor ad = annotationVec.elementAt(i);
1821 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1823 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1825 if (locDecCount > 1) {// variable can have at most one location
1826 throw new Error(vd.getSymbol() + " has more than one location declaration.");
1828 String locDec = ad.getValue(); // check if location is defined
1830 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1831 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1832 d2loc.put(vd, deltaLoc);
1833 addLocationType(vd.getType(), deltaLoc);
1835 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1837 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1838 if (ssjava.isSharedLocation(lastElement)) {
1839 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1842 d2loc.put(vd, compLoc);
1843 addLocationType(vd.getType(), compLoc);
1852 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1855 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1858 int beginIdx = dIdx + 6;
1859 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1860 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1863 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1864 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1869 private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1871 int idx = decl.indexOf(".");
1873 String className = decl.substring(0, idx);
1874 String fieldName = decl.substring(idx + 1);
1876 className.replaceAll(" ", "");
1877 fieldName.replaceAll(" ", "");
1879 Descriptor d = state.getClassSymbolTable().get(className);
1882 // System.out.println("state.getClassSymbolTable()=" +
1883 // state.getClassSymbolTable());
1884 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1888 assert (d instanceof ClassDescriptor);
1889 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1890 if (!lattice.containsKey(fieldName)) {
1891 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1892 + className + "' at " + msg);
1895 return new Location(d, fieldName);
1898 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1900 CompositeLocation compLoc = new CompositeLocation();
1902 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1903 List<String> locIdList = new ArrayList<String>();
1904 while (tokenizer.hasMoreTokens()) {
1905 String locId = tokenizer.nextToken();
1906 locIdList.add(locId);
1909 // at least,one location element needs to be here!
1910 assert (locIdList.size() > 0);
1912 // assume that loc with idx 0 comes from the local lattice
1913 // loc with idx 1 comes from the field lattice
1915 String localLocId = locIdList.get(0);
1916 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1917 Location localLoc = new Location(md, localLocId);
1918 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1919 throw new Error("Location " + localLocId
1920 + " is not defined in the local variable lattice at "
1921 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1923 compLoc.addLocation(localLoc);
1925 for (int i = 1; i < locIdList.size(); i++) {
1926 String locName = locIdList.get(i);
1929 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1930 compLoc.addLocation(fieldLoc);
1931 } catch (Exception e) {
1932 throw new Error("The location declaration '" + locName + "' is wrong at "
1933 + generateErrorMessage(md.getClassDesc(), n));
1941 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1942 VarDescriptor vd = dn.getVarDescriptor();
1943 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1946 private void checkDeclarationInClass(ClassDescriptor cd) {
1947 // Check to see that fields are okay
1948 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1949 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1951 if (!(fd.isFinal() && fd.isStatic())) {
1952 checkFieldDeclaration(cd, fd);
1954 // for static final, assign top location by default
1955 Location loc = Location.createTopLocation(cd);
1956 addLocationType(fd.getType(), loc);
1961 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1963 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1965 // currently enforce every field to have corresponding location
1966 if (annotationVec.size() == 0) {
1967 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1968 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1971 if (annotationVec.size() > 1) {
1972 // variable can have at most one location
1973 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1974 + " has more than one location.");
1977 AnnotationDescriptor ad = annotationVec.elementAt(0);
1978 Location loc = null;
1980 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1981 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1982 String locationID = ad.getValue();
1983 // check if location is defined
1984 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1985 if (lattice == null || (!lattice.containsKey(locationID))) {
1986 throw new Error("Location " + locationID
1987 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1988 + cd.getSourceFileName() + ".");
1990 loc = new Location(cd, locationID);
1992 if (ssjava.isSharedLocation(loc)) {
1993 ssjava.mapSharedLocation2Descriptor(loc, fd);
1996 addLocationType(fd.getType(), loc);
1998 if (ssjava.isSharedLocation(loc)) {
1999 ssjava.addSharedDesc(loc, fd);
2007 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
2009 TypeExtension te = type.getExtension();
2012 ssType = (SSJavaType) te;
2013 ssType.setCompLoc(loc);
2015 ssType = new SSJavaType(loc);
2016 type.setExtension(ssType);
2021 private void addLocationType(TypeDescriptor type, Location loc) {
2023 type.setExtension(loc);
2027 static class CompositeLattice {
2029 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
2031 // System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" +
2033 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
2034 if (baseCompareResult == ComparisonResult.EQUAL) {
2035 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
2040 } else if (baseCompareResult == ComparisonResult.GREATER) {
2048 public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
2051 // System.out.println("compare=" + loc1 + " " + loc2);
2052 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
2054 if (baseCompareResult == ComparisonResult.EQUAL) {
2055 return compareDelta(loc1, loc2);
2057 return baseCompareResult;
2062 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
2064 int deltaCount1 = 0;
2065 int deltaCount2 = 0;
2066 if (dLoc1 instanceof DeltaLocation) {
2067 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
2070 if (dLoc2 instanceof DeltaLocation) {
2071 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
2073 if (deltaCount1 < deltaCount2) {
2074 return ComparisonResult.GREATER;
2075 } else if (deltaCount1 == deltaCount2) {
2076 return ComparisonResult.EQUAL;
2078 return ComparisonResult.LESS;
2083 private static int compareBaseLocationSet(CompositeLocation compLoc1,
2084 CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
2086 // if compLoc1 is greater than compLoc2, return true
2087 // else return false;
2089 // compare one by one in according to the order of the tuple
2091 for (int i = 0; i < compLoc1.getSize(); i++) {
2092 Location loc1 = compLoc1.get(i);
2093 if (i >= compLoc2.getSize()) {
2095 return ComparisonResult.INCOMPARABLE;
2097 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2098 + " because they are not comparable at " + msg);
2101 Location loc2 = compLoc2.get(i);
2103 Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
2104 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
2106 // check if the shared location is appeared only at the end of the
2107 // composite location
2108 if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2109 if (i != (compLoc1.getSize() - 1)) {
2110 throw new Error("The shared location " + loc1.getLocIdentifier()
2111 + " cannot be appeared in the middle of composite location at" + msg);
2115 if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
2116 if (i != (compLoc2.getSize() - 1)) {
2117 throw new Error("The shared location " + loc2.getLocIdentifier()
2118 + " cannot be appeared in the middle of composite location at " + msg);
2122 // if (!lattice1.equals(lattice2)) {
2123 // throw new Error("Failed to compare two locations of " + compLoc1 +
2124 // " and " + compLoc2
2125 // + " because they are not comparable at " + msg);
2128 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
2130 // check if the current location is the spinning location
2131 // note that the spinning location only can be appeared in the last
2132 // part of the composite location
2133 if (awareSharedLoc && numOfTie == compLoc1.getSize()
2134 && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2135 return ComparisonResult.GREATER;
2138 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
2139 return ComparisonResult.GREATER;
2141 if (lattice.isComparable(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
2142 return ComparisonResult.LESS;
2144 return ComparisonResult.INCOMPARABLE;
2150 if (numOfTie == compLoc1.getSize()) {
2152 if (numOfTie != compLoc2.getSize()) {
2155 return ComparisonResult.INCOMPARABLE;
2157 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2158 + " because they are not comparable at " + msg);
2163 return ComparisonResult.EQUAL;
2166 return ComparisonResult.LESS;
2170 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
2172 System.out.println("Calculating GLB=" + inputSet);
2173 CompositeLocation glbCompLoc = new CompositeLocation();
2175 // calculate GLB of the first(priority) element
2176 Set<String> priorityLocIdentifierSet = new HashSet<String>();
2177 Descriptor priorityDescriptor = null;
2179 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
2180 new Hashtable<String, Set<CompositeLocation>>();
2181 // mapping from the priority loc ID to its full representation by the
2182 // composite location
2184 int maxTupleSize = 0;
2185 int minTupleSize = 0;
2186 CompositeLocation maxCompLoc = null;
2188 Location prevPriorityLoc = null;
2189 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
2190 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2191 if (compLoc.getSize() > maxTupleSize) {
2192 maxTupleSize = compLoc.getSize();
2193 maxCompLoc = compLoc;
2195 if (minTupleSize == 0 || compLoc.getSize() < minTupleSize) {
2196 minTupleSize = compLoc.getSize();
2198 Location priorityLoc = compLoc.get(0);
2199 String priorityLocId = priorityLoc.getLocIdentifier();
2200 priorityLocIdentifierSet.add(priorityLocId);
2202 if (locId2CompLocSet.containsKey(priorityLocId)) {
2203 locId2CompLocSet.get(priorityLocId).add(compLoc);
2205 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
2206 newSet.add(compLoc);
2207 locId2CompLocSet.put(priorityLocId, newSet);
2210 // check if priority location are coming from the same lattice
2211 if (priorityDescriptor == null) {
2212 priorityDescriptor = priorityLoc.getDescriptor();
2214 priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
2216 prevPriorityLoc = priorityLoc;
2217 // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
2218 // throw new Error("Failed to calculate GLB of " + inputSet
2219 // + " because they are from different lattices.");
2223 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
2224 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
2225 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
2226 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
2228 if (compSet == null) {
2229 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
2230 // mean that the result is already lower than <x1,y1> and <x2,y2>
2231 // assign TOP to the rest of the location elements
2233 // in this case, do not take care about delta
2234 // CompositeLocation inputComp = inputSet.iterator().next();
2235 // for (int i = 1; i < maxTupleSize; i++) {
2236 for (int i = 1; i < minTupleSize; i++) {
2237 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
2241 // here find out composite location that has a maximum length tuple
2242 // if we have three input set: [A], [A,B], [A,B,C]
2243 // maximum length tuple will be [A,B,C]
2245 CompositeLocation maxFromCompSet = null;
2246 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2247 CompositeLocation c = (CompositeLocation) iterator.next();
2248 if (c.getSize() > max) {
2254 if (compSet.size() == 1) {
2255 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
2256 CompositeLocation comp = compSet.iterator().next();
2257 for (int i = 1; i < comp.getSize(); i++) {
2258 glbCompLoc.addLocation(comp.get(i));
2261 // if input location corresponding to glb is a delta, need to apply
2262 // delta to glb result
2263 if (comp instanceof DeltaLocation) {
2264 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2268 // when GLB(x1,x2)==x1 and x2 : GLB case 1
2269 // if more than one location shares the same priority GLB
2270 // need to calculate the rest of GLB loc
2272 // setup input set starting from the second tuple item
2273 Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
2274 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2275 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2276 CompositeLocation innerCompLoc = new CompositeLocation();
2277 for (int idx = 1; idx < compLoc.getSize(); idx++) {
2278 innerCompLoc.addLocation(compLoc.get(idx));
2280 if (innerCompLoc.getSize() > 0) {
2281 innerGLBInput.add(innerCompLoc);
2285 if (innerGLBInput.size() > 0) {
2286 // System.out.println("######innerGLBInput=" + innerGLBInput);
2287 CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
2288 for (int idx = 0; idx < innerGLB.getSize(); idx++) {
2289 glbCompLoc.addLocation(innerGLB.get(idx));
2293 // if input location corresponding to glb is a delta, need to apply
2294 // delta to glb result
2296 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2297 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2298 if (compLoc instanceof DeltaLocation) {
2299 if (glbCompLoc.equals(compLoc)) {
2300 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2309 System.out.println("GLB=" + glbCompLoc);
2314 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
2316 SSJavaLattice<String> lattice = null;
2318 if (d instanceof ClassDescriptor) {
2319 lattice = ssjava.getCd2lattice().get(d);
2320 } else if (d instanceof MethodDescriptor) {
2321 if (ssjava.getMd2lattice().containsKey(d)) {
2322 lattice = ssjava.getMd2lattice().get(d);
2324 // use default lattice for the method
2325 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
2332 static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
2334 Descriptor d1 = loc1.getDescriptor();
2335 Descriptor d2 = loc2.getDescriptor();
2337 Descriptor descriptor;
2339 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
2341 if (d1.equals(d2)) {
2344 // identifying which one is parent class
2345 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
2346 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
2348 if (d1 == null && d2 == null) {
2349 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2350 + " because they are not comparable at " + msg);
2351 } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
2353 } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
2356 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2357 + " because they are not comparable at " + msg);
2361 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
2363 if (d1.equals(d2)) {
2367 // identifying which one is parent class
2368 MethodDescriptor md1 = (MethodDescriptor) d1;
2369 MethodDescriptor md2 = (MethodDescriptor) d2;
2371 if (!md1.matches(md2)) {
2372 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2373 + " because they are not comparable at " + msg);
2376 Set<Descriptor> d1SubClassesSet =
2377 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
2378 Set<Descriptor> d2SubClassesSet =
2379 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
2381 if (d1 == null && d2 == null) {
2382 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2383 + " because they are not comparable at " + msg);
2384 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
2386 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
2389 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2390 + " because they are not comparable at " + msg);
2395 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2396 + " because they are not comparable at " + msg);
2405 class ComparisonResult {
2407 public static final int GREATER = 0;
2408 public static final int EQUAL = 1;
2409 public static final int LESS = 2;
2410 public static final int INCOMPARABLE = 3;
2417 class ReturnLocGenerator {
2419 public static final int PARAMISHIGHER = 0;
2420 public static final int PARAMISSAME = 1;
2421 public static final int IGNORE = 2;
2423 private Hashtable<Integer, Integer> paramIdx2paramType;
2425 private CompositeLocation declaredReturnLoc = null;
2427 public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2428 List<CompositeLocation> params, String msg) {
2430 CompositeLocation thisLoc = params.get(0);
2431 if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2432 // if the declared return location consists of THIS and field location,
2433 // return location for the caller's side has to have same field element
2434 this.declaredReturnLoc = returnLoc;
2436 // creating mappings
2437 paramIdx2paramType = new Hashtable<Integer, Integer>();
2438 for (int i = 0; i < params.size(); i++) {
2439 CompositeLocation param = params.get(i);
2440 int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2443 if (compareResult == ComparisonResult.GREATER) {
2445 } else if (compareResult == ComparisonResult.EQUAL) {
2450 paramIdx2paramType.put(new Integer(i), new Integer(type));
2456 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2458 if (declaredReturnLoc != null) {
2459 // when developer specify that the return value is [THIS,field]
2460 // needs to translate to the caller's location
2461 CompositeLocation callerLoc = new CompositeLocation();
2462 CompositeLocation callerBaseLocation = args.get(0);
2464 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2465 callerLoc.addLocation(callerBaseLocation.get(i));
2467 for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2468 callerLoc.addLocation(declaredReturnLoc.get(i));
2472 // compute the highest possible location in caller's side
2473 assert paramIdx2paramType.keySet().size() == args.size();
2475 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2476 for (int i = 0; i < args.size(); i++) {
2477 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2478 CompositeLocation argLoc = args.get(i);
2479 if (type == PARAMISHIGHER || type == PARAMISSAME) {
2480 // return loc is equal to or lower than param
2481 inputGLB.add(argLoc);
2485 // compute GLB of arguments subset that are same or higher than return
2487 if (inputGLB.isEmpty()) {
2488 if (args.size() == 0) {
2491 CompositeLocation rtr =
2492 new CompositeLocation(Location.createTopLocation(args.get(0).get(0).getDescriptor()));
2495 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");