View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.rule.design;
5   
6   import java.util.ArrayList;
7   import java.util.Collections;
8   import java.util.Comparator;
9   import java.util.Iterator;
10  import java.util.List;
11  import java.util.Map;
12  import java.util.Set;
13  import java.util.TreeMap;
14  
15  import net.sourceforge.pmd.lang.ast.Node;
16  import net.sourceforge.pmd.lang.java.ast.ASTArguments;
17  import net.sourceforge.pmd.lang.java.ast.ASTClassOrInterfaceDeclaration;
18  import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
19  import net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration;
20  import net.sourceforge.pmd.lang.java.ast.ASTEnumDeclaration;
21  import net.sourceforge.pmd.lang.java.ast.ASTExplicitConstructorInvocation;
22  import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
23  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclaration;
24  import net.sourceforge.pmd.lang.java.ast.ASTMethodDeclarator;
25  import net.sourceforge.pmd.lang.java.ast.ASTName;
26  import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
27  import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
28  import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix;
29  import net.sourceforge.pmd.lang.java.ast.AccessNode;
30  import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
31  
32  /**
33   * Searches through all methods and constructors called from constructors.  It
34   * marks as dangerous any call to overridable methods from non-private
35   * constructors.  It marks as dangerous any calls to dangerous private constructors
36   * from non-private constructors.
37   *
38   * @author CL Gilbert (dnoyeb@users.sourceforge.net)
39   *
40   * TODO match parameter types.  Aggressively strips off any package names.  Normal
41   * compares the names as is.
42   * TODO What about interface declarations which can have internal classes
43   */
44  public final class ConstructorCallsOverridableMethodRule extends AbstractJavaRule {
45      /**
46       * 2: method();
47       * ASTPrimaryPrefix
48       * ASTName			image = "method"
49       * ASTPrimarySuffix
50       * *ASTArguments
51       * 3: a.method();
52       * ASTPrimaryPrefix ->
53       * ASTName			image = "a.method" ???
54       * ASTPrimarySuffix -> ()
55       * ASTArguments
56       * 3: this.method();
57       * ASTPrimaryPrefix -> this image=null
58       * ASTPrimarySuffix -> method
59       * ASTPrimarySuffix -> ()
60       * ASTArguments
61       * <p/>
62       * super.method();
63       * ASTPrimaryPrefix -> image = "method"
64       * ASTPrimarySuffix -> image = null
65       * ASTArguments ->
66       * <p/>
67       * super.a.method();
68       * ASTPrimaryPrefix -> image = "a"
69       * ASTPrimarySuffix -> image = "method"
70       * ASTPrimarySuffix -> image = null
71       * ASTArguments ->
72       * <p/>
73       * <p/>
74       * 4: this.a.method();
75       * ASTPrimaryPrefix -> image = null
76       * ASTPrimarySuffix -> image = "a"
77       * ASTPrimarySuffix -> image = "method"
78       * ASTPrimarySuffix ->
79       * ASTArguments
80       * <p/>
81       * 4: ClassName.this.method();
82       * ASTPrimaryPrefix
83       * ASTName	image = "ClassName"
84       * ASTPrimarySuffix -> this image=null
85       * ASTPrimarySuffix -> image = "method"
86       * ASTPrimarySuffix -> ()
87       * ASTArguments
88       * 5: ClassName.this.a.method();
89       * ASTPrimaryPrefix
90       * ASTName image = "ClassName"
91       * ASTPrimarySuffix -> this image=null
92       * ASTPrimarySuffix -> image="a"
93       * ASTPrimarySuffix -> image="method"
94       * ASTPrimarySuffix -> ()
95       * ASTArguments
96       * 5: Package.ClassName.this.method();
97       * ASTPrimaryPrefix
98       * ASTName image ="Package.ClassName"
99       * ASTPrimarySuffix -> this image=null
100      * ASTPrimarySuffix -> image="method"
101      * ASTPrimarySuffix -> ()
102      * ASTArguments
103      * 6: Package.ClassName.this.a.method();
104      * ASTPrimaryPrefix
105      * ASTName image ="Package.ClassName"
106      * ASTPrimarySuffix -> this image=null
107      * ASTPrimarySuffix -> a
108      * ASTPrimarySuffix -> method
109      * ASTPrimarySuffix -> ()
110      * ASTArguments
111      * 5: OuterClass.InnerClass.this.method();
112      * ASTPrimaryPrefix
113      * ASTName image = "OuterClass.InnerClass"
114      * ASTPrimarySuffix -> this image=null
115      * ASTPrimarySuffix -> method
116      * ASTPrimarySuffix -> ()
117      * ASTArguments
118      * 6: OuterClass.InnerClass.this.a.method();
119      * ASTPrimaryPrefix
120      * ASTName image = "OuterClass.InnerClass"
121      * ASTPrimarySuffix -> this image=null
122      * ASTPrimarySuffix -> a
123      * ASTPrimarySuffix -> method
124      * ASTPrimarySuffix -> ()
125      * ASTArguments
126      * <p/>
127      * OuterClass.InnerClass.this.a.method().method().method();
128      * ASTPrimaryPrefix
129      * ASTName image = "OuterClass.InnerClass"
130      * ASTPrimarySuffix -> this		image=null
131      * ASTPrimarySuffix -> a			image='a'
132      * ASTPrimarySuffix -> method		image='method'
133      * ASTPrimarySuffix -> ()			image=null
134      * ASTArguments
135      * ASTPrimarySuffix -> method		image='method'
136      * ASTPrimarySuffix -> ()			image=null
137      * ASTArguments
138      * ASTPrimarySuffix -> method		image='method'
139      * ASTPrimarySuffix -> ()			image=null
140      * ASTArguments
141      * <p/>
142      * 3..n:	Class.InnerClass[0].InnerClass[n].this.method();
143      * ASTPrimaryPrefix
144      * ASTName image = "Class[0]..InnerClass[n]"
145      * ASTPrimarySuffix -> image=null
146      * ASTPrimarySuffix -> method
147      * ASTPrimarySuffix -> ()
148      * ASTArguments
149      * <p/>
150      * super.aMethod();
151      * ASTPrimaryPrefix -> aMethod
152      * ASTPrimarySuffix -> ()
153      * <p/>
154      * Evaluate right to left
155      */
156     private static class MethodInvocation {
157         private String name;
158         private ASTPrimaryExpression ape;
159         private List<String> referenceNames;
160         private List<String> qualifierNames;
161         private int argumentSize;
162         private boolean superCall;
163 
164         private MethodInvocation(ASTPrimaryExpression ape, List<String> qualifierNames, List<String> referenceNames, String name, int argumentSize, boolean superCall) {
165             this.ape = ape;
166             this.qualifierNames = qualifierNames;
167             this.referenceNames = referenceNames;
168             this.name = name;
169             this.argumentSize = argumentSize;
170             this.superCall = superCall;
171         }
172 
173         public boolean isSuper() {
174             return superCall;
175         }
176 
177         public String getName() {
178             return name;
179         }
180 
181         public int getArgumentCount() {
182             return argumentSize;
183         }
184 
185         public List<String> getReferenceNames() {
186             return referenceNames;//new ArrayList(variableNames);
187         }
188 
189         public List<String> getQualifierNames() {
190             return qualifierNames;
191         }
192 
193         public ASTPrimaryExpression getASTPrimaryExpression() {
194             return ape;
195         }
196 
197         public static MethodInvocation getMethod(ASTPrimaryExpression node) {
198             MethodInvocation meth = null;
199             int i = node.jjtGetNumChildren();
200             if (i > 1) {//should always be at least 2, probably can eliminate this check
201                 //start at end which is guaranteed, work backwards
202                 Node lastNode = node.jjtGetChild(i - 1);
203                 if (lastNode.jjtGetNumChildren() == 1 && lastNode.jjtGetChild(0) instanceof ASTArguments) { //could be ASTExpression for instance 'a[4] = 5';
204                     //start putting method together
205                     //					System.out.println("Putting method together now");
206                     List<String> varNames = new ArrayList<String>();
207                     List<String> packagesAndClasses = new ArrayList<String>(); //look in JLS for better name here;
208                     String methodName = null;
209                     ASTArguments args = (ASTArguments) lastNode.jjtGetChild(0);
210                     int numOfArguments = args.getArgumentCount();
211                     boolean superFirst = false;
212                     int thisIndex = -1;
213 
214                     FIND_SUPER_OR_THIS: {
215                         //search all nodes except last for 'this' or 'super'.  will be at: (node 0 | node 1 | nowhere)
216                         //this is an ASTPrimarySuffix with a null image and does not have child (which will be of type ASTArguments)
217                         //this is an ASTPrimaryPrefix with a null image and an ASTName that has a null image
218                         //super is an ASTPrimarySuffix with a null image and does not have child (which will be of type ASTArguments)
219                         //super is an ASTPrimaryPrefix with a non-null image
220                         for (int x = 0; x < i - 1; x++) {
221                             Node child = node.jjtGetChild(x);
222                             if (child instanceof ASTPrimarySuffix) { //check suffix type match
223                                 ASTPrimarySuffix child2 = (ASTPrimarySuffix) child;
224                                 //								String name = getNameFromSuffix((ASTPrimarySuffix)child);
225                                 //								System.out.println("found name suffix of : " + name);
226                                 if (child2.getImage() == null && child2.jjtGetNumChildren() == 0) {
227                                     thisIndex = x;
228                                     break;
229                                 }
230                                 //could be super, could be this.  currently we cant tell difference so we miss super when
231                                 //XYZ.ClassName.super.method();
232                                 //still works though.
233                             } else if (child instanceof ASTPrimaryPrefix) { //check prefix type match
234                                 ASTPrimaryPrefix child2 = (ASTPrimaryPrefix) child;
235                                 if (getNameFromPrefix(child2) == null) {
236                                     if (child2.getImage() == null) {
237                                         thisIndex = x;
238                                         break;
239                                     } else {//happens when super is used [super.method(): image = 'method']
240                                         superFirst = true;
241                                         thisIndex = x;
242                                         //the true super is at an unusable index because super.method() has only 2 nodes [method=0,()=1]
243                                         //as opposed to the 3 you might expect and which this.method() actually has. [this=0,method=1.()=2]
244                                         break;
245                                     }
246                                 }
247                             }
248                             //							else{
249                             //								System.err.println("Bad Format error"); //throw exception, quit evaluating this compilation node
250                             //							}
251                         }
252                     }
253 
254                     if (thisIndex != -1) {
255                         //						System.out.println("Found this or super: " + thisIndex);
256                         //Hack that must be removed if and when the patters of super.method() begins to logically match the rest of the patterns !!!
257                         if (superFirst) { //this is when super is the first node of statement.  no qualifiers, all variables or method
258                             //							System.out.println("super first");
259                             FIRSTNODE:{
260                                 ASTPrimaryPrefix child = (ASTPrimaryPrefix) node.jjtGetChild(0);
261                                 String name = child.getImage();//special case
262                                 if (i == 2) { //last named node = method name
263                                     methodName = name;
264                                 } else { //not the last named node so its only var name
265                                     varNames.add(name);
266                                 }
267                             }
268                             OTHERNODES:{ //variables
269                                 for (int x = 1; x < i - 1; x++) {
270                                     Node child = node.jjtGetChild(x);
271                                     ASTPrimarySuffix ps = (ASTPrimarySuffix) child;
272                                     if (!ps.isArguments()) {
273                                         String name = ((ASTPrimarySuffix) child).getImage();
274                                         if (x == i - 2) {//last node
275                                             methodName = name;
276                                         } else {//not the last named node so its only var name
277                                             varNames.add(name);
278                                         }
279                                     }
280                                 }
281                             }
282                         } else {//not super call
283                             FIRSTNODE:{
284                                 if (thisIndex == 1) {//qualifiers in node 0
285                                     ASTPrimaryPrefix child = (ASTPrimaryPrefix) node.jjtGetChild(0);
286                                     String toParse = getNameFromPrefix(child);
287                                     //									System.out.println("parsing for class/package names in : " + toParse);
288                                     java.util.StringTokenizer st = new java.util.StringTokenizer(toParse, ".");
289                                     while (st.hasMoreTokens()) {
290                                         packagesAndClasses.add(st.nextToken());
291                                     }
292                                 }
293                             }
294                             OTHERNODES:{ //other methods called in this statement are grabbed here
295                                 //this is at 0, then no Qualifiers
296                                 //this is at 1, the node 0 contains qualifiers
297                                 for (int x = thisIndex + 1; x < i - 1; x++) {//everything after this is var name or method name
298                                     ASTPrimarySuffix child = (ASTPrimarySuffix) node.jjtGetChild(x);
299                                     if (!child.isArguments()) { //skip the () of method calls
300                                         String name = child.getImage();
301                                         //										System.out.println("Found suffix: " + suffixName);
302                                         if (x == i - 2) {
303                                             methodName = name;
304                                         } else {
305                                             varNames.add(name);
306                                         }
307                                     }
308                                 }
309                             }
310                         }
311                     } else { //if no this or super found, everything is method name or variable
312                         //System.out.println("no this found:");
313                         FIRSTNODE:{ //variable names are in the prefix + the first method call [a.b.c.x()]
314                             ASTPrimaryPrefix child = (ASTPrimaryPrefix) node.jjtGetChild(0);
315                             String toParse = getNameFromPrefix(child);
316                             //							System.out.println("parsing for var names in : " + toParse);
317                             java.util.StringTokenizer st = new java.util.StringTokenizer(toParse, ".");
318                             while (st.hasMoreTokens()) {
319                                 String value = st.nextToken();
320                                 if (!st.hasMoreTokens()) {
321                                     if (i == 2) {//if this expression is 2 nodes long, then the last part of prefix is method name
322                                         methodName = value;
323                                     } else {
324                                         varNames.add(value);
325                                     }
326                                 } else { //variable name
327                                     varNames.add(value);
328                                 }
329                             }
330                         }
331                         OTHERNODES:{ //other methods called in this statement are grabbed here
332                             for (int x = 1; x < i - 1; x++) {
333                                 ASTPrimarySuffix child = (ASTPrimarySuffix) node.jjtGetChild(x);
334                                 if (!child.isArguments()) {
335                                     String name = child.getImage();
336                                     if (x == i - 2) {
337                                         methodName = name;
338                                     } else {
339                                         varNames.add(name);
340                                     }
341                                 }
342                             }
343                         }
344                     }
345                     meth = new MethodInvocation(node, packagesAndClasses, varNames, methodName, numOfArguments, superFirst);
346                 }
347             }
348             return meth;
349         }
350 
351         public void show() {
352             System.out.println("<MethodInvocation>");
353             System.out.println("  <Qualifiers>");
354             for (String name: getQualifierNames()) {
355                 System.out.println("    " + name);
356             }
357             System.out.println("  </Qualifiers>");
358             System.out.println("  <Super>" + isSuper() + "</Super>");
359             System.out.println("  <References>");
360             for (String name: getReferenceNames()) {
361                 System.out.println("    " + name);
362             }
363             System.out.println("  </References>");
364             System.out.println("  <Name>" + getName() + "</Name>");
365             System.out.println("</MethodInvocation>");
366         }
367     }
368 
369     private static final class ConstructorInvocation {
370         private ASTExplicitConstructorInvocation eci;
371         private String name;
372         private int count = 0;
373 
374         public ConstructorInvocation(ASTExplicitConstructorInvocation eci) {
375             this.eci = eci;
376             List<ASTArguments> l = eci.findChildrenOfType(ASTArguments.class);
377             if (!l.isEmpty()) {
378                 ASTArguments aa = l.get(0);
379                 count = aa.getArgumentCount();
380             }
381             name = eci.getImage();
382         }
383 
384         public ASTExplicitConstructorInvocation getASTExplicitConstructorInvocation() {
385             return eci;
386         }
387 
388         public int getArgumentCount() {
389             return count;
390         }
391 
392         public String getName() {
393             return name;
394         }
395     }
396 
397     private static final class MethodHolder {
398         private ASTMethodDeclarator amd;
399         private boolean dangerous;
400         private String called;
401 
402         public MethodHolder(ASTMethodDeclarator amd) {
403             this.amd = amd;
404         }
405 
406         public void setCalledMethod(String name) {
407             this.called = name;
408         }
409 
410         public String getCalled() {
411             return this.called;
412         }
413 
414         public ASTMethodDeclarator getASTMethodDeclarator() {
415             return amd;
416         }
417 
418         public boolean isDangerous() {
419             return dangerous;
420         }
421 
422         public void setDangerous() {
423             dangerous = true;
424         }
425     }
426 
427     private final class ConstructorHolder {
428         private ASTConstructorDeclaration cd;
429         private boolean dangerous;
430         private ConstructorInvocation ci;
431         private boolean ciInitialized;
432 
433         public ConstructorHolder(ASTConstructorDeclaration cd) {
434             this.cd = cd;
435         }
436 
437         public ASTConstructorDeclaration getASTConstructorDeclaration() {
438             return cd;
439         }
440 
441         public ConstructorInvocation getCalledConstructor() {
442             if (!ciInitialized) {
443                 initCI();
444             }
445             return ci;
446         }
447 
448         public ASTExplicitConstructorInvocation getASTExplicitConstructorInvocation() {
449             ASTExplicitConstructorInvocation eci = null;
450             if (!ciInitialized) {
451                 initCI();
452             }
453             if (ci != null) {
454                 eci = ci.getASTExplicitConstructorInvocation();
455             }
456             return eci;
457         }
458 
459         private void initCI() {
460             List<ASTExplicitConstructorInvocation> expressions = cd.findChildrenOfType(ASTExplicitConstructorInvocation.class); //only 1...
461             if (!expressions.isEmpty()) {
462                 ASTExplicitConstructorInvocation eci = expressions.get(0);
463                 ci = new ConstructorInvocation(eci);
464                 //System.out.println("Const call " + eci.getImage()); //super or this???
465             }
466             ciInitialized = true;
467         }
468 
469         public boolean isDangerous() {
470             return dangerous;
471         }
472 
473         public void setDangerous(boolean dangerous) {
474             this.dangerous = dangerous;
475         }
476     }
477 
478     private static int compareNodes(Node n1, Node n2) {
479         int l1 = n1.getBeginLine();
480         int l2 = n2.getBeginLine();
481         if (l1 == l2) {
482             return n1.getBeginColumn() - n2.getBeginColumn();
483         }
484         return l1 - l2;
485     }
486 
487     private static class MethodHolderComparator implements Comparator<MethodHolder> {
488         public int compare(MethodHolder o1, MethodHolder o2) {
489             return compareNodes(o1.getASTMethodDeclarator(), o2.getASTMethodDeclarator());
490         }
491     }
492 
493     private static class ConstructorHolderComparator implements Comparator<ConstructorHolder> {
494         public int compare(ConstructorHolder o1, ConstructorHolder o2) {
495             return compareNodes(o1.getASTConstructorDeclaration(), o2.getASTConstructorDeclaration());
496         }
497     }
498 
499     /**
500      * 1 package per class. holds info for evaluating a single class.
501      */
502     private static class EvalPackage {
503         public EvalPackage() {
504         }
505 
506         public EvalPackage(String className) {
507             this.className = className;
508             this.calledMethods = new ArrayList<MethodInvocation>();//meths called from constructor
509             this.allMethodsOfClass = new TreeMap<MethodHolder, List<MethodInvocation>>(new MethodHolderComparator());
510             this.calledConstructors = new ArrayList<ConstructorInvocation>();//all constructors called from constructor
511             this.allPrivateConstructorsOfClass = new TreeMap<ConstructorHolder, List<MethodInvocation>>(new ConstructorHolderComparator());
512         }
513 
514         public String className;
515         public List<MethodInvocation> calledMethods;
516         public Map<MethodHolder, List<MethodInvocation>> allMethodsOfClass;
517 
518         public List<ConstructorInvocation> calledConstructors;
519         public Map<ConstructorHolder, List<MethodInvocation>> allPrivateConstructorsOfClass;
520     }
521 
522     private static final class NullEvalPackage extends EvalPackage {
523         public NullEvalPackage() {
524             className = "";
525             calledMethods = Collections.emptyList();
526             allMethodsOfClass = Collections.emptyMap();
527             calledConstructors = Collections.emptyList();
528             allPrivateConstructorsOfClass = Collections.emptyMap();
529         }
530     }
531 
532     private static final NullEvalPackage NULL_EVAL_PACKAGE = new NullEvalPackage();
533 
534 
535     /**
536      * 1 package per class.
537      */
538     private final List<EvalPackage> evalPackages = new ArrayList<EvalPackage>();//could use java.util.Stack
539 
540     private EvalPackage getCurrentEvalPackage() {
541         return evalPackages.get(evalPackages.size() - 1);
542     }
543 
544     /**
545      * Adds and evaluation package and makes it current
546      */
547     private void putEvalPackage(EvalPackage ep) {
548         evalPackages.add(ep);
549     }
550 
551     private void removeCurrentEvalPackage() {
552         evalPackages.remove(evalPackages.size() - 1);
553     }
554 
555     private void clearEvalPackages() {
556         evalPackages.clear();
557     }
558 
559     /**
560      * This check must be evaluated independently for each class. Inner classes
561      * get their own EvalPackage in order to perform independent evaluation.
562      */
563     private Object visitClassDec(ASTClassOrInterfaceDeclaration node, Object data) {
564         String className = node.getImage();
565         if (!node.isFinal()) {
566             putEvalPackage(new EvalPackage(className));
567         } else {
568             putEvalPackage(NULL_EVAL_PACKAGE);
569         }
570         //store any errors caught from other passes.
571         super.visit(node, data);
572 
573         //skip this class if it has no evaluation package
574         if (!(getCurrentEvalPackage() instanceof NullEvalPackage)) {
575             //evaluate danger of all methods in class, this method will return false when all methods have been evaluated
576             while (evaluateDangerOfMethods(getCurrentEvalPackage().allMethodsOfClass)) { } //NOPMD
577             //evaluate danger of constructors
578             evaluateDangerOfConstructors1(getCurrentEvalPackage().allPrivateConstructorsOfClass, getCurrentEvalPackage().allMethodsOfClass.keySet());
579             while (evaluateDangerOfConstructors2(getCurrentEvalPackage().allPrivateConstructorsOfClass)) { } //NOPMD
580 
581             //get each method called on this object from a non-private constructor, if its dangerous flag it
582             for (MethodInvocation meth: getCurrentEvalPackage().calledMethods) {
583                 //check against each dangerous method in class
584                 for (MethodHolder h: getCurrentEvalPackage().allMethodsOfClass.keySet()) {
585                     if (h.isDangerous()) {
586                         String methName = h.getASTMethodDeclarator().getImage();
587                         int count = h.getASTMethodDeclarator().getParameterCount();
588                         if (methName.equals(meth.getName()) && meth.getArgumentCount() == count) {
589                             addViolation(data, meth.getASTPrimaryExpression(), "method '" + h.getCalled() + "'");
590                         }
591                     }
592                 }
593             }
594             //get each unsafe private constructor, and check if its called from any non private constructors
595             for (ConstructorHolder ch: getCurrentEvalPackage().allPrivateConstructorsOfClass.keySet()) {
596                 if (ch.isDangerous()) { //if its dangerous check if its called from any non-private constructors
597                     //System.out.println("visitClassDec Evaluating dangerous constructor with " + ch.getASTConstructorDeclaration().getParameterCount() + " params");
598                     int paramCount = ch.getASTConstructorDeclaration().getParameterCount();
599                     for (ConstructorInvocation ci: getCurrentEvalPackage().calledConstructors) {
600                         if (ci.getArgumentCount() == paramCount) {
601                             //match name  super / this !?
602                             addViolation(data, ci.getASTExplicitConstructorInvocation(), "constructor");
603                         }
604                     }
605                 }
606             }
607         }
608         //finished evaluating this class, move up a level
609         removeCurrentEvalPackage();
610         return data;
611     }
612 
613     /**
614      * Check the methods called on this class by each of the methods on this
615      * class.  If a method calls an unsafe method, mark the calling method as
616      * unsafe.  This changes the list of unsafe methods which necessitates
617      * another pass.  Keep passing until you make a clean pass in which no
618      * methods are changed to unsafe.
619      * For speed it is possible to limit the number of passes.
620      * <p/>
621      * Impossible to tell type of arguments to method, so forget method matching
622      * on types.  just use name and num of arguments.  will be some false hits,
623      * but oh well.
624      *
625      * TODO investigate limiting the number of passes through config.
626      */
627     private boolean evaluateDangerOfMethods(Map<MethodHolder, List<MethodInvocation>> classMethodMap) {
628         //check each method if it calls overridable method
629         boolean found = false;
630         for (Map.Entry<MethodHolder, List<MethodInvocation>> entry: classMethodMap.entrySet()) {
631             MethodHolder h = entry.getKey();
632             List<MethodInvocation> calledMeths = entry.getValue();
633             for (Iterator<MethodInvocation> calledMethsIter = calledMeths.iterator(); calledMethsIter.hasNext() && !h.isDangerous();) {
634                 //if this method matches one of our dangerous methods, mark it dangerous
635                 MethodInvocation meth = calledMethsIter.next();
636                 //System.out.println("Called meth is " + meth);
637                 for (MethodHolder h3: classMethodMap.keySet()) { //need to skip self here h == h3
638                     if (h3.isDangerous()) {
639                         String matchMethodName = h3.getASTMethodDeclarator().getImage();
640                         int matchMethodParamCount = h3.getASTMethodDeclarator().getParameterCount();
641                         //System.out.println("matching " + matchMethodName + " to " + meth.getName());
642                         if (matchMethodName.equals(meth.getName()) && matchMethodParamCount == meth.getArgumentCount()) {
643                             h.setDangerous();
644                             h.setCalledMethod(matchMethodName);
645                             found = true;
646                             break;
647                         }
648                     }
649                 }
650             }
651         }
652         return found;
653     }
654 
655     /**
656      * marks constructors dangerous if they call any dangerous methods
657      * Requires only a single pass as methods are already marked
658      *
659      * TODO optimize by having methods already evaluated somehow!?
660      */
661     private void evaluateDangerOfConstructors1(Map<ConstructorHolder, List<MethodInvocation>> classConstructorMap, Set<MethodHolder> evaluatedMethods) {
662         //check each constructor in the class
663         for (Map.Entry<ConstructorHolder, List<MethodInvocation>> entry: classConstructorMap.entrySet()) {
664             ConstructorHolder ch = entry.getKey();
665             if (!ch.isDangerous()) {//if its not dangerous then evaluate if it should be
666                 //if it calls dangerous method mark it as dangerous
667                 List<MethodInvocation> calledMeths = entry.getValue();
668                 //check each method it calls
669                 for (Iterator<MethodInvocation> calledMethsIter = calledMeths.iterator(); calledMethsIter.hasNext() && !ch.isDangerous();) {//but thee are diff objects which represent same thing but were never evaluated, they need reevaluation
670                     MethodInvocation meth = calledMethsIter.next();//CCE
671                     String methName = meth.getName();
672                     int methArgCount = meth.getArgumentCount();
673                     //check each of the already evaluated methods: need to optimize this out
674                     for (MethodHolder h: evaluatedMethods) {
675                         if (h.isDangerous()) {
676                             String matchName = h.getASTMethodDeclarator().getImage();
677                             int matchParamCount = h.getASTMethodDeclarator().getParameterCount();
678                             if (methName.equals(matchName) && methArgCount == matchParamCount) {
679                                 ch.setDangerous(true);
680                                 //System.out.println("evaluateDangerOfConstructors1 setting dangerous constructor with " + ch.getASTConstructorDeclaration().getParameterCount() + " params");
681                                 break;
682                             }
683                         }
684 
685                     }
686                 }
687             }
688         }
689     }
690 
691     /**
692      * Constructor map should contain a key for each private constructor, and
693      * maps to a List which contains all called constructors of that key.
694      * marks dangerous if call dangerous private constructor
695      * we ignore all non-private constructors here.  That is, the map passed in
696      * should not contain any non-private constructors.
697      * we return boolean in order to limit the number of passes through this method
698      * but it seems as if we can forgo that and just process it till its done.
699      */
700     private boolean evaluateDangerOfConstructors2(Map<ConstructorHolder, List<MethodInvocation>> classConstructorMap) {
701         boolean found = false;//triggers on danger state change
702         //check each constructor in the class
703         for (ConstructorHolder ch: classConstructorMap.keySet()) {
704             ConstructorInvocation calledC = ch.getCalledConstructor();
705             if (calledC == null || ch.isDangerous()) {
706                 continue;
707             }
708             //if its not dangerous then evaluate if it should be
709             //if it calls dangerous constructor mark it as dangerous
710             int cCount = calledC.getArgumentCount();
711             for (Iterator<ConstructorHolder> innerConstIter = classConstructorMap.keySet().iterator(); innerConstIter.hasNext() && !ch.isDangerous();) { //forget skipping self because that introduces another check for each, but only 1 hit
712                 ConstructorHolder h2 = innerConstIter.next();
713                 if (h2.isDangerous()) {
714                     int matchConstArgCount = h2.getASTConstructorDeclaration().getParameterCount();
715                     if (matchConstArgCount == cCount) {
716                         ch.setDangerous(true);
717                         found = true;
718                         //System.out.println("evaluateDangerOfConstructors2 setting dangerous constructor with " + ch.getASTConstructorDeclaration().getParameterCount() + " params");
719                     }
720                 }
721             }
722         }
723         return found;
724     }
725 
726     @Override
727     public Object visit(ASTCompilationUnit node, Object data) {
728         clearEvalPackages();
729         return super.visit(node, data);
730     }
731 
732     @Override
733     public Object visit(ASTEnumDeclaration node, Object data) {
734         // just skip Enums
735         return data;
736     }
737 
738     /**
739      * This check must be evaluated independently for each class.  Inner classes
740      * get their own EvalPackage in order to perform independent evaluation.
741      */
742     @Override
743     public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
744         if (!node.isInterface()) {
745             return visitClassDec(node, data);
746         } else {
747             putEvalPackage(NULL_EVAL_PACKAGE);
748             Object o = super.visit(node, data);//interface may have inner classes, possible? if not just skip whole interface
749             removeCurrentEvalPackage();
750             return o;
751         }
752     }
753 
754 
755     /**
756      * Non-private constructor's methods are added to a list for later safety
757      * evaluation.  Non-private constructor's calls on private constructors
758      * are added to a list for later safety evaluation.  Private constructors
759      * are added to a list so their safety to be called can be later evaluated.
760      * <p/>
761      * Note: We are not checking private constructor's calls on non-private
762      * constructors because all non-private constructors will be evaluated for
763      * safety anyway.  This means we wont flag a private constructor as unsafe
764      * just because it calls an unsafe public constructor.  We want to show only
765      * 1 instance of an error, and this would be 2 instances of the same error.
766      *
767      * TODO eliminate the redundancy
768      */
769     @Override
770     public Object visit(ASTConstructorDeclaration node, Object data) {
771         if (!(getCurrentEvalPackage() instanceof NullEvalPackage)) {//only evaluate if we have an eval package for this class
772             List<MethodInvocation> calledMethodsOfConstructor = new ArrayList<MethodInvocation>();
773             ConstructorHolder ch = new ConstructorHolder(node);
774             addCalledMethodsOfNode(node, calledMethodsOfConstructor, getCurrentEvalPackage().className);
775             if (!node.isPrivate()) {
776                 //these calledMethods are what we will evaluate for being called badly
777                 getCurrentEvalPackage().calledMethods.addAll(calledMethodsOfConstructor);
778                 //these called private constructors are what we will evaluate for being called badly
779                 //we add all constructors invoked by non-private constructors
780                 //but we are only interested in the private ones.  We just can't tell the difference here
781                 ASTExplicitConstructorInvocation eci = ch.getASTExplicitConstructorInvocation();
782                 if (eci != null && eci.isThis()) {
783                     getCurrentEvalPackage().calledConstructors.add(ch.getCalledConstructor());
784                 }
785             } else {
786                 //add all private constructors to list for later evaluation on if they are safe to call from another constructor
787                 //store this constructorHolder for later evaluation
788                 getCurrentEvalPackage().allPrivateConstructorsOfClass.put(ch, calledMethodsOfConstructor);
789             }
790         }
791         return super.visit(node, data);
792     }
793 
794     /**
795      * Create a MethodHolder to hold the method.
796      * Store the MethodHolder in the Map as the key
797      * Store each method called by the current method as a List in the Map as the Object
798      */
799     @Override
800     public Object visit(ASTMethodDeclarator node, Object data) {
801         if (!(getCurrentEvalPackage() instanceof NullEvalPackage)) {//only evaluate if we have an eval package for this class
802             AccessNode parent = (AccessNode) node.jjtGetParent();
803             MethodHolder h = new MethodHolder(node);
804             if (!parent.isAbstract() && !parent.isPrivate() && !parent.isStatic() && !parent.isFinal()) { //Skip abstract methods, have a separate rule for that
805                 h.setDangerous();//this method is overridable
806                 ASTMethodDeclaration decl = node.getFirstParentOfType(ASTMethodDeclaration.class);
807                 h.setCalledMethod(decl.getMethodName());
808             }
809             List<MethodInvocation> l = new ArrayList<MethodInvocation>();
810             addCalledMethodsOfNode((Node)parent, l, getCurrentEvalPackage().className);
811             getCurrentEvalPackage().allMethodsOfClass.put(h, l);
812         }
813         return super.visit(node, data);
814     }
815 
816 
817     /**
818      * Adds all methods called on this instance from within this Node.
819      */
820     private static void addCalledMethodsOfNode(Node node, List<MethodInvocation> calledMethods, String className) {
821         List<ASTPrimaryExpression> expressions = new ArrayList<ASTPrimaryExpression>();
822         node.findDescendantsOfType(ASTPrimaryExpression.class, expressions, !(node instanceof AccessNode));
823         addCalledMethodsOfNodeImpl(expressions, calledMethods, className);
824     }
825 
826     private static void addCalledMethodsOfNodeImpl(List<ASTPrimaryExpression> expressions, List<MethodInvocation> calledMethods, String className) {
827         for (ASTPrimaryExpression ape: expressions) {
828             MethodInvocation meth = findMethod(ape, className);
829             if (meth != null) {
830                 //System.out.println("Adding call " + methName);
831                 calledMethods.add(meth);
832             }
833         }
834     }
835 
836     /**
837      * @return A method call on the class passed in, or null if no method call
838      *         is found.
839      * TODO Need a better way to match the class and package name to the actual
840      * method being called.
841      */
842     private static MethodInvocation findMethod(ASTPrimaryExpression node, String className) {
843         if (node.jjtGetNumChildren() > 0
844                 && node.jjtGetChild(0).jjtGetNumChildren() > 0
845                 && node.jjtGetChild(0).jjtGetChild(0) instanceof ASTLiteral) {
846             return null;
847         }
848         MethodInvocation meth = MethodInvocation.getMethod(node);
849         boolean found = false;
850         //		if(meth != null){
851         //			meth.show();
852         //		}
853         if (meth != null) {
854             //if it's a call on a variable, or on its superclass ignore it.
855             if (meth.getReferenceNames().isEmpty() && !meth.isSuper()) {
856                 //if this list does not contain our class name, then its not referencing our class
857                 //this is a cheezy test... but it errs on the side of less false hits.
858                 List<String> packClass = meth.getQualifierNames();
859                 if (!packClass.isEmpty()) {
860                     for (String name: packClass) {
861                         if (name.equals(className)) {
862                             found = true;
863                             break;
864                         }
865                     }
866                 } else {
867                     found = true;
868                 }
869             }
870         }
871 
872         return found ? meth : null;
873     }
874 
875     /**
876      * ASTPrimaryPrefix has name in child node of ASTName
877      */
878     private static String getNameFromPrefix(ASTPrimaryPrefix node) {
879         String name = null;
880         //should only be 1 child, if more I need more knowledge
881         if (node.jjtGetNumChildren() == 1) { //safety check
882             Node nnode = node.jjtGetChild(0);
883             if (nnode instanceof ASTName) { //just as easy as null check and it should be an ASTName anyway
884                 name = ((ASTName) nnode).getImage();
885             }
886         }
887         return name;
888     }
889 
890 }