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()) && thisLocId == null) {
358 throw new Error("Method '" + md + "' does not have the definition of 'this' location at "
359 + md.getClassDesc().getSourceFileName());
361 CompositeLocation thisLoc = new CompositeLocation(new Location(md, thisLocId));
362 paramList.add(0, thisLoc);
363 md2ReturnLocGen.put(md, new ReturnLocGenerator(md2ReturnLoc.get(md), md, paramList, md
364 + " of " + cd.getSourceFileName()));
367 // fourth, check declarations inside of method
369 checkDeclarationInBlockNode(md, md.getParameterTable(), bn);
373 private void checkDeclarationInBlockNode(MethodDescriptor md, SymbolTable nametable, BlockNode bn) {
374 bn.getVarTable().setParent(nametable);
375 for (int i = 0; i < bn.size(); i++) {
376 BlockStatementNode bsn = bn.get(i);
377 checkDeclarationInBlockStatementNode(md, bn.getVarTable(), bsn);
381 private void checkDeclarationInBlockStatementNode(MethodDescriptor md, SymbolTable nametable,
382 BlockStatementNode bsn) {
384 switch (bsn.kind()) {
385 case Kind.SubBlockNode:
386 checkDeclarationInSubBlockNode(md, nametable, (SubBlockNode) bsn);
389 case Kind.DeclarationNode:
390 checkDeclarationNode(md, nametable, (DeclarationNode) bsn);
394 checkDeclarationInLoopNode(md, nametable, (LoopNode) bsn);
397 case Kind.IfStatementNode:
398 checkDeclarationInIfStatementNode(md, nametable, (IfStatementNode) bsn);
401 case Kind.SwitchStatementNode:
402 checkDeclarationInSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn);
405 case Kind.SynchronizedNode:
406 checkDeclarationInSynchronizedNode(md, nametable, (SynchronizedNode) bsn);
412 private void checkDeclarationInSynchronizedNode(MethodDescriptor md, SymbolTable nametable,
413 SynchronizedNode sbn) {
414 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
417 private void checkDeclarationInSwitchStatementNode(MethodDescriptor md, SymbolTable nametable,
418 SwitchStatementNode ssn) {
419 BlockNode sbn = ssn.getSwitchBody();
420 for (int i = 0; i < sbn.size(); i++) {
421 SwitchBlockNode node = (SwitchBlockNode) sbn.get(i);
422 checkDeclarationInBlockNode(md, nametable, node.getSwitchBlockStatement());
426 private void checkDeclarationInIfStatementNode(MethodDescriptor md, SymbolTable nametable,
427 IfStatementNode isn) {
428 checkDeclarationInBlockNode(md, nametable, isn.getTrueBlock());
429 if (isn.getFalseBlock() != null)
430 checkDeclarationInBlockNode(md, nametable, isn.getFalseBlock());
433 private void checkDeclarationInLoopNode(MethodDescriptor md, SymbolTable nametable, LoopNode ln) {
435 if (ln.getType() == LoopNode.FORLOOP) {
436 // check for loop case
437 ClassDescriptor cd = md.getClassDesc();
438 BlockNode bn = ln.getInitializer();
439 for (int i = 0; i < bn.size(); i++) {
440 BlockStatementNode bsn = bn.get(i);
441 checkDeclarationInBlockStatementNode(md, nametable, bsn);
446 checkDeclarationInBlockNode(md, nametable, ln.getBody());
449 private void checkMethodBody(ClassDescriptor cd, MethodDescriptor md,
450 CompositeLocation constraints) {
451 BlockNode bn = state.getMethodBody(md);
452 checkLocationFromBlockNode(md, md.getParameterTable(), bn, constraints);
455 private String generateErrorMessage(ClassDescriptor cd, TreeNode tn) {
457 return cd.getSourceFileName() + "::" + tn.getNumLine();
459 return cd.getSourceFileName();
464 private CompositeLocation checkLocationFromBlockNode(MethodDescriptor md, SymbolTable nametable,
465 BlockNode bn, CompositeLocation constraint) {
467 bn.getVarTable().setParent(nametable);
468 for (int i = 0; i < bn.size(); i++) {
469 BlockStatementNode bsn = bn.get(i);
470 checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
472 return new CompositeLocation();
476 private CompositeLocation checkLocationFromBlockStatementNode(MethodDescriptor md,
477 SymbolTable nametable, BlockStatementNode bsn, CompositeLocation constraint) {
479 CompositeLocation compLoc = null;
480 switch (bsn.kind()) {
481 case Kind.BlockExpressionNode:
483 checkLocationFromBlockExpressionNode(md, nametable, (BlockExpressionNode) bsn, constraint);
486 case Kind.DeclarationNode:
487 compLoc = checkLocationFromDeclarationNode(md, nametable, (DeclarationNode) bsn, constraint);
490 case Kind.IfStatementNode:
491 compLoc = checkLocationFromIfStatementNode(md, nametable, (IfStatementNode) bsn, constraint);
495 compLoc = checkLocationFromLoopNode(md, nametable, (LoopNode) bsn, constraint);
498 case Kind.ReturnNode:
499 compLoc = checkLocationFromReturnNode(md, nametable, (ReturnNode) bsn, constraint);
502 case Kind.SubBlockNode:
503 compLoc = checkLocationFromSubBlockNode(md, nametable, (SubBlockNode) bsn, constraint);
506 case Kind.ContinueBreakNode:
507 compLoc = new CompositeLocation();
510 case Kind.SwitchStatementNode:
512 checkLocationFromSwitchStatementNode(md, nametable, (SwitchStatementNode) bsn, constraint);
518 private CompositeLocation checkLocationFromSwitchStatementNode(MethodDescriptor md,
519 SymbolTable nametable, SwitchStatementNode ssn, CompositeLocation constraint) {
521 ClassDescriptor cd = md.getClassDesc();
522 CompositeLocation condLoc =
523 checkLocationFromExpressionNode(md, nametable, ssn.getCondition(), new CompositeLocation(),
525 BlockNode sbn = ssn.getSwitchBody();
527 constraint = generateNewConstraint(constraint, condLoc);
529 for (int i = 0; i < sbn.size(); i++) {
530 checkLocationFromSwitchBlockNode(md, nametable, (SwitchBlockNode) sbn.get(i), constraint);
532 return new CompositeLocation();
535 private CompositeLocation checkLocationFromSwitchBlockNode(MethodDescriptor md,
536 SymbolTable nametable, SwitchBlockNode sbn, CompositeLocation constraint) {
538 CompositeLocation blockLoc =
539 checkLocationFromBlockNode(md, nametable, sbn.getSwitchBlockStatement(), constraint);
545 private CompositeLocation checkLocationFromReturnNode(MethodDescriptor md, SymbolTable nametable,
546 ReturnNode rn, CompositeLocation constraint) {
548 ExpressionNode returnExp = rn.getReturnExpression();
550 CompositeLocation declaredReturnLoc = md2ReturnLoc.get(md);
552 CompositeLocation returnValueLoc;
553 if (returnExp != null) {
555 checkLocationFromExpressionNode(md, nametable, returnExp, new CompositeLocation(),
558 // System.out.println("# RETURN VALUE LOC=" + returnValueLoc +
559 // " with constraint=" + constraint);
561 // TODO: do we need to check here?
562 // if this return statement is inside branch, return value has an implicit
563 // flow from conditional location
564 // if (constraint != null) {
565 // Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
566 // inputGLB.add(returnValueLoc);
567 // inputGLB.add(constraint);
569 // CompositeLattice.calculateGLB(inputGLB,
570 // generateErrorMessage(md.getClassDesc(), rn));
573 if (constraint != null) {
575 // Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
576 // inputGLB.add(returnValueLoc);
577 // inputGLB.add(constraint);
579 // CompositeLattice.calculateGLB(inputGLB,
580 // generateErrorMessage(md.getClassDesc(), rn));
582 // if (!returnValueLoc.get(returnValueLoc.getSize() - 1).isTop()) {
583 // if (!CompositeLattice.isGreaterThan(constraint, returnValueLoc,
584 // generateErrorMessage(md.getClassDesc(), rn))) {
585 // System.out.println("returnValueLoc.get(returnValueLoc.getSize() - 1).isTop()="
586 // + returnValueLoc.get(returnValueLoc.getSize() - 1).isTop());
587 // throw new Error("The value flow from " + constraint + " to " +
589 // + " does not respect location hierarchy on the assignment " +
591 // + " at " + md.getClassDesc().getSourceFileName() + "::" +
596 if (!CompositeLattice.isGreaterThan(constraint, declaredReturnLoc,
597 generateErrorMessage(md.getClassDesc(), rn))) {
598 throw new Error("The value flow from " + constraint + " to " + declaredReturnLoc
599 + " does not respect location hierarchy on the assignment " + rn.printNode(0)
600 + " at " + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
605 // check if return value is equal or higher than RETRUNLOC of method
606 // declaration annotation
609 CompositeLattice.compare(returnValueLoc, declaredReturnLoc, false,
610 generateErrorMessage(md.getClassDesc(), rn));
612 if (compareResult == ComparisonResult.LESS || compareResult == ComparisonResult.INCOMPARABLE) {
614 "Return value location is not equal or higher than the declaraed return location at "
615 + md.getClassDesc().getSourceFileName() + "::" + rn.getNumLine());
619 return new CompositeLocation();
622 private boolean hasOnlyLiteralValue(ExpressionNode en) {
623 if (en.kind() == Kind.LiteralNode) {
630 private CompositeLocation checkLocationFromLoopNode(MethodDescriptor md, SymbolTable nametable,
631 LoopNode ln, CompositeLocation constraint) {
633 ClassDescriptor cd = md.getClassDesc();
634 if (ln.getType() == LoopNode.WHILELOOP || ln.getType() == LoopNode.DOWHILELOOP) {
636 CompositeLocation condLoc =
637 checkLocationFromExpressionNode(md, nametable, ln.getCondition(),
638 new CompositeLocation(), constraint, false);
639 // addLocationType(ln.getCondition().getType(), (condLoc));
641 constraint = generateNewConstraint(constraint, condLoc);
642 checkLocationFromBlockNode(md, nametable, ln.getBody(), constraint);
644 return new CompositeLocation();
647 // check 'for loop' case
648 BlockNode bn = ln.getInitializer();
649 bn.getVarTable().setParent(nametable);
650 // need to check initialization node
651 // checkLocationFromBlockNode(md, bn.getVarTable(), bn, constraint);
652 for (int i = 0; i < bn.size(); i++) {
653 BlockStatementNode bsn = bn.get(i);
654 checkLocationFromBlockStatementNode(md, bn.getVarTable(), bsn, constraint);
657 // calculate glb location of condition and update statements
658 CompositeLocation condLoc =
659 checkLocationFromExpressionNode(md, bn.getVarTable(), ln.getCondition(),
660 new CompositeLocation(), constraint, false);
661 // addLocationType(ln.getCondition().getType(), condLoc);
663 constraint = generateNewConstraint(constraint, condLoc);
665 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getUpdate(), constraint);
666 checkLocationFromBlockNode(md, bn.getVarTable(), ln.getBody(), constraint);
668 return new CompositeLocation();
674 private CompositeLocation checkLocationFromSubBlockNode(MethodDescriptor md,
675 SymbolTable nametable, SubBlockNode sbn, CompositeLocation constraint) {
676 CompositeLocation compLoc =
677 checkLocationFromBlockNode(md, nametable, sbn.getBlockNode(), constraint);
681 private CompositeLocation generateNewConstraint(CompositeLocation currentCon,
682 CompositeLocation newCon) {
684 if (currentCon == null) {
687 // compute GLB of current constraint and new constraint
688 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
689 inputSet.add(currentCon);
690 inputSet.add(newCon);
691 return CompositeLattice.calculateGLB(inputSet, "");
696 private CompositeLocation checkLocationFromIfStatementNode(MethodDescriptor md,
697 SymbolTable nametable, IfStatementNode isn, CompositeLocation constraint) {
699 CompositeLocation condLoc =
700 checkLocationFromExpressionNode(md, nametable, isn.getCondition(), new CompositeLocation(),
703 // addLocationType(isn.getCondition().getType(), condLoc);
704 constraint = generateNewConstraint(constraint, condLoc);
705 checkLocationFromBlockNode(md, nametable, isn.getTrueBlock(), constraint);
707 if (isn.getFalseBlock() != null) {
708 checkLocationFromBlockNode(md, nametable, isn.getFalseBlock(), constraint);
711 return new CompositeLocation();
714 private void checkOwnership(MethodDescriptor md, TreeNode tn, ExpressionNode srcExpNode) {
716 if (srcExpNode.kind() == Kind.NameNode || srcExpNode.kind() == Kind.FieldAccessNode) {
717 if (srcExpNode.getType().isPtr() && !srcExpNode.getType().isNull()) {
718 // first, check the linear type
719 // RHS reference should be owned by the current method
720 FieldDescriptor fd = getFieldDescriptorFromExpressionNode(srcExpNode);
724 isOwned = ((SSJavaType) srcExpNode.getType().getExtension()).isOwned();
727 isOwned = ssjava.isOwnedByMethod(md, fd);
731 "It is not allowed to create the reference alias from the reference not owned by the method at "
732 + generateErrorMessage(md.getClassDesc(), tn));
740 private CompositeLocation checkLocationFromDeclarationNode(MethodDescriptor md,
741 SymbolTable nametable, DeclarationNode dn, CompositeLocation constraint) {
743 VarDescriptor vd = dn.getVarDescriptor();
745 CompositeLocation destLoc = d2loc.get(vd);
747 if (dn.getExpression() != null) {
749 checkOwnership(md, dn, dn.getExpression());
751 CompositeLocation expressionLoc =
752 checkLocationFromExpressionNode(md, nametable, dn.getExpression(),
753 new CompositeLocation(), constraint, false);
754 // addTypeLocation(dn.getExpression().getType(), expressionLoc);
756 if (expressionLoc != null) {
758 // checking location order
759 if (!CompositeLattice.isGreaterThan(expressionLoc, destLoc,
760 generateErrorMessage(md.getClassDesc(), dn))) {
761 throw new Error("The value flow from " + expressionLoc + " to " + destLoc
762 + " does not respect location hierarchy on the assignment " + dn.printNode(0)
763 + " at " + md.getClassDesc().getSourceFileName() + "::" + dn.getNumLine());
766 return expressionLoc;
770 return new CompositeLocation();
776 private void checkDeclarationInSubBlockNode(MethodDescriptor md, SymbolTable nametable,
778 checkDeclarationInBlockNode(md, nametable, sbn.getBlockNode());
781 private CompositeLocation checkLocationFromBlockExpressionNode(MethodDescriptor md,
782 SymbolTable nametable, BlockExpressionNode ben, CompositeLocation constraint) {
784 CompositeLocation compLoc =
785 checkLocationFromExpressionNode(md, nametable, ben.getExpression(), null, constraint, false);
786 // addTypeLocation(ben.getExpression().getType(), compLoc);
790 private CompositeLocation checkLocationFromExpressionNode(MethodDescriptor md,
791 SymbolTable nametable, ExpressionNode en, CompositeLocation loc,
792 CompositeLocation constraint, boolean isLHS) {
794 CompositeLocation compLoc = null;
797 case Kind.AssignmentNode:
799 checkLocationFromAssignmentNode(md, nametable, (AssignmentNode) en, loc, constraint);
802 case Kind.FieldAccessNode:
804 checkLocationFromFieldAccessNode(md, nametable, (FieldAccessNode) en, loc, constraint);
808 compLoc = checkLocationFromNameNode(md, nametable, (NameNode) en, loc, constraint);
812 compLoc = checkLocationFromOpNode(md, nametable, (OpNode) en, constraint);
815 case Kind.CreateObjectNode:
816 compLoc = checkLocationFromCreateObjectNode(md, nametable, (CreateObjectNode) en);
819 case Kind.ArrayAccessNode:
821 checkLocationFromArrayAccessNode(md, nametable, (ArrayAccessNode) en, constraint, isLHS);
824 case Kind.LiteralNode:
825 compLoc = checkLocationFromLiteralNode(md, nametable, (LiteralNode) en, loc);
828 case Kind.MethodInvokeNode:
830 checkLocationFromMethodInvokeNode(md, nametable, (MethodInvokeNode) en, loc, constraint);
833 case Kind.TertiaryNode:
834 compLoc = checkLocationFromTertiaryNode(md, nametable, (TertiaryNode) en, constraint);
838 compLoc = checkLocationFromCastNode(md, nametable, (CastNode) en, constraint);
841 // case Kind.InstanceOfNode:
842 // checkInstanceOfNode(md, nametable, (InstanceOfNode) en, td);
845 // case Kind.ArrayInitializerNode:
846 // checkArrayInitializerNode(md, nametable, (ArrayInitializerNode) en,
850 // case Kind.ClassTypeNode:
851 // checkClassTypeNode(md, nametable, (ClassTypeNode) en, td);
854 // case Kind.OffsetNode:
855 // checkOffsetNode(md, nametable, (OffsetNode)en, td);
862 // addTypeLocation(en.getType(), compLoc);
867 private CompositeLocation checkLocationFromCastNode(MethodDescriptor md, SymbolTable nametable,
868 CastNode cn, CompositeLocation constraint) {
870 ExpressionNode en = cn.getExpression();
871 return checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
876 private CompositeLocation checkLocationFromTertiaryNode(MethodDescriptor md,
877 SymbolTable nametable, TertiaryNode tn, CompositeLocation constraint) {
878 ClassDescriptor cd = md.getClassDesc();
880 CompositeLocation condLoc =
881 checkLocationFromExpressionNode(md, nametable, tn.getCond(), new CompositeLocation(),
883 // addLocationType(tn.getCond().getType(), condLoc);
884 CompositeLocation trueLoc =
885 checkLocationFromExpressionNode(md, nametable, tn.getTrueExpr(), new CompositeLocation(),
887 // addLocationType(tn.getTrueExpr().getType(), trueLoc);
888 CompositeLocation falseLoc =
889 checkLocationFromExpressionNode(md, nametable, tn.getFalseExpr(), new CompositeLocation(),
891 // addLocationType(tn.getFalseExpr().getType(), falseLoc);
893 // locations from true/false branches can be TOP when there are only literal
895 // in this case, we don't need to check flow down rule!
897 // System.out.println("\n#tertiary cond=" + tn.getCond().printNode(0) +
898 // " Loc=" + condLoc);
899 // System.out.println("# true=" + tn.getTrueExpr().printNode(0) + " Loc=" +
901 // System.out.println("# false=" + tn.getFalseExpr().printNode(0) + " Loc="
904 // check if condLoc is higher than trueLoc & falseLoc
905 if (!trueLoc.get(0).isTop()
906 && !CompositeLattice.isGreaterThan(condLoc, trueLoc, generateErrorMessage(cd, tn))) {
908 "The location of the condition expression is lower than the true expression at "
909 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
912 if (!falseLoc.get(0).isTop()
913 && !CompositeLattice.isGreaterThan(condLoc, falseLoc,
914 generateErrorMessage(cd, tn.getCond()))) {
916 "The location of the condition expression is lower than the false expression at "
917 + cd.getSourceFileName() + ":" + tn.getCond().getNumLine());
920 // then, return glb of trueLoc & falseLoc
921 Set<CompositeLocation> glbInputSet = new HashSet<CompositeLocation>();
922 glbInputSet.add(trueLoc);
923 glbInputSet.add(falseLoc);
925 if (glbInputSet.size() == 1) {
928 return CompositeLattice.calculateGLB(glbInputSet, generateErrorMessage(cd, tn));
933 private CompositeLocation checkLocationFromMethodInvokeNode(MethodDescriptor md,
934 SymbolTable nametable, MethodInvokeNode min, CompositeLocation loc,
935 CompositeLocation constraint) {
937 ClassDescriptor cd = md.getClassDesc();
938 MethodDescriptor calleeMethodDesc = min.getMethod();
940 NameDescriptor baseName = min.getBaseName();
941 boolean isSystemout = false;
942 if (baseName != null) {
943 isSystemout = baseName.getSymbol().equals("System.out");
946 if (!ssjava.isSSJavaUtil(calleeMethodDesc.getClassDesc())
947 && !ssjava.isTrustMethod(calleeMethodDesc) && !calleeMethodDesc.getModifiers().isNative()
950 CompositeLocation baseLocation = null;
951 if (min.getExpression() != null) {
953 checkLocationFromExpressionNode(md, nametable, min.getExpression(),
954 new CompositeLocation(), constraint, false);
956 if (min.getMethod().isStatic()) {
957 String globalLocId = ssjava.getMethodLattice(md).getGlobalLoc();
958 if (globalLocId == null) {
959 throw new Error("Method lattice does not define global variable location at "
960 + generateErrorMessage(md.getClassDesc(), min));
962 baseLocation = new CompositeLocation(new Location(md, globalLocId));
964 String thisLocId = ssjava.getMethodLattice(md).getThisLoc();
965 baseLocation = new CompositeLocation(new Location(md, thisLocId));
969 // System.out.println("\n#checkLocationFromMethodInvokeNode=" +
971 // + " baseLocation=" + baseLocation + " constraint=" + constraint);
973 // setup the location list of caller's arguments
974 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
976 // setup the location list of callee's parameters
977 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleeMethodDesc);
978 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
980 if (min.numArgs() > 0) {
981 if (!calleeMethodDesc.isStatic()) {
982 callerArgList.add(baseLocation);
984 for (int i = 0; i < min.numArgs(); i++) {
985 ExpressionNode en = min.getArg(i);
986 CompositeLocation callerArgLoc =
987 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(),
989 callerArgList.add(callerArgLoc);
992 if (!calleeMethodDesc.isStatic()) {
993 CompositeLocation calleeThisLoc =
994 new CompositeLocation(new Location(calleeMethodDesc, calleeLattice.getThisLoc()));
995 calleeParamList.add(calleeThisLoc);
998 for (int i = 0; i < calleeMethodDesc.numParameters(); i++) {
999 VarDescriptor calleevd = (VarDescriptor) calleeMethodDesc.getParameter(i);
1000 CompositeLocation calleeLoc = d2loc.get(calleevd);
1001 calleeParamList.add(calleeLoc);
1005 if (constraint != null) {
1006 // check whether the PC location is lower than one of the
1007 // argument locations. If it is lower, the callee has to have @PCLOC
1008 // annotation that declares the program counter that is higher than
1009 // corresponding parameter
1011 CompositeLocation calleePCLOC = ssjava.getPCLocation(calleeMethodDesc);
1013 for (int idx = 0; idx < callerArgList.size(); idx++) {
1014 CompositeLocation argLocation = callerArgList.get(idx);
1016 // need to check that param is higher than PCLOC
1017 if (!argLocation.get(0).isTop()
1018 && CompositeLattice.compare(argLocation, constraint, true,
1019 generateErrorMessage(cd, min)) == ComparisonResult.GREATER) {
1021 CompositeLocation paramLocation = calleeParamList.get(idx);
1023 int paramCompareResult =
1024 CompositeLattice.compare(calleePCLOC, paramLocation, true,
1025 generateErrorMessage(cd, min));
1027 if (paramCompareResult == ComparisonResult.GREATER) {
1029 "The program counter location "
1031 + " is lower than the argument(idx="
1035 + ". Need to specify that the initial PC location of the callee, which is currently set to "
1036 + calleePCLOC + ", is lower than " + paramLocation + " in the method "
1037 + calleeMethodDesc.getSymbol() + ":" + min.getNumLine());
1046 checkCalleeConstraints(md, nametable, min, baseLocation, constraint);
1048 // checkCallerArgumentLocationConstraints(md, nametable, min,
1049 // baseLocation, constraint);
1051 if (!min.getMethod().getReturnType().isVoid()) {
1052 // If method has a return value, compute the highest possible return
1053 // location in the caller's perspective
1054 CompositeLocation ceilingLoc =
1055 computeCeilingLocationForCaller(md, nametable, min, baseLocation, constraint);
1057 if (ceilingLoc == null) {
1058 return new CompositeLocation(Location.createTopLocation(md));
1064 return new CompositeLocation(Location.createTopLocation(md));
1068 private CompositeLocation translateCallerLocToCalleeLoc(MethodDescriptor calleeMD,
1069 CompositeLocation calleeBaseLoc, CompositeLocation constraint) {
1071 CompositeLocation calleeConstraint = new CompositeLocation();
1073 // if (constraint.startsWith(calleeBaseLoc)) {
1074 // if the first part of constraint loc is matched with callee base loc
1075 Location thisLoc = new Location(calleeMD, ssjava.getMethodLattice(calleeMD).getThisLoc());
1076 calleeConstraint.addLocation(thisLoc);
1077 for (int i = calleeBaseLoc.getSize(); i < constraint.getSize(); i++) {
1078 calleeConstraint.addLocation(constraint.get(i));
1083 return calleeConstraint;
1086 private void checkCallerArgumentLocationConstraints(MethodDescriptor md, SymbolTable nametable,
1087 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1088 // if parameter location consists of THIS and FIELD location,
1089 // caller should pass an argument that is comparable to the declared
1090 // parameter location
1091 // and is not lower than the declared parameter location in the field
1094 MethodDescriptor calleemd = min.getMethod();
1096 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1097 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1099 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1100 Location calleeThisLoc = new Location(calleemd, calleeLattice.getThisLoc());
1102 for (int i = 0; i < min.numArgs(); i++) {
1103 ExpressionNode en = min.getArg(i);
1104 CompositeLocation callerArgLoc =
1105 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1107 callerArgList.add(callerArgLoc);
1110 // setup callee params set
1111 for (int i = 0; i < calleemd.numParameters(); i++) {
1112 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1113 CompositeLocation calleeLoc = d2loc.get(calleevd);
1114 calleeParamList.add(calleeLoc);
1117 String errorMsg = generateErrorMessage(md.getClassDesc(), min);
1119 // System.out.println("checkCallerArgumentLocationConstraints=" +
1120 // min.printNode(0));
1121 // System.out.println("base location=" + callerBaseLoc + " constraint=" +
1124 for (int i = 0; i < calleeParamList.size(); i++) {
1125 CompositeLocation calleeParamLoc = calleeParamList.get(i);
1126 if (calleeParamLoc.get(0).equals(calleeThisLoc) && calleeParamLoc.getSize() > 1) {
1128 // callee parameter location has field information
1129 CompositeLocation callerArgLoc = callerArgList.get(i);
1131 CompositeLocation paramLocation =
1132 translateCalleeParamLocToCaller(md, calleeParamLoc, callerBaseLoc, errorMsg);
1134 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1135 if (constraint != null) {
1136 inputGLBSet.add(callerArgLoc);
1137 inputGLBSet.add(constraint);
1139 CompositeLattice.calculateGLB(inputGLBSet,
1140 generateErrorMessage(md.getClassDesc(), min));
1143 if (!CompositeLattice.isGreaterThan(callerArgLoc, paramLocation, errorMsg)) {
1144 throw new Error("Caller argument '" + min.getArg(i).printNode(0) + " : " + callerArgLoc
1145 + "' should be higher than corresponding callee's parameter : " + paramLocation
1146 + " at " + errorMsg);
1154 private CompositeLocation translateCalleeParamLocToCaller(MethodDescriptor md,
1155 CompositeLocation calleeParamLoc, CompositeLocation callerBaseLocation, String errorMsg) {
1157 CompositeLocation translate = new CompositeLocation();
1159 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
1160 translate.addLocation(callerBaseLocation.get(i));
1163 for (int i = 1; i < calleeParamLoc.getSize(); i++) {
1164 translate.addLocation(calleeParamLoc.get(i));
1167 // System.out.println("TRANSLATED=" + translate + " from calleeParamLoc=" +
1173 private CompositeLocation computeCeilingLocationForCaller(MethodDescriptor md,
1174 SymbolTable nametable, MethodInvokeNode min, CompositeLocation baseLocation,
1175 CompositeLocation constraint) {
1176 List<CompositeLocation> argList = new ArrayList<CompositeLocation>();
1178 // by default, method has a THIS parameter
1179 if (!min.getMethod().isStatic()) {
1180 argList.add(baseLocation);
1183 for (int i = 0; i < min.numArgs(); i++) {
1184 ExpressionNode en = min.getArg(i);
1185 CompositeLocation callerArg =
1186 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1188 argList.add(callerArg);
1191 System.out.println("\n## computeReturnLocation=" + min.getMethod() + " argList=" + argList);
1192 CompositeLocation ceilLoc = md2ReturnLocGen.get(min.getMethod()).computeReturnLocation(argList);
1193 System.out.println("## ReturnLocation=" + ceilLoc);
1199 private void checkCalleeConstraints(MethodDescriptor md, SymbolTable nametable,
1200 MethodInvokeNode min, CompositeLocation callerBaseLoc, CompositeLocation constraint) {
1202 MethodDescriptor calleemd = min.getMethod();
1204 MethodLattice<String> calleeLattice = ssjava.getMethodLattice(calleemd);
1206 System.out.println("checkCalleeConstraints=" + calleemd + " calleeLattice.getThisLoc()="
1207 + calleeLattice.getThisLoc());
1209 CompositeLocation calleeThisLoc =
1210 new CompositeLocation(new Location(calleemd, calleeLattice.getThisLoc()));
1212 List<CompositeLocation> callerArgList = new ArrayList<CompositeLocation>();
1213 List<CompositeLocation> calleeParamList = new ArrayList<CompositeLocation>();
1215 if (min.numArgs() > 0) {
1216 // caller needs to guarantee that it passes arguments in regarding to
1217 // callee's hierarchy
1219 // setup caller args set
1220 // first, add caller's base(this) location
1221 if (!calleemd.isStatic())
1222 callerArgList.add(callerBaseLoc);
1223 // second, add caller's arguments
1224 for (int i = 0; i < min.numArgs(); i++) {
1225 ExpressionNode en = min.getArg(i);
1226 CompositeLocation callerArgLoc =
1227 checkLocationFromExpressionNode(md, nametable, en, new CompositeLocation(), constraint,
1229 callerArgList.add(callerArgLoc);
1232 // setup callee params set
1233 // first, add callee's this location
1234 if (!calleemd.isStatic())
1235 calleeParamList.add(calleeThisLoc);
1236 // second, add callee's parameters
1237 for (int i = 0; i < calleemd.numParameters(); i++) {
1238 VarDescriptor calleevd = (VarDescriptor) calleemd.getParameter(i);
1239 CompositeLocation calleeLoc = d2loc.get(calleevd);
1240 // System.out.println("calleevd=" + calleevd + " loc=" + calleeLoc);
1241 calleeParamList.add(calleeLoc);
1244 // here, check if ordering relations among caller's args respect
1245 // ordering relations in-between callee's args
1246 CHECK: for (int i = 0; i < calleeParamList.size(); i++) {
1247 CompositeLocation calleeLoc1 = calleeParamList.get(i);
1248 CompositeLocation callerLoc1 = callerArgList.get(i);
1250 for (int j = 0; j < calleeParamList.size(); j++) {
1252 CompositeLocation calleeLoc2 = calleeParamList.get(j);
1253 CompositeLocation callerLoc2 = callerArgList.get(j);
1255 if (callerLoc1.get(callerLoc1.getSize() - 1).isTop()
1256 || callerLoc2.get(callerLoc2.getSize() - 1).isTop()) {
1260 // System.out.println("calleeLoc1=" + calleeLoc1);
1261 // System.out.println("calleeLoc2=" + calleeLoc2 +
1262 // "calleeParamList=" + calleeParamList);
1265 CompositeLattice.compare(callerLoc1, callerLoc2, true,
1266 generateErrorMessage(md.getClassDesc(), min));
1267 // System.out.println("callerResult=" + callerResult);
1269 CompositeLattice.compare(calleeLoc1, calleeLoc2, true,
1270 generateErrorMessage(md.getClassDesc(), min));
1271 // System.out.println("calleeResult=" + calleeResult);
1273 if (callerResult == ComparisonResult.EQUAL) {
1274 if (ssjava.isSharedLocation(callerLoc1.get(callerLoc1.getSize() - 1))
1275 && ssjava.isSharedLocation(callerLoc2.get(callerLoc2.getSize() - 1))) {
1276 // if both of them are shared locations, promote them to
1277 // "GREATER relation"
1278 callerResult = ComparisonResult.GREATER;
1282 if (calleeResult == ComparisonResult.GREATER
1283 && callerResult != ComparisonResult.GREATER) {
1284 // If calleeLoc1 is higher than calleeLoc2
1285 // then, caller should have same ordering relation in-bet
1286 // callerLoc1 & callerLoc2
1288 String paramName1, paramName2;
1291 paramName1 = "'THIS'";
1293 paramName1 = "'parameter " + calleemd.getParamName(i - 1) + "'";
1297 paramName2 = "'THIS'";
1299 paramName2 = "'parameter " + calleemd.getParamName(j - 1) + "'";
1303 "Caller doesn't respect an ordering relation among method arguments: callee expects that "
1304 + paramName1 + " should be higher than " + paramName2 + " in " + calleemd
1305 + " at " + md.getClassDesc().getSourceFileName() + ":" + min.getNumLine());
1316 private CompositeLocation checkLocationFromArrayAccessNode(MethodDescriptor md,
1317 SymbolTable nametable, ArrayAccessNode aan, CompositeLocation constraint, boolean isLHS) {
1318 System.out.println("aan=" + aan.printNode(0) + " line#=" + aan.getNumLine());
1319 ClassDescriptor cd = md.getClassDesc();
1321 CompositeLocation arrayLoc =
1322 checkLocationFromExpressionNode(md, nametable, aan.getExpression(),
1323 new CompositeLocation(), constraint, isLHS);
1325 // addTypeLocation(aan.getExpression().getType(), arrayLoc);
1326 CompositeLocation indexLoc =
1327 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), new CompositeLocation(),
1329 // addTypeLocation(aan.getIndex().getType(), indexLoc);
1332 if (!CompositeLattice.isGreaterThan(indexLoc, arrayLoc, generateErrorMessage(cd, aan))) {
1333 throw new Error("Array index value is not higher than array location at "
1334 + generateErrorMessage(cd, aan));
1338 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1339 inputGLB.add(arrayLoc);
1340 inputGLB.add(indexLoc);
1341 return CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(cd, aan));
1346 private CompositeLocation checkLocationFromCreateObjectNode(MethodDescriptor md,
1347 SymbolTable nametable, CreateObjectNode con) {
1349 ClassDescriptor cd = md.getClassDesc();
1351 CompositeLocation compLoc = new CompositeLocation();
1352 compLoc.addLocation(Location.createTopLocation(md));
1357 private CompositeLocation checkLocationFromOpNode(MethodDescriptor md, SymbolTable nametable,
1358 OpNode on, CompositeLocation constraint) {
1360 ClassDescriptor cd = md.getClassDesc();
1361 CompositeLocation leftLoc = new CompositeLocation();
1363 checkLocationFromExpressionNode(md, nametable, on.getLeft(), leftLoc, constraint, false);
1364 // addTypeLocation(on.getLeft().getType(), leftLoc);
1366 CompositeLocation rightLoc = new CompositeLocation();
1367 if (on.getRight() != null) {
1369 checkLocationFromExpressionNode(md, nametable, on.getRight(), rightLoc, constraint, false);
1370 // addTypeLocation(on.getRight().getType(), rightLoc);
1373 // System.out.println("\n# OP NODE=" + on.printNode(0));
1374 // System.out.println("# left loc=" + leftLoc + " from " +
1375 // on.getLeft().getClass());
1376 // if (on.getRight() != null) {
1377 // System.out.println("# right loc=" + rightLoc + " from " +
1378 // on.getRight().getClass());
1381 Operation op = on.getOp();
1383 switch (op.getOp()) {
1385 case Operation.UNARYPLUS:
1386 case Operation.UNARYMINUS:
1387 case Operation.LOGIC_NOT:
1391 case Operation.LOGIC_OR:
1392 case Operation.LOGIC_AND:
1393 case Operation.COMP:
1394 case Operation.BIT_OR:
1395 case Operation.BIT_XOR:
1396 case Operation.BIT_AND:
1397 case Operation.ISAVAILABLE:
1398 case Operation.EQUAL:
1399 case Operation.NOTEQUAL:
1406 case Operation.MULT:
1409 case Operation.LEFTSHIFT:
1410 case Operation.RIGHTSHIFT:
1411 case Operation.URIGHTSHIFT:
1413 Set<CompositeLocation> inputSet = new HashSet<CompositeLocation>();
1414 inputSet.add(leftLoc);
1415 inputSet.add(rightLoc);
1416 CompositeLocation glbCompLoc =
1417 CompositeLattice.calculateGLB(inputSet, generateErrorMessage(cd, on));
1421 throw new Error(op.toString());
1426 private CompositeLocation checkLocationFromLiteralNode(MethodDescriptor md,
1427 SymbolTable nametable, LiteralNode en, CompositeLocation loc) {
1429 // literal value has the top location so that value can be flowed into any
1431 Location literalLoc = Location.createTopLocation(md);
1432 loc.addLocation(literalLoc);
1437 private CompositeLocation checkLocationFromNameNode(MethodDescriptor md, SymbolTable nametable,
1438 NameNode nn, CompositeLocation loc, CompositeLocation constraint) {
1440 NameDescriptor nd = nn.getName();
1441 if (nd.getBase() != null) {
1443 checkLocationFromExpressionNode(md, nametable, nn.getExpression(), loc, constraint, false);
1445 String varname = nd.toString();
1446 if (varname.equals("this")) {
1448 MethodLattice<String> methodLattice = ssjava.getMethodLattice(md);
1449 String thisLocId = methodLattice.getThisLoc();
1450 if (thisLocId == null) {
1451 throw new Error("The location for 'this' is not defined at "
1452 + md.getClassDesc().getSourceFileName() + "::" + nn.getNumLine());
1454 Location locElement = new Location(md, thisLocId);
1455 loc.addLocation(locElement);
1460 Descriptor d = (Descriptor) nametable.get(varname);
1462 // CompositeLocation localLoc = null;
1463 if (d instanceof VarDescriptor) {
1464 VarDescriptor vd = (VarDescriptor) d;
1465 // localLoc = d2loc.get(vd);
1466 // the type of var descriptor has a composite location!
1467 loc = ((SSJavaType) vd.getType().getExtension()).getCompLoc().clone();
1468 } else if (d instanceof FieldDescriptor) {
1469 // the type of field descriptor has a location!
1470 FieldDescriptor fd = (FieldDescriptor) d;
1471 if (fd.isStatic()) {
1473 // if it is 'static final', the location has TOP since no one can
1475 loc.addLocation(Location.createTopLocation(md));
1478 // if 'static', the location has pre-assigned global loc
1479 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1480 String globalLocId = localLattice.getGlobalLoc();
1481 if (globalLocId == null) {
1482 throw new Error("Global location element is not defined in the method " + md);
1484 Location globalLoc = new Location(md, globalLocId);
1486 loc.addLocation(globalLoc);
1489 // the location of field access starts from this, followed by field
1491 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1492 Location thisLoc = new Location(md, localLattice.getThisLoc());
1493 loc.addLocation(thisLoc);
1496 Location fieldLoc = (Location) fd.getType().getExtension();
1497 loc.addLocation(fieldLoc);
1498 } else if (d == null) {
1499 // access static field
1500 FieldDescriptor fd = nn.getField();
1502 MethodLattice<String> localLattice = ssjava.getMethodLattice(md);
1503 String globalLocId = localLattice.getGlobalLoc();
1504 if (globalLocId == null) {
1505 throw new Error("Method lattice does not define global variable location at "
1506 + generateErrorMessage(md.getClassDesc(), nn));
1508 loc.addLocation(new Location(md, globalLocId));
1510 Location fieldLoc = (Location) fd.getType().getExtension();
1511 loc.addLocation(fieldLoc);
1520 private CompositeLocation checkLocationFromFieldAccessNode(MethodDescriptor md,
1521 SymbolTable nametable, FieldAccessNode fan, CompositeLocation loc,
1522 CompositeLocation constraint) {
1524 ExpressionNode left = fan.getExpression();
1525 TypeDescriptor ltd = left.getType();
1527 FieldDescriptor fd = fan.getField();
1529 String varName = null;
1530 if (left.kind() == Kind.NameNode) {
1531 NameDescriptor nd = ((NameNode) left).getName();
1532 varName = nd.toString();
1535 if (ltd.isClassNameRef() || (varName != null && varName.equals("this"))) {
1536 // using a class name directly or access using this
1537 if (fd.isStatic() && fd.isFinal()) {
1538 loc.addLocation(Location.createTopLocation(md));
1543 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
1544 if (left instanceof ArrayAccessNode) {
1545 ArrayAccessNode aan = (ArrayAccessNode) left;
1546 CompositeLocation indexLoc =
1547 checkLocationFromExpressionNode(md, nametable, aan.getIndex(), loc, constraint, false);
1548 inputGLB.add(indexLoc);
1551 loc = checkLocationFromExpressionNode(md, nametable, left, loc, constraint, false);
1553 if (!left.getType().isPrimitive()) {
1555 if (!fd.getSymbol().equals("length")) {
1556 // array.length access, return the location of the array
1557 Location fieldLoc = getFieldLocation(fd);
1558 loc.addLocation(fieldLoc);
1564 loc = CompositeLattice.calculateGLB(inputGLB, generateErrorMessage(md.getClassDesc(), fan));
1568 private Location getFieldLocation(FieldDescriptor fd) {
1570 // System.out.println("### getFieldLocation=" + fd);
1571 // System.out.println("### fd.getType().getExtension()=" +
1572 // fd.getType().getExtension());
1574 Location fieldLoc = (Location) fd.getType().getExtension();
1576 // handle the case that method annotation checking skips checking field
1578 if (fieldLoc == null) {
1579 fieldLoc = checkFieldDeclaration(fd.getClassDescriptor(), fd);
1586 private FieldDescriptor getFieldDescriptorFromExpressionNode(ExpressionNode en) {
1588 if (en.kind() == Kind.NameNode) {
1589 NameNode nn = (NameNode) en;
1590 if (nn.getField() != null) {
1591 return nn.getField();
1594 if (nn.getName() != null && nn.getName().getBase() != null) {
1595 return getFieldDescriptorFromExpressionNode(nn.getExpression());
1598 } else if (en.kind() == Kind.FieldAccessNode) {
1599 FieldAccessNode fan = (FieldAccessNode) en;
1600 return fan.getField();
1606 private CompositeLocation checkLocationFromAssignmentNode(MethodDescriptor md,
1607 SymbolTable nametable, AssignmentNode an, CompositeLocation loc, CompositeLocation constraint) {
1608 ClassDescriptor cd = md.getClassDesc();
1610 Set<CompositeLocation> inputGLBSet = new HashSet<CompositeLocation>();
1612 boolean postinc = true;
1613 if (an.getOperation().getBaseOp() == null
1614 || (an.getOperation().getBaseOp().getOp() != Operation.POSTINC && an.getOperation()
1615 .getBaseOp().getOp() != Operation.POSTDEC))
1618 // if LHS is array access node, need to check if array index is higher
1619 // than array itself
1620 CompositeLocation destLocation =
1621 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1624 CompositeLocation rhsLocation;
1625 CompositeLocation srcLocation;
1629 checkOwnership(md, an, an.getSrc());
1632 checkLocationFromExpressionNode(md, nametable, an.getSrc(), new CompositeLocation(),
1635 if (an.getOperation().getOp() >= 2 && an.getOperation().getOp() <= 12) {
1636 // if assignment contains OP+EQ operator, need to merge location types
1637 // of LHS & RHS into the RHS
1638 Set<CompositeLocation> srcGLBSet = new HashSet<CompositeLocation>();
1639 srcGLBSet.add(rhsLocation);
1640 srcGLBSet.add(destLocation);
1641 srcLocation = CompositeLattice.calculateGLB(srcGLBSet, generateErrorMessage(cd, an));
1643 srcLocation = rhsLocation;
1646 if (constraint != null) {
1648 if (!CompositeLattice.isGreaterThan(constraint, destLocation, generateErrorMessage(cd, an))) {
1649 throw new Error("The value flow from " + constraint + " to " + destLocation
1650 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1651 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1653 // inputGLBSet.add(srcLocation);
1654 // inputGLBSet.add(constraint);
1655 // srcLocation = CompositeLattice.calculateGLB(inputGLBSet,
1656 // generateErrorMessage(cd, an));
1659 System.out.println("src=" + srcLocation + " dest=" + destLocation + " const=" + constraint);
1661 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1663 String context = "";
1664 if (constraint != null) {
1665 context = " and the current context constraint is " + constraint;
1668 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1669 + " does not respect location hierarchy on the assignment " + an.printNode(0) + context
1670 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1673 if (srcLocation.equals(destLocation)) {
1674 // keep it for definitely written analysis
1675 Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1676 for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1677 FlatNode fn = (FlatNode) iterator.next();
1678 ssjava.addSameHeightWriteFlatNode(fn);
1686 checkLocationFromExpressionNode(md, nametable, an.getDest(), new CompositeLocation(),
1689 if (constraint != null) {
1691 if (!CompositeLattice.isGreaterThan(constraint, destLocation, generateErrorMessage(cd, an))) {
1692 throw new Error("The value flow from " + constraint + " to " + destLocation
1693 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1694 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1696 // inputGLBSet.add(rhsLocation);
1697 // inputGLBSet.add(constraint);
1698 // srcLocation = CompositeLattice.calculateGLB(inputGLBSet,
1699 // generateErrorMessage(cd, an));
1700 srcLocation = rhsLocation;
1702 srcLocation = rhsLocation;
1705 if (!CompositeLattice.isGreaterThan(srcLocation, destLocation, generateErrorMessage(cd, an))) {
1707 if (srcLocation.equals(destLocation)) {
1708 throw new Error("Location " + srcLocation
1709 + " is not allowed to have the value flow that moves within the same location at '"
1710 + an.printNode(0) + "' of " + cd.getSourceFileName() + "::" + an.getNumLine());
1712 throw new Error("The value flow from " + srcLocation + " to " + destLocation
1713 + " does not respect location hierarchy on the assignment " + an.printNode(0)
1714 + " at " + cd.getSourceFileName() + "::" + an.getNumLine());
1719 if (srcLocation.equals(destLocation)) {
1720 // keep it for definitely written analysis
1721 Set<FlatNode> flatNodeSet = ssjava.getBuildFlat().getFlatNodeSet(an);
1722 for (Iterator iterator = flatNodeSet.iterator(); iterator.hasNext();) {
1723 FlatNode fn = (FlatNode) iterator.next();
1724 ssjava.addSameHeightWriteFlatNode(fn);
1730 return destLocation;
1733 private void assignLocationOfVarDescriptor(VarDescriptor vd, MethodDescriptor md,
1734 SymbolTable nametable, TreeNode n) {
1736 ClassDescriptor cd = md.getClassDesc();
1737 Vector<AnnotationDescriptor> annotationVec = vd.getType().getAnnotationMarkers();
1739 // currently enforce every variable to have corresponding location
1740 if (annotationVec.size() == 0) {
1741 throw new Error("Location is not assigned to variable '" + vd.getSymbol()
1742 + "' in the method '" + md + "' of the class " + cd.getSymbol() + " at "
1743 + generateErrorMessage(cd, n));
1746 int locDecCount = 0;
1747 for (int i = 0; i < annotationVec.size(); i++) {
1748 AnnotationDescriptor ad = annotationVec.elementAt(i);
1750 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1752 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1754 if (locDecCount > 1) {// variable can have at most one location
1755 throw new Error(vd.getSymbol() + " has more than one location declaration.");
1757 String locDec = ad.getValue(); // check if location is defined
1759 if (locDec.startsWith(SSJavaAnalysis.DELTA)) {
1760 DeltaLocation deltaLoc = parseDeltaDeclaration(md, n, locDec);
1761 d2loc.put(vd, deltaLoc);
1762 addLocationType(vd.getType(), deltaLoc);
1764 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1766 Location lastElement = compLoc.get(compLoc.getSize() - 1);
1767 if (ssjava.isSharedLocation(lastElement)) {
1768 ssjava.mapSharedLocation2Descriptor(lastElement, vd);
1771 d2loc.put(vd, compLoc);
1772 addLocationType(vd.getType(), compLoc);
1781 private DeltaLocation parseDeltaDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1784 int dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1787 int beginIdx = dIdx + 6;
1788 locDec = locDec.substring(beginIdx, locDec.length() - 1);
1789 dIdx = locDec.indexOf(SSJavaAnalysis.DELTA);
1792 CompositeLocation compLoc = parseLocationDeclaration(md, n, locDec);
1793 DeltaLocation deltaLoc = new DeltaLocation(compLoc, deltaCount);
1798 private Location parseFieldLocDeclaraton(String decl, String msg) throws Exception {
1800 int idx = decl.indexOf(".");
1802 String className = decl.substring(0, idx);
1803 String fieldName = decl.substring(idx + 1);
1805 className.replaceAll(" ", "");
1806 fieldName.replaceAll(" ", "");
1808 Descriptor d = state.getClassSymbolTable().get(className);
1811 // System.out.println("state.getClassSymbolTable()=" +
1812 // state.getClassSymbolTable());
1813 throw new Error("The class in the location declaration '" + decl + "' does not exist at "
1817 assert (d instanceof ClassDescriptor);
1818 SSJavaLattice<String> lattice = ssjava.getClassLattice((ClassDescriptor) d);
1819 if (!lattice.containsKey(fieldName)) {
1820 throw new Error("The location " + fieldName + " is not defined in the field lattice of '"
1821 + className + "' at " + msg);
1824 return new Location(d, fieldName);
1827 private CompositeLocation parseLocationDeclaration(MethodDescriptor md, TreeNode n, String locDec) {
1829 CompositeLocation compLoc = new CompositeLocation();
1831 StringTokenizer tokenizer = new StringTokenizer(locDec, ",");
1832 List<String> locIdList = new ArrayList<String>();
1833 while (tokenizer.hasMoreTokens()) {
1834 String locId = tokenizer.nextToken();
1835 locIdList.add(locId);
1838 // at least,one location element needs to be here!
1839 assert (locIdList.size() > 0);
1841 // assume that loc with idx 0 comes from the local lattice
1842 // loc with idx 1 comes from the field lattice
1844 String localLocId = locIdList.get(0);
1845 SSJavaLattice<String> localLattice = CompositeLattice.getLatticeByDescriptor(md);
1846 Location localLoc = new Location(md, localLocId);
1847 if (localLattice == null || (!localLattice.containsKey(localLocId))) {
1848 throw new Error("Location " + localLocId
1849 + " is not defined in the local variable lattice at "
1850 + md.getClassDesc().getSourceFileName() + "::" + (n != null ? n.getNumLine() : md) + ".");
1852 compLoc.addLocation(localLoc);
1854 for (int i = 1; i < locIdList.size(); i++) {
1855 String locName = locIdList.get(i);
1858 parseFieldLocDeclaraton(locName, generateErrorMessage(md.getClassDesc(), n));
1859 compLoc.addLocation(fieldLoc);
1860 } catch (Exception e) {
1861 throw new Error("The location declaration '" + locName + "' is wrong at "
1862 + generateErrorMessage(md.getClassDesc(), n));
1870 private void checkDeclarationNode(MethodDescriptor md, SymbolTable nametable, DeclarationNode dn) {
1871 VarDescriptor vd = dn.getVarDescriptor();
1872 assignLocationOfVarDescriptor(vd, md, nametable, dn);
1875 private void checkDeclarationInClass(ClassDescriptor cd) {
1876 // Check to see that fields are okay
1877 for (Iterator field_it = cd.getFields(); field_it.hasNext();) {
1878 FieldDescriptor fd = (FieldDescriptor) field_it.next();
1880 if (!(fd.isFinal() && fd.isStatic())) {
1881 checkFieldDeclaration(cd, fd);
1883 // for static final, assign top location by default
1884 Location loc = Location.createTopLocation(cd);
1885 addLocationType(fd.getType(), loc);
1890 private Location checkFieldDeclaration(ClassDescriptor cd, FieldDescriptor fd) {
1892 Vector<AnnotationDescriptor> annotationVec = fd.getType().getAnnotationMarkers();
1894 // currently enforce every field to have corresponding location
1895 if (annotationVec.size() == 0) {
1896 throw new Error("Location is not assigned to the field '" + fd.getSymbol()
1897 + "' of the class " + cd.getSymbol() + " at " + cd.getSourceFileName());
1900 if (annotationVec.size() > 1) {
1901 // variable can have at most one location
1902 throw new Error("Field " + fd.getSymbol() + " of class " + cd
1903 + " has more than one location.");
1906 AnnotationDescriptor ad = annotationVec.elementAt(0);
1907 Location loc = null;
1909 if (ad.getType() == AnnotationDescriptor.SINGLE_ANNOTATION) {
1910 if (ad.getMarker().equals(SSJavaAnalysis.LOC)) {
1911 String locationID = ad.getValue();
1912 // check if location is defined
1913 SSJavaLattice<String> lattice = ssjava.getClassLattice(cd);
1914 if (lattice == null || (!lattice.containsKey(locationID))) {
1915 throw new Error("Location " + locationID
1916 + " is not defined in the field lattice of class " + cd.getSymbol() + " at"
1917 + cd.getSourceFileName() + ".");
1919 loc = new Location(cd, locationID);
1921 if (ssjava.isSharedLocation(loc)) {
1922 ssjava.mapSharedLocation2Descriptor(loc, fd);
1925 addLocationType(fd.getType(), loc);
1933 private void addLocationType(TypeDescriptor type, CompositeLocation loc) {
1935 TypeExtension te = type.getExtension();
1938 ssType = (SSJavaType) te;
1939 ssType.setCompLoc(loc);
1941 ssType = new SSJavaType(loc);
1942 type.setExtension(ssType);
1947 private void addLocationType(TypeDescriptor type, Location loc) {
1949 type.setExtension(loc);
1953 static class CompositeLattice {
1955 public static boolean isGreaterThan(CompositeLocation loc1, CompositeLocation loc2, String msg) {
1957 // System.out.println("\nisGreaterThan=" + loc1 + " " + loc2 + " msg=" +
1959 int baseCompareResult = compareBaseLocationSet(loc1, loc2, true, false, msg);
1960 if (baseCompareResult == ComparisonResult.EQUAL) {
1961 if (compareDelta(loc1, loc2) == ComparisonResult.GREATER) {
1966 } else if (baseCompareResult == ComparisonResult.GREATER) {
1974 public static int compare(CompositeLocation loc1, CompositeLocation loc2, boolean ignore,
1977 // System.out.println("compare=" + loc1 + " " + loc2);
1978 int baseCompareResult = compareBaseLocationSet(loc1, loc2, false, ignore, msg);
1980 if (baseCompareResult == ComparisonResult.EQUAL) {
1981 return compareDelta(loc1, loc2);
1983 return baseCompareResult;
1988 private static int compareDelta(CompositeLocation dLoc1, CompositeLocation dLoc2) {
1990 int deltaCount1 = 0;
1991 int deltaCount2 = 0;
1992 if (dLoc1 instanceof DeltaLocation) {
1993 deltaCount1 = ((DeltaLocation) dLoc1).getNumDelta();
1996 if (dLoc2 instanceof DeltaLocation) {
1997 deltaCount2 = ((DeltaLocation) dLoc2).getNumDelta();
1999 if (deltaCount1 < deltaCount2) {
2000 return ComparisonResult.GREATER;
2001 } else if (deltaCount1 == deltaCount2) {
2002 return ComparisonResult.EQUAL;
2004 return ComparisonResult.LESS;
2009 private static int compareBaseLocationSet(CompositeLocation compLoc1,
2010 CompositeLocation compLoc2, boolean awareSharedLoc, boolean ignore, String msg) {
2012 // if compLoc1 is greater than compLoc2, return true
2013 // else return false;
2015 // compare one by one in according to the order of the tuple
2017 for (int i = 0; i < compLoc1.getSize(); i++) {
2018 Location loc1 = compLoc1.get(i);
2019 if (i >= compLoc2.getSize()) {
2021 return ComparisonResult.INCOMPARABLE;
2023 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2024 + " because they are not comparable at " + msg);
2027 Location loc2 = compLoc2.get(i);
2029 Descriptor descriptor = getCommonParentDescriptor(loc1, loc2, msg);
2030 SSJavaLattice<String> lattice = getLatticeByDescriptor(descriptor);
2032 // check if the shared location is appeared only at the end of the
2033 // composite location
2034 if (lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2035 if (i != (compLoc1.getSize() - 1)) {
2036 throw new Error("The shared location " + loc1.getLocIdentifier()
2037 + " cannot be appeared in the middle of composite location at" + msg);
2041 if (lattice.getSharedLocSet().contains(loc2.getLocIdentifier())) {
2042 if (i != (compLoc2.getSize() - 1)) {
2043 throw new Error("The shared location " + loc2.getLocIdentifier()
2044 + " cannot be appeared in the middle of composite location at " + msg);
2048 // if (!lattice1.equals(lattice2)) {
2049 // throw new Error("Failed to compare two locations of " + compLoc1 +
2050 // " and " + compLoc2
2051 // + " because they are not comparable at " + msg);
2054 if (loc1.getLocIdentifier().equals(loc2.getLocIdentifier())) {
2056 // check if the current location is the spinning location
2057 // note that the spinning location only can be appeared in the last
2058 // part of the composite location
2059 if (awareSharedLoc && numOfTie == compLoc1.getSize()
2060 && lattice.getSharedLocSet().contains(loc1.getLocIdentifier())) {
2061 return ComparisonResult.GREATER;
2064 } else if (lattice.isGreaterThan(loc1.getLocIdentifier(), loc2.getLocIdentifier())) {
2065 return ComparisonResult.GREATER;
2067 return ComparisonResult.LESS;
2072 if (numOfTie == compLoc1.getSize()) {
2074 if (numOfTie != compLoc2.getSize()) {
2077 return ComparisonResult.INCOMPARABLE;
2079 throw new Error("Failed to compare two locations of " + compLoc1 + " and " + compLoc2
2080 + " because they are not comparable at " + msg);
2085 return ComparisonResult.EQUAL;
2088 return ComparisonResult.LESS;
2092 public static CompositeLocation calculateGLB(Set<CompositeLocation> inputSet, String errMsg) {
2094 System.out.println("Calculating GLB=" + inputSet);
2095 CompositeLocation glbCompLoc = new CompositeLocation();
2097 // calculate GLB of the first(priority) element
2098 Set<String> priorityLocIdentifierSet = new HashSet<String>();
2099 Descriptor priorityDescriptor = null;
2101 Hashtable<String, Set<CompositeLocation>> locId2CompLocSet =
2102 new Hashtable<String, Set<CompositeLocation>>();
2103 // mapping from the priority loc ID to its full representation by the
2104 // composite location
2106 int maxTupleSize = 0;
2107 CompositeLocation maxCompLoc = null;
2109 Location prevPriorityLoc = null;
2110 for (Iterator iterator = inputSet.iterator(); iterator.hasNext();) {
2111 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2112 if (compLoc.getSize() > maxTupleSize) {
2113 maxTupleSize = compLoc.getSize();
2114 maxCompLoc = compLoc;
2116 Location priorityLoc = compLoc.get(0);
2117 String priorityLocId = priorityLoc.getLocIdentifier();
2118 priorityLocIdentifierSet.add(priorityLocId);
2120 if (locId2CompLocSet.containsKey(priorityLocId)) {
2121 locId2CompLocSet.get(priorityLocId).add(compLoc);
2123 Set<CompositeLocation> newSet = new HashSet<CompositeLocation>();
2124 newSet.add(compLoc);
2125 locId2CompLocSet.put(priorityLocId, newSet);
2128 // check if priority location are coming from the same lattice
2129 if (priorityDescriptor == null) {
2130 priorityDescriptor = priorityLoc.getDescriptor();
2132 priorityDescriptor = getCommonParentDescriptor(priorityLoc, prevPriorityLoc, errMsg);
2134 prevPriorityLoc = priorityLoc;
2135 // else if (!priorityDescriptor.equals(priorityLoc.getDescriptor())) {
2136 // throw new Error("Failed to calculate GLB of " + inputSet
2137 // + " because they are from different lattices.");
2141 SSJavaLattice<String> locOrder = getLatticeByDescriptor(priorityDescriptor);
2142 String glbOfPriorityLoc = locOrder.getGLB(priorityLocIdentifierSet);
2143 glbCompLoc.addLocation(new Location(priorityDescriptor, glbOfPriorityLoc));
2144 Set<CompositeLocation> compSet = locId2CompLocSet.get(glbOfPriorityLoc);
2146 if (compSet == null) {
2147 // when GLB(x1,x2)!=x1 and !=x2 : GLB case 4
2148 // mean that the result is already lower than <x1,y1> and <x2,y2>
2149 // assign TOP to the rest of the location elements
2151 // in this case, do not take care about delta
2152 // CompositeLocation inputComp = inputSet.iterator().next();
2153 for (int i = 1; i < maxTupleSize; i++) {
2154 glbCompLoc.addLocation(Location.createTopLocation(maxCompLoc.get(i).getDescriptor()));
2158 // here find out composite location that has a maximum length tuple
2159 // if we have three input set: [A], [A,B], [A,B,C]
2160 // maximum length tuple will be [A,B,C]
2162 CompositeLocation maxFromCompSet = null;
2163 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2164 CompositeLocation c = (CompositeLocation) iterator.next();
2165 if (c.getSize() > max) {
2171 if (compSet.size() == 1) {
2172 // if GLB(x1,x2)==x1 or x2 : GLB case 2,3
2173 CompositeLocation comp = compSet.iterator().next();
2174 for (int i = 1; i < comp.getSize(); i++) {
2175 glbCompLoc.addLocation(comp.get(i));
2178 // if input location corresponding to glb is a delta, need to apply
2179 // delta to glb result
2180 if (comp instanceof DeltaLocation) {
2181 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2185 // when GLB(x1,x2)==x1 and x2 : GLB case 1
2186 // if more than one location shares the same priority GLB
2187 // need to calculate the rest of GLB loc
2189 // setup input set starting from the second tuple item
2190 Set<CompositeLocation> innerGLBInput = new HashSet<CompositeLocation>();
2191 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2192 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2193 CompositeLocation innerCompLoc = new CompositeLocation();
2194 for (int idx = 1; idx < compLoc.getSize(); idx++) {
2195 innerCompLoc.addLocation(compLoc.get(idx));
2197 if (innerCompLoc.getSize() > 0) {
2198 innerGLBInput.add(innerCompLoc);
2202 if (innerGLBInput.size() > 0) {
2203 CompositeLocation innerGLB = CompositeLattice.calculateGLB(innerGLBInput, errMsg);
2204 for (int idx = 0; idx < innerGLB.getSize(); idx++) {
2205 glbCompLoc.addLocation(innerGLB.get(idx));
2209 // if input location corresponding to glb is a delta, need to apply
2210 // delta to glb result
2212 for (Iterator iterator = compSet.iterator(); iterator.hasNext();) {
2213 CompositeLocation compLoc = (CompositeLocation) iterator.next();
2214 if (compLoc instanceof DeltaLocation) {
2215 if (glbCompLoc.equals(compLoc)) {
2216 glbCompLoc = new DeltaLocation(glbCompLoc, 1);
2225 // System.out.println("GLB=" + glbCompLoc);
2230 static SSJavaLattice<String> getLatticeByDescriptor(Descriptor d) {
2232 SSJavaLattice<String> lattice = null;
2234 if (d instanceof ClassDescriptor) {
2235 lattice = ssjava.getCd2lattice().get(d);
2236 } else if (d instanceof MethodDescriptor) {
2237 if (ssjava.getMd2lattice().containsKey(d)) {
2238 lattice = ssjava.getMd2lattice().get(d);
2240 // use default lattice for the method
2241 lattice = ssjava.getCd2methodDefault().get(((MethodDescriptor) d).getClassDesc());
2248 static Descriptor getCommonParentDescriptor(Location loc1, Location loc2, String msg) {
2250 Descriptor d1 = loc1.getDescriptor();
2251 Descriptor d2 = loc2.getDescriptor();
2253 Descriptor descriptor;
2255 if (d1 instanceof ClassDescriptor && d2 instanceof ClassDescriptor) {
2257 if (d1.equals(d2)) {
2260 // identifying which one is parent class
2261 Set<Descriptor> d1SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d1);
2262 Set<Descriptor> d2SubClassesSet = ssjava.tu.getSubClasses((ClassDescriptor) d2);
2264 if (d1 == null && d2 == null) {
2265 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2266 + " because they are not comparable at " + msg);
2267 } else if (d1SubClassesSet != null && d1SubClassesSet.contains(d2)) {
2269 } else if (d2SubClassesSet != null && d2SubClassesSet.contains(d1)) {
2272 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2273 + " because they are not comparable at " + msg);
2277 } else if (d1 instanceof MethodDescriptor && d2 instanceof MethodDescriptor) {
2279 if (d1.equals(d2)) {
2283 // identifying which one is parent class
2284 MethodDescriptor md1 = (MethodDescriptor) d1;
2285 MethodDescriptor md2 = (MethodDescriptor) d2;
2287 if (!md1.matches(md2)) {
2288 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2289 + " because they are not comparable at " + msg);
2292 Set<Descriptor> d1SubClassesSet =
2293 ssjava.tu.getSubClasses(((MethodDescriptor) d1).getClassDesc());
2294 Set<Descriptor> d2SubClassesSet =
2295 ssjava.tu.getSubClasses(((MethodDescriptor) d2).getClassDesc());
2297 if (d1 == null && d2 == null) {
2298 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2299 + " because they are not comparable at " + msg);
2300 } else if (d1 != null && d1SubClassesSet.contains(d2)) {
2302 } else if (d2 != null && d2SubClassesSet.contains(d1)) {
2305 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2306 + " because they are not comparable at " + msg);
2311 throw new Error("Failed to compare two locations of " + loc1 + " and " + loc2
2312 + " because they are not comparable at " + msg);
2321 class ComparisonResult {
2323 public static final int GREATER = 0;
2324 public static final int EQUAL = 1;
2325 public static final int LESS = 2;
2326 public static final int INCOMPARABLE = 3;
2333 class ReturnLocGenerator {
2335 public static final int PARAMISHIGHER = 0;
2336 public static final int PARAMISSAME = 1;
2337 public static final int IGNORE = 2;
2339 private Hashtable<Integer, Integer> paramIdx2paramType;
2341 private CompositeLocation declaredReturnLoc = null;
2343 public ReturnLocGenerator(CompositeLocation returnLoc, MethodDescriptor md,
2344 List<CompositeLocation> params, String msg) {
2346 CompositeLocation thisLoc = params.get(0);
2347 if (returnLoc.get(0).equals(thisLoc.get(0)) && returnLoc.getSize() > 1) {
2348 // if the declared return location consists of THIS and field location,
2349 // return location for the caller's side has to have same field element
2350 this.declaredReturnLoc = returnLoc;
2352 // creating mappings
2353 paramIdx2paramType = new Hashtable<Integer, Integer>();
2354 for (int i = 0; i < params.size(); i++) {
2355 CompositeLocation param = params.get(i);
2356 int compareResult = CompositeLattice.compare(param, returnLoc, true, msg);
2359 if (compareResult == ComparisonResult.GREATER) {
2361 } else if (compareResult == ComparisonResult.EQUAL) {
2366 paramIdx2paramType.put(new Integer(i), new Integer(type));
2372 public CompositeLocation computeReturnLocation(List<CompositeLocation> args) {
2374 if (declaredReturnLoc != null) {
2375 // when developer specify that the return value is [THIS,field]
2376 // needs to translate to the caller's location
2377 CompositeLocation callerLoc = new CompositeLocation();
2378 CompositeLocation callerBaseLocation = args.get(0);
2380 for (int i = 0; i < callerBaseLocation.getSize(); i++) {
2381 callerLoc.addLocation(callerBaseLocation.get(i));
2383 for (int i = 1; i < declaredReturnLoc.getSize(); i++) {
2384 callerLoc.addLocation(declaredReturnLoc.get(i));
2388 // compute the highest possible location in caller's side
2389 assert paramIdx2paramType.keySet().size() == args.size();
2391 Set<CompositeLocation> inputGLB = new HashSet<CompositeLocation>();
2392 for (int i = 0; i < args.size(); i++) {
2393 int type = (paramIdx2paramType.get(new Integer(i))).intValue();
2394 CompositeLocation argLoc = args.get(i);
2395 if (type == PARAMISHIGHER || type == PARAMISSAME) {
2396 // return loc is equal to or lower than param
2397 inputGLB.add(argLoc);
2401 // compute GLB of arguments subset that are same or higher than return
2403 if (inputGLB.isEmpty()) {
2404 if (args.size() == 0) {
2407 CompositeLocation rtr =
2408 new CompositeLocation(Location.createTopLocation(args.get(0).get(0).getDescriptor()));
2411 CompositeLocation glb = CompositeLattice.calculateGLB(inputGLB, "");