Skip to content
Snippets Groups Projects
Commit b96ebc28 authored by Johannes Mey's avatar Johannes Mey
Browse files

cleanup

parent fdbee264
Branches
No related tags found
No related merge requests found
Showing
with 0 additions and 2905 deletions
...@@ -17,7 +17,6 @@ include 'deps4j' ...@@ -17,7 +17,6 @@ include 'deps4j'
include 'scope' include 'scope'
include 'scope4j' include 'scope4j'
include 'scope4m' include 'scope4m'
include 'simplecfg'
include 'extendj:java4' include 'extendj:java4'
include 'extendj:java5' include 'extendj:java5'
include 'extendj:java6' include 'extendj:java6'
......
# gradle build
/build/
/.gradle/
# generated files
/*.jar
/src/gen/
# generated graphs
/testdata/*.png
# vim
*.swp
# eclipse
/.project
/.classpath
/.settings/
/bin/
Want to contribute? Great! First, read this page (including the small print at the end).
### Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
### Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.
### The small print
Contributions made by corporations are covered by a different agreement than
the one above, the Software Grant and Corporate Contributor License Agreement.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Simple CFG module for ExtendJ
=============================
This is a Control Flow Graph (CFG) module for the ExtendJ compiler for building
simplified CFGs. This module builds CFGs for Java methods where only branches
and method calls have are included. These simple CFGs provide enough
information to perform intraprocedural static analyses on Java code.
This repository also includes two sample Java static analyzers based on the this
CFG module. One analyzer checks for additional calls to a
java.io.Reader/java.io.Writer after `close()` was called on the same instance.
The other analyzer checks for potential `null` dereferences on paramters
annotated with javax.annotation.Nullable.
Disclaimer
----------
This is not an official Google product (experimental or otherwise), it is just
code that happens to be owned by Google.
Shipshape Module
----------------
The demo analyzers can be plugged into the [Shipshape][1] pipeline. The
Shipshape integration is currently experimental.
Dependencies
------------
To build the Simplified CFG generator you need the following dependencies:
* Git
* Gradle 2.4
* ExtendJ
This repository has a submodule for the ExtendJ compiler. If you did not clone
this repository with the `--recursive` flag you will have to run `git submodule
init` followed by `git submodule update`, this will clone a specific commit from
the ExtendJ repository into the `third_party/extendj/` directory.
Building
--------
Note that you must have the Git submodule `third_party/extendj/git` in
order to build SimpleCFG. To download the submodule, use the following commands:
git submodule init
git submodule update
Build the Simplified CFG generator Jar file by running the following Gradle command:
gradle jar
Testing
-------
The tests may be run by issuing the following command:
gradle test
Most tests check that a well-formed SimpleCFG is built for each Java file in the
testdata directory. The tests are structured so that they test the successors of
each node in the resulting CFG for the single block/method in each of the Java files.
You can generate images for the CFGs in each test file by running the `graph.sh`
shell script.
[1]: https://github.com/google/shipshape
buildscript {
repositories.mavenLocal()
repositories.mavenCentral()
dependencies {
classpath 'org.jastadd:jastaddgradle:1.13.3'
}
}
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'jastadd'
apply plugin: 'idea'
repositories {
mavenLocal()
}
idea {
module {
generatedSourceDirs += file('./src/gen/java')
sourceDirs += file('../extendj/src/frontend')
sourceDirs += file('../extendj/src/frontend-main')
}
}
sourceSets.main {
java {
srcDirs "src/gen/java"
srcDirs '../extendj/src/frontend'
srcDirs '../extendj/src/frontend-main'
}
resources {
srcDir '../extendj/src/res'
srcDir jastadd.buildInfoDir
}
}
dependencies {
testCompile group: 'com.google.truth', name: 'truth', version: '0.27'
}
jastadd {
configureModuleBuild()
modules {
include("../extendj/jastadd_modules")
module "simplecfg", {
imports "java8 frontend"
jastadd {
basedir "src/main/jastadd/"
include "**/*.ast"
include "**/*.jadd"
include "**/*.jrag"
}
java {
basedir "src/main/java/"
include "**/*.java"
}
}
}
// Target module to build:
module = 'simplecfg'
astPackage = 'org.extendj.ast'
parser.name = 'JavaParser'
scanner.name = 'OriginalScanner'
genDir = 'src/gen/java'
parser.genDir = 'src/gen/java/org/extendj/parser'
scanner.genDir = 'src/gen/java/org/extendj/scanner'
//
// if (project.hasProperty('extraJastAddOptions')) {
// extraJastAddOptions += project.extraJastAddOptions.split(',') as List
// print("options: ${extraJastAddOptions}")
// }
}
test {
inputs.dir file('testdata')
}
mainClassName = 'com.google.simplecfg.PrintCfg'
jar.manifest.attributes 'Main-Class': mainClassName
jar.destinationDir = projectDir
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
#!/bin/bash
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
if [ $# -lt "1" ]; then
echo "Error: no input program specified."
exit 1
else
gradle jar
for src in "$@"; do
java -cp simplecfg.jar com.google.simplecfg.TestGenerator "$src"
done
fi
echo "done"
#!/bin/bash
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
gradle jar
gengraph()
{
OUT="${1%%\.javax}.png"
echo "$1 -> $OUT"
java -jar simplecfg.jar "$1" | dot -Tpng > "$OUT"
}
if [ $# -lt "1" ]; then
for f in testdata/*.javax; do
gengraph $f
done
else
gengraph $1
fi
echo "done"
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Adds an analysis checking for calls to an instance of java.io.Writer or java.io.Reader after
* {@code close()} has been called on the same instance.
*
* <p>For each method call to an effectively final variable of type java.io.Closeable,
* we do a breadth-first search on the reverse CFG from the location of that call to see if a
* call to {@code close()} was made on the same instance previously.
*/
aspect AlreadyClosedAnalysis {
MethodAccess contributes alreadyClosedFinding()
when alreadyClosedStream()
to CompilationUnit.findings()
for compilationUnit();
/** Allow MethodAccess to lookup the enclosing compilation unit. */
inh CompilationUnit MethodAccess.compilationUnit();
/** Generate a finding for method call after close() call. */
syn lazy ExtendJFinding MethodAccess.alreadyClosedFinding() =
finding("AlreadyClosed", String.format(
"close() may have already been called on %s at this point",
prevExpr().prettyPrint()));
/** Check if the reciever of this method access was already closed. */
syn boolean MethodAccess.alreadyClosedStream() {
// The receiver must be an effectively final local variable (or parameter).
if (name().equals("close") // Don't check for repeated close() calls.
|| name().equals("toString") || name().equals("toByteArray")
|| !hasPrevExpr() // Does not have a variable or parameter receiver.
|| prevExpr().varDecl() == null // Receiver is not a variable/parameter.
|| !(prevExpr().varDecl().isFinal()
|| prevExpr().varDecl().isEffectivelyFinal()) // Receiver might have changed.
|| !prevExpr().type().isCloseable()) { // Receiver is not instance of java.io.Closeable.
return false;
}
final Variable receiver = prevExpr().varDecl();
return null != call().reverseBfs(new CfgVisitor() {
@Override
public SearchAction processEdge(CfgNode pred, CfgNode succ) {
if (succ.isCloseCall(receiver)) {
if (pred.isException()) {
// This call is interrupted by an exception. Don't continue the search from this node.
return SearchAction.SKIP;
} else {
return SearchAction.SUCCESSOR_MATCH;
}
}
if (succ.isCall(receiver)) {
// Already analyzed from this point.
return SearchAction.SKIP;
}
if (succ.isDeclarationOf(receiver)) {
// Skip this node and don't reconsider any other path that encounters the node.
return SearchAction.IGNORE;
}
return SearchAction.CONTINUE;
}
});
}
/** Test if the CFG node is a call node with the given variable as receiver. */
syn boolean CfgNode.isCall(Variable receiver) = false;
eq CfgMethodCall.isCall(Variable receiver) = methodAccess().hasReceiver(receiver);
/** Test if the CFG node is a call node for receiver.close(). */
syn boolean CfgNode.isCloseCall(Variable receiver) = false;
eq CfgMethodCall.isCloseCall(Variable receiver) =
methodAccess().hasReceiver(receiver) && methodAccess().getID().equals("close");
/** Check if this is a Reader or Writer. */
syn boolean TypeDecl.isCloseable() =
!isUnknown() && instanceOf(lookupType("java.io", "Closeable"));
}
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** A node in a Control Flow Graph (CFG). */
abstract CfgNode;
/** The CFG entry node. */
CfgEntry : CfgNode ::= <Succ:CfgNode>;
/** The CFG exit node. */
CfgExit : CfgNode;
/** A method call in the CFG. */
CfgMethodCall : CfgNode;
/** A conditional branch in the CFG. */
CfgBranch : CfgNode;
/** A branch in the CFG caused by potential thrown exceptions. */
CfgException : CfgNode;
/** A marker node used to mark try block entry points or the end of if-statement branches. */
CfgMarker : CfgNode;
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This aspect adds an API for searching for nodes matching some property in a Control Flow Graph.
*/
aspect CfgSearch {
enum SearchAction {
/**
* The search is complete because the currently processed edge successor matches the search.
*/
SUCCESSOR_MATCH,
/**
* The search is complete because the currently processed edge predecessor matches the search.
*/
PREDECESSOR_MATCH,
/**
* The search should skip adding the successors from the successor of the current edge.
*/
SKIP,
/**
* The search continues as normal, adding successors from the target of the current edge.
*/
CONTINUE,
/**
* The search does not process additional edges to the target of the current edge, and the
* successors of the target node are not added to the work queue.
*/
IGNORE
}
/** A CFG visitor decides which nodes to process based on the current edge (pred, succ). */
interface CfgVisitor {
/**
* Returns the action a Breadth-First search should take for this edge.
* @param pred Edge source.
* @param succ Edge destination.
*/
public SearchAction processEdge(CfgNode pred, CfgNode succ);
}
/**
* Performs a Breadth-First Search over the CFG successors starting from this node.
* @param visitor a visitor that decides when the search is terminated and which
* successors to process
* @return {@code null} if no match was found
*/
public CfgNode CfgNode.bfs(CfgVisitor visitor) {
Set<CfgNode> visited = Collections.newSetFromMap(
new IdentityHashMap<CfgNode, Boolean>());
Queue<CfgNode> work = new LinkedList<CfgNode>();
work.add(this);
while (!work.isEmpty()) {
CfgNode node = work.poll();
for (CfgNode succ : node.successors()) {
if (!visited.contains(succ)) {
switch (visitor.processEdge(node, succ)) {
case SUCCESSOR_MATCH:
return succ;
case PREDECESSOR_MATCH:
return node;
case SKIP:
continue;
case CONTINUE:
work.add(succ);
visited.add(succ);
break;
case IGNORE:
visited.add(succ);
break;
}
}
}
}
// The search matched nothing and we exhausted all successors.
return null;
}
inh lazy CfgEntry CfgNode.cfg();
/**
* Performs a Breadth-First Search over the CFG predecessors starting from this node.
* @param visitor a visitor that decides when the search is terminated and which
* predecessors to process
* @return {@code null} if no match was found
*/
public CfgNode CfgNode.reverseBfs(CfgVisitor visitor) {
Set<CfgNode> visited = Collections.newSetFromMap(
new IdentityHashMap<CfgNode, Boolean>());
cfg().initPredecessors();
Queue<CfgNode> work = new LinkedList<CfgNode>();
work.add(this);
while (!work.isEmpty()) {
CfgNode node = work.poll();
for (CfgNode pred : node.predecessors) {
if (!visited.contains(pred)) {
switch (visitor.processEdge(node, pred)) {
case SUCCESSOR_MATCH:
return pred;
case PREDECESSOR_MATCH:
return node;
case SKIP:
continue;
case CONTINUE:
work.add(pred);
visited.add(pred);
break;
case IGNORE:
visited.add(pred);
break;
}
}
}
}
// The search matched nothing and we exhausted all predecessors.
return null;
}
/** A matcher used to search for particular nodes in a CFG. */
interface CfgMatcher {
public boolean match(CfgNode node);
}
/** Search for a previous node matching the matcher, starting from the current CFG node. */
public CfgNode CfgNode.findPreviousNode(final CfgMatcher matcher) {
return reverseBfs(new CfgVisitor() {
@Override
public SearchAction processEdge(CfgNode pred, CfgNode succ) {
return matcher.match(succ) ? SearchAction.SUCCESSOR_MATCH : SearchAction.CONTINUE;
}
});
}
/** Check if there is a previous node matching the matcher, starting from the current CFG node. */
syn boolean CfgNode.hasPreviousNode(CfgMatcher matcher) = null != findPreviousNode(matcher);
}
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* PlaceholderTypeDecl is used to avoid locating and parsing source or class files when
* analyzing a single file.
* Represents a type that is known to exist but which we don't know anything else about.
*/
PlaceholderTypeDecl : ClassDecl;
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Replace type lookup to avoid parsing extra sources.
* All sources other than the one that is being analyzed is replaced
* by the Unknown type, or a placeholder type - a TypeDecl with just
* a name and package.
*/
aspect ClassPathFilter {
/** The type lookup filter to use during type lookups. */
private TypeLookupFilter Program.typeLookupFilter = NO_TYPE_FILTER;
/** Changes the type lookup filter. */
public void Program.setTypeLookupFilter(TypeLookupFilter filter) {
typeLookupFilter = filter;
}
public interface TypeLookupFilter {
/**
* This allows extra source type map initialization. It is run after the default source type map
* initialization code.
*/
void initializeSourceTypeMap(Program program);
/**
* This allows extra library type map initialization. It is run after the default library type
* map initialization code.
*/
void initializeLibraryTypeMap(Program program);
/**
* Returns the TypeDecl for the requested type. Returns UnknownType if the type was not
* found, or if the type was filtered out by this filter.
*/
TypeDecl lookupSourceType(Program program, String packageName, String typeName);
/**
* Returns the TypeDecl for the requested type. Returns UnknownType if the type was not
* found, or if the type was filtered out by this filter.
*/
TypeDecl lookupLibraryType(Program program, String packageName, String typeName);
}
/** This type filter does not perform any filtering. */
public static final TypeLookupFilter Program.NO_TYPE_FILTER = new TypeLookupFilter() {
@Override
public void initializeSourceTypeMap(Program program) {
}
@Override
public void initializeLibraryTypeMap(Program program) {
}
@Override
public TypeDecl lookupSourceType(Program program, String packageName, String typeName) {
return program.lookupSourceType(packageName, typeName);
}
@Override
public TypeDecl lookupLibraryType(Program program, String packageName, String typeName) {
return program.lookupLibraryType(packageName, typeName);
}
};
/** This type filter filters out library types. */
public static final TypeLookupFilter Program.BASE_LIBRARY_FILTER = new TypeLookupFilter() {
@Override
public void initializeSourceTypeMap(Program program) {
}
@Override
public void initializeLibraryTypeMap(Program program) {
// All types that need to be distinguishable in the code being analyzed
// should be added as placeholders here.
// This list contains all types which are looked up explicitly in the
// ExtendJ frontend code with lookupType(pkg, name) All type lookups that
// don't match a placeholder type get mapped to the Unknown type.
program.addPlaceholderType("java.lang", "Object");
program.addPlaceholderType("java.lang", "AutoCloseable");
program.addPlaceholderType("java.lang", "Class");
program.addPlaceholderType("java.lang", "Cloneable");
program.addPlaceholderType("java.lang", "Error");
program.addPlaceholderType("java.lang", "Exception");
program.addPlaceholderType("java.lang", "FunctionalInterface");
program.addPlaceholderType("java.lang", "NullPointerException");
program.addPlaceholderType("java.lang", "Throwable");
program.addPlaceholderType("java.lang", "Enum");
program.addPlaceholderType("java.lang", "Iterable");
program.addPlaceholderType("java.lang", "Iterator");
program.addPlaceholderType("java.lang", "RuntimeException");
// Annotations and boxed primitive types are required
// to do some simple type analysis.
// Add annotation types.
program.addPlaceholderType("java.lang.annotation", "Target");
program.addPlaceholderType("java.lang.annotation", "Retention");
program.addPlaceholderType("java.lang.annotation", "Inherited");
program.addPlaceholderType("java.lang", "SuppressWarnings");
program.addPlaceholderType("java.lang", "Override");
program.addPlaceholderType("java.lang", "Serializable");
// Boxed primitive types.
program.addPlaceholderType("java.lang", "Integer");
program.addPlaceholderType("java.lang", "Float");
program.addPlaceholderType("java.lang", "Short");
program.addPlaceholderType("java.lang", "Byte");
program.addPlaceholderType("java.lang", "Character");
program.addPlaceholderType("java.lang", "Long");
program.addPlaceholderType("java.lang", "Double");
program.addPlaceholderType("java.lang", "String");
program.addPlaceholderType("java.lang", "Boolean");
program.addPlaceholderType("java.lang", "Void");
}
@Override
public TypeDecl lookupSourceType(Program program, String packageName, String typeName) {
return program.lookupSourceType(packageName, typeName);
}
@Override
public TypeDecl lookupLibraryType(Program program, String packageName, String typeName) {
String fullName = packageName.isEmpty() ? typeName : packageName + "." + typeName;
if (program.libraryTypeMap.containsKey(fullName)) {
return program.libraryTypeMap.get(fullName);
} else {
program.libraryTypeMap.put(fullName, program.unknownType());
return program.unknownType();
}
}
};
public static final TypeLookupFilter Program.ANALYZER_TYPE_FILTER = new TypeLookupFilter() {
@Override
public void initializeSourceTypeMap(Program program) {
BASE_LIBRARY_FILTER.initializeSourceTypeMap(program);
}
@Override
public void initializeLibraryTypeMap(Program program) {
BASE_LIBRARY_FILTER.initializeLibraryTypeMap(program);
// Types needed for read/write after close analysis.
program.addPlaceholderType("java.io", "Writer");
program.addPlaceholderType("java.io", "Reader");
// Types needed for Nullable Dereference analysis.
program.addPlaceholderType("javax.annotation", "Nullable");
}
@Override
public TypeDecl lookupSourceType(Program program, String packageName, String typeName) {
return BASE_LIBRARY_FILTER.lookupSourceType(program, packageName, typeName);
}
@Override
public TypeDecl lookupLibraryType(Program program, String packageName, String typeName) {
return BASE_LIBRARY_FILTER.lookupLibraryType(program, packageName, typeName);
}
};
refine LookupFullyQualifiedTypes
protected void Program.initializeSourceTypeMap() {
refined();
typeLookupFilter.initializeSourceTypeMap(this);
}
refine LookupFullyQualifiedTypes
protected void Program.initializeLibraryTypeMap() {
refined();
typeLookupFilter.initializeLibraryTypeMap(this);
}
refine LookupFullyQualifiedTypes
eq Program.lookupType(String packageName, String typeName) {
TypeDecl sourceType = typeLookupFilter.lookupSourceType(this, packageName, typeName);
if (!sourceType.isUnknown()) {
return sourceType;
}
if (!libraryTypeMapInitialized) {
initializeLibraryTypeMap();
libraryTypeMapInitialized = true;
}
return typeLookupFilter.lookupLibraryType(this, packageName, typeName);
}
/**
* Add a placeholder type declaration to the library type map.
* This triggers evaluation of a placeholder type NTA and a placeholder
* compilation unit NTA.
*/
public void Program.addPlaceholderType(String packageName, String typeName) {
String fullName = packageName.equals("") ? typeName : packageName + "." + typeName;
CompilationUnit cu = placeholderCompilationUnit(packageName);
cu.setFromSource(false);
cu.setClassSource(ClassSource.NONE);
TypeDecl placeholder = cu.placeholderTypeDecl(typeName);
libraryTypeMap.put(fullName, placeholder);
}
/**
* Build a placeholder compilation unit for types in a package.
*/
syn nta CompilationUnit Program.placeholderCompilationUnit(String packageName) {
CompilationUnit u = new CompilationUnit();
u.setPackageDecl(packageName);
return u;
}
/**
* Build placeholder type declaration.
*/
syn nta TypeDecl CompilationUnit.placeholderTypeDecl(String typeName) {
PlaceholderTypeDecl decl = new PlaceholderTypeDecl();
decl.setModifiers(new Modifiers(new List().add(new Modifier("public"))));
decl.setID(typeName);
return decl;
}
}
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Collection;
import java.util.LinkedList;
/**
* This aspect provides the general attributes to collect findings for the
* available analyses.
*/
aspect Findings {
/** Collection of API usage findings. */
coll Collection<ExtendJFinding> CompilationUnit.findings()
[new LinkedList<ExtendJFinding>()]
with add
root CompilationUnit;
/** Build a new finding with the given subcategory and message. */
syn ExtendJFinding ASTNode.finding(String subcategory, String message) {
ASTNode location = locationNode();
return new ExtendJFinding(sourceFile(), subcategory, message,
getLine(location.getStart()), getColumn(location.getStart()),
getLine(location.getEnd()), getColumn(location.getEnd()));
}
/** Find the closest AST node with source location information. */
syn ASTNode ASTNode.locationNode() {
ASTNode node = this;
while (node.getParent() != null && node.getStart() == 0) {
node = node.getParent();
}
return node;
}
/** Find the indentation for the current statement. */
inh String Stmt.indentation();
/** Find the indentation for the current expression. */
inh String Expr.indentation();
/** Find the indentation for the current type declaration. */
inh String TypeDecl.indentation();
eq Block.getChild().indentation() = indentation() + " ";
eq TypeDecl.getChild().indentation() = indentation() + " ";
eq CompilationUnit.getChild().indentation() = "";
eq Program.getChild().indentation() = "";
/** A finding produced by an ExtendJ analyzer. */
public class ExtendJFinding {
public final String sourcePath;
public final String subcategory;
public final String message;
public final int startLine;
public final int startColumn;
public final int endLine;
public final int endColumn;
public final Collection<ExtendJFix> fixes = new ArrayList<>();
/**
* Describes a suggested fix. The suggested fix has a description which does not seem to
* show up in Critique. The new text should end with a newline.
*/
public static class ExtendJFix {
public final String description;
public final int startLine;
public final int endLine;
public final String newText;
ExtendJFix(String description, int startLine, int endLine, String newText) {
this.description = description;
this.startLine = startLine;
this.endLine = endLine;
this.newText = newText;
}
}
public ExtendJFinding(String sourcePath, String subcategory, String message,
int startLine, int startColumn, int endLine, int endColumn) {
this.sourcePath = sourcePath;
this.subcategory = subcategory;
this.message = message;
this.startLine = startLine;
this.startColumn = startColumn;
this.endLine = endLine;
this.endColumn = endColumn;
}
/**
* Set a new suggested fix for this finding.
*/
public ExtendJFinding addFix(String description, int startLine, int endLine, String newText) {
fixes.add(new ExtendJFix(description, startLine, endLine, newText));
return this;
}
@Override
public String toString() {
// This message is printed for each finding when running the CLI.
return String.format("%s:%d:%d: %s", sourcePath, startLine, startColumn, message);
}
}
}
This diff is collapsed.
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.Queue;
/** Helper attributes used to print a CFG in dot graph format. */
aspect PrintCfg {
@Override
public String CfgNode.toString() {
return name();
}
public void BodyDecl.printReverseCfg() {
entry().initPredecessors();
System.out.println("digraph " + graphName() + " {");
exit().printReverseCfg();
System.out.println("}");
}
public void CfgNode.printReverseCfg() {
Set<CfgNode> visited = Collections.newSetFromMap(new IdentityHashMap<CfgNode, Boolean>());
Queue<CfgNode> queue = new LinkedList<CfgNode>();
// Enqueue this node.
visited.add(this);
queue.add(this);
while (!queue.isEmpty()) {
CfgNode work = queue.poll();
System.out.format(" %s%s;\n", work.dotId(), work.dotAttributes());
// Add all out-edges for this node.
for (CfgNode succ : work.predecessors) {
System.out.format(" %s -> %s;\n", work.dotId(), succ.dotId());
if (!visited.contains(succ)) {
visited.add(succ);
queue.add(succ);
}
}
}
}
public void BodyDecl.printCfg() {
System.out.println("digraph " + graphName() + " {");
entry().printCfg();
System.out.println("}");
}
public void CfgNode.printCfg() {
Set<CfgNode> visited = Collections.newSetFromMap(new IdentityHashMap<CfgNode, Boolean>());
Queue<CfgNode> queue = new LinkedList<CfgNode>();
// Enqueue this node.
visited.add(this);
queue.add(this);
while (!queue.isEmpty()) {
CfgNode work = queue.poll();
System.out.format(" %s%s;\n", work.dotId(), work.dotAttributes());
// Add all out-edges for this node.
for (CfgNode succ : work.successors()) {
System.out.format(" %s -> %s;\n", work.dotId(), succ.dotId());
if (!visited.contains(succ)) {
visited.add(succ);
queue.add(succ);
}
}
}
}
syn String BodyDecl.graphName() = "";
eq MethodDecl.graphName() = name();
/**
* The ID for this node in a dot graph.
*/
syn String CfgNode.dotId() = String.format("n%08X", hashCode());
// TODO(joqvist): escape string literals in generated labels.
syn String CfgNode.dotAttributes() = " [label=\"" + name() + "\"]";
eq CfgBranch.dotAttributes() = " [label=\"" + name() + "\",shape=diamond]";
eq CfgException.dotAttributes() = " [label=\"" + name() + "\",shape=box]";
eq CfgMarker.dotAttributes() = " [label=\"" + name() + "\",shape=box]";
syn String CfgNode.name();
eq CfgBranch.name() = branchLabel();
eq CfgEntry.name() = "entry";
eq CfgExit.name() = "exit";
eq CfgException.name() = "exception";
eq CfgMarker.name() = markerName();
eq CfgMethodCall.name() = callLabel();
inh String CfgMethodCall.callLabel();
eq MethodAccess.call().callLabel() = name() + "()";
inh String CfgBranch.branchLabel();
eq IfStmt.branch().branchLabel() = "if (" + getCondition().prettyPrint() + ")";
eq ConditionalExpr.branch().branchLabel() = "if (" + getCondition().prettyPrint() + ")";
eq ForStmt.branch().branchLabel() = "for (" + getCondition().prettyPrint() + ")";
eq WhileStmt.branch().branchLabel() = "while (" + getCondition().prettyPrint() + ")";
eq DoStmt.branch().branchLabel() = "do_while (" + getCondition().prettyPrint() + ")";
eq EnhancedForStmt.branch().branchLabel() = String.format("for (%s %s : %s)",
getVariableDecl().getTypeAccess().prettyPrint(),
getVariableDecl().getID(),
getExpr().prettyPrint());
eq SwitchStmt.branch().branchLabel() = "switch (" + getExpr().prettyPrint() + ")";
inh String CfgMarker.markerName();
eq BreakStmt.marker().markerName() = "break";
eq ContinueStmt.marker().markerName() = "continue";
eq ConditionalExpr.thenEndMarker().markerName() = "then-end";
eq ConditionalExpr.elseEndMarker().markerName() = "else-end";
eq IfStmt.thenEndMarker().markerName() = "then-end";
eq IfStmt.elseEndMarker().markerName() = "else-end";
eq ReturnStmt.marker().markerName() = "return";
eq TryStmt.tryEntryMarker().markerName() = "try";
eq Program.getChild().markerName() = "marker";
eq Dot.nullableDereferenceMarker().markerName() = "nullable access";
eq ForStmt.loopEndMarker().markerName() = "for-end";
eq EnhancedForStmt.loopEndMarker().markerName() = "for-end";
eq WhileStmt.loopEndMarker().markerName() = "while-end";
eq DoStmt.doEntryMarker().markerName() = "do-entry";
}
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Set;
import java.util.Collections;
import java.util.Queue;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Queue;
import java.util.LinkedList;
/** Attributes useful for generating a test case from a CFG. */
aspect PrintCfgTest {
/** Generate a test case from the CFG of this body decl. */
public void BodyDecl.printCfgTest() {
CfgNode entry = entry();
String className = hostType().name();
String testName = className.substring(0, 1).toLowerCase()
+ className.substring(1);
System.out.println(" @Test public void " + testName + "() {");
System.out.println(" CfgNode entry = parseCfg(\"" + className + "\");");
Queue<CfgNode> work = new LinkedList<CfgNode>();
Set<CfgNode> visited = Collections.newSetFromMap(
new IdentityHashMap<CfgNode, Boolean>());
visited.add(entry);
Map<CfgNode, String> vars = new HashMap<CfgNode, String>();
vars.put(entry, entry.toString());
Map<String, Integer> nextIds = new HashMap<String, Integer>();
nextIds.put("entry", 2);
work.add(entry);
while (!work.isEmpty()) {
CfgNode node = work.poll();
boolean testSuccs = node.printAssert(visited, vars, nextIds);
if (testSuccs) {
for (CfgNode succ : node.successors()) {
if (!visited.contains(succ)) {
visited.add(succ);
work.add(succ);
}
}
}
}
System.out.println(" }");
}
/**
* @return {@code true} if successors should be tested.
*/
protected boolean CfgNode.printAssert(
Set<CfgNode> visited,
Map<CfgNode, String> vars,
Map<String, Integer> nextIds) {
Set<? extends CfgNode> successors = successors();
if (successors.size() == 1) {
CfgNode succ = successors.iterator().next();
String nodeName = nextVarName(succ.varName(), nextIds);
if (!visited.contains(succ)) {
vars.put(succ, nodeName);
System.out.println(String.format(
" CfgNode %s = succ(%s, \"%s\");",
nodeName, vars.get(this), succ.name()));
} else {
System.out.println(String.format(
" assertThat(succ(%s, \"%s\")).isSameAs(%s);",
vars.get(this), succ.name(), vars.get(succ)));
}
} else if (successors.size() > 1) {
boolean duplicates = false;
Set<String> dups = new HashSet<String>();
for (CfgNode succ : successors) {
if (dups.contains(succ.name())) {
duplicates = true;
break;
}
dups.add(succ.name());
}
if (duplicates) {
System.out.print(String.format(
" assertThat(%s.successors()).containsExactly(\"",
vars.get(this)));
boolean first = true;
for (CfgNode succ : successors) {
if (!first) {
System.out.print("\", \"");
}
first = false;
System.out.print(succ.name());
}
System.out.println("\");");
System.out.println(String.format(
" // NOTE Code to test the successors of %s was not "
+ "auto-generated\n // due to identical successor names.",
vars.get(this)));
return false;
} else {
String arrayName = nextVarName(this.varName() + "Succ", nextIds);
System.out.print(String.format(
" CfgNode[] %s = succ(%s",
arrayName, vars.get(this)));
int index = 0;
Map<String, CfgNode> succMap = new HashMap<String, CfgNode>();
for (CfgNode succ : successors) {
System.out.format(", \"%s\"", succ.name());
succMap.put(arrayName + "[" + index + "]", succ);
index += 1;
}
System.out.println(");");
for (Map.Entry<String, CfgNode> succ : succMap.entrySet()) {
if (!visited.contains(succ.getValue())) {
vars.put(succ.getValue(), succ.getKey());
} else {
System.out.println(String.format(
" assertThat(%s).isSameAs(%s);",
succ.getKey(), vars.get(succ.getValue())));
}
}
}
}
return true;
}
protected static String CfgNode.nextVarName(String name,
Map<String, Integer> nextIds) {
if (nextIds.containsKey(name)) {
int id = nextIds.get(name);
nextIds.put(name, id+1);
return name + id;
} else {
nextIds.put(name, 2);
return name;
}
}
syn String CfgNode.varName() = name();
eq CfgBranch.varName() = branchKind() + "Branch";
eq CfgException.varName() = "exception";
eq CfgMarker.varName() = markerVarName();
eq CfgMethodCall.varName() = methodAccess().getID();
inh String CfgBranch.branchKind();
eq IfStmt.branch().branchKind() = "if";
eq ConditionalExpr.branch().branchKind() = "if";
eq ForStmt.branch().branchKind() = "for";
eq WhileStmt.branch().branchKind() = "while";
eq DoStmt.branch().branchKind() = "doWhile";
eq EnhancedForStmt.branch().branchKind() = "for";
eq SwitchStmt.branch().branchKind() = "switch";
inh String CfgMarker.markerVarName();
eq BreakStmt.marker().markerVarName() = "breakMarker";
eq ContinueStmt.marker().markerVarName() = "continueMarker";
eq ConditionalExpr.thenEndMarker().markerVarName() = "thenEnd";
eq ConditionalExpr.elseEndMarker().markerVarName() = "elseEnd";
eq IfStmt.thenEndMarker().markerVarName() = "thenEnd";
eq IfStmt.elseEndMarker().markerVarName() = "elseEnd";
eq ReturnStmt.marker().markerVarName() = "returnMarker";
eq TryStmt.tryEntryMarker().markerVarName() = "tryEntry";
eq Program.getChild().markerVarName() = "marker";
eq Dot.nullableDereferenceMarker().markerVarName() = "nullable";
eq ForStmt.loopEndMarker().markerVarName() = "forEnd";
eq EnhancedForStmt.loopEndMarker().markerVarName() = "forEnd";
eq WhileStmt.loopEndMarker().markerVarName() = "whileEnd";
eq DoStmt.doEntryMarker().markerVarName() = "doEntry";
}
This diff is collapsed.
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This aspect adds attributes to check if a variable was declared inside an a statement represented
* by a particular CFG node.
*/
aspect VariableDeclarationScope {
/** @return {@code true} if this method access has the given variable as receiver. */
syn boolean MethodAccess.hasReceiver(Variable receiver) =
hasPrevExpr() && prevExpr().isVariable(receiver);
/**
* Test if the CFG node is tied to a statement that declares the variable,
* or if the declaration of the variable is somewhere inside the statement this
* branch represents.
*/
syn boolean CfgNode.isDeclarationOf(Variable var) = false;
eq CfgBranch.isDeclarationOf(Variable var) =
branchDeclaresVariable(var)
|| variableDeclaredInsideStatement(var);
syn boolean CfgBranch.variableDeclaredInsideStatement(Variable var) {
Stmt stmt = hostStatement();
ASTNode node = (ASTNode) var;
while (node != stmt && node != null) {
node = node.getParent();
}
return node == stmt;
}
/** The statement this branch represents. */
inh Stmt CfgBranch.hostStatement();
/** The statement this expression is part of. */
inh Stmt Expr.hostStatement();
eq Stmt.getChild().hostStatement() = this;
eq Program.getChild().hostStatement() = null;
eq IfStmt.branch().hostStatement() = this;
eq ConditionalExpr.branch().hostStatement() = hostStatement();
eq ForStmt.branch().hostStatement() = this;
eq WhileStmt.branch().hostStatement() = this;
eq DoStmt.branch().hostStatement() = this;
eq EnhancedForStmt.branch().hostStatement() = this;
eq SwitchStmt.branch().hostStatement() = this;
/** Test if the CFG node is tied to a statement that declares the variable. */
inh boolean CfgBranch.branchDeclaresVariable(Variable var);
eq EnhancedForStmt.branch().branchDeclaresVariable(Variable var) =
getVariableDecl() == var;
eq IfStmt.branch().branchDeclaresVariable(Variable var) = false;
eq ConditionalExpr.branch().branchDeclaresVariable(Variable var) = false;
eq ForStmt.branch().branchDeclaresVariable(Variable var) = false;
eq WhileStmt.branch().branchDeclaresVariable(Variable var) = false;
eq DoStmt.branch().branchDeclaresVariable(Variable var) = false;
eq SwitchStmt.branch().branchDeclaresVariable(Variable var) = false;
}
/**
* Copyright 2015 Google Inc. All Rights Reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.simplecfg;
import org.extendj.ExtendJVersion;
import org.extendj.ast.CompilationUnit;
import org.extendj.ast.ExtendJFinding;
import org.extendj.ast.Frontend;
import org.extendj.ast.Program;
import java.util.ArrayList;
import java.util.Collection;
/**
* Produces findings using analyzers implemented in the ExtendJ compiler.
*/
public class ExtendJAnalyzerFrontend extends Frontend {
private final Collection<ExtendJFinding> findings = new ArrayList<>();
public ExtendJAnalyzerFrontend() {
super("Simple CFG Checker", ExtendJVersion.getVersion());
}
/**
* Analyze a single file for findings and return the findings in a collection.
*/
public static Collection<ExtendJFinding> analyzeFile(final String path) throws Error {
ExtendJAnalyzerFrontend checker = new ExtendJAnalyzerFrontend();
int result = checker.run(new String[]{path});
if (result != EXIT_SUCCESS) {
throw new Error("exit code: " + result);
}
return checker.findings;
}
/**
* Returns the list of findings from the analyzed source files.
*
* <p>Used by ExtendJAnalyzerMain to print the generated findings on stdout.
*/
Collection<ExtendJFinding> getFindings() {
return findings;
}
/**
* Run the Java checker.
*
* @param args command-line arguments
* @return 0 on success, 1 on error, 2 on configuration error, 3 on system
*/
public int run(String[] args) {
return run(args, Program.defaultBytecodeReader(), Program.defaultJavaParser());
}
@Override
protected int processCompilationUnit(CompilationUnit unit) {
super.processCompilationUnit(unit);
if (unit.fromSource()) {
findings.addAll(unit.findings());
}
return EXIT_SUCCESS;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment