Search in sources :

Example 1 with Location

use of com.android.tools.klint.detector.api.Location in project kotlin by JetBrains.

the class JavaParser method getNameLocation.

/**
     * Returns a {@link Location} for the given node. This attempts to pick a shorter
     * location range than the entire node; for a class or method for example, it picks
     * the name node (if found). For statement constructs such as a {@code switch} statement
     * it will highlight the keyword, etc.
     *
     * @param context information about the file being parsed
     * @param node the node to create a location for
     * @return a location for the given node
     * @deprecated Use {@link #getNameLocation(JavaContext, PsiElement)} instead
     */
@Deprecated
@NonNull
public Location getNameLocation(@NonNull JavaContext context, @NonNull Node node) {
    Node nameNode = JavaContext.findNameNode(node);
    if (nameNode != null) {
        node = nameNode;
    } else {
        if (node instanceof Switch || node instanceof For || node instanceof If || node instanceof While || node instanceof Throw || node instanceof Return) {
            // Lint doesn't want to highlight the entire statement/block associated
            // with this node, it wants to just highlight the keyword.
            Location location = getLocation(context, node);
            Position start = location.getStart();
            if (start != null) {
                // The Lombok classes happen to have the same length as the target keyword
                int length = node.getClass().getSimpleName().length();
                return Location.create(location.getFile(), start, new DefaultPosition(start.getLine(), start.getColumn() + length, start.getOffset() + length));
            }
        }
    }
    return getLocation(context, node);
}
Also used : Return(lombok.ast.Return) Switch(lombok.ast.Switch) Position(com.android.tools.klint.detector.api.Position) DefaultPosition(com.android.tools.klint.detector.api.DefaultPosition) Throw(lombok.ast.Throw) Node(lombok.ast.Node) DefaultPosition(com.android.tools.klint.detector.api.DefaultPosition) For(lombok.ast.For) While(lombok.ast.While) If(lombok.ast.If) Location(com.android.tools.klint.detector.api.Location) NonNull(com.android.annotations.NonNull)

Example 2 with Location

use of com.android.tools.klint.detector.api.Location in project kotlin by JetBrains.

the class AllowAllHostnameVerifierDetector method visitMethod.

@Override
public void visitMethod(@NonNull JavaContext context, @Nullable UastVisitor visitor, @NonNull UCallExpression node, @NonNull UMethod method) {
    JavaEvaluator evaluator = context.getEvaluator();
    if (evaluator.methodMatches(method, null, false, "javax.net.ssl.HostnameVerifier")) {
        UExpression argument = node.getValueArguments().get(0);
        PsiElement resolvedArgument = UastUtils.tryResolve(argument);
        if (resolvedArgument instanceof PsiField) {
            PsiField field = (PsiField) resolvedArgument;
            if ("ALLOW_ALL_HOSTNAME_VERIFIER".equals(field.getName())) {
                Location location = context.getUastLocation(argument);
                String message = "Using the ALLOW_ALL_HOSTNAME_VERIFIER HostnameVerifier " + "is unsafe because it always returns true, which could cause " + "insecure network traffic due to trusting TLS/SSL server " + "certificates for wrong hostnames";
                context.report(ISSUE, argument, location, message);
            }
        }
    }
}
Also used : UExpression(org.jetbrains.uast.UExpression) PsiField(com.intellij.psi.PsiField) JavaEvaluator(com.android.tools.klint.client.api.JavaEvaluator) PsiElement(com.intellij.psi.PsiElement) Location(com.android.tools.klint.detector.api.Location)

Example 3 with Location

use of com.android.tools.klint.detector.api.Location in project kotlin by JetBrains.

the class LintDriver method analyze.

/** Runs the driver to analyze the requested files */
private void analyze() {
    mCanceled = false;
    mScope = mRequest.getScope();
    assert mScope == null || !mScope.contains(Scope.ALL_RESOURCE_FILES) || mScope.contains(Scope.RESOURCE_FILE);
    Collection<Project> projects;
    try {
        projects = mRequest.getProjects();
        if (projects == null) {
            projects = computeProjects(mRequest.getFiles());
        }
    } catch (CircularDependencyException e) {
        mCurrentProject = e.getProject();
        if (mCurrentProject != null) {
            Location location = e.getLocation();
            File file = location != null ? location.getFile() : mCurrentProject.getDir();
            Context context = new Context(this, mCurrentProject, null, file);
            context.report(IssueRegistry.LINT_ERROR, e.getLocation(), e.getMessage());
            mCurrentProject = null;
        }
        return;
    }
    if (projects.isEmpty()) {
        mClient.log(null, "No projects found for %1$s", mRequest.getFiles().toString());
        return;
    }
    if (mCanceled) {
        return;
    }
    registerCustomDetectors(projects);
    if (mScope == null) {
        mScope = Scope.infer(projects);
    }
    fireEvent(EventType.STARTING, null);
    for (Project project : projects) {
        mPhase = 1;
        Project main = mRequest.getMainProject(project);
        // The set of available detectors varies between projects
        computeDetectors(project);
        if (mApplicableDetectors.isEmpty()) {
            // No detectors enabled in this project: skip it
            continue;
        }
        checkProject(project, main);
        if (mCanceled) {
            break;
        }
        runExtraPhases(project, main);
    }
    fireEvent(mCanceled ? EventType.CANCELED : EventType.COMPLETED, null);
}
Also used : ClassContext(com.android.tools.klint.detector.api.ClassContext) XmlContext(com.android.tools.klint.detector.api.XmlContext) JavaContext(com.android.tools.klint.detector.api.JavaContext) ResourceContext(com.android.tools.klint.detector.api.ResourceContext) Context(com.android.tools.klint.detector.api.Context) Project(com.android.tools.klint.detector.api.Project) File(java.io.File) PsiFile(com.intellij.psi.PsiFile) Location(com.android.tools.klint.detector.api.Location)

Example 4 with Location

use of com.android.tools.klint.detector.api.Location in project kotlin by JetBrains.

the class ViewConstructorDetector method checkClass.

@Override
public void checkClass(@NonNull JavaContext context, @NonNull UClass declaration) {
    // Only applies to concrete classes
    JavaEvaluator evaluator = context.getEvaluator();
    if (evaluator.isAbstract(declaration) || declaration instanceof PsiAnonymousClass) {
        // Ignore abstract classes
        return;
    }
    if (declaration.getContainingClass() != null && !evaluator.isStatic(declaration)) {
        // anyway since we'd need the outer instance
        return;
    }
    boolean found = false;
    for (PsiMethod constructor : declaration.getConstructors()) {
        if (isXmlConstructor(evaluator, constructor)) {
            found = true;
            break;
        }
    }
    if (!found) {
        String message = String.format("Custom view `%1$s` is missing constructor used by tools: " + "`(Context)` or `(Context,AttributeSet)` " + "or `(Context,AttributeSet,int)`", declaration.getName());
        Location location = context.getUastNameLocation(declaration);
        context.reportUast(ISSUE, declaration, location, message);
    }
}
Also used : PsiMethod(com.intellij.psi.PsiMethod) PsiAnonymousClass(com.intellij.psi.PsiAnonymousClass) JavaEvaluator(com.android.tools.klint.client.api.JavaEvaluator) Location(com.android.tools.klint.detector.api.Location)

Example 5 with Location

use of com.android.tools.klint.detector.api.Location in project kotlin by JetBrains.

the class StringFormatDetector method checkStringFormatCall.

/**
     * Check the given String.format call (with the given arguments) to see if the string format is
     * being used correctly
     *  @param context           the context to report errors to
     * @param calledMethod      the method being called
     * @param call              the AST node for the {@link String#format}
     * @param specifiesLocale   whether the first parameter is a locale string, shifting the
     */
private void checkStringFormatCall(JavaContext context, PsiMethod calledMethod, UCallExpression call, boolean specifiesLocale) {
    int argIndex = specifiesLocale ? 1 : 0;
    List<UExpression> args = call.getValueArguments();
    if (args.size() <= argIndex) {
        return;
    }
    UExpression argument = args.get(argIndex);
    ResourceUrl resource = ResourceEvaluator.getResource(context, argument);
    if (resource == null || resource.framework || resource.type != ResourceType.STRING) {
        return;
    }
    String name = resource.name;
    if (mIgnoreStrings != null && mIgnoreStrings.contains(name)) {
        return;
    }
    boolean passingVarArgsArray = false;
    int callCount = args.size() - 1 - argIndex;
    if (callCount == 1) {
        // If instead of a varargs call like
        //    getString(R.string.foo, arg1, arg2, arg3)
        // the code is calling the varargs method with a packed Object array, as in
        //    getString(R.string.foo, new Object[] { arg1, arg2, arg3 })
        // we'll need to handle that such that we don't think this is a single
        // argument
        UExpression lastArg = args.get(args.size() - 1);
        PsiParameterList parameterList = calledMethod.getParameterList();
        int parameterCount = parameterList.getParametersCount();
        if (parameterCount > 0 && parameterList.getParameters()[parameterCount - 1].isVarArgs()) {
            boolean knownArity = false;
            boolean argWasReference = false;
            if (lastArg instanceof UReferenceExpression) {
                PsiElement resolved = ((UReferenceExpression) lastArg).resolve();
                if (resolved instanceof PsiVariable) {
                    UExpression initializer = context.getUastContext().getInitializerBody((PsiVariable) resolved);
                    if (initializer != null && (UastExpressionUtils.isNewArray(initializer) || UastExpressionUtils.isArrayInitializer(initializer))) {
                        argWasReference = true;
                        // Now handled by check below
                        lastArg = initializer;
                    }
                }
            }
            if (UastExpressionUtils.isNewArray(lastArg) || UastExpressionUtils.isArrayInitializer(lastArg)) {
                UCallExpression arrayInitializer = (UCallExpression) lastArg;
                if (UastExpressionUtils.isNewArrayWithInitializer(lastArg) || UastExpressionUtils.isArrayInitializer(lastArg)) {
                    callCount = arrayInitializer.getValueArgumentCount();
                    knownArity = true;
                } else if (UastExpressionUtils.isNewArrayWithDimensions(lastArg)) {
                    List<UExpression> arrayDimensions = arrayInitializer.getValueArguments();
                    if (arrayDimensions.size() == 1) {
                        UExpression first = arrayDimensions.get(0);
                        if (first instanceof ULiteralExpression) {
                            Object o = ((ULiteralExpression) first).getValue();
                            if (o instanceof Integer) {
                                callCount = (Integer) o;
                                knownArity = true;
                            }
                        }
                    }
                }
                if (!knownArity) {
                    if (!argWasReference) {
                        return;
                    }
                } else {
                    passingVarArgsArray = true;
                }
            }
        }
    }
    if (callCount > 0 && mNotFormatStrings.containsKey(name)) {
        checkNotFormattedHandle(context, call, name, mNotFormatStrings.get(name));
        return;
    }
    List<Pair<Handle, String>> list = mFormatStrings != null ? mFormatStrings.get(name) : null;
    if (list == null) {
        LintClient client = context.getClient();
        if (client.supportsProjectResources() && !context.getScope().contains(Scope.RESOURCE_FILE)) {
            AbstractResourceRepository resources = client.getProjectResources(context.getMainProject(), true);
            List<ResourceItem> items;
            if (resources != null) {
                items = resources.getResourceItem(ResourceType.STRING, name);
            } else {
                // Must be a non-Android module
                items = null;
            }
            if (items != null) {
                for (final ResourceItem item : items) {
                    ResourceValue v = item.getResourceValue(false);
                    if (v != null) {
                        String value = v.getRawXmlValue();
                        if (value != null) {
                            // Make sure it's really a formatting string,
                            // not for example "Battery remaining: 90%"
                            boolean isFormattingString = value.indexOf('%') != -1;
                            for (int j = 0, m = value.length(); j < m && isFormattingString; j++) {
                                char c = value.charAt(j);
                                if (c == '\\') {
                                    j++;
                                } else if (c == '%') {
                                    Matcher matcher = FORMAT.matcher(value);
                                    if (!matcher.find(j)) {
                                        isFormattingString = false;
                                    } else {
                                        String conversion = matcher.group(6);
                                        int conversionClass = getConversionClass(conversion.charAt(0));
                                        if (conversionClass == CONVERSION_CLASS_UNKNOWN || matcher.group(5) != null) {
                                            // Some date format etc - don't process
                                            return;
                                        }
                                    }
                                    // Don't process second % in a %%
                                    j++;
                                }
                            // If the user marked the string with
                            }
                            Handle handle = client.createResourceItemHandle(item);
                            if (isFormattingString) {
                                if (list == null) {
                                    list = Lists.newArrayList();
                                    if (mFormatStrings == null) {
                                        mFormatStrings = Maps.newHashMap();
                                    }
                                    mFormatStrings.put(name, list);
                                }
                                list.add(Pair.of(handle, value));
                            } else if (callCount > 0) {
                                checkNotFormattedHandle(context, call, name, handle);
                            }
                        }
                    }
                }
            }
        } else {
            return;
        }
    }
    if (list != null) {
        Set<String> reported = null;
        for (Pair<Handle, String> pair : list) {
            String s = pair.getSecond();
            if (reported != null && reported.contains(s)) {
                continue;
            }
            int count = getFormatArgumentCount(s, null);
            Handle handle = pair.getFirst();
            if (count != callCount) {
                Location location = context.getUastLocation(call);
                Location secondary = handle.resolve();
                secondary.setMessage(String.format("This definition requires %1$d arguments", count));
                location.setSecondary(secondary);
                String message = String.format("Wrong argument count, format string `%1$s` requires `%2$d` but format " + "call supplies `%3$d`", name, count, callCount);
                context.report(ARG_TYPES, call, location, message);
                if (reported == null) {
                    reported = Sets.newHashSet();
                }
                reported.add(s);
            } else {
                if (passingVarArgsArray) {
                    // flag parameters on the Object[] instead of the wrapped parameters
                    return;
                }
                for (int i = 1; i <= count; i++) {
                    int argumentIndex = i + argIndex;
                    PsiType type = args.get(argumentIndex).getExpressionType();
                    if (type != null) {
                        boolean valid = true;
                        String formatType = getFormatArgumentType(s, i);
                        if (formatType == null) {
                            continue;
                        }
                        char last = formatType.charAt(formatType.length() - 1);
                        if (formatType.length() >= 2 && Character.toLowerCase(formatType.charAt(formatType.length() - 2)) == 't') {
                            // TODO
                            continue;
                        }
                        switch(last) {
                            // unusual and probably not intended.
                            case 'b':
                            case 'B':
                                valid = isBooleanType(type);
                                break;
                            // Numeric: integer and floats in various formats
                            case 'x':
                            case 'X':
                            case 'd':
                            case 'o':
                            case 'e':
                            case 'E':
                            case 'f':
                            case 'g':
                            case 'G':
                            case 'a':
                            case 'A':
                                valid = isNumericType(type, true);
                                break;
                            case 'c':
                            case 'C':
                                // Unicode character
                                valid = isCharacterType(type);
                                break;
                            case 'h':
                            // Hex print of hash code of objects
                            case 'H':
                            case 's':
                            case 'S':
                                // String. Can pass anything, but warn about
                                // numbers since you may have meant more
                                // specific formatting. Use special issue
                                // explanation for this?
                                valid = !isBooleanType(type) && !isNumericType(type, false);
                                break;
                        }
                        if (!valid) {
                            Location location = context.getUastLocation(args.get(argumentIndex));
                            Location secondary = handle.resolve();
                            secondary.setMessage("Conflicting argument declaration here");
                            location.setSecondary(secondary);
                            String suggestion = null;
                            if (isBooleanType(type)) {
                                suggestion = "`b`";
                            } else if (isCharacterType(type)) {
                                suggestion = "'c'";
                            } else if (PsiType.INT.equals(type) || PsiType.LONG.equals(type) || PsiType.BYTE.equals(type) || PsiType.SHORT.equals(type)) {
                                suggestion = "`d`, 'o' or `x`";
                            } else if (PsiType.FLOAT.equals(type) || PsiType.DOUBLE.equals(type)) {
                                suggestion = "`e`, 'f', 'g' or `a`";
                            } else if (type instanceof PsiClassType) {
                                String fqn = type.getCanonicalText();
                                if (TYPE_INTEGER_WRAPPER.equals(fqn) || TYPE_LONG_WRAPPER.equals(fqn) || TYPE_BYTE_WRAPPER.equals(fqn) || TYPE_SHORT_WRAPPER.equals(fqn)) {
                                    suggestion = "`d`, 'o' or `x`";
                                } else if (TYPE_FLOAT_WRAPPER.equals(fqn) || TYPE_DOUBLE_WRAPPER.equals(fqn)) {
                                    suggestion = "`d`, 'o' or `x`";
                                } else if (TYPE_OBJECT.equals(fqn)) {
                                    suggestion = "'s' or 'h'";
                                }
                            }
                            if (suggestion != null) {
                                suggestion = " (Did you mean formatting character " + suggestion + "?)";
                            } else {
                                suggestion = "";
                            }
                            String canonicalText = type.getCanonicalText();
                            canonicalText = canonicalText.substring(canonicalText.lastIndexOf('.') + 1);
                            String message = String.format("Wrong argument type for formatting argument '#%1$d' " + "in `%2$s`: conversion is '`%3$s`', received `%4$s` " + "(argument #%5$d in method call)%6$s", i, name, formatType, canonicalText, argumentIndex + 1, suggestion);
                            context.report(ARG_TYPES, call, location, message);
                            if (reported == null) {
                                reported = Sets.newHashSet();
                            }
                            reported.add(s);
                        }
                    }
                }
            }
        }
    }
}
Also used : ULiteralExpression(org.jetbrains.uast.ULiteralExpression) Matcher(java.util.regex.Matcher) UCallExpression(org.jetbrains.uast.UCallExpression) AbstractResourceRepository(com.android.ide.common.res2.AbstractResourceRepository) ResourceValue(com.android.ide.common.rendering.api.ResourceValue) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) NodeList(org.w3c.dom.NodeList) PsiParameterList(com.intellij.psi.PsiParameterList) ResourceUrl(com.android.ide.common.resources.ResourceUrl) PsiElement(com.intellij.psi.PsiElement) Pair(com.android.utils.Pair) PsiType(com.intellij.psi.PsiType) PsiVariable(com.intellij.psi.PsiVariable) LintClient(com.android.tools.klint.client.api.LintClient) Handle(com.android.tools.klint.detector.api.Location.Handle) UExpression(org.jetbrains.uast.UExpression) PsiClassType(com.intellij.psi.PsiClassType) UReferenceExpression(org.jetbrains.uast.UReferenceExpression) PsiParameterList(com.intellij.psi.PsiParameterList) ResourceItem(com.android.ide.common.res2.ResourceItem) Location(com.android.tools.klint.detector.api.Location)

Aggregations

Location (com.android.tools.klint.detector.api.Location)38 UExpression (org.jetbrains.uast.UExpression)8 JavaEvaluator (com.android.tools.klint.client.api.JavaEvaluator)7 File (java.io.File)7 PsiElement (com.intellij.psi.PsiElement)4 PsiMethod (com.intellij.psi.PsiMethod)4 ArrayList (java.util.ArrayList)4 Attr (org.w3c.dom.Attr)4 Node (org.w3c.dom.Node)4 Handle (com.android.tools.klint.detector.api.Location.Handle)3 XmlContext (com.android.tools.klint.detector.api.XmlContext)3 PsiClassType (com.intellij.psi.PsiClassType)3 PsiType (com.intellij.psi.PsiType)3 List (java.util.List)3 UAnonymousClass (org.jetbrains.uast.UAnonymousClass)3 NodeList (org.w3c.dom.NodeList)3 NonNull (com.android.annotations.NonNull)2 ResourceType (com.android.resources.ResourceType)2 ClassContext (com.android.tools.klint.detector.api.ClassContext)2 Context (com.android.tools.klint.detector.api.Context)2