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 // check if 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(trueLoc);
936 glbInputSet.add(falseLoc);
938 if (glbInputSet.size() == 1) {
941 return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
946 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
947 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
948 CompositeLocation constraint) {
950 ClassDescriptor cd = md.getClassDesc();
951 MethodDescriptor calleeMethodDesc = min.getMethod();
953 NameDescriptor baseName = min.getBaseName();
954 boolean isSystemout = false;
955 if (baseName != null) {
956 isSystemout = baseName.getSymbol().equals("System.out");
959 if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
960 && !ssjava.isTrustMethod(calleeMethodDesc) && !calleeMethodDesc.getModifiers().isNative()
963 CompositeLocation baseLocation = null;
964 if (min.getExpression() != null) {
966 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
967 new CompositeLocation(), constraint, false);
969 if (min.getMethod().isStatic()) {
970 String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
971 if (globalLocId == null) {
972 throw new Error("Method lattice does not define global variable location at "
973 + generateErrorMessage(md.getClassDesc(), min));
975 baseLocation = new CompositeLocation(new Location(md, globalLocId));
977 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
978 baseLocation = new CompositeLocation(new Location(md, thisLocId));
982 // System.out.println("\n#checkLocationFromMethodInvokeNode=" +
984 // + " baseLocation=" + baseLocation + " constraint=" + constraint);
986 // setup the location list of caller's arguments
987 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
989 // setup the location list of callee's parameters
990 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleeMethodDesc);
991 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
993 if (min.numArgs() > 0) {
994 if (!calleeMethodDesc.isStatic()) {
995 callerArgList.add(baseLocation);
997 for (int i = 0; i < min.numArgs(); i++) {
998 ExpressionNode en = min.getArg(i);
999 CompositeLocation callerArgLoc =
1000 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(),
1002 callerArgList.add(callerArgLoc);
1005 if (!calleeMethodDesc.isStatic()) {
1006 CompositeLocation calleeThisLoc =
1007 new CompositeLocation(new Location(calleeMethodDesc, calleeLattice.getThisLoc()));
1008 calleeParamList.add(calleeThisLoc);
1011 for (int i = 0; i < calleeMethodDesc.numParameters(); i++) {
1012 VarDescriptor calleevd = (VarDescriptor) calleeMethodDesc.getParameter(i);
1013 CompositeLocation calleeLoc = d2loc.get(calleevd);
1014 calleeParamList.add(calleeLoc);
1018 if (constraint != null) {
1019 // check whether the PC location is lower than one of the
1020 // argument locations. If it is lower, the callee has to have @PCLOC
1021 // annotation that declares the program counter that is higher than
1022 // corresponding parameter
1024 CompositeLocation calleePCLOC = ssjava.getPCLocation(calleeMethodDesc);
1026 for (int idx = 0; idx < callerArgList.size(); idx++) {
1027 CompositeLocation argLocation = callerArgList.get(idx);
1029 // if the PC location is lower than an argument location
1030 // then, need to check that the callee's the initial location for the PC is also lower
1031 // than the corresponding parameter location
1033 if (!argLocation.get(0).isTop()
1034 && CompositeLattice.compare(argLocation, constraint, true,
1035 generateErrorMessage(cd, min)) == ComparisonResult.LESS) {
1037 CompositeLocation paramLocation = calleeParamList.get(idx);
1039 int paramCompareResult =
1040 CompositeLattice.compare(paramLocation, calleePCLOC, true,
1041 generateErrorMessage(cd, min));
1042 // CompositeLattice.compare(calleePCLOC, paramLocation, true,
1043 // generateErrorMessage(cd, min));
1045 System.out.println("-CHECKPCLOC:");
1046 System.out.println("---ARG LOC="
1051 + CompositeLattice.compare(argLocation, constraint, true,
1052 generateErrorMessage(cd, min)));
1053 System.out.println("---PARAM LOC=" + paramLocation + " calleePCLOC=" + calleePCLOC
1054 + " paramCompareResult=" + paramCompareResult);
1056 if (!(paramLocation.get(0).equals(calleePCLOC.get(0)) && calleePCLOC.getSize() > 1)
1057 && paramCompareResult != ComparisonResult.LESS) {
1059 "The program counter location "
1061 + " is lower than the argument(idx="
1065 + ". Need to specify that the initial PC location of the callee, which is currently set to "
1066 + calleePCLOC + ", is lower than " + paramLocation + " in the method "
1067 + calleeMethodDesc.getSymbol() + ":" + min.getNumLine());
1076 checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1078 checkCallerArgumentLocationConstraints(md, nametable, min, baseLocation, constraint);
1080 if (!min.getMethod().getReturnType().isVoid()) {
1081 // If method has a return value, compute the highest possible return
1082 // location in the caller's perspective
1083 CompositeLocation ceilingLoc =
1084 computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
1086 if (ceilingLoc == null) {
1087 return new CompositeLocation(Location.createTopLocation(md));
1093 return new CompositeLocation(Location.createTopLocation(md));
1097 private CompositeLocation translateCallerLocToCalleeLoc(MethodDescriptor calleeMD,
1098 CompositeLocation calleeBaseLoc, CompositeLocation constraint) {
1100 CompositeLocation calleeConstraint = new CompositeLocation();
1102 // if (constraint.startsWith(calleeBaseLoc)) {
1103 // if the first part of constraint loc is matched with callee base loc
1104 Location thisLoc = new Location(calleeMD, ssjava.getMethodLattice(calleeMD).getThisLoc());
1105 calleeConstraint.addLocation(thisLoc);
1106 for (int i = calleeBaseLoc.getSize(); i < constraint.getSize(); i++) {
1107 calleeConstraint.addLocation(constraint.get(i));
1112 return calleeConstraint;
1115 private void checkCallerArgumentLocationConstraints(MethodDescriptor md, SymbolTable nametable,
1116 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1117 // if parameter location consists of THIS and FIELD location,
1118 // caller should pass an argument that is comparable to the declared
1119 // parameter location
1120 // and is not lower than the declared parameter location in the field
1123 MethodDescriptor calleemd = min.getMethod();
1125 if (calleemd.isStatic()) {
1129 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1130 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1132 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1133 Location calleeThisLoc = new Location(calleemd, calleeLattice.getThisLoc());
1135 for (int i = 0; i < min.numArgs(); i++) {
1136 ExpressionNode en = min.getArg(i);
1137 CompositeLocation callerArgLoc =
1138 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1140 callerArgList.add(callerArgLoc);
1143 // setup callee params set
1144 for (int i = 0; i < calleemd.numParameters(); i++) {
1145 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1146 CompositeLocation calleeLoc = d2loc.get(calleevd);
1147 calleeParamList.add(calleeLoc);
1150 String errorMsg = generateErrorMessage(md.getClassDesc(), min);
1152 // System.out.println("checkCallerArgumentLocationConstraints=" +
1153 // min.printNode(0));
1154 // System.out.println("base location=" + callerBaseLoc + " constraint=" +
1157 for (int i = 0; i < calleeParamList.size(); i++) {
1158 CompositeLocation calleeParamLoc = calleeParamList.get(i);
1159 if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
1161 // callee parameter location has field information
1162 CompositeLocation callerArgLoc = callerArgList.get(i);
1164 CompositeLocation paramLocation =
1165 translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
1167 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1168 if (constraint != null) {
1169 inputGLBSet.add(callerArgLoc);
1170 inputGLBSet.add(constraint);
1172 CompositeLattice.calculateGLB(inputGLBSet,
1173 generateErrorMessage(md.getClassDesc(), min));
1176 Location argLastLoc = callerArgLoc.get(callerArgLoc.getSize() - 1);
1177 Location paramLastLoc = paramLocation.get(paramLocation.getSize() - 1);
1179 if (argLastLoc.equals(paramLastLoc) && ssjava.isSharedLocation(argLastLoc)
1180 && ssjava.isSharedLocation(paramLastLoc)) {
1184 // if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
1185 if (CompositeLattice.compare(callerArgLoc, paramLocation, true, errorMsg) == ComparisonResult.LESS) {
1186 throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
1187 + "' should be higher than corresponding callee's parameter : " + paramLocation
1188 + " at " + errorMsg);
1196 private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
1197 CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
1199 CompositeLocation translate = new CompositeLocation();
1201 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
1202 translate.addLocation(callerBaseLocation.get(i));
1205 for (int i = 1; i < calleeParamLoc.getSize(); i++) {
1206 translate.addLocation(calleeParamLoc.get(i));
1209 // System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" +
1215 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
1216 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
1217 CompositeLocation constraint) {
1218 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
1220 // by default, method has a THIS parameter
1221 if (!min.getMethod().isStatic()) {
1222 argList.add(baseLocation);
1225 for (int i = 0; i < min.numArgs(); i++) {
1226 ExpressionNode en = min.getArg(i);
1227 CompositeLocation callerArg =
1228 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1230 argList.add(callerArg);
1233 // System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
1234 CompositeLocation ceilLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
1235 // System.out.println("## ReturnLocation=" + ceilLoc);
1241 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
1242 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1244 MethodDescriptor calleemd = min.getMethod();
1246 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1248 System.out.println("checkCalleeConstraints=" + calleemd + " calleeLattice.getThisLoc()="
1249 + calleeLattice.getThisLoc());
1251 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1252 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1254 if (min.numArgs() > 0) {
1255 // caller needs to guarantee that it passes arguments in regarding to
1256 // callee's hierarchy
1258 // setup caller args set
1259 // first, add caller's base(this) location
1260 if (!calleemd.isStatic())
1261 callerArgList.add(callerBaseLoc);
1262 // second, add caller's arguments
1263 for (int i = 0; i < min.numArgs(); i++) {
1264 ExpressionNode en = min.getArg(i);
1265 CompositeLocation callerArgLoc =
1266 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1268 callerArgList.add(callerArgLoc);
1271 // setup callee params set
1272 // first, add callee's this location
1273 if (!calleemd.isStatic()) {
1274 CompositeLocation calleeThisLoc =
1275 new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
1276 calleeParamList.add(calleeThisLoc);
1278 // second, add callee's parameters
1279 for (int i = 0; i < calleemd.numParameters(); i++) {
1280 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1281 CompositeLocation calleeLoc = d2loc.get(calleevd);
1282 // System.out.println("calleevd=" + calleevd + " loc=" + calleeLoc);
1283 calleeParamList.add(calleeLoc);
1286 // here, check if ordering relations among caller's args respect
1287 // ordering relations in-between callee's args
1288 CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1289 CompositeLocation calleeLoc1 = calleeParamList.get(i);
1290 CompositeLocation callerLoc1 = callerArgList.get(i);
1292 for (int j = 0; j < calleeParamList.size(); j++) {
1294 CompositeLocation calleeLoc2 = calleeParamList.get(j);
1295 CompositeLocation callerLoc2 = callerArgList.get(j);
1297 if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1298 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1302 // System.out.println("calleeLoc1=" + calleeLoc1);
1303 // System.out.println("calleeLoc2=" + calleeLoc2 +
1304 // "calleeParamList=" + calleeParamList);
1307 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1308 generateErrorMessage(md.getClassDesc(), min));
1309 // System.out.println("callerResult=" + callerResult);
1311 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1312 generateErrorMessage(md.getClassDesc(), min));
1313 // System.out.println("calleeResult=" + calleeResult);
1315 if (callerResult == ComparisonResult.EQUAL) {
1316 if (ssjava.isSharedLocation(callerLoc1.get(callerLoc1.getSize() - 1))
1317 && ssjava.isSharedLocation(callerLoc2.get(callerLoc2.getSize() - 1))) {
1318 // if both of them are shared locations, promote them to
1319 // "GREATER relation"
1320 callerResult = ComparisonResult.GREATER;
1324 if (calleeResult == ComparisonResult.GREATER
1325 && callerResult != ComparisonResult.GREATER) {
1326 // If calleeLoc1 is higher than calleeLoc2
1327 // then, caller should have same ordering relation in-bet
1328 // callerLoc1 & callerLoc2
1330 String paramName1, paramName2;
1332 if (!calleemd.isStatic()) {
1334 paramName1 = "'THIS'";
1336 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1339 paramName1 = "'parameter " + calleemd.getParamName(i) + "'";
1342 if (!calleemd.isStatic()) {
1343 if (j == 0 && !calleemd.isStatic()) {
1344 paramName2 = "'THIS'";
1346 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1349 paramName2 = "'parameter " + calleemd.getParamName(j) + "'";
1353 "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1354 + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1355 + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1366 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1367 SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1368 System.out.println("aan=" + aan.printNode(0) + " line#=" + aan.getNumLine());
1369 ClassDescriptor cd = md.getClassDesc();
1370 System.out.println("aan.getExpression()=" +aan.getExpression().getClass());
1371 CompositeLocation arrayLoc =
1372 checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1373 new CompositeLocation(), constraint, isLHS);
1374 System.out.println("HERE?");
1375 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1376 CompositeLocation indexLoc =
1377 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1379 // addTypeLocation(aan.getIndex().getType(), indexLoc);
1380 System.out.println("HERE2?");
1383 if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1384 throw new Error("Array index value is not higher than array location at "
1385 + generateErrorMessage(cd, aan));
1389 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1390 inputGLB.add(arrayLoc);
1391 inputGLB.add(indexLoc);
1392 System.out.println("arrayLoc=" + arrayLoc + " indexLoc=" + indexLoc);
1393 CompositeLocation comp =
1394 CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1395 System.out.println("---aan=" + aan.printNode(0) + " compLoc=" + comp);
1401 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1402 SymbolTable nametable, CreateObjectNode con) {
1404 ClassDescriptor cd = md.getClassDesc();
1406 CompositeLocation compLoc = new CompositeLocation();
1407 compLoc.addLocation(Location.createTopLocation(md));
1412 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1413 OpNode on, CompositeLocation constraint) {
1415 ClassDescriptor cd = md.getClassDesc();
1416 CompositeLocation leftLoc = new CompositeLocation();
1418 checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1419 // addTypeLocation(on.getLeft().getType(), leftLoc);
1421 CompositeLocation rightLoc = new CompositeLocation();
1422 if (on.getRight() != null) {
1424 checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1425 // addTypeLocation(on.getRight().getType(), rightLoc);
1428 System.out.println("\n# OP NODE=" + on.printNode(0));
1429 // System.out.println("# left loc=" + leftLoc + " from " +
1430 // on.getLeft().getClass());
1431 // if (on.getRight() != null) {
1432 // System.out.println("# right loc=" + rightLoc + " from " +
1433 // on.getRight().getClass());
1436 Operation op = on.getOp();
1438 switch (op.getOp()) {
1440 case Operation.UNARYPLUS:
1441 case Operation.UNARYMINUS:
1442 case Operation.LOGIC_NOT:
1446 case Operation.LOGIC_OR:
1447 case Operation.LOGIC_AND:
1448 case Operation.COMP:
1449 case Operation.BIT_OR:
1450 case Operation.BIT_XOR:
1451 case Operation.BIT_AND:
1452 case Operation.ISAVAILABLE:
1453 case Operation.EQUAL:
1454 case Operation.NOTEQUAL:
1461 case Operation.MULT:
1464 case Operation.LEFTSHIFT:
1465 case Operation.RIGHTSHIFT:
1466 case Operation.URIGHTSHIFT:
1468 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1469 inputSet.add(leftLoc);
1470 inputSet.add(rightLoc);
1471 CompositeLocation glbCompLoc =
1472 CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1476 throw new Error(op.toString());
1481 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1482 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1484 // literal value has the top location so that value can be flowed into any
1486 Location literalLoc = Location.createTopLocation(md);
1487 loc.addLocation(literalLoc);
1492 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1493 NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1495 // System.out.println("checkLocationFromNameNode nn=" + nn.printNode(0));
1496 NameDescriptor nd = nn.getName();
1497 if (nd.getBase() != null) {
1499 checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1501 String varname = nd.toString();
1502 if (varname.equals("this")) {
1504 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1505 String thisLocId = methodLattice.getThisLoc();
1506 if (thisLocId == null) {
1507 throw new Error("The location for 'this' is not defined at "
1508 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1510 Location locElement = new Location(md, thisLocId);
1511 loc.addLocation(locElement);
1516 Descriptor d = (Descriptor) nametable.get(varname);
1518 // CompositeLocation localLoc = null;
1519 if (d instanceof VarDescriptor) {
1520 VarDescriptor vd = (VarDescriptor) d;
1521 // localLoc = d2loc.get(vd);
1522 // the type of var descriptor has a composite location!
1523 loc = ((SSJavaType) vd.getType().getExtension()).getCompLoc().clone();
1524 } else if (d instanceof FieldDescriptor) {
1525 // the type of field descriptor has a location!
1526 FieldDescriptor fd = (FieldDescriptor) d;
1527 // System.out.println("fd=" + fd);
1528 if (fd.isStatic()) {
1530 // if it is 'static final', the location has TOP since no one can
1532 loc.addLocation(Location.createTopLocation(md));
1536 // if 'static', the location has pre-assigned global loc
1537 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1538 String globalLocId = localLattice.getGlobalLoc();
1539 if (globalLocId == null) {
1540 throw new Error("Global location element is not defined in the method " + md);
1542 Location globalLoc = new Location(md, globalLocId);
1543 System.out.println("static=" + globalLoc);
1544 loc.addLocation(globalLoc);
1547 // the location of field access starts from this, followed by field
1549 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1550 Location thisLoc = new Location(md, localLattice.getThisLoc());
1551 loc.addLocation(thisLoc);
1554 Location fieldLoc = (Location) fd.getType().getExtension();
1555 loc.addLocation(fieldLoc);
1556 } else if (d == null) {
1557 // access static field
1558 FieldDescriptor fd = nn.getField();
1560 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1561 String globalLocId = localLattice.getGlobalLoc();
1562 if (globalLocId == null) {
1563 throw new Error("Method lattice does not define global variable location at "
1564 + generateErrorMessage(md.getClassDesc(), nn));
1566 loc.addLocation(new Location(md, globalLocId));
1568 Location fieldLoc = (Location) fd.getType().getExtension();
1569 loc.addLocation(fieldLoc);
1579 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1580 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1581 CompositeLocation constraint) {
1583 ExpressionNode left = fan.getExpression();
1584 TypeDescriptor ltd = left.getType();
1586 FieldDescriptor fd = fan.getField();
1588 String varName = null;
1589 if (left.kind() == Kind.NameNode) {
1590 NameDescriptor nd = ((NameNode) left).getName();
1591 varName = nd.toString();
1594 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1595 // using a class name directly or access using this
1596 if (fd.isStatic() && fd.isFinal()) {
1597 loc.addLocation(Location.createTopLocation(md));
1602 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1603 if (left instanceof ArrayAccessNode) {
1604 ArrayAccessNode aan = (ArrayAccessNode) left;
1605 CompositeLocation indexLoc =
1606 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), loc, constraint, false);
1607 inputGLB.add(indexLoc);
1610 loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1612 if (!left.getType().isPrimitive()) {
1614 if (!fd.getSymbol().equals("length")) {
1615 // array.length access, return the location of the array
1616 Location fieldLoc = getFieldLocation(fd);
1617 loc.addLocation(fieldLoc);
1623 loc = CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), fan));
1628 private Location getFieldLocation(FieldDescriptor fd) {
1630 // System.out.println("### getFieldLocation=" + fd);
1631 // System.out.println("### fd.getType().getExtension()=" +
1632 // fd.getType().getExtension());
1634 Location fieldLoc = (Location) fd.getType().getExtension();
1636 // handle the case that method annotation checking skips checking field
1638 if (fieldLoc == null) {
1639 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1646 private FieldDescriptor getFieldDescriptorFromExpressionNode(ExpressionNode en) {
1648 if (en.kind() == Kind.NameNode) {
1649 NameNode nn = (NameNode) en;
1650 if (nn.getField() != null) {
1651 return nn.getField();
1654 if (nn.getName() != null && nn.getName().getBase() != null) {
1655 return getFieldDescriptorFromExpressionNode(nn.getExpression());
1658 } else if (en.kind() == Kind.FieldAccessNode) {
1659 FieldAccessNode fan = (FieldAccessNode) en;
1660 return fan.getField();
1666 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1667 SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1669 System.out.println("\n\ncheckLocationFromAssignmentNode=" + an.printNode(0));
1671 ClassDescriptor cd = md.getClassDesc();
1673 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1675 boolean postinc = true;
1676 if (an.getOperation().getBaseOp() == null
1677 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1678 .getBaseOp().getOp() != Operation.POSTDEC))
1681 // if LHS is array access node, need to check if array index is higher
1682 // than array itself
1683 CompositeLocation destLocation =
1684 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1687 CompositeLocation rhsLocation;
1688 CompositeLocation srcLocation;
1692 checkOwnership(md, an, an.getSrc());
1695 checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1698 if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
1699 // if assignment contains OP+EQ operator, need to merge location types
1700 // of LHS & RHS into the RHS
1701 Set<CompositeLocation> srcGLBSet = new HashSet<CompositeLocation>();
1702 srcGLBSet.add(rhsLocation);
1703 srcGLBSet.add(destLocation);
1704 srcLocation = CompositeLattice.calculateGLB(srcGLBSet, generateErrorMessage(cd, an));
1706 srcLocation = rhsLocation;
1709 if (constraint != null) {
1711 if (!CompositeLattice.isGreaterThan(constraint, destLocation, generateErrorMessage(cd, an))) {
1712 throw new Error("The value flow from " + constraint + " to " + destLocation
1713 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1714 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1716 // inputGLBSet.add(srcLocation);
1717 // inputGLBSet.add(constraint);
1718 // srcLocation = CompositeLattice.calculateGLB(inputGLBSet,
1719 // generateErrorMessage(cd, an));
1722 System.out.println("src=" + srcLocation + " dest=" + destLocation + " const=" + constraint);
1724 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1726 String context = "";
1727 if (constraint != null) {
1728 context = " and the current context constraint is " + constraint;
1731 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1732 + " does not respect location hierarchy on the assignment " + an.printNode(0) + context
1733 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1736 if (srcLocation.equals(destLocation)) {
1737 // keep it for definitely written analysis
1738 Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1739 for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1740 FlatNode fn = (FlatNode) iterator.next();
1741 ssjava.addSameHeightWriteFlatNode(fn);
1749 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1752 if (constraint != null) {
1754 if (!CompositeLattice.isGreaterThan(constraint, destLocation, generateErrorMessage(cd, an))) {
1755 throw new Error("The value flow from " + constraint + " to " + destLocation
1756 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1757 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1759 // inputGLBSet.add(rhsLocation);
1760 // inputGLBSet.add(constraint);
1761 // srcLocation = CompositeLattice.calculateGLB(inputGLBSet,
1762 // generateErrorMessage(cd, an));
1763 srcLocation = rhsLocation;
1765 srcLocation = rhsLocation;
1768 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1770 if (srcLocation.equals(destLocation)) {
1771 throw new Error("Location " + srcLocation
1772 + " is not allowed to have the value flow that moves within the same location at '"
1773 + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1775 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1776 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1777 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1782 if (srcLocation.equals(destLocation)) {
1783 // keep it for definitely written analysis
1784 Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1785 for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1786 FlatNode fn = (FlatNode) iterator.next();
1787 ssjava.addSameHeightWriteFlatNode(fn);
1793 return destLocation;
1796 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1797 SymbolTable nametable, TreeNode n) {
1799 ClassDescriptor cd = md.getClassDesc();
1800 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1802 // currently enforce every variable to have corresponding location
1803 if (annotationVec.size() == 0) {
1804 throw new Error("Location is not assigned to variable '" + vd.getSymbol()
1805 + "' in the method '" + md + "' of the class " + cd.getSymbol() + " at "
1806 + generateErrorMessage(cd, n));
1809 int locDecCount = 0;
1810 for (int i = 0; i < annotationVec.size(); i++) {
1811 AnnotationDescriptor ad = annotationVec.elementAt(i);
1813 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1815 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1817 if (locDecCount > 1) {// variable can have at most one location
1818 throw new Error(vd.getSymbol() + " has more than one location declaration.");
1820 String locDec = ad.getValue(); // check if location is defined
1822 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1823 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1824 d2loc.put(vd, deltaLoc);
1825 addLocationType(vd.getType(), deltaLoc);
1827 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1829 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1830 if (ssjava.isSharedLocation(lastElement)) {
1831 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1834 d2loc.put(vd, compLoc);
1835 addLocationType(vd.getType(), compLoc);
1844 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1847 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1850 int beginIdx = dIdx + 6;
1851 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1852 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1855 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1856 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1861 private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1863 int idx = decl.indexOf(".");
1865 String className = decl.substring(0, idx);
1866 String fieldName = decl.substring(idx + 1);
1868 className.replaceAll(" ", "");
1869 fieldName.replaceAll(" ", "");
1871 Descriptor d = state.getClassSymbolTable().get(className);
1874 // System.out.println("state.getClassSymbolTable()=" +
1875 // state.getClassSymbolTable());
1876 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1880 assert (d instanceof ClassDescriptor);
1881 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1882 if (!lattice.containsKey(fieldName)) {
1883 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1884 + className + "' at " + msg);
1887 return new Location(d, fieldName);
1890 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1892 CompositeLocation compLoc = new CompositeLocation();
1894 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1895 List<String> locIdList = new ArrayList<String>();
1896 while (tokenizer.hasMoreTokens()) {
1897 String locId = tokenizer.nextToken();
1898 locIdList.add(locId);
1901 // at least,one location element needs to be here!
1902 assert (locIdList.size() > 0);
1904 // assume that loc with idx 0 comes from the local lattice
1905 // loc with idx 1 comes from the field lattice
1907 String localLocId = locIdList.get(0);
1908 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1909 Location localLoc = new Location(md, localLocId);
1910 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1911 throw new Error("Location " + localLocId
1912 + " is not defined in the local variable lattice at "
1913 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1915 compLoc.addLocation(localLoc);
1917 for (int i = 1; i < locIdList.size(); i++) {
1918 String locName = locIdList.get(i);
1921 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1922 compLoc.addLocation(fieldLoc);
1923 } catch (Exception e) {
1924 throw new Error("The location declaration '" + locName + "' is wrong at "
1925 + generateErrorMessage(md.getClassDesc(), n));
1933 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1934 VarDescriptor vd = dn.getVarDescriptor();
1935 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1938 private void checkDeclarationInClass(ClassDescriptor cd) {
1939 // Check to see that fields are okay
1940 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1941 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1943 if (!(fd.isFinal() && fd.isStatic())) {
1944 checkFieldDeclaration(cd, fd);
1946 // for static final, assign top location by default
1947 Location loc = Location.createTopLocation(cd);
1948 addLocationType(fd.getType(), loc);
1953 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1955 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1957 // currently enforce every field to have corresponding location
1958 if (annotationVec.size() == 0) {
1959 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1960 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1963 if (annotationVec.size() > 1) {
1964 // variable can have at most one location
1965 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1966 + " has more than one location.");
1969 AnnotationDescriptor ad = annotationVec.elementAt(0);
1970 Location loc = null;
1972 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1973 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1974 String locationID = ad.getValue();
1975 // check if location is defined
1976 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1977 if (lattice == null || (!lattice.containsKey(locationID))) {
1978 throw new Error("Location " + locationID
1979 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1980 + cd.getSourceFileName() + ".");
1982 loc = new Location(cd, locationID);
1984 if (ssjava.isSharedLocation(loc)) {
1985 ssjava.mapSharedLocation2Descriptor(loc, fd);
1988 addLocationType(fd.getType(), loc);
1996 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1998 TypeExtension te = type.getExtension();
2001 ssType = (SSJavaType) te;
2002 ssType.setCompLoc(loc);
2004 ssType = new SSJavaType(loc);
2005 type.setExtension(ssType);
2010 private void addLocationType(TypeDescriptor type, Location loc) {
2012 type.setExtension(loc);
2016 static class CompositeLattice {
2018 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
2020 // System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" +
2022 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
2023 if (baseCompareResult == ComparisonResult.EQUAL) {
2024 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
2029 } else if (baseCompareResult == ComparisonResult.GREATER) {
2037 public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
2040 // System.out.println("compare=" + loc1 + " " + loc2);
2041 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
2043 if (baseCompareResult == ComparisonResult.EQUAL) {
2044 return compareDelta(loc1, loc2);
2046 return baseCompareResult;
2051 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
2053 int deltaCount1 = 0;
2054 int deltaCount2 = 0;
2055 if (dLoc1 instanceof DeltaLocation) {
2056 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
2059 if (dLoc2 instanceof DeltaLocation) {
2060 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
2062 if (deltaCount1 < deltaCount2) {
2063 return ComparisonResult.GREATER;
2064 } else if (deltaCount1 == deltaCount2) {
2065 return ComparisonResult.EQUAL;
2067 return ComparisonResult.LESS;
2072 private static int compareBaseLocationSet(CompositeLocation compLoc1,
2073 CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
2075 // if compLoc1 is greater than compLoc2, return true
2076 // else return false;
2078 // compare one by one in according to the order of the tuple
2080 for (int i = 0; i < compLoc1.getSize(); i++) {
2081 Location loc1 = compLoc1.get(i);
2082 if (i >= compLoc2.getSize()) {
2084 return ComparisonResult.INCOMPARABLE;
2086 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2087 + " because they are not comparable at " + msg);
2090 Location loc2 = compLoc2.get(i);
2092 Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
2093 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
2095 // check if the shared location is appeared only at the end of the
2096 // composite location
2097 if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2098 if (i != (compLoc1.getSize() - 1)) {
2099 throw new Error("The shared location " + loc1.getLocIdentifier()
2100 + " cannot be appeared in the middle of composite location at" + msg);
2104 if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
2105 if (i != (compLoc2.getSize() - 1)) {
2106 throw new Error("The shared location " + loc2.getLocIdentifier()
2107 + " cannot be appeared in the middle of composite location at " + msg);
2111 // if (!lattice1.equals(lattice2)) {
2112 // throw new Error("Failed to compare two locations of " + compLoc1 +
2113 // " and " + compLoc2
2114 // + " because they are not comparable at " + msg);
2117 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
2119 // check if the current location is the spinning location
2120 // note that the spinning location only can be appeared in the last
2121 // part of the composite location
2122 if (awareSharedLoc && numOfTie == compLoc1.getSize()
2123 && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2124 return ComparisonResult.GREATER;
2127 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
2128 return ComparisonResult.GREATER;
2130 return ComparisonResult.LESS;
2135 if (numOfTie == compLoc1.getSize()) {
2137 if (numOfTie != compLoc2.getSize()) {
2140 return ComparisonResult.INCOMPARABLE;
2142 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2143 + " because they are not comparable at " + msg);
2148 return ComparisonResult.EQUAL;
2151 return ComparisonResult.LESS;
2155 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
2157 System.out.println("Calculating GLB=" + inputSet);
2158 CompositeLocation glbCompLoc = new CompositeLocation();
2160 // calculate GLB of the first(priority) element
2161 Set<String> priorityLocIdentifierSet = new HashSet<String>();
2162 Descriptor priorityDescriptor = null;
2164 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
2165 new Hashtable<String, Set<CompositeLocation>>();
2166 // mapping from the priority loc ID to its full representation by the
2167 // composite location
2169 int maxTupleSize = 0;
2170 CompositeLocation maxCompLoc = null;
2172 Location prevPriorityLoc = null;
2173 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
2174 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2175 if (compLoc.getSize() > maxTupleSize) {
2176 maxTupleSize = compLoc.getSize();
2177 maxCompLoc = compLoc;
2179 Location priorityLoc = compLoc.get(0);
2180 String priorityLocId = priorityLoc.getLocIdentifier();
2181 priorityLocIdentifierSet.add(priorityLocId);
2183 if (locId2CompLocSet.containsKey(priorityLocId)) {
2184 locId2CompLocSet.get(priorityLocId).add(compLoc);
2186 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
2187 newSet.add(compLoc);
2188 locId2CompLocSet.put(priorityLocId, newSet);
2191 // check if priority location are coming from the same lattice
2192 if (priorityDescriptor == null) {
2193 priorityDescriptor = priorityLoc.getDescriptor();
2195 priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
2197 prevPriorityLoc = priorityLoc;
2198 // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
2199 // throw new Error("Failed to calculate GLB of " + inputSet
2200 // + " because they are from different lattices.");
2204 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
2205 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
2206 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
2207 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
2209 if (compSet == null) {
2210 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
2211 // mean that the result is already lower than <x1,y1> and <x2,y2>
2212 // assign TOP to the rest of the location elements
2214 // in this case, do not take care about delta
2215 // CompositeLocation inputComp = inputSet.iterator().next();
2216 for (int i = 1; i < maxTupleSize; i++) {
2217 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
2221 // here find out composite location that has a maximum length tuple
2222 // if we have three input set: [A], [A,B], [A,B,C]
2223 // maximum length tuple will be [A,B,C]
2225 CompositeLocation maxFromCompSet = null;
2226 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2227 CompositeLocation c = (CompositeLocation) iterator.next();
2228 if (c.getSize() > max) {
2234 if (compSet.size() == 1) {
2235 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
2236 CompositeLocation comp = compSet.iterator().next();
2237 for (int i = 1; i < comp.getSize(); i++) {
2238 glbCompLoc.addLocation(comp.get(i));
2241 // if input location corresponding to glb is a delta, need to apply
2242 // delta to glb result
2243 if (comp instanceof DeltaLocation) {
2244 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2248 // when GLB(x1,x2)==x1 and x2 : GLB case 1
2249 // if more than one location shares the same priority GLB
2250 // need to calculate the rest of GLB loc
2252 // setup input set starting from the second tuple item
2253 Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
2254 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2255 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2256 CompositeLocation innerCompLoc = new CompositeLocation();
2257 for (int idx = 1; idx < compLoc.getSize(); idx++) {
2258 innerCompLoc.addLocation(compLoc.get(idx));
2260 if (innerCompLoc.getSize() > 0) {
2261 innerGLBInput.add(innerCompLoc);
2265 if (innerGLBInput.size() > 0) {
2266 // System.out.println("######innerGLBInput=" + innerGLBInput);
2267 CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
2268 for (int idx = 0; idx < innerGLB.getSize(); idx++) {
2269 glbCompLoc.addLocation(innerGLB.get(idx));
2273 // if input location corresponding to glb is a delta, need to apply
2274 // delta to glb result
2276 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2277 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2278 if (compLoc instanceof DeltaLocation) {
2279 if (glbCompLoc.equals(compLoc)) {
2280 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2289 System.out.println("GLB=" + glbCompLoc);
2294 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
2296 SSJavaLattice<String> lattice = null;
2298 if (d instanceof ClassDescriptor) {
2299 lattice = ssjava.getCd2lattice().get(d);
2300 } else if (d instanceof MethodDescriptor) {
2301 if (ssjava.getMd2lattice().containsKey(d)) {
2302 lattice = ssjava.getMd2lattice().get(d);
2304 // use default lattice for the method
2305 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
2312 static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
2314 Descriptor d1 = loc1.getDescriptor();
2315 Descriptor d2 = loc2.getDescriptor();
2317 Descriptor descriptor;
2319 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
2321 if (d1.equals(d2)) {
2324 // identifying which one is parent class
2325 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
2326 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
2328 if (d1 == null && d2 == null) {
2329 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2330 + " because they are not comparable at " + msg);
2331 } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
2333 } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
2336 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2337 + " because they are not comparable at " + msg);
2341 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
2343 if (d1.equals(d2)) {
2347 // identifying which one is parent class
2348 MethodDescriptor md1 = (MethodDescriptor) d1;
2349 MethodDescriptor md2 = (MethodDescriptor) d2;
2351 if (!md1.matches(md2)) {
2352 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2353 + " because they are not comparable at " + msg);
2356 Set<Descriptor> d1SubClassesSet =
2357 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
2358 Set<Descriptor> d2SubClassesSet =
2359 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
2361 if (d1 == null && d2 == null) {
2362 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2363 + " because they are not comparable at " + msg);
2364 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
2366 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
2369 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2370 + " because they are not comparable at " + msg);
2375 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2376 + " because they are not comparable at " + msg);
2385 class ComparisonResult {
2387 public static final int GREATER = 0;
2388 public static final int EQUAL = 1;
2389 public static final int LESS = 2;
2390 public static final int INCOMPARABLE = 3;
2397 class ReturnLocGenerator {
2399 public static final int PARAMISHIGHER = 0;
2400 public static final int PARAMISSAME = 1;
2401 public static final int IGNORE = 2;
2403 private Hashtable<Integer, Integer> paramIdx2paramType;
2405 private CompositeLocation declaredReturnLoc = null;
2407 public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2408 List<CompositeLocation> params, String msg) {
2410 CompositeLocation thisLoc = params.get(0);
2411 if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2412 // if the declared return location consists of THIS and field location,
2413 // return location for the caller's side has to have same field element
2414 this.declaredReturnLoc = returnLoc;
2416 // creating mappings
2417 paramIdx2paramType = new Hashtable<Integer, Integer>();
2418 for (int i = 0; i < params.size(); i++) {
2419 CompositeLocation param = params.get(i);
2420 int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2423 if (compareResult == ComparisonResult.GREATER) {
2425 } else if (compareResult == ComparisonResult.EQUAL) {
2430 paramIdx2paramType.put(new Integer(i), new Integer(type));
2436 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2438 if (declaredReturnLoc != null) {
2439 // when developer specify that the return value is [THIS,field]
2440 // needs to translate to the caller's location
2441 CompositeLocation callerLoc = new CompositeLocation();
2442 CompositeLocation callerBaseLocation = args.get(0);
2444 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2445 callerLoc.addLocation(callerBaseLocation.get(i));
2447 for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2448 callerLoc.addLocation(declaredReturnLoc.get(i));
2452 // compute the highest possible location in caller's side
2453 assert paramIdx2paramType.keySet().size() == args.size();
2455 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2456 for (int i = 0; i < args.size(); i++) {
2457 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2458 CompositeLocation argLoc = args.get(i);
2459 if (type == PARAMISHIGHER || type == PARAMISSAME) {
2460 // return loc is equal to or lower than param
2461 inputGLB.add(argLoc);
2465 // compute GLB of arguments subset that are same or higher than return
2467 if (inputGLB.isEmpty()) {
2468 if (args.size() == 0) {
2471 CompositeLocation rtr =
2472 new CompositeLocation(Location.createTopLocation(args.get(0).get(0).getDescriptor()));
2475 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");