Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Achim D. Brucker 2018-04-05 23:19:36 +01:00
commit f6c663c238
658 changed files with 5196 additions and 7764 deletions

View File

@ -1,4 +1,7 @@
language: android
android:
components:
- build-tools-26.0.2
jdk: oraclejdk8
addons:
apt:
@ -6,6 +9,7 @@ addons:
- realpath
- xvfb
before_install:
- echo $ANDROID_HOME
- git clone --depth=1 https://github.com/secure-software-engineering/DroidBench.git /tmp/DroidBench
- export M2_HOME=$HOME/apache-maven-3.5.0
- if [ ! -d $M2_HOME/bin ]; then curl https://archive.apache.org/dist/maven/maven-3/3.5.0/binaries/apache-maven-3.5.0-bin.tar.gz | tar zxf - -C $HOME; fi

277
LICENSE Normal file
View File

@ -0,0 +1,277 @@
Eclipse Public License - v 2.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial content
Distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program originate from
and are Distributed by that particular Contributor. A Contribution
"originates" from a Contributor if it was added to the Program by
such Contributor itself or anyone acting on such Contributor's behalf.
Contributions do not include changes or additions to the Program that
are not Modified Works.
"Contributor" means any person or entity that Distributes the Program.
"Licensed Patents" mean patent claims licensable by a Contributor which
are necessarily infringed by the use or sale of its Contribution alone
or when combined with the Program.
"Program" means the Contributions Distributed in accordance with this
Agreement.
"Recipient" means anyone who receives the Program under this Agreement
or any Secondary License (as applicable), including Contributors.
"Derivative Works" shall mean any work, whether in Source Code or other
form, that is based on (or derived from) the Program and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship.
"Modified Works" shall mean any work in Source Code or other form that
results from an addition to, deletion from, or modification of the
contents of the Program, including, for purposes of clarity any new file
in Source Code form that contains any contents of the Program. Modified
Works shall not include works that contain only declarations,
interfaces, types, classes, structures, or files of the Program solely
in each case in order to link to, bind by name, or subclass the Program
or Modified Works thereof.
"Distribute" means the acts of a) distributing or b) making available
in any manner that enables the transfer of a copy.
"Source Code" means the form of a Program preferred for making
modifications, including but not limited to software source code,
documentation source, and configuration files.
"Secondary License" means either the GNU General Public License,
Version 2.0, or any later versions of that license, including any
exceptions or additional permissions as identified by the initial
Contributor.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each Contributor hereby
grants Recipient a non-exclusive, worldwide, royalty-free copyright
license to reproduce, prepare Derivative Works of, publicly display,
publicly perform, Distribute and sublicense the Contribution of such
Contributor, if any, and such Derivative Works.
b) Subject to the terms of this Agreement, each Contributor hereby
grants Recipient a non-exclusive, worldwide, royalty-free patent
license under Licensed Patents to make, use, sell, offer to sell,
import and otherwise transfer the Contribution of such Contributor,
if any, in Source Code or other form. This patent license shall
apply to the combination of the Contribution and the Program if, at
the time the Contribution is added by the Contributor, such addition
of the Contribution causes such combination to be covered by the
Licensed Patents. The patent license shall not apply to any other
combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor grants the
licenses to its Contributions set forth herein, no assurances are
provided by any Contributor that the Program does not infringe the
patent or other intellectual property rights of any other entity.
Each Contributor disclaims any liability to Recipient for claims
brought by any other entity based on infringement of intellectual
property rights or otherwise. As a condition to exercising the
rights and licenses granted hereunder, each Recipient hereby
assumes sole responsibility to secure any other intellectual
property rights needed, if any. For example, if a third party
patent license is required to allow Recipient to Distribute the
Program, it is Recipient's responsibility to acquire that license
before distributing the Program.
d) Each Contributor represents that to its knowledge it has
sufficient copyright rights in its Contribution, if any, to grant
the copyright license set forth in this Agreement.
e) Notwithstanding the terms of any Secondary License, no
Contributor makes additional grants to any Recipient (other than
those set forth in this Agreement) as a result of such Recipient's
receipt of the Program under the terms of a Secondary License
(if permitted under the terms of Section 3).
3. REQUIREMENTS
3.1 If a Contributor Distributes the Program in any form, then:
a) the Program must also be made available as Source Code, in
accordance with section 3.2, and the Contributor must accompany
the Program with a statement that the Source Code for the Program
is available under this Agreement, and informs Recipients how to
obtain it in a reasonable manner on or through a medium customarily
used for software exchange; and
b) the Contributor may Distribute the Program under a license
different than this Agreement, provided that such license:
i) effectively disclaims on behalf of all other Contributors all
warranties and conditions, express and implied, including
warranties or conditions of title and non-infringement, and
implied warranties or conditions of merchantability and fitness
for a particular purpose;
ii) effectively excludes on behalf of all other Contributors all
liability for damages, including direct, indirect, special,
incidental and consequential damages, such as lost profits;
iii) does not attempt to limit or alter the recipients' rights
in the Source Code under section 3.2; and
iv) requires any subsequent distribution of the Program by any
party to be under a license that satisfies the requirements
of this section 3.
3.2 When the Program is Distributed as Source Code:
a) it must be made available under this Agreement, or if the
Program (i) is combined with other material in a separate file or
files made available under a Secondary License, and (ii) the initial
Contributor attached to the Source Code the notice described in
Exhibit A of this Agreement, then the Program may be made available
under the terms of such Secondary Licenses, and
b) a copy of this Agreement must be included with each copy of
the Program.
3.3 Contributors may not remove or alter any copyright, patent,
trademark, attribution notices, disclaimers of warranty, or limitations
of liability ("notices") contained within the Program from any copy of
the Program which they Distribute, provided that Contributors may add
their own appropriate notices.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain responsibilities
with respect to end users, business partners and the like. While this
license is intended to facilitate the commercial use of the Program,
the Contributor who includes the Program in a commercial product
offering should do so in a manner which does not create potential
liability for other Contributors. Therefore, if a Contributor includes
the Program in a commercial product offering, such Contributor
("Commercial Contributor") hereby agrees to defend and indemnify every
other Contributor ("Indemnified Contributor") against any losses,
damages and costs (collectively "Losses") arising from claims, lawsuits
and other legal actions brought by a third party against the Indemnified
Contributor to the extent caused by the acts or omissions of such
Commercial Contributor in connection with its distribution of the Program
in a commercial product offering. The obligations in this section do not
apply to any claims or Losses relating to any actual or alleged
intellectual property infringement. In order to qualify, an Indemnified
Contributor must: a) promptly notify the Commercial Contributor in
writing of such claim, and b) allow the Commercial Contributor to control,
and cooperate with the Commercial Contributor in, the defense and any
related settlement negotiations. The Indemnified Contributor may
participate in any such claim at its own expense.
For example, a Contributor might include the Program in a commercial
product offering, Product X. That Contributor is then a Commercial
Contributor. If that Commercial Contributor then makes performance
claims, or offers warranties related to Product X, those performance
claims and warranties are such Commercial Contributor's responsibility
alone. Under this section, the Commercial Contributor would have to
defend claims against the other Contributors related to those performance
claims and warranties, and if a court requires any other Contributor to
pay any damages as a result, the Commercial Contributor must pay
those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
PERMITTED BY APPLICABLE LAW, THE PROGRAM IS PROVIDED 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. Each Recipient is solely responsible for determining the
appropriateness of using and distributing the Program and assumes all
risks associated with its exercise of rights under this Agreement,
including but not limited to the risks and costs of program errors,
compliance with applicable laws, damage to or loss of data, programs
or equipment, and unavailability or interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, AND TO THE EXTENT
PERMITTED BY APPLICABLE LAW, NEITHER RECIPIENT NOR ANY CONTRIBUTORS
SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this Agreement, and without further
action by the parties hereto, such provision shall be reformed to the
minimum extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the
Program itself (excluding combinations of the Program with other software
or hardware) infringes such Recipient's patent(s), then such Recipient's
rights granted under Section 2(b) shall terminate as of the date such
litigation is filed.
All Recipient's rights under this Agreement shall terminate if it
fails to comply with any of the material terms or conditions of this
Agreement and does not cure such failure in a reasonable period of
time after becoming aware of such noncompliance. If all Recipient's
rights under this Agreement terminate, Recipient agrees to cease use
and distribution of the Program as soon as reasonably practicable.
However, Recipient's obligations under this Agreement and any licenses
granted by Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this Agreement,
but in order to avoid inconsistency the Agreement is copyrighted and
may only be modified in the following manner. The Agreement Steward
reserves the right to publish new versions (including revisions) of
this Agreement from time to time. No one other than the Agreement
Steward has the right to modify this Agreement. The Eclipse Foundation
is the initial Agreement Steward. The Eclipse Foundation may assign the
responsibility to serve as the Agreement Steward to a suitable separate
entity. Each new version of the Agreement will be given a distinguishing
version number. The Program (including Contributions) may always be
Distributed subject to the version of the Agreement under which it was
received. In addition, after a new version of the Agreement is published,
Contributor may elect to Distribute the Program (including its
Contributions) under the new version.
Except as expressly stated in Sections 2(a) and 2(b) above, Recipient
receives no rights or licenses to the intellectual property of any
Contributor under this Agreement, whether expressly, by implication,
estoppel or otherwise. All rights in the Program not expressly granted
under this Agreement are reserved. Nothing in this Agreement is intended
to be enforceable by any entity that is not a Contributor or Recipient.
No third-party beneficiary rights are created under this Agreement.
Exhibit A - Form of Secondary Licenses Notice
"This Source Code may also be made available under the following
Secondary Licenses when the conditions for such availability set forth
in the Eclipse Public License, v. 2.0 are satisfied: {name license(s),
version(s), and exceptions or additional permissions here}."
Simply including a copy of this Agreement, including this Exhibit A
is not sufficient to license the Source Code under Secondary Licenses.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to
look for such a notice.
You may add additional accurate notices of copyright ownership.

View File

@ -16,7 +16,7 @@ org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=error
org.eclipse.jdt.core.compiler.problem.comparingIdentical=error
org.eclipse.jdt.core.compiler.problem.deadCode=error
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecation=ignore
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=error

View File

@ -106,8 +106,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

View File

@ -52,8 +52,8 @@ public class SourceDirCallGraph {
AnalysisScope scope = new JavaSourceAnalysisScope();
// add standard libraries to scope
String[] stdlibs = WalaProperties.getJ2SEJarFiles();
for (int i = 0; i < stdlibs.length; i++) {
scope.addToScope(ClassLoaderReference.Primordial, new JarFile(stdlibs[i]));
for (String stdlib : stdlibs) {
scope.addToScope(ClassLoaderReference.Primordial, new JarFile(stdlib));
}
// add the source directory
scope.addToScope(JavaSourceAnalysisScope.SOURCE, new SourceDirectoryTreeModule(new File(sourceDir)));

View File

@ -174,7 +174,6 @@ public class JDT2CAstUtils {
* Returns true if type is char, byte, short, int, or long. Return false otherwise (including boolean!)
*
* @param type
* @return
*/
public static boolean isLongOrLess(ITypeBinding type) {
String t = type.getBinaryName();
@ -186,7 +185,6 @@ public class JDT2CAstUtils {
* CAstSymbol.NULL_DEFAULT_VALUE.
*
* @param type
* @return
*/
public static Object defaultValueForType(ITypeBinding type) {
if (isLongOrLess(type))
@ -237,7 +235,6 @@ public class JDT2CAstUtils {
*
* @param returnType
* @param ast
* @return
*/
public static ITypeBinding getErasedType(ITypeBinding returnType, AST ast) {
if (returnType.isTypeVariable() || returnType.isCapture())

View File

@ -42,7 +42,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@ -254,8 +253,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
List<CAstEntity> declEntities = new ArrayList<>();
for (Iterator<CAstEntity> iter = cu.types().iterator(); iter.hasNext();) {
AbstractTypeDeclaration decl = (AbstractTypeDeclaration) iter.next();
for (AbstractTypeDeclaration decl : (Iterable<AbstractTypeDeclaration>) cu.types()) {
// can be of type AnnotationTypeDeclaration, EnumDeclaration, TypeDeclaration
declEntities.add(visit(decl, new RootContext()));
}
@ -413,7 +411,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
* @param typeBinding
* @param name Used in creating default constructor, and passed into new ClassEntity()
* @param context
* @return
*/
private CAstEntity createClassDeclaration(ASTNode n, List<BodyDeclaration> bodyDecls,
List<EnumConstantDeclaration> enumConstants, ITypeBinding typeBinding, String name, int modifiers,
@ -427,13 +424,11 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
ArrayList<ASTNode> staticInits = new ArrayList<>();
if (enumConstants != null) {
for (Object decl : enumConstants) {
EnumConstantDeclaration ecd = (EnumConstantDeclaration) decl;
staticInits.add(ecd); // always (implicitly) static,final (actually, no modifiers allowed)
}
// always (implicitly) static,final (actually, no modifiers allowed)
staticInits.addAll(enumConstants);
}
for (Object decl : bodyDecls) {
for (BodyDeclaration decl : bodyDecls) {
if (decl instanceof Initializer) {
Initializer initializer = (Initializer) decl;
boolean isStatic = ((initializer.getModifiers() & Modifier.STATIC) != 0);
@ -441,8 +436,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
} else if (decl instanceof FieldDeclaration) {
FieldDeclaration fd = (FieldDeclaration) decl;
for (Object f : fd.fragments()) {
VariableDeclarationFragment frag = (VariableDeclarationFragment) f;
for (VariableDeclarationFragment frag : (Iterable<VariableDeclarationFragment>) fd.fragments()) {
if (frag.getInitializer() != null) {
boolean isStatic = ((fd.getModifiers() & Modifier.STATIC) != 0);
(isStatic ? staticInits : inits).add(frag);
@ -453,18 +447,16 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
// process entities. initializers will be folded in here.
if (enumConstants != null) {
for (Object decl : enumConstants) {
memberEntities.add(visit((EnumConstantDeclaration) decl, context));
for (EnumConstantDeclaration decl : enumConstants) {
memberEntities.add(visit(decl, context));
}
}
for (Object d : bodyDecls) {
BodyDeclaration decl = (BodyDeclaration) d;
for (BodyDeclaration decl : bodyDecls) {
if (decl instanceof FieldDeclaration) {
FieldDeclaration fieldDecl = (FieldDeclaration) decl;
Collection<CAstQualifier> quals = JDT2CAstUtils.mapModifiersToQualifiers(fieldDecl.getModifiers(), false, false);
for (Object f : fieldDecl.fragments()) {
VariableDeclarationFragment fieldFrag = (VariableDeclarationFragment) f;
for (VariableDeclarationFragment fieldFrag : (Iterable<VariableDeclarationFragment>) fieldDecl.fragments()) {
IVariableBinding fieldBinding = fieldFrag.resolveBinding();
memberEntities.add(new FieldEntity(fieldFrag.getName().getIdentifier(), fieldBinding.getType(), quals,
makePosition(fieldFrag.getStartPosition(), fieldFrag.getStartPosition() + fieldFrag.getLength()),
@ -500,8 +492,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
// add default constructor(s) if necessary
// most default constructors have no parameters; however, those created by anonymous classes will have parameters
// (they just call super with those parameters)
for (Object m : typeBinding.getDeclaredMethods()) {
IMethodBinding met = (IMethodBinding) m;
for (IMethodBinding met : typeBinding.getDeclaredMethods()) {
if (met.isDefaultConstructor()) {
if (typeBinding.isEnum())
memberEntities.add(createEnumConstructorWithParameters(met, n, context, inits, null));
@ -657,7 +648,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
* constructor.
* @param context
* @param inits
* @return
*/
private CAstNode createConstructorBody(MethodDeclaration n, ITypeBinding classBinding, WalkContext context,
ArrayList<ASTNode> inits) {
@ -729,7 +719,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
* @param overriding Declaration of the overriding method.
* @param overridden Binding of the overridden method, in a a superclass or implemented interface.
* @param oldContext
* @return
*/
private CAstEntity makeSyntheticCovariantRedirect(MethodDeclaration overriding, IMethodBinding overridingBinding,
IMethodBinding overridden, WalkContext oldContext) {
@ -751,8 +740,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
ArrayList<CAstNode> arguments = new ArrayList<>();
int i = 0;
for (Object o : overriding.parameters()) {
SingleVariableDeclaration svd = (SingleVariableDeclaration) o;
for (SingleVariableDeclaration svd : (Iterable<SingleVariableDeclaration>) overriding.parameters()) {
CAstNode varNode = makeNode(context, fFactory, null, CAstNode.VAR, fFactory.makeConstant(svd.getName().getIdentifier()));
ITypeBinding fromType = JDT2CAstUtils.getErasedType(paramTypes[i], ast);
ITypeBinding toType = JDT2CAstUtils.getErasedType(overridingBinding.getParameterTypes()[i], ast);
@ -941,16 +929,16 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
if (parameterTypes == null) {
fParameterTypes = new ArrayList<>(fDecl.parameters().size());
for (Object p : fDecl.parameters()) {
fParameterNames[i++] = ((SingleVariableDeclaration) p).getName().getIdentifier();
fParameterTypes.add(fTypeDict.getCAstTypeFor(((SingleVariableDeclaration) p).resolveBinding().getType()));
for (SingleVariableDeclaration p : (Iterable<SingleVariableDeclaration>) fDecl.parameters()) {
fParameterNames[i++] = p.getName().getIdentifier();
fParameterTypes.add(fTypeDict.getCAstTypeFor(p.resolveBinding().getType()));
}
} else {
// currently this is only used in making a default constructor with arguments (anonymous classes).
// this is because we cannot synthesize bindings.
fParameterTypes = parameterTypes;
for (Object p : fDecl.parameters()) {
fParameterNames[i++] = ((SingleVariableDeclaration) p).getName().getIdentifier();
for (SingleVariableDeclaration p : (Iterable<SingleVariableDeclaration>) fDecl.parameters()) {
fParameterNames[i++] = p.getName().getIdentifier();
}
}
} else {
@ -1044,7 +1032,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
private Collection<CAstType> fExceptionTypes = null;
@Override
@SuppressWarnings("deprecation")
public CAstType getReturnType() {
if (fReturnType != null)
return fTypeDict.getCAstTypeFor(fReturnType);
@ -1088,9 +1075,9 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
if (fExceptionTypes == null) {
fExceptionTypes = new LinkedHashSet<>();
if (fDecl != null)
for (Object exception : fDecl.thrownExceptionTypes())
for (SimpleType exception : (Iterable<SimpleType>) fDecl.thrownExceptionTypes())
fExceptionTypes.add(fTypeDict.getCAstTypeFor(((SimpleType) exception).resolveBinding()));
fExceptionTypes.add(fTypeDict.getCAstTypeFor(exception.resolveBinding()));
}
return fExceptionTypes;
}
@ -1264,8 +1251,8 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
*/
private ArrayList<CAstNode> createBlock(Block n, WalkContext context) {
ArrayList<CAstNode> stmtNodes = new ArrayList<>();
for (Object s : n.statements())
visitNodeOrNodes((ASTNode) s, context, stmtNodes);
for (ASTNode s : (Iterable<ASTNode>) n.statements())
visitNodeOrNodes(s, context, stmtNodes);
return stmtNodes;
}
@ -1311,8 +1298,8 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
private ArrayList<CAstNode> visit(VariableDeclarationStatement n, WalkContext context) {
ArrayList<CAstNode> result = new ArrayList<>();
for (Object o : n.fragments())
result.add(visit((VariableDeclarationFragment) o, context));
for (VariableDeclarationFragment o : (Iterable<VariableDeclarationFragment>) n.fragments())
result.add(visit(o, context));
return result;
}
@ -1325,11 +1312,11 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
eltNodes[idx++] = makeNode(context, fFactory, n, CAstNode.NEW, fFactory.makeConstant(newTypeRef), fFactory.makeConstant(n
.expressions().size()));
for (Iterator<CAstEntity> iter = n.expressions().iterator(); iter.hasNext(); idx++) {
Expression element = (Expression) iter.next();
for (Expression element : (Iterable<Expression>) n.expressions()) {
eltNodes[idx] = visitNode(element, context);
if (eltNodes[idx] == null)
assert eltNodes[idx] != null : element.toString();
++idx;
}
return makeNode(context, fFactory, n, CAstNode.ARRAY_LITERAL, eltNodes);
@ -1412,8 +1399,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
argNodes[idx++] = fFactory.makeConstant(callSiteRef);
// rest of args
for (Iterator<?> iter = arguments.iterator(); iter.hasNext();) {
Object arg = iter.next();
for (Object arg : arguments) {
argNodes[idx++] = (arg instanceof CAstNode) ? ((CAstNode) arg) : visitNode((Expression) arg, context);
}
callNode = makeNode(context, fFactory, nn, CAstNode.CALL, argNodes);
@ -1676,7 +1662,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
* the code into an assignment and binary operation.
*
* @param context
* @return
*/
private CAstNode doFunkyGenericAssignPreOpHack(Assignment assign, WalkContext context) {
Expression left = assign.getLeftHandSide();
@ -1762,7 +1747,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
*
* @param n
* @param context
* @return
*/
private CAstNode visit(SimpleName n, WalkContext context) {
// class name, handled above in either method invocation, qualified name, or qualified this
@ -1829,7 +1813,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
*
* @param typeOfThis
* @param isPrivate
* @return
*/
private static ITypeBinding findClosestEnclosingClassSubclassOf(ITypeBinding typeOfThis, ITypeBinding owningType, boolean isPrivate) {
// GENERICS
@ -1877,7 +1860,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
*
* @param n
* @param context
* @return
*/
private CAstNode visit(FieldAccess n, WalkContext context) {
CAstNode targetNode = visitNode(n.getExpression(), context);
@ -1894,7 +1876,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
* @param fieldName Name of the field.
* @param positioningNode Used only for making a JdtPosition.
* @param context
* @return
*/
private CAstNode createFieldAccess(CAstNode targetNode, String fieldName, IVariableBinding possiblyParameterizedBinding,
ASTNode positioningNode, WalkContext context) {
@ -1989,7 +1970,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
*
* @param n
* @param context
* @return
*/
private CAstNode visit(QualifiedName n, WalkContext context) {
// "package.Class" is a QualifiedName, but also is "Class.staticField"
@ -2022,8 +2002,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
// keep on adding operands on the right side
leftLength = n.getRightOperand().getStartPosition() + n.getRightOperand().getLength() - leftStartPosition;
for (Object o : n.extendedOperands()) {
Expression operand = (Expression) o;
for (Expression operand : (Iterable<Expression>) n.extendedOperands()) {
result = createInfixExpression(n.getOperator(), leftType, leftStartPosition, leftLength, result, operand, context);
if (leftType.isPrimitive() && operand.resolveTypeBinding().isPrimitive())
@ -2390,8 +2369,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
ArrayList<CAstNode> currentBlock = new ArrayList<>();
// Now produce the CAst representation for each case
for (Object o : cases) {
Statement s = (Statement) o;
for (Statement s : cases) {
if (s instanceof SwitchCase) {
if (!currentBlock.isEmpty()) {
// bundle up statements before this case
@ -2451,12 +2429,11 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
/**
* Expands the form: for ( [final] Type var: iterable ) { ... } Into something equivalent to: for ( Iterator iter =
* iterable.iter(); iter.hasNext(); ) { [final] Type var = (Type) iter.next(); ... } Or, in the case of an array: for ( int idx =
* 0; i < iterable.length; i++ ) { [final] Type var = iterable[idx]; ... } Except that the expression "iterable" is only evaluate
* 0; i &lt; iterable.length; i++ ) { [final] Type var = iterable[idx]; ... } Except that the expression "iterable" is only evaluate
* once (or is it?)
*
* @param n
* @param context
* @return
*/
private CAstNode visit(EnhancedForStatement n, WalkContext context) {
if (n.getExpression().resolveTypeBinding().isArray())
@ -2637,8 +2614,8 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
for (int i = 0; i < n.initializers().size(); i++) {
ASTNode init = (ASTNode) n.initializers().get(i);
if (init instanceof VariableDeclarationExpression) {
for (Object o : ((VariableDeclarationExpression) init).fragments())
inits.add(visitNode((ASTNode) o, context));
for (ASTNode o : (Iterable<ASTNode>) ((VariableDeclarationExpression) init).fragments())
inits.add(visitNode(o, context));
} else
inits.add(visitNode(init, context));
}
@ -2804,7 +2781,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
* Giant switch statement.
*
* @param n
* @return
*/
private CAstEntity visit(AbstractTypeDeclaration n, WalkContext context) {
// handling of compilationunit in translate()
@ -2824,7 +2800,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
* Giant switch statement, part deux
*
* @param context
* @return
*/
private CAstNode visitNode(ASTNode n, WalkContext context) {
if (n == null)
@ -3128,8 +3103,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
TryCatchContext(WalkContext parent, TryStatement tryNode) {
super(parent);
for (Iterator<CatchClause> catchIter = tryNode.catchClauses().iterator(); catchIter.hasNext();) {
CatchClause c = catchIter.next();
for (CatchClause c : (Iterable<CatchClause>) tryNode.catchClauses()) {
Pair<ITypeBinding, Object> p = Pair.make(c.getException().resolveBinding().getType(), (Object) c);
fCatchNodes.add(p);
@ -3334,7 +3308,6 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
*
* @param decl
* @param context
* @return
*/
private CAstEntity visit(EnumConstantDeclaration decl, WalkContext context) {
return new FieldEntity(decl.getName().getIdentifier(), decl.resolveVariable().getType(), enumQuals, makePosition(decl
@ -3477,12 +3450,7 @@ public abstract class JDTJava2CAstTranslator<T extends Position> {
constants.add(var);
// constants are unsorted by default
Collections.sort(constants, new Comparator<IVariableBinding>() {
@Override
public int compare(IVariableBinding arg0, IVariableBinding arg1) {
return arg0.getVariableId() - arg1.getVariableId();
}
});
Collections.sort(constants, (arg0, arg1) -> arg0.getVariableId() - arg1.getVariableId());
// PART II: create values()
memberEntities.add(createEnumValuesMethod(typeBinding, constants, context));

View File

@ -51,7 +51,7 @@ import com.ibm.wala.cast.tree.CAstType;
import com.ibm.wala.cast.tree.impl.CAstTypeDictionaryImpl;
import com.ibm.wala.util.debug.Assertions;
public class JDTTypeDictionary extends CAstTypeDictionaryImpl {
public class JDTTypeDictionary extends CAstTypeDictionaryImpl<ITypeBinding> {
// TODO: better way of getting type "ObjecT" that doesn't require us to keep AST? although this is similar to
// polyglot.
@ -88,7 +88,7 @@ public class JDTTypeDictionary extends CAstTypeDictionaryImpl {
type = new JdtJavaArrayType(jdtType);
} else
Assertions.UNREACHABLE("getCAstTypeFor() passed type that is not primitive, array, or class?");
super.map(astType, type); // put in cache
super.map((ITypeBinding)astType, type); // put in cache
}
return type;
}

View File

@ -42,7 +42,6 @@ import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@ -136,9 +135,7 @@ public class ECJSourceModuleTranslator implements SourceModuleTranslator {
while (cl != null) {
List<Module> modules = scope.getModules(cl);
for (Iterator<Module> iter = modules.iterator(); iter.hasNext();) {
Module m = iter.next();
for (Module m : modules) {
if (m instanceof JarFileModule) {
JarFileModule jarFileModule = (JarFileModule) m;

View File

@ -80,7 +80,7 @@ org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=error
org.eclipse.jdt.core.compiler.problem.rawTypeReference=ignore
org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=error
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=error
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore

View File

@ -13,8 +13,8 @@
<property name="javacVerbose" value="false"/>
<property name="logExtension" value=".log"/>
<property name="compilerArg" value=""/>
<property name="javacSource" value="1.7"/>
<property name="javacTarget" value="1.7"/>
<property name="javacSource" value="1.8"/>
<property name="javacTarget" value="1.8"/>
<!-- This property has been updated to correspond to the paths used by the latest Java update
on Mac OS X 10.6 (Java version 1.6.0_22). If you are not using this version of Mac OS X or Java,
try changing the value of the property to "${java.home}/../../../Classes" -->

View File

@ -42,7 +42,7 @@ import java.util.Iterator;
public class BasicsGenerics {
static ArrayList<String> strs = new ArrayList<String>();
static ArrayList<String> strs = new ArrayList<>();
static ArrayList<Integer> ints = new ArrayList<>();
public BasicsGenerics() {

View File

@ -95,7 +95,7 @@ class MyGeneric<A extends Object, B extends IGeneric<A>> {
}
public class CustomGenericsAndFields {
static ConcreteGeneric2<String> cg2 = new ConcreteGeneric2<String>();
static ConcreteGeneric2<String> cg2 = new ConcreteGeneric2<>();
static public ConcreteGeneric2<String> cg2WithSideEffects() {
System.out.println("look at me! I'm a side effect!");
@ -109,7 +109,7 @@ public class CustomGenericsAndFields {
private void doit() {
// Simple: concrete generic
ConcreteGeneric<String> absinthe = new ConcreteGeneric<String>();
ConcreteGeneric<String> absinthe = new ConcreteGeneric<>();
IGeneric<String> rye = absinthe;
String foo = rye.bar("hello", "world");
System.out.println(absinthe.foo() + foo);
@ -118,7 +118,7 @@ public class CustomGenericsAndFields {
String thrownaway = cg2.bar("a","b");
cg2.setFoo("real one");
MyGeneric<String,ConcreteGeneric2<String>> mygeneric = new MyGeneric<String,ConcreteGeneric2<String>>("useless",cg2);
MyGeneric<String,ConcreteGeneric2<String>> mygeneric = new MyGeneric<>("useless",cg2);
String x = mygeneric.doFoo();
System.out.println(x);
String y = cg2.x;

View File

@ -49,7 +49,7 @@ public class GenericArrays {
List<?>[] lsa = new List<?>[10]; // ok, array of unbounded wildcard type
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
List<Integer> li = new ArrayList<>();
li.add(new Integer(3));
oa[1] = li; // correct
String s = (String) lsa[1].get(0); // run time error, but cast is explicit

View File

@ -64,7 +64,7 @@ public class GenericMemberClasses<T>
}
}
public static void main(String args[]) {
(new GenericMemberClasses<Object>()).doit();
(new GenericMemberClasses<>()).doit();
}
private void doit() {

View File

@ -47,14 +47,14 @@ public class GenericSuperSink {
private void doit() {
Collection<? super String> sink;
Collection<String> cs = new ArrayList<String>();
Collection<String> cs = new ArrayList<>();
cs.add("hello");
sink = new ArrayList<Object>();
sink.add(cs.iterator().next());
System.out.println(sink);
sink = new ArrayList<String>();
sink = new ArrayList<>();
sink.add(cs.iterator().next());
System.out.println(sink);
}

View File

@ -55,7 +55,7 @@ public class MethodGenerics {
}
private void doit() {
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<>();
String array[] = new String[] { "coucou monde", "ciao mondo", "guten tag welt", "hola mundo", "shalom olam" };
fromArrayToCollection(array, list);
System.out.println(list);

View File

@ -64,14 +64,14 @@ public class Wildcards {
}
private void doit() {
ArrayList<String> e = new ArrayList<String>();
ArrayList<String> e = new ArrayList<>();
e.add("hello");
e.add("goodbye");
printCollection(e);
printCollection1(e);
printCollection2(e);
ArrayList<Integer> e3 = new ArrayList<Integer>();
ArrayList<Integer> e3 = new ArrayList<>();
e3.add(new Integer(123));
e3.add(new Integer(42));
printCollection(e3);

View File

@ -53,6 +53,7 @@ import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.strings.Atom;
@ -190,9 +191,7 @@ public abstract class IRTests {
CGNode tgtNode = tgtNodes.iterator().next();
boolean found = false;
for (Iterator<? extends CGNode> succIter = callGraph.getSuccNodes(srcNode); succIter.hasNext();) {
CGNode succ = succIter.next();
for (CGNode succ : Iterator2Iterable.make(callGraph.getSuccNodes(srcNode))) {
if (tgtNode == succ) {
found = true;
break;
@ -378,8 +377,7 @@ public abstract class IRTests {
Set<IMethod> unreachable = HashSetFactory.make();
IClassHierarchy cha = cg.getClassHierarchy();
IClassLoader sourceLoader = cha.getLoader(JavaSourceAnalysisScope.SOURCE);
for (Iterator<IClass> iter = sourceLoader.iterateAllClasses(); iter.hasNext();) {
IClass clazz = iter.next();
for (IClass clazz : Iterator2Iterable.make(sourceLoader.iterateAllClasses())) {
System.err.println(clazz);
if (clazz.isInterface())

View File

@ -82,103 +82,76 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testTwoClasses() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
cg -> {
final String typeStr = singleInputForTest();
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest();
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
/*
Assert.assertEquals("Expected two classes.", iClass.getClassLoader().getNumberOfClasses(), 2);
/*
Assert.assertEquals("Expected two classes.", iClass.getClassLoader().getNumberOfClasses(), 2);
for (Iterator<IClass> it = iClass.getClassLoader().iterateAllClasses(); it.hasNext();) {
IClass cls = it.next();
Assert.assertTrue("Expected class to be either " + typeStr + " or " + "Bar", cls.getName().getClassName().toString()
.equals(typeStr)
|| cls.getName().getClassName().toString().equals("Bar"));
}
*/
for (IClass cls : Iterator2Iterable.make(iClass.getClassLoader().iterateAllClasses())) {
Assert.assertTrue("Expected class to be either " + typeStr + " or " + "Bar", cls.getName().getClassName().toString()
.equals(typeStr)
|| cls.getName().getClassName().toString().equals("Bar"));
}
*/
}), true);
}
@Test public void testInterfaceTest1() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
* IFoo is an interface
*/
new IRAssertion() {
cg -> {
final String typeStr = "IFoo";
@Override
public void check(CallGraph cg) {
final String typeStr = "IFoo";
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
Assert.assertTrue("Expected IFoo to be an interface.", iClass.isInterface());
}
Assert.assertTrue("Expected IFoo to be an interface.", iClass.isInterface());
},
/**
* Foo implements IFoo
*/
new IRAssertion() {
cg -> {
final String typeStr = "FooIT1";
@Override
public void check(CallGraph cg) {
final String typeStr = "FooIT1";
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final Collection<? extends IClass> interfaces = iClass.getDirectInterfaces();
final Collection<? extends IClass> interfaces = iClass.getDirectInterfaces();
Assert.assertEquals("Expected one single interface.", interfaces.size(), 1);
Assert.assertEquals("Expected one single interface.", interfaces.size(), 1);
Assert.assertTrue("Expected Foo to implement IFoo", interfaces.contains(cg.getClassHierarchy().lookupClass(
findOrCreateTypeReference("Source", "IFoo", cg.getClassHierarchy()))));
}
Assert.assertTrue("Expected Foo to implement IFoo", interfaces.contains(cg.getClassHierarchy().lookupClass(
findOrCreateTypeReference("Source", "IFoo", cg.getClassHierarchy()))));
}), true);
}
@Test public void testInheritance1() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
* 'Derived' extends 'Base'
*/
new IRAssertion() {
cg -> {
final String typeStr = "Derived";
@Override
public void check(CallGraph cg) {
final String typeStr = "Derived";
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass derivedClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, derivedClass);
final IClass derivedClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, derivedClass);
final TypeReference baseType = findOrCreateTypeReference("Source", "Base", cg.getClassHierarchy());
final IClass baseClass = cg.getClassHierarchy().lookupClass(baseType);
final TypeReference baseType = findOrCreateTypeReference("Source", "Base", cg.getClassHierarchy());
final IClass baseClass = cg.getClassHierarchy().lookupClass(baseType);
Assert.assertTrue("Expected 'Base' to be the superclass of 'Derived'", derivedClass.getSuperclass().equals(baseClass));
Assert.assertTrue("Expected 'Base' to be the superclass of 'Derived'", derivedClass.getSuperclass().equals(baseClass));
Collection<IClass> subclasses = cg.getClassHierarchy().computeSubClasses(baseType);
Collection<IClass> subclasses = cg.getClassHierarchy().computeSubClasses(baseType);
Assert.assertTrue("Expected subclasses of 'Base' to be 'Base' and 'Derived'.", subclasses.contains(derivedClass)
&& subclasses.contains(baseClass));
}
Assert.assertTrue("Expected subclasses of 'Base' to be 'Base' and 'Derived'.", subclasses.contains(derivedClass)
&& subclasses.contains(baseClass));
}), true);
}
@ -214,80 +187,62 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testArrayLiteral1() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
* 'foo' has four array instructions: - 2 SSAArrayLengthInstruction - 1
* SSAArrayLoadInstruction - 1 SSAArrayStoreInstruction
*/
new IRAssertion() {
cg -> {
@Override
public void check(CallGraph cg) {
MethodReference mref = descriptorToMethodRef("Source#ArrayLiteral1#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
CGNode node = cg.getNodes(mref).iterator().next();
SSAInstruction s = node.getIR().getInstructions()[2];
Assert.assertTrue("Did not find new array instruction.", s instanceof SSANewInstruction);
Assert.assertTrue("", ((SSANewInstruction) s).getNewSite().getDeclaredType().isArrayType());
}
MethodReference mref = descriptorToMethodRef("Source#ArrayLiteral1#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
CGNode node = cg.getNodes(mref).iterator().next();
SSAInstruction s = node.getIR().getInstructions()[2];
Assert.assertTrue("Did not find new array instruction.", s instanceof SSANewInstruction);
Assert.assertTrue("", ((SSANewInstruction) s).getNewSite().getDeclaredType().isArrayType());
}), true);
}
@Test public void testArrayLiteral2() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
* int[] y= { 1, 2, 3, 4 } is represented in the IR as four array store
* instructions
*/
new IRAssertion() {
cg -> {
@Override
public void check(CallGraph cg) {
MethodReference mref = descriptorToMethodRef("Source#ArrayLiteral2#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
MethodReference mref = descriptorToMethodRef("Source#ArrayLiteral2#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
CGNode node = cg.getNodes(mref).iterator().next();
CGNode node = cg.getNodes(mref).iterator().next();
final SSAInstruction[] instructions = node.getIR().getInstructions();
// test 1
{
SSAInstruction s1 = instructions[2];
if (s1 instanceof SSANewInstruction) {
Assert.assertTrue("", ((SSANewInstruction) s1).getNewSite().getDeclaredType().isArrayType());
} else {
Assert.assertTrue("Expected 3rd to be a new array instruction.", false);
}
}
// test 2
{
SSAInstruction s2 = instructions[3];
if (s2 instanceof SSANewInstruction) {
Assert.assertTrue("", ((SSANewInstruction) s2).getNewSite().getDeclaredType().isArrayType());
} else {
Assert.assertTrue("Expected 4th to be a new array instruction.", false);
}
}
// test 3: the last 4 instructions are of the form y[i] = i+1;
{
final SymbolTable symbolTable = node.getIR().getSymbolTable();
for (int i = 4; i <= 7; i++) {
Assert.assertTrue("Expected only array stores.", instructions[i] instanceof SSAArrayStoreInstruction);
SSAArrayStoreInstruction as = (SSAArrayStoreInstruction) instructions[i];
Assert.assertEquals("Expected an array store to 'y'.", node.getIR().getLocalNames(i, as.getArrayRef())[0], "y");
final Integer valueOfArrayIndex = ((Integer) symbolTable.getConstantValue(as.getIndex()));
final Integer valueAssigned = (Integer) symbolTable.getConstantValue(as.getValue());
Assert.assertEquals("Expected an array store to 'y' with value " + (valueOfArrayIndex + 1), valueAssigned.intValue(),
valueOfArrayIndex + 1);
}
final SSAInstruction[] instructions = node.getIR().getInstructions();
// test 1
{
SSAInstruction s1 = instructions[2];
if (s1 instanceof SSANewInstruction) {
Assert.assertTrue("", ((SSANewInstruction) s1).getNewSite().getDeclaredType().isArrayType());
} else {
Assert.assertTrue("Expected 3rd to be a new array instruction.", false);
}
}
// test 2
{
SSAInstruction s2 = instructions[3];
if (s2 instanceof SSANewInstruction) {
Assert.assertTrue("", ((SSANewInstruction) s2).getNewSite().getDeclaredType().isArrayType());
} else {
Assert.assertTrue("Expected 4th to be a new array instruction.", false);
}
}
// test 3: the last 4 instructions are of the form y[i] = i+1;
{
final SymbolTable symbolTable = node.getIR().getSymbolTable();
for (int i = 4; i <= 7; i++) {
Assert.assertTrue("Expected only array stores.", instructions[i] instanceof SSAArrayStoreInstruction);
SSAArrayStoreInstruction as = (SSAArrayStoreInstruction) instructions[i];
Assert.assertEquals("Expected an array store to 'y'.", node.getIR().getLocalNames(i, as.getArrayRef())[0], "y");
final Integer valueOfArrayIndex = ((Integer) symbolTable.getConstantValue(as.getIndex()));
final Integer valueAssigned = (Integer) symbolTable.getConstantValue(as.getValue());
Assert.assertEquals("Expected an array store to 'y' with value " + (valueOfArrayIndex + 1), valueAssigned.intValue(),
valueOfArrayIndex + 1);
}
}
}), true);
}
@ -299,53 +254,41 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testQualifiedStatic() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
/**
*
*/
new IRAssertion() {
cg -> {
@Override
public void check(CallGraph cg) {
MethodReference mref = descriptorToMethodRef("Source#QualifiedStatic#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
MethodReference mref = descriptorToMethodRef("Source#QualifiedStatic#main#([Ljava/lang/String;)V", cg.getClassHierarchy());
CGNode node = cg.getNodes(mref).iterator().next();
SSAInstruction s = node.getIR().getInstructions()[4];
Assert.assertTrue("Did not find a getstatic instruction.", s instanceof SSAGetInstruction
&& ((SSAGetInstruction) s).isStatic());
final FieldReference field = ((SSAGetInstruction) s).getDeclaredField();
Assert.assertEquals("Expected a getstatic for 'value'.", field.getName().toString(), "value");
Assert.assertEquals("Expected a getstatic for 'value'.", field.getDeclaringClass().getName().toString(), "LFooQ");
}
CGNode node = cg.getNodes(mref).iterator().next();
SSAInstruction s = node.getIR().getInstructions()[4];
Assert.assertTrue("Did not find a getstatic instruction.", s instanceof SSAGetInstruction
&& ((SSAGetInstruction) s).isStatic());
final FieldReference field = ((SSAGetInstruction) s).getDeclaredField();
Assert.assertEquals("Expected a getstatic for 'value'.", field.getName().toString(), "value");
Assert.assertEquals("Expected a getstatic for 'value'.", field.getDeclaringClass().getName().toString(), "LFooQ");
}), true);
}
@Test public void testStaticNesting() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
cg -> {
final String typeStr = singleInputForTest() + "$WhatsIt";
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest() + "$WhatsIt";
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
// todo: this fails: Assert.assertNotNull("Expected to be enclosed in
// 'StaticNesting'.",
// ((JavaSourceLoaderImpl.JavaClass)iClass).getEnclosingClass());
// todo: is there the concept of CompilationUnit?
// todo: this fails: Assert.assertNotNull("Expected to be enclosed in
// 'StaticNesting'.",
// ((JavaSourceLoaderImpl.JavaClass)iClass).getEnclosingClass());
// todo: is there the concept of CompilationUnit?
/**
* {@link JavaCAst2IRTranslator#getEnclosingType} return null for static
* inner classes..?
*/
}
/**
* {@link JavaCAst2IRTranslator#getEnclosingType} return null for static
* inner classes..?
*/
}), true);
}
@ -356,21 +299,17 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testInnerClass() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
cg -> {
final String typeStr = singleInputForTest();
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest();
final TypeReference type = findOrCreateTypeReference("Source", typeStr + "$WhatsIt", cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr + "$WhatsIt", cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
Assert.assertEquals("Expected to be enclosed in 'InnerClass'.", ((JavaSourceLoaderImpl.JavaClass) iClass)
.getEnclosingClass(), // todo is there another way?
cg.getClassHierarchy().lookupClass(findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy())));
}
Assert.assertEquals("Expected to be enclosed in 'InnerClass'.", ((JavaSourceLoaderImpl.JavaClass) iClass)
.getEnclosingClass(), // todo is there another way?
cg.getClassHierarchy().lookupClass(findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy())));
}), true);
}
@ -471,61 +410,49 @@ public abstract class JavaIRTests extends IRTests {
@Test public void testLocalClass() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
cg -> {
final String typeStr = singleInputForTest();
final String localClassStr = "Foo";
/**
* Classes local to method are enclosed in the class the methods belong
* to.
*/
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest();
final String localClassStr = "Foo";
// Observe the descriptor for a class local to a method.
final TypeReference mainFooType = findOrCreateTypeReference("Source", typeStr + "/main([Ljava/lang/String;)V/"
+ localClassStr, cg.getClassHierarchy());
// Observe the descriptor for a class local to a method.
final TypeReference mainFooType = findOrCreateTypeReference("Source", typeStr + "/main([Ljava/lang/String;)V/"
+ localClassStr, cg.getClassHierarchy());
// Observe the descriptor for a class local to a method.
final IClass mainFooClass = cg.getClassHierarchy().lookupClass(mainFooType);
Assert.assertNotNull("Could not find class " + mainFooType, mainFooClass);
// Observe the descriptor for a class local to a method.
final IClass mainFooClass = cg.getClassHierarchy().lookupClass(mainFooType);
Assert.assertNotNull("Could not find class " + mainFooType, mainFooClass);
final TypeReference methodFooType = findOrCreateTypeReference("Source", typeStr + "/method()V/" + localClassStr, cg
.getClassHierarchy());
final TypeReference methodFooType = findOrCreateTypeReference("Source", typeStr + "/method()V/" + localClassStr, cg
.getClassHierarchy());
final IClass methodFooClass = cg.getClassHierarchy().lookupClass(methodFooType);
Assert.assertNotNull("Could not find class " + methodFooType, methodFooClass);
final IClass methodFooClass = cg.getClassHierarchy().lookupClass(methodFooType);
Assert.assertNotNull("Could not find class " + methodFooType, methodFooClass);
final IClass localClass = cg.getClassHierarchy().lookupClass(
findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()));
final IClass localClass = cg.getClassHierarchy().lookupClass(
findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()));
Assert.assertSame("'Foo' is enclosed in 'Local'", ((JavaSourceLoaderImpl.JavaClass) methodFooClass).getEnclosingClass(),
localClass);
// todo: is this failing because 'main' is static?
// Assert.assertSame("'Foo' is enclosed in 'Local'",
// ((JavaSourceLoaderImpl.JavaClass)mainFooClass).getEnclosingClass(),
// localClass);
}
Assert.assertSame("'Foo' is enclosed in 'Local'", ((JavaSourceLoaderImpl.JavaClass) methodFooClass).getEnclosingClass(),
localClass);
// todo: is this failing because 'main' is static?
// Assert.assertSame("'Foo' is enclosed in 'Local'",
// ((JavaSourceLoaderImpl.JavaClass)mainFooClass).getEnclosingClass(),
// localClass);
}), true);
}
@Test public void testAnonymousClass() throws IllegalArgumentException, CancelException, IOException {
runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList(
new IRAssertion() {
cg -> {
final String typeStr = singleInputForTest();
@Override
public void check(CallGraph cg) {
final String typeStr = singleInputForTest();
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy());
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
final IClass iClass = cg.getClassHierarchy().lookupClass(type);
Assert.assertNotNull("Could not find class " + typeStr, iClass);
// todo what to check?? could not find anything in the APIs for
// anonymous
}
// todo what to check?? could not find anything in the APIs for
// anonymous
}), true);
}

View File

@ -91,8 +91,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

View File

@ -132,9 +132,8 @@ public class AstJavaTypeInference extends AstTypeInference {
public byte evaluate(TypeVariable lhs, TypeVariable[] rhs) {
TypeAbstraction meet = null;
for (int i = 0; i < rhs.length; i++) {
if (rhs[i] != null) {
TypeVariable r = rhs[i];
for (TypeVariable r : rhs) {
if (r != null) {
TypeAbstraction ta = r.getType();
if (ta instanceof PointType) {
if (ta.getType().equals(getStringClass())) {

View File

@ -159,12 +159,7 @@ public abstract class JavaSourceAnalysisEngine<I extends InstanceKey> extends Ab
AnalysisOptions options = new AnalysisOptions(getScope(), entrypoints);
SSAOptions ssaOptions = new SSAOptions();
ssaOptions.setDefaultValues(new SSAOptions.DefaultValues() {
@Override
public int getDefaultValue(SymbolTable symtab, int valueNumber) {
return symtab.getDefaultValue(valueNumber);
}
});
ssaOptions.setDefaultValues(SymbolTable::getDefaultValue);
options.setSSAOptions(ssaOptions);

View File

@ -10,6 +10,7 @@
*****************************************************************************/
package com.ibm.wala.cast.java.ipa.callgraph;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultPointerKeyFactory;
@ -21,7 +22,7 @@ import com.ibm.wala.ipa.cha.IClassHierarchy;
public class AstJavaCFABuilder extends AstJavaSSAPropagationCallGraphBuilder {
public AstJavaCFABuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(cha, options, cache, new DefaultPointerKeyFactory());
super(Language.JAVA.getFakeRootMethod(cha, options, cache), options, cache, new DefaultPointerKeyFactory());
}
}

View File

@ -20,6 +20,7 @@ import com.ibm.wala.cast.java.ssa.AstJavaInvokeInstruction;
import com.ibm.wala.cast.java.ssa.AstJavaNewEnclosingInstruction;
import com.ibm.wala.cast.java.ssa.EnclosingObjectReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.fixpoint.IntSetVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
@ -31,20 +32,18 @@ import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory;
import com.ibm.wala.ipa.callgraph.propagation.PointsToSetVariable;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.strings.Atom;
public class AstJavaSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraphBuilder {
protected AstJavaSSAPropagationCallGraphBuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache,
protected AstJavaSSAPropagationCallGraphBuilder(IMethod fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache,
PointerKeyFactory pointerKeyFactory) {
super(cha, options, cache, pointerKeyFactory);
super(fakeRootClass, options, cache, pointerKeyFactory);
}
// ///////////////////////////////////////////////////////////////////////////
@ -173,8 +172,8 @@ public class AstJavaSSAPropagationCallGraphBuilder extends AstSSAPropagationCall
InstanceKey[] objs = getInvariantContents(objVal);
for (int i = 0; i < objs.length; i++) {
PointerKey enclosing = new EnclosingObjectReferenceKey(objs[i], cls);
for (InstanceKey obj : objs) {
PointerKey enclosing = new EnclosingObjectReferenceKey(obj, cls);
system.newConstraint(lvalKey, assignOperator, enclosing);
}
@ -184,13 +183,10 @@ public class AstJavaSSAPropagationCallGraphBuilder extends AstSSAPropagationCall
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
IntSetVariable<?> tv = rhs;
if (tv.getValue() != null) {
tv.getValue().foreach(new IntSetAction() {
@Override
public void act(int ptr) {
InstanceKey iKey = system.getInstanceKey(ptr);
PointerKey enclosing = new EnclosingObjectReferenceKey(iKey, cls);
system.newConstraint(lvalKey, assignOperator, enclosing);
}
tv.getValue().foreach(ptr -> {
InstanceKey iKey = system.getInstanceKey(ptr);
PointerKey enclosing = new EnclosingObjectReferenceKey(iKey, cls);
system.newConstraint(lvalKey, assignOperator, enclosing);
});
}
return NOT_CHANGED;

View File

@ -53,8 +53,8 @@ public class AstJavaZeroXCFABuilder extends AstJavaCFABuilder {
AnalysisScope scope, String[] xmlFiles, byte instancePolicy) {
com.ibm.wala.ipa.callgraph.impl.Util.addDefaultSelectors(options, cha);
for (int i = 0; i < xmlFiles.length; i++) {
com.ibm.wala.ipa.callgraph.impl.Util.addBypassLogic(options, scope, cl, xmlFiles[i], cha);
for (String xmlFile : xmlFiles) {
com.ibm.wala.ipa.callgraph.impl.Util.addBypassLogic(options, scope, cl, xmlFile, cha);
}
return new AstJavaZeroXCFABuilder(cha, options, cache, null, null, instancePolicy);

View File

@ -44,8 +44,8 @@ public class JavaScopeMappingInstanceKeys extends ScopeMappingInstanceKeys {
if ((m instanceof AstMethod) && !m.isStatic()) {
AstMethod M = (AstMethod) m;
LexicalParent[] parents = M.getParents();
for (int i = 0; i < parents.length; i++) {
result.add(parents[i]);
for (LexicalParent parent : parents) {
result.add(parent);
}
}
}

View File

@ -12,7 +12,6 @@ package com.ibm.wala.cast.java.ipa.slicer;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Predicate;
@ -59,8 +58,7 @@ public class AstJavaSlicer extends Slicer {
public static Set<Statement> gatherStatements(CallGraph CG, Collection<CGNode> partialRoots, Predicate<SSAInstruction> filter) {
Set<Statement> result = new HashSet<>();
for (Iterator<CGNode> ns = DFS.getReachableNodes(CG, partialRoots).iterator(); ns.hasNext();) {
CGNode n = ns.next();
for (CGNode n : DFS.getReachableNodes(CG, partialRoots)) {
IR nir = n.getIR();
if (nir != null) {
SSAInstruction insts[] = nir.getInstructions();
@ -76,35 +74,19 @@ public class AstJavaSlicer extends Slicer {
}
public static Set<Statement> gatherAssertions(CallGraph CG, Collection<CGNode> partialRoots) {
return gatherStatements(CG, partialRoots, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return o instanceof AstAssertInstruction;
}
});
return gatherStatements(CG, partialRoots, AstAssertInstruction.class::isInstance);
}
public static Set<Statement> gatherMonitors(CallGraph CG, Collection<CGNode> partialRoots) {
return gatherStatements(CG, partialRoots, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return o instanceof SSAMonitorInstruction;
}
});
return gatherStatements(CG, partialRoots, SSAMonitorInstruction.class::isInstance);
}
public static Set<Statement> gatherWrites(CallGraph CG, Collection<CGNode> partialRoots) {
return gatherStatements(CG, partialRoots, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return (o instanceof SSAPutInstruction) || (o instanceof SSAArrayStoreInstruction);
}
});
return gatherStatements(CG, partialRoots, o -> (o instanceof SSAPutInstruction) || (o instanceof SSAArrayStoreInstruction));
}
public static Set<Statement> gatherReads(CallGraph CG, Collection<CGNode> partialRoots) {
return gatherStatements(CG, partialRoots, new Predicate<SSAInstruction>() {
@Override public boolean test(SSAInstruction o) {
return (o instanceof SSAGetInstruction) || (o instanceof SSAArrayLoadInstruction);
}
});
return gatherStatements(CG, partialRoots, o -> (o instanceof SSAGetInstruction) || (o instanceof SSAArrayLoadInstruction));
}
public static Pair<Collection<Statement>, SDG<InstanceKey>> computeAssertionSlice(CallGraph CG, PointerAnalysis<InstanceKey> pa,

View File

@ -17,7 +17,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -123,8 +122,7 @@ public abstract class JavaSourceLoaderImpl extends ClassLoaderImpl {
@Override
public IClass getSuperclass() {
boolean excludedSupertype=false;
for (Iterator<TypeName> iter = superTypeNames.iterator(); iter.hasNext();) {
TypeName name = iter.next();
for (TypeName name : superTypeNames) {
IClass domoType = lookupClass(name);
if (domoType != null && !domoType.isInterface()) {
return domoType;

View File

@ -231,7 +231,9 @@ public class JavaCAst2IRTranslator extends AstTranslator {
assert owner != null : makeType(owningType).getName().toString() + " not found in " + loader;
((JavaSourceLoaderImpl) loader).defineAbstractFunction(N, owner);
if (N.getQualifiers().contains(CAstQualifier.ABSTRACT)) {
((JavaSourceLoaderImpl) loader).defineAbstractFunction(N, owner);
}
}
@Override

View File

@ -1,68 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project>
<project name="com.ibm.wala.cast.js.html.nu_validator" default="getJars" basedir=".">
<property name="basews" value="${ws}"/>
<property name="baseos" value="${os}"/>
<property name="basearch" value="${arch}"/>
<property name="basenl" value="${nl}"/>
<!-- Compiler settings. -->
<property name="javacFailOnError" value="true"/>
<property name="javacDebugInfo" value="on"/>
<property name="javacVerbose" value="false"/>
<property name="logExtension" value=".log"/>
<property name="compilerArg" value=""/>
<property name="javacSource" value="1.5"/>
<property name="javacTarget" value="1.5"/>
<!-- This property has been updated to correspond to the paths used by the latest Java update
on Mac OS X 10.6 (Java version 1.6.0_22). If you are not using this version of Mac OS X or Java,
try changing the value of the property to "${java.home}/../../../Classes" -->
<condition property="dir_bootclasspath" value="${java.home}/../Classes">
<os family="mac"/>
</condition>
<property name="dir_bootclasspath" value="${java.home}/lib"/>
<path id="path_bootclasspath">
<fileset dir="${dir_bootclasspath}">
<include name="*.jar"/>
</fileset>
</path>
<property name="bootclasspath" refid="path_bootclasspath"/>
<property name="bundleJavacSource" value="${javacSource}"/>
<property name="bundleJavacTarget" value="${javacTarget}"/>
<property name="bundleBootClasspath" value="${bootclasspath}"/>
<target name="NuPresent" depends="init">
<available file="${plugin.destination}/lib/htmlparser-1.4.jar" property="nu.present"/>
</target>
<target name="fetchNu" depends="NuPresent" unless="nu.present">
<delete dir="${temp.folder}"/>
<mkdir dir="${temp.folder}"/>
<get src="http://about.validator.nu/htmlparser/htmlparser-1.4.zip" dest="${temp.folder}/htmlparser-1.4.zip"/>
<unzip src="${temp.folder}/htmlparser-1.4.zip" dest="${temp.folder}"/>
<copy file="${temp.folder}/htmlparser-1.4/htmlparser-1.4.jar" tofile="${plugin.destination}/lib/htmlparser-1.4.jar" />
<delete dir="${temp.folder}"/>
</target>
<target name="getJars" depends="fetchNu" />
<target name="init" depends="properties">
<condition property="pluginTemp" value="${buildTempFolder}/plugins">
<isset property="buildTempFolder"/>
</condition>
<property name="pluginTemp" value="${basedir}"/>
<condition property="build.result.folder" value="${pluginTemp}/com.ibm.wala.core.testdata">
<isset property="buildTempFolder"/>
</condition>
<property name="build.result.folder" value="${basedir}"/>
<property name="temp.folder" value="${basedir}/temp.folder"/>
<property name="plugin.destination" value="${basedir}"/>
</target>
<target name="properties" if="eclipse.running">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
</target>
</project>

View File

@ -22,7 +22,7 @@ import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder;
/**
* @author Brian Pfretzschner <brian.pfretzschner@gmail.com>
* @author Brian Pfretzschner &lt;brian.pfretzschner@gmail.com&gt;
*/
public class NodejsRequireJsonTest {

View File

@ -22,7 +22,7 @@ import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder;
/**
* @author Brian Pfretzschner <brian.pfretzschner@gmail.com>
* @author Brian Pfretzschner &lt;brian.pfretzschner@gmail.com&gt;
*/
public class NodejsRequireTargetSelectorResolveTest {

View File

@ -46,7 +46,7 @@ import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.util.WalaException;
/**
* @author Brian Pfretzschner <brian.pfretzschner@gmail.com>
* @author Brian Pfretzschner &lt;brian.pfretzschner@gmail.com&gt;
*/
public class NodejsCallGraphBuilderUtil extends JSCallGraphUtil {

View File

@ -51,7 +51,7 @@ import com.ibm.wala.util.ssa.ClassLookupException;
* This class is used by WALA internals to resolve to what functions a call
* could potentially invoke.
*
* @author Brian Pfretzschner <brian.pfretzschner@gmail.com>
* @author Brian Pfretzschner &lt;brian.pfretzschner@gmail.com&gt;
*/
public class NodejsRequireTargetSelector implements MethodTargetSelector {
@ -185,7 +185,6 @@ public class NodejsRequireTargetSelector implements MethodTargetSelector {
*
* @param dir Y in the pseudo algorithm
* @param target X in the pseudo algorithm
* @return
* @throws IOException
*/
public static SourceFileModule resolve(File rootDir, File dir, String target) throws IOException {
@ -214,8 +213,7 @@ public class NodejsRequireTargetSelector implements MethodTargetSelector {
* 4. If X.node is a file, load X.node as binary addon. STOP
*
* @param f
* @return
* @throws IOException
* @throws IOException
*/
private static SourceFileModule loadAsFile(File rootDir, File f) throws IOException {
// 1.
@ -248,7 +246,6 @@ public class NodejsRequireTargetSelector implements MethodTargetSelector {
* 4. If X/index.node is a file, load X/index.node as binary addon. STOP
*
* @param d
* @return
* @throws IOException
*/
private static SourceFileModule loadAsDirectory(File rootDir, File d) throws IOException {
@ -293,8 +290,7 @@ public class NodejsRequireTargetSelector implements MethodTargetSelector {
*
* @param dir
* @param target
* @return
* @throws IOException
* @throws IOException
*/
private static SourceFileModule loadNodeModules(File rootDir, File d, String target) throws IOException {
List<File> dirs = nodeModulePaths(rootDir, d);
@ -314,7 +310,7 @@ public class NodejsRequireTargetSelector implements MethodTargetSelector {
* 1. let PARTS = path split(START)
* 2. let I = count of PARTS - 1
* 3. let DIRS = []
* 4. while I >= 0,
* 4. while I &gt;= 0,
* a. if PARTS[I] = "node_modules" CONTINUE
* b. DIR = path join(PARTS[0 .. I] + "node_modules")
* c. DIRS = DIRS + DIR
@ -322,8 +318,7 @@ public class NodejsRequireTargetSelector implements MethodTargetSelector {
* 5. return DIRS
*
* @param d
* @return
* @throws IOException
* @throws IOException
*/
private static List<File> nodeModulePaths(File rootDir, File d) throws IOException {
LinkedList<File> dirs = new LinkedList<>();

View File

@ -24,7 +24,7 @@ import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.io.TemporaryFile;
/**
* @author Brian Pfretzschner <brian.pfretzschner@gmail.com>
* @author Brian Pfretzschner &lt;brian.pfretzschner@gmail.com&gt;
*/
public class NodejsRequiredCoreModule extends NodejsRequiredSourceModule {

View File

@ -30,7 +30,7 @@ import com.ibm.wala.util.io.Streams;
* environment. The resulting function will be named GLOBAL_PREFIX + relative
* file-name. To retrieve the final function name, use getFunctioName().
*
* @author Brian Pfretzschner <brian.pfretzschner@gmail.com>
* @author Brian Pfretzschner &lt;brian.pfretzschner@gmail.com&gt;
*/
public class NodejsRequiredSourceModule extends SourceFileModule {
@ -47,8 +47,6 @@ public class NodejsRequiredSourceModule extends SourceFileModule {
private final String className;
/**
* @param workingDir
* Must be a direct or indirect parent folder of file f.
* @param f
* Must be a file located below folder workingDir.
* @param clonedFrom
@ -127,7 +125,6 @@ public class NodejsRequiredSourceModule extends SourceFileModule {
*
* @param rootDir
* @param file
* @return
*/
public static String convertFileToClassName(File rootDir, File file) {
URI normalizedWorkingDirURI = rootDir.getAbsoluteFile().toURI().normalize();

View File

@ -4,6 +4,7 @@ import java.io.IOException;
import java.net.URL;
import java.util.Map;
import com.ibm.wala.cast.ipa.callgraph.CrossLanguageCallGraph;
import com.ibm.wala.cast.ipa.callgraph.CrossLanguageMethodTargetSelector;
import com.ibm.wala.cast.ipa.callgraph.StandardFunctionTargetSelector;
import com.ibm.wala.cast.ipa.cha.CrossLanguageClassHierarchy;
@ -22,6 +23,8 @@ import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.callgraph.impl.ComposedEntrypoints;
import com.ibm.wala.ipa.callgraph.impl.FakeRootClass;
import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.IRFactory;
@ -82,7 +85,7 @@ public class Driver {
addDefaultDispatchLogic(options, cha);
JavaJavaScriptHybridCallGraphBuilder b = new JavaJavaScriptHybridCallGraphBuilder(cha, options, cache);
JavaJavaScriptHybridCallGraphBuilder b = new JavaJavaScriptHybridCallGraphBuilder(new FakeRootMethod(new FakeRootClass(CrossLanguageCallGraph.crossCoreLoader, cha), options, cache), options, cache);
System.err.println(b.makeCallGraph(options));
}

View File

@ -9,7 +9,6 @@ import com.ibm.wala.cast.ipa.callgraph.CrossLanguageContextSelector;
import com.ibm.wala.cast.ipa.callgraph.CrossLanguageInstanceKeys;
import com.ibm.wala.cast.ipa.callgraph.CrossLanguageSSAPropagationCallGraphBuilder;
import com.ibm.wala.cast.ipa.callgraph.GlobalObjectKey;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraph.JSFakeRoot;
import com.ibm.wala.cast.js.ipa.callgraph.JSSSAPropagationCallGraphBuilder;
import com.ibm.wala.cast.js.ipa.callgraph.JSSSAPropagationCallGraphBuilder.JSConstraintVisitor;
import com.ibm.wala.cast.js.ipa.callgraph.JSSSAPropagationCallGraphBuilder.JSInterestingVisitor;
@ -21,6 +20,7 @@ import com.ibm.wala.cast.js.ipa.callgraph.JavaScriptScopeMappingInstanceKeys;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.util.TargetLanguageSelector;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
@ -28,7 +28,6 @@ import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector;
import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory;
@ -36,15 +35,14 @@ import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.strings.Atom;
public class JavaJavaScriptHybridCallGraphBuilder extends CrossLanguageSSAPropagationCallGraphBuilder {
public JavaJavaScriptHybridCallGraphBuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(cha, options, cache, new AstCFAPointerKeys());
public JavaJavaScriptHybridCallGraphBuilder(IMethod fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache) {
super(fakeRootClass, options, cache, new AstCFAPointerKeys());
globalObject = new GlobalObjectKey(cha.lookupClass(JavaScriptTypes.Root));
SSAContextInterpreter contextInterpreter = makeDefaultContextInterpreters(null, options, cha);
@ -78,28 +76,22 @@ public class JavaJavaScriptHybridCallGraphBuilder extends CrossLanguageSSAPropag
@Override
protected TargetLanguageSelector<ConstraintVisitor, CGNode> makeMainVisitorSelector() {
return new TargetLanguageSelector<ConstraintVisitor, CGNode>() {
@Override
public ConstraintVisitor get(Atom language, CGNode construct) {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSConstraintVisitor(JavaJavaScriptHybridCallGraphBuilder.this, construct);
} else {
return new ConstraintVisitor(JavaJavaScriptHybridCallGraphBuilder.this, construct);
}
return (language, construct) -> {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSConstraintVisitor(JavaJavaScriptHybridCallGraphBuilder.this, construct);
} else {
return new ConstraintVisitor(JavaJavaScriptHybridCallGraphBuilder.this, construct);
}
};
}
@Override
protected TargetLanguageSelector<InterestingVisitor, Integer> makeInterestingVisitorSelector() {
return new TargetLanguageSelector<InterestingVisitor, Integer>() {
@Override
public InterestingVisitor get(Atom language, Integer construct) {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSInterestingVisitor(construct);
} else {
return new InterestingVisitor(construct);
}
return (language, construct) -> {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSInterestingVisitor(construct);
} else {
return new InterestingVisitor(construct);
}
};
}
@ -107,29 +99,19 @@ public class JavaJavaScriptHybridCallGraphBuilder extends CrossLanguageSSAPropag
@Override
protected TargetLanguageSelector<AstImplicitPointsToSetVisitor, LocalPointerKey> makeImplicitVisitorSelector(
CrossLanguagePointerAnalysisImpl analysis) {
return new TargetLanguageSelector<AstImplicitPointsToSetVisitor, LocalPointerKey>() {
@Override
public AstImplicitPointsToSetVisitor get(Atom language, LocalPointerKey construct) {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSImplicitPointsToSetVisitor((AstPointerAnalysisImpl) getPointerAnalysis(), construct);
} else {
return new AstImplicitPointsToSetVisitor((AstPointerAnalysisImpl) getPointerAnalysis(), construct);
}
return (language, construct) -> {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSImplicitPointsToSetVisitor((AstPointerAnalysisImpl) getPointerAnalysis(), construct);
} else {
return new AstImplicitPointsToSetVisitor((AstPointerAnalysisImpl) getPointerAnalysis(), construct);
}
};
}
@Override
protected TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph> makeRootNodeSelector() {
return new TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph>() {
@Override
public AbstractRootMethod get(Atom language, CrossLanguageCallGraph construct) {
if (JavaScriptTypes.jsName.equals(language)) {
return new JSFakeRoot(getClassHierarchy(), getOptions(), getAnalysisCache());
} else {
return new FakeRootMethod(getClassHierarchy(), getOptions(), getAnalysisCache());
}
}
return (language, construct) -> {
return getOptions().getAnalysisScope().getLanguage(language).getFakeRootMethod(getClassHierarchy(), getOptions(), getAnalysisCache());
};
}

View File

@ -4,6 +4,8 @@ import java.net.URL;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assume.*;
import org.junit.Before;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst.Error;
@ -55,12 +57,9 @@ public abstract class AbstractFieldBasedTest extends TestJSCallGraphShape {
/**
* for long-running tests that tend to time out on Travis
*/
protected JSCallGraph runTestExceptOnTravis(URL url, Object[][] assertions, BuilderType... builderTypes) throws WalaException, Error, CancelException {
if (System.getenv("TRAVIS") == null) {
return runTest(url, assertions, builderTypes);
} else {
return null;
}
protected void runTestExceptOnTravis(URL url, Object[][] assertions, BuilderType... builderTypes) throws WalaException, Error, CancelException {
assumeThat("not running on Travis CI", System.getenv("TRAVIS"), nullValue());
runTest(url, assertions, builderTypes);
}
protected void dumpCG(JSCallGraph cg) {

View File

@ -38,15 +38,15 @@ public class FieldBasedCGGamesTest extends AbstractFieldBasedTest {
runTestExceptOnTravis(new URL("http://www.inmensia.com/files/solitaire1.0.html"), new Object[][]{}, BuilderType.OPTIMISTIC);
}
@Test(expected = CancelException.class)
@Test // (expected = CancelException.class)
public void testWorldOfSolitaire() throws IOException, WalaException, Error, CancelException {
runTestExceptOnTravis(new URL("http://worldofsolitaire.com/"), new Object[][]{}, BuilderType.OPTIMISTIC);
if (System.getenv("TRAVIS") != null) {
// fake it
throw new CancelException(null);
// throw new CancelException(null);
}
}
@Test
public void testMinesweeper() throws IOException, WalaException, Error, CancelException {
runTestExceptOnTravis(new URL("http://www.inmensia.com/files/minesweeper1.0.html"), new Object[][]{}, BuilderType.OPTIMISTIC_WORKLIST);

View File

@ -58,13 +58,7 @@ public class PrintIRs {
JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
// build a class hierarchy, for access to code info
IClassHierarchy cha = JSCallGraphUtil.makeHierarchyForScripts(filename);
printIRsForCHA(cha, new Predicate<String>() {
@Override
public boolean test(String t) {
return t.startsWith("Lprologue.js");
}
});
printIRsForCHA(cha, t -> t.startsWith("Lprologue.js"));
}
protected static void printIRsForCHA(IClassHierarchy cha, Predicate<String> exclude) {
@ -101,13 +95,7 @@ public class PrintIRs {
CAstAnalysisScope scope = new CAstAnalysisScope(scripts, loaders, Collections.singleton(JavaScriptLoader.JS));
IClassHierarchy cha = ClassHierarchyFactory.make(scope, loaders, JavaScriptLoader.JS);
com.ibm.wala.cast.util.Util.checkForFrontEndErrors(cha);
printIRsForCHA(cha, new Predicate<String>() {
@Override
public boolean test(String t) {
return t.startsWith("Lprologue.js") || t.startsWith("Lpreamble.js");
}
});
printIRsForCHA(cha, t -> t.startsWith("Lprologue.js") || t.startsWith("Lpreamble.js"));
}
/**

View File

@ -17,7 +17,6 @@ import org.junit.Test;
import com.ibm.wala.cast.js.html.DefaultSourceExtractor;
import com.ibm.wala.cast.js.html.IHtmlParser;
import com.ibm.wala.cast.js.html.IHtmlParserFactory;
import com.ibm.wala.cast.js.html.JSSourceExtractor;
import com.ibm.wala.cast.js.html.WebUtil;
import com.ibm.wala.cast.js.ipa.callgraph.JSCFABuilder;
@ -58,12 +57,7 @@ public abstract class TestSimplePageCallGraphShapeRhino extends TestSimplePageCa
@Before
public void setUp() {
com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil.setTranslatorFactory(new CAstRhinoTranslatorFactory());
WebUtil.setFactory(new IHtmlParserFactory() {
@Override
public IHtmlParser getParser() {
return TestSimplePageCallGraphShapeRhino.this.getParser();
}
});
WebUtil.setFactory(TestSimplePageCallGraphShapeRhino.this::getParser);
JSSourceExtractor.USE_TEMP_NAME = false;
// JSSourceExtractor.DELETE_UPON_EXIT = false;
}

View File

@ -15,8 +15,8 @@ compilers.p.discouraged-class=0
compilers.p.internal=0
compilers.p.missing-packages=0
compilers.p.missing-version-export-package=2
compilers.p.missing-version-import-package=0
compilers.p.missing-version-require-bundle=0
compilers.p.missing-version-import-package=2
compilers.p.missing-version-require-bundle=2
compilers.p.no-required-att=0
compilers.p.not-externalized-att=0
compilers.p.unknown-attribute=0

View File

@ -4,9 +4,10 @@ Bundle-Name: %Bundle-Name
Bundle-SymbolicName: com.ibm.wala.cast.js.rhino
Bundle-Version: 1.4.4.qualifier
Bundle-Vendor: %Bundle-Vendor
Require-Bundle: com.ibm.wala.cast;bundle-version="1.0.0",
com.ibm.wala.cast.js;bundle-version="1.0.0",
com.ibm.wala.core;bundle-version="1.1.3"
Require-Bundle: com.ibm.wala.cast;bundle-version="1.4.4",
com.ibm.wala.cast.js;bundle-version="1.4.4",
com.ibm.wala.core;bundle-version="1.4.4",
com.ibm.wala.util;bundle-version="1.4.4"
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Bundle-ActivationPolicy: lazy
Export-Package: com.ibm.wala.cast.js.translator,

View File

@ -1,48 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project>
<project name="com.ibm.wala.cast.js.rhino" default="getJars" basedir=".">
<property name="basews" value="${ws}"/>
<property name="baseos" value="${os}"/>
<property name="basearch" value="${arch}"/>
<property name="basenl" value="${nl}"/>
<!-- Compiler settings. -->
<property name="javacFailOnError" value="true"/>
<property name="javacDebugInfo" value="on"/>
<property name="javacVerbose" value="false"/>
<property name="logExtension" value=".log"/>
<property name="compilerArg" value=""/>
<property name="javacSource" value="1.5"/>
<property name="javacTarget" value="1.5"/>
<target name="RhinoPresent" depends="init">
<available file="${plugin.destination}/lib/rhino-1.7.6.jar" property="rhino.present"/>
</target>
<target name="fetchRhino" depends="RhinoPresent" unless="rhino.present">
<get src="http://central.maven.org/maven2/org/mozilla/rhino/1.7.6/rhino-1.7.6.jar" dest="${plugin.destination}/lib/rhino-1.7.6.jar" />
</target>
<target name="getJars" depends="fetchRhino" />
<target name="init" depends="properties">
<condition property="pluginTemp" value="${buildTempFolder}/plugins">
<isset property="buildTempFolder"/>
</condition>
<property name="pluginTemp" value="${basedir}"/>
<condition property="build.result.folder" value="${pluginTemp}/com.ibm.wala.core.testdata">
<isset property="buildTempFolder"/>
</condition>
<property name="build.result.folder" value="${basedir}"/>
<property name="temp.folder" value="${basedir}/temp.folder"/>
<property name="plugin.destination" value="${basedir}"/>
</target>
<target name="properties" if="eclipse.running">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
</target>
</project>

View File

@ -96,8 +96,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

View File

@ -159,10 +159,9 @@ public class RhinoToAstTranslator implements TranslatorToCAst {
*/
private static class FunctionContext extends JavaScriptTranslatorToCAst.FunctionContext<WalkContext,Node> implements WalkContext {
FunctionContext(WalkContext parent, Node s) {
super(parent, s);
}
}
super(parent, s);
}
}
/**
* context used for top-level script declarations
@ -191,26 +190,41 @@ public class RhinoToAstTranslator implements TranslatorToCAst {
private static class BreakContext extends JavaScriptTranslatorToCAst.BreakContext<WalkContext, Node> implements WalkContext {
@Override
public WalkContext getParent() {
return (WalkContext) super.getParent();
}
BreakContext(WalkContext parent, Node breakTo, String label) {
super(parent, breakTo, label);
}
}
private static class LoopContext extends JavaScriptTranslatorToCAst.LoopContext<WalkContext, Node> implements WalkContext {
private static class LoopContext extends TranslatorToCAst.LoopContext<WalkContext, Node> implements WalkContext {
LoopContext(WalkContext parent, Node breakTo, Node continueTo, String label) {
super(parent, breakTo, continueTo, label);
}
@Override
public WalkContext getParent() {
return (WalkContext) super.getParent();
}
private static class TryCatchContext extends JavaScriptTranslatorToCAst.TryCatchContext<WalkContext, Node> implements WalkContext {
}
private static class TryCatchContext extends TranslatorToCAst.TryCatchContext<WalkContext, Node> implements WalkContext {
TryCatchContext(WalkContext parent, CAstNode catchNode) {
super(parent, catchNode);
}
@Override
public WalkContext getParent() {
return (WalkContext) super.getParent();
}
}
private static String operationReceiverName(int operationIndex) {
@ -554,15 +568,7 @@ public class RhinoToAstTranslator implements TranslatorToCAst {
return pos;
}
private void pushSourcePosition(WalkContext context, CAstNode n, Position p) {
if (context.pos().getPosition(n) == null && !(n.getKind()==CAstNode.FUNCTION_EXPR || n.getKind()==CAstNode.FUNCTION_STMT)) {
context.pos().setPosition(n, p);
for(int i = 0; i < n.getChildCount(); i++) {
pushSourcePosition(context, n.getChild(i), p);
}
}
}
private CAstNode noteSourcePosition(WalkContext context, CAstNode n, AstNode p) {
protected CAstNode noteSourcePosition(WalkContext context, CAstNode n, AstNode p) {
if (p.getLineno() != -1 && context.pos().getPosition(n) == null) {
pushSourcePosition(context, n, makePosition(p));
}
@ -1696,8 +1702,8 @@ public class RhinoToAstTranslator implements TranslatorToCAst {
if (finallyNode != null) {
int i = 0;
CAstNode[] finallyAsts = new CAstNode[finallyList.size()];
for (Iterator<Node> fns = finallyList.iterator(); fns.hasNext();) {
finallyAsts[i++] = walkNodes(fns.next(), context);
for (Node fn : finallyList) {
finallyAsts[i++] = walkNodes(fn, context);
}
finallyBlock = Ast.makeNode(CAstNode.BLOCK_STMT, finallyAsts);
}
@ -1707,8 +1713,8 @@ public class RhinoToAstTranslator implements TranslatorToCAst {
int i = 0;
WalkContext catchChild = new CatchBlockContext(context);
CAstNode[] catchAsts = new CAstNode[catchList.size()];
for (Iterator<Node> cns = catchList.iterator(); cns.hasNext();) {
catchAsts[i++] = walkNodes(cns.next(), catchChild);
for (Node cn : catchList.iterator()) {
catchAsts[i++] = walkNodes(cn, catchChild);
}
CAstNode catchBlock = Ast.makeNode(CAstNode.CATCH, Ast.makeConstant(catchChild.getCatchVar()),
Ast.makeNode(CAstNode.BLOCK_STMT, catchAsts));
@ -1717,8 +1723,8 @@ public class RhinoToAstTranslator implements TranslatorToCAst {
i = 0;
WalkContext tryChild = new TryBlockContext(context, catchBlock);
CAstNode[] tryAsts = new CAstNode[tryList.size()];
for (Iterator<Node> tns = tryList.iterator(); tns.hasNext();) {
tryAsts[i++] = walkNodes(tns.next(), tryChild);
for (Node tn : tryList) {
tryAsts[i++] = walkNodes(tn, tryChild);
}
CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts);
@ -1732,8 +1738,8 @@ public class RhinoToAstTranslator implements TranslatorToCAst {
} else {
int i = 0;
CAstNode[] tryAsts = new CAstNode[tryList.size()];
for (Iterator<Node> tns = tryList.iterator(); tns.hasNext();) {
tryAsts[i++] = walkNodes(tns.next(), context);
for (Node tn : tryList) {
tryAsts[i++] = walkNodes(tn, context);
}
CAstNode tryBlock = Ast.makeNode(CAstNode.BLOCK_STMT, tryAsts);

View File

@ -13,8 +13,8 @@
<property name="javacVerbose" value="false"/>
<property name="logExtension" value=".log"/>
<property name="compilerArg" value=""/>
<property name="javacSource" value="1.5"/>
<property name="javacTarget" value="1.5"/>
<property name="javacSource" value="1.8"/>
<property name="javacTarget" value="1.8"/>
<!-- This property has been updated to correspond to the paths used by the latest Java update
on Mac OS X 10.6 (Java version 1.6.0_22). If you are not using this version of Mac OS X or Java,
try changing the value of the property to "${java.home}/../../../Classes" -->

View File

@ -19,7 +19,6 @@ import static com.ibm.wala.cast.tree.CAstNode.EMPTY;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
@ -99,12 +98,7 @@ public class CAstDumper {
scopedEntities.add(scopedEntity);
m.put(scopedEntity, e.getKey());
}
Collections.sort(scopedEntities, new Comparator<CAstEntity>() {
@Override
public int compare(CAstEntity o1, CAstEntity o2) {
return o1.getName().compareTo(o2.getName());
}
});
Collections.sort(scopedEntities, (o1, o2) -> o1.getName().compareTo(o2.getName()));
buf.append(indent(indent) + "> ");
boolean first = true;

View File

@ -12,8 +12,6 @@ package com.ibm.wala.cast.js.test;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import org.junit.Assert;
import org.junit.Test;
@ -33,7 +31,7 @@ import com.ibm.wala.ipa.slicer.Statement;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.collections.Iterator2Iterable;
public abstract class TestJavaScriptSlicer extends TestJSCallGraphShape {
@ -86,15 +84,9 @@ public abstract class TestJavaScriptSlicer extends TestJSCallGraphShape {
private Collection<Statement> findTargetStatement(CallGraph CG) {
final Collection<Statement> ss = HashSetFactory.make();
for(CGNode n : getNodes(CG, "suffix:_slice_target_fn")) {
for(Iterator<CGNode> callers = CG.getPredNodes(n); callers.hasNext(); ) {
final CGNode caller = callers.next();
for(Iterator<CallSiteReference> sites = CG.getPossibleSites(caller, n); sites.hasNext(); ) {
caller.getIR().getCallInstructionIndices(sites.next()).foreach(new IntSetAction() {
@Override
public void act(int x) {
ss.add(new NormalStatement(caller, x));
}
});
for(CGNode caller : Iterator2Iterable.make(CG.getPredNodes(n))) {
for(CallSiteReference site : Iterator2Iterable.make(CG.getPossibleSites(caller, n))) {
caller.getIR().getCallInstructionIndices(site).foreach(x -> ss.add(new NormalStatement(caller, x)));
}
}
}

View File

@ -57,6 +57,7 @@ import com.ibm.wala.util.NullProgressMonitor;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.MapIterator;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.OrdinalSet;
@ -132,8 +133,8 @@ public abstract class TestPointerAnalyses {
OrdinalSet<? extends InstanceKey> pointers = pa.getPointsToSet(l);
if (pointers != null) {
for(InstanceKey k : pointers) {
for(Iterator<Pair<CGNode, NewSiteReference>> css = k.getCreationSites(CG); css.hasNext(); ) {
result.add(css.next());
for(Pair<CGNode, NewSiteReference> cs : Iterator2Iterable.make(k.getCreationSites(CG))) {
result.add(cs);
}
}
}
@ -302,8 +303,8 @@ public abstract class TestPointerAnalyses {
System.err.println("empty " + f + " for " + k + "(" + k.getConcreteType() + ")");
}
if (dump) {
for(Iterator<Pair<CGNode, NewSiteReference>> css = k.getCreationSites(fbCG); css.hasNext(); ) {
System.err.println(css.next());
for(Pair<CGNode, NewSiteReference> cs : Iterator2Iterable.make(k.getCreationSites(fbCG))) {
System.err.println(cs);
}
}
}
@ -319,9 +320,9 @@ public abstract class TestPointerAnalyses {
PointerKey fbKey = fbPA.getHeapModel().getPointerKeyForLocal(node, vn);
OrdinalSet<T> fbPointsTo = fbPA.getPointsToSet(fbKey);
for(T o : fbPointsTo) {
for(Iterator<T> ps = proto.apply(o); ps.hasNext(); ) {
for(Iterator<Pair<CGNode, NewSiteReference>> css = ps.next().getCreationSites(CG); css.hasNext(); ) {
fbProtos.add(css.next());
for(T p : Iterator2Iterable.make(proto.apply(o))) {
for(Pair<CGNode, NewSiteReference> cs : Iterator2Iterable.make(p.getCreationSites(CG))) {
fbProtos.add(cs);
}
}
}
@ -333,23 +334,15 @@ public abstract class TestPointerAnalyses {
CallGraph CG,
CGNode node,
int vn) {
return getPrototypeSites(fbPA, CG, new Function<ObjectVertex,Iterator<ObjectVertex>>() {
@Override
public Iterator<ObjectVertex> apply(ObjectVertex o) {
PrototypeFieldVertex proto = new PrototypeFieldVertex(PrototypeField.__proto__, o);
if (hg.containsNode(proto)) {
return
new MapIterator<>(hg.getSuccNodes(proto),
new Function<Object,ObjectVertex>() {
@Override
public ObjectVertex apply(Object object) {
return (ObjectVertex)object;
}
});
} else {
return EmptyIterator.instance();
}
}
return getPrototypeSites(fbPA, CG, o -> {
PrototypeFieldVertex proto = new PrototypeFieldVertex(PrototypeField.__proto__, o);
if (hg.containsNode(proto)) {
return
new MapIterator<>(hg.getSuccNodes(proto),
ObjectVertex.class::cast);
} else {
return EmptyIterator.instance();
}
}, node, vn);
}
@ -357,12 +350,7 @@ public abstract class TestPointerAnalyses {
CallGraph CG,
CGNode node,
int vn) {
return getPrototypeSites(fbPA, CG, new Function<InstanceKey,Iterator<InstanceKey>>() {
@Override
public Iterator<InstanceKey> apply(InstanceKey o) {
return fbPA.getPointsToSet(new TransitivePrototypeKey(o)).iterator();
}
}, node, vn);
return getPrototypeSites(fbPA, CG, o -> fbPA.getPointsToSet(new TransitivePrototypeKey(o)).iterator(), node, vn);
}
private void testPageUserCodeEquivalent(URL page) throws WalaException, CancelException {
@ -371,13 +359,10 @@ public abstract class TestPointerAnalyses {
}
protected Predicate<MethodReference> nameFilter(final String name) {
return new Predicate<MethodReference>() {
@Override
public boolean test(MethodReference t) {
System.err.println(t + " " + name);
return t.getSelector().equals(AstMethodReference.fnSelector) &&
t.getDeclaringClass().getName().toString().startsWith("L" + name);
}
return t -> {
System.err.println(t + " " + name);
return t.getSelector().equals(AstMethodReference.fnSelector) &&
t.getDeclaringClass().getName().toString().startsWith("L" + name);
};
}

View File

@ -8,7 +8,7 @@ org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annota
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary=
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
org.eclipse.jdt.core.compiler.annotation.nullable.secondary=
org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve

View File

@ -1,68 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project>
<project name="com.ibm.wala.cast.js" default="getJars" basedir=".">
<property name="basews" value="${ws}"/>
<property name="baseos" value="${os}"/>
<property name="basearch" value="${arch}"/>
<property name="basenl" value="${nl}"/>
<!-- Compiler settings. -->
<property name="javacFailOnError" value="true"/>
<property name="javacDebugInfo" value="on"/>
<property name="javacVerbose" value="false"/>
<property name="logExtension" value=".log"/>
<property name="compilerArg" value=""/>
<property name="javacSource" value="1.5"/>
<property name="javacTarget" value="1.5"/>
<!-- This property has been updated to correspond to the paths used by the latest Java update
on Mac OS X 10.6 (Java version 1.6.0_22). If you are not using this version of Mac OS X or Java,
try changing the value of the property to "${java.home}/../../../Classes" -->
<condition property="dir_bootclasspath" value="${java.home}/../Classes">
<os family="mac"/>
</condition>
<property name="dir_bootclasspath" value="${java.home}/lib"/>
<path id="path_bootclasspath">
<fileset dir="${dir_bootclasspath}">
<include name="*.jar"/>
</fileset>
</path>
<property name="bootclasspath" refid="path_bootclasspath"/>
<property name="bundleJavacSource" value="${javacSource}"/>
<property name="bundleJavacTarget" value="${javacTarget}"/>
<property name="bundleBootClasspath" value="${bootclasspath}"/>
<target name="JerichoPresent" depends="init">
<available file="${plugin.destination}/lib/jericho-html-3.2.jar" property="jericho.present"/>
</target>
<target name="fetchJericho" depends="JerichoPresent" unless="jericho.present">
<delete dir="${temp.folder}"/>
<mkdir dir="${temp.folder}"/>
<get src="http://sourceforge.net/projects/jerichohtml/files/jericho-html/3.2/jericho-html-3.2.zip/download" dest="${temp.folder}/jericho-html-3.2.zip"/>
<unzip src="${temp.folder}/jericho-html-3.2.zip" dest="${temp.folder}"/>
<copy file="${temp.folder}/jericho-html-3.2/dist/jericho-html-3.2.jar" tofile="${plugin.destination}/lib/jericho-html-3.2.jar" />
<delete dir="${temp.folder}"/>
</target>
<target name="getJars" depends="fetchJericho" />
<target name="init" depends="properties">
<condition property="pluginTemp" value="${buildTempFolder}/plugins">
<isset property="buildTempFolder"/>
</condition>
<property name="pluginTemp" value="${basedir}"/>
<condition property="build.result.folder" value="${pluginTemp}/com.ibm.wala.core.testdata">
<isset property="buildTempFolder"/>
</condition>
<property name="build.result.folder" value="${basedir}"/>
<property name="temp.folder" value="${basedir}/temp.folder"/>
<property name="plugin.destination" value="${basedir}"/>
</target>
<target name="properties" if="eclipse.running">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
</target>
</project>

View File

@ -106,8 +106,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

View File

@ -29,6 +29,7 @@ import com.ibm.wala.cast.js.ipa.callgraph.JavaScriptFunctionApplyTargetSelector;
import com.ibm.wala.cast.js.ipa.callgraph.JavaScriptFunctionDotCallTargetSelector;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptConstructorFunctions;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptConstructorFunctions.JavaScriptConstructor;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
@ -146,7 +147,7 @@ public abstract class FieldBasedCallGraphBuilder {
@SuppressWarnings("deprecation")
public JSCallGraph extract(SSAContextInterpreter interpreter, FlowGraph flowgraph, Iterable<? extends Entrypoint> eps, IProgressMonitor monitor) throws CancelException {
// set up call graph
final JSCallGraph cg = new JSCallGraph(cha, options, cache);
final JSCallGraph cg = new JSCallGraph(JavaScriptLoader.JS.getFakeRootMethod(cha, options, cache), options, cache);
cg.init();
// setup context interpreters
@ -158,8 +159,7 @@ public abstract class FieldBasedCallGraphBuilder {
// set up call edges from fake root to all script nodes
AbstractRootMethod fakeRootMethod = (AbstractRootMethod)cg.getFakeRootNode().getMethod();
CGNode fakeRootNode = cg.findOrCreateNode(fakeRootMethod, Everywhere.EVERYWHERE);
for(Iterator<? extends Entrypoint> iter = eps.iterator(); iter.hasNext();) {
Entrypoint ep = iter.next();
for (Entrypoint ep : eps) {
CGNode nd = cg.findOrCreateNode(ep.getMethod(), Everywhere.EVERYWHERE);
SSAAbstractInvokeInstruction invk = ep.addCall(fakeRootMethod);
fakeRootNode.addTarget(invk.getCallSite(), nd);

View File

@ -10,8 +10,6 @@
*****************************************************************************/
package com.ibm.wala.cast.js.callgraph.fieldbased;
import java.util.Iterator;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.FlowGraph;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.FuncVertex;
import com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph.vertices.VertexFactory;
@ -30,6 +28,7 @@ import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.Iterator2Iterable;
/**
* Call graph builder for building pessimistic call graphs, where inter-procedural flows are not
@ -103,8 +102,7 @@ public class PessimisticCallGraphBuilder extends FieldBasedCallGraphBuilder {
FuncVertex callee = factory.makeFuncVertex(fnClass);
// look at all uses
for(Iterator<SSAInstruction> uses = du.getUses(defn);uses.hasNext();) {
SSAInstruction use = uses.next();
for(SSAInstruction use : Iterator2Iterable.make(du.getUses(defn))) {
// check whether this is a local call
if(use instanceof JavaScriptInvoke && ((JavaScriptInvoke)use).getFunction() == defn) {

View File

@ -14,7 +14,6 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import com.ibm.wala.analysis.pointers.HeapGraph;
import com.ibm.wala.cast.ipa.callgraph.AstHeapModel;
@ -61,6 +60,7 @@ import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.CompoundIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.graph.GraphReachability;
@ -106,32 +106,23 @@ public class FlowGraph implements Iterable<Vertex> {
private static <T> GraphReachability<Vertex, T> computeClosure(NumberedGraph<Vertex> graph, IProgressMonitor monitor, final Class<?> type) throws CancelException {
// prune flowgraph by taking out 'unknown' vertex
Graph<Vertex> pruned_flowgraph = GraphSlicer.prune(graph, new Predicate<Vertex>() {
@Override
public boolean test(Vertex t) {
return t.accept(new AbstractVertexVisitor<Boolean>() {
@Override
public Boolean visitVertex() {
return true;
}
@Override
public Boolean visitUnknownVertex(UnknownVertex unknownVertex) {
return false;
}
});
}
});
Graph<Vertex> pruned_flowgraph = GraphSlicer.prune(graph, t -> t.accept(new AbstractVertexVisitor<Boolean>() {
@Override
public Boolean visitVertex() {
return true;
}
@Override
public Boolean visitUnknownVertex(UnknownVertex unknownVertex) {
return false;
}
}));
// compute transitive closure
GraphReachability<Vertex, T> optimistic_closure =
new GraphReachability<>(
new InvertedGraph<>(pruned_flowgraph),
new Predicate<Vertex>() {
@Override public boolean test(Vertex o) {
return type.isInstance(o);
}
}
type::isInstance
);
optimistic_closure.solve(monitor);
@ -204,14 +195,12 @@ public class FlowGraph implements Iterable<Vertex> {
{
PropVertex proto = factory.makePropVertex("prototype");
if (graph.containsNode(proto)) {
for(Iterator<Vertex> ps = graph.getPredNodes(proto); ps.hasNext(); ) {
Vertex p = ps.next();
for(Vertex p : Iterator2Iterable.make(graph.getPredNodes(proto))) {
if (p instanceof VarVertex) {
int rval = ((VarVertex) p).getValueNumber();
FuncVertex func = ((VarVertex) p).getFunction();
DefUse du = cache.getDefUse(getIR(cache, func));
for(Iterator<SSAInstruction> insts = du.getUses(rval); insts.hasNext(); ) {
SSAInstruction inst = insts.next();
for(SSAInstruction inst : Iterator2Iterable.make(du.getUses(rval))) {
if (inst instanceof JavaScriptPropertyWrite) {
int obj = ((JavaScriptPropertyWrite) inst).getObjectRef();
VarVertex object = factory.makeVarVertex(func, obj);
@ -285,15 +274,10 @@ public class FlowGraph implements Iterable<Vertex> {
@Override
public Iterable<PointerKey> getPointerKeys() {
return new Iterable<PointerKey> () {
@Override
public Iterator<PointerKey> iterator() {
return new CompoundIterator<>(factory.getArgVertices().iterator(),
new CompoundIterator<>(factory.getRetVertices().iterator(),
new CompoundIterator<PointerKey>(factory.getVarVertices().iterator(),
factory.getPropVertices().iterator())));
}
};
return () -> new CompoundIterator<>(factory.getArgVertices().iterator(),
new CompoundIterator<>(factory.getRetVertices().iterator(),
new CompoundIterator<PointerKey>(factory.getVarVertices().iterator(),
factory.getPropVertices().iterator())));
}
@Override
@ -467,14 +451,12 @@ public class FlowGraph implements Iterable<Vertex> {
for(PropVertex property : factory.getPropVertices()) {
// edges from objects to properties assigned to them
for(Iterator<Vertex> ps = dataflow.getPredNodes(property); ps.hasNext(); ) {
Vertex p = ps.next();
for(Vertex p : Iterator2Iterable.make(dataflow.getPredNodes(property))) {
if (p instanceof VarVertex) {
int rval = ((VarVertex) p).getValueNumber();
FuncVertex func = ((VarVertex) p).getFunction();
DefUse du = cache.getDefUse(getIR(cache, func));
for(Iterator<SSAInstruction> insts = du.getUses(rval); insts.hasNext(); ) {
SSAInstruction inst = insts.next();
for(SSAInstruction inst : Iterator2Iterable.make(du.getUses(rval))) {
if (inst instanceof JavaScriptPropertyWrite) {
int obj = ((JavaScriptPropertyWrite) inst).getObjectRef();
VarVertex object = factory.makeVarVertex(func, obj);
@ -517,8 +499,7 @@ public class FlowGraph implements Iterable<Vertex> {
// prototype dataflow for object creations
for(CreationSiteVertex cs : factory.creationSites()) {
if (cg.getNode(cs.getMethod(), Everywhere.EVERYWHERE) != null) {
for(Iterator<Pair<CGNode, NewSiteReference>> sites = cs.getCreationSites(cg); sites.hasNext(); ) {
Pair<CGNode, NewSiteReference> site = sites.next();
for(Pair<CGNode, NewSiteReference> site : Iterator2Iterable.make(cs.getCreationSites(cg))) {
IR ir = site.fst.getIR();
SSAInstruction creation = ir.getInstructions()[ site.snd.getProgramCounter() ];
if (creation instanceof JavaScriptInvoke) {
@ -548,11 +529,7 @@ public class FlowGraph implements Iterable<Vertex> {
@Override
public Collection<Object> getReachableInstances(Set<Object> roots) {
return DFS.getReachableNodes(this, roots, new Predicate<Object>() {
@Override public boolean test(Object o) {
return o instanceof ObjectVertex;
}
});
return DFS.getReachableNodes(this, roots, ObjectVertex.class::isInstance);
}
@Override

View File

@ -10,8 +10,6 @@
*****************************************************************************/
package com.ibm.wala.cast.js.callgraph.fieldbased.flowgraph;
import java.util.Iterator;
import com.ibm.wala.cast.ir.ssa.AstGlobalRead;
import com.ibm.wala.cast.ir.ssa.AstGlobalWrite;
import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access;
@ -50,6 +48,7 @@ import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.intset.EmptyIntSet;
import com.ibm.wala.util.intset.IntSet;
@ -117,11 +116,11 @@ public class FlowGraphBuilder {
// now visit phis and catches
visitor.instructionIndex = -1;
for(Iterator<? extends SSAInstruction> iter=ir.iteratePhis();iter.hasNext();)
iter.next().visit(visitor);
for(SSAInstruction inst : Iterator2Iterable.make(ir.iteratePhis()))
inst.visit(visitor);
for(Iterator<SSAInstruction> iter=ir.iterateCatchInstructions();iter.hasNext();)
iter.next().visit(visitor);
for(SSAInstruction inst : Iterator2Iterable.make(ir.iterateCatchInstructions()))
inst.visit(visitor);
}
}

View File

@ -27,12 +27,7 @@ import com.ibm.wala.util.collections.Pair;
public class DefaultSourceExtractor extends DomLessSourceExtractor{
public static Supplier<JSSourceExtractor> factory = new Supplier<JSSourceExtractor>() {
@Override
public JSSourceExtractor get() {
return new DefaultSourceExtractor();
}
};
public static Supplier<JSSourceExtractor> factory = DefaultSourceExtractor::new;
protected static class HtmlCallBack extends DomLessSourceExtractor.HtmlCallback{

View File

@ -42,12 +42,7 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
private static final Pattern LEGAL_JS_IDENTIFIER_REGEXP = Pattern.compile("^[a-zA-Z$_][a-zA-Z\\d$_]*$");
private static final Pattern LEGAL_JS_KEYWORD_REGEXP = Pattern.compile("^((break)|(case)|(catch)|(continue)|(debugger)|(default)|(delete)|(do)|(else)|(finally)|(for)|(function)|(if)|(in)|(instanceof)|(new)|(return)|(switch)|(this)|(throw)|(try)|(typeof)|(var)|(void)|(while)|(with))$");
public static Supplier<JSSourceExtractor> factory = new Supplier<JSSourceExtractor>() {
@Override
public JSSourceExtractor get() {
return new DomLessSourceExtractor();
}
};
public static Supplier<JSSourceExtractor> factory = DomLessSourceExtractor::new;
protected interface IGeneratorCallback extends IHtmlCallback {
void writeToFinalRegion(SourceRegion finalRegion);

View File

@ -22,14 +22,12 @@ public interface IUrlResolver {
/**
* From Internet to local
* @param input
* @return
*/
public URL resolve(URL input);
/**
* From local to Internet
* @param input
* @return
*/
public URL deResolve(URL input);

View File

@ -19,7 +19,6 @@ public class UrlManipulator {
/**
* @param urlFound the link as appear
* @param context the URL in which the link appeared
* @return
* @throws MalformedURLException
*/
public static URL relativeToAbsoluteUrl(String urlFound, URL context) throws MalformedURLException {

View File

@ -28,12 +28,7 @@ public class WebUtil {
public static final String preamble = "preamble.js";
private static IHtmlParserFactory factory = new IHtmlParserFactory() {
@Override
public IHtmlParser getParser() {
return new JerichoHtmlParser();
}
};
private static IHtmlParserFactory factory = JerichoHtmlParser::new;
public static void setFactory(IHtmlParserFactory factory) {
WebUtil.factory = factory;

View File

@ -13,7 +13,6 @@ package com.ibm.wala.cast.js.html.jericho;
import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@ -110,8 +109,7 @@ public class JerichoHtmlParser implements IHtmlParser{
src = new Source(reader);
src.setLogger(Config.LoggerProvider.getLogger(fileName));
List<Element> childElements = src.getChildElements();
for (Iterator<Element> nodeIterator = childElements.iterator(); nodeIterator.hasNext();) {
Element e = nodeIterator.next();
for (Element e : childElements) {
parser.parse(e);
}
if (! warnings.isEmpty()) {
@ -139,8 +137,7 @@ public class JerichoHtmlParser implements IHtmlParser{
handler.handleStartTag(tag);
handler.handleText(tag.getElementPosition(), tag.getBodyText().snd);
List<Element> childElements = root.getChildElements();
for (Iterator<Element> nodeIterator = childElements.iterator(); nodeIterator.hasNext();) {
Element child = nodeIterator.next();
for (Element child : childElements) {
parse(child);
}
handler.handleEndTag(tag);

View File

@ -14,6 +14,7 @@ import java.util.Iterator;
import com.ibm.wala.cast.ipa.callgraph.AstCFAPointerKeys;
import com.ibm.wala.cast.ipa.callgraph.ReflectedFieldPointerKey;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
@ -34,7 +35,7 @@ import com.ibm.wala.util.strings.Atom;
public abstract class JSCFABuilder extends JSSSAPropagationCallGraphBuilder {
public JSCFABuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(cha, options, cache, new AstCFAPointerKeys() {
super(JavaScriptLoader.JS.getFakeRootMethod(cha, options, cache), options, cache, new AstCFAPointerKeys() {
private boolean isBogusKey(InstanceKey K) {
TypeReference t = K.getConcreteType().getReference();

View File

@ -14,14 +14,13 @@ import java.util.Set;
import com.ibm.wala.cast.ipa.callgraph.AstCallGraph;
import com.ibm.wala.cast.js.cfg.JSInducedCFG;
import com.ibm.wala.cast.js.loader.JSCallSiteReference;
import com.ibm.wala.cast.js.ssa.JavaScriptInvoke;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
@ -30,15 +29,13 @@ import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
public class JSCallGraph extends AstCallGraph {
public JSCallGraph(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(cha, options, cache);
public JSCallGraph(IMethod fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache) {
super(fakeRootClass, options, cache);
}
public final static MethodReference fakeRoot = MethodReference.findOrCreate(JavaScriptTypes.FakeRoot, FakeRootMethod.name,
@ -55,22 +52,9 @@ public class JSCallGraph extends AstCallGraph {
return new JSInducedCFG(instructions, this, Everywhere.EVERYWHERE);
}
@Override
public SSANewInstruction addAllocation(TypeReference T) {
if (cha.isSubclassOf(cha.lookupClass(T), cha.lookupClass(JavaScriptTypes.Root))) {
int instance = nextLocal++;
NewSiteReference ref = NewSiteReference.make(statements.size(), T);
SSANewInstruction result = getDeclaringClass().getClassLoader().getInstructionFactory().NewInstruction(statements.size(), instance, ref);
statements.add(result);
return result;
} else {
return super.addAllocation(T);
}
}
@Override
public SSAAbstractInvokeInstruction addDirectCall(int function, int[] params, CallSiteReference site) {
CallSiteReference newSite = new JSCallSiteReference(statements.size());
CallSiteReference newSite = new DynamicCallSiteReference(JavaScriptTypes.CodeBody, statements.size());
JavaScriptInvoke s = new JavaScriptInvoke(statements.size(), function, nextLocal++, params, nextLocal++, newSite);
statements.add(s);

View File

@ -107,7 +107,6 @@ public class JSCallGraphUtil extends com.ibm.wala.cast.ipa.callgraph.CAstCallGra
/**
* @param preprocessor CAst rewriter to use for preprocessing JavaScript source files; may be null
* @return
*/
public static JavaScriptLoaderFactory makeLoaders(CAstRewriterFactory<?, ?> preprocessor) {
if (translatorFactory == null) {

View File

@ -48,6 +48,7 @@ import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph;
import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey;
@ -151,9 +152,9 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
this.scriptBaseURL = url;
}
protected JSSSAPropagationCallGraphBuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache,
protected JSSSAPropagationCallGraphBuilder(AbstractRootMethod abstractRootMethod, AnalysisOptions options, IAnalysisCacheView cache,
PointerKeyFactory pointerKeyFactory) {
super(cha, options, cache, pointerKeyFactory);
super(abstractRootMethod, options, cache, pointerKeyFactory);
globalObject = new GlobalObjectKey(cha.lookupClass(JavaScriptTypes.Root));
}
@ -218,8 +219,8 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
return getPointerKeyForInstanceField(getGlobalObject(JavaScriptTypes.jsName), f);
}
@Override
protected ExplicitCallGraph createEmptyCallGraph(IClassHierarchy cha, AnalysisOptions options) {
return new JSCallGraph(cha, options, getAnalysisCache());
protected ExplicitCallGraph createEmptyCallGraph(IMethod fakeRootClass, AnalysisOptions options) {
return new JSCallGraph(fakeRootClass, options, getAnalysisCache());
}
protected TypeInference makeTypeInference(IR ir, IClassHierarchy cha) {
@ -528,8 +529,8 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
if (contentsAreInvariant(symbolTable, du, rval)) {
system.recordImplicitPointsToSet(rvalKey);
InstanceKey[] ik = getInvariantContents(rval);
for (int i = 0; i < ik.length; i++) {
system.newConstraint(p, ik[i]);
for (InstanceKey element : ik) {
system.newConstraint(p, element);
}
} else {
system.newConstraint(p, assignOperator, rvalKey);
@ -601,23 +602,20 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable ptrs) {
if (ptrs.getValue() != null) {
ptrs.getValue().foreachExcluding(previous, new IntSetAction() {
@Override
public void act(int x) {
final InstanceKey functionObj = system.getInstanceKey(x);
visitInvokeInternal(instruction, new DefaultInvariantComputer() {
@Override
public InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call) {
InstanceKey[][] x = super.computeInvariantParameters(call);
if (x == null) {
x = new InstanceKey[call.getNumberOfUses()][];
}
x[0] = new InstanceKey[]{ functionObj };
x[1] = new InstanceKey[]{ receiverType };
return x;
ptrs.getValue().foreachExcluding(previous, x -> {
final InstanceKey functionObj = system.getInstanceKey(x);
visitInvokeInternal(instruction, new DefaultInvariantComputer() {
@Override
public InstanceKey[][] computeInvariantParameters(SSAAbstractInvokeInstruction call) {
InstanceKey[][] x = super.computeInvariantParameters(call);
if (x == null) {
x = new InstanceKey[call.getNumberOfUses()][];
}
});
}
x[0] = new InstanceKey[]{ functionObj };
x[1] = new InstanceKey[]{ receiverType };
return x;
}
});
});
previous.addAll(ptrs.getValue());
}
@ -668,8 +666,8 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
if (contentsAreInvariant(symbolTable, du, receiverVn)) {
system.recordImplicitPointsToSet(receiverKey);
InstanceKey[] ik = getInvariantContents(receiverVn);
for (int i = 0; i < ik.length; i++) {
handleJavascriptDispatch(instruction, ik[i]);
for (InstanceKey element : ik) {
handleJavascriptDispatch(instruction, element);
}
} else {
class ReceiverForDispatchOp extends UnaryOperator<PointsToSetVariable> {
@ -682,17 +680,14 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
@Override
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
if (rhs.getValue() != null) {
rhs.getValue().foreachExcluding(previous, new IntSetAction() {
@Override
public void act(int x) {
try {
MonitorUtil.throwExceptionIfCanceled(getBuilder().monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
InstanceKey ik = system.getInstanceKey(x);
handleJavascriptDispatch(instruction, ik);
rhs.getValue().foreachExcluding(previous, x -> {
try {
MonitorUtil.throwExceptionIfCanceled(getBuilder().monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
InstanceKey ik = system.getInstanceKey(x);
handleJavascriptDispatch(instruction, ik);
});
previous.addAll(rhs.getValue());
}
@ -775,12 +770,7 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
return new InstanceKey[0];
} else {
final Set<InstanceKey> temp = HashSetFactory.make();
v.getValue().foreach(new IntSetAction() {
@Override
public void act(int keyIndex) {
temp.add(system.getInstanceKey(keyIndex));
}
});
v.getValue().foreach(keyIndex -> temp.add(system.getInstanceKey(keyIndex)));
return temp.toArray(new InstanceKey[temp.size()]);
}
@ -810,17 +800,17 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
InstanceKey[] iks2 = getInstancesArray(arg2);
if ((instruction.getOperator() == BinaryOpInstruction.Operator.ADD) && (getOptions().getTraceStringConstants())) {
for (int i = 0; i < iks1.length; i++) {
if (isStringConstant(iks1[i])) {
for (int j = 0; j < iks2.length; j++) {
if (isStringConstant(iks2[j])) {
for (InstanceKey element : iks1) {
if (isStringConstant(element)) {
for (InstanceKey element2 : iks2) {
if (isStringConstant(element2)) {
try {
MonitorUtil.throwExceptionIfCanceled(builder.monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
String v1 = (String) ((ConstantKey<?>) iks1[i]).getValue();
String v2 = (String) ((ConstantKey<?>) iks2[j]).getValue();
String v1 = (String) ((ConstantKey<?>) element).getValue();
String v2 = (String) ((ConstantKey<?>) element2).getValue();
if (v1.indexOf(v2) == -1 && v2.indexOf(v1) == -1) {
InstanceKey lvalKey = getInstanceKeyForConstant(v1 + v2);
if (addKey(lvalKey)) {
@ -842,14 +832,14 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
}
if (doDefault) {
for (int i = 0; i < iks1.length; i++) {
for (int j = 0; j < iks2.length; j++) {
for (InstanceKey element : iks1) {
for (InstanceKey element2 : iks2) {
try {
MonitorUtil.throwExceptionIfCanceled(builder.monitor);
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
if (handleBinaryOperatorArgs(iks1[i], iks2[j])) {
if (handleBinaryOperatorArgs(element, element2)) {
changed = CHANGED;
}
}
@ -1097,8 +1087,8 @@ public class JSSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraph
InstanceKey[] nullkeys = builder.getInvariantContents(sourceST, sourceDU, caller, nullvn, builder);
for (int i = argCount; i < paramCount; i++) {
PointerKey F = builder.getPointerKeyForLocal(target, targetST.getParameter(i));
for (int k = 0; k < nullkeys.length; k++) {
builder.getSystem().newConstraint(F, nullkeys[k]);
for (InstanceKey nullkey : nullkeys) {
builder.getSystem().newConstraint(F, nullkey);
}
}
}

View File

@ -110,8 +110,8 @@ public class JSZeroOrOneXCFABuilder extends JSCFABuilder {
public static JSCFABuilder make(JSAnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, ClassLoader cl,
AnalysisScope scope, String[] xmlFiles, byte instancePolicy, boolean doOneCFA) {
com.ibm.wala.ipa.callgraph.impl.Util.addDefaultSelectors(options, cha);
for (int i = 0; i < xmlFiles.length; i++) {
com.ibm.wala.ipa.callgraph.impl.Util.addBypassLogic(options, scope, cl, xmlFiles[i], cha);
for (String xmlFile : xmlFiles) {
com.ibm.wala.ipa.callgraph.impl.Util.addBypassLogic(options, scope, cl, xmlFile, cha);
}
return new JSZeroOrOneXCFABuilder(cha, options, cache, null, null, instancePolicy, doOneCFA);

View File

@ -11,8 +11,8 @@
package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.ipa.callgraph.ScriptEntryPoints;
import com.ibm.wala.cast.js.loader.JSCallSiteReference;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IMethod;
@ -22,7 +22,7 @@ public class JavaScriptEntryPoints extends ScriptEntryPoints {
@Override
protected CallSiteReference makeScriptSite(IMethod m, int pc) {
return new JSCallSiteReference(pc);
return new DynamicCallSiteReference(JavaScriptTypes.CodeBody, pc);
}
public JavaScriptEntryPoints(IClassHierarchy cha, IClassLoader loader) {

View File

@ -13,8 +13,9 @@ package com.ibm.wala.cast.js.ipa.callgraph;
import com.ibm.wala.cast.ipa.callgraph.AstContextInsensitiveSSAContextInterpreter;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummarizedFunction;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummary;
import com.ibm.wala.cast.js.loader.JSCallSiteReference;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
@ -30,9 +31,7 @@ import com.ibm.wala.types.TypeName;
/**
* TODO cache generated IRs
*
* @see <a
* href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Apply">MDN
* Function.apply() docs</a> *
* @see <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Apply">MDN Function.apply() docs</a>
*/
public class JavaScriptFunctionApplyContextInterpreter extends AstContextInsensitiveSSAContextInterpreter {
@ -105,7 +104,7 @@ public class JavaScriptFunctionApplyContextInterpreter extends AstContextInsensi
// int curValNum = passArbitraryPropertyValAsParams(insts, nargs, S, paramsToPassToInvoked);
int curValNum = passActualPropertyValsAsParams(insts, nargs, S, paramsToPassToInvoked);
CallSiteReference cs = new JSCallSiteReference(S.getNextProgramCounter());
CallSiteReference cs = new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNextProgramCounter());
// function being invoked is in v2
int resultVal = curValNum++;
@ -177,7 +176,7 @@ public class JavaScriptFunctionApplyContextInterpreter extends AstContextInsensi
// generate invocation instruction for the real method being invoked
int resultVal = nargs + 2;
CallSiteReference cs = new JSCallSiteReference(S.getNextProgramCounter());
CallSiteReference cs = new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNextProgramCounter());
int[] params = new int[1];
params[0] = 3;
// function being invoked is in v2

View File

@ -15,11 +15,12 @@ import java.util.Map;
import com.ibm.wala.cast.ipa.callgraph.CAstCallGraphUtil;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummarizedFunction;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummary;
import com.ibm.wala.cast.js.loader.JSCallSiteReference;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
@ -124,7 +125,6 @@ public class JavaScriptFunctionDotCallTargetSelector implements MethodTargetSele
* @param caller
* @param site
* @param receiver
* @return
*/
private IMethod getFunctionCallTarget(CGNode caller, CallSiteReference site, IClass receiver) {
int nargs = getNumberOfArgsPassed(caller, site);
@ -154,7 +154,7 @@ public class JavaScriptFunctionDotCallTargetSelector implements MethodTargetSele
// generate invocation instruction for the real method being invoked
int resultVal = nargs + 2;
CallSiteReference cs = new JSCallSiteReference(S.getNextProgramCounter());
CallSiteReference cs = new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNextProgramCounter());
int[] params = new int[nargs - 2];
for (int i = 0; i < params.length; i++) {
// add 3 to skip v1 (which points to Function.call() itself) and v2 (the

View File

@ -15,9 +15,9 @@ import java.util.Collections;
import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.loader.JavaScriptLoader.JavaScriptMethodObject;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstMethod.LexicalParent;
import com.ibm.wala.cast.loader.CAstAbstractModuleLoader.DynamicMethodObject;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
@ -50,7 +50,7 @@ public class JavaScriptScopeMappingInstanceKeys extends ScopeMappingInstanceKeys
}
protected LexicalParent[] getParents(InstanceKey base) {
JavaScriptMethodObject function = (JavaScriptMethodObject)
DynamicMethodObject function = (DynamicMethodObject)
base.getConcreteType().getMethod(AstMethodReference.fnSelector);
return function==null? new LexicalParent[0]: function.getParents();

View File

@ -130,7 +130,6 @@ public class RecursionCheckContextSelector implements ContextSelector {
/**
* is it possible for m to be involved in a recursive cycle?
* @param m
* @return
*/
private static boolean recursionPossible(IMethod m) {
// object or array constructors cannot be involved

View File

@ -464,8 +464,8 @@ public class ClosureExtractor extends CAstRewriterExt {
CAstNode[] before = new CAstNode[tler.getStartInner()];
for(i=0;i<tler.getStartInner();++i)
before[i] = copyNodes(start.getChild(i), cfg, context, nodeMap);
for(int x = 0; x < before.length; x++) {
prologue.add(before[x]);
for (CAstNode element : before) {
prologue.add(element);
}
if(i+1 == start.getChildCount()) {
fun_body_stmts.add(addSpuriousExnFlow(start.getChild(i), cfg));
@ -473,8 +473,8 @@ public class ClosureExtractor extends CAstRewriterExt {
CAstNode[] after = new CAstNode[start.getChildCount()-i];
for(int j=0;j+i<start.getChildCount();++j)
after[j] = addSpuriousExnFlow(start.getChild(j+i), cfg);
for(int x = 0; x < after.length; x++) {
fun_body_stmts.add(after[x]);
for (CAstNode element : after) {
fun_body_stmts.add(element);
}
}
for(i=context.getStart()+1;i<context.getEnd();++i)

View File

@ -30,6 +30,7 @@ import com.ibm.wala.cast.tree.rewrite.CAstRewriter.Rewrite;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
/**
* A simple implementation of {@link CAstEntity} used by the {@link ClosureExtractor}.
@ -120,8 +121,7 @@ class ExtractedFunction implements CAstEntity {
}
}
// now, add all new entities which arise from extracted nested for-in loops
for(Iterator<ExtractionPos> iter=pos.getNestedLoops(); iter.hasNext();) {
ExtractionPos nested_loop = iter.next();
for(ExtractionPos nested_loop : Iterator2Iterable.make(pos.getNestedLoops())) {
CAstNode callsite = nested_loop.getCallSite();
CAstEntity scoped_entity = nested_loop.getExtractedEntity();
Collection<CAstEntity> c = scopedEntities.get(callsite);

View File

@ -12,8 +12,6 @@
package com.ibm.wala.cast.js.ipa.modref;
import java.util.Collection;
import java.util.Iterator;
import com.ibm.wala.cast.ipa.callgraph.AstHeapModel;
import com.ibm.wala.cast.ipa.modref.AstModRef;
import com.ibm.wala.cast.js.ssa.JSInstructionVisitor;
@ -31,6 +29,7 @@ import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.modref.ExtendedHeapModel;
import com.ibm.wala.util.collections.Iterator2Iterable;
public class JavaScriptModRef<T extends InstanceKey> extends AstModRef<T> {
@ -56,8 +55,7 @@ public class JavaScriptModRef<T extends InstanceKey> extends AstModRef<T> {
PointerKey prop = h.getPointerKeyForLocal(n, instruction.getMemberRef());
for(InstanceKey o : pa.getPointsToSet(obj)) {
for(InstanceKey p : pa.getPointsToSet(prop)) {
for(Iterator<PointerKey> keys = h.getPointerKeysForReflectedFieldRead(o, p); keys.hasNext(); ) {
PointerKey x = keys.next();
for(PointerKey x : Iterator2Iterable.make(h.getPointerKeysForReflectedFieldRead(o, p))) {
assert x != null : instruction;
result.add(x);
}
@ -130,8 +128,7 @@ public class JavaScriptModRef<T extends InstanceKey> extends AstModRef<T> {
PointerKey prop = h.getPointerKeyForLocal(n, instruction.getMemberRef());
for(T o : pa.getPointsToSet(obj)) {
for(T p : pa.getPointsToSet(prop)) {
for(Iterator<PointerKey> keys = h.getPointerKeysForReflectedFieldWrite(o, p); keys.hasNext(); ) {
PointerKey x = keys.next();
for(PointerKey x : Iterator2Iterable.make(h.getPointerKeysForReflectedFieldWrite(o, p))) {
assert x != null : instruction;
result.add(x);
}

View File

@ -22,11 +22,11 @@ import java.util.Map;
import java.util.Set;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraphUtil;
import com.ibm.wala.cast.js.loader.JSCallSiteReference;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
@ -316,7 +316,7 @@ public class JavaScriptConstructorFunctions {
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 4, 2, "toString"));
S.getNextProgramCounter();
CallSiteReference cs = new JSCallSiteReference(S.getNextProgramCounter());
CallSiteReference cs = new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNextProgramCounter());
S.addStatement(insts.Invoke(S.getNumberOfStatements(), 4, 5, new int[] { 2 }, 6, cs));
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 5, false));
@ -356,7 +356,7 @@ public class JavaScriptConstructorFunctions {
S.addStatement(insts.GetInstruction(S.getNumberOfStatements(), 4, 2, "toNumber"));
S.getNextProgramCounter();
CallSiteReference cs = new JSCallSiteReference(S.getNextProgramCounter());
CallSiteReference cs = new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNextProgramCounter());
S.addStatement(insts.Invoke(S.getNumberOfStatements(), 4, 5, new int[] { 2 }, 6, cs));
S.addStatement(insts.ReturnInstruction(S.getNumberOfStatements(), 5, false));
@ -569,7 +569,7 @@ public class JavaScriptConstructorFunctions {
S.addStatement(insts.SetPrototype(S.getNumberOfStatements(), nargs + 5, nargs + 4));
S.getNextProgramCounter();
CallSiteReference cs = new JSCallSiteReference(S.getNextProgramCounter());
CallSiteReference cs = new DynamicCallSiteReference(JavaScriptTypes.CodeBody, S.getNextProgramCounter());
int[] args = new int[nargs + 1];
args[0] = nargs + 5;
for (int i = 0; i < nargs; i++)

View File

@ -28,12 +28,12 @@ import com.ibm.wala.cast.ir.ssa.AstLexicalRead;
import com.ibm.wala.cast.ir.ssa.AstLexicalWrite;
import com.ibm.wala.cast.ir.ssa.EachElementGetInstruction;
import com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction;
import com.ibm.wala.cast.ir.translator.AstTranslator;
import com.ibm.wala.cast.ir.translator.AstTranslator.AstLexicalInformation;
import com.ibm.wala.cast.ir.translator.AstTranslator.WalkContext;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.ir.translator.TranslatorToIR;
import com.ibm.wala.cast.js.analysis.typeInference.JSPrimitiveType;
import com.ibm.wala.cast.js.ipa.callgraph.JSCallGraph.JSFakeRoot;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.ssa.JavaScriptCheckReference;
import com.ibm.wala.cast.js.ssa.JavaScriptInstanceOf;
@ -47,30 +47,26 @@ import com.ibm.wala.cast.js.ssa.SetPrototype;
import com.ibm.wala.cast.js.translator.JSAstTranslator;
import com.ibm.wala.cast.js.translator.JavaScriptTranslatorFactory;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.AstClass;
import com.ibm.wala.cast.loader.AstDynamicPropertyClass;
import com.ibm.wala.cast.loader.AstFunctionClass;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation;
import com.ibm.wala.cast.loader.AstMethod.Retranslatable;
import com.ibm.wala.cast.loader.CAstAbstractModuleLoader;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstQualifier;
import com.ibm.wala.cast.tree.CAstSourcePositionMap;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.cast.types.AstMethodReference;
import com.ibm.wala.cast.types.AstTypeReference;
import com.ibm.wala.cfg.AbstractCFG;
import com.ibm.wala.cfg.IBasicBlock;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.LanguageImpl;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrikeBT.IBinaryOpInstruction.IOperator;
import com.ibm.wala.shrikeBT.IComparisonInstruction.Operator;
@ -109,10 +105,8 @@ import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.Selector;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.types.annotations.Annotation;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.strings.Atom;
@ -668,12 +662,13 @@ public class JavaScriptLoader extends CAstAbstractModuleLoader {
return false;
}
@Override
public AbstractRootMethod getFakeRootMethod(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
return new JSFakeRoot(cha, options, cache);
}
};
private static final Map<Selector, IMethod> emptyMap1 = Collections.emptyMap();
private static final Map<Atom, IField> emptyMap2 = Collections.emptyMap();
private final JavaScriptTranslatorFactory translatorFactory;
private final CAstRewriterFactory<?, ?> preprocessor;
@ -688,106 +683,6 @@ public class JavaScriptLoader extends CAstAbstractModuleLoader {
this.preprocessor = preprocessor;
}
public class JavaScriptClass extends AstClass {
private IClass superClass;
private JavaScriptClass(IClassLoader loader, TypeReference classRef, TypeReference superRef,
CAstSourcePositionMap.Position sourcePosition) {
super(sourcePosition, classRef.getName(), loader, (short) 0, emptyMap2, emptyMap1);
types.put(classRef.getName(), this);
superClass = superRef == null ? null : loader.lookupClass(superRef.getName());
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
@Override
public String toString() {
return "JS:" + getReference().toString();
}
@Override
public Collection<IClass> getDirectInterfaces() {
return Collections.emptySet();
}
@Override
public IClass getSuperclass() {
return superClass;
}
@Override
public Collection<Annotation> getAnnotations() {
return Collections.emptySet();
}
}
public class JavaScriptRootClass extends AstDynamicPropertyClass {
private JavaScriptRootClass(IClassLoader loader, CAstSourcePositionMap.Position sourcePosition) {
super(sourcePosition, JavaScriptTypes.Root.getName(), loader, (short) 0, emptyMap1, JavaScriptTypes.Root);
types.put(JavaScriptTypes.Root.getName(), this);
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
@Override
public String toString() {
return "JS Root:" + getReference().toString();
}
@Override
public Collection<IClass> getDirectInterfaces() {
return Collections.emptySet();
}
@Override
public IClass getSuperclass() {
return null;
}
@Override
public Collection<Annotation> getAnnotations() {
return Collections.emptySet();
}
}
class JavaScriptCodeBody extends AstFunctionClass {
private final WalkContext translationContext;
private final CAstEntity entity;
public JavaScriptCodeBody(TypeReference codeName, TypeReference parent, IClassLoader loader,
CAstSourcePositionMap.Position sourcePosition, CAstEntity entity, WalkContext context) {
super(codeName, parent, loader, sourcePosition);
types.put(codeName.getName(), this);
this.translationContext = context;
this.entity = entity;
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
private IMethod setCodeBody(JavaScriptMethodObject codeBody) {
this.functionBody = codeBody;
codeBody.entity = entity;
codeBody.translationContext = translationContext;
return codeBody;
}
@Override
public Collection<Annotation> getAnnotations() {
return Collections.emptySet();
}
}
private static final Set<CAstQualifier> functionQualifiers;
static {
@ -796,113 +691,8 @@ public class JavaScriptLoader extends CAstAbstractModuleLoader {
functionQualifiers.add(CAstQualifier.FINAL);
}
public class JavaScriptMethodObject extends AstMethod implements Retranslatable {
private WalkContext translationContext;
private CAstEntity entity;
JavaScriptMethodObject(IClass cls, AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock,
Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo) {
super(cls, functionQualifiers, cfg, symtab, AstMethodReference.fnReference(cls.getReference()), hasCatchBlock, caughtTypes,
hasMonitorOp, lexicalInfo, debugInfo, null);
// force creation of these constants by calling the getter methods
symtab.getNullConstant();
}
@Override
public CAstEntity getEntity() {
return entity;
}
@Override
public void retranslate(AstTranslator xlator) {
xlator.translate(entity, translationContext);
}
@Override
public IClassHierarchy getClassHierarchy() {
return cha;
}
@Override
public String toString() {
return "<Code body of " + cls + ">";
}
@Override
public TypeReference[] getDeclaredExceptions() {
return null;
}
@Override
public LexicalParent[] getParents() {
if (lexicalInfo() == null)
return new LexicalParent[0];
final String[] parents = lexicalInfo().getScopingParents();
if (parents == null)
return new LexicalParent[0];
LexicalParent result[] = new LexicalParent[parents.length];
for (int i = 0; i < parents.length; i++) {
final int hack = i;
final AstMethod method = (AstMethod) lookupClass(parents[i], cha).getMethod(AstMethodReference.fnSelector);
result[i] = new LexicalParent() {
@Override
public String getName() {
return parents[hack];
}
@Override
public AstMethod getMethod() {
return method;
}
};
if (AstTranslator.DEBUG_LEXICAL) {
System.err.println(("parent " + result[i].getName() + " is " + result[i].getMethod()));
}
}
return result;
}
@Override
public String getLocalVariableName(int bcIndex, int localNumber) {
return null;
}
@Override
public boolean hasLocalVariableTable() {
return false;
}
public int getMaxLocals() {
Assertions.UNREACHABLE();
return -1;
}
public int getMaxStackHeight() {
Assertions.UNREACHABLE();
return -1;
}
@Override
public TypeReference getParameterType(int i) {
if (i == 0) {
return getDeclaringClass().getReference();
} else {
return JavaScriptTypes.Root;
}
}
}
public IClass makeCodeBodyType(String name, TypeReference P, CAstSourcePositionMap.Position sourcePosition, CAstEntity entity, WalkContext context) {
return new JavaScriptCodeBody(TypeReference.findOrCreate(JavaScriptTypes.jsLoader, TypeName.string2TypeName(name)), P, this,
return new DynamicCodeBody(TypeReference.findOrCreate(JavaScriptTypes.jsLoader, TypeName.string2TypeName(name)), P, this,
sourcePosition, entity, context);
}
@ -916,59 +706,59 @@ public class JavaScriptLoader extends CAstAbstractModuleLoader {
public IMethod defineCodeBodyCode(String clsName, AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock,
Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo) {
JavaScriptCodeBody C = (JavaScriptCodeBody) lookupClass(clsName, cha);
DynamicCodeBody C = (DynamicCodeBody) lookupClass(clsName, cha);
assert C != null : clsName;
return C.setCodeBody(makeCodeBodyCode(cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo, debugInfo, C));
}
public JavaScriptMethodObject makeCodeBodyCode(AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock,
public DynamicMethodObject makeCodeBodyCode(AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock,
Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo,
IClass C) {
return new JavaScriptMethodObject(C, cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo,
return new DynamicMethodObject(C, functionQualifiers, cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo,
debugInfo);
}
final JavaScriptRootClass ROOT = new JavaScriptRootClass(this, null);
final CoreClass ROOT = new CoreClass(AstTypeReference.rootTypeName, null, this, null);
final JavaScriptClass UNDEFINED = new JavaScriptClass(this, JavaScriptTypes.Undefined, JavaScriptTypes.Root, null);
final CoreClass UNDEFINED = new CoreClass(JavaScriptTypes.Undefined.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass PRIMITIVES = new JavaScriptClass(this, JavaScriptTypes.Primitives, JavaScriptTypes.Root, null);
final CoreClass PRIMITIVES = new CoreClass(JavaScriptTypes.Primitives.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass FAKEROOT = new JavaScriptClass(this, JavaScriptTypes.FakeRoot, JavaScriptTypes.Root, null);
final CoreClass FAKEROOT = new CoreClass(JavaScriptTypes.FakeRoot.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass STRING = new JavaScriptClass(this, JavaScriptTypes.String, JavaScriptTypes.Root, null);
final CoreClass STRING = new CoreClass(JavaScriptTypes.String.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass NULL = new JavaScriptClass(this, JavaScriptTypes.Null, JavaScriptTypes.Root, null);
final CoreClass NULL = new CoreClass(JavaScriptTypes.Null.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass ARRAY = new JavaScriptClass(this, JavaScriptTypes.Array, JavaScriptTypes.Root, null);
final CoreClass ARRAY = new CoreClass(JavaScriptTypes.Array.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass OBJECT = new JavaScriptClass(this, JavaScriptTypes.Object, JavaScriptTypes.Root, null);
final CoreClass OBJECT = new CoreClass(JavaScriptTypes.Object.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass TYPE_ERROR = new JavaScriptClass(this, JavaScriptTypes.TypeError, JavaScriptTypes.Root, null);
final CoreClass TYPE_ERROR = new CoreClass(JavaScriptTypes.TypeError.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass CODE_BODY = new JavaScriptClass(this, JavaScriptTypes.CodeBody, JavaScriptTypes.Root, null);
final CoreClass CODE_BODY = new CoreClass(JavaScriptTypes.CodeBody.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass FUNCTION = new JavaScriptClass(this, JavaScriptTypes.Function, JavaScriptTypes.CodeBody, null);
final CoreClass FUNCTION = new CoreClass(JavaScriptTypes.Function.getName(), JavaScriptTypes.CodeBody.getName(), this, null);
final JavaScriptClass SCRIPT = new JavaScriptClass(this, JavaScriptTypes.Script, JavaScriptTypes.CodeBody, null);
final CoreClass SCRIPT = new CoreClass(JavaScriptTypes.Script.getName(), JavaScriptTypes.CodeBody.getName(), this, null);
final JavaScriptClass BOOLEAN = new JavaScriptClass(this, JavaScriptTypes.Boolean, JavaScriptTypes.Root, null);
final CoreClass BOOLEAN = new CoreClass(JavaScriptTypes.Boolean.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass NUMBER = new JavaScriptClass(this, JavaScriptTypes.Number, JavaScriptTypes.Root, null);
final CoreClass NUMBER = new CoreClass(JavaScriptTypes.Number.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass DATE = new JavaScriptClass(this, JavaScriptTypes.Date, JavaScriptTypes.Root, null);
final CoreClass DATE = new CoreClass(JavaScriptTypes.Date.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass REGEXP = new JavaScriptClass(this, JavaScriptTypes.RegExp, JavaScriptTypes.Root, null);
final CoreClass REGEXP = new CoreClass(JavaScriptTypes.RegExp.getName(), JavaScriptTypes.Root.getName(), this, null);
final JavaScriptClass BOOLEAN_OBJECT = new JavaScriptClass(this, JavaScriptTypes.BooleanObject, JavaScriptTypes.Object, null);
final CoreClass BOOLEAN_OBJECT = new CoreClass(JavaScriptTypes.BooleanObject.getName(), JavaScriptTypes.Object.getName(), this, null);
final JavaScriptClass NUMBER_OBJECT = new JavaScriptClass(this, JavaScriptTypes.NumberObject, JavaScriptTypes.Object, null);
final CoreClass NUMBER_OBJECT = new CoreClass(JavaScriptTypes.NumberObject.getName(), JavaScriptTypes.Object.getName(), this, null);
final JavaScriptClass DATE_OBJECT = new JavaScriptClass(this, JavaScriptTypes.DateObject, JavaScriptTypes.Object, null);
final CoreClass DATE_OBJECT = new CoreClass(JavaScriptTypes.DateObject.getName(), JavaScriptTypes.Object.getName(), this, null);
final JavaScriptClass REGEXP_OBJECT = new JavaScriptClass(this, JavaScriptTypes.RegExpObject, JavaScriptTypes.Object, null);
final CoreClass REGEXP_OBJECT = new CoreClass(JavaScriptTypes.RegExpObject.getName(), JavaScriptTypes.Object.getName(), this, null);
final JavaScriptClass STRING_OBJECT = new JavaScriptClass(this, JavaScriptTypes.StringObject, JavaScriptTypes.Object, null);
final CoreClass STRING_OBJECT = new CoreClass(JavaScriptTypes.StringObject.getName(), JavaScriptTypes.Object.getName(), this, null);
@Override
public Language getLanguage() {

View File

@ -16,13 +16,13 @@ import java.util.Map;
import java.util.Set;
import com.ibm.wala.cast.ir.translator.AstTranslator;
import com.ibm.wala.cast.js.loader.JSCallSiteReference;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.ssa.JSInstructionFactory;
import com.ibm.wala.cast.js.ssa.JavaScriptInstanceOf;
import com.ibm.wala.cast.js.ssa.PrototypeLookup;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
import com.ibm.wala.cast.js.types.JavaScriptTypes;
import com.ibm.wala.cast.loader.DynamicCallSiteReference;
import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
@ -196,7 +196,7 @@ public class JSAstTranslator extends AstTranslator {
context.cfg().addInstruction(
((JSInstructionFactory) insts).Invoke(context.cfg().getCurrentInstruction(), receiver, result, arguments, exception,
new JSCallSiteReference(ref, context.cfg().getCurrentInstruction())));
new DynamicCallSiteReference(ref, context.cfg().getCurrentInstruction())));
context.cfg().addPreNode(call, context.getUnwindState());
@ -226,7 +226,7 @@ public class JSAstTranslator extends AstTranslator {
int tmp = super.doGlobalRead(n, context, "Function", JavaScriptTypes.Function);
context.cfg().addInstruction(
((JSInstructionFactory)insts).Invoke(context.cfg().getCurrentInstruction(), tmp, result, new int[]{ nm }, exception,
new JSCallSiteReference(JavaScriptMethods.ctorReference, context.cfg().getCurrentInstruction())));
new DynamicCallSiteReference(JavaScriptMethods.ctorReference, context.cfg().getCurrentInstruction())));
}
@Override

View File

@ -13,10 +13,6 @@ package com.ibm.wala.cast.js.translator;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.tree.CAst;
import com.ibm.wala.cast.tree.rewrite.AstLoopUnwinder;
import com.ibm.wala.cast.tree.rewrite.AstLoopUnwinder.UnwindKey;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter;
import com.ibm.wala.cast.tree.rewrite.CAstRewriter.RewriteContext;
import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory;
import com.ibm.wala.classLoader.ModuleEntry;
import com.ibm.wala.classLoader.SourceFileModule;
import com.ibm.wala.classLoader.SourceModule;
@ -46,12 +42,7 @@ public abstract class JavaScriptLoopUnwindingTranslatorFactory
}
TranslatorToCAst xlator = translateInternal(ast, (SourceModule)M, N);
xlator.addRewriter(new CAstRewriterFactory<CAstRewriter.RewriteContext<AstLoopUnwinder.UnwindKey>,AstLoopUnwinder.UnwindKey>() {
@Override
public CAstRewriter<RewriteContext<UnwindKey>, UnwindKey> createCAstRewriter(CAst ast) {
return new AstLoopUnwinder(ast, true, unwindFactor);
}
}, false);
xlator.addRewriter(ast1 -> new AstLoopUnwinder(ast1, true, unwindFactor), false);
return xlator;
}

View File

@ -12,26 +12,24 @@ package com.ibm.wala.cast.js.translator;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import com.ibm.wala.cast.ir.translator.TranslatorToCAst;
import com.ibm.wala.cast.tree.CAstControlFlowMap;
import com.ibm.wala.cast.tree.CAstEntity;
import com.ibm.wala.cast.tree.CAstNode;
import com.ibm.wala.cast.tree.impl.CAstControlFlowRecorder;
import com.ibm.wala.cast.tree.impl.CAstSourcePositionRecorder;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.debug.Assertions;
public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
interface WalkContext<C extends WalkContext<C, T>, T> extends TranslatorToCAst.WalkContext<C, T> {
String script();
@Override
WalkContext<C, T> getParent();
T top();
default String script() {
return getParent().script();
}
/**
* Add a name declaration to this context. For variables or constants, n
@ -39,22 +37,35 @@ public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
* variable (if any) may occur in a separate assignment. For functions, n
* should be a {@link CAstNode#FUNCTION_STMT}, including the function body.
*/
void addNameDecl(CAstNode n);
default void addNameDecl(CAstNode n) {
getParent().addNameDecl(n);
}
Collection<CAstNode> getNameDecls();
default Collection<CAstNode> getNameDecls() {
return getParent().getNameDecls();
}
CAstNode getCatchTarget();
default int setOperation(T node) {
return getParent().setOperation(node);
}
int setOperation(T node);
boolean foundMemberOperation(T node);
void copyOperation(T from, T to);
default boolean foundMemberOperation(T node) {
return getParent().foundMemberOperation(node);
}
default void copyOperation(T from, T to) {
getParent().copyOperation(from, to);
}
}
public static class RootContext<C extends WalkContext<C, T>, T> extends TranslatorToCAst.RootContext<C, T> implements WalkContext<C,T> {
@Override
public WalkContext<C, T> getParent() {
assert false;
return null;
}
@Override
public String script() { return null; }
@ -98,35 +109,34 @@ public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
}
class DelegatingContext<C extends WalkContext<C, T>, T> extends TranslatorToCAst.DelegatingContext<C, T> implements WalkContext<C,T> {
public static class FunctionContext<C extends WalkContext<C, T>, T> extends TranslatorToCAst.FunctionContext<C, T> implements WalkContext<C,T> {
protected DelegatingContext(C parent) {
super(parent);
private final Vector<CAstNode> initializers = new Vector<>();
@Override
public WalkContext<C, T> getParent() {
return (WalkContext<C, T>) super.getParent();
}
protected FunctionContext(C parent, T s) {
super(parent, s);
}
@Override
public void addNameDecl(CAstNode v) { initializers.add(v); }
@Override
public Collection<CAstNode> getNameDecls() { return initializers; }
@Override
public String script() {
return parent.script();
}
@Override
public T top() {
return parent.top();
}
@Override
public void addNameDecl(CAstNode n) {
parent.addNameDecl(n);
}
@Override
public Collection<CAstNode> getNameDecls() {
return parent.getNameDecls();
}
@Override
public CAstNode getCatchTarget() {
return parent.getCatchTarget();
return CAstControlFlowMap.EXCEPTION_TO_EXIT;
}
@Override
@ -143,51 +153,6 @@ public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
public void copyOperation(T from, T to) {
parent.copyOperation(from, to);
}
}
public static class FunctionContext<C extends WalkContext<C, T>, T> extends DelegatingContext<C,T> {
private final T topNode;
private final CAstSourcePositionRecorder pos = new CAstSourcePositionRecorder();
private final CAstControlFlowRecorder cfg = new CAstControlFlowRecorder(pos);
private final Map<CAstNode, Collection<CAstEntity>> scopedEntities = HashMapFactory.make();
private final Vector<CAstNode> initializers = new Vector<>();
protected FunctionContext(C parent, T s) {
super(parent);
this.topNode = s;
}
@Override
public T top() { return topNode; }
@Override
public CAstNode getCatchTarget() { return CAstControlFlowMap.EXCEPTION_TO_EXIT; }
@Override
public void addScopedEntity(CAstNode construct, CAstEntity e) {
if (! scopedEntities.containsKey(construct)) {
scopedEntities.put(construct, new HashSet<CAstEntity>(1));
}
scopedEntities.get(construct).add(e);
}
@Override
public Map<CAstNode, Collection<CAstEntity>> getScopedEntities() {
return scopedEntities;
}
@Override
public void addNameDecl(CAstNode v) { initializers.add(v); }
@Override
public Collection<CAstNode> getNameDecls() { return initializers; }
@Override
public CAstControlFlowRecorder cfg() { return cfg; }
@Override
public CAstSourcePositionRecorder pos() { return pos; }
}
public static class ScriptContext<C extends WalkContext<C, T>, T> extends FunctionContext<C,T> {
@ -202,48 +167,6 @@ public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
public String script() { return script; }
}
public static class TryCatchContext<C extends WalkContext<C, T>, T> extends DelegatingContext<C,T> {
private final CAstNode catchNode;
protected TryCatchContext(C parent, CAstNode catchNode) {
super(parent);
this.catchNode = catchNode;
}
@Override
public CAstNode getCatchTarget() { return catchNode; }
}
class BreakContext<C extends WalkContext<C, T>, T> extends DelegatingContext<C,T> {
private final T breakTarget;
protected final String label;
protected BreakContext(C parent, T breakTarget, String label) {
super(parent);
this.breakTarget = breakTarget;
this.label = label;
}
@Override
public T getBreakFor(String l) {
return (l == null || l.equals(label))? breakTarget: super.getBreakFor(l);
}
}
public class LoopContext<C extends WalkContext<C, T>, T> extends BreakContext<C,T> {
private final T continueTo;
protected LoopContext(C parent, T breakTo, T continueTo, String label) {
super(parent, breakTo, label);
this.continueTo = continueTo;
}
@Override
public T getContinueFor(String l) {
return (l == null || l.equals(label))? continueTo: super.getContinueFor(l);
}
}
/**
* Used to determine the value to be passed as the 'this' argument for a
* function call. This is needed since in JavaScript, you can write a call
@ -255,7 +178,8 @@ public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
* 'this' parameter in baseVar, and then to use baseVar as the actual argument
* sub-node for the CAst call node
*/
public class MemberDestructuringContext<C extends WalkContext<C, T>, T> extends DelegatingContext<C,T> {
public class MemberDestructuringContext<C extends WalkContext<C, T>, T> implements WalkContext<C,T> {
private final WalkContext<C, T> parent;
/**
* node for which we actually care about what the base pointer is. this
@ -272,7 +196,7 @@ public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
private boolean foundBase = false;
protected MemberDestructuringContext(C parent, T initialBaseFor, int operationIndex) {
super(parent);
this.parent = parent;
baseFor.add( initialBaseFor );
this.operationIndex = operationIndex;
}
@ -296,6 +220,11 @@ public interface JavaScriptTranslatorToCAst extends TranslatorToCAst {
public void copyOperation(T from, T to) {
if (baseFor.contains(from)) baseFor.add(to);
}
@Override
public WalkContext<C, T> getParent() {
return parent;
}
}
}

View File

@ -145,7 +145,6 @@ public class PropertyReadExpander extends CAstRewriter<PropertyReadExpander.Rewr
* @param element
* @param context
* @param nodeMap
* @return
*/
private CAstNode makeConstRead(CAstNode root, CAstNode receiver, CAstNode element, RewriteContext context,
Map<Pair<CAstNode, ExpanderKey>, CAstNode> nodeMap) {

View File

@ -10,10 +10,8 @@
*****************************************************************************/
package com.ibm.wala.cast.js.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import com.ibm.wala.cast.js.loader.JavaScriptLoader;
import com.ibm.wala.cast.js.types.JavaScriptMethods;
@ -25,6 +23,7 @@ import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.MapUtil;
import com.ibm.wala.util.collections.Util;
@ -73,14 +72,8 @@ public class CallGraph2JSON {
continue;
AstMethod method = (AstMethod)nd.getMethod();
for(Iterator<CallSiteReference> iter = nd.iterateCallSites(); iter.hasNext();) {
CallSiteReference callsite = iter.next();
Set<IMethod> targets = Util.mapToSet(cg.getPossibleTargets(nd, callsite), new Function<CGNode, IMethod>() {
@Override
public IMethod apply(CGNode nd) {
return nd.getMethod();
}
});
for(CallSiteReference callsite : Iterator2Iterable.make(nd.iterateCallSites())) {
Set<IMethod> targets = Util.mapToSet(cg.getPossibleTargets(nd, callsite), CGNode::getMethod);
serializeCallSite(method, callsite, targets, edges);
}
}
@ -137,23 +130,15 @@ public class CallGraph2JSON {
public static String toJSON(Map<String, Set<String>> map) {
StringBuffer res = new StringBuffer();
res.append("{\n");
res.append(joinWith(Util.mapToSet(map.entrySet(), new Function<Map.Entry<String, Set<String>>, String>() {
@Override
public String apply(Map.Entry<String, Set<String>> e) {
StringBuffer res = new StringBuffer();
if(e.getValue().size() > 0) {
res.append(" \"" + e.getKey() + "\": [\n");
res.append(joinWith(Util.mapToSet(e.getValue(), new Function<String, String>() {
@Override
public String apply(String str) {
return " \"" + str + "\"";
}
}), ",\n"));
res.append("\n ]");
}
return res.length() == 0 ? null : res.toString();
}
}), ",\n"));
res.append(joinWith(Util.mapToSet(map.entrySet(), e -> {
StringBuffer res1 = new StringBuffer();
if(e.getValue().size() > 0) {
res1.append(" \"" + e.getKey() + "\": [\n");
res1.append(joinWith(Util.mapToSet(e.getValue(), str -> " \"" + str + "\""), ",\n"));
res1.append("\n ]");
}
return res1.length() == 0 ? null : res1.toString();
}), ",\n"));
res.append("\n}");
return res.toString();
}

View File

@ -10,15 +10,13 @@
*******************************************************************************/
package com.ibm.wala.cast.js.util;
import java.util.Iterator;
import com.ibm.wala.cast.js.ssa.PrototypeLookup;
import com.ibm.wala.ssa.DefUse;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
@ -35,14 +33,10 @@ public class Util {
int size;
do {
size = result.size();
result.foreach(new IntSetAction() {
@Override
public void act(int vn) {
for(Iterator<SSAInstruction> insts = du.getUses(vn); insts.hasNext(); ) {
SSAInstruction inst = insts.next();
if (inst instanceof PrototypeLookup || inst instanceof SSAPhiInstruction) {
result.add(inst.getDef());
}
result.foreach(vn -> {
for(SSAInstruction inst : Iterator2Iterable.make(du.getUses(vn))) {
if (inst instanceof PrototypeLookup || inst instanceof SSAPhiInstruction) {
result.add(inst.getDef());
}
}
});

View File

@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project>
<!--
=======================================================================
WALA CAst core tests build file
=======================================================================
-->
<project name="com.ibm.wala.cast.test" default="jar" basedir=".">
<!-- Software version details -->
<property name="name" value="walacasttest" />
<property name="module_name" value="com.ibm.wala.cast.test" />
<property name="Name" value="WALA CAst core tests" />
<property name="version" value="1-alpha" />
<!-- Compilation switches -->
<property name="debug" value="true" />
<property name="deprecation" value="false" />
<property name="optimize" value="true" />
<property name="javacFailOnError" value="true" />
<property name="javacDebugInfo" value="on" />
<property name="javacVerbose" value="false" />
<!-- Set global properties for this build -->
<property name="src" value="harness-src" />
<property name="build" value="build" />
<property name="build.result" value="${basedir}" />
<property name="build.tests" value="${basedir}" />
<property name="build.javadocs" value="${build}/javadocs" />
<property name="publish.javadocs" value="javadocs/com.ibm.wala.cast.test" />
<property name="dist" value="dist" />
<property name="etc" value="etc" />
<property name="docs" value="docs" />
<property name="lib" value="lib" />
<property name="mainlib" value="../mainlib" />
<property name="sharedlib" value="../sharedlib" />
<property name="templates" value="../com.ibm.safe/templates"/>
<property name="specifications" value="../com.ibm.safe/specifications"/>
<property name="cvsroot" value="/gsa/watgsa/home/d/o/dolby/cvs/JTD"/>
<property name="excluded-tests-file" value="excluded-tests.txt" />
<import file="${sharedlib}/scripts/common-tests-targets.xml"/>
</project>

View File

@ -27,8 +27,8 @@ $(C_GENERATED)/smoke_main.o: $(TEST_JNI_BRIDGE_HEADER) smoke_main.cpp
$(CAST_TEST_BIN)$(LIBPREFIX)xlator_test.$(DLLEXT): $(C_GENERATED)/smoke.o
$(CC) $(CC_LDFLAGS) -Wl,-rpath -Wl,$(DOMO_AST_BIN) $(CAST_OBJS) -o $@
main: /tmp/smoke_main
main: $(C_GENERATED)/smoke_main
/tmp/smoke_main: $(TEST_JNI_BRIDGE_HEADER) $(DOMO_AST_BIN)/$(LIBPREFIX)cast/launch.o $(C_GENERATED)/smoke_main.o
$(C_GENERATED)/smoke_main: $(TEST_JNI_BRIDGE_HEADER) $(DOMO_AST_BIN)/$(LIBPREFIX)cast/launch.o $(C_GENERATED)/smoke_main.o
$(CC) $(ALL_FLAGS) $(DOMO_AST_BIN)/$(LIBPREFIX)cast/launch.o $(C_GENERATED)/smoke_main.o $(CC_LD_PATHS) -o $@

View File

@ -37,7 +37,7 @@ int main(int argc, char **argv) {
JNIEnv *java_env = launch_jvm(buf);
printf("2: %s\n", buf);
printf("2: %s, %p\n", buf, java_env);
jclass NativeTranslatorTest =
java_env->FindClass("com/ibm/wala/cast/test/TestNativeTranslator");

View File

@ -14,7 +14,6 @@ import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@ -78,8 +77,7 @@ public abstract class TestCAstTranslator extends WalaTestCase {
}
public TranslatorAssertions(Object[][] data) {
for (int dataIndex = 0; dataIndex < data.length; dataIndex++) {
Object[] entry = data[dataIndex];
for (Object[] entry : data) {
String clsName = (String) entry[0];
this.classes.add(clsName);
@ -88,29 +86,29 @@ public abstract class TestCAstTranslator extends WalaTestCase {
String[] instanceFields = (String[]) entry[2];
if (instanceFields != null) {
for (int i = 0; i < instanceFields.length; i++) {
this.instanceFields.add(Pair.make(clsName, instanceFields[i]));
for (String instanceField : instanceFields) {
this.instanceFields.add(Pair.make(clsName, instanceField));
}
}
String[] staticFields = (String[]) entry[3];
if (staticFields != null) {
for (int i = 0; i < staticFields.length; i++) {
this.staticFields.add(Pair.make(clsName, staticFields[i]));
for (String staticField : staticFields) {
this.staticFields.add(Pair.make(clsName, staticField));
}
}
Pair<?, ?>[] instanceMethods = (Pair[]) entry[4];
if (instanceMethods != null) {
for (int i = 0; i < instanceMethods.length; i++) {
this.instanceMethods.put(Pair.make(clsName, (Object) instanceMethods[i].fst), instanceMethods[i].snd);
for (Pair<?, ?> instanceMethod : instanceMethods) {
this.instanceMethods.put(Pair.make(clsName, (Object) instanceMethod.fst), instanceMethod.snd);
}
}
Pair<?, ?>[] staticMethods = (Pair[]) entry[5];
if (staticMethods != null) {
for (int i = 0; i < staticMethods.length; i++) {
this.staticMethods.put(Pair.make(clsName, (Object) staticMethods[i].fst), staticMethods[i].snd);
for (Pair<?, ?> staticMethod : staticMethods) {
this.staticMethods.put(Pair.make(clsName, (Object) staticMethod.fst), staticMethod.snd);
}
}
}
@ -138,19 +136,19 @@ public abstract class TestCAstTranslator extends WalaTestCase {
}
protected void dump(ClassHierarchy cha) {
for (Iterator<?> clss = cha.iterator(); clss.hasNext();) {
IClass cls = (IClass) clss.next();
for (Object name : cha) {
IClass cls = (IClass) name;
System.err.println(("class " + cls));
for (Iterator<?> flds = cls.getDeclaredInstanceFields().iterator(); flds.hasNext();) {
IField fld = (IField) flds.next();
for (Object name2 : cls.getDeclaredInstanceFields()) {
IField fld = (IField) name2;
System.err.println(("instance field " + fld));
}
for (Iterator<?> flds = cls.getDeclaredStaticFields().iterator(); flds.hasNext();) {
IField fld = (IField) flds.next();
for (Object name2 : cls.getDeclaredStaticFields()) {
IField fld = (IField) name2;
System.err.println(("static field " + fld));
}
for (Iterator<?> mths = cls.getDeclaredMethods().iterator(); mths.hasNext();) {
IMethod mth = (IMethod) mths.next();
for (Object name2 : cls.getDeclaredMethods()) {
IMethod mth = (IMethod) name2;
if (mth.isStatic())
System.err.print("static ");
System.err.println(("method " + mth + " with " + mth.getNumberOfParameters() + " parameters"));
@ -171,8 +169,8 @@ public abstract class TestCAstTranslator extends WalaTestCase {
Map<Pair<String, Object>, Object> staticMethods = assertions.getStaticMethods();
int clsCount = 0;
for (Iterator<?> clss = cha.iterator(); clss.hasNext();) {
IClass cls = (IClass) clss.next();
for (Object name : cha) {
IClass cls = (IClass) name;
clsCount++;
Assert.assertTrue("found class " + cls.getName().toString(), classes.contains(cls.getName().toString()));
@ -183,20 +181,20 @@ public abstract class TestCAstTranslator extends WalaTestCase {
.get(cls.getName().toString()).equals(cls.getSuperclass().getName().toString()));
}
for (Iterator<?> flds = cls.getDeclaredInstanceFields().iterator(); flds.hasNext();) {
IField fld = (IField) flds.next();
for (Object name2 : cls.getDeclaredInstanceFields()) {
IField fld = (IField) name2;
Assert.assertTrue(cls.getName() + " has field " + fld.getName(), instanceFields.contains(Pair.make(
cls.getName().toString(), fld.getName().toString())));
}
for (Iterator<?> flds = cls.getDeclaredStaticFields().iterator(); flds.hasNext();) {
IField fld = (IField) flds.next();
for (Object name2 : cls.getDeclaredStaticFields()) {
IField fld = (IField) name2;
Assert.assertTrue(cls.getName() + " has static field " + fld.getName(), staticFields.contains(Pair.make(cls.getName()
.toString(), fld.getName().toString())));
}
for (Iterator<?> mths = cls.getDeclaredMethods().iterator(); mths.hasNext();) {
IMethod mth = (IMethod) mths.next();
for (Object name2 : cls.getDeclaredMethods()) {
IMethod mth = (IMethod) name2;
Integer np = new Integer(mth.getNumberOfParameters());
Pair<String, String> key = Pair.make(cls.getName().toString(), mth.getName().toString());

View File

@ -24,6 +24,7 @@ import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSACFG;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
public abstract class TestCallGraphShape extends WalaTestCase {
@ -100,26 +101,26 @@ public abstract class TestCallGraphShape extends WalaTestCase {
}
protected void verifyNameAssertions(CallGraph CG, Object[][] assertionData) {
for (int i = 0; i < assertionData.length; i++) {
Iterator<CGNode> NS = getNodes(CG, (String) assertionData[i][0]).iterator();
for (Object[] element : assertionData) {
Iterator<CGNode> NS = getNodes(CG, (String) element[0]).iterator();
while (NS.hasNext()) {
CGNode N = NS.next();
IR ir = N.getIR();
Name[] names = (Name[]) assertionData[i][1];
for (int j = 0; j < names.length; j++) {
Name[] names = (Name[]) element[1];
for (Name name : names) {
System.err.println("looking for " + names[j].name + ", " + names[j].vn + " in " + N);
System.err.println("looking for " + name.name + ", " + name.vn + " in " + N);
String[] localNames = ir.getLocalNames(names[j].instructionIndex, names[j].vn);
String[] localNames = ir.getLocalNames(name.instructionIndex, name.vn);
boolean found = false;
for (int k = 0; k < localNames.length; k++) {
if (localNames[k].equals(names[j].name)) {
for (String localName : localNames) {
if (localName.equals(name.name)) {
found = true;
}
}
Assert.assertTrue("no name " + names[j].name + " for " + N + "\n" + ir, found);
Assert.assertTrue("no name " + name.name + " for " + N + "\n" + ir, found);
}
}
}
@ -149,8 +150,7 @@ public abstract class TestCallGraphShape extends WalaTestCase {
while (srcs.hasNext()) {
CGNode src = srcs.next();
for (Iterator<CallSiteReference> sites = src.iterateCallSites(); sites.hasNext();) {
CallSiteReference sr = sites.next();
for (CallSiteReference sr : Iterator2Iterable.make(src.iterateCallSites())) {
Iterator<CGNode> dsts = getNodes(CG, targetName).iterator();
if (! checkAbsence) {
@ -159,8 +159,8 @@ public abstract class TestCallGraphShape extends WalaTestCase {
while (dsts.hasNext()) {
CGNode dst = dsts.next();
for (Iterator<CGNode> tos = CG.getPossibleTargets(src, sr).iterator(); tos.hasNext();) {
if (tos.next().equals(dst)) {
for (CGNode cgNode : CG.getPossibleTargets(src, sr)) {
if (cgNode.equals(dst)) {
if (checkAbsence) {
System.err.println(("found unexpected " + src + " --> " + dst + " at " + sr));
Assert.assertTrue("found edge " + assertionData[i][0] + " ---> " + targetName, false);
@ -194,8 +194,8 @@ public abstract class TestCallGraphShape extends WalaTestCase {
Collection<CGNode> dests = getNodes(CG, destDescription);
for (Object source : sources) {
for (Object dest : dests) {
for (Iterator<CGNode> i = CG.getSuccNodes((CGNode) source); i.hasNext();) {
if (i.next().equals(dest)) {
for (CGNode n : Iterator2Iterable.make(CG.getSuccNodes((CGNode) source))) {
if (n.equals(dest)) {
Assert.fail("Found a link from " + source + " to " + dest);
}
}

View File

@ -35,7 +35,7 @@
<id>test-native</id>
<phase>test</phase>
<configuration>
<executable>/tmp/smoke_main</executable>
<executable>${basedir}/../com.ibm.wala.cast/target/classes/libcast/smoke_main</executable>
<arguments>
<argument>${project.build.outputDirectory}:${basedir}/../com.ibm.wala.cast/target/classes:${basedir}/../com.ibm.wala.core/target/classes:${basedir}/../com.ibm.wala.util/target/classes</argument>
</arguments>

View File

@ -1,71 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project>
<!--
=======================================================================
WALA CAst build file
=======================================================================
-->
<project name="com.ibm.wala.cast" default="getJars" basedir=".">
<!-- Software version details -->
<property name="name" value="walacast" />
<property name="module_name" value="com.ibm.wala.cast" />
<property name="Name" value="walacast" />
<property name="version" value="1-alpha" />
<!-- Compilation switches -->
<property name="debug" value="true" />
<property name="deprecation" value="false" />
<property name="optimize" value="true" />
<property name="javacFailOnError" value="true" />
<property name="javacDebugInfo" value="on" />
<property name="javacVerbose" value="false" />
<!-- Set global properties for this build -->
<property name="src" value="source/java" />
<property name="nativesourcedir" value="source/c" />
<property name="src.tests" value="tests" />
<property name="build" value="build" />
<property name="build.result" value="${basedir}" />
<property name="build.tests" value="build/tests" />
<property name="build.javadocs" value="${build}/javadocs" />
<property name="publish.javadocs" value="javadocs/com.ibm.wala.cast" />
<property name="dist" value="dist" />
<property name="etc" value="etc" />
<property name="docs" value="docs" />
<property name="lib" value="lib" />
<property name="mainlib" value="../mainlib" />
<property name="sharedlib" value="../sharedlib" />
<target name="properties" if="eclipse.running">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
</target>
<target name="init" depends="properties">
<condition property="pluginTemp" value="${buildTempFolder}/plugins">
<isset property="buildTempFolder"/>
</condition>
<property name="pluginTemp" value="${basedir}"/>
<condition property="build.result.folder" value="${pluginTemp}/com.ibm.wala.core.testdata">
<isset property="buildTempFolder"/>
</condition>
<property name="build.result.folder" value="${basedir}"/>
<property name="temp.folder" value="${basedir}/temp.folder"/>
<property name="plugin.destination" value="${basedir}"/>
</target>
<target name="CommonsIoPresent" depends="init">
<available file="${plugin.destination}/lib/commons-io-2.4.jar" property="commons.io.present"/>
</target>
<target name="fetchCommonsIo" depends="CommonsIoPresent" unless="commons.io.present">
<delete dir="${temp.folder}"/>
<mkdir dir="${temp.folder}"/>
<get src="http://archive.apache.org/dist/commons/io/binaries/commons-io-2.4-bin.zip" dest="${temp.folder}/commons-io-2.4.zip"/>
<unzip src="${temp.folder}/commons-io-2.4.zip" dest="${temp.folder}"/>
<copy file="${temp.folder}/commons-io-2.4/commons-io-2.4.jar" tofile="${plugin.destination}/lib/commons-io-2.4.jar" />
<delete dir="${temp.folder}"/>
</target>
<target name="getJars" depends="fetchCommonsIo" />
</project>

View File

@ -91,8 +91,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

View File

@ -17,7 +17,7 @@ endif
vpath %.cpp jni
JAVA_INCLUDES = -I$(JAVA_SDK)include -I$(JAVA_SDK)include/$(JNI_MD_DIR) -DWALA_CLASSPATH="\"$(DOMO_AST_BIN)$(JAVAH_CLASS_PATH)\""
JAVA_INCLUDES = -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/$(JNI_MD_DIR) -DWALA_CLASSPATH="\"$(DOMO_AST_BIN)$(JAVAH_CLASS_PATH)\""
CAPA_INCLUDE_DIR = ../../../com.ibm.wala.cast/source/c/include/
CAPA_INCLUDES = -I$(CAPA_INCLUDE_DIR) -I$(C_GENERATED)
@ -57,7 +57,7 @@ else
endif
endif
CC_LD_PATHS = -L$(JAVA_SDK)jre/lib/amd64/server -Wl,-rpath -Wl,$(JAVA_SDK)jre/lib/amd64/server -L$(JAVA_SDK)jre/lib/x86_64/server -Wl,-rpath -Wl,$(JAVA_SDK)jre/lib/x86_64/server -L$(JAVA_SDK)jre/lib/x64/server -Wl,-rpath -Wl,$(JAVA_SDK)jre/lib/x64/server -L$(JAVA_SDK)jre/lib/server -Wl,-rpath -Wl,$(JAVA_SDK)jre/lib/server -L$(JAVA_SDK)jre/lib -Wl,-rpath -Wl,$(JAVA_SDK)jre/lib -ljvm
CC_LD_PATHS = -L$(JAVA_HOME)/jre/lib/amd64/server -Wl,-rpath -Wl,$(JAVA_HOME)/jre/lib/amd64/server -L$(JAVA_HOME)/jre/lib/x86_64/server -Wl,-rpath -Wl,$(JAVA_HOME)/jre/lib/x86_64/server -L$(JAVA_HOME)/jre/lib/x64/server -Wl,-rpath -Wl,$(JAVA_HOME)/jre/lib/x64/server -L$(JAVA_HOME)/jre/lib/server -Wl,-rpath -Wl,$(JAVA_HOME)/jre/lib/server -L$(JAVA_HOME)/jre/lib -Wl,-rpath -Wl,$(JAVA_HOME)/jre/lib -ljvm
CC_LDFLAGS += $(CC_LD_PATHS)

View File

@ -11,7 +11,6 @@
package com.ibm.wala.cast.ipa.callgraph;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Function;
@ -21,6 +20,7 @@ import com.ibm.wala.cfg.InducedCFG;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
@ -28,18 +28,18 @@ import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.AbstractRootMethod;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.impl.ExplicitCallGraph;
import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
public class AstCallGraph extends ExplicitCallGraph {
public AstCallGraph(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(cha, options, cache);
public AstCallGraph(IMethod fakeRootClass2, AnalysisOptions options, IAnalysisCacheView cache) {
super(fakeRootClass2, options, cache);
}
public static class AstFakeRoot extends AbstractRootMethod {
@ -76,6 +76,19 @@ public class AstCallGraph extends ExplicitCallGraph {
public abstract SSAAbstractInvokeInstruction addDirectCall(int functionVn, int[] argVns, CallSiteReference callSite);
@Override
public SSANewInstruction addAllocation(TypeReference T) {
if (cha.isSubclassOf(cha.lookupClass(T), cha.lookupClass(declaringClass.getClassLoader().getLanguage().getRootType()))) {
int instance = nextLocal++;
NewSiteReference ref = NewSiteReference.make(statements.size(), T);
SSANewInstruction result = getDeclaringClass().getClassLoader().getInstructionFactory().NewInstruction(statements.size(), instance, ref);
statements.add(result);
return result;
} else {
return super.addAllocation(T);
}
}
}
public class AstCGNode extends ExplicitNode {
@ -90,8 +103,8 @@ public class AstCallGraph extends ExplicitCallGraph {
boolean done = false;
while (!done) {
try {
for (Iterator<Function<Object, Object>> x = callbacks.iterator(); x.hasNext();) {
x.next().apply(null);
for (Function<Object, Object> function : callbacks) {
function.apply(null);
}
} catch (ConcurrentModificationException e) {
done = false;
@ -118,8 +131,8 @@ public class AstCallGraph extends ExplicitCallGraph {
callbacks.add(callback);
for (Iterator<CGNode> ps = getCallGraph().getPredNodes(this); ps.hasNext();) {
((AstCGNode) ps.next()).addCallback(callback);
for (CGNode p : Iterator2Iterable.make(getCallGraph().getPredNodes(this))) {
((AstCGNode) p).addCallback(callback);
}
}
}
@ -132,8 +145,8 @@ public class AstCallGraph extends ExplicitCallGraph {
callbacks.addAll(callback);
for (Iterator<CGNode> ps = getCallGraph().getPredNodes(this); ps.hasNext();) {
((AstCGNode) ps.next()).addAllCallbacks(callback);
for (CGNode p : Iterator2Iterable.make(getCallGraph().getPredNodes(this))) {
((AstCGNode) p).addAllCallbacks(callback);
}
}
}
@ -161,9 +174,4 @@ public class AstCallGraph extends ExplicitCallGraph {
return new AstCGNode(method, context);
}
@Override
protected CGNode makeFakeRootNode() throws CancelException {
return findOrCreateNode(new AstFakeRoot(FakeRootMethod.rootMethod, cha, options, getAnalysisCache()), Everywhere.EVERYWHERE);
}
}

View File

@ -34,6 +34,7 @@ import com.ibm.wala.cast.ir.translator.AstTranslator;
import com.ibm.wala.cast.loader.AstMethod;
import com.ibm.wala.cast.loader.AstMethod.LexicalInformation;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.fixpoint.AbstractOperator;
import com.ibm.wala.fixpoint.IntSetVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
@ -66,10 +67,10 @@ import com.ibm.wala.ssa.IRView;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetAction;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableMapping;
@ -115,9 +116,9 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public abstract GlobalObjectKey getGlobalObject(Atom language);
protected AstSSAPropagationCallGraphBuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache,
protected AstSSAPropagationCallGraphBuilder(IMethod fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache,
PointerKeyFactory pointerKeyFactory) {
super(cha, options, cache, pointerKeyFactory);
super(fakeRootClass, options, cache, pointerKeyFactory);
}
public SSAContextInterpreter makeDefaultContextInterpreters(SSAContextInterpreter appContextInterpreter, AnalysisOptions options,
@ -249,8 +250,8 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
// /////////////////////////////////////////////////////////////////////////
@Override
protected ExplicitCallGraph createEmptyCallGraph(IClassHierarchy cha, AnalysisOptions options) {
return new AstCallGraph(cha, options, getAnalysisCache());
protected ExplicitCallGraph createEmptyCallGraph(IMethod fakeRootClass, AnalysisOptions options) {
return new AstCallGraph(fakeRootClass, options, getAnalysisCache());
}
public static class AstInterestingVisitor extends InterestingVisitor implements AstInstructionVisitor {
@ -384,9 +385,9 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
if (contentsAreInvariant(lsymtab, ldu, lvn)) {
InstanceKey[] ik = getInvariantContents(lsymtab, ldu, lnode, lvn);
system.recordImplicitPointsToSet(lexicalKey);
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
system.newConstraint(lval, ik[i]);
for (InstanceKey element : ik) {
system.findOrCreateIndexForInstanceKey(element);
system.newConstraint(lval, element);
}
return;
@ -407,9 +408,9 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
if (contentsAreInvariant(symbolTable, du, vn)) {
InstanceKey[] ik = getInvariantContents(vn);
system.recordImplicitPointsToSet(rval);
for (int i = 0; i < ik.length; i++) {
system.findOrCreateIndexForInstanceKey(ik[i]);
system.newConstraint(lexicalKey, ik[i]);
for (InstanceKey element : ik) {
system.findOrCreateIndexForInstanceKey(element);
system.newConstraint(lexicalKey, element);
}
} else {
system.newConstraint(lexicalKey, assignOperator, rval);
@ -473,15 +474,12 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects.getValue().foreach(new IntSetAction() {
@Override
public void act(int optr) {
InstanceKey object = system.getInstanceKey(optr);
if (!getBuilder().isUncataloguedField(object.getConcreteType(), hack)) {
PointerKey cat = getPointerKeyForObjectCatalog(object);
if (cat != null) {
system.newConstraint(cat, fieldNameKeys[0]);
}
objects.getValue().foreach(optr -> {
InstanceKey object = system.getInstanceKey(optr);
if (!getBuilder().isUncataloguedField(object.getConcreteType(), hack)) {
PointerKey cat = getPointerKeyForObjectCatalog(object);
if (cat != null) {
system.newConstraint(cat, fieldNameKeys[0]);
}
}
});
@ -527,8 +525,8 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
if (contentsAreInvariant(symbolTable, du, rval)) {
InstanceKey objects[] = getInvariantContents(rval);
for (int i = 0; i < objects.length; i++) {
PointerKey catalog = getPointerKeyForObjectCatalog(objects[i]);
for (InstanceKey object : objects) {
PointerKey catalog = getPointerKeyForObjectCatalog(object);
system.newConstraint(lk, assignOperator, catalog);
}
}
@ -539,14 +537,11 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects.getValue().foreach(new IntSetAction() {
@Override
public void act(int optr) {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
if (objCatalog != null) {
system.newConstraint(lk, assignOperator, objCatalog);
}
objects.getValue().foreach(optr -> {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
if (objCatalog != null) {
system.newConstraint(lk, assignOperator, objCatalog);
}
});
}
@ -619,10 +614,10 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
* .
*/
private void doLexicalPointerKeys() {
for (int i = 0; i < accesses.length; i++) {
final String name = accesses[i].variableName;
final String definer = accesses[i].variableDefiner;
final int vn = accesses[i].valueNumber;
for (Access accesse : accesses) {
final String name = accesse.variableName;
final String definer = accesse.variableDefiner;
final int vn = accesse.valueNumber;
if (AstTranslator.DEBUG_LEXICAL)
System.err.println(("looking up lexical parent " + definer));
@ -707,9 +702,9 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
if (contentsAreInvariant(symtab, du, 1)) {
system.recordImplicitPointsToSet(F);
final InstanceKey[] functionKeys = getInvariantContents(symtab, du, opNode, 1);
for (int f = 0; f < functionKeys.length; f++) {
system.findOrCreateIndexForInstanceKey(functionKeys[f]);
ScopeMappingInstanceKey K = (ScopeMappingInstanceKey) functionKeys[f];
for (InstanceKey functionKey : functionKeys) {
system.findOrCreateIndexForInstanceKey(functionKey);
ScopeMappingInstanceKey K = (ScopeMappingInstanceKey) functionKey;
Iterator<CGNode> x = K.getFunargNodes(definer);
while (x.hasNext()) {
result.add(x.next());
@ -718,19 +713,16 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
} else {
PointsToSetVariable FV = system.findOrCreatePointsToSet(F);
if (FV.getValue() != null) {
FV.getValue().foreach(new IntSetAction() {
@Override
public void act(int ptr) {
InstanceKey iKey = system.getInstanceKey(ptr);
if (iKey instanceof ScopeMappingInstanceKey) {
ScopeMappingInstanceKey K = (ScopeMappingInstanceKey) iKey;
Iterator<CGNode> x = K.getFunargNodes(definer);
while (x.hasNext()) {
result.add(x.next());
}
} else {
Assertions.UNREACHABLE("unexpected instance key " + iKey);
FV.getValue().foreach(ptr -> {
InstanceKey iKey = system.getInstanceKey(ptr);
if (iKey instanceof ScopeMappingInstanceKey) {
ScopeMappingInstanceKey K = (ScopeMappingInstanceKey) iKey;
Iterator<CGNode> x = K.getFunargNodes(definer);
while (x.hasNext()) {
result.add(x.next());
}
} else {
Assertions.UNREACHABLE("unexpected instance key " + iKey);
}
});
}
@ -764,9 +756,9 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
if (contentsAreInvariant(st, du, vn)) {
system.recordImplicitPointsToSet(rhs);
final InstanceKey[] objs = getInvariantContents(st, du, definingNode, vn);
for (int f = 0; f < objs.length; f++) {
system.findOrCreateIndexForInstanceKey(objs[f]);
system.newConstraint(lhs, objs[f]);
for (InstanceKey obj : objs) {
system.findOrCreateIndexForInstanceKey(obj);
system.newConstraint(lhs, obj);
}
} else {
system.newConstraint(lhs, assignOperator, rhs);
@ -861,8 +853,8 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
if (contentsAreInvariant(symtab, du, objVn)) {
System.err.print(" constant obj:");
InstanceKey[] x = getInvariantContents(symtab, du, opNode, objVn);
for (int i = 0; i < x.length; i++) {
System.err.print((x[i].toString() + " "));
for (InstanceKey element : x) {
System.err.print((element.toString() + " "));
}
} else {
System.err.print((" obj:" + system.findOrCreatePointsToSet(objKey)));
@ -871,8 +863,8 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
if (contentsAreInvariant(symtab, du, fieldsVn)) {
System.err.print(" constant prop:");
InstanceKey[] x = getInvariantContents(symtab, du, opNode, fieldsVn);
for (int i = 0; i < x.length; i++) {
System.err.print((x[i].toString() + " "));
for (InstanceKey element : x) {
System.err.print((element.toString() + " "));
}
} else {
System.err.print((" props:" + system.findOrCreatePointsToSet(fieldKey)));
@ -884,14 +876,14 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
// make sure instance keys get mapped for PointerAnalysisImpl
if (contentsAreInvariant(symtab, du, objVn)) {
InstanceKey[] x = getInvariantContents(symtab, du, opNode, objVn);
for (int i = 0; i < x.length; i++) {
system.findOrCreateIndexForInstanceKey(x[i]);
for (InstanceKey element : x) {
system.findOrCreateIndexForInstanceKey(element);
}
}
if (contentsAreInvariant(symtab, du, fieldsVn)) {
InstanceKey[] x = getInvariantContents(symtab, du, opNode, fieldsVn);
for (int i = 0; i < x.length; i++) {
system.findOrCreateIndexForInstanceKey(x[i]);
for (InstanceKey element : x) {
system.findOrCreateIndexForInstanceKey(element);
}
}
@ -957,34 +949,28 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
final IntSetVariable<?> receivers = rhs[0];
final IntSetVariable<?> fields = rhs[1];
if (receivers.getValue() != null && fields.getValue() != null) {
receivers.getValue().foreach(new IntSetAction() {
@Override
public void act(final int rptr) {
final InstanceKey receiver = system.getInstanceKey(rptr);
receivers.getValue().foreach(rptr -> {
final InstanceKey receiver = system.getInstanceKey(rptr);
if (!isLoadOperation) {
PointerKey cat = getPointerKeyForObjectCatalog(receiver);
if (cat != null) {
system.newConstraint(cat, assignOperator, fieldKey);
if (!isLoadOperation) {
PointerKey cat = getPointerKeyForObjectCatalog(receiver);
if (cat != null) {
system.newConstraint(cat, assignOperator, fieldKey);
}
}
fields.getValue().foreach(fptr -> {
if (!doneField.contains(fptr) || !doneReceiver.contains(rptr)) {
InstanceKey field = system.getInstanceKey(fptr);
for (PointerKey pkey : Iterator2Iterable.make(isLoadOperation ? getPointerKeysForReflectedFieldRead(receiver, field)
: getPointerKeysForReflectedFieldWrite(receiver, field))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES)
action.dump(key, false, false);
action.action(key);
}
}
fields.getValue().foreach(new IntSetAction() {
@Override
public void act(int fptr) {
if (!doneField.contains(fptr) || !doneReceiver.contains(rptr)) {
InstanceKey field = system.getInstanceKey(fptr);
for (Iterator<PointerKey> keys = isLoadOperation ? getPointerKeysForReflectedFieldRead(receiver, field)
: getPointerKeysForReflectedFieldWrite(receiver, field); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, false, false);
action.action(key);
}
}
}
});
}
});
});
doneReceiver.addAll(receivers.getValue());
doneField.addAll(fields.getValue());
@ -1017,29 +1003,26 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> objects = rhs;
if (objects.getValue() != null) {
objects.getValue().foreach(new IntSetAction() {
@Override
public void act(int optr) {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
for (int f = 0; f < fieldsKeys.length; f++) {
if (isLoadOperation) {
for (Iterator<PointerKey> keys = getPointerKeysForReflectedFieldRead(object, fieldsKeys[f]); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, true, false);
action.action(key);
}
} else {
if (objCatalog != null) {
system.newConstraint(objCatalog, fieldsKeys[f]);
}
for (Iterator<PointerKey> keys = getPointerKeysForReflectedFieldWrite(object, fieldsKeys[f]); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, true, false);
action.action(key);
}
objects.getValue().foreach(optr -> {
InstanceKey object = system.getInstanceKey(optr);
PointerKey objCatalog = getPointerKeyForObjectCatalog(object);
for (InstanceKey fieldsKey : fieldsKeys) {
if (isLoadOperation) {
for (PointerKey pkey : Iterator2Iterable.make(getPointerKeysForReflectedFieldRead(object, fieldsKey))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES)
action.dump(key, true, false);
action.action(key);
}
} else {
if (objCatalog != null) {
system.newConstraint(objCatalog, fieldsKey);
}
for (PointerKey pkey : Iterator2Iterable.make(getPointerKeysForReflectedFieldWrite(object, fieldsKey))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES)
action.dump(key, true, false);
action.action(key);
}
}
}
@ -1068,8 +1051,8 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
protected void newFieldOperationOnlyObjectConstant(final boolean isLoadOperation, final ReflectedFieldAction action,
final PointerKey fieldKey, final InstanceKey[] objKeys) {
if (!isLoadOperation) {
for (int o = 0; o < objKeys.length; o++) {
PointerKey objCatalog = getPointerKeyForObjectCatalog(objKeys[o]);
for (InstanceKey objKey : objKeys) {
PointerKey objCatalog = getPointerKeyForObjectCatalog(objKey);
if (objCatalog != null) {
system.newConstraint(objCatalog, assignOperator, fieldKey);
}
@ -1081,18 +1064,15 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) {
final IntSetVariable<?> fields = rhs;
if (fields.getValue() != null) {
fields.getValue().foreach(new IntSetAction() {
@Override
public void act(int fptr) {
InstanceKey field = system.getInstanceKey(fptr);
for (int o = 0; o < objKeys.length; o++) {
for (Iterator<PointerKey> keys = isLoadOperation ? getPointerKeysForReflectedFieldRead(objKeys[o], field)
: getPointerKeysForReflectedFieldWrite(objKeys[o], field); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
if (DEBUG_PROPERTIES)
action.dump(key, false, true);
action.action(key);
}
fields.getValue().foreach(fptr -> {
InstanceKey field = system.getInstanceKey(fptr);
for (InstanceKey objKey : objKeys) {
for (PointerKey pkey : Iterator2Iterable.make(isLoadOperation ? getPointerKeysForReflectedFieldRead(objKey, field)
: getPointerKeysForReflectedFieldWrite(objKey, field))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES)
action.dump(key, false, true);
action.action(key);
}
}
});
@ -1119,22 +1099,22 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
protected void newFieldOperationObjectAndFieldConstant(final boolean isLoadOperation, final ReflectedFieldAction action,
final InstanceKey[] objKeys, InstanceKey[] fieldsKeys) {
for (int o = 0; o < objKeys.length; o++) {
PointerKey objCatalog = getPointerKeyForObjectCatalog(objKeys[o]);
for (int f = 0; f < fieldsKeys.length; f++) {
for (InstanceKey objKey : objKeys) {
PointerKey objCatalog = getPointerKeyForObjectCatalog(objKey);
for (InstanceKey fieldsKey : fieldsKeys) {
if (isLoadOperation) {
for (Iterator<PointerKey> keys = getPointerKeysForReflectedFieldRead(objKeys[o], fieldsKeys[f]); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
for (PointerKey pkey : Iterator2Iterable.make(getPointerKeysForReflectedFieldRead(objKey, fieldsKey))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES)
action.dump(key, true, true);
action.action(key);
}
} else {
if (objCatalog != null) {
system.newConstraint(objCatalog, fieldsKeys[f]);
system.newConstraint(objCatalog, fieldsKey);
}
for (Iterator<PointerKey> keys = getPointerKeysForReflectedFieldWrite(objKeys[o], fieldsKeys[f]); keys.hasNext();) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) keys.next();
for (PointerKey pkey : Iterator2Iterable.make(getPointerKeysForReflectedFieldWrite(objKey, fieldsKey))) {
AbstractFieldPointerKey key = (AbstractFieldPointerKey) pkey;
if (DEBUG_PROPERTIES)
action.dump(key, true, true);
action.action(key);
@ -1167,17 +1147,17 @@ public abstract class AstSSAPropagationCallGraphBuilder extends SSAPropagationCa
@Override
public void dump(AbstractFieldPointerKey fieldKey, boolean constObj, boolean constProp) {
System.err.println(("writing fixed rvals to " + fieldKey + " " + constObj + ", " + constProp));
for (int i = 0; i < rhsFixedValues.length; i++) {
System.err.println(("writing " + rhsFixedValues[i]));
for (InstanceKey rhsFixedValue : rhsFixedValues) {
System.err.println(("writing " + rhsFixedValue));
}
}
@Override
public void action(AbstractFieldPointerKey fieldKey) {
if (!representsNullType(fieldKey.getInstanceKey())) {
for (int i = 0; i < rhsFixedValues.length; i++) {
system.findOrCreateIndexForInstanceKey(rhsFixedValues[i]);
system.newConstraint(fieldKey, rhsFixedValues[i]);
for (InstanceKey rhsFixedValue : rhsFixedValues) {
system.findOrCreateIndexForInstanceKey(rhsFixedValue);
system.newConstraint(fieldKey, rhsFixedValue);
}
}
}

View File

@ -32,16 +32,16 @@ public class CAstAnalysisScope extends AnalysisScope {
public CAstAnalysisScope(String[] sourceFileNames, SingleClassLoaderFactory loaders, Collection<Language> languages) {
this(loaders, languages);
for (int i = 0; i < sourceFileNames.length; i++) {
File F = new File(sourceFileNames[i]);
for (String sourceFileName : sourceFileNames) {
File F = new File(sourceFileName);
addSourceFileToScope(theLoader, F, F.getPath());
}
}
public CAstAnalysisScope(Module[] sources, SingleClassLoaderFactory loaders, Collection<Language> languages) {
this(loaders, languages);
for (int i = 0; i < sources.length; i++) {
addToScope(theLoader, sources[i]);
for (Module source : sources) {
addToScope(theLoader, source);
}
}
@ -94,7 +94,6 @@ public class CAstAnalysisScope extends AnalysisScope {
*/
@Override
public ClassLoaderReference getSyntheticLoader() {
Assertions.UNREACHABLE();
return null;
}

View File

@ -16,8 +16,6 @@ import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Iterator;
import org.apache.commons.io.ByteOrderMark;
import org.apache.commons.io.input.BOMInputStream;
@ -37,6 +35,7 @@ import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ssa.IRFactory;
import com.ibm.wala.ssa.IRView;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
public class CAstCallGraphUtil {
@ -126,12 +125,12 @@ public class CAstCallGraphUtil {
for (CGNode N : CG) {
System.err.print("callees of node " + getShortName(N) + " : [");
boolean fst = true;
for (Iterator<? extends CGNode> ns = CG.getSuccNodes(N); ns.hasNext();) {
for (CGNode n : Iterator2Iterable.make(CG.getSuccNodes(N))) {
if (fst)
fst = false;
else
System.err.print(", ");
System.err.print(getShortName(ns.next()));
System.err.print(getShortName(n));
}
System.err.println("]");
System.err.println("\nIR of node " + N.getGraphNodeId() + ", context " + N.getContext());

View File

@ -28,9 +28,11 @@ import com.ibm.wala.ipa.callgraph.impl.FakeRootMethod;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.shrikeBT.IInvokeInstruction;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.collections.HashMapFactory;
@ -49,9 +51,9 @@ import com.ibm.wala.util.strings.Atom;
*/
public class CrossLanguageCallGraph extends AstCallGraph {
public CrossLanguageCallGraph(TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph> roots, IClassHierarchy cha,
public CrossLanguageCallGraph(TargetLanguageSelector<AbstractRootMethod, CrossLanguageCallGraph> roots, IMethod fakeRootClass2,
AnalysisOptions options, IAnalysisCacheView cache) {
super(cha, options, cache);
super(fakeRootClass2, options, cache);
this.roots = roots;
}
@ -91,14 +93,20 @@ public class CrossLanguageCallGraph extends AstCallGraph {
return (AbstractRootMethod) languageRoots.get(language);
}
public static ClassLoaderReference crossCoreLoader = ClassLoaderReference.Primordial;
public static TypeReference fakeRootClass = TypeReference.findOrCreate(crossCoreLoader, TypeName.findOrCreate("CrossFakeRoot"));
public static MethodReference rootMethod = MethodReference.findOrCreate(fakeRootClass, FakeRootMethod.name, FakeRootMethod.descr);
public class CrossLanguageFakeRoot extends ScriptFakeRoot {
public CrossLanguageFakeRoot(IClass declaringClass, IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(FakeRootMethod.rootMethod, declaringClass, cha, options, cache);
super(rootMethod, declaringClass, cha, options, cache);
}
public CrossLanguageFakeRoot(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) {
super(FakeRootMethod.rootMethod, cha, options, cache);
super(rootMethod, cha, options, cache);
}
public int addPhi(TypeReference type, int[] values) {
@ -138,14 +146,14 @@ public class CrossLanguageCallGraph extends AstCallGraph {
}
@Override
public SSAInvokeInstruction addInvocation(int[] params, CallSiteReference site) {
public SSAAbstractInvokeInstruction addInvocation(int[] params, CallSiteReference site) {
TypeReference type = site.getDeclaredTarget().getDeclaringClass();
Atom language = type.getClassLoader().getLanguage();
AbstractRootMethod root = getLanguageRoot(language);
return root.addInvocation(params, site);
}
public SSAInvokeInstruction addInvocationInternal(int[] params, CallSiteReference site) {
public SSAAbstractInvokeInstruction addInvocationInternal(int[] params, CallSiteReference site) {
return super.addInvocation(params, site);
}

Some files were not shown because too many files have changed in this diff Show More