repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/domain/FieldElement.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.domain;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.types.FieldReference;
public class FieldElement extends CodeElement {
private final FieldReference fieldRef;
private final InstanceKey object;
// private TypeReference object;
public FieldElement(InstanceKey object, FieldReference fieldRef) {
this.fieldRef = fieldRef;
this.object = object;
}
// public FieldElement(TypeReference object, String fieldname)
// {
// this.fieldname = fieldname;
// this.object = object;
// }
public InstanceKey getIK() {
return object;
}
public FieldReference getRef() {
return fieldRef;
}
@Override
public boolean equals(Object other) {
if (other != null && other instanceof FieldElement) {
FieldElement otherFE = (FieldElement) other;
return object.equals(otherFE.object) && fieldRef.equals(otherFE.fieldRef);
}
return false;
}
@Override
public int hashCode() {
return object.hashCode() * fieldRef.hashCode();
}
@Override
public String toString() {
return "FieldElement(" + fieldRef.getSignature() + ',' + object + ')';
}
}
| 3,129
| 31.947368
| 80
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/domain/IFDSTaintDomain.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.domain;
import com.ibm.wala.dataflow.IFDS.PathEdge;
import com.ibm.wala.dataflow.IFDS.TabulationDomain;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
public class IFDSTaintDomain<E extends ISSABasicBlock>
implements TabulationDomain<DomainElement, BasicBlockInContext<E>> {
private final Map<DomainElement, Integer> table = new HashMap<>();
private final ArrayList<DomainElement> objects = new ArrayList<>();
private final Map<CodeElement, Set<DomainElement>> elementIndex = new HashMap<>();
Set<DomainElement> emptySet = new HashSet<>();
public Set<DomainElement> getPossibleElements(CodeElement codeElement) {
Set<DomainElement> elts = elementIndex.get(codeElement);
if (elts != null) return elts;
return emptySet;
}
private void index(DomainElement e) {
Set<DomainElement> elements = elementIndex.computeIfAbsent(e.codeElement, k -> new HashSet<>());
elements.add(e);
}
@Override
public int add(DomainElement o) {
Integer i = table.get(o);
if (i == null) {
objects.add(o);
i = table.size() + 1;
table.put(o, i);
// System.out.println("Adding domain element "+i+": "+o);
}
index(o);
return i;
}
@Override
public synchronized int getMappedIndex(final Object o) {
if (!(o instanceof DomainElement)) {
throw new IllegalArgumentException(o.getClass().getCanonicalName());
}
final DomainElement de = (DomainElement) o;
final Integer i = table.get(de);
return (i == null ? add(de) : i);
}
@Override
public boolean hasPriorityOver(
PathEdge<BasicBlockInContext<E>> p1, PathEdge<BasicBlockInContext<E>> p2) {
return false;
}
@Override
public DomainElement getMappedObject(int n) {
if (n > 0 && n <= objects.size()) return objects.get(n - 1);
return null;
}
@Override
public int getMaximumIndex() {
return objects.size();
}
@Override
public int getSize() {
return objects.size() + 1;
}
@Override
public boolean hasMappedIndex(DomainElement o) {
return table.containsKey(o);
}
@Override
public Iterator<DomainElement> iterator() {
return table.keySet().iterator();
}
@Override
public Stream<DomainElement> stream() {
return objects.stream();
}
public Set<CodeElement> codeElements() {
return elementIndex.keySet();
}
}
| 4,524
| 29.369128
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/domain/InstanceKeyElement.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.domain;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
public class InstanceKeyElement extends CodeElement {
private final InstanceKey ik;
public InstanceKeyElement(InstanceKey ik) {
this.ik = ik;
}
@Override
public boolean equals(Object other) {
if (other != null && other instanceof InstanceKeyElement)
return ((InstanceKeyElement) other).ik.equals(this.ik);
return false;
}
@Override
public int hashCode() {
return ik.hashCode();
}
@Override
public String toString() {
return "InstanceKeyElement(" + ik + ')';
}
public InstanceKey getInstanceKey() {
return ik;
}
}
| 2,603
| 31.55
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/domain/LocalElement.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.domain;
public final class LocalElement extends CodeElement {
private final int id;
public LocalElement(int id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
LocalElement other = (LocalElement) obj;
if (id != other.id) return false;
return true;
}
@Override
public String toString() {
return "LocalElement(" + id + ')';
}
}
| 2,605
| 31.575
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/domain/ReturnElement.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.domain;
public class ReturnElement extends CodeElement {
@Override
public boolean equals(Object other) {
return other != null && other instanceof ReturnElement;
}
@Override
public int hashCode() {
return 1;
}
@Override
public String toString() {
return "ReturnElement()";
}
}
| 2,268
| 32.865672
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/domain/StaticFieldElement.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.domain;
import com.ibm.wala.types.FieldReference;
public class StaticFieldElement extends CodeElement {
private final FieldReference fieldRef;
public StaticFieldElement(FieldReference fieldRef) {
this.fieldRef = fieldRef;
}
public FieldReference getRef() {
return fieldRef;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fieldRef == null) ? 0 : fieldRef.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
StaticFieldElement other = (StaticFieldElement) obj;
if (fieldRef == null) {
if (other.fieldRef != null) return false;
} else if (!fieldRef.equals(other.fieldRef)) return false;
return true;
}
}
| 2,903
| 37.72
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/FlowAnalysis.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Adam Fuchs <afuchs@cs.umd.edu> Avik Chaudhuri <avik@cs.umd.edu>
* Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow;
import com.ibm.wala.core.util.CancelRuntimeException;
import com.ibm.wala.dataflow.IFDS.IFlowFunctionMap;
import com.ibm.wala.dataflow.IFDS.IMergeFunction;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.dataflow.IFDS.PathEdge;
import com.ibm.wala.dataflow.IFDS.TabulationDomain;
import com.ibm.wala.dataflow.IFDS.TabulationProblem;
import com.ibm.wala.dataflow.IFDS.TabulationResult;
import com.ibm.wala.dataflow.IFDS.TabulationSolver;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.CancelException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.flow.functions.TaintTransferFunctions;
import org.scandroid.flow.types.FlowType;
import org.scandroid.util.CGAnalysisContext;
public class FlowAnalysis {
public static <E extends ISSABasicBlock>
TabulationResult<BasicBlockInContext<E>, CGNode, DomainElement> analyze(
final CGAnalysisContext<E> analysisContext,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> initialTaints,
IFDSTaintDomain<E> d)
throws CancelRuntimeException {
return analyze(analysisContext.graph, analysisContext.cg, analysisContext.pa, initialTaints, d);
}
public static <E extends ISSABasicBlock>
TabulationResult<BasicBlockInContext<E>, CGNode, DomainElement> analyze(
final CGAnalysisContext<E> analysisContext,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> initialTaints,
IFDSTaintDomain<E> d,
IFlowFunctionMap<BasicBlockInContext<E>> flowFunctionMap)
throws CancelRuntimeException {
return analyze(analysisContext.graph, analysisContext.cg, initialTaints, d, flowFunctionMap);
}
public static <E extends ISSABasicBlock>
TabulationResult<BasicBlockInContext<E>, CGNode, DomainElement> analyze(
final ISupergraph<BasicBlockInContext<E>, CGNode> graph,
CallGraph cg,
PointerAnalysis<InstanceKey> pa,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> initialTaints,
IFDSTaintDomain<E> d) {
return analyze(graph, cg, initialTaints, d, new TaintTransferFunctions<>(d, pa));
// return analyze(graph, cg, pa, initialTaints, d,
// progressMonitor, new IDTransferFunctions<E>(d, graph, pa));
// return analyze(graph, cg, pa, initialTaints, d,
// progressMonitor, new IFDSTaintFlowFunctionProvider<E>(d, graph, pa));
}
public static <E extends ISSABasicBlock>
TabulationResult<BasicBlockInContext<E>, CGNode, DomainElement> analyze(
final ISupergraph<BasicBlockInContext<E>, CGNode> graph,
CallGraph cg,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> initialTaints,
IFDSTaintDomain<E> d,
final IFlowFunctionMap<BasicBlockInContext<E>> flowFunctionMap) {
final IFDSTaintDomain<E> domain = d;
final List<PathEdge<BasicBlockInContext<E>>> initialEdges = new ArrayList<>();
// Add PathEdges to the taints
// Places that initial taints occur, and where they initially flow into
for (Map.Entry<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> bbEntry :
initialTaints.entrySet()) {
Map<FlowType<E>, Set<CodeElement>> bbTaints = bbEntry.getValue();
for (Map.Entry<FlowType<E>, Set<CodeElement>> flowEntry : bbTaints.entrySet()) {
for (CodeElement taintElement : flowEntry.getValue()) {
final BasicBlockInContext<E> taintBB = bbEntry.getKey();
BasicBlockInContext<E>[] entryBlocks = graph.getEntriesForProcedure(taintBB.getNode());
for (BasicBlockInContext<E> entryBlock : entryBlocks) {
// Add PathEdge <s_p,0> -> <n,d1>
initialEdges.add(
PathEdge.createPathEdge(
entryBlock,
0,
taintBB,
domain.getMappedIndex(new DomainElement(taintElement, flowEntry.getKey()))));
}
// initialEdges.add(PathEdge.createPathEdge(e.getKey(), 0, e.getKey(),
// domain.getMappedIndex(new DomainElement(o,e2.getKey()))));
}
}
}
// Add PathEdges to the entry points of the supergraph <s_main,0> -> <s_main,0>
for (CGNode entry : cg.getEntrypointNodes()) {
BasicBlockInContext<E>[] bbic = graph.getEntriesForProcedure(entry);
for (BasicBlockInContext<E> element : bbic)
initialEdges.add(PathEdge.createPathEdge(element, 0, element, 0));
}
final TabulationProblem<BasicBlockInContext<E>, CGNode, DomainElement> problem =
new TabulationProblem<>() {
@Override
public TabulationDomain<DomainElement, BasicBlockInContext<E>> getDomain() {
return domain;
}
@Override
public IFlowFunctionMap<BasicBlockInContext<E>> getFunctionMap() {
return flowFunctionMap;
}
@Override
public IMergeFunction getMergeFunction() {
return null;
}
@Override
public ISupergraph<BasicBlockInContext<E>, CGNode> getSupergraph() {
return graph;
}
@Override
public Collection<PathEdge<BasicBlockInContext<E>>> initialSeeds() {
return initialEdges;
// CGNode entryProc = cfg.getCallGraph().getEntrypointNodes()
// .iterator().next();
// BasicBlockInContext<ISSABasicBlock> entryBlock = cfg
// .getEntry(entryProc);
// for (int i = 0; i < entryProc.getIR().getNumberOfParameters(); i++) {
// list.add(PathEdge.createPathEdge(entryBlock, 0, entryBlock,
// domain.getMappedIndex(new LocalElement(i + 1))));
// }
// return list;
}
};
TabulationSolver<BasicBlockInContext<E>, CGNode, DomainElement> solver =
TabulationSolver.make(
problem
// , progressMonitor
);
try {
TabulationResult<BasicBlockInContext<E>, CGNode, DomainElement> flowResult = solver.solve();
// if (options.ifdsExplorer()) {
// for (int i = 1; i < domain.getSize(); i++) {
//
// }
// GraphUtil.exploreIFDS(flowResult);
// }
return flowResult;
} catch (CancelException e) {
throw new CancelRuntimeException(e);
}
}
}
| 9,151
| 43.21256
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/ISinkPoint.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow;
import com.ibm.wala.dataflow.IFDS.TabulationResult;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import java.util.Set;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.flow.types.FlowType;
import org.scandroid.util.CGAnalysisContext;
public interface ISinkPoint {
Set<FlowType<IExplodedBasicBlock>> findSources(
CGAnalysisContext<IExplodedBasicBlock> ctx,
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain);
FlowType<IExplodedBasicBlock> getFlow();
}
| 2,759
| 44.245902
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/InflowAnalysis.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Adam Fuchs <afuchs@cs.umd.edu> Avik Chaudhuri <avik@cs.umd.edu>
* Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow;
// import static util.MyLogger.LogLevel.DEBUG;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.util.collections.HashMapFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.flow.types.FlowType;
import org.scandroid.spec.CallArgSourceSpec;
import org.scandroid.spec.CallRetSourceSpec;
import org.scandroid.spec.EntryArgSourceSpec;
import org.scandroid.spec.ISpecs;
import org.scandroid.spec.SourceSpec;
import org.scandroid.spec.StaticFieldSourceSpec;
import org.scandroid.util.CGAnalysisContext;
@SuppressWarnings("rawtypes")
public class InflowAnalysis {
@SuppressWarnings("unchecked")
public static <E extends ISSABasicBlock> void addDomainElements(
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
BasicBlockInContext<E> block,
FlowType taintType,
Set<CodeElement> newElements) {
Map<FlowType<E>, Set<CodeElement>> blockMap =
taintMap.computeIfAbsent(block, k -> new HashMap<>());
Set<CodeElement> elements = blockMap.computeIfAbsent(taintType, k -> new HashSet<>());
elements.addAll(newElements);
}
public static <E extends ISSABasicBlock> void addDomainElement(
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
BasicBlockInContext<E> block,
FlowType taintType,
CodeElement element) {
final Set<CodeElement> elements = Collections.singleton(element);
addDomainElements(taintMap, block, taintType, elements);
}
private static <E extends ISSABasicBlock> void processInputSource(
CGAnalysisContext<E> ctx,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
SourceSpec ss,
CallGraph cg,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
ClassHierarchy cha,
PointerAnalysis<InstanceKey> pa) {
int[] newArgNums;
for (IMethod im : ss.getNamePattern().getPossibleTargets(cha)) {
newArgNums =
(ss.getArgNums() == null)
? SourceSpec.getNewArgNums(
im.isStatic() ? im.getNumberOfParameters() : im.getNumberOfParameters() - 1)
: ss.getArgNums();
for (CGNode node : cg.getNodes(im.getReference())) {
BasicBlockInContext<E>[] entriesForProcedure = graph.getEntriesForProcedure(node);
if (entriesForProcedure == null) {
continue;
}
for (BasicBlockInContext<E> bb : entriesForProcedure) {
ss.addDomainElements(ctx, taintMap, im, bb, null, newArgNums, graph, pa, cg);
}
}
}
}
private static <E extends ISSABasicBlock> void processStaticFieldSource(
CGAnalysisContext<E> ctx,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
StaticFieldSourceSpec ss,
CallGraph cg,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa) {
// get the first block:
BasicBlockInContext<E> bb = null;
for (CGNode n : cg.getEntrypointNodes()) {
bb = graph.getEntriesForProcedure(n)[0];
}
assert bb != null : "Could not find entry basic block.";
ss.addDomainElements(ctx, taintMap, bb.getMethod(), bb, null, null, graph, pa, cg);
}
private static <E extends ISSABasicBlock> void processFunctionCalls(
CGAnalysisContext<E> ctx,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
ArrayList<SourceSpec> ssAL,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa,
ClassHierarchy cha,
CallGraph cg) {
Collection<IMethod> targets = new HashSet<>();
ArrayList<Collection<IMethod>> targetList = new ArrayList<>();
for (SourceSpec sourceSpec : ssAL) {
Collection<IMethod> tempList = sourceSpec.getNamePattern().getPossibleTargets(cha);
targets.addAll(tempList);
targetList.add(tempList);
}
for (BasicBlockInContext<E> block : graph) {
for (SSAInstruction inst : block) {
if (!(inst instanceof SSAInvokeInstruction)) {
continue;
}
SSAInvokeInstruction invInst = (SSAInvokeInstruction) inst;
for (IMethod target : cha.getPossibleTargets(invInst.getDeclaredTarget())) {
if (targets.contains(target)) {
for (int i = 0; i < targetList.size(); i++) {
if (targetList.get(i).contains(target)) {
int[] argNums = ssAL.get(i).getArgNums();
argNums =
(argNums == null)
? SourceSpec.getNewArgNums(
target.isStatic()
? target.getNumberOfParameters()
: target.getNumberOfParameters() - 1)
: argNums;
ssAL.get(i)
.addDomainElements(
ctx, taintMap, target, block, invInst, argNums, graph, pa, cg);
}
}
}
}
}
}
}
public static <E extends ISSABasicBlock>
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> analyze(
CGAnalysisContext<E> analysisContext, ISpecs s) {
return analyze(
analysisContext,
analysisContext.cg,
analysisContext.getClassHierarchy(),
analysisContext.graph,
analysisContext.pa,
s);
}
public static <E extends ISSABasicBlock>
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> analyze(
CGAnalysisContext<E> ctx,
CallGraph cg,
ClassHierarchy cha,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa,
ISpecs s) {
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap =
HashMapFactory.make();
SourceSpec[] ss = s.getSourceSpecs();
ArrayList<SourceSpec> ssAL = new ArrayList<>();
for (SourceSpec element : ss) {
if (element instanceof EntryArgSourceSpec)
processInputSource(ctx, taintMap, element, cg, graph, cha, pa);
else if (element instanceof CallRetSourceSpec || element instanceof CallArgSourceSpec)
ssAL.add(element);
else if (element instanceof StaticFieldSourceSpec) {
processStaticFieldSource(ctx, taintMap, (StaticFieldSourceSpec) element, cg, graph, pa);
} else throw new UnsupportedOperationException("Unrecognized SourceSpec");
}
if (!ssAL.isEmpty()) processFunctionCalls(ctx, taintMap, ssAL, graph, pa, cha, cg);
return taintMap;
}
}
| 9,318
| 38.320675
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/LocalSinkPoint.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow;
import com.ibm.wala.dataflow.IFDS.TabulationResult;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.OrdinalSet;
import java.util.Collections;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.LocalElement;
import org.scandroid.flow.types.FlowType;
import org.scandroid.util.CGAnalysisContext;
public class LocalSinkPoint implements ISinkPoint {
private final BasicBlockInContext<IExplodedBasicBlock> block;
private final int ssaVal;
private final FlowType<IExplodedBasicBlock> sinkFlow;
public LocalSinkPoint(
BasicBlockInContext<IExplodedBasicBlock> block,
int ssaVal,
FlowType<IExplodedBasicBlock> sinkFlow) {
this.block = block;
this.ssaVal = ssaVal;
this.sinkFlow = sinkFlow;
}
@SuppressWarnings("unchecked")
@Override
public Set<FlowType<IExplodedBasicBlock>> findSources(
CGAnalysisContext<IExplodedBasicBlock> ctx,
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain) {
Set<FlowType<IExplodedBasicBlock>> sources = HashSetFactory.make();
final CodeElement localElt = new LocalElement(ssaVal);
Set<CodeElement> elts = HashSetFactory.make(Collections.singleton(localElt));
final CGNode node = block.getNode();
PointerKey pk = ctx.pa.getHeapModel().getPointerKeyForLocal(node, ssaVal);
OrdinalSet<InstanceKey> iks = ctx.pa.getPointsToSet(pk);
for (InstanceKey ik : iks) {
elts.addAll(ctx.codeElementsForInstanceKey(ik));
}
for (CodeElement elt : elts) {
for (DomainElement de : domain.getPossibleElements(elt)) {
if (flowResult.getResult(block).contains(domain.getMappedIndex(de))) {
sources.add(de.taintSource);
}
}
}
return sources;
}
@Override
public FlowType<IExplodedBasicBlock> getFlow() {
return sinkFlow;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((block == null) ? 0 : block.hashCode());
result = prime * result + ((sinkFlow == null) ? 0 : sinkFlow.hashCode());
result = prime * result + ssaVal;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
LocalSinkPoint other = (LocalSinkPoint) obj;
if (block == null) {
if (other.block != null) return false;
} else if (!block.equals(other.block)) return false;
if (sinkFlow == null) {
if (other.sinkFlow != null) return false;
} else if (!sinkFlow.equals(other.sinkFlow)) return false;
if (ssaVal != other.ssaVal) return false;
return true;
}
@Override
public String toString() {
return "SinkPoint [block=" + block + ", ssaVal=" + ssaVal + ", sinkFlow=" + sinkFlow + ']';
}
}
| 5,335
| 37.388489
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/OutflowAnalysis.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Adam Fuchs <afuchs@cs.umd.edu> Avik Chaudhuri <avik@cs.umd.edu> Steve Suh <suhsteve@gmail.com>
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>)
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.dataflow.IFDS.ICFGSupergraph;
import com.ibm.wala.dataflow.IFDS.TabulationResult;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInstruction.Visitor;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.IteratorUtil;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.intset.IntSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.InstanceKeyElement;
import org.scandroid.domain.LocalElement;
import org.scandroid.domain.ReturnElement;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.ParameterFlow;
import org.scandroid.flow.types.ReturnFlow;
import org.scandroid.spec.CallArgSinkSpec;
import org.scandroid.spec.EntryArgSinkSpec;
import org.scandroid.spec.EntryRetSinkSpec;
import org.scandroid.spec.ISpecs;
import org.scandroid.spec.SinkSpec;
import org.scandroid.spec.StaticFieldSinkSpec;
import org.scandroid.util.CGAnalysisContext;
/** @author acfoltzer */
public class OutflowAnalysis {
private final CGAnalysisContext<IExplodedBasicBlock> ctx;
private final CallGraph cg;
private final ClassHierarchy cha;
private final PointerAnalysis<InstanceKey> pa;
private final ICFGSupergraph graph;
private final ISpecs specs;
public OutflowAnalysis(CGAnalysisContext<IExplodedBasicBlock> ctx, ISpecs specs) {
this.ctx = ctx;
this.cg = ctx.cg;
this.cha = ctx.getClassHierarchy();
this.pa = ctx.pa;
this.graph = (ICFGSupergraph) ctx.graph;
this.specs = specs;
}
private static void addEdge(
Map<FlowType<IExplodedBasicBlock>, Set<FlowType<IExplodedBasicBlock>>> graph,
FlowType<IExplodedBasicBlock> source,
FlowType<IExplodedBasicBlock> dest) {
Set<FlowType<IExplodedBasicBlock>> dests = graph.computeIfAbsent(source, k -> new HashSet<>());
dests.add(dest);
}
@SuppressWarnings({"unused", "unchecked"})
private void processArgSinks(
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain,
Map<FlowType<IExplodedBasicBlock>, Set<FlowType<IExplodedBasicBlock>>> flowGraph,
List<SinkSpec> sinkSpecs) {
List<Collection<IMethod>> targetList = new ArrayList<>();
for (SinkSpec sinkSpec : sinkSpecs) {
Collection<IMethod> tempList = sinkSpec.getNamePattern().getPossibleTargets(cha);
targetList.add(tempList);
}
// look for all uses of query function and taint the results with the
// Uri used in those functions
for (BasicBlockInContext<IExplodedBasicBlock> block : graph) {
Iterator<SSAInvokeInstruction> invokeInstrs =
IteratorUtil.filter(block.iterator(), SSAInvokeInstruction.class);
while (invokeInstrs.hasNext()) {
SSAInvokeInstruction invInst = invokeInstrs.next();
for (IMethod target : cha.getPossibleTargets(invInst.getDeclaredTarget())) {
for (int i = 0; i < targetList.size(); i++) {
if (!targetList.get(i).contains(target)) {
continue;
}
int[] argNums = sinkSpecs.get(i).getArgNums();
if (null == argNums) {
int staticIndex = 0;
if (target.isStatic()) {
staticIndex = 1;
}
int targetParamCount = target.getNumberOfParameters() - staticIndex;
argNums = SinkSpec.getNewArgNums(targetParamCount);
}
CGNode node = block.getNode();
IntSet resultSet = flowResult.getResult(block);
for (int argNum : argNums) {
// The set of flow types we're looking for:
Set<FlowType<IExplodedBasicBlock>> taintTypeSet = HashSetFactory.make();
LocalElement le = new LocalElement(invInst.getUse(argNum));
Set<DomainElement> elements = domain.getPossibleElements(le);
if (elements != null) {
for (DomainElement de : elements) {
if (resultSet.contains(domain.getMappedIndex(de))) {
taintTypeSet.add(de.taintSource);
}
}
}
LocalPointerKey lpkey = new LocalPointerKey(node, invInst.getUse(argNum));
for (InstanceKey ik : pa.getPointsToSet(lpkey)) {
for (DomainElement de : domain.getPossibleElements(new InstanceKeyElement(ik))) {
if (resultSet.contains(domain.getMappedIndex(de))) {
taintTypeSet.add(de.taintSource);
}
}
}
for (FlowType<IExplodedBasicBlock> dest : sinkSpecs.get(i).getFlowType(block)) {
for (FlowType<IExplodedBasicBlock> source : taintTypeSet) {
// flow taint into uriIK
addEdge(flowGraph, source, dest);
}
}
}
}
}
}
}
}
@SuppressWarnings({"unused", "unchecked"})
private void processEntryArgs(
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain,
Map<FlowType<IExplodedBasicBlock>, Set<FlowType<IExplodedBasicBlock>>> flowGraph,
SinkSpec ss) {
int[] newArgNums;
for (IMethod im : ss.getNamePattern().getPossibleTargets(cha)) {
// look for a tainted reply
CGNode node = cg.getNode(im, Everywhere.EVERYWHERE);
if (node == null) {
continue;
}
BasicBlockInContext<IExplodedBasicBlock>[] entriesForProcedure =
graph.getEntriesForProcedure(node);
if (entriesForProcedure == null || 0 == entriesForProcedure.length) {
continue;
}
BasicBlockInContext<IExplodedBasicBlock> entryBlock = entriesForProcedure[0];
newArgNums = ss.getArgNums();
if (null == newArgNums) {
int staticIndex = 1;
if (im.isStatic()) {
staticIndex = 0;
}
int targetParamCount = im.getNumberOfParameters() - staticIndex;
newArgNums = SinkSpec.getNewArgNums(targetParamCount);
}
// for (BasicBlockInContext<E> block:
// graph.getExitsForProcedure(node) ) {
// IntIterator itr = flowResult.getResult(block).intIterator();
// while (itr.hasNext()) {
// int i = itr.next();
//
//
//
// }
// }
for (int newArgNum : newArgNums) {
// see if anything flowed into the args as sinks:
for (DomainElement de :
domain.getPossibleElements(new LocalElement(node.getIR().getParameter(newArgNum)))) {
for (BasicBlockInContext<IExplodedBasicBlock> block : graph.getExitsForProcedure(node)) {
int mappedIndex = domain.getMappedIndex(de);
if (flowResult.getResult(block).contains(mappedIndex)) {
addEdge(flowGraph, de.taintSource, new ParameterFlow<>(entryBlock, newArgNum, false));
}
}
int mappedIndex = domain.getMappedIndex(de);
if (flowResult.getResult(entryBlock).contains(mappedIndex)) {
addEdge(flowGraph, de.taintSource, new ParameterFlow<>(entryBlock, newArgNum, false));
}
}
for (InstanceKey ik :
pa.getPointsToSet(new LocalPointerKey(node, node.getIR().getParameter(newArgNum)))) {
for (DomainElement de : domain.getPossibleElements(new InstanceKeyElement(ik))) {
if (flowResult.getResult(entryBlock).contains(domain.getMappedIndex(de))) {
addEdge(flowGraph, de.taintSource, new ParameterFlow<>(entryBlock, newArgNum, false));
}
}
}
}
}
}
@SuppressWarnings({"unused", "unchecked"})
private void processEntryRets(
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain,
Map<FlowType<IExplodedBasicBlock>, Set<FlowType<IExplodedBasicBlock>>> flowGraph,
SinkSpec ss) {
for (IMethod im : ss.getNamePattern().getPossibleTargets(cha)) {
// look for a tainted reply
CGNode node = cg.getNode(im, Everywhere.EVERYWHERE);
if (node == null) {
continue;
}
BasicBlockInContext<IExplodedBasicBlock>[] exitsForProcedure =
graph.getExitsForProcedure(node);
if (exitsForProcedure == null || 0 == exitsForProcedure.length) {
continue;
}
final Set<DomainElement> possibleElements = domain.getPossibleElements(new ReturnElement());
for (DomainElement de : possibleElements) {
for (BasicBlockInContext<IExplodedBasicBlock> block : exitsForProcedure) {
if (flowResult.getResult(block).contains(domain.getMappedIndex(de))) {
addEdge(flowGraph, de.taintSource, new ReturnFlow<>(block, false));
}
// Iterator<BasicBlockInContext<E>> it =
// graph.getPredNodes(block);
// while (it.hasNext()) {
// BasicBlockInContext<E> realBlock = it.next();
// if (realBlock.isExitBlock()) {
//
// // addEdge(flowGraph,de.taintSource, new
// ReturnFlow<E>(realBlock, false));
// }
// if(flowResult.getResult(realBlock).contains(domain.getMappedIndex(de)))
// {
// logger.debug("adding edge from {} to ReturnFlow",
// de.taintSource);
// addEdge(flowGraph,de.taintSource, new
// ReturnFlow<E>(realBlock, false));
// } else {
// logger.debug("no edge from block {} for {}", realBlock,
// de);
// }
}
}
for (BasicBlockInContext<IExplodedBasicBlock> block : exitsForProcedure) {
Iterator<BasicBlockInContext<IExplodedBasicBlock>> it = graph.getPredNodes(block);
while (it.hasNext()) {
BasicBlockInContext<IExplodedBasicBlock> realBlock = it.next();
final SSAInstruction inst = realBlock.getLastInstruction();
if (null != inst && inst instanceof SSAReturnInstruction) {
PointerKey pk = new LocalPointerKey(node, inst.getUse(0));
for (InstanceKey ik : pa.getPointsToSet(pk)) {
for (DomainElement ikElement :
domain.getPossibleElements(new InstanceKeyElement(ik))) {
if (flowResult.getResult(realBlock).contains(domain.getMappedIndex(ikElement))) {
addEdge(flowGraph, ikElement.taintSource, new ReturnFlow<>(realBlock, false));
}
}
}
}
}
}
}
}
public Map<FlowType<IExplodedBasicBlock>, Set<FlowType<IExplodedBasicBlock>>> analyze(
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain) {
return analyze(flowResult, domain, specs);
}
public Map<FlowType<IExplodedBasicBlock>, Set<FlowType<IExplodedBasicBlock>>> analyze(
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain,
ISpecs s) {
Map<FlowType<IExplodedBasicBlock>, Set<FlowType<IExplodedBasicBlock>>> taintFlow =
HashMapFactory.make();
SinkSpec[] ss = s.getSinkSpecs();
for (SinkSpec element : ss) {
if (element instanceof EntryArgSinkSpec)
processSinkSpec(flowResult, domain, taintFlow, element);
else if (element instanceof CallArgSinkSpec)
processSinkSpec(flowResult, domain, taintFlow, element);
else if (element instanceof EntryRetSinkSpec)
processSinkSpec(flowResult, domain, taintFlow, element);
else if (element instanceof StaticFieldSinkSpec)
processSinkSpec(flowResult, domain, taintFlow, element);
else throw new UnsupportedOperationException("SinkSpec not yet Implemented");
}
/* TODO: re-enable this soon! */
/*
* for(Entry<FlowType,Set<FlowType>> e: taintFlow.entrySet()) {
* WalaGraphToJGraphT walaJgraphT = new WalaGraphToJGraphT(flowResult,
* domain, e.getKey(), graph, cg); logger.debug("Source: " +
* e.getKey()); for(FlowType target:e.getValue()) {
* //logger.debug("SourceNode: "+
* e.getKey().getRelevantNode() +
* "\nSinkNode: "+target.getRelevantNode());
* walaJgraphT.calcPath(e.getKey().getRelevantNode(),
* target.getRelevantNode()); Iterator<DefaultEdge> edgeI =
* walaJgraphT.getPath().getEdgeList().iterator(); if (edgeI.hasNext())
* int counter = 1; while
* (edgeI.hasNext()) { DefaultEdge edge = edgeI.next();
* logger.debug("\t\t#"+counter+": " +
* walaJgraphT.getJGraphT().getEdgeSource
* (edge).getMethod().getSignature() + " ==> " +
* walaJgraphT.getJGraphT()
* .getEdgeTarget(edge).getMethod().getSignature()); }
*
* } }
*/
return taintFlow;
}
private void processSinkSpec(
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain,
Map<FlowType<IExplodedBasicBlock>, Set<FlowType<IExplodedBasicBlock>>> flowGraph,
SinkSpec ss) {
Set<ISinkPoint> sinkPoints = calculateSinkPoints(ss);
if (!(ss instanceof StaticFieldSinkSpec)) {}
for (ISinkPoint sinkPoint : sinkPoints) {
for (FlowType<IExplodedBasicBlock> source : sinkPoint.findSources(ctx, flowResult, domain)) {
addEdge(flowGraph, source, sinkPoint.getFlow());
}
}
}
private Set<ISinkPoint> calculateSinkPoints(SinkSpec sinkSpec) {
if (sinkSpec instanceof EntryArgSinkSpec) {
return calculateSinkPoints((EntryArgSinkSpec) sinkSpec);
}
if (sinkSpec instanceof CallArgSinkSpec) {
return calculateSinkPoints((CallArgSinkSpec) sinkSpec);
}
if (sinkSpec instanceof EntryRetSinkSpec) {
return calculateSinkPoints((EntryRetSinkSpec) sinkSpec);
}
if (sinkSpec instanceof StaticFieldSinkSpec) {
return calculateSinkPoints((StaticFieldSinkSpec) sinkSpec);
}
throw new UnimplementedError();
}
private Set<ISinkPoint> calculateSinkPoints(EntryArgSinkSpec sinkSpec) {
Set<ISinkPoint> points = HashSetFactory.make();
Collection<IMethod> methods = sinkSpec.getNamePattern().getPossibleTargets(cha);
if (null == methods) {}
for (IMethod method : methods) {
for (CGNode node : cg.getNodes(method.getReference())) {
BasicBlockInContext<IExplodedBasicBlock> entryBlock = graph.getICFG().getEntry(node);
BasicBlockInContext<IExplodedBasicBlock> exitBlock = graph.getICFG().getExit(node);
for (int argNum : sinkSpec.getArgNums()) {
final int ssaVal = node.getIR().getParameter(argNum);
final ParameterFlow<IExplodedBasicBlock> sinkFlow =
new ParameterFlow<>(entryBlock, argNum, false);
final LocalSinkPoint sinkPoint = new LocalSinkPoint(exitBlock, ssaVal, sinkFlow);
points.add(sinkPoint);
}
}
}
return points;
}
private Set<ISinkPoint> calculateSinkPoints(final CallArgSinkSpec sinkSpec) {
final Set<ISinkPoint> points = HashSetFactory.make();
Collection<IMethod> methods = sinkSpec.getNamePattern().getPossibleTargets(cha);
if (null == methods) {}
Set<CGNode> callees = HashSetFactory.make();
final Set<MethodReference> calleeRefs = HashSetFactory.make();
for (IMethod method : methods) {
callees.addAll(cg.getNodes(method.getReference()));
calleeRefs.add(method.getReference());
}
// for each possible callee
for (CGNode callee : callees) {
Iterator<CGNode> callers = cg.getPredNodes(callee);
// for each possible caller of that callee
while (callers.hasNext()) {
final CGNode caller = callers.next();
// look for invoke instructions
caller
.getIR()
.visitAllInstructions(
new Visitor() {
@Override
public void visitInvoke(SSAInvokeInstruction invokeInst) {
// if the invoke instruction targets a possible callee
if (calleeRefs.contains(invokeInst.getDeclaredTarget())) {
// look up the instruction's block in context
// (surely there's a more straightforward way to do
// this!)
final SSAInstruction[] insts =
graph.getICFG().getCFG(caller).getInstructions();
int invokeIndex = -1;
for (int i = 0; i < insts.length; i++) {
if (insts[i] instanceof SSAInvokeInstruction) {
SSAInvokeInstruction invokeInst2 = (SSAInvokeInstruction) insts[i];
if (invokeInst
.getDeclaredTarget()
.equals(invokeInst2.getDeclaredTarget())) {
invokeIndex = i;
break;
}
}
}
if (invokeIndex == -1) {}
final IExplodedBasicBlock block =
graph.getICFG().getCFG(caller).getBlockForInstruction(invokeIndex);
BasicBlockInContext<IExplodedBasicBlock> callBlock =
new BasicBlockInContext<>(caller, block);
for (int argNum : sinkSpec.getArgNums()) {
// and add a sink point for each arg num
final int ssaVal = invokeInst.getUse(argNum);
final ParameterFlow<IExplodedBasicBlock> sinkFlow =
new ParameterFlow<>(callBlock, argNum, false);
final LocalSinkPoint sinkPoint =
new LocalSinkPoint(callBlock, ssaVal, sinkFlow);
points.add(sinkPoint);
}
}
}
});
}
}
return points;
}
private Set<ISinkPoint> calculateSinkPoints(EntryRetSinkSpec sinkSpec) {
Set<ISinkPoint> points = HashSetFactory.make();
Collection<IMethod> methods = sinkSpec.getNamePattern().getPossibleTargets(cha);
if (null == methods) {}
// for all possible returning methods
for (IMethod method : methods) {
// for all possible CGNodes of that method
for (CGNode node : cg.getNodes(method.getReference())) {
// get the unique (null) exit block
BasicBlockInContext<IExplodedBasicBlock> nullExitBlock = graph.getICFG().getExit(node);
// and for each predecessor to the exit block
Iterator<BasicBlockInContext<IExplodedBasicBlock>> exitBlocks =
graph.getPredNodes(nullExitBlock);
while (exitBlocks.hasNext()) {
// if that predecessor is a return instruction
BasicBlockInContext<IExplodedBasicBlock> exitBlock = exitBlocks.next();
final SSAInstruction inst = exitBlock.getDelegate().getInstruction();
if (inst instanceof SSAReturnInstruction) {
// add a sink point for the instruction
SSAReturnInstruction returnInst = (SSAReturnInstruction) inst;
if (!returnInst.returnsVoid()) {
final int ssaVal = returnInst.getResult();
final ReturnFlow<IExplodedBasicBlock> sinkFlow = new ReturnFlow<>(exitBlock, false);
final LocalSinkPoint sinkPoint = new LocalSinkPoint(exitBlock, ssaVal, sinkFlow);
points.add(sinkPoint);
}
}
}
}
}
return points;
}
private Set<ISinkPoint> calculateSinkPoints(StaticFieldSinkSpec sinkSpec) {
Set<ISinkPoint> points = HashSetFactory.make();
ICFGSupergraph graph = (ICFGSupergraph) ctx.graph;
for (CGNode node : ctx.cg.getNodes(sinkSpec.getMethod().getReference())) {
points.add(new StaticFieldSinkPoint(sinkSpec, graph.getICFG().getExit(node)));
}
return points;
}
}
| 23,258
| 39.520906
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/StaticFieldSinkPoint.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.dataflow.IFDS.TabulationResult;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Set;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.StaticFieldElement;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.StaticFieldFlow;
import org.scandroid.spec.StaticFieldSinkSpec;
import org.scandroid.util.CGAnalysisContext;
/** @author acfoltzer */
public class StaticFieldSinkPoint implements ISinkPoint {
// private static final Logger logger = LoggerFactory
// .getLogger(StaticFieldSinkPoint.class);
private final IField field;
private final FlowType<IExplodedBasicBlock> flow;
private final BasicBlockInContext<IExplodedBasicBlock> block;
public StaticFieldSinkPoint(
StaticFieldSinkSpec spec, BasicBlockInContext<IExplodedBasicBlock> block) {
this.field = spec.getField();
this.block = block;
this.flow = new StaticFieldFlow<>(block, field, false);
}
/*
* (non-Javadoc)
*
* @see org.scandroid.flow.ISinkPoint#findSources(org.scandroid.util.
* CGAnalysisContext, com.ibm.wala.dataflow.IFDS.TabulationResult,
* org.scandroid.domain.IFDSTaintDomain)
*/
@SuppressWarnings("unchecked")
@Override
public Set<FlowType<IExplodedBasicBlock>> findSources(
CGAnalysisContext<IExplodedBasicBlock> ctx,
TabulationResult<BasicBlockInContext<IExplodedBasicBlock>, CGNode, DomainElement> flowResult,
IFDSTaintDomain<IExplodedBasicBlock> domain) {
Set<FlowType<IExplodedBasicBlock>> sources = HashSetFactory.make();
for (DomainElement de :
domain.getPossibleElements(new StaticFieldElement(field.getReference()))) {
if (de.taintSource instanceof StaticFieldFlow<?>) {
StaticFieldFlow<IExplodedBasicBlock> source =
(StaticFieldFlow<IExplodedBasicBlock>) de.taintSource;
if (source.getField().equals(field)) {
continue;
}
} else if (flowResult.getResult(block).contains(domain.getMappedIndex(de))) {
sources.add(de.taintSource);
}
}
return sources;
}
/*
* (non-Javadoc)
*
* @see org.scandroid.flow.ISinkPoint#getFlow()
*/
@Override
public FlowType<IExplodedBasicBlock> getFlow() {
return flow;
}
}
| 4,534
| 38.780702
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/CallFlowFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.LocalElement;
/**
* @author creswick
* @author acfoltzer
*/
public class CallFlowFunction<E extends ISSABasicBlock> implements IUnaryFlowFunction {
/**
* A map from the code elements of actual parameters, to the set of code elements for formal
* parameters
*/
private final Map<CodeElement, Set<CodeElement>> paramArgsMap;
private final IFDSTaintDomain<E> domain;
public CallFlowFunction(IFDSTaintDomain<E> domain, List<CodeElement> actualParams) {
this.domain = domain;
final int numParams = actualParams.size();
this.paramArgsMap = HashMapFactory.make(numParams);
for (int i = 0; i < numParams; i++) {
// add a mapping for each parameter
final CodeElement actual = actualParams.get(i);
if (!(actual instanceof LocalElement)) {}
final CodeElement formal = new LocalElement(i + 1); // +1 for SSA
Set<CodeElement> existingFormals = paramArgsMap.get(actual);
if (null == existingFormals) {
existingFormals = HashSetFactory.make(numParams);
}
existingFormals.add(formal);
paramArgsMap.put(actual, existingFormals);
}
}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction#getTargets(int)
*/
@Override
public IntSet getTargets(int d1) {
if (0 == d1) {
return TaintTransferFunctions.ZERO_SET;
}
DomainElement de = domain.getMappedObject(d1);
MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
/*
* We're in the situation of calling a function:
*
* f(x, y, z)
*
* And determining how taints flow from that call site to the entry of
* the function
*
* ... f(X x, Y y, Z z) { ... }
*
* Our goals are twofold: 1. Propagate taints from the actual parameter
* x to the formal parameter x 2. Exclude any other non-local
* information from propagating to callee
*
* Since we're unioning the result of this with the
* GlobalIdentityFunction, we don't have to worry about 2 for this
* IntSet.
*/
final Set<CodeElement> formals = paramArgsMap.get(de.codeElement);
if (null != formals) {
for (CodeElement formal : formals) {
set.add(domain.getMappedIndex(new DomainElement(formal, de.taintSource)));
}
}
return set;
}
}
| 4,874
| 36.21374
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/CallNoneToReturnFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.flow.types.FlowType;
public final class CallNoneToReturnFunction<E extends ISSABasicBlock>
implements IUnaryFlowFunction {
private final IFDSTaintDomain<E> domain;
public CallNoneToReturnFunction(IFDSTaintDomain<E> domain) {
this.domain = domain;
}
@Override
public IntSet getTargets(int d) {
if (0 == d) {
return TaintTransferFunctions.ZERO_SET;
}
MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
// TODO: this is questionable
// We don't know anything about the function called,
// so we have to make some assumptions. The safest assumption
// is that everything goes to everything:
// this effectively taints everything in the heap that we've seen before.
DomainElement de = domain.getMappedObject(d);
@SuppressWarnings("unchecked")
FlowType<E> taint = de.taintSource;
for (CodeElement ce : domain.codeElements()) {
int elt = domain.getMappedIndex(new DomainElement(ce, taint));
set.add(elt);
}
return set;
}
}
| 3,408
| 39.583333
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/CallToReturnFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.LocalElement;
import org.scandroid.domain.ReturnElement;
public class CallToReturnFunction<E extends ISSABasicBlock> implements IUnaryFlowFunction {
private final IFDSTaintDomain<E> domain;
public CallToReturnFunction(IFDSTaintDomain<E> domain) {
this.domain = domain;
}
@Override
public IntSet getTargets(int d) {
MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
// Local elements (and the 0 element) flow through CallToReturn edges,
// but nothing else does (everything else is subject to whatever
// happened in the invoked function)
if (0 == d) {
set.add(d);
} else {
DomainElement de = domain.getMappedObject(d);
if (de.codeElement instanceof LocalElement || de.codeElement instanceof ReturnElement) {
set.add(d);
} else {
}
}
return set;
}
}
| 3,198
| 39.493671
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/ConstantFlowFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.SparseIntSet;
import java.util.Set;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
/**
* A flow function which maps the zero fact to a set of new dataflow facts, essentially introducing
* them from nothing. Identity for all other facts.
*
* @author acfoltzer
*/
public class ConstantFlowFunction<E extends ISSABasicBlock> implements IUnaryFlowFunction {
private final MutableSparseIntSet result;
public ConstantFlowFunction(IFDSTaintDomain<E> domain, Set<DomainElement> elts) {
result = MutableSparseIntSet.make(TaintTransferFunctions.ZERO_SET);
for (DomainElement de : elts) {
result.add(domain.getMappedIndex(de));
}
}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction#getTargets(int)
*/
@Override
public IntSet getTargets(int d1) {
return 0 == d1 ? result : SparseIntSet.singleton(d1);
}
}
| 3,178
| 40.285714
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/GlobalIdentityFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.SparseIntSet;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.LocalElement;
/**
* Flow function that only permits globals - and the zero element - to flow through
*
* @author creswick
*/
public class GlobalIdentityFunction<E extends ISSABasicBlock> implements IUnaryFlowFunction {
private final IFDSTaintDomain<E> domain;
public GlobalIdentityFunction(IFDSTaintDomain<E> domain) {
this.domain = domain;
}
/* (non-Javadoc)
* @see com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction#getTargets(int)
*/
@Override
public IntSet getTargets(int d1) {
if (0 == d1) {
return TaintTransferFunctions.ZERO_SET;
}
DomainElement de = domain.getMappedObject(d1);
if (de.codeElement instanceof LocalElement) {
// if the query domain element is a local, then it is /not/ passed through.
return TaintTransferFunctions.EMPTY_SET;
} else {
return SparseIntSet.singleton(d1);
}
}
}
| 3,217
| 38.243902
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/GlobalReturnToNodeFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.InstanceKeyElement;
import org.scandroid.domain.LocalElement;
/**
* Propagates heap information from InstanceKeys to the LocalElements that point to those keys
*
* @author acfoltzer
*/
public class GlobalReturnToNodeFunction<E extends ISSABasicBlock> implements IUnaryFlowFunction {
private final IFDSTaintDomain<E> domain;
private final Map<InstanceKey, Set<CodeElement>> ikMap;
public GlobalReturnToNodeFunction(
IFDSTaintDomain<E> domain, PointerAnalysis<InstanceKey> pa, CGNode node) {
this.domain = domain;
this.ikMap = HashMapFactory.make();
for (PointerKey pk : pa.getPointerKeys()) {
if (!(pk instanceof LocalPointerKey)) {
continue;
}
LocalPointerKey lpk = (LocalPointerKey) pk;
if (!lpk.getNode().equals(node)) {
continue;
}
for (InstanceKey ik : pa.getPointsToSet(lpk)) {
Set<CodeElement> elts = ikMap.get(ik);
if (null == elts) {
elts = HashSetFactory.make();
ikMap.put(ik, elts);
}
elts.add(new LocalElement(lpk.getValueNumber()));
}
}
}
@Override
public IntSet getTargets(int d) {
MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
if (0 == d) {
set.add(d);
} else {
DomainElement de = domain.getMappedObject(d);
if (de.codeElement instanceof InstanceKeyElement) {
InstanceKey ik = ((InstanceKeyElement) de.codeElement).getInstanceKey();
Set<CodeElement> elts = ikMap.get(ik);
if (null != elts) {
for (CodeElement elt : elts) {
set.add(domain.getMappedIndex(new DomainElement(elt, de.taintSource)));
}
}
} else {
}
}
return set;
}
}
| 4,548
| 38.215517
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/IDTransferFunctions.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IFlowFunction;
import com.ibm.wala.dataflow.IFDS.IFlowFunctionMap;
import com.ibm.wala.dataflow.IFDS.IReversibleFlowFunction;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.dataflow.IFDS.IdentityFlowFunction;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.SparseIntSet;
public class IDTransferFunctions<E extends ISSABasicBlock>
implements IFlowFunctionMap<BasicBlockInContext<E>> {
public static final IntSet EMPTY_SET = new SparseIntSet();
public static final IntSet ZERO_SET = SparseIntSet.singleton(0);
private static final IReversibleFlowFunction IDENTITY_FN = new IdentityFlowFunction();
@Override
public IUnaryFlowFunction getNormalFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
return IDENTITY_FN;
}
@Override
public IUnaryFlowFunction getCallFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest, BasicBlockInContext<E> ret) {
return IDENTITY_FN;
}
@Override
public IFlowFunction getReturnFlowFunction(
BasicBlockInContext<E> call, BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
return IDENTITY_FN;
}
@Override
public IUnaryFlowFunction getCallToReturnFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
return IDENTITY_FN;
}
@Override
public IUnaryFlowFunction getCallNoneToReturnFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
return IDENTITY_FN;
}
}
| 3,647
| 37
| 93
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/IFDSTaintFlowFunctionProvider.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.flow.functions;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.dataflow.IFDS.IFlowFunction;
import com.ibm.wala.dataflow.IFDS.IFlowFunctionMap;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.StaticFieldKey;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.BitVectorIntSet;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.FieldElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.InstanceKeyElement;
import org.scandroid.domain.LocalElement;
import org.scandroid.domain.ReturnElement;
import org.scandroid.flow.types.FlowType;
/** @deprecated Replaced by TaintTransferFunctions. */
@Deprecated
public class IFDSTaintFlowFunctionProvider<E extends ISSABasicBlock>
implements IFlowFunctionMap<BasicBlockInContext<E>> {
private final IFDSTaintDomain<E> domain;
private final ISupergraph<BasicBlockInContext<E>, CGNode> graph;
private final PointerAnalysis<InstanceKey> pa;
public IFDSTaintFlowFunctionProvider(
IFDSTaintDomain<E> domain,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa) {
this.domain = domain;
this.graph = graph;
this.pa = pa;
}
// instruction has a valid def set
private static boolean inFlow(SSAInstruction instruction) {
return (instruction instanceof SSAArrayLoadInstruction)
|| (instruction instanceof SSAGetInstruction);
}
// instruction's def is getUse(0)
private static boolean outFlow(SSAInstruction instruction) {
return (instruction instanceof SSAArrayStoreInstruction)
|| (instruction instanceof SSAPutInstruction)
|| (instruction instanceof SSAInvokeInstruction);
}
// instruction is a return instruction
private static boolean returnFlow(SSAInstruction instruction) {
return (instruction instanceof SSAReturnInstruction);
}
private static class UseDefSetPair {
public Set<CodeElement> uses = HashSetFactory.make();
public Set<CodeElement> defs = HashSetFactory.make();
}
private class DefUse implements IUnaryFlowFunction {
private final List<UseDefSetPair> useToDefList = new ArrayList<>();
private final BasicBlockInContext<E> bb;
public DefUse(final BasicBlockInContext<E> inBlock) {
this.bb = inBlock;
for (SSAInstruction instruction : bb) {
handleInstruction(instruction);
}
}
private void handleInstruction(SSAInstruction instruction) {
// System.out.println("handle instruction: "+instruction);
UseDefSetPair p = new UseDefSetPair();
boolean thisToResult = false;
if (instruction instanceof SSAInvokeInstruction) {
thisToResult = handleInvokeInstruction(instruction, p);
}
if (thisToResult) {
useToDefList.add(p);
p = new UseDefSetPair();
}
IClassHierarchy ch = bb.getNode().getClassHierarchy();
if (inFlow(instruction)) {
handleInflowInstruction(instruction, p, ch);
} else if (outFlow(instruction)) {
handleOutflowInstruction(instruction, p, ch);
} else if (returnFlow(instruction)) {
handleReturnFlowInstruction(instruction, p);
} else {
for (int i = 0; i < instruction.getNumberOfUses(); i++) {
p.uses.addAll(CodeElement.valueElements(instruction.getUse(i)));
}
for (int j = 0; j < instruction.getNumberOfDefs(); j++) {
p.defs.addAll(CodeElement.valueElements(instruction.getDef(j)));
}
}
useToDefList.add(p);
}
private void handleReturnFlowInstruction(SSAInstruction instruction, UseDefSetPair p) {
SSAReturnInstruction retInst = (SSAReturnInstruction) instruction;
if (retInst.getNumberOfUses() > 0) {
/* TODO: why not add instance keys, too? */
for (int i = 0; i < instruction.getNumberOfUses(); i++) {
// p.uses.add(new LocalElement(instruction.getUse(i)));
p.uses.addAll(CodeElement.valueElements(instruction.getUse(i)));
}
p.defs.add(new ReturnElement());
}
}
private boolean handleInvokeInstruction(SSAInstruction instruction, UseDefSetPair p) {
boolean thisToResult;
SSAInvokeInstruction invInst = (SSAInvokeInstruction) instruction;
if (!invInst.isSpecial() && !invInst.isStatic() && instruction.getNumberOfDefs() > 0) {
// System.out.println("adding receiver flow in "+this+" for "+invInst);
// System.out.println("\tadding local element "+invInst.getReceiver());
// getReceiver() == getUse(0) == param[0] == this
p.uses.addAll(CodeElement.valueElements(invInst.getReceiver()));
for (int i = 0; i < invInst.getNumberOfDefs(); i++) {
// System.out.println("\tadding def local element "+invInst.getDef(i));
// return valuenumber of invoke instruction
p.defs.addAll(CodeElement.valueElements(invInst.getDef(i)));
}
}
thisToResult = true;
return thisToResult;
}
private void handleInflowInstruction(
SSAInstruction instruction, UseDefSetPair p, IClassHierarchy ch) {
if (instruction instanceof SSAGetInstruction) {
handleInflowGetInstruction(instruction, p, ch);
} else if (instruction instanceof SSAArrayLoadInstruction) {
handleInflowArrayLoadInstruction(instruction, p);
}
}
private void handleOutflowInstruction(
SSAInstruction instruction, UseDefSetPair p, IClassHierarchy ch) {
if (instruction instanceof SSAPutInstruction) {
handleOutflowPutInstruction(instruction, p, ch);
} else if (instruction instanceof SSAArrayStoreInstruction) {
handleOutflowArrayStoreInstruction(instruction, p);
} else if (instruction instanceof SSAInvokeInstruction) {
handleOutflowInvokeInstruction(instruction, p);
}
}
private void handleOutflowInvokeInstruction(SSAInstruction instruction, UseDefSetPair p) {
MethodReference targetMethod =
((SSAInvokeInstruction) instruction).getCallSite().getDeclaredTarget();
if (methodExcluded(targetMethod)) {
// TODO make all parameters flow into all other
// parameters, which could happen in the static case as well.
if (!((SSAInvokeInstruction) instruction).isStatic()) {
// These loops cause all parameters flow into the
// 'this' param (due to instruction.getUse(0))
for (int i = 1; i < instruction.getNumberOfUses(); i++) {
p.uses.addAll(CodeElement.valueElements(instruction.getUse(i)));
}
if (instruction.getNumberOfUses() > 0) {
p.defs.addAll(CodeElement.valueElements(instruction.getUse(0)));
}
}
}
}
private void handleOutflowArrayStoreInstruction(SSAInstruction instruction, UseDefSetPair p) {
p.uses.addAll(CodeElement.valueElements(instruction.getUse(2)));
p.defs.addAll(CodeElement.valueElements(instruction.getUse(0)));
}
private void handleOutflowPutInstruction(
SSAInstruction instruction, UseDefSetPair p, IClassHierarchy ch) {
SSAPutInstruction pi = (SSAPutInstruction) instruction;
PointerKey pk;
Set<CodeElement> elements = HashSetFactory.make();
if (pi.isStatic()) {
p.uses.addAll(CodeElement.valueElements(instruction.getUse(0)));
FieldReference declaredField = pi.getDeclaredField();
IField staticField = getStaticIField(ch, declaredField);
if (staticField == null) {
pk = null;
} else {
pk = new StaticFieldKey(staticField);
}
} else {
p.uses.addAll(CodeElement.valueElements(instruction.getUse(1)));
// this value number seems to be the object referenced in this instruction (?)
int valueNumber = instruction.getUse(0);
pk = new LocalPointerKey(bb.getNode(), valueNumber);
// MyLogger.log(LogLevel.DEBUG, " instruction: "+instruction);
// add the object that holds the field that was modified
// to the list of things tainted by this flow:
p.defs.addAll(CodeElement.valueElements(valueNumber));
}
// now add the field keys to the defs list so that they
// are also tainted:
if (pk != null) {
OrdinalSet<InstanceKey> m = pa.getPointsToSet(pk);
if (m != null) {
for (InstanceKey instanceKey : m) {
elements.add(new FieldElement(instanceKey, pi.getDeclaredField()));
elements.add(new InstanceKeyElement(instanceKey));
}
}
p.defs.addAll(elements);
}
}
private void handleInflowArrayLoadInstruction(SSAInstruction instruction, UseDefSetPair p) {
p.uses.addAll(CodeElement.valueElements(instruction.getUse(0)));
p.defs.addAll(CodeElement.valueElements(instruction.getDef()));
}
private void handleInflowGetInstruction(
SSAInstruction instruction, UseDefSetPair p, IClassHierarchy ch) {
SSAGetInstruction gi = (SSAGetInstruction) instruction;
PointerKey pk;
FieldReference declaredField = gi.getDeclaredField();
if (gi.isStatic()) {
IField staticField = getStaticIField(ch, declaredField);
if (staticField == null) {
pk = null;
} else {
pk = new StaticFieldKey(staticField);
}
} else {
int valueNumber = instruction.getUse(0);
pk = new LocalPointerKey(bb.getNode(), valueNumber);
}
if (pk != null) {
Set<CodeElement> elements = HashSetFactory.make();
OrdinalSet<InstanceKey> m = pa.getPointsToSet(pk);
if (m != null) {
for (InstanceKey instanceKey : m) {
elements.add(new FieldElement(instanceKey, declaredField));
elements.add(new InstanceKeyElement(instanceKey));
}
}
p.uses.addAll(elements);
// getinstruction only has 1 def
p.defs.add(new LocalElement(instruction.getDef(0)));
}
}
/**
* Determines if the provide method is in the exclusions by checking the supergraph.
*
* @return True if the method can not be found in the supergraph.
*/
private boolean methodExcluded(MethodReference method) {
Collection<IMethod> iMethods = pa.getClassHierarchy().getPossibleTargets(method);
return 0 == iMethods.size();
}
private IField getStaticIField(IClassHierarchy ch, FieldReference declaredField) {
TypeReference staticTypeRef = declaredField.getDeclaringClass();
IClass staticClass = ch.lookupClass(staticTypeRef);
// referring to a static field which we don't have loaded in the class hierarchy
// possibly ignored in the exclusions file or just not included in the scope
if (staticClass == null) return null;
IField staticField = staticClass.getField(declaredField.getName());
return staticField;
}
private void addTargets(CodeElement d1, MutableIntSet set, FlowType<E> taintType) {
// System.out.println(this.toString()+".addTargets("+d1+"...)");
for (UseDefSetPair p : useToDefList) {
if (p.uses.contains(d1)) {
// System.out.println("\t\tfound pair that uses "+d1);
for (CodeElement i : p.defs) {
// System.out.println("\t\tadding outflow "+i);
set.add(domain.getMappedIndex(new DomainElement(i, taintType)));
}
}
}
}
@Override
@SuppressWarnings("unchecked")
public IntSet getTargets(int d1) {
// System.out.println(this.toString()+".getTargets("+d1+") "+bb);
// BitVectorIntSet set = new BitVectorIntSet();
MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
set.add(d1);
DomainElement de = domain.getMappedObject(d1);
if (de != null) {
addTargets(de.codeElement, set, de.taintSource);
}
return set;
}
}
@Override
public IUnaryFlowFunction getCallFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest, BasicBlockInContext<E> ret) {
assert graph.isCall(src);
final SSAInvokeInstruction instruction = (SSAInvokeInstruction) src.getLastInstruction();
// String signature = dest.getMethod().getSignature();
// if ( dest.getMethod().isWalaSynthetic() ) {
// System.out.println("Synthetic: "+signature);
// } else {
// System.err.println(signature);
// }
// if ( LoaderUtils.fromLoader(src.getNode(), ClassLoaderReference.Application)
// && LoaderUtils.fromLoader(dest.getNode(), ClassLoaderReference.Primordial)) {
// System.out.println("Call to system: "+signature);
// }
// if (! dest.getMethod().isWalaSynthetic()
// && LoaderUtils.fromLoader(dest.getNode(), ClassLoaderReference.Primordial)) {
//
// MyLogger.log(DEBUG,"Primordial and No Summary! (getCallFlowFunction) - " +
// dest.getMethod().getReference());
// }
final Map<CodeElement, CodeElement> parameterMap = HashMapFactory.make();
for (int i = 0; i < instruction.getNumberOfPositionalParameters(); i++) {
Set<CodeElement> elements = CodeElement.valueElements(instruction.getUse(i));
for (CodeElement e : elements) {
parameterMap.put(e, new LocalElement(i + 1));
}
}
return d1 -> {
BitVectorIntSet set = new BitVectorIntSet();
if (d1 == 0 || !(domain.getMappedObject(d1).codeElement instanceof LocalElement)) {
set.add(d1);
}
DomainElement de = domain.getMappedObject(d1);
if (de != null && parameterMap.containsKey(de.codeElement))
set.add(
domain.getMappedIndex(
new DomainElement(parameterMap.get(de.codeElement), de.taintSource)));
return set;
};
}
@Override
public IUnaryFlowFunction getCallNoneToReturnFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
// I Believe this method is called only if there are no callees of src in the supergraph
// if supergraph included all primordials, this method can still be called if it calls a
// method that wasn't included in the scope
// Assertions.UNREACHABLE();
// TODO: Look up summary for this method, or warn if it doesn't exist.
assert src.getNode().equals(dest.getNode());
// final SSAInvokeInstruction instruction = (SSAInvokeInstruction) src.getLastInstruction();
// System.out.println("call to return(no callee) method inside call graph: " +
// src.getNode()+"--" + instruction.getDeclaredTarget());
// System.out.println("call to system: " + instruction.getDeclaredTarget());
return new DefUse(dest);
}
@Override
public IUnaryFlowFunction getCallToReturnFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
assert src.getNode().equals(dest.getNode());
// final SSAInvokeInstruction instruction = (SSAInvokeInstruction) src.getLastInstruction();
// System.out.println("call to return method inside call graph: " +
// instruction.getDeclaredTarget());
return new DefUse(dest);
}
@Override
public IUnaryFlowFunction getNormalFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
assert src.getNode().equals(dest.getNode());
// System.out.println("getNormalFlowFuntion");
// System.out.println("\tSrc " + src.getLastInstruction());
// System.out.println("\tDest " + dest.getLastInstruction());
return new DefUse(dest);
}
public class ReturnDefUse extends DefUse {
CodeElement callSet;
Set<CodeElement> receivers = new HashSet<>();
public ReturnDefUse(BasicBlockInContext<E> dest, BasicBlockInContext<E> call) {
super(dest);
// TODO: look into exception handling through getDef(1)
if (call.getLastInstruction() instanceof SSAInvokeInstruction) {
SSAInvokeInstruction invInst = (SSAInvokeInstruction) call.getLastInstruction();
if (!invInst.isSpecial()) { // && !invInst.isStatic()) {
// for (int i = 0; i < invInst.getNumberOfReturnValues(); i++) {
//
// }
if (invInst.hasDef()) {
callSet = new LocalElement(invInst.getReturnValue(0));
if (!invInst.isStatic()) {
// used to be invInst.getReceiver(), but I believe that was incorrect.
receivers.addAll(CodeElement.valueElements(invInst.getReceiver()));
// receivers.addAll(CodeElement.valueElements(pa, call.getNode(),
// invInst.getReturnValue(0)));
}
}
}
} else {
callSet = null;
}
// // TODO: look into exception handling through getDef(1)
// if(call.getLastInstruction().getNumberOfDefs() == 1)
// {
// //System.out.println("\treturn defines something: "+call.getLastInstruction());
// callSet = new LocalElement(call.getLastInstruction().getDef(0));
// if(call.getLastInstruction() instanceof SSAInvokeInstruction)
// {
// SSAInvokeInstruction invInst = (SSAInvokeInstruction) call.getLastInstruction();
// if(!invInst.isSpecial() && !invInst.isStatic()) {
// receivers.addAll(CodeElement.valueElements(pa, call.getNode(),
// invInst.getReceiver()));
// }
// }
// }
// else
// callSet = null;
}
@Override
public IntSet getTargets(int d1) {
if (d1 != 0 && domain.getMappedObject(d1).codeElement instanceof ReturnElement) {
BitVectorIntSet set = new BitVectorIntSet();
if (callSet != null) {
// System.out.println("callset: " + callSet);
set.add(
domain.getMappedIndex(
new DomainElement(callSet, domain.getMappedObject(d1).taintSource)));
}
return set;
} else if (d1 != 0 && domain.getMappedObject(d1).codeElement instanceof LocalElement) {
return new BitVectorIntSet();
} else if (d1 != 0 && receivers.contains(domain.getMappedObject(d1).codeElement)) {
BitVectorIntSet set = new BitVectorIntSet();
if (callSet != null)
set.add(
domain.getMappedIndex(
new DomainElement(callSet, domain.getMappedObject(d1).taintSource)));
set.addAll(super.getTargets(d1));
return set;
} else {
return super.getTargets(d1);
}
}
}
@Override
public IFlowFunction getReturnFlowFunction(
BasicBlockInContext<E> call, BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
assert (graph.isCall(call) && graph.isReturn(dest) && call.getNode().equals(dest.getNode()));
// final SSAInvokeInstruction instruction = (SSAInvokeInstruction) call.getLastInstruction();
// System.out.println("Return from call to method inside call graph: " +
// instruction.getDeclaredTarget());
return new ReturnDefUse(dest, call);
}
}
| 22,435
| 38.5
| 98
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/PairBasedFlowFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import java.util.List;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
final class PairBasedFlowFunction<E extends ISSABasicBlock> implements IUnaryFlowFunction {
// private static final Logger logger =
// LoggerFactory.getLogger(PairBasedFlowFunction.class);
private final List<UseDefPair> useToDefList;
private final IFDSTaintDomain<E> domain;
public PairBasedFlowFunction(IFDSTaintDomain<E> domain, List<UseDefPair> useToDefList) {
this.domain = domain;
this.useToDefList = useToDefList;
}
@Override
public IntSet getTargets(int d) {
// logger.debug("getTargets("+d+")");
if (0 == d) {
// logger.debug("getTargets("+d+"): {0}");
return TaintTransferFunctions.ZERO_SET;
}
MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
DomainElement de = domain.getMappedObject(d);
// Here we list what facts we pass through. If a fact was true
// before executing this instruction, it'll be true after,
// unless we created a new definition of its associated
// CodeElement.
// see if D is still true; if so, pass it through:
// (this corresponds to the vertical 'pass through' arrows in the RHS paper)
// we actually assume that D passes through, unless there
// is evidence to the contrary. Because of this, instructions will
// 'default' to propagating taints that were not relevant to that
// instruction, which is what we want.
set.add(d);
for (UseDefPair udPair : useToDefList) {
CodeElement def = udPair.getDef();
if (def.equals(de.codeElement)) {
// this instruction redefined D, so we
// do *not* pass it through - this conditional has
// contradicted our assumption that D should be passed through,
// so remove it from the set:
set.remove(d);
break;
}
}
////////////////////////////////////////////////////////////////
// see if the taints associated with D also flow through to any
// other domain elements:
for (UseDefPair udPair : useToDefList) {
CodeElement use = udPair.getUse();
if (use.equals(de.codeElement)) {
// ok, the d element flows to the def, so we add that def
// and keep looking.
DomainElement newDE = new DomainElement(udPair.getDef(), de.taintSource);
set.add(domain.getMappedIndex(newDE));
}
}
// logger.debug("getTargets("+d+"): "+set);
return set;
}
}
| 4,733
| 37.177419
| 91
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/ReturnFlowFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.SparseIntSet;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.LocalElement;
import org.scandroid.domain.ReturnElement;
/** @author creswick */
public class ReturnFlowFunction<E extends ISSABasicBlock> implements IUnaryFlowFunction {
private final IFDSTaintDomain<E> domain;
private final CodeElement ce;
/** @param def of the invoke instruction we're returning to */
public ReturnFlowFunction(IFDSTaintDomain<E> domain, int def) {
this.domain = domain;
this.ce = new LocalElement(def);
}
/*
* (non-Javadoc)
*
* @see com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction#getTargets(int)
*/
@Override
public IntSet getTargets(int d1) {
if (0 == d1) {
return TaintTransferFunctions.ZERO_SET;
}
DomainElement de = domain.getMappedObject(d1);
// if the domain element is a return element, propagate its taint
if (de.codeElement instanceof ReturnElement) {
return SparseIntSet.singleton(domain.getMappedIndex(new DomainElement(ce, de.taintSource)));
}
return TaintTransferFunctions.EMPTY_SET;
}
}
| 3,386
| 39.807229
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/TaintTransferFunctions.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.dataflow.IFDS.IFlowFunction;
import com.ibm.wala.dataflow.IFDS.IFlowFunctionMap;
import com.ibm.wala.dataflow.IFDS.IReversibleFlowFunction;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.dataflow.IFDS.IdentityFlowFunction;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey;
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.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayReferenceInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSAFieldAccessInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.types.FieldReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.SparseIntSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.DomainElement;
import org.scandroid.domain.FieldElement;
import org.scandroid.domain.IFDSTaintDomain;
import org.scandroid.domain.InstanceKeyElement;
import org.scandroid.domain.LocalElement;
import org.scandroid.domain.ReturnElement;
import org.scandroid.domain.StaticFieldElement;
import org.scandroid.flow.types.StaticFieldFlow;
public class TaintTransferFunctions<E extends ISSABasicBlock>
implements IFlowFunctionMap<BasicBlockInContext<E>> {
// Java, you need type aliases.
private static class BlockPair<E extends ISSABasicBlock>
extends Pair<BasicBlockInContext<E>, BasicBlockInContext<E>> {
private static final long serialVersionUID = 6838579950051954781L;
protected BlockPair(BasicBlockInContext<E> fst, BasicBlockInContext<E> snd) {
super(fst, snd);
}
}
private final IFDSTaintDomain<E> domain;
private final PointerAnalysis<InstanceKey> pa;
private final boolean taintStaticFields;
private final IUnaryFlowFunction globalId;
private final IUnaryFlowFunction callToReturn;
private final LoadingCache<BlockPair<E>, IUnaryFlowFunction> callFlowFunctions;
private final LoadingCache<BlockPair<E>, IUnaryFlowFunction> normalFlowFunctions;
public static final IntSet EMPTY_SET = new SparseIntSet();
public static final IntSet ZERO_SET = SparseIntSet.singleton(0);
private static final IReversibleFlowFunction IDENTITY_FN = new IdentityFlowFunction();
public TaintTransferFunctions(IFDSTaintDomain<E> domain, PointerAnalysis<InstanceKey> pa) {
this(domain, pa, false);
}
public TaintTransferFunctions(
IFDSTaintDomain<E> domain, PointerAnalysis<InstanceKey> pa, boolean taintStaticFields) {
this.domain = domain;
this.pa = pa;
this.globalId = new GlobalIdentityFunction<>(domain);
this.callToReturn = new CallToReturnFunction<>(domain);
this.callFlowFunctions =
CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader<>() {
@Override
public IUnaryFlowFunction load(BlockPair<E> key) {
return makeCallFlowFunction(key.fst);
}
});
this.normalFlowFunctions =
CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader<>() {
@Override
public IUnaryFlowFunction load(BlockPair<E> key) {
return makeNormalFlowFunction(key.snd);
}
});
this.taintStaticFields = taintStaticFields;
}
@Override
public IUnaryFlowFunction getCallFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest, BasicBlockInContext<E> ret) {
try {
return callFlowFunctions.get(new BlockPair<>(src, dest));
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
private IUnaryFlowFunction makeCallFlowFunction(BasicBlockInContext<E> src) {
SSAInstruction srcInst = src.getLastInstruction();
if (null == srcInst) {
return IDENTITY_FN;
}
if (srcInst instanceof SSAInvokeInstruction) {
// build list of actual parameter code elements, and return a
// function
final int numParams = ((SSAInvokeInstruction) srcInst).getNumberOfPositionalParameters();
List<CodeElement> actualParams = new ArrayList<>(numParams);
for (int i = 0; i < numParams; i++) {
actualParams.add(i, new LocalElement(srcInst.getUse(i)));
}
// return new TracingFlowFunction<E>(domain, union(new
// GlobalIdentityFunction<E>(domain),
// new CallFlowFunction<E>(domain, actualParams)));
return union(globalId, new CallFlowFunction<>(domain, actualParams));
} else {
throw new RuntimeException("src block not an invoke instruction");
}
}
@Override
public IUnaryFlowFunction getCallNoneToReturnFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
// return callNoneToReturn;
/*
* TODO: is this right?
*
* The original callNoneToReturn impl just adds taints to absolutely
* everything in the domain. This seems like the wrong approach, but
* it's unclear what would be correct...
*
* Switching this to the identity for now improves performance
* drastically.
*/
return IDENTITY_FN;
}
@Override
public IUnaryFlowFunction getCallToReturnFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
// return new TracingFlowFunction<E>(domain, new
// CallToReturnFunction<E>(domain));
return callToReturn;
}
@Override
public IUnaryFlowFunction getNormalFlowFunction(
BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
try {
return normalFlowFunctions.get(new BlockPair<>(src, dest));
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
private IUnaryFlowFunction makeNormalFlowFunction(BasicBlockInContext<E> dest) {
List<UseDefPair> pairs = new ArrayList<>();
// we first try to process the destination instruction
SSAInstruction inst = dest.getLastInstruction();
CGNode node = dest.getNode();
if (null == inst) {
return IDENTITY_FN;
}
Iterable<CodeElement> inCodeElts = getInCodeElts(node, inst);
Iterable<CodeElement> outCodeElts = getOutCodeElts(node, inst);
if (!inCodeElts.iterator().hasNext()) {}
if (!outCodeElts.iterator().hasNext()) {}
// for now, take the Cartesian product of the inputs and outputs:
// TODO specialize this on a per-instruction basis to improve precision.
for (CodeElement use : inCodeElts) {
for (CodeElement def : outCodeElts) {
pairs.add(new UseDefPair(use, def));
}
}
// globals may be redefined here, so we can't union with the globals ID
// flow function, as we often do elsewhere.
final PairBasedFlowFunction<E> flowFunction = new PairBasedFlowFunction<>(domain, pairs);
// special case for static field gets so we can introduce new taints for
// them
if (taintStaticFields
&& inst instanceof SSAGetInstruction
&& ((SSAGetInstruction) inst).isStatic()) {
return makeStaticFieldTaints(dest, inst, flowFunction);
}
return flowFunction;
}
public IUnaryFlowFunction makeStaticFieldTaints(
BasicBlockInContext<E> dest,
SSAInstruction inst,
final PairBasedFlowFunction<E> flowFunction) {
final Set<DomainElement> elts = HashSetFactory.make();
for (CodeElement ce : getStaticFieldAccessCodeElts((SSAGetInstruction) inst)) {
StaticFieldElement sfe = (StaticFieldElement) ce;
IField field = pa.getClassHierarchy().resolveField(sfe.getRef());
if (field.isFinal()) {
continue;
}
final StaticFieldFlow<E> taintSource = new StaticFieldFlow<>(dest, field, true);
elts.add(new DomainElement(ce, taintSource));
}
IUnaryFlowFunction newTaints = new ConstantFlowFunction<>(domain, elts);
return compose(flowFunction, newTaints);
}
/*
* The usual arguments:
*
* call: the invoke instruction that took us into this method
*
* src: a block that's the postdominator of this method, usually with no
* instructions
*
* dest: whatever instruction followed the invoke instruction in call
*
* What we want to accomplish:
*
* 1. Map taints from the value being returned to a LocalElement in the
* caller's context
*
* 2. Pass through any global information that the callee may have changed
*
* 3. Process ins/outs of dest block as well (it will never be the dest of a
* NormalFlowFunction)
*
* @see
* com.ibm.wala.dataflow.IFDS.IFlowFunctionMap#getReturnFlowFunction(java
* .lang.Object, java.lang.Object, java.lang.Object)
*/
@Override
public IFlowFunction getReturnFlowFunction(
BasicBlockInContext<E> call, BasicBlockInContext<E> src, BasicBlockInContext<E> dest) {
final SSAInstruction inst = call.getLastInstruction();
if (null == inst || !(inst instanceof SSAInvokeInstruction)) {
// if we don't have an invoke, just punt and hope the necessary
// information is already in global elements
return globalId;
}
// we always need to process the destination instruction
final IUnaryFlowFunction flowFromDest = getNormalFlowFunction(null, dest);
final SSAInvokeInstruction invoke = (SSAInvokeInstruction) inst;
if (invoke.getNumberOfReturnValues() == 0) {
// no return values, just propagate global information
// return new TracingFlowFunction<E>(domain, compose (flowFromDest,
// new GlobalIdentityFunction<E>(domain)));
return compose(flowFromDest, globalId);
}
// we have a return value, so we need to map any return elements onto
// the local element corresponding to the invoke's def
final IUnaryFlowFunction flowToDest =
union(globalId, new ReturnFlowFunction<>(domain, invoke.getDef()));
// return new TracingFlowFunction<E>(domain, compose(flowFromDest,
// flowToDest));
return compose(flowFromDest, flowToDest);
}
private Iterable<CodeElement> getOutCodeElts(CGNode node, SSAInstruction inst) {
int defNo = inst.getNumberOfDefs();
Set<CodeElement> elts = HashSetFactory.make();
if (inst instanceof SSAReturnInstruction) {
// only one possible element for returns
elts.add(new ReturnElement());
return elts;
}
if (inst instanceof SSAPutInstruction) {
final Set<CodeElement> fieldAccessCodeElts =
getFieldAccessCodeElts(node, (SSAPutInstruction) inst);
elts.addAll(fieldAccessCodeElts);
}
if (inst instanceof SSAArrayStoreInstruction) {
elts.addAll(getArrayRefCodeElts(node, (SSAArrayStoreInstruction) inst));
}
for (int i = 0; i < defNo; i++) {
int valNo = inst.getDef(i);
elts.addAll(CodeElement.valueElements(valNo));
}
return elts;
}
private Iterable<CodeElement> getInCodeElts(CGNode node, SSAInstruction inst) {
int useNo = inst.getNumberOfUses();
Set<CodeElement> elts = HashSetFactory.make();
if (inst instanceof SSAGetInstruction) {
elts.addAll(getFieldAccessCodeElts(node, (SSAGetInstruction) inst));
}
if (inst instanceof SSAArrayLoadInstruction) {
elts.addAll(getArrayRefCodeElts(node, (SSAArrayLoadInstruction) inst));
}
for (int i = 0; i < useNo; i++) {
int valNo = inst.getUse(i);
// Constants have valuenumber 0, which is otherwise, illegal.
// these need to be skipped:
if (0 == valNo) {
continue;
}
try {
elts.addAll(CodeElement.valueElements(valNo));
} catch (IllegalArgumentException e) {
throw e;
}
}
return elts;
}
// private Iterable<CodeElement> getOutCodeElts(final CGNode node, final
// SSAInstruction inst) {
// return new Iterable<CodeElement>() {
// @Override
// public Iterator<CodeElement> iterator() {
// return new DefEltIterator(node, inst);
// }
// };
// }
//
// private Iterable<CodeElement> getInCodeElts(final CGNode node, final
// SSAInstruction inst) {
// return new Iterable<CodeElement>() {
// @Override
// public Iterator<CodeElement> iterator() {
// return new UseEltIterator(node, inst);
// }
// };
// }
private Set<CodeElement> getFieldAccessCodeElts(CGNode node, SSAFieldAccessInstruction inst) {
if (inst.isStatic()) {
return getStaticFieldAccessCodeElts(inst);
}
Set<CodeElement> elts = HashSetFactory.make();
final FieldReference fieldRef = inst.getDeclaredField();
final IField field = node.getClassHierarchy().resolveField(fieldRef);
PointerKey pk = pa.getHeapModel().getPointerKeyForLocal(node, inst.getRef());
final OrdinalSet<InstanceKey> pointsToSet = pa.getPointsToSet(pk);
if (pointsToSet.isEmpty()) {
InstanceKey ik = new ConcreteTypeKey(field.getDeclaringClass());
elts.add(new FieldElement(ik, fieldRef));
elts.add(new InstanceKeyElement(ik));
} else {
for (InstanceKey ik : pointsToSet) {
elts.add(new FieldElement(ik, fieldRef));
elts.add(new InstanceKeyElement(ik));
}
}
return elts;
}
private static Set<CodeElement> getStaticFieldAccessCodeElts(SSAFieldAccessInstruction inst) {
Set<CodeElement> elts = HashSetFactory.make();
final FieldReference fieldRef = inst.getDeclaredField();
elts.add(new StaticFieldElement(fieldRef));
// TODO: what about tainting the declaring class?
return elts;
}
private Set<CodeElement> getArrayRefCodeElts(CGNode node, SSAArrayReferenceInstruction inst) {
Set<CodeElement> elts = HashSetFactory.make();
final PointerKey pk = pa.getHeapModel().getPointerKeyForLocal(node, inst.getArrayRef());
final OrdinalSet<InstanceKey> pointsToSet = pa.getPointsToSet(pk);
if (pointsToSet.isEmpty()) {
TypeReference arrayType = TypeReference.findOrCreateArrayOf(inst.getElementType());
InstanceKey ik = new ConcreteTypeKey(pa.getClassHierarchy().lookupClass(arrayType));
elts.add(new InstanceKeyElement(ik));
} else {
for (InstanceKey ik : pointsToSet) {
elts.add(new InstanceKeyElement(ik));
}
}
return elts;
}
private static IUnaryFlowFunction union(final IUnaryFlowFunction g, final IUnaryFlowFunction h) {
return d1 -> g.getTargets(d1).union(h.getTargets(d1));
}
/**
* Flow function composition
*
* @return { (x, z) | (x, y) \in g, (y, z) \in f }
*/
private static IUnaryFlowFunction compose(
final IUnaryFlowFunction f, final IUnaryFlowFunction g) {
return d1 -> {
final MutableSparseIntSet set = MutableSparseIntSet.makeEmpty();
g.getTargets(d1).foreach(x -> set.addAll(f.getTargets(x)));
return set;
};
}
/*
* private class UseEltIterator implements Iterator<CodeElement> { private
* int idx = 0; private Iterator<CodeElement> subIt; private final CGNode
* node; private final SSAInstruction inst; private final int count;
*
* public UseEltIterator(CGNode node, SSAInstruction inst) { this.node =
* node; this.inst = inst; count = inst.getNumberOfUses();
* updateIterator(node, inst); }
*
* private void updateIterator(final CGNode node, final SSAInstruction inst)
* { int valNo = inst.getUse(idx); idx++; Set<CodeElement> elements =
* CodeElement.valueElements(pa, node, valNo); subIt = elements.iterator();
* }
*
* @Override public boolean hasNext() { if (subIt.hasNext()) { return true;
* } else if (idx < count) { updateIterator(node, inst); return hasNext(); }
* else { return false; } }
*
* @Override public CodeElement next() { return subIt.next(); }
*
* @Override public void remove() {} }
*
* private class DefEltIterator implements Iterator<CodeElement> { private
* int idx = 0; private Iterator<CodeElement> subIt; private final CGNode
* node; private final SSAInstruction inst; private final int count;
*
* public DefEltIterator(CGNode node, SSAInstruction inst) { this.node =
* node; this.inst = inst; count = inst.getNumberOfDefs();
* updateIterator(node, inst); }
*
* private void updateIterator(final CGNode node, final SSAInstruction inst)
* { int valNo = inst.getDef(idx); idx++; Set<CodeElement> elements =
* CodeElement.valueElements(pa, node, valNo); subIt = elements.iterator();
* }
*
* @Override public boolean hasNext() { if (subIt.hasNext()) { return true;
* } else if (idx < count) { updateIterator(node, inst); return hasNext(); }
* else { return false; } }
*
* @Override public CodeElement next() { return subIt.next(); }
*
* @Override public void remove() {} }
*/
}
| 19,786
| 36.333962
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/TracingFlowFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.functions;
import com.ibm.wala.dataflow.IFDS.IUnaryFlowFunction;
import com.ibm.wala.util.intset.IntSet;
public class TracingFlowFunction implements IUnaryFlowFunction {
private final IUnaryFlowFunction function;
public TracingFlowFunction(IUnaryFlowFunction function) {
this.function = function;
}
@Override
public IntSet getTargets(int d1) {
return function.getTargets(d1);
}
}
| 2,437
| 41.77193
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/functions/UseDefPair.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.flow.functions;
import org.scandroid.domain.CodeElement;
final class UseDefPair {
private final CodeElement use;
private final CodeElement def;
public UseDefPair(CodeElement use, CodeElement def) {
this.use = use;
this.def = def;
}
public CodeElement getUse() {
return use;
}
public CodeElement getDef() {
return def;
}
@Override
public String toString() {
return "UseDefPair [use=" + use + ", def=" + def + ']';
}
}
| 2,461
| 32.726027
| 86
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/types/FieldFlow.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.types;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
/**
* A flow to or from a field. The associated block represents either the location of the get or put
* instruction, or the entry or exit block of a method which is reading or writing the field. In the
* former case, the associate field is redundant, but potentially convenient. In the latter case,
* it's necessary.
*
* @author atomb
*/
public class FieldFlow<E extends ISSABasicBlock> extends FlowType<E> {
private final IField field;
public FieldFlow(BasicBlockInContext<E> block, IField field, boolean source) {
super(block, source);
this.field = field;
}
@Override
public String toString() {
return "FieldFlow( field=" + field + ' ' + super.toString() + ')';
}
@Override
public String descString() {
return field.getDeclaringClass().toString() + '.' + field.getName().toString();
}
public IField getField() {
return field;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((field == null) ? 0 : field.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
@SuppressWarnings("unchecked")
FieldFlow<E> other = (FieldFlow<E>) obj;
if (field == null) {
if (other.field != null) return false;
} else if (!field.equals(other.field)) return false;
return true;
}
@Override
public <R> R visit(FlowTypeVisitor<E, R> v) {
return v.visitFieldFlow(this);
}
}
| 3,761
| 35.173077
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/types/FlowType.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Adam Fuchs <afuchs@cs.umd.edu> Avik Chaudhuri <avik@cs.umd.edu>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.types;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
/**
* Flow types represent specific instances of sources or sinks.
*
* <p>In contrast to the Source/Sink specs, these have ties to specific locations in the source.
*
* @author creswick
*/
public abstract class FlowType<E extends ISSABasicBlock> {
private final BasicBlockInContext<E> block;
private final boolean source;
protected FlowType(BasicBlockInContext<E> block, boolean source) {
this.block = block;
this.source = source;
}
public final BasicBlockInContext<E> getBlock() {
return block;
}
public final boolean isSource() {
return source;
}
@Override
public String toString() {
return "block=" + block + ", source=" + source + ", desc=" + descString();
}
public String descString() {
if (source) return "I";
else return "O";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((block == null) ? 0 : block.getNumber());
result = prime * result + (source ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
@SuppressWarnings("unchecked")
FlowType<E> other = (FlowType<E>) obj;
if (block == null) {
if (other.block != null) return false;
} else if (block.getNumber() != other.block.getNumber()) {
return false;
}
if (source != other.source) return false;
return true;
}
/**
* custom comparison for BasicBlockInContext. The WALA .equals() implementation eventually
* delegates to pointer equality, which is too specific for our needs.
*/
@SuppressWarnings("unused")
private boolean compareBlocks(BasicBlockInContext<E> a, BasicBlockInContext<E> b) {
if (null == a || null == b) {
return false;
}
// delegate to the defined implementation, but only if it's true.
if (a.equals(b)) {
return true;
}
if (a.getNumber() != b.getNumber()) {
return false;
}
if (!a.getMethod().getSignature().equals(b.getMethod().getSignature())) {
return false;
}
return true;
}
public abstract <R> R visit(FlowTypeVisitor<E, R> v);
public interface FlowTypeVisitor<E extends ISSABasicBlock, R> {
R visitFieldFlow(FieldFlow<E> flow);
R visitIKFlow(IKFlow<E> flow);
R visitParameterFlow(ParameterFlow<E> flow);
R visitReturnFlow(ReturnFlow<E> flow);
R visitStaticFieldFlow(StaticFieldFlow<E> flow);
}
}
| 4,576
| 31.232394
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/types/IKFlow.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Adam Fuchs <afuchs@cs.umd.edu> Avik Chaudhuri <avik@cs.umd.edu>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.types;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
public class IKFlow<E extends ISSABasicBlock> extends FlowType<E> {
private final InstanceKey ik;
public IKFlow(InstanceKey ik, BasicBlockInContext<E> block, boolean source) {
super(block, source);
this.ik = ik;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((ik == null) ? 0 : ik.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
@SuppressWarnings("unchecked")
IKFlow<E> other = (IKFlow<E>) obj;
if (ik == null) {
if (other.ik != null) return false;
} else if (!ik.equals(other.ik)) // TODO InstanceKey may not supply equals()
return false;
return true;
}
@Override
public String toString() {
return "IKFlow(ik=" + ik + ' ' + super.toString() + ')';
}
public InstanceKey getIK() {
return ik;
}
@Override
public <R> R visit(org.scandroid.flow.types.FlowType.FlowTypeVisitor<E, R> v) {
return v.visitIKFlow(this);
}
}
| 3,246
| 35.483146
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/types/ParameterFlow.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.flow.types;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
/**
* A flow to or from the parameter of a method. This can represent formal parameters of methods
* being analyzed, or actual parameters of methods being called. In the former case, the associated
* block is the entry block of the method. In the latter case, the block is the block containing the
* invoke instruction.
*
* @author atomb
*/
public class ParameterFlow<E extends ISSABasicBlock> extends FlowType<E> {
private final int argNum;
public ParameterFlow(BasicBlockInContext<E> block, int argNum, boolean source) {
super(block, source);
this.argNum = argNum;
}
public int getArgNum() {
return argNum;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + argNum;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
@SuppressWarnings("unchecked")
ParameterFlow<E> other = (ParameterFlow<E>) obj;
if (argNum != other.argNum) return false;
return true;
}
@Override
public String toString() {
return "ParameterFlow( argNum=" + argNum + ' ' + super.toString() + ')';
}
@Override
public String descString() {
String s = "arg(" + argNum + ')';
if (!getBlock().isEntryBlock()) {
SSAInvokeInstruction inv =
(SSAInvokeInstruction) ((IExplodedBasicBlock) getBlock().getDelegate()).getInstruction();
s = s + ':' + inv.getDeclaredTarget().getSignature();
}
return s;
}
@Override
public <R> R visit(FlowTypeVisitor<E, R> v) {
return v.visitParameterFlow(this);
}
}
| 3,824
| 32.26087
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/types/ReturnFlow.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.scandroid.flow.types;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInvokeInstruction;
/**
* A return flow represents either a flow from a method that was just invoked if this points to an
* invoke instruction (in which case this is a source) or a method return, if this points to a
* return instruction (in which case it is a sink).
*/
public class ReturnFlow<E extends ISSABasicBlock> extends FlowType<E> {
public ReturnFlow(BasicBlockInContext<E> block, boolean source) {
super(block, source);
}
@Override
public String toString() {
return "ReturnFlow( " + super.toString() + ')';
}
@Override
public String descString() {
if (isSource()) {
SSAInvokeInstruction inv = (SSAInvokeInstruction) getBlock().getLastInstruction();
return "ret:" + inv.getDeclaredTarget().getSignature();
} else {
return "ret";
}
}
@Override
public <R> R visit(FlowTypeVisitor<E, R> v) {
return v.visitReturnFlow(this);
}
}
| 2,992
| 34.630952
| 98
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/flow/types/StaticFieldFlow.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.flow.types;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
/** @author acfoltzer */
public class StaticFieldFlow<E extends ISSABasicBlock> extends FlowType<E> {
private final IField field;
public StaticFieldFlow(BasicBlockInContext<E> block, IField field, boolean source) {
super(block, source);
this.field = field;
}
@Override
public String toString() {
return "StaticFieldFlow( field=" + field + ' ' + super.toString() + ')';
}
@Override
public String descString() {
return field.getDeclaringClass().toString() + '.' + field.getName().toString();
}
public IField getField() {
return field;
}
/* (non-Javadoc)
* @see org.scandroid.flow.types.FlowType#visit(org.scandroid.flow.types.FlowType.FlowTypeVisitor)
*/
@Override
public <R> R visit(FlowTypeVisitor<E, R> v) {
return v.visitStaticFieldFlow(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((field == null) ? 0 : field.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
@SuppressWarnings("unchecked")
StaticFieldFlow<E> other = (StaticFieldFlow<E>) obj;
if (field == null) {
if (other.field != null) return false;
} else if (!field.equals(other.field)) return false;
return true;
}
}
| 3,600
| 35.744898
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/model/AppModelMethod.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>) Steve Suh
* <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.model;
import com.ibm.wala.classLoader.ArrayClass;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.summaries.MethodSummary;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.IDispatch;
import com.ibm.wala.ssa.ConstantValue;
import com.ibm.wala.ssa.SSAAbstractInvokeInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSAInstructionFactory;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.debug.UnimplementedError;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.scandroid.spec.AndroidSpecs;
import org.scandroid.spec.MethodNamePattern;
import org.scandroid.util.LoaderUtils;
public class AppModelMethod {
int nextLocal;
/** A mapping from String (variable name) -> Integer (local number) */
private Map<String, Integer> symbolTable = null;
private MethodSummary methodSummary;
private final IClassHierarchy cha;
private final AnalysisScope scope;
private final Map<ConstantValue, Integer> constant2ValueNumber = HashMapFactory.make();
SSAInstructionFactory insts;
// Maps a Type to variable name
private final Map<TypeReference, Integer> typeToID = new HashMap<>();
// innerclass dependencies
private final Map<TypeReference, LinkedList<TypeReference>> icDependencies = new HashMap<>();
// all callbacks to consider
private final List<MethodParams> callBacks = new ArrayList<>();
private final Map<TypeReference, TypeReference> aClassToTR = new HashMap<>();
private static class MethodParams {
public IMethod im;
public int params[];
private MethodParams(IMethod method) {
im = method;
}
private void setParams(int p[]) {
params = p;
}
private IMethod getIMethod() {
return im;
}
private int[] getParams() {
return params;
}
}
public AppModelMethod(IClassHierarchy cha, AnalysisScope scope, AndroidSpecs specs) {
this.cha = cha;
this.scope = scope;
Language lang = scope.getLanguage(ClassLoaderReference.Application.getLanguage());
insts = lang.instructionFactory();
startMethod();
buildTypeMap(specs);
processTypeMap();
processCallBackParams();
createLoopAndSwitch();
}
private void createLoopAndSwitch() {
int callbackSize = callBacks.size();
// start of while loop
int loopLabel = methodSummary.getNumberOfStatements();
int switchValue = nextLocal++;
// default label, for now same as case1
int defLabel = loopLabel + 1;
int[] casesAndLabels = new int[2 * callbackSize];
for (int i = 0; i < callbackSize; i++) {
casesAndLabels[i * 2] = i + 1;
casesAndLabels[i * 2 + 1] = defLabel + i * 2;
}
methodSummary.addStatement(
insts.SwitchInstruction(
methodSummary.getNumberOfStatements(), switchValue, defLabel, casesAndLabels));
for (MethodParams mp : callBacks) {
IMethod im = mp.getIMethod();
IDispatch dispatch;
if (im.isInit()) {
dispatch = IInvokeInstruction.Dispatch.SPECIAL;
} else if (im.isAbstract()) {
dispatch = IInvokeInstruction.Dispatch.INTERFACE;
} else if (im.isStatic()) {
dispatch = IInvokeInstruction.Dispatch.STATIC;
} else dispatch = IInvokeInstruction.Dispatch.VIRTUAL;
addInvocation(
mp.getParams(),
CallSiteReference.make(
methodSummary.getNumberOfStatements(), mp.getIMethod().getReference(), dispatch));
methodSummary.addStatement(
insts.GotoInstruction(methodSummary.getNumberOfStatements(), loopLabel));
}
}
private void startMethod() {
String className = "Lcom/SCanDroid/AppModel";
String methodName = "entry";
TypeReference governingClass =
TypeReference.findOrCreate(
ClassLoaderReference.Application, TypeName.string2TypeName(className));
Atom mName = Atom.findOrCreateUnicodeAtom(methodName);
Language lang = scope.getLanguage(ClassLoaderReference.Application.getLanguage());
Descriptor D = Descriptor.findOrCreateUTF8(lang, "()V");
MethodReference mref = MethodReference.findOrCreate(governingClass, mName, D);
methodSummary = new MethodSummary(mref);
methodSummary.setStatic(true);
methodSummary.setFactory(false);
int nParams = mref.getNumberOfParameters();
nextLocal = nParams + 1;
symbolTable = HashMapFactory.make(5);
for (int i = 0; i < nParams; i++) {
symbolTable.put("arg" + i, i + 1);
}
}
private void buildTypeMap(AndroidSpecs specs) {
// Go through all possible callbacks found in Application code
// Associate their TypeReference with a unique number in typeToID.
// Also keep track of all anonymous classes found.
for (MethodNamePattern mnp : specs.getCallBacks()) {
for (IMethod im : mnp.getPossibleTargets(cha)) {
// limit to functions defined within the application
if (LoaderUtils.fromLoader(im, ClassLoaderReference.Application)) {
callBacks.add(new MethodParams(im));
TypeReference tr = im.getDeclaringClass().getReference();
if (!typeToID.containsKey(tr)) {
typeToID.put(tr, nextLocal++);
// class is an innerclass
if (tr.getName().getClassName().toString().contains("$")) {
addDependencies(tr);
}
}
}
}
}
}
private void addDependencies(TypeReference tr) {
String packageName = 'L' + tr.getName().getPackage().toString() + '/';
String outerClassName;
String innerClassName = tr.getName().getClassName().toString();
@SuppressWarnings("JdkObsolete") // too many LinkedList APIs used
LinkedList<TypeReference> trLL = new LinkedList<>();
trLL.push(tr);
int index = innerClassName.lastIndexOf('$');
while (index != -1) {
outerClassName = innerClassName.substring(0, index);
TypeReference innerTR =
TypeReference.findOrCreate(
ClassLoaderReference.Application, packageName + outerClassName);
trLL.push(innerTR);
if (!typeToID.containsKey(innerTR)) {
typeToID.put(innerTR, nextLocal++);
aClassToTR.put(innerTR, tr);
}
innerClassName = outerClassName;
index = outerClassName.lastIndexOf('$');
}
icDependencies.put(tr, trLL);
}
private void processTypeMap() {
Set<Integer> createdIDs = new HashSet<>();
for (Entry<TypeReference, Integer> eSet : typeToID.entrySet()) {
Integer i = eSet.getValue();
if (createdIDs.contains(i)) continue;
TypeReference tr = eSet.getKey();
String className = tr.getName().getClassName().toString();
// Not an anonymous innerclass
if (!className.contains("$")) {
processAllocation(tr, i, false);
createdIDs.add(i);
}
// Is an anonymous innerclass
else {
LinkedList<TypeReference> deps = icDependencies.get(tr);
if (deps == null) {
tr = aClassToTR.get(tr);
}
for (TypeReference trD : icDependencies.get(tr)) {
Integer j = typeToID.get(trD);
if (!createdIDs.contains(j)) {
String depClassName = trD.getName().getClassName().toString();
processAllocation(trD, j, depClassName.contains("$"));
createdIDs.add(j);
}
}
}
}
assert (createdIDs.size() == typeToID.size()) : "typeToID and createdID size do not match";
}
private void processCallBackParams() {
for (MethodParams mp : callBacks) {
int params[] = new int[mp.getIMethod().getNumberOfParameters()];
int startPos;
if (mp.getIMethod().isStatic()) {
startPos = 0;
} else {
params[0] = typeToID.get(mp.getIMethod().getDeclaringClass().getReference());
startPos = 1;
}
for (int i = startPos; i < params.length; i++) {
params[i] = makeArgument(mp.getIMethod().getParameterType(i));
}
mp.setParams(params);
}
}
private int makeArgument(TypeReference tr) {
if (tr.isPrimitiveType()) return addLocal();
else {
SSANewInstruction n = processAllocation(tr, nextLocal++, false);
return (n == null) ? -1 : n.getDef();
}
}
private int addLocal() {
return nextLocal++;
}
private SSANewInstruction processAllocation(TypeReference tr, Integer i, boolean isInner) {
// create the allocation statement and add it to the method summary
NewSiteReference ref = NewSiteReference.make(methodSummary.getNumberOfStatements(), tr);
SSANewInstruction a = null;
if (tr.isArrayType()) {
int[] sizes = new int[((ArrayClass) cha.lookupClass(tr)).getDimensionality()];
Arrays.fill(sizes, getValueNumberForIntConstant(1));
a = insts.NewInstruction(methodSummary.getNumberOfStatements(), i, ref, sizes);
} else {
a = insts.NewInstruction(methodSummary.getNumberOfStatements(), i, ref);
}
methodSummary.addStatement(a);
IClass klass = cha.lookupClass(tr);
if (klass == null) {
return null;
}
if (klass.isArrayClass()) {
int arrayRef = a.getDef();
TypeReference e = klass.getReference().getArrayElementType();
while (e != null && !e.isPrimitiveType()) {
// allocate an instance for the array contents
NewSiteReference n = NewSiteReference.make(methodSummary.getNumberOfStatements(), e);
int alloc = nextLocal++;
SSANewInstruction ni = null;
if (e.isArrayType()) {
int[] sizes = new int[((ArrayClass) cha.lookupClass(tr)).getDimensionality()];
Arrays.fill(sizes, getValueNumberForIntConstant(1));
ni = insts.NewInstruction(methodSummary.getNumberOfStatements(), alloc, n, sizes);
} else {
ni = insts.NewInstruction(methodSummary.getNumberOfStatements(), alloc, n);
}
methodSummary.addStatement(ni);
// emit an astore
SSAArrayStoreInstruction store =
insts.ArrayStoreInstruction(
methodSummary.getNumberOfStatements(),
arrayRef,
getValueNumberForIntConstant(0),
alloc,
e);
methodSummary.addStatement(store);
e = e.isArrayType() ? e.getArrayElementType() : null;
arrayRef = alloc;
}
}
// invoke constructor
IMethod ctor = cha.resolveMethod(klass, MethodReference.initSelector);
if (ctor != null) {
// only check for more constructors when we're looking through the inner classes?
if (isInner
&& !ctor.getDeclaringClass().getName().toString().equals(klass.getName().toString())) {
boolean foundValidCtor = false;
for (IMethod im : klass.getAllMethods()) {
if (im.getDeclaringClass().getName().toString().equals(klass.getName().toString())
&& im.getSelector()
.getName()
.toString()
.equals(MethodReference.initAtom.toString())) {
ctor = im;
foundValidCtor = true;
// found a default constructor that takes only the outer class as a parameter
if (im.getDescriptor().getNumberOfParameters() == 1) {
break;
}
}
}
if (!foundValidCtor) {
throw new UnimplementedError(
"Check for other constructors, or just use default Object constructor");
}
}
int[] params;
if (ctor.getDescriptor().getNumberOfParameters() == 0) params = new int[] {i};
else {
params = new int[ctor.getNumberOfParameters()];
params[0] = i;
LinkedList<TypeReference> deps = icDependencies.get(tr);
if (deps == null) {
deps = icDependencies.get(aClassToTR.get(tr));
int index = deps.lastIndexOf(tr);
TypeReference otr = deps.get(index - 1);
assert ctor.getParameterType(1).equals(otr) : "Type Mismatch";
params[1] = typeToID.get(otr);
} else {
TypeReference otr = deps.get(deps.size() - 2);
assert ctor.getParameterType(1).equals(otr) : "Type Mismatch";
params[1] = typeToID.get(otr);
}
// Allocate new instances for each of the other parameters
// in the current constructor.
for (int pI = 2; pI < params.length; pI++) {
params[pI] = makeArgument(ctor.getParameterType(pI));
}
}
addInvocation(
params,
CallSiteReference.make(
methodSummary.getNumberOfStatements(),
ctor.getReference(),
IInvokeInstruction.Dispatch.SPECIAL));
}
return a;
}
public SSAAbstractInvokeInstruction addInvocation(int[] params, CallSiteReference site) {
if (site == null) {
throw new IllegalArgumentException("site is null");
}
CallSiteReference newSite =
CallSiteReference.make(
methodSummary.getNumberOfStatements(),
site.getDeclaredTarget(),
site.getInvocationCode());
SSAAbstractInvokeInstruction s = null;
if (newSite.getDeclaredTarget().getReturnType().equals(TypeReference.Void)) {
s =
insts.InvokeInstruction(
methodSummary.getNumberOfStatements(), params, nextLocal++, newSite, null);
} else {
s =
insts.InvokeInstruction(
methodSummary.getNumberOfStatements(),
nextLocal++,
params,
nextLocal++,
newSite,
null);
}
methodSummary.addStatement(s);
// cache.invalidate(this, Everywhere.EVERYWHERE);
return s;
}
protected int getValueNumberForIntConstant(int c) {
ConstantValue v = new ConstantValue(c);
Integer result = constant2ValueNumber.get(v);
if (result == null) {
result = nextLocal++;
constant2ValueNumber.put(v, result);
}
return result;
}
public MethodSummary getSummary() {
return methodSummary;
}
}
| 16,793
| 34.884615
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/BlockSearch.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSACFG;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
public class BlockSearch {
private final ArrayList<ISSABasicBlock> blockQueue = new ArrayList<>();
private int location = 0;
private final SSACFG cfg;
BlockSearch(IR ir) {
cfg = ir.getControlFlowGraph();
}
public ISSABasicBlock searchFromBlock(ISSABasicBlock b, Set<ISSABasicBlock> targets) {
blockQueue.clear();
location = 0;
Iterator<ISSABasicBlock> startNodes = cfg.getPredNodes(b);
while (startNodes.hasNext()) {
blockQueue.add(startNodes.next());
}
ISSABasicBlock candidate = null;
while (location < blockQueue.size()) {
ISSABasicBlock current = blockQueue.get(location);
location++;
// TODO: inspect current for function calls or other instructions that could confuse the
// analysis
if (targets.contains(current)) {
if (candidate == null) {
candidate = current;
} else if (candidate != current) {
return null;
}
continue;
} else {
Iterator<ISSABasicBlock> predNodes = cfg.getPredNodes(current);
while (predNodes.hasNext()) {
blockQueue.add(predNodes.next());
}
}
}
return candidate;
}
}
| 3,340
| 32.747475
| 94
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/InstanceKeySite.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
public abstract class InstanceKeySite {
public abstract int instanceID();
public abstract PrefixVariable propagate(PrefixVariable input);
}
| 2,121
| 36.892857
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/PrefixTransferFunction.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
import com.ibm.wala.fixpoint.UnaryOperator;
public class PrefixTransferFunction extends UnaryOperator<PrefixVariable> {
private final InstanceKeySite node;
public PrefixTransferFunction(InstanceKeySite node) {
this.node = node;
}
// public int nodeID = finalNode.getGraphNodeId();
@Override
public byte evaluate(PrefixVariable lhs, PrefixVariable rhs) {
PrefixVariable newLhs = node.propagate(rhs);
// if(lhs.equals(newLhs))
// return 1;
lhs.copyState(newLhs);
return 1;
}
@Override
public boolean equals(Object o) {
if (o != null && o.getClass().equals(this.getClass()))
return this.node == ((PrefixTransferFunction) o).node;
return false;
}
@Override
public int hashCode() {
return node.hashCode();
}
@Override
public String toString() {
return "Unary operator for " + node;
}
}
| 2,855
| 32.209302
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/PrefixTransferFunctionProvider.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
import com.ibm.wala.dataflow.graph.AbstractMeetOperator;
import com.ibm.wala.dataflow.graph.ITransferFunctionProvider;
import com.ibm.wala.fixpoint.UnaryOperator;
public class PrefixTransferFunctionProvider
implements ITransferFunctionProvider<InstanceKeySite, PrefixVariable> {
public PrefixTransferFunctionProvider() {}
@Override
public UnaryOperator<PrefixVariable> getEdgeTransferFunction(
InstanceKeySite src, InstanceKeySite dst) {
return null;
}
@Override
public AbstractMeetOperator<PrefixVariable> getMeetOperator() {
return new AbstractMeetOperator<>() {
@Override
public boolean equals(Object o) {
return o != null && o.toString().equals(toString());
}
@Override
public byte evaluate(PrefixVariable lhs, PrefixVariable[] rhs) {
// System.out.println("Evaluating meet");
boolean changed = false;
for (final PrefixVariable rhsTPV : rhs) {
changed = lhs.updateAll(rhsTPV) || changed;
}
return (changed ? (byte) 1 : (byte) 0);
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
return "TaintPropagationVariable union";
}
};
}
@Override
public UnaryOperator<PrefixVariable> getNodeTransferFunction(InstanceKeySite node) {
return new PrefixTransferFunction(node);
}
@Override
public boolean hasEdgeTransferFunctions() {
return false;
}
@Override
public boolean hasNodeTransferFunctions() {
return true;
}
}
| 3,579
| 30.681416
| 86
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/PrefixTransferGraph.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.AllocationSite;
import com.ibm.wala.ipa.callgraph.propagation.AllocationSiteInNode;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.NormalAllocationInNode;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.util.graph.Graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Stream;
import org.scandroid.prefixtransfer.StringBuilderUseAnalysis.StringBuilderToStringInstanceKeySite;
import org.scandroid.prefixtransfer.modeledAllocations.ConstantString;
public class PrefixTransferGraph implements Graph<InstanceKeySite> {
private final Map<InstanceKey, InstanceKeySite> nodeMap = new HashMap<>();
private final List<InstanceKeySite> nodes = new ArrayList<>();
private final Map<InstanceKeySite, Set<InstanceKeySite>> successors = new HashMap<>();
private final Map<InstanceKeySite, Set<InstanceKeySite>> predecessors = new HashMap<>();
public final Map<InstanceKey, StringBuilderUseAnalysis> sbuaMap = new HashMap<>();
public PrefixTransferGraph(PointerAnalysis<InstanceKey> pa) {
Map<InstanceKeySite, Set<InstanceKey>> unresolvedDependencies = new HashMap<>();
ArrayList<InstanceKey> instanceKeys = new ArrayList<>(pa.getInstanceKeys());
for (InstanceKey k : instanceKeys) {
if (k.getConcreteType().getName().toString().equals("Ljava/lang/StringBuilder")) {
if (k instanceof AllocationSiteInNode) {
AllocationSiteInNode as = (AllocationSiteInNode) k;
if (as.getSite()
.getDeclaredType()
.getClassLoader()
.equals(ClassLoaderReference.Application)) {
StringBuilderUseAnalysis sbua;
try {
sbua = new StringBuilderUseAnalysis(k, pa);
} catch (Exception e) {
continue;
}
sbuaMap.put(k, sbua); // map k to sbua in some global map
}
continue;
}
}
}
InstanceKeySite node = null;
for (InstanceKey k : instanceKeys) {
// create a node for each InstanceKey of type string
if (k.getConcreteType().getName().toString().equals("Ljava/lang/String")) {
if (k instanceof ConstantKey) {
node =
new ConstantString(
pa.getInstanceKeyMapping().getMappedIndex(k),
(String) ((ConstantKey<?>) k).getValue());
addNode(node);
nodeMap.put(k, node);
} else if (k instanceof NormalAllocationInNode) {
IMethod m = ((NormalAllocationInNode) k).getNode().getMethod();
if (m.getSignature().equals("java.lang.StringBuilder.toString()Ljava/lang/String;")) {
Context context = ((NormalAllocationInNode) k).getNode().getContext();
CGNode caller = (CGNode) context.get(ContextKey.CALLER);
CallSiteReference csr = (CallSiteReference) context.get(ContextKey.CALLSITE);
InstanceKey receiver = (InstanceKey) context.get(ContextKey.RECEIVER);
if (caller != null
&& caller
.getMethod()
.getReference()
.getDeclaringClass()
.getClassLoader()
.equals(ClassLoaderReference.Application)) {
node = sbuaMap.get(receiver).getNode(csr, k);
if (node == null) {
continue;
}
addNode(node);
nodeMap.put(k, node);
HashSet<InstanceKey> iks = new HashSet<>();
for (Integer i :
((StringBuilderToStringInstanceKeySite) node).concatenatedInstanceKeys) {
iks.add(pa.getInstanceKeyMapping().getMappedObject(i));
}
unresolvedDependencies.put(node, iks);
// TODO: if this string is created inside the toString function of a string builder,
// find the StringBuilderUseAnalysis for that string builder and call getNode(k) to
// get the node for this instance key
// - this may have to be done in another phase
// NormalAllocationInNode ak = (NormalAllocationInNode)k;
// SSAInstruction inst =
// ak.getNode().getIR().getPEI(ak.getSite());
//
//
// for(int i = 0; i < inst.getNumberOfUses(); i++)
// {
// int use = inst.getUse(i);
// OrdinalSet<InstanceKey> useKeys =
// pa.getPointsToSet(new LocalPointerKey(ak.getNode(), use));
//
// }
//
// for(int i = 0; i < inst.getNumberOfDefs(); i++)
// {
// int def = inst.getDef(i);
// OrdinalSet<InstanceKey> useKeys =
// pa.getPointsToSet(new LocalPointerKey(ak.getNode(), def));
//
// }
}
}
} else if (k instanceof AllocationSite) {
} else {
}
// create an edge for dependencies used in the creation of each instance key
} else {
}
}
for (Entry<InstanceKeySite, Set<InstanceKey>> deps : unresolvedDependencies.entrySet()) {
for (InstanceKey dep : deps.getValue()) {
InstanceKeySite depSite = nodeMap.get(dep);
if (depSite == null) {
throw new IllegalStateException(
"cannot resolve dependency of " + deps.getKey() + " on " + dep);
}
addEdge(depSite, deps.getKey());
}
}
}
@Override
public void removeNodeAndEdges(InstanceKeySite n) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void addNode(InstanceKeySite n) {
predecessors.put(n, new HashSet<>());
successors.put(n, new HashSet<>());
nodes.add(n);
}
@Override
public boolean containsNode(InstanceKeySite n) {
return nodes.contains(n);
}
@Override
public int getNumberOfNodes() {
return nodes.size();
}
@Override
public Iterator<InstanceKeySite> iterator() {
return nodes.iterator();
}
@Override
public Stream<InstanceKeySite> stream() {
return nodes.stream();
}
@Override
public void removeNode(InstanceKeySite n) {
throw new UnsupportedOperationException();
}
@Override
public void addEdge(InstanceKeySite src, InstanceKeySite dst) {
Set<InstanceKeySite> predSet = predecessors.computeIfAbsent(dst, k -> new HashSet<>());
predSet.add(src);
Set<InstanceKeySite> succSet = successors.computeIfAbsent(src, k -> new HashSet<>());
succSet.add(dst);
}
@Override
public int getPredNodeCount(InstanceKeySite n) {
return predecessors.get(n).size();
}
@Override
public Iterator<InstanceKeySite> getPredNodes(InstanceKeySite n) {
return predecessors.get(n).iterator();
}
@Override
public int getSuccNodeCount(InstanceKeySite N) {
return successors.get(N).size();
}
@Override
public Iterator<InstanceKeySite> getSuccNodes(InstanceKeySite n) {
return successors.get(n).iterator();
}
@Override
public boolean hasEdge(InstanceKeySite src, InstanceKeySite dst) {
throw new UnsupportedOperationException();
}
@Override
public void removeAllIncidentEdges(InstanceKeySite node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeEdge(InstanceKeySite src, InstanceKeySite dst)
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeIncomingEdges(InstanceKeySite node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeOutgoingEdges(InstanceKeySite node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
| 10,785
| 36.713287
| 98
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/PrefixVariable.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
import com.ibm.wala.fixpoint.AbstractVariable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
public class PrefixVariable extends AbstractVariable<PrefixVariable> {
// map instance keys to their prefixes
public HashMap<Integer, String> knownPrefixes = new HashMap<>();
public HashSet<Integer> fullPrefixKnown = new HashSet<>();
// TODO: keep track of completely known strings (not just known by prefix)
// HashMap<Integer, String> knownStrings = new HashMap<Integer,String>();
@Override
public void copyState(PrefixVariable v) {
knownPrefixes.clear();
knownPrefixes.putAll(v.knownPrefixes);
fullPrefixKnown.clear();
fullPrefixKnown.addAll(v.fullPrefixKnown);
}
public static String intersect(String one, String two) {
int i = 0;
while (i < one.length() && i < two.length()) {
if (one.charAt(i) != two.charAt(i)) break;
i++;
}
return one.substring(0, i);
}
public String getPrefix(int instance) {
return knownPrefixes.get(instance);
}
public boolean updateAll(PrefixVariable other) {
boolean changed = false;
for (Entry<Integer, String> e : other.knownPrefixes.entrySet()) {
changed = update(e.getKey(), e.getValue()) || changed;
}
for (Integer i : other.fullPrefixKnown) {
changed = include(i) || changed;
}
return changed;
}
public boolean include(Integer i) {
return fullPrefixKnown.add(i);
}
// set an instance key to have a known prefix
public boolean update(Integer instance, String prefix) {
String prevPrefix = knownPrefixes.get(instance);
if (prevPrefix == null) {
knownPrefixes.put(instance, prefix);
} else {
String newPrefix = intersect(prevPrefix, prefix);
if (newPrefix.equals(prevPrefix)) return false;
knownPrefixes.put(instance, newPrefix);
}
return true;
}
@Override
public String toString() {
return knownPrefixes.toString();
}
// set an instance key to be a particular constant
// public boolean setConstant(Integer instance, String prefix)
// {
// return false;
// }
}
| 4,108
| 31.872
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/StringBuilderUseAnalysis.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.callgraph.propagation.ReturnValueKey;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class StringBuilderUseAnalysis {
public final Map<ISSABasicBlock, ISSABasicBlock> blockOrdering;
private final CGNode node;
private final PointerAnalysis<InstanceKey> pa;
private final Set<LocalPointerKey> localPointerKeys = new HashSet<>();
private final List<SSAInstruction> instructions;
public StringBuilderUseAnalysis(final InstanceKey ik, final PointerAnalysis<InstanceKey> pa) {
assert ik.getConcreteType().getName().toString().equals("Ljava/lang/StringBuilder");
this.pa = pa;
this.node = findCGNode(ik, pa);
this.instructions = findInstructions();
final HashSet<ISSABasicBlock> blockSet = new HashSet<>();
for (final SSAInstruction inst : instructions) {
blockSet.add(node.getIR().getBasicBlockForInstruction(inst));
}
// find the ordering for all of the instructions
final BlockSearch blockSearch = new BlockSearch(node.getIR());
final Map<ISSABasicBlock, ISSABasicBlock> blockOrdering = new HashMap<>();
for (final ISSABasicBlock b : blockSet) {
final ISSABasicBlock target = blockSearch.searchFromBlock(b, blockSet);
if (target != null) {
blockOrdering.put(b, target);
}
}
this.blockOrdering = blockOrdering;
}
private CGNode findCGNode(final InstanceKey ik, final PointerAnalysis<InstanceKey> pa) {
CGNode nominatedNode = null;
for (final PointerKey pk : pa.getPointerKeys()) {
if (pk instanceof LocalPointerKey) {
final LocalPointerKey lpk = (LocalPointerKey) pk;
if (!lpk.getNode()
.getMethod()
.getReference()
.getDeclaringClass()
.getClassLoader()
.equals(ClassLoaderReference.Application)) {
continue;
}
for (final InstanceKey k : pa.getPointsToSet(pk)) {
if (k.equals(ik)) {
// make sure it's a local pointer key, and make sure that it's in just one cgnode
localPointerKeys.add(lpk);
if (nominatedNode == null) {
nominatedNode = lpk.getNode();
} else if (nominatedNode != lpk.getNode()) {
return null;
}
}
}
} else if (!(pk instanceof ReturnValueKey)) {
// if this pointer key points to our instance key then we have to give up -- we can only
// analyze local pointer keys
final OrdinalSet<InstanceKey> pts = pa.getPointsToSet(pk);
if (pts.contains(ik)) {
return null;
}
}
}
return nominatedNode;
}
private List<SSAInstruction> findInstructions() {
List<SSAInstruction> instructions = new ArrayList<>();
if (node != null) {
for (SSAInstruction inst : node.getIR().getInstructions()) {
if (inst instanceof SSAInvokeInstruction) {
if (localPointerKeys.contains(new LocalPointerKey(node, inst.getUse(0)))) {
instructions.add(inst);
}
}
}
}
return instructions;
}
public Set<InstanceKey> getDeps() {
return null;
}
public static class StringBuilderToStringInstanceKeySite extends InstanceKeySite {
final ArrayList<Integer> concatenatedInstanceKeys;
final int instanceID;
StringBuilderToStringInstanceKeySite(
final int instanceID, final ArrayList<Integer> concatenatedInstanceKeys) {
this.concatenatedInstanceKeys = concatenatedInstanceKeys;
this.instanceID = instanceID;
}
@Override
public PrefixVariable propagate(final PrefixVariable input) {
// TODO: go through each of the concatenatedInstanceKeys and look up their prefixes in input
// to figure out the prefix of the string generated by toString()
final StringBuilder buf = new StringBuilder();
boolean prefixNew = false;
boolean prefixFull = true;
for (final Integer i : concatenatedInstanceKeys) {
final String prefix = input.getPrefix(i);
if (prefix != null) {
buf.append(prefix);
prefixNew = true;
}
if (!input.fullPrefixKnown.contains(i)) {
prefixFull = false;
break;
}
}
final PrefixVariable retVal = new PrefixVariable();
retVal.copyState(input);
if (prefixNew) {
final String s = buf.toString();
retVal.update(instanceID, s);
if (prefixFull) {
retVal.include(instanceID);
}
}
return retVal;
}
@Override
public String toString() {
return ("StringBuilderToString(instanceID = "
+ instanceID
+ "; concatenatedInstanceKeys = "
+ concatenatedInstanceKeys
+ ')');
}
@Override
public int instanceID() {
return instanceID;
}
}
public InstanceKeySite getNode(final CallSiteReference csr, final InstanceKey k) {
final ISSABasicBlock bbs[] = node.getIR().getBasicBlocksForCall(csr);
final OrdinalSetMapping<InstanceKey> mapping = pa.getInstanceKeyMapping();
final HashSet<ISSABasicBlock> blocksSeen = new HashSet<>();
final ArrayList<Integer> concatenatedInstanceKeys = new ArrayList<>();
ISSABasicBlock bPrev = bbs[0];
ISSABasicBlock bNext = blockOrdering.get(bPrev);
while (bNext != null) {
// detect loops
if (blocksSeen.contains(bNext)) {
return null;
}
blocksSeen.add(bNext);
final SSAInvokeInstruction iNext = (SSAInvokeInstruction) bNext.getLastInstruction();
final MethodReference tgt = iNext.getDeclaredTarget();
if ("append".equals(tgt.getName().toString())) {
final LocalPointerKey lpk = new LocalPointerKey(node, iNext.getUse(1));
for (final InstanceKey ikey : pa.getPointsToSet(lpk)) {
if (isNonNullConstant(ikey)) {
concatenatedInstanceKeys.add(0, mapping.getMappedIndex(ikey));
}
}
} else if (isDefaultConstructor(tgt)) {
final LocalPointerKey lpk = new LocalPointerKey(node, iNext.getUse(1));
for (final InstanceKey ikey : pa.getPointsToSet(lpk)) {
if (isNonNullConstant(ikey)) {
concatenatedInstanceKeys.add(0, mapping.getMappedIndex(ikey));
}
}
return new StringBuilderToStringInstanceKeySite(
mapping.getMappedIndex(k), concatenatedInstanceKeys);
}
bPrev = bNext;
bNext = blockOrdering.get(bNext);
}
return null;
}
private static boolean isDefaultConstructor(final MethodReference mref) {
return "<init>".equals(mref.getName().toString()) && mref.getNumberOfParameters() == 0;
}
private static boolean isNonNullConstant(final InstanceKey ik) {
if (ik instanceof ConstantKey<?>) {
final ConstantKey<?> ck = (ConstantKey<?>) ik;
return !"null".equals(ck.getValue().toString());
}
return false;
}
}
| 9,771
| 32.125424
| 98
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/UriPrefixContextSelector.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.NormalAllocationInNode;
import com.ibm.wala.ipa.callgraph.propagation.ReceiverInstanceContext;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContext;
import com.ibm.wala.ipa.callgraph.propagation.cfa.CallerSiteContextPair;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.util.intset.IntSet;
public class UriPrefixContextSelector extends DefaultContextSelector {
// private final ContextSelector delegate;
public UriPrefixContextSelector(AnalysisOptions options, IClassHierarchy cha) {
super(options, cha);
}
/* TODO: fix receivers[0] references. */
@Override
public Context getCalleeTarget(
CGNode caller, CallSiteReference site, IMethod callee, InstanceKey[] receivers) {
if (callee.getSignature().equals("java.lang.StringBuilder.toString()Ljava/lang/String;")
|| callee
.getSignature()
.equals("java.lang.StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;")
|| callee
.getSignature()
.equals("java.lang.String.valueOf(Ljava/lang/Object;)Ljava/lang/String;")
|| callee.getSignature().equals("java.lang.String.toString()Ljava/lang/String;")
|| callee
.getSignature()
.equals("android.net.Uri.parse(Ljava/lang/String;)Landroid/net/Uri;")
|| callee
.getSignature()
.equals(
"android.net.Uri.withAppendedPath(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;")
||
//
// callee.getSignature().equals("android.net.Uri$StringUri.buildUpon()Landroid/net/Uri$Builder;") ||
//
// callee.getSignature().equals("android.net.Uri$OpaqueUri.buildUpon()Landroid/net/Uri$Builder;") ||
callee.getSignature().equals("android.net.Uri$Builder.build()Landroid/net/Uri;")) {
// System.out.println("Adding context to "+callee.getSignature());
// for (int i = 0; i < receivers.length; i++)
// System.out.println("\t#"+i+" "+receivers[i]);
if (receivers[0] instanceof NormalAllocationInNode) {
// System.out.println("\t\tNormalAllocationInNode "+callee.getSignature());
if (((NormalAllocationInNode) receivers[0])
.getSite()
.getDeclaredType()
.getClassLoader()
.equals(ClassLoaderReference.Application))
// create a context based on the site and the receiver
return new CallerSiteContextPair(caller, site, new ReceiverInstanceContext(receivers[0]));
// if
// (callee.getSignature().equals("android.net.Uri$StringUri.buildUpon()Landroid/net/Uri$Builder;") ||
//
// callee.getSignature().equals("android.net.Uri$OpaqueUri.buildUpon()Landroid/net/Uri$Builder;") ||
//
// callee.getSignature().equals("android.net.Uri$Builder.build()Landroid/net/Uri;"))
// return new CallerSiteContextPair(caller,site,new
// ReceiverInstanceContext(receivers[0]));
if (callee.getSignature().equals("android.net.Uri$Builder.build()Landroid/net/Uri;"))
return new CallerSiteContextPair(caller, site, new ReceiverInstanceContext(receivers[0]));
// return new CallerSiteContext(caller,site);
} else if (callee
.getSignature()
.equals("java.lang.String.valueOf(Ljava/lang/Object;)Ljava/lang/String;")
|| callee.getSignature().equals("java.lang.String.toString()Ljava/lang/String;")
|| callee
.getSignature()
.equals("android.net.Uri.parse(Ljava/lang/String;)Landroid/net/Uri;")
|| callee
.getSignature()
.equals(
"android.net.Uri.withAppendedPath(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;")) {
return new CallerSiteContext(caller, site);
}
} else // if(callee.getSignature().contains("value"))
{
// System.out.println("Found signature: "+callee.getSignature());
}
if (!caller.getContext().equals(Everywhere.EVERYWHERE)) {
// System.out.println("Call to "+callee+" from caller "+caller+" in context
// "+caller.getContext());
}
return super.getCalleeTarget(caller, site, callee, receivers);
}
@Override
public IntSet getRelevantParameters(CGNode node, CallSiteReference call) {
return super.getRelevantParameters(node, call);
}
}
| 6,936
| 44.940397
| 110
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/UriPrefixTransferGraph.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer;
import com.ibm.wala.analysis.reflection.InstanceKeyWithNode;
import com.ibm.wala.classLoader.CallSiteReference;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.Context;
import com.ibm.wala.ipa.callgraph.ContextKey;
import com.ibm.wala.ipa.callgraph.propagation.AllocationSiteInNode;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.NormalAllocationInNode;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.intset.OrdinalSet;
import com.ibm.wala.util.intset.OrdinalSetMapping;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Stream;
import org.scandroid.prefixtransfer.StringBuilderUseAnalysis.StringBuilderToStringInstanceKeySite;
import org.scandroid.prefixtransfer.modeledAllocations.ConstantString;
import org.scandroid.prefixtransfer.modeledAllocations.UriAppendString;
import org.scandroid.prefixtransfer.modeledAllocations.UriParseString;
public class UriPrefixTransferGraph implements Graph<InstanceKeySite> {
public final Map<InstanceKey, InstanceKeySite> nodeMap = new HashMap<>();
public final Map<InstanceKey, StringBuilderUseAnalysis> sbuaMap = new HashMap<>();
private final List<InstanceKeySite> nodes = new ArrayList<>();
private final Map<InstanceKeySite, Set<InstanceKeySite>> successors = new HashMap<>();
private final Map<InstanceKeySite, Set<InstanceKeySite>> predecessors = new HashMap<>();
public UriPrefixTransferGraph(final PointerAnalysis<InstanceKey> pa) {
final Map<InstanceKeySite, Set<InstanceKey>> unresolvedDependencies = new HashMap<>();
final OrdinalSetMapping<InstanceKey> mapping = pa.getInstanceKeyMapping();
final Collection<InstanceKey> instanceKeys = pa.getInstanceKeys();
for (final InstanceKey k : instanceKeys) {
handleStringBuilder(k, pa);
}
for (final InstanceKey k : instanceKeys) {
handleString(k, mapping, unresolvedDependencies);
}
for (final PointerKey pk : pa.getPointerKeys()) {
if (pk instanceof LocalPointerKey) {
final LocalPointerKey lpk = (LocalPointerKey) pk;
handleUriWitAppendPath(lpk, pa, mapping, unresolvedDependencies);
}
}
for (final InstanceKey ik : instanceKeys) {
if (ik instanceof NormalAllocationInNode) {
final NormalAllocationInNode naik = (NormalAllocationInNode) ik;
handleUriParse(naik, pa, mapping, unresolvedDependencies);
handleUriWitAppendPath(naik, pa, mapping, unresolvedDependencies);
}
}
for (final Entry<InstanceKeySite, Set<InstanceKey>> deps : unresolvedDependencies.entrySet()) {
for (final InstanceKey dep : deps.getValue()) {
final InstanceKeySite depSite = nodeMap.get(dep);
if (depSite != null) {
addEdge(depSite, deps.getKey());
}
}
}
}
private void handleString(
final InstanceKey ik,
final OrdinalSetMapping<InstanceKey> mapping,
final Map<InstanceKeySite, Set<InstanceKey>> unresolvedDependencies) {
if (isOfType(ik, "Ljava/lang/String")) {
if (ik instanceof ConstantKey) {
final String value = (String) ((ConstantKey<?>) ik).getValue();
final InstanceKeySite node = new ConstantString(mapping.getMappedIndex(ik), value);
addNode(node);
nodeMap.put(ik, node);
} else if (ik instanceof NormalAllocationInNode) {
final NormalAllocationInNode nain = (NormalAllocationInNode) ik;
handleStringBuilderToString(nain, mapping, unresolvedDependencies);
}
}
}
private void handleStringBuilder(final InstanceKey ik, final PointerAnalysis<InstanceKey> pa) {
if (isOfType(ik, "Ljava/lang/StringBuilder")) {
if (ik instanceof AllocationSiteInNode) {
final AllocationSiteInNode as = (AllocationSiteInNode) ik;
if (isApplicationCode(as.getSite().getDeclaredType())) {
final StringBuilderUseAnalysis sbua;
try {
sbua = new StringBuilderUseAnalysis(ik, pa);
} catch (Exception e) {
return;
}
sbuaMap.put(ik, sbua); // map ik to sbua in some global map
}
}
}
}
private void handleStringBuilderToString(
final NormalAllocationInNode nain,
final OrdinalSetMapping<InstanceKey> mapping,
final Map<InstanceKeySite, Set<InstanceKey>> unresolvedDependencies) {
if (hasSignature(nain, "java.lang.StringBuilder.toString()Ljava/lang/String;")) {
final Context context = nain.getNode().getContext();
final CGNode caller = (CGNode) context.get(ContextKey.CALLER);
if (caller != null && isApplicationCode(caller.getMethod())) {
final InstanceKey receiver = (InstanceKey) context.get(ContextKey.RECEIVER);
if (sbuaMap.get(receiver) != null) {
final CallSiteReference csr = (CallSiteReference) context.get(ContextKey.CALLSITE);
final InstanceKeySite node = sbuaMap.get(receiver).getNode(csr, nain);
if (node != null) {
addNode(node);
nodeMap.put(nain, node);
final StringBuilderToStringInstanceKeySite s2si =
(StringBuilderToStringInstanceKeySite) node;
final HashSet<InstanceKey> iks = new HashSet<>();
for (final Integer i : s2si.concatenatedInstanceKeys) {
iks.add(mapping.getMappedObject(i));
}
unresolvedDependencies.put(node, iks);
// TODO: if this string is created inside the toString function of a string builder,
// find the StringBuilderUseAnalysis for that string builder and call getNode(k) to
// get the node for this instance key
// - this may have to be done in another phase
}
}
}
}
}
private void handleUriWitAppendPath(
final LocalPointerKey lpk,
final PointerAnalysis<InstanceKey> pa,
final OrdinalSetMapping<InstanceKey> mapping,
final Map<InstanceKeySite, Set<InstanceKey>> unresolvedDependencies) {
final Context context = lpk.getNode().getContext();
final CGNode caller = (CGNode) context.get(ContextKey.CALLER);
if (caller != null
&& isApplicationCode(caller.getMethod())
&& hasSignature(
lpk,
"android.net.Uri.withAppendedPath(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;")) {
final CallSiteReference csr = (CallSiteReference) context.get(ContextKey.CALLSITE);
final SSAInvokeInstruction invoke =
(SSAInvokeInstruction) caller.getIR().getBasicBlocksForCall(csr)[0].getLastInstruction();
final OrdinalSet<InstanceKey> ptsUri =
pa.getPointsToSet(new LocalPointerKey(caller, invoke.getUse(0)));
if (!ptsUri.isEmpty()) {
final InstanceKey uriKey = ptsUri.iterator().next();
final OrdinalSet<InstanceKey> points =
pa.getPointsToSet(new LocalPointerKey(caller, invoke.getUse(1)));
if (!points.isEmpty()) {
final InstanceKey stringKey = points.iterator().next();
final OrdinalSet<InstanceKey> returnSet =
pa.getPointsToSet(new LocalPointerKey(caller, invoke.getReturnValue(0)));
for (InstanceKey returnIK : returnSet) {
final UriAppendString node =
new UriAppendString(
mapping.getMappedIndex(returnIK),
mapping.getMappedIndex(uriKey),
mapping.getMappedIndex(stringKey));
if (!nodeMap.containsKey(returnIK)) {
addNode(node);
nodeMap.put(returnIK, node);
final HashSet<InstanceKey> iks = new HashSet<>();
iks.add(uriKey);
iks.add(stringKey);
unresolvedDependencies.put(node, iks);
}
}
}
}
}
}
private void handleUriWitAppendPath(
final NormalAllocationInNode ik,
final PointerAnalysis<InstanceKey> pa,
final OrdinalSetMapping<InstanceKey> mapping,
final Map<InstanceKeySite, Set<InstanceKey>> unresolvedDependencies) {
final CGNode allocNode = ik.getNode();
final Context context = allocNode.getContext();
final CGNode caller = (CGNode) context.get(ContextKey.CALLER);
if (hasSignature(
allocNode,
"android.net.Uri.withAppendedPath(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;")) {
// Doesn't seem to be entering this else with the current android jar -- reimplemented above
// using LocalPointerKey
final CallSiteReference csr = (CallSiteReference) context.get(ContextKey.CALLSITE);
final SSAInvokeInstruction invoke =
(SSAInvokeInstruction) caller.getIR().getBasicBlocksForCall(csr)[0].getLastInstruction();
final OrdinalSet<InstanceKey> ptsUri =
pa.getPointsToSet(new LocalPointerKey(caller, invoke.getUse(0)));
if (!ptsUri.isEmpty()) {
final InstanceKey uriKey = ptsUri.iterator().next();
final OrdinalSet<InstanceKey> points =
pa.getPointsToSet(new LocalPointerKey(caller, invoke.getUse(1)));
if (!points.isEmpty()) {
final InstanceKey stringKey = points.iterator().next();
final UriAppendString node =
new UriAppendString(
mapping.getMappedIndex(ik),
mapping.getMappedIndex(uriKey),
mapping.getMappedIndex(stringKey));
addNode(node);
nodeMap.put(ik, node);
final HashSet<InstanceKey> iks = new HashSet<>();
iks.add(uriKey);
iks.add(stringKey);
unresolvedDependencies.put(node, iks);
}
}
}
}
private void handleUriParse(
final NormalAllocationInNode ik,
final PointerAnalysis<InstanceKey> pa,
final OrdinalSetMapping<InstanceKey> mapping,
final Map<InstanceKeySite, Set<InstanceKey>> unresolvedDependencies) {
final CGNode allocNode = ik.getNode();
final Context context = allocNode.getContext();
final CGNode caller = (CGNode) context.get(ContextKey.CALLER);
if (hasSignature(allocNode, "android.net.Uri.parse(Ljava/lang/String;)Landroid/net/Uri;")) {
final CallSiteReference csr = (CallSiteReference) context.get(ContextKey.CALLSITE);
final SSAInvokeInstruction invoke =
(SSAInvokeInstruction) caller.getIR().getBasicBlocksForCall(csr)[0].getLastInstruction();
final OrdinalSet<InstanceKey> points =
pa.getPointsToSet(new LocalPointerKey(caller, invoke.getUse(0)));
if (!points.isEmpty()) {
final InstanceKey stringKey = points.iterator().next();
final UriParseString node =
new UriParseString(mapping.getMappedIndex(ik), mapping.getMappedIndex(stringKey));
addNode(node);
nodeMap.put(ik, node);
final Set<InstanceKey> iks = Collections.singleton(stringKey);
unresolvedDependencies.put(node, iks);
}
}
}
@Override
public void removeNodeAndEdges(InstanceKeySite n) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void addNode(final InstanceKeySite n) {
predecessors.put(n, new HashSet<>());
successors.put(n, new HashSet<>());
nodes.add(n);
}
@Override
public boolean containsNode(final InstanceKeySite n) {
return nodes.contains(n);
}
@Override
public int getNumberOfNodes() {
return nodes.size();
}
@Override
public Iterator<InstanceKeySite> iterator() {
return nodes.iterator();
}
@Override
public Stream<InstanceKeySite> stream() {
return nodes.stream();
}
@Override
public void removeNode(final InstanceKeySite n) {
throw new UnsupportedOperationException();
}
@Override
public void addEdge(final InstanceKeySite src, final InstanceKeySite dst) {
Set<InstanceKeySite> predSet = predecessors.computeIfAbsent(dst, k -> new HashSet<>());
predSet.add(src);
Set<InstanceKeySite> succSet = successors.computeIfAbsent(src, k -> new HashSet<>());
succSet.add(dst);
}
@Override
public int getPredNodeCount(final InstanceKeySite n) {
return predecessors.get(n).size();
}
@Override
public Iterator<InstanceKeySite> getPredNodes(InstanceKeySite n) {
return predecessors.get(n).iterator();
}
@Override
public int getSuccNodeCount(InstanceKeySite N) {
return successors.get(N).size();
}
@Override
public Iterator<InstanceKeySite> getSuccNodes(InstanceKeySite n) {
return successors.get(n).iterator();
}
@Override
public boolean hasEdge(InstanceKeySite src, InstanceKeySite dst) {
throw new UnsupportedOperationException();
}
@Override
public void removeAllIncidentEdges(InstanceKeySite node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeEdge(InstanceKeySite src, InstanceKeySite dst)
throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeIncomingEdges(InstanceKeySite node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public void removeOutgoingEdges(InstanceKeySite node) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
private static boolean isApplicationCode(final IMethod im) {
return isApplicationCode(im.getReference());
}
private static boolean isApplicationCode(final MethodReference mref) {
return isApplicationCode(mref.getDeclaringClass());
}
private static boolean isApplicationCode(final TypeReference tref) {
return tref.getClassLoader().equals(ClassLoaderReference.Application);
}
private static boolean isOfType(final InstanceKey ik, final String typeName) {
return typeName.equals(ik.getConcreteType().getName().toString());
}
private static boolean hasSignature(final CGNode n, final String signature) {
return hasSignature(n.getMethod(), signature);
}
private static boolean hasSignature(final IMethod im, final String signature) {
return signature.equals(im.getSignature());
}
private static boolean hasSignature(final LocalPointerKey pk, final String signature) {
return hasSignature(pk.getNode(), signature);
}
private static boolean hasSignature(final InstanceKeyWithNode ik, final String signature) {
return hasSignature(ik.getNode(), signature);
}
}
| 17,163
| 36.475983
| 104
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/modeledAllocations/ConstantString.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer.modeledAllocations;
import org.scandroid.prefixtransfer.InstanceKeySite;
import org.scandroid.prefixtransfer.PrefixVariable;
public class ConstantString extends InstanceKeySite {
final String constantValue;
final int instanceID;
public ConstantString(int instanceID, String constantValue) {
this.constantValue = constantValue;
this.instanceID = instanceID;
}
@Override
public PrefixVariable propagate(PrefixVariable input) {
// System.out.println("Propagating at: " + instanceID + " (" + constantValue + ")");
PrefixVariable retVal = new PrefixVariable();
retVal.update(instanceID, constantValue);
retVal.include(instanceID);
return retVal;
}
@Override
public String toString() {
return ("ConstantString(instanceID = " + instanceID + "; value = " + constantValue + ')');
}
@Override
public int instanceID() {
return instanceID;
}
}
| 2,879
| 34.121951
| 94
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/modeledAllocations/StringToLower.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer.modeledAllocations;
import java.util.Set;
import org.scandroid.prefixtransfer.InstanceKeySite;
import org.scandroid.prefixtransfer.PrefixVariable;
public class StringToLower extends InstanceKeySite {
private final int instanceID;
private final Set<Integer> dependencies;
public StringToLower(int instanceID, Set<Integer> dependencies) {
this.instanceID = instanceID;
this.dependencies = dependencies;
}
@Override
public PrefixVariable propagate(PrefixVariable input) {
// TODO Auto-generated method stub
PrefixVariable retVal = new PrefixVariable();
String prefix = null;
for (Integer dep : dependencies) {
String depPrefix = input.getPrefix(dep);
// if any of the dependencies are unknown, then this prefix is also unknown
if (depPrefix == null) return retVal;
depPrefix = depPrefix.toLowerCase();
if (prefix == null) prefix = depPrefix;
else prefix = PrefixVariable.intersect(prefix, depPrefix);
}
retVal.update(instanceID, prefix);
return retVal;
}
@Override
public int instanceID() {
return instanceID;
}
}
| 3,086
| 34.895349
| 81
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/modeledAllocations/UriAppendString.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer.modeledAllocations;
import org.scandroid.prefixtransfer.InstanceKeySite;
import org.scandroid.prefixtransfer.PrefixVariable;
public class UriAppendString extends InstanceKeySite {
final int uriInstanceID;
final int stringInstanceID;
final int instanceID;
public UriAppendString(int instanceID, int uriInstanceID, int stringInstanceID) {
this.uriInstanceID = uriInstanceID;
this.stringInstanceID = stringInstanceID;
this.instanceID = instanceID;
}
@Override
public PrefixVariable propagate(PrefixVariable input) {
// System.out.println("Propagating at: " + instanceID + " (" + constantValue + ")");
PrefixVariable retVal = new PrefixVariable();
retVal.copyState(input);
String prefix = input.getPrefix(uriInstanceID);
if (input.fullPrefixKnown.contains(uriInstanceID)) {
retVal.update(instanceID, prefix + '/' + input.getPrefix(stringInstanceID));
if (input.fullPrefixKnown.contains(stringInstanceID)) retVal.include(instanceID);
} else retVal.update(instanceID, prefix);
return retVal;
}
@Override
public String toString() {
return ("UriAppendString(instanceID = "
+ instanceID
+ "; uriInstanceID = "
+ uriInstanceID
+ "; stringInstanceID = "
+ stringInstanceID
+ ')');
}
@Override
public int instanceID() {
return instanceID;
}
}
| 3,352
| 34.670213
| 93
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/prefixtransfer/modeledAllocations/UriParseString.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Adam Fuchs <afuchs@cs.umd.edu>
* Avik Chaudhuri <avik@cs.umd.edu>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.prefixtransfer.modeledAllocations;
import org.scandroid.prefixtransfer.InstanceKeySite;
import org.scandroid.prefixtransfer.PrefixVariable;
public class UriParseString extends InstanceKeySite {
final int stringInstanceID;
final int instanceID;
public UriParseString(int instanceID, int stringInstanceID) {
this.stringInstanceID = stringInstanceID;
this.instanceID = instanceID;
}
@Override
public PrefixVariable propagate(PrefixVariable input) {
// System.out.println("Propagating at: " + instanceID + " (" + constantValue + ")");
PrefixVariable retVal = new PrefixVariable();
retVal.copyState(input);
String prefix = input.getPrefix(stringInstanceID);
retVal.update(instanceID, prefix);
if (input.fullPrefixKnown.contains(stringInstanceID)) retVal.include(instanceID);
return retVal;
}
@Override
public String toString() {
return ("UriParseString(instanceID = "
+ instanceID
+ "; stringInstanceID = "
+ stringInstanceID
+ ')');
}
@Override
public int instanceID() {
return instanceID;
}
}
| 3,062
| 33.806818
| 93
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/AndroidSpecs.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.types.ClassLoaderReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.scandroid.util.LoaderUtils;
public class AndroidSpecs implements ISpecs {
// private AppModelMethod appEntrySummary;
static String act = "Landroid/app/Activity";
static String svc = "Landroid/app/Service";
static String prv = "Landroid/content/ContentProvider";
static String rslv = "Landroid/content/ContentResolver";
static String ctx = "Landroid/content/Context";
static String http = "Landroid/net/AndroidHttpClient";
static String bnd = "Landroid/os/IBinder";
static String lm = "Landroid/location/LocationManager";
static String tm = "Landroid/telephony/TelephonyManager";
static String sms = "android/telephony/SmsManager";
static String smsGsm = "android/telephony/gsm/SmsManager";
static String ll = "Landroid/location/LocationListener";
static String gl = "Landroid/location/GpsStatus$Listener";
static String nl = "Landroid/location/GpsStatus$NmeaListener";
static MethodNamePattern actCreate = new MethodNamePattern(act, "onCreate");
static MethodNamePattern actStart = new MethodNamePattern(act, "onStart");
static MethodNamePattern actResume = new MethodNamePattern(act, "onResume");
static MethodNamePattern actStop = new MethodNamePattern(act, "onStop");
static MethodNamePattern actRestart = new MethodNamePattern(act, "onRestart");
static MethodNamePattern actDestroy = new MethodNamePattern(act, "onDestroy");
static MethodNamePattern actOnActivityResult = new MethodNamePattern(act, "onActivityResult");
static MethodNamePattern actOnRestoreInstanceState =
new MethodNamePattern(act, "onRestoreInstanceState");
static MethodNamePattern actOnSaveInstanceState =
new MethodNamePattern(act, "onSaveInstanceState");
static MethodNamePattern actSetResult = new MethodNamePattern(act, "setResult");
static MethodNamePattern actGetIntent = new MethodNamePattern(act, "getIntent");
static MethodNamePattern actStartActivityForResult =
new MethodNamePattern(act, "startActivityForResult");
static MethodNamePattern actStartActivityIfNeeded =
new MethodNamePattern(act, "startActivityIfNeeded");
static MethodNamePattern actStartNextMatchingActivity =
new MethodNamePattern(act, "startNextMatchingActivity");
static MethodNamePattern actStartActivityFromChild =
new MethodNamePattern(act, "startActivityFromChild");
static MethodNamePattern svcCreate = new MethodNamePattern(svc, "onCreate");
static MethodNamePattern svcStart = new MethodNamePattern(svc, "onStart");
static MethodNamePattern svcStartCommand = new MethodNamePattern(svc, "onStartCommand");
static MethodNamePattern svcBind = new MethodNamePattern(svc, "onBind");
static MethodNamePattern rslvQuery = new MethodNamePattern(rslv, "query");
static MethodNamePattern rslvInsert = new MethodNamePattern(rslv, "insert");
static MethodNamePattern rslvUpdate = new MethodNamePattern(rslv, "update");
static MethodNamePattern prvCreate = new MethodNamePattern(prv, "onCreate");
static MethodNamePattern prvQuery = new MethodNamePattern(prv, "query");
static MethodNamePattern prvInsert = new MethodNamePattern(prv, "insert");
static MethodNamePattern prvUpdate = new MethodNamePattern(prv, "update");
static MethodNamePattern ctxStartActivity = new MethodNamePattern(ctx, "startActivity");
static MethodNamePattern ctxStartService = new MethodNamePattern(ctx, "startService");
static MethodNamePattern ctxBindService = new MethodNamePattern(ctx, "bindService");
static MethodNamePattern bndTransact = new MethodNamePattern(bnd, "transact");
static MethodNamePattern bndOnTransact = new MethodNamePattern(bnd, "onTransact");
static MethodNamePattern httpExecute = new MethodNamePattern(http, "execute");
// private static MethodNamePattern[] callbackModelEntry = {
// new MethodNamePattern("Lcom/SCanDroid/AppModel", "entry")
// };
static MethodNamePattern llLocChanged = new MethodNamePattern(ll, "onLocationChanged");
static MethodNamePattern llProvDisabled = new MethodNamePattern(ll, "onProviderDisabled");
static MethodNamePattern llProvEnabled = new MethodNamePattern(ll, "onProviderEnabled");
static MethodNamePattern llStatusChanged = new MethodNamePattern(ll, "onStatusChanged");
static MethodNamePattern glStatusChanged = new MethodNamePattern(gl, "onGpsStatusChanged");
static MethodNamePattern nlNmeaRecvd = new MethodNamePattern(nl, "onNmeaReceived");
private static final MethodNamePattern[] defaultCallbacks = {
actCreate,
actStart,
actResume,
actStop,
actRestart,
actDestroy,
actOnActivityResult,
svcCreate,
svcStart,
svcStartCommand,
svcBind,
// svcTransact,
prvCreate,
prvQuery,
prvInsert,
prvUpdate,
llLocChanged,
llProvDisabled,
llProvEnabled,
llStatusChanged,
glStatusChanged,
nlNmeaRecvd,
};
@Override
public MethodNamePattern[] getEntrypointSpecs() {
return defaultCallbacks;
}
private static final SourceSpec[] sourceSpecs = {
// new EntryArgSourceSpec( actCreate, null ),
// doesn't have any parameters
// new EntryArgSourceSpec( actStart, null ),
// new EntryArgSourceSpec( actResume, null ),
// new EntryArgSourceSpec( actStop, null ),
// new EntryArgSourceSpec( actRestart, null ),
// new EntryArgSourceSpec( actDestroy, null ),
// track all parameters? or just the Intent data(3)
new EntryArgSourceSpec(actOnActivityResult, new int[] {3}),
// new EntryArgSourceSpec( actOnRestoreInstanceState, null ),
// new EntryArgSourceSpec( actOnSaveInstanceState, null ),
// new EntryArgSourceSpec( svcCreate, null ),
new EntryArgSourceSpec(svcStart, new int[] {1}),
new EntryArgSourceSpec(svcStartCommand, new int[] {1}),
new EntryArgSourceSpec(svcBind, new int[] {1}),
new EntryArgSourceSpec(bndOnTransact, new int[] {2}),
new EntryArgSourceSpec(llLocChanged, null),
new EntryArgSourceSpec(llProvDisabled, null),
new EntryArgSourceSpec(llProvEnabled, null),
new EntryArgSourceSpec(llStatusChanged, null),
new EntryArgSourceSpec(glStatusChanged, null),
new EntryArgSourceSpec(nlNmeaRecvd, null),
// doesn't exist
// new EntryArgSourceSpec( svcTransact, null ),
// no parameters
// new EntryArgSourceSpec( prvCreate, null ),
// new CallArgSourceSpec( prvQuery, new int[] { 2, 3, 4, 5 }, SourceType.PROVIDER_SOURCE),
// new CallArgSourceSpec( prvInsert, new int[] { 2 }, SourceType.PROVIDER_SOURCE),
// new CallArgSourceSpec( prvUpdate, new int[] { 2, 3, 4 }, SourceType.PROVIDER_SOURCE),
new CallArgSourceSpec(bndTransact, new int[] {3}),
new CallRetSourceSpec(rslvQuery, new int[] {}),
// new CallRetSourceSpec(httpExecute, new int[] {}),
new CallRetSourceSpec(actGetIntent, new int[] {}),
// new CallRetSourceSpec(new MethodNamePattern("LTest/Apps/GenericSource", "getIntSource"), new
// int[]{}),
new CallRetSourceSpec(
new MethodNamePattern("LTest/Apps/GenericSource", "getStringSource"), new int[] {}),
new CallRetSourceSpec(new MethodNamePattern(lm, "getProviders"), null),
new CallRetSourceSpec(new MethodNamePattern(lm, "getProvider"), null),
new CallRetSourceSpec(new MethodNamePattern(lm, "getLastKnownLocation"), null),
new CallRetSourceSpec(new MethodNamePattern(lm, "isProviderEnabled"), null),
new CallRetSourceSpec(new MethodNamePattern(lm, "getBestProvider"), null),
new CallRetSourceSpec(new MethodNamePattern(tm, "getNeighboringCellInfo"), null),
new CallRetSourceSpec(new MethodNamePattern(tm, "getCellLocation"), null),
};
@Override
public SourceSpec[] getSourceSpecs() {
return sourceSpecs;
}
/** TODO: document! */
private static final SinkSpec[] sinkSpecs = {
new CallArgSinkSpec(actSetResult, new int[] {2}),
// new CallArgSinkSpec(bndTransact, new int[] { 2 }),
new CallArgSinkSpec(rslvQuery, new int[] {2, 3, 4, 5}),
new CallArgSinkSpec(rslvInsert, new int[] {2}),
// new CallArgSinkSpec(rslvUpdate, new int[] { 2, 3, 4 }),
new CallArgSinkSpec(ctxBindService, new int[] {1}),
new CallArgSinkSpec(ctxStartService, new int[] {1}),
new CallArgSinkSpec(ctxStartActivity, new int[] {1}),
new CallArgSinkSpec(actStartActivityForResult, new int[] {1}),
new CallArgSinkSpec(actStartActivityIfNeeded, new int[] {1}),
new CallArgSinkSpec(actStartNextMatchingActivity, new int[] {1}),
new CallArgSinkSpec(actStartActivityFromChild, new int[] {2}),
new EntryArgSinkSpec(bndOnTransact, new int[] {3}),
// new EntryArgSinkSpec( actOnActivityResult, new int[] { 2 } ),
// new EntryArgSinkSpec( actOnSaveInstanceState, new int[] { 0 } ),
// new EntryRetSinkSpec(prvQuery),
new CallArgSinkSpec(new MethodNamePattern("LTest/Apps/GenericSink", "setSink"), new int[] {1}),
new CallArgSinkSpec(new MethodNamePattern(smsGsm, "sendTextMessage"), null),
new CallArgSinkSpec(new MethodNamePattern(sms, "sendMultipartTextMessage"), null),
new CallArgSinkSpec(new MethodNamePattern(smsGsm, "sendDataMessage"), null),
new CallArgSinkSpec(new MethodNamePattern(sms, "sendTextMessage"), null),
new CallArgSinkSpec(new MethodNamePattern(smsGsm, "sendMultipartTextMessage"), null),
new CallArgSinkSpec(new MethodNamePattern(sms, "sendDataMessage"), null),
};
@Override
public SinkSpec[] getSinkSpecs() {
return sinkSpecs;
}
private static MethodNamePattern[] callBacks = new MethodNamePattern[] {};
// public MethodNamePattern[] getCallBacks() {
// if (callBacks == null)
// callBacks = new MethodNamePattern[] {};
// return callBacks;
// }
public void addPossibleListeners(ClassHierarchy cha) {
Set<String> ignoreMethods = new HashSet<>();
ignoreMethods.add("<init>");
ignoreMethods.add("<clinit>");
ignoreMethods.add("registerNatives");
ignoreMethods.add("getClass");
ignoreMethods.add("hashCode");
ignoreMethods.add("equals");
ignoreMethods.add("clone");
ignoreMethods.add("toString");
ignoreMethods.add("notify");
ignoreMethods.add("notifyAll");
ignoreMethods.add("finalize");
ignoreMethods.add("wait");
// add default entrypoints from AndroidSpecs.entrypointSpecs
// Currently adds methods even if they exist in the ignnoreMethods
// set.
List<MethodNamePattern> moreEntryPointSpecs = new ArrayList<>(Arrays.asList(defaultCallbacks));
for (IClass ic : cha) {
if (!LoaderUtils.fromLoader(ic, ClassLoaderReference.Application)) {
continue;
}
// finds all *Listener classes and fetches all methods for the listener
if (ic.getName().getClassName().toString().endsWith("Listener")) {
for (IMethod im : ic.getAllMethods()) {
// TODO: add isAbstract()?
if (!ignoreMethods.contains(im.getName().toString()) && !im.isPrivate()) {
moreEntryPointSpecs.add(
new MethodNamePattern(ic.getName().toString(), im.getName().toString()));
}
}
}
// not a listener, just find all the methods that start with "on____"
else {
for (IMethod im : ic.getAllMethods()) {
// TODO: add isAbstract()?
if (!ignoreMethods.contains(im.getName().toString())
&& im.getName().toString().startsWith("on")
&& !im.isPrivate()) {
moreEntryPointSpecs.add(
new MethodNamePattern(ic.getName().toString(), im.getName().toString()));
}
}
}
}
// entrypointSpecs =
callBacks = moreEntryPointSpecs.toArray(new MethodNamePattern[0]);
}
public MethodNamePattern[] getCallBacks() {
return callBacks;
}
// public void setEntrySummary(AppModelMethod amm) {
// this.appEntrySummary = amm;
// }
// public AppModelMethod getEntrySummary() {
// return appEntrySummary;
// }
}
| 14,148
| 41.362275
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/CallArgSinkSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.ParameterFlow;
public class CallArgSinkSpec extends SinkSpec {
public CallArgSinkSpec(MethodNamePattern name, int[] args) {
namePattern = name;
argNums = args;
}
@Override
public <E extends ISSABasicBlock> Collection<FlowType<E>> getFlowType(
BasicBlockInContext<E> block) {
HashSet<FlowType<E>> flowSet = new HashSet<>();
if (argNums == null) {
SSAInvokeInstruction i = (SSAInvokeInstruction) block.getLastInstruction();
argNums = new int[i.getDeclaredTarget().getNumberOfParameters()];
Arrays.setAll(argNums, p -> p);
}
for (int arg : argNums) {
flowSet.add(new ParameterFlow<>(block, arg, false));
}
return flowSet;
}
@Override
public String toString() {
return String.format(
"CallArgSinkSpec(%s,%s)", namePattern.getDescriptor(), Arrays.toString(argNums));
}
}
| 3,123
| 34.5
| 89
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/CallArgSourceSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
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.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.InstanceKeyElement;
import org.scandroid.flow.InflowAnalysis;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.ParameterFlow;
import org.scandroid.util.CGAnalysisContext;
/**
* CallArgSourceSpecs represent sources that are arguments to another function.
*
* <p>For example, if code you analyze invokes a function {@code foo(Object obj)} and foo
* <em>writes</em> to the argument, then {@code obj} would be a source.
*/
public class CallArgSourceSpec extends SourceSpec {
final String name = "CallArgSource";
public CallArgSourceSpec(MethodNamePattern name, int[] args) {
namePattern = name;
argNums = args;
}
@Override
public <E extends ISSABasicBlock> void addDomainElements(
CGAnalysisContext<E> ctx,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
IMethod target,
BasicBlockInContext<E> block,
SSAInvokeInstruction invInst,
int[] newArgNums,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa,
CallGraph cg) {
for (int newArgNum : newArgNums) {
for (FlowType<E> ft : getFlowType(block)) {
// a collection of a LocalElement for this argument's SSA value,
// along with a set of InstanceKeyElements for each instance
// that this SSA value might point to
final int ssaVal = invInst.getUse(newArgNum);
final CGNode node = block.getNode();
Set<CodeElement> valueElements = CodeElement.valueElements(ssaVal);
PointerKey pk = pa.getHeapModel().getPointerKeyForLocal(node, ssaVal);
for (InstanceKey ik : pa.getPointsToSet(pk)) {
valueElements.add(new InstanceKeyElement(ik));
}
InflowAnalysis.addDomainElements(taintMap, block, ft, valueElements);
}
}
}
public <E extends ISSABasicBlock> Collection<FlowType<E>> getFlowType(
BasicBlockInContext<E> block) {
HashSet<FlowType<E>> flowSet = HashSetFactory.make();
for (int i : argNums) {
flowSet.add(new ParameterFlow<>(block, i, true));
}
return flowSet;
}
@Override
public String toString() {
return String.format("CallArgSourceSpec(%s, %s)", namePattern, Arrays.toString(argNums));
}
}
| 4,962
| 36.885496
| 93
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/CallRetSourceSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.flow.InflowAnalysis;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.ReturnFlow;
import org.scandroid.util.CGAnalysisContext;
/**
* CallRetSourceSpecs represent sources from invocations of other methods (eg: API methods).
*
* <p>reading file contents, and returning bytes eg: via {@code int read(...)} is an example of a
* call return source.
*/
public class CallRetSourceSpec extends SourceSpec {
final String sig = "CallRetSource";
public CallRetSourceSpec(MethodNamePattern name, int[] args) {
namePattern = name;
argNums = args;
}
@Override
public <E extends ISSABasicBlock> void addDomainElements(
CGAnalysisContext<E> ctx,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
IMethod im,
BasicBlockInContext<E> block,
SSAInvokeInstruction invInst,
int[] newArgNums,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa,
CallGraph cg) {
for (FlowType<E> ft : getFlowType(block)) {
InflowAnalysis.addDomainElements(
taintMap, block, ft, CodeElement.valueElements(invInst.getDef(0)));
}
}
private static <E extends ISSABasicBlock> Collection<FlowType<E>> getFlowType(
BasicBlockInContext<E> block) {
return Collections.singleton(new ReturnFlow<>(block, true));
}
@Override
public String toString() {
return String.format("CallRetSourceSpec(%s)", namePattern);
}
}
| 4,048
| 35.151786
| 97
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/EntryArgSinkSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.ParameterFlow;
public class EntryArgSinkSpec extends SinkSpec {
/**
* @param name of the method
* @param args to be tainted. These are zero-based; zero refers to `this` for a non-static method,
* or the first parameter of a static method
*/
public EntryArgSinkSpec(MethodNamePattern name, int[] args) {
namePattern = name;
argNums = args;
}
@Override
public <E extends ISSABasicBlock> Collection<FlowType<E>> getFlowType(
BasicBlockInContext<E> block) {
return Arrays.stream(argNums)
.mapToObj(i -> new ParameterFlow<>(block, i, false))
.collect(Collectors.toSet());
}
@Override
public String toString() {
return String.format(
"EntryArgSinkSpec(%s,%s)", namePattern.getDescriptor(), Arrays.toString(argNums));
}
}
| 3,026
| 34.611765
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/EntryArgSourceSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey;
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.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.intset.OrdinalSet;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.flow.InflowAnalysis;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.ParameterFlow;
import org.scandroid.util.CGAnalysisContext;
/**
* Entry arg source specs represent sources that are arguments to methods that are entry points.
*
* <p>For example, the command line arguments to a {@code main(String[] args)} are entry arg
* sources.
*/
public class EntryArgSourceSpec extends SourceSpec {
public EntryArgSourceSpec(MethodNamePattern name, int[] args) {
namePattern = name;
argNums = args;
}
@Override
public <E extends ISSABasicBlock> void addDomainElements(
CGAnalysisContext<E> ctx,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
IMethod im,
BasicBlockInContext<E> block,
SSAInvokeInstruction invInst,
int[] newArgNums,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa,
CallGraph cg) {
for (CGNode node : cg.getNodes(im.getReference())) {
for (int i : newArgNums) {
FlowType<E> flow = new ParameterFlow<>(block, i, true);
final int ssaVal = node.getIR().getParameter(i);
final Set<CodeElement> valueElements = CodeElement.valueElements(ssaVal);
PointerKey pk = pa.getHeapModel().getPointerKeyForLocal(node, ssaVal);
final OrdinalSet<InstanceKey> pointsToSet = pa.getPointsToSet(pk);
if (pointsToSet.isEmpty()) {
TypeReference typeRef = node.getMethod().getParameterType(i);
IClass clazz = node.getMethod().getClassHierarchy().lookupClass(typeRef);
if (null == clazz) {
} else if (clazz.isInterface()) {
for (IClass impl : pa.getClassHierarchy().getImplementors(typeRef)) {
InstanceKey ik = new ConcreteTypeKey(impl);
valueElements.addAll(ctx.codeElementsForInstanceKey(ik));
}
} else {
InstanceKey ik = new ConcreteTypeKey(clazz);
valueElements.addAll(ctx.codeElementsForInstanceKey(ik));
}
}
for (InstanceKey ik : pointsToSet) {
valueElements.addAll(ctx.codeElementsForInstanceKey(ik));
}
InflowAnalysis.addDomainElements(taintMap, block, flow, valueElements);
}
}
}
@Override
public String toString() {
return String.format("EntryArgSourceSpec(%s, %s)", namePattern, Arrays.toString(argNums));
}
}
| 5,215
| 37.072993
| 96
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/EntryRetSinkSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.spec;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import java.util.Collection;
import java.util.Collections;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.ReturnFlow;
public class EntryRetSinkSpec extends SinkSpec {
public EntryRetSinkSpec(MethodNamePattern name) {
namePattern = name;
}
@Override
public <E extends ISSABasicBlock> Collection<FlowType<E>> getFlowType(
BasicBlockInContext<E> block) {
return Collections.singleton(new ReturnFlow<>(block, false));
}
@Override
public String toString() {
return String.format("EntryRetSinkSpec(%s)", namePattern.getDescriptor());
}
}
| 2,721
| 40.242424
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/FieldNamePattern.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IClassLoader;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.types.TypeName;
import java.util.ArrayList;
import java.util.Collection;
public class FieldNamePattern {
final String className; // null = match any class
final String memberName; // null = match any method
// * used to match arbitrary substrings
public FieldNamePattern(String c, String m) {
className = c;
memberName = m;
}
Collection<IField> lookupFields(IClassLoader cl) {
Collection<IField> matching = new ArrayList<>();
IClass c = cl.lookupClass(TypeName.findOrCreate(className));
if (c == null) return matching;
Atom atom = Atom.findOrCreateUnicodeAtom(memberName);
Collection<IField> allFields = c.getAllFields();
for (IField f : allFields) {
if (f.getName().equals(atom)) {
matching.add(f);
}
}
return matching;
}
}
| 2,965
| 35.170732
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/ISinkSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
public interface ISinkSpec {}
| 2,003
| 38.294118
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/ISourceSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
public interface ISourceSpec {}
| 2,005
| 38.333333
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/ISpecs.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.spec;
public interface ISpecs {
/* A list of functions that are entry points. Arguments to these
* functions that are considered sources should be in the
* SourceSpec list. */
MethodNamePattern[] getEntrypointSpecs();
/* Other methods that source data via their return values or
* modification of their parameters. */
SourceSpec[] getSourceSpecs();
/* Methods that sink data supplied by some of their parameters. */
SinkSpec[] getSinkSpecs();
ISpecs EMPTY_SPECS =
new ISpecs() {
@Override
public SourceSpec[] getSourceSpecs() {
return new SourceSpec[] {};
}
@Override
public SinkSpec[] getSinkSpecs() {
return new SinkSpec[] {};
}
@Override
public MethodNamePattern[] getEntrypointSpecs() {
return new MethodNamePattern[] {};
}
};
}
| 2,905
| 38.27027
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/MethodNamePattern.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.Descriptor;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import java.io.UTFDataFormatException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
public class MethodNamePattern {
private final String className;
private final String memberName;
private final String descriptor; // null = match any types
public MethodNamePattern(String c, String m, String d) {
className = c;
memberName = m;
descriptor = d;
}
public MethodNamePattern(String c, String m) {
className = c;
memberName = m;
descriptor = null;
}
private Collection<IMethod> lookupMethods(IClass c) {
Collection<IMethod> matching = new ArrayList<>();
Atom atom = Atom.findOrCreateUnicodeAtom(memberName);
Descriptor desc = descriptor == null ? null : Descriptor.findOrCreateUTF8(descriptor);
Collection<? extends IMethod> allMethods = c.getAllMethods();
for (IMethod m : allMethods) {
if (m.getName().equals(atom) && (desc == null || m.getDescriptor().equals(desc))) {
matching.add(m);
}
}
return matching;
}
/**
* Returns a Collection of IMethods which are found in the following ClassLoaders: Application,
* Primordial, Extension
*/
public Collection<IMethod> getPossibleTargets(IClassHierarchy cha) {
Collection<IMethod> matching = new ArrayList<>();
IClass c;
c = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Application, className));
if (c != null) matching.addAll(lookupMethods(c));
c = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Primordial, className));
if (c != null) matching.addAll(lookupMethods(c));
c = cha.lookupClass(TypeReference.findOrCreate(ClassLoaderReference.Extension, className));
if (c != null) matching.addAll(lookupMethods(c));
Set<IMethod> targets = HashSetFactory.make();
for (IMethod im : matching) {
targets.addAll(cha.getPossibleTargets(im.getReference()));
}
return targets;
}
@Override
public String toString() {
String returnString = "MethodNamePattern (Class: " + className + " - Method: " + memberName;
if (descriptor == null) return returnString + ')';
return returnString + " - Descriptor: " + descriptor + ')';
}
public String getDescriptor() {
return String.format("%s.%s%s", className, memberName, descriptor == null ? "" : descriptor);
}
public String getClassName() {
return className;
}
public String getMemberName() {
return memberName;
}
public static MethodNamePattern patternForReference(MethodReference methodRef)
throws UTFDataFormatException {
String className = methodRef.getDeclaringClass().getName().toUnicodeString();
String methodName = methodRef.getName().toUnicodeString();
String descriptor = methodRef.getDescriptor().toUnicodeString();
MethodNamePattern pattern = new MethodNamePattern(className, methodName, descriptor);
return pattern;
}
}
| 5,286
| 35.212329
| 97
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/ResolveSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
class ResolvedSpec {
ResolvedSpec() {
// AndroidSpecs spec = new AndroidSpecs();
//
// for(MethodNamePattern m: spec.getEntrypointSpecs()) {
// }
// for(SourceSpec s: spec.getSourceSpecs()) {
// }
// for(ISinkSpec s: spec.getSinkSpecs()) {
// }
}
}
| 2,307
| 36.225806
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/SinkSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.spec;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import java.util.Arrays;
import java.util.Collection;
import org.scandroid.flow.types.FlowType;
public abstract class SinkSpec implements ISinkSpec {
protected MethodNamePattern namePattern;
// Zero-based arguments, but 0 is 'this'
protected int[] argNums; // null = all arguments, empty = no arguments?
public static int[] getNewArgNums(int n) {
int[] newArgNums = new int[n];
Arrays.setAll(newArgNums, i -> i + 1);
return newArgNums;
}
public MethodNamePattern getNamePattern() {
return namePattern;
}
public int[] getArgNums() {
return argNums;
}
@Override
public String toString() {
return "SinkSpec [namePattern=" + namePattern + ", argNums=" + Arrays.toString(argNums) + ']';
}
public abstract <E extends ISSABasicBlock> Collection<FlowType<E>> getFlowType(
BasicBlockInContext<E> block);
}
| 2,921
| 34.204819
| 98
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/SourceSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.flow.types.FlowType;
import org.scandroid.util.CGAnalysisContext;
public abstract class SourceSpec implements ISourceSpec {
protected MethodNamePattern namePattern;
protected int[] argNums; // null = all arguments, empty = no arguments?
public static int[] getNewArgNums(int n) {
int[] newArgNums = new int[n];
Arrays.setAll(newArgNums, i -> i + 1);
return newArgNums;
}
public MethodNamePattern getNamePattern() {
return namePattern;
}
public int[] getArgNums() {
return argNums;
}
@Override
public abstract String toString();
public abstract <E extends ISSABasicBlock> void addDomainElements(
CGAnalysisContext<E> ctx,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
IMethod im,
BasicBlockInContext<E> block,
SSAInvokeInstruction invInst,
int[] newArgNums,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa,
CallGraph cg);
}
| 3,587
| 38.428571
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/SpecUtils.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.spec;
import java.util.Arrays;
public class SpecUtils {
/** Combine two specs objects. */
public static ISpecs combine(final ISpecs s1, final ISpecs s2) {
return new ISpecs() {
@Override
public SourceSpec[] getSourceSpecs() {
SourceSpec[] s1Sources = s1.getSourceSpecs();
SourceSpec[] s2Sources = s2.getSourceSpecs();
return concat(s1Sources, s2Sources);
}
@Override
public SinkSpec[] getSinkSpecs() {
return concat(s1.getSinkSpecs(), s2.getSinkSpecs());
}
@Override
public MethodNamePattern[] getEntrypointSpecs() {
return concat(s1.getEntrypointSpecs(), s2.getEntrypointSpecs());
}
private <T> T[] concat(final T[] a, final T[] b) {
if (null == a) {
return b;
}
if (null == b) {
return a;
}
T[] newArray = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b, 0, newArray, a.length, b.length);
return newArray;
}
};
}
}
| 3,059
| 36.317073
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/StaticFieldSinkSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.Collection;
import java.util.Collections;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.StaticFieldFlow;
/** @author acfoltzer */
public class StaticFieldSinkSpec extends SinkSpec {
private final IField field;
private final IMethod method;
/**
* @param field to check for flows
* @param method to check for flow (at method's exit), e.g., main
*/
public StaticFieldSinkSpec(IField field, IMethod method) {
this.field = field;
this.method = method;
}
/* (non-Javadoc)
* @see org.scandroid.spec.SinkSpec#getFlowType(com.ibm.wala.ipa.cfg.BasicBlockInContext)
*/
@Override
public <E extends ISSABasicBlock> Collection<FlowType<E>> getFlowType(
BasicBlockInContext<E> block) {
Collection<FlowType<E>> flow =
HashSetFactory.make(
Collections.singleton((FlowType<E>) new StaticFieldFlow<>(block, field, false)));
return flow;
}
@Override
public String toString() {
return String.format("StaticFieldSinkSpec(%s)", field);
}
public IField getField() {
return field;
}
public IMethod getMethod() {
return method;
}
}
| 3,417
| 36.152174
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/StaticFieldSourceSpec.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey;
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.cfg.BasicBlockInContext;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.intset.OrdinalSet;
import java.util.Map;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.InstanceKeyElement;
import org.scandroid.domain.StaticFieldElement;
import org.scandroid.flow.InflowAnalysis;
import org.scandroid.flow.types.FlowType;
import org.scandroid.flow.types.StaticFieldFlow;
import org.scandroid.util.CGAnalysisContext;
/** @author creswick */
public class StaticFieldSourceSpec extends SourceSpec {
private final IField field;
public StaticFieldSourceSpec(IField field) {
this.field = field;
argNums = null;
}
/* (non-Javadoc)
* @see org.scandroid.spec.SourceSpec#addDomainElements(java.util.Map, com.ibm.wala.classLoader.IMethod, com.ibm.wala.ipa.cfg.BasicBlockInContext, com.ibm.wala.ssa.SSAInvokeInstruction, int[], com.ibm.wala.dataflow.IFDS.ISupergraph, com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis, com.ibm.wala.ipa.callgraph.CallGraph)
*/
@Override
public <E extends ISSABasicBlock> void addDomainElements(
CGAnalysisContext<E> ctx,
Map<BasicBlockInContext<E>, Map<FlowType<E>, Set<CodeElement>>> taintMap,
IMethod im,
BasicBlockInContext<E> block,
SSAInvokeInstruction invInst,
int[] newArgNums,
ISupergraph<BasicBlockInContext<E>, CGNode> graph,
PointerAnalysis<InstanceKey> pa,
CallGraph cg) {
Set<CodeElement> valueElements = HashSetFactory.make();
valueElements.add(new StaticFieldElement(field.getReference()));
FlowType<E> flow = new StaticFieldFlow<>(block, field, true);
TypeReference typeRef = field.getFieldTypeReference();
if (typeRef.isPrimitiveType()) {
InflowAnalysis.addDomainElements(taintMap, block, flow, valueElements);
return;
}
// else, handle reference types:
PointerKey pk = pa.getHeapModel().getPointerKeyForStaticField(field);
OrdinalSet<InstanceKey> pointsToSet = pa.getPointsToSet(pk);
if (pointsToSet.isEmpty()) {
IClassHierarchy cha = im.getClassHierarchy();
if (null == cha.lookupClass(typeRef)) {
return;
}
if (cha.isInterface(typeRef)) {
// TODO we could find all implementations of the interface, and add a concrete type key for
// each.
// we aren't doing that yet.
InflowAnalysis.addDomainElements(taintMap, block, flow, valueElements);
return;
}
IClass clazz = cha.lookupClass(typeRef);
if (null == clazz) {
} else {
InstanceKey ik = new ConcreteTypeKey(clazz);
valueElements.add(new InstanceKeyElement(ik));
}
}
for (InstanceKey ik : pointsToSet) {
valueElements.add(new InstanceKeyElement(ik));
}
InflowAnalysis.addDomainElements(taintMap, block, flow, valueElements);
}
@Override
public String toString() {
return "StaticFieldSourceSpec [field=" + field + ']';
}
}
| 5,712
| 38.673611
| 328
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/spec/StaticSpecs.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.spec;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.StringStuff;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/** @author creswick */
public class StaticSpecs implements ISpecs {
private final ClassHierarchy cha;
private final String methodSignature;
private final Collection<IField> fields;
public StaticSpecs(ClassHierarchy cha, String methodSignature) {
this.cha = cha;
this.methodSignature = methodSignature;
this.fields = collectFields();
}
/* (non-Javadoc)
* @see org.scandroid.spec.ISpecs#getEntrypointSpecs()
*/
@Override
public MethodNamePattern[] getEntrypointSpecs() {
return new MethodNamePattern[0];
}
/* (non-Javadoc)
* @see org.scandroid.spec.ISpecs#getSourceSpecs()
*/
@Override
public SourceSpec[] getSourceSpecs() {
// List<SourceSpec> specs = Lists.newArrayList();
//
// for (IField field : fields) {
// specs.add(new StaticFieldSourceSpec(field));
// }
//
// return specs.toArray(new SourceSpec[] {});
return new SourceSpec[] {};
}
private List<IField> collectFields() {
List<IField> fields = new ArrayList<>();
for (IClass cls : cha) {
for (IField field : cls.getAllStaticFields()) {
if (field.getFieldTypeReference().isReferenceType()) {
fields.add(field);
}
}
}
return fields;
}
/* (non-Javadoc)
* @see org.scandroid.spec.ISpecs#getSinkSpecs()
*/
@Override
public SinkSpec[] getSinkSpecs() {
List<SinkSpec> specs = new ArrayList<>();
Collection<IMethod> methods =
cha.getPossibleTargets(StringStuff.makeMethodReference(methodSignature));
for (IField field : fields) {
if (!field.isFinal()) {
for (IMethod method : methods) {
specs.add(new StaticFieldSinkSpec(field, method));
}
}
}
return specs.toArray(new SinkSpec[] {});
}
}
| 4,108
| 34.119658
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/synthmethod/DefaultSCanDroidOptions.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.synthmethod;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions;
import java.io.File;
import java.net.URI;
import org.scandroid.util.ISCanDroidOptions;
public abstract class DefaultSCanDroidOptions implements ISCanDroidOptions {
@Override
public boolean pdfCG() {
return false;
}
@Override
public boolean pdfPartialCG() {
return false;
}
@Override
public boolean pdfOneLevelCG() {
return false;
}
@Override
public boolean systemToApkCG() {
return false;
}
@Override
public boolean stdoutCG() {
return true;
}
@Override
public boolean includeLibrary() {
// TODO is this right? we haven't summarized with CLI options set, so
// this is what we've been doing...
return true;
}
@Override
public boolean separateEntries() {
return false;
}
@Override
public boolean ifdsExplorer() {
return false;
}
@Override
public boolean addMainEntrypoints() {
return false;
}
@Override
public boolean useThreadRunMain() {
return false;
}
@Override
public boolean stringPrefixAnalysis() {
return false;
}
@Override
public boolean testCGBuilder() {
return false;
}
@Override
public boolean useDefaultPolicy() {
return false;
}
@Override
public abstract URI getClasspath();
@Override
public String getFilename() {
return new File(getClasspath()).getName();
}
@Override
public URI getAndroidLibrary() {
try {
return new FileProvider().getResource("data/android-2.3.7_r1.jar").toURI();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public ReflectionOptions getReflectionOptions() {
return ReflectionOptions.NONE;
}
@Override
public URI getSummariesURI() {
try {
return new FileProvider().getResource("data/MethodSummaries.xml").toURI();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public boolean classHierarchyWarnings() {
return false;
}
@Override
public boolean cgBuilderWarnings() {
return false;
}
public static String dumpString(ISCanDroidOptions options) {
return "DefaultSCanDroidOptions [pdfCG()="
+ options.pdfCG()
+ ", pdfPartialCG()="
+ options.pdfPartialCG()
+ ", pdfOneLevelCG()="
+ options.pdfOneLevelCG()
+ ", systemToApkCG()="
+ options.systemToApkCG()
+ ", stdoutCG()="
+ options.stdoutCG()
+ ", includeLibrary()="
+ options.includeLibrary()
+ ", separateEntries()="
+ options.separateEntries()
+ ", ifdsExplorer()="
+ options.ifdsExplorer()
+ ", addMainEntrypoints()="
+ options.addMainEntrypoints()
+ ", useThreadRunMain()="
+ options.useThreadRunMain()
+ ", stringPrefixAnalysis()="
+ options.stringPrefixAnalysis()
+ ", testCGBuilder()="
+ options.testCGBuilder()
+ ", useDefaultPolicy()="
+ options.useDefaultPolicy()
+ ", getClasspath()="
+ options.getClasspath()
+ ", getFilename()="
+ options.getFilename()
+ ", getAndroidLibrary()="
+ options.getAndroidLibrary()
+ ", getReflectionOptions()="
+ options.getReflectionOptions()
+ ", getSummariesURI()="
+ options.getSummariesURI()
+ ", classHierarchyWarnings()="
+ options.classHierarchyWarnings()
+ ", cgBuilderWarnings()="
+ options.cgBuilderWarnings()
+ ']';
}
}
| 5,649
| 26.970297
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/synthmethod/SSASerializationException.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.synthmethod;
public class SSASerializationException extends RuntimeException {
private static final long serialVersionUID = 5679383911644331821L;
public SSASerializationException(Exception e) {
super(e);
}
public SSASerializationException(String string) {
super(string);
}
}
| 2,293
| 36.606557
| 86
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/synthmethod/SSAtoXMLVisitor.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.synthmethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAComparisonInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAConversionInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.io.UTFDataFormatException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class SSAtoXMLVisitor implements SSAInstruction.IVisitor {
/** A counter to use for generating unique local definition names. */
private int defCounter = 0;
/** Map the known defNum to local def names. */
private final Map<Integer, String> localDefs = HashMapFactory.make();
/** XML document to use for creating elements. */
private final Document doc;
/** XML elements that represent the ssa instructions */
private final List<Element> summary = new ArrayList<>();
public SSAtoXMLVisitor(Document doc, int argCount) {
this.doc = doc;
for (int i = 0; i < argCount; i++) {
localDefs.put(i + 1, "arg" + i);
}
}
@Override
public void visitGoto(SSAGotoInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
/**
* Load from an array ref, at specified index, and store in def. {@code <aaload ref="x" index="0"
* def="y" />}
*/
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
try {
Element elt = doc.createElement(XMLSummaryWriter.E_AALOAD);
String refStr = getLocalName(instruction.getArrayRef());
elt.setAttribute(XMLSummaryWriter.A_REF, refStr);
String defStr = getLocalName(instruction.getDef());
elt.setAttribute(XMLSummaryWriter.A_VALUE, defStr);
elt.setAttribute(XMLSummaryWriter.A_INDEX, String.valueOf(instruction.getIndex()));
summary.add(elt);
} catch (Exception e) {
throw new SSASerializationException(e);
}
}
/** {@code <aastore ref="x" value="y" index="0" />} */
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
try {
Element elt = doc.createElement(XMLSummaryWriter.E_AASTORE);
String refStr = getLocalName(instruction.getArrayRef());
elt.setAttribute(XMLSummaryWriter.A_REF, refStr);
String valueStr = getLocalName(instruction.getValue());
elt.setAttribute(XMLSummaryWriter.A_VALUE, valueStr);
elt.setAttribute(XMLSummaryWriter.A_INDEX, String.valueOf(instruction.getIndex()));
summary.add(elt);
} catch (Exception e) {
throw new SSASerializationException(e);
}
}
@Override
public void visitBinaryOp(SSABinaryOpInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitUnaryOp(SSAUnaryOpInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitConversion(SSAConversionInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitComparison(SSAComparisonInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitConditionalBranch(SSAConditionalBranchInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitSwitch(SSASwitchInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitReturn(SSAReturnInstruction instruction) {
try {
Element elt = doc.createElement(XMLSummaryWriter.E_RETURN);
if (!instruction.returnsVoid()) {
String localName = getLocalName(instruction.getResult());
elt.setAttribute(XMLSummaryWriter.A_VALUE, localName);
}
summary.add(elt);
} catch (Exception e) {
throw new SSASerializationException(e);
}
}
/**
* eg: {@code <getfield class="Ljava/lang/Thread" field="runnable" fieldType="Ljava/lang/Runnable"
* def="x" ref="arg0" />}
*
* <p>I think the get statics look like this:
*
* <p>1007g 9.1g 12m S 237.9 0.9 4:27.32 java {@code <getstatic class="Ljava/lang/Thread"
* field="runnable" fieldType="Ljava/lang/Runnable" def="x" />}
*/
@Override
public void visitGet(SSAGetInstruction instruction) {
try {
String eltName;
if (instruction.isStatic()) {
eltName = XMLSummaryWriter.E_GETSTATIC;
} else {
eltName = XMLSummaryWriter.E_GETFIELD;
}
Element elt = doc.createElement(eltName);
if (!instruction.isStatic()) {
String refName = getLocalName(instruction.getRef());
elt.setAttribute(XMLSummaryWriter.A_REF, refName);
}
String def = newLocalDef(instruction.getDef());
TypeReference fieldType = instruction.getDeclaredFieldType();
TypeReference classType = instruction.getDeclaredField().getDeclaringClass();
String fieldName = instruction.getDeclaredField().getName().toUnicodeString();
elt.setAttribute(XMLSummaryWriter.A_CLASS, classType.getName().toUnicodeString());
elt.setAttribute(XMLSummaryWriter.A_FIELD, fieldName);
elt.setAttribute(XMLSummaryWriter.A_FIELD_TYPE, fieldType.getName().toUnicodeString());
elt.setAttribute(XMLSummaryWriter.A_DEF, def);
summary.add(elt);
} catch (Exception e) {
throw new SSASerializationException(e);
}
}
/**
* {@code <putstatic class="Ljava/lang/System" field="security"
* fieldType="Ljava/lang/SecurityManager" value="secure" />}
*
* <p>{@code <putfield class="Ljava/lang/Thread" field="runnable" fieldType="Ljava/lang/Runnable"
* ref="arg0" value="arg0" />}
*/
@Override
public void visitPut(SSAPutInstruction instruction) {
try {
String eltName;
if (instruction.isStatic()) {
eltName = XMLSummaryWriter.E_PUTSTATIC;
} else {
eltName = XMLSummaryWriter.E_PUTFIELD;
}
Element elt = doc.createElement(eltName);
if (!instruction.isStatic()) {
String refName = getLocalName(instruction.getRef());
elt.setAttribute(XMLSummaryWriter.A_REF, refName);
}
String value = getLocalName(instruction.getVal());
TypeReference fieldType = instruction.getDeclaredFieldType();
TypeReference classType = instruction.getDeclaredField().getDeclaringClass();
String fieldName = instruction.getDeclaredField().getName().toUnicodeString();
elt.setAttribute(XMLSummaryWriter.A_CLASS, classType.getName().toUnicodeString());
elt.setAttribute(XMLSummaryWriter.A_FIELD, fieldName);
elt.setAttribute(XMLSummaryWriter.A_FIELD_TYPE, fieldType.getName().toUnicodeString());
elt.setAttribute(XMLSummaryWriter.A_VALUE, value);
summary.add(elt);
} catch (Exception e) {
throw new SSASerializationException(e);
}
}
/**
* {@code <call type="virtual" name="put" class="Ljava/util/Hashtable"
* descriptor="(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;" arg0="x" arg1="key"
* arg2="value" def="local_def" />}
*/
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
try {
Element elt = doc.createElement(XMLSummaryWriter.E_CALL);
MethodReference callee = instruction.getDeclaredTarget();
String descString = callee.getDescriptor().toUnicodeString();
elt.setAttribute(XMLSummaryWriter.A_DESCRIPTOR, descString);
String typeString = instruction.getCallSite().getInvocationString();
elt.setAttribute(XMLSummaryWriter.A_TYPE, typeString);
String nameString = callee.getName().toUnicodeString();
elt.setAttribute(XMLSummaryWriter.A_NAME, nameString);
String classString =
instruction.getDeclaredTarget().getDeclaringClass().getName().toUnicodeString();
elt.setAttribute(XMLSummaryWriter.A_CLASS, classString);
if (!instruction.getDeclaredResultType().equals(TypeReference.Void)) {
int defNum = instruction.getDef();
String localName = newLocalDef(defNum);
elt.setAttribute(XMLSummaryWriter.A_DEF, localName);
}
int paramCount = instruction.getNumberOfPositionalParameters();
for (int i = 0; i < paramCount; i++) {
String argName = getLocalName(instruction.getUse(i));
elt.setAttribute(XMLSummaryWriter.A_ARG + i, argName);
}
summary.add(elt);
} catch (Exception e) {
throw new SSASerializationException(e);
}
}
@Override
public void visitNew(SSANewInstruction instruction) {
try {
int defNum = instruction.getDef();
String localName = newLocalDef(defNum);
TypeReference type = instruction.getConcreteType();
String className = type.getName().toUnicodeString();
Element elt = doc.createElement(XMLSummaryWriter.E_NEW);
elt.setAttribute(XMLSummaryWriter.A_DEF, localName);
elt.setAttribute(XMLSummaryWriter.A_CLASS, className);
if (type.isArrayType()) {
// array allocations need a size value
Element sizeElt = doc.createElement(XMLSummaryWriter.E_CONSTANT);
final String sizeName = "sizeOf$allocAt" + instruction.getNewSite().getProgramCounter();
sizeElt.setAttribute(XMLSummaryWriter.A_NAME, sizeName);
sizeElt.setAttribute(XMLSummaryWriter.A_TYPE, "int");
sizeElt.setAttribute(XMLSummaryWriter.A_VALUE, "1");
summary.add(sizeElt);
elt.setAttribute(XMLSummaryWriter.A_SIZE, sizeName);
}
summary.add(elt);
} catch (Exception e) {
throw new SSASerializationException(e);
}
}
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
/**
* Serialiaze a throw to XML.
*
* <p>Something like this? {@code <throw value="val_localDef" />}
*/
@Override
public void visitThrow(SSAThrowInstruction instruction) {
throw new SSASerializationException("Exceptions not currently supported.");
// try {
// int exValNo = instruction.getException();
// String value = getLocalName(exValNo);
//
// Element elt = doc.createElement(XMLSummaryWriter.E_ATHROW);
// elt.setAttribute(XMLSummaryWriter.A_VALUE, value);
// summary.add(elt);
// } catch (Exception e) {
// throw new SSASerializationException(e);
// }
}
@Override
public void visitMonitor(SSAMonitorInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitInstanceof(SSAInstanceofInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitPi(SSAPiInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
@Override
public void visitLoadMetadata(SSALoadMetadataInstruction instruction) {
throw new SSASerializationException("Unsupported.");
}
/** Add a new defNum, creating a name for that defnum. */
private String newLocalDef(int defNum) {
String newName = "localdef_" + defCounter;
localDefs.put(defNum, newName);
defCounter++;
return newName;
}
/**
* Get a local name for the provided defNum.
*
* <p>If, for some reason, the defNum has not yet been seen (and, thus, has no local name
* associated with it) then this will throw an illegal state exception.
*
* <p>TODO needs to return 'arg0' -> 'argN' for those value numbers...
*/
private String getLocalName(int defNum) throws IllegalStateException {
if (0 == defNum) {
return "unknown";
}
if (localDefs.containsKey(defNum)) {
return localDefs.get(defNum);
}
return XMLSummaryWriter.A_ARG + (defNum - 1);
// throw new IllegalStateException("defNum: " + defNum
// + " is not defined.");
}
public List<Element> getInstSummary() {
return summary;
}
@SuppressWarnings("unused")
private static String typeRefToStr(TypeReference fieldType) throws UTFDataFormatException {
Atom className = fieldType.getName().getClassName();
Atom pkgName = fieldType.getName().getPackage();
if (null == pkgName && null != className) {
return className.toUnicodeString();
}
if (null == className) {}
return pkgName.toUnicodeString() + '/' + className.toUnicodeString();
}
}
| 15,981
| 34.280353
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/synthmethod/XMLSummaryWriter.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.synthmethod;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.ipa.summaries.MethodSummary;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import java.io.ByteArrayOutputStream;
import java.io.UTFDataFormatException;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class XMLSummaryWriter {
//
// Define XML element names
//
static final String E_CLASSLOADER = "classloader";
static final String E_METHOD = "method";
static final String E_CLASS = "class";
static final String E_PACKAGE = "package";
static final String E_CALL = "call";
static final String E_NEW = "new";
static final String E_POISON = "poison";
static final String E_SUMMARY_SPEC = "summary-spec";
static final String E_RETURN = "return";
static final String E_PUTSTATIC = "putstatic";
static final String E_GETSTATIC = "getstatic";
static final String E_PUTFIELD = "putfield";
static final String E_AALOAD = "aaload";
static final String E_AASTORE = "aastore";
static final String E_GETFIELD = "getfield";
static final String E_ATHROW = "throw";
static final String E_CONSTANT = "constant";
//
// Define XML attribute names
//
static final String A_NAME = "name";
static final String A_TYPE = "type";
static final String A_CLASS = "class";
static final String A_SIZE = "size";
static final String A_DESCRIPTOR = "descriptor";
static final String A_REASON = "reason";
static final String A_LEVEL = "level";
static final String A_WILDCARD = "*";
static final String A_DEF = "def";
static final String A_STATIC = "static";
static final String A_VALUE = "value";
static final String A_FIELD = "field";
static final String A_FIELD_TYPE = "fieldType";
static final String A_ARG = "arg";
static final String A_ALLOCATABLE = "allocatable";
static final String A_REF = "ref";
static final String A_INDEX = "index";
static final String A_IGNORE = "ignore";
static final String A_FACTORY = "factory";
static final String A_NUM_ARGS = "numArgs";
static final String V_NULL = "null";
static final String V_TRUE = "true";
private final Document doc;
private final Element rootElement;
private Element clrElt = null;
private Element pkgElt = null;
private final Map<Atom, Element> classElts;
public XMLSummaryWriter() throws ParserConfigurationException {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
rootElement = doc.createElement(E_SUMMARY_SPEC);
doc.appendChild(rootElement);
classElts = HashMapFactory.make();
}
public String serialize() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
// transformerFactory.setAttribute("indent-number", new Integer(4));
try {
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(baos);
transformer.transform(source, result);
} catch (TransformerException | IllegalArgumentException e) {
e.printStackTrace();
}
// using the default encoding here, since the bytes were just written
// with a default encoding...
return baos.toString();
}
/**
* Throws various exceptions if a problem occurred serializing this method.
*
* <p>No guarantees as to the state of the Document if an exception is thrown.
*/
public void add(MethodSummary summary) throws UTFDataFormatException {
// create a method element, and populate it's attributes:
Element methElt;
TypeReference methClass = summary.getMethod().getDeclaringClass();
Atom clrName = methClass.getClassLoader().getName();
Atom pkg = methClass.getName().getPackage();
Atom className = methClass.getName().getClassName();
Atom methodName = summary.getMethod().getName();
methElt = doc.createElement(E_METHOD);
methElt.setAttribute(A_NAME, methodName.toUnicodeString());
String descriptor = getMethodDescriptor(summary);
methElt.setAttribute(A_DESCRIPTOR, descriptor);
// default is false:
if (summary.isStatic()) {
methElt.setAttribute(A_STATIC, "true");
}
// default is false:
if (summary.isFactory()) {
methElt.setAttribute(A_FACTORY, "true");
}
// summarize the instructions:
List<Element> instructions = summarizeInstructions(summary);
for (Element elt : instructions) {
methElt.appendChild(elt);
}
// get an element to add this method to:
Element classElt = findOrCreateClassElt(clrName, pkg, className);
classElt.appendChild(methElt);
}
private Element findOrCreateClassElt(Atom classLoaderName, Atom pkg, Atom className)
throws UTFDataFormatException {
Element classElt = classElts.get(className);
if (classElt == null) {
Element pkgElt = findOrCreatePkgElt(classLoaderName, pkg);
classElt = doc.createElement(E_CLASS);
classElt.setAttribute(A_NAME, className.toUnicodeString());
pkgElt.appendChild(classElt);
classElts.put(className, classElt);
}
return classElt;
}
private Element findOrCreateClrElt(Atom classLoaderName)
throws DOMException, UTFDataFormatException {
if (clrElt == null) {
clrElt = doc.createElement(E_CLASSLOADER);
clrElt.setAttribute(A_NAME, classLoaderName.toUnicodeString());
rootElement.appendChild(clrElt);
}
return clrElt;
}
private Element findOrCreatePkgElt(Atom classLoaderName, Atom pkg) throws UTFDataFormatException {
if (pkgElt == null) {
Element clrElt = findOrCreateClrElt(classLoaderName);
pkgElt = doc.createElement(E_PACKAGE);
pkgElt.setAttribute(A_NAME, pkg.toUnicodeString());
clrElt.appendChild(pkgElt);
}
return pkgElt;
}
private List<Element> summarizeInstructions(MethodSummary summary) {
SSAtoXMLVisitor v = new SSAtoXMLVisitor(doc, summary.getNumberOfParameters());
for (SSAInstruction inst : summary.getStatements()) {
inst.visit(v);
}
return v.getInstSummary();
}
/** Generate a method descriptor, such as (I[Ljava/lang/String;)[Ljava/lang/String; */
private static String getMethodDescriptor(MethodSummary summary) {
StringBuilder typeSigs = new StringBuilder("(");
int i = 0;
if (!summary.isStatic()) {
i = 1; // if it's not static, start with param 1.
}
for (; i < summary.getNumberOfParameters(); i++) {
TypeReference tr = summary.getParameterType(i);
// unwrap array types
while (tr.isArrayType()) {
typeSigs.append('[');
tr = tr.getArrayElementType();
}
if (tr.isPrimitiveType()) {
typeSigs.append(tr.getName().toUnicodeString());
} else {
typeSigs.append(tr.getName().toUnicodeString()).append(';');
}
}
typeSigs.append(')');
TypeReference returnType = summary.getReturnType();
if (returnType.isPrimitiveType()) {
typeSigs.append(returnType.getName().toUnicodeString());
} else {
typeSigs.append(returnType.getName().toUnicodeString()).append(';');
}
String descriptor = typeSigs.toString();
return descriptor;
}
}
| 10,103
| 35.741818
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/AndroidAnalysisContext.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Adam Fuchs <afuchs@cs.umd.edu> Avik Chaudhuri <avik@cs.umd.edu> Steve Suh <suhsteve@gmail.com>
* Galois, Inc. (Adam Foltzer <acfoltzer@galois.com)
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.util;
import com.google.common.collect.Queues;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.Language;
import com.ibm.wala.core.util.io.FileProvider;
import com.ibm.wala.core.util.strings.Atom;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.dalvik.util.AndroidAnalysisScope;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.ClassTargetSelector;
import com.ibm.wala.ipa.callgraph.ContextSelector;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter;
import com.ibm.wala.ipa.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXCFABuilder;
import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.ipa.cha.ClassHierarchyFactory;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ipa.summaries.BypassClassTargetSelector;
import com.ibm.wala.ipa.summaries.BypassMethodTargetSelector;
import com.ibm.wala.ipa.summaries.MethodSummary;
import com.ibm.wala.ipa.summaries.XMLMethodSummaryReader;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.HashSetFactory;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Deque;
import java.util.Map;
import java.util.Set;
public class AndroidAnalysisContext {
private static final String methodSpec = "MethodSummaries.xml";
private static final String pathToSpec = "data";
private final ISCanDroidOptions options;
private final AnalysisScope scope;
private final ClassHierarchy cha;
public AndroidAnalysisContext() {
throw new IllegalArgumentException();
}
public AndroidAnalysisContext(ISCanDroidOptions options)
throws IllegalArgumentException, ClassHierarchyException, IOException {
this(options, "Java60RegressionExclusions.txt");
}
public AndroidAnalysisContext(ISCanDroidOptions options, String exclusions)
throws IOException, IllegalArgumentException, ClassHierarchyException {
this.options = options;
scope =
AndroidAnalysisScope.setUpAndroidAnalysisScope(
options.getClasspath(),
exclusions,
getClass().getClassLoader(),
options.getAndroidLibrary());
cha = ClassHierarchyFactory.make(scope);
/*
if (options.classHierarchyWarnings()) {
// log ClassHierarchy warnings
for (Warning w : Iterator2Iterable.make(Warnings.iterator())) {
}
}
*/
Warnings.clear();
}
public static SSAPropagationCallGraphBuilder makeVanillaZeroOneCFABuilder(
AnalysisOptions options,
IAnalysisCacheView cache,
IClassHierarchy cha,
AnalysisScope scope,
ContextSelector customSelector,
SSAContextInterpreter customInterpreter,
InputStream summariesStream,
MethodSummary extraSummary) {
if (options == null) {
throw new IllegalArgumentException("options is null");
}
Util.addDefaultSelectors(options, cha);
// addDefaultBypassLogic(options, scope, Util.class.getClassLoader(),
// cha);
// addBypassLogic(options, scope,
// AndroidAppLoader.class.getClassLoader(), methodSpec, cha);
addBypassLogic(options, scope, summariesStream, cha, extraSummary);
return ZeroXCFABuilder.make(
Language.JAVA,
cha,
options,
cache,
customSelector,
customInterpreter,
ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.CONSTANT_SPECIFIC);
}
/**
* @param options options that govern call graph construction
* @param cha governing class hierarchy
* @param scope representation of the analysis scope
* @param customSelector user-defined context selector, or null if none
* @param customInterpreter user-defined context interpreter, or null if none
* @return a 0-CFA Call Graph Builder.
* @throws IllegalArgumentException if options is null
* <p>TODO: move
*/
public static SSAPropagationCallGraphBuilder makeZeroCFABuilder(
AnalysisOptions options,
IAnalysisCacheView cache,
IClassHierarchy cha,
AnalysisScope scope,
ContextSelector customSelector,
SSAContextInterpreter customInterpreter,
Collection<InputStream> summariesStreams,
MethodSummary extraSummary) {
if (options == null) {
throw new IllegalArgumentException("options is null");
}
Util.addDefaultSelectors(options, cha);
for (InputStream stream : summariesStreams) {
addBypassLogic(options, scope, stream, cha, extraSummary);
}
return ZeroXCFABuilder.make(
Language.JAVA,
cha,
options,
cache,
customSelector,
customInterpreter,
ZeroXInstanceKeys.NONE);
}
// public static void addBypassLogic(AnalysisOptions options, AnalysisScope
// scope, ClassLoader cl, String xmlFile,
// IClassHierarchy cha) throws IllegalArgumentException {
public static void addBypassLogic(
AnalysisOptions options,
AnalysisScope scope,
InputStream xmlIStream,
IClassHierarchy cha,
MethodSummary extraSummary)
throws IllegalArgumentException {
if (scope == null) {
throw new IllegalArgumentException("scope is null");
}
if (options == null) {
throw new IllegalArgumentException("options is null");
}
// if (cl == null) {
// throw new IllegalArgumentException("cl is null");
// }
if (cha == null) {
throw new IllegalArgumentException("cha cannot be null");
}
try {
Set<TypeReference> summaryClasses = HashSetFactory.make();
Map<MethodReference, MethodSummary> summaries = HashMapFactory.make();
if (null != xmlIStream) {
XMLMethodSummaryReader newSummaryXML = loadMethodSummaries(scope, xmlIStream);
summaryClasses.addAll(newSummaryXML.getAllocatableClasses());
summaries.putAll(newSummaryXML.getSummaries());
}
// for (MethodReference mr : summaries.keySet()) {
//
// }
try (final InputStream s =
new FileProvider()
.getInputStreamFromClassLoader(
pathToSpec + File.separator + methodSpec,
AndroidAnalysisContext.class.getClassLoader())) {
XMLMethodSummaryReader nativeSummaries = loadMethodSummaries(scope, s);
summaries.putAll(nativeSummaries.getSummaries());
summaryClasses.addAll(nativeSummaries.getAllocatableClasses());
if (extraSummary != null) {
summaries.put(extraSummary.getMethod(), extraSummary);
}
MethodTargetSelector ms =
new BypassMethodTargetSelector(
options.getMethodTargetSelector(), summaries,
nativeSummaries.getIgnoredPackages(), cha);
options.setSelector(ms);
ClassTargetSelector cs =
new BypassClassTargetSelector(
options.getClassTargetSelector(),
summaryClasses,
cha,
cha.getLoader(scope.getLoader(Atom.findOrCreateUnicodeAtom("Synthetic"))));
options.setSelector(cs);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static XMLMethodSummaryReader loadMethodSummaries(
AnalysisScope scope, InputStream xmlIStream) {
try (@SuppressWarnings("resource")
InputStream s =
xmlIStream != null
? xmlIStream
: AndroidAnalysisContext.class
.getClassLoader()
.getResourceAsStream(pathToSpec + File.separator + methodSpec)) {
return new XMLMethodSummaryReader(s, scope);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/** Returns all concrete classes implementing the given interface or any subinterfaces */
public Collection<IClass> concreteClassesForInterface(IClass iRoot) {
Set<IClass> clazzes = HashSetFactory.make();
Set<IClass> done = HashSetFactory.make();
Deque<IClass> todo = Queues.newArrayDeque();
todo.push(iRoot);
while (!todo.isEmpty()) {
IClass i = todo.pop();
for (IClass clazz : cha.getImplementors(i.getReference())) {
if (clazz.isInterface() && !done.contains(clazz)) {
done.add(i);
todo.push(clazz);
} else if (!clazz.isAbstract()) {
clazzes.add(clazz);
}
}
}
return clazzes;
}
public ISCanDroidOptions getOptions() {
return options;
}
public AnalysisScope getScope() {
return scope;
}
public ClassHierarchy getClassHierarchy() {
return cha;
}
}
| 11,080
| 34.860841
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/CGAnalysisContext.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.util;
import com.google.common.collect.Queues;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IField;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.warnings.Warnings;
import com.ibm.wala.dalvik.classLoader.DexIRFactory;
import com.ibm.wala.dataflow.IFDS.ICFGSupergraph;
import com.ibm.wala.dataflow.IFDS.ISupergraph;
import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.IAnalysisCacheView;
import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector;
import com.ibm.wala.ipa.callgraph.impl.Everywhere;
import com.ibm.wala.ipa.callgraph.impl.PartialCallGraph;
import com.ibm.wala.ipa.callgraph.propagation.ConcreteTypeKey;
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.callgraph.propagation.SSAPropagationCallGraphBuilder;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ssa.ISSABasicBlock;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.TypeReference;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.graph.GraphSlicer;
import com.ibm.wala.util.intset.OrdinalSet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.scandroid.domain.CodeElement;
import org.scandroid.domain.FieldElement;
import org.scandroid.domain.InstanceKeyElement;
/**
* @author acfoltzer
* <p>Represents an analysis context after the call graph, pointer analysis, and supergraphs
* have been generated. This is separated from AndroidAnalysisContext since these depend on the
* entrypoints for analysis in a way that is not likely reusable across all analyses of a
* particular classpath
*/
public class CGAnalysisContext<E extends ISSABasicBlock> {
public final AndroidAnalysisContext analysisContext;
private final List<Entrypoint> entrypoints;
public CallGraph cg;
public PointerAnalysis<InstanceKey> pa;
public ISupergraph<BasicBlockInContext<E>, CGNode> graph;
public Graph<CGNode> oneLevelGraph;
public Graph<CGNode> systemToApkGraph;
public Graph<CGNode> partialGraph;
public CGAnalysisContext(AndroidAnalysisContext analysisContext, IEntryPointSpecifier specifier)
throws IOException {
this(analysisContext, specifier, new ArrayList<>());
}
@SuppressWarnings({"rawtypes", "unchecked"})
public CGAnalysisContext(
AndroidAnalysisContext analysisContext,
IEntryPointSpecifier specifier,
Collection<InputStream> extraSummaries)
throws IOException {
this.analysisContext = analysisContext;
final AnalysisScope scope = analysisContext.getScope();
final ClassHierarchy cha = analysisContext.getClassHierarchy();
final ISCanDroidOptions options = analysisContext.getOptions();
entrypoints = specifier.specify(analysisContext);
AnalysisOptions analysisOptions = new AnalysisOptions(scope, entrypoints);
/*
for (Entrypoint e : entrypoints) {
}
*/
analysisOptions.setReflectionOptions(options.getReflectionOptions());
IAnalysisCacheView cache = new AnalysisCacheImpl(new DexIRFactory());
SSAPropagationCallGraphBuilder cgb;
if (null != options.getSummariesURI()) {
try (final FileInputStream in = new FileInputStream(new File(options.getSummariesURI()))) {
extraSummaries.add(in);
}
}
cgb =
AndroidAnalysisContext.makeZeroCFABuilder(
analysisOptions,
cache,
cha,
scope,
new DefaultContextSelector(analysisOptions, cha),
null,
extraSummaries,
null);
/*
if (analysisContext.getOptions().cgBuilderWarnings()) {
// CallGraphBuilder construction warnings
for (Warning w : Iterator2Iterable.make(Warnings.iterator())) {
}
}
*/
Warnings.clear();
boolean graphBuilt = true;
try {
cg = cgb.makeCallGraph(cgb.getOptions());
} catch (Exception e) {
graphBuilt = false;
if (!options.testCGBuilder()) {
throw new RuntimeException(e);
} else {
e.printStackTrace();
}
}
if (options.testCGBuilder()) {
// TODO: this is too specialized for cmd-line apps
int status = graphBuilt ? 0 : 1;
System.exit(status);
}
/*
// makeCallGraph warnings
for (Warning w : Iterator2Iterable.make(Warnings.iterator())) {
}
*/
Warnings.clear();
pa = cgb.getPointerAnalysis();
partialGraph =
GraphSlicer.prune(
cg,
node ->
LoaderUtils.fromLoader(node, ClassLoaderReference.Application)
|| node.getMethod().isWalaSynthetic());
if (options.includeLibrary()) {
graph = (ISupergraph) ICFGSupergraph.make(cg);
} else {
Collection<CGNode> nodes = HashSetFactory.make();
for (CGNode cgNode : partialGraph) {
nodes.add(cgNode);
}
CallGraph pcg = PartialCallGraph.make(cg, cg.getEntrypointNodes(), nodes);
graph = (ISupergraph) ICFGSupergraph.make(pcg);
}
oneLevelGraph =
GraphSlicer.prune(
cg,
node -> {
// Node in APK
if (LoaderUtils.fromLoader(node, ClassLoaderReference.Application)) {
return true;
} else {
Iterator<CGNode> n = cg.getPredNodes(node);
while (n.hasNext()) {
// Primordial node has a successor in APK
if (LoaderUtils.fromLoader(n.next(), ClassLoaderReference.Application))
return true;
}
n = cg.getSuccNodes(node);
while (n.hasNext()) {
// Primordial node has a predecessor in APK
if (LoaderUtils.fromLoader(n.next(), ClassLoaderReference.Application))
return true;
}
// Primordial node with no direct successors or predecessors
// to APK code
return false;
}
});
systemToApkGraph =
GraphSlicer.prune(
cg,
node -> {
if (LoaderUtils.fromLoader(node, ClassLoaderReference.Primordial)) {
Iterator<CGNode> succs = cg.getSuccNodes(node);
while (succs.hasNext()) {
CGNode n1 = succs.next();
if (LoaderUtils.fromLoader(n1, ClassLoaderReference.Application)) {
return true;
}
}
// Primordial method, with no link to APK code:
return false;
} else if (LoaderUtils.fromLoader(node, ClassLoaderReference.Application)) {
// see if this is an APK method that was
// invoked by a Primordial method:
Iterator<CGNode> preds = cg.getPredNodes(node);
while (preds.hasNext()) {
CGNode n2 = preds.next();
if (LoaderUtils.fromLoader(n2, ClassLoaderReference.Primordial)) {
return true;
}
}
// APK code, no link to Primordial:
return false;
}
// who knows, not interesting:
return false;
});
/*
if (options.stdoutCG()) {
for (CGNode node : Iterator2Iterable.make(cg.iterator())) {
}
}
for (CGNode node : Iterator2Iterable.make(cg.iterator())) {
if (node.getMethod().isWalaSynthetic()) {
SSACFG ssaCFG = node.getIR().getControlFlowGraph();
int totalBlocks = ssaCFG.getNumberOfNodes();
for (int i = 0; i < totalBlocks; i++) {
BasicBlock bb = ssaCFG.getBasicBlock(i);
for (SSAInstruction ssaI : bb.getAllInstructions()) {
}
}
}
}
*/
}
/**
* @return a set of all code elements that might refer to this object or one of its fields
* (recursively)
*/
public Set<CodeElement> codeElementsForInstanceKey(InstanceKey rootIK) {
Set<CodeElement> elts = HashSetFactory.make();
Deque<InstanceKey> iks = Queues.newArrayDeque();
iks.push(rootIK);
while (!iks.isEmpty()) {
InstanceKey ik = iks.pop();
elts.add(new InstanceKeyElement(ik));
final IClass clazz = ik.getConcreteType();
final TypeReference typeRef = clazz.getReference();
// If an array, recur down into the structure
if (typeRef.isArrayType()) {
if (typeRef.getArrayElementType().isPrimitiveType()) {
// don't do anything for primitive contents
continue;
}
OrdinalSet<InstanceKey> pointsToSet =
pa.getPointsToSet(pa.getHeapModel().getPointerKeyForArrayContents(ik));
if (pointsToSet.isEmpty()) {
final IClass contentsClass =
pa.getClassHierarchy().lookupClass(typeRef.getArrayElementType());
if (contentsClass.isInterface()) {
for (IClass implementor : analysisContext.concreteClassesForInterface(contentsClass)) {
final InstanceKey contentsIK = new ConcreteTypeKey(implementor);
final InstanceKeyElement elt = new InstanceKeyElement(contentsIK);
if (elts.add(elt)) {
iks.push(contentsIK);
}
}
} else {
InstanceKey contentsIK = new ConcreteTypeKey(contentsClass);
final InstanceKeyElement elt = new InstanceKeyElement(contentsIK);
if (elts.add(elt)) {
iks.push(contentsIK);
}
}
} else {
for (InstanceKey contentsIK : pointsToSet) {
final InstanceKeyElement elt = new InstanceKeyElement(contentsIK);
if (elts.add(elt)) {
iks.push(contentsIK);
}
}
}
continue;
}
for (IField field : clazz.getAllInstanceFields()) {
final TypeReference fieldTypeRef = field.getFieldTypeReference();
elts.add(new FieldElement(ik, field.getReference()));
final IClass fieldClass = analysisContext.getClassHierarchy().lookupClass(fieldTypeRef);
if (fieldTypeRef.isPrimitiveType() || fieldClass == null) {
continue;
} else if (fieldTypeRef.isArrayType()) {
PointerKey pk = pa.getHeapModel().getPointerKeyForInstanceField(ik, field);
final OrdinalSet<InstanceKey> pointsToSet = pa.getPointsToSet(pk);
if (pointsToSet.isEmpty()) {
InstanceKey fieldIK =
new ConcreteTypeKey(pa.getClassHierarchy().lookupClass(fieldTypeRef));
final InstanceKeyElement elt = new InstanceKeyElement(fieldIK);
if (elts.add(elt)) {
iks.push(fieldIK);
}
} else {
for (InstanceKey fieldIK : pointsToSet) {
final InstanceKeyElement elt = new InstanceKeyElement(fieldIK);
if (elts.add(elt)) {
iks.push(fieldIK);
}
}
}
} else if (fieldTypeRef.isReferenceType()) {
PointerKey pk = pa.getHeapModel().getPointerKeyForInstanceField(ik, field);
final OrdinalSet<InstanceKey> pointsToSet = pa.getPointsToSet(pk);
if (pointsToSet.isEmpty()
&& !analysisContext.getClassHierarchy().isInterface(fieldTypeRef)) {
InstanceKey fieldIK = new ConcreteTypeKey(fieldClass);
final InstanceKeyElement elt = new InstanceKeyElement(fieldIK);
if (elts.add(elt)) {
iks.push(fieldIK);
}
} else {
for (InstanceKey fieldIK : pointsToSet) {
final InstanceKeyElement elt = new InstanceKeyElement(fieldIK);
if (elts.add(elt)) {
iks.push(fieldIK);
}
}
}
} else {
}
}
}
return elts;
}
public ISCanDroidOptions getOptions() {
return analysisContext.getOptions();
}
public ClassHierarchy getClassHierarchy() {
return analysisContext.getClassHierarchy();
}
public AnalysisScope getScope() {
return analysisContext.getScope();
}
public List<Entrypoint> getEntrypoints() {
return entrypoints;
}
public CGNode nodeForMethod(IMethod method) {
return cg.getNode(method, Everywhere.EVERYWHERE);
}
}
| 15,072
| 34.973747
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/CLISCanDroidOptions.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.util;
import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions;
import java.io.File;
import java.net.URI;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
public class CLISCanDroidOptions implements ISCanDroidOptions {
private static final String VERBOSE = "verbose";
private static final String REFLECTION = "reflection";
private static final String ANDROID_LIB = "android-lib";
private static final String CHECK_POLICY = "check-policy";
private static final String TEST_CGB = "test-cgb";
private static final String SUMMARIES_FILE = "summaries-file";
private static final String PREFIX_ANALYSIS = "prefix-analysis";
private static final String THREAD_RUN_MAIN = "thread-run-main";
private static final String STDOUT_CALL_GRAPH = "stdout-call-graph";
private static final String MAIN_ENTRYPOINT = "main-entrypoint";
private static final String IFDS_EXPLORER = "IFDS-Explorer";
private static final String SEPARATE_ENTRIES = "separate-entries";
private static final String INCLUDE_LIBRARY = "include-library";
private static final String SYSTEM_TO_APK_CALL_GRAPH = "system-to-apk-call-graph";
private static final String ONE_LEVEL_CALL_GRAPH = "one-level-call-graph";
private static final String PARTIAL_CALL_GRAPH = "partial-call-graph";
private static final String CALL_GRAPH = "call-graph";
private final CommandLineParser parser = new DefaultParser();
private CommandLine line;
private final URI classpath;
private final String filename;
private final URI androidLib;
private final URI summariesFile;
private final ReflectionOptions reflectionOptions;
private static final String USAGE = "[options] <.apk or .jar>";
private final Options options = new Options();
{
options.addOption("h", "help", false, "print this message");
options.addOption(
Option.builder()
.longOpt(VERBOSE)
.desc("logging level (default INFO) [OFF, ERROR, WARN, INFO, DEBUG, TRACE, ALL]")
.hasArg()
.argName("level")
.build());
options.addOption("c", CALL_GRAPH, false, "create full call graph pdf");
options.addOption(
"p", PARTIAL_CALL_GRAPH, false, "create partial call graph pdf (Application only)");
options.addOption(
"o",
ONE_LEVEL_CALL_GRAPH,
false,
"create one level call graph pdf (Application + 1 level of System calls)");
options.addOption(
"s",
SYSTEM_TO_APK_CALL_GRAPH,
false,
"create system to apk callgraph (System + 1 level of Application calls)");
options.addOption("l", INCLUDE_LIBRARY, false, "analyze library in flow analysis");
options.addOption("e", SEPARATE_ENTRIES, false, "analyze each entry point separately");
options.addOption(
"i", IFDS_EXPLORER, false, "bring up a gui to analyze domainelements for flow analysis");
options.addOption(
"m", MAIN_ENTRYPOINT, false, "look for main methods and add them as entrypoints");
options.addOption("a", STDOUT_CALL_GRAPH, false, "output full call graph to stdout");
options.addOption(
"t", THREAD_RUN_MAIN, false, "use ServerThread.run as the entry point for analysis");
options.addOption("x", PREFIX_ANALYSIS, false, "run string prefix analysis");
options.addOption("f", SUMMARIES_FILE, true, "Use the specified summaries xml file");
options.addOption(
Option.builder()
.longOpt(TEST_CGB)
.desc("Only load the call graph, exit status indicates success")
.build());
options.addOption("y", CHECK_POLICY, false, "Check conformance with built-in policy");
options.addOption(
Option.builder()
.longOpt(ANDROID_LIB)
.desc("include ALIB in scope of analysis")
.hasArg()
.argName("ALIB")
.build());
options.addOption(
Option.builder()
.longOpt(REFLECTION)
.desc(
"FULL, NO_FLOW_TO_CASTS, NO_METHOD_INVOKE, NO_FLOW_TO_CASTS_NO_METHOD_INVOKE, ONE_FLOW_TO_CASTS_NO_METHOD_INVOKE, NO_STRING_CONSTANTS, NONE (Default)")
.hasArg()
.argName("option")
.build());
}
public CLISCanDroidOptions(String[] args, boolean reqArgs) {
try {
line = parser.parse(options, args);
} catch (ParseException exp) {
System.err.println("Unexpected exception: " + exp.getMessage());
System.err.println("Usage: " + USAGE);
System.exit(0);
}
if (hasOption("help")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(USAGE, options);
System.exit(0);
}
// handle verbosity
// parse this arg as a Logback level, then set the root logger level
// appropriately
if (!hasOption(ANDROID_LIB)) {
System.err.println("Please specify an android library");
System.exit(0);
}
classpath = processClasspath(reqArgs);
filename = processFilename();
androidLib = processURIArg(getOption(ANDROID_LIB));
summariesFile = processURIArg(getOption(SUMMARIES_FILE));
reflectionOptions = processReflectionOptions();
if (reqArgs && !(filename.endsWith(".apk") || filename.endsWith(".jar"))) {
System.err.println("Usage: " + USAGE);
System.exit(0);
}
}
private static URI processURIArg(String arg) {
if (arg == null) {
return null;
} else {
return new File(arg).toURI();
}
}
private URI processClasspath(boolean reqArgs) {
// getArgs() returns all args that are not recognized;
String[] myargs = line.getArgs();
if ((myargs.length != 1 || !(myargs[0].endsWith(".apk") || myargs[0].endsWith(".jar")))
&& reqArgs) {
System.err.println("Usage: " + USAGE);
System.exit(0);
}
return processURIArg(myargs[0]);
}
private String processFilename() {
if (classpath == null) return null;
return new File(classpath).getName();
}
private ReflectionOptions processReflectionOptions() {
final String reflection = getOption(REFLECTION);
if (reflection == null) {
return ReflectionOptions.NONE;
} else {
return ReflectionOptions.valueOf(reflection);
}
}
private boolean hasOption(String s) {
return line != null && line.hasOption(s);
}
private String getOption(String s) {
return line.getOptionValue(s);
}
@Override
public boolean pdfCG() {
return hasOption(CALL_GRAPH);
}
@Override
public boolean pdfPartialCG() {
return hasOption(PARTIAL_CALL_GRAPH);
}
@Override
public boolean pdfOneLevelCG() {
return hasOption(ONE_LEVEL_CALL_GRAPH);
}
@Override
public boolean systemToApkCG() {
return hasOption(SYSTEM_TO_APK_CALL_GRAPH);
}
@Override
public boolean stdoutCG() {
return hasOption(STDOUT_CALL_GRAPH);
}
@Override
public boolean includeLibrary() {
return hasOption(INCLUDE_LIBRARY);
}
@Override
public boolean separateEntries() {
return hasOption(SEPARATE_ENTRIES);
}
@Override
public boolean ifdsExplorer() {
return hasOption(IFDS_EXPLORER);
}
@Override
public boolean addMainEntrypoints() {
return hasOption(MAIN_ENTRYPOINT);
}
@Override
public boolean useThreadRunMain() {
return hasOption(THREAD_RUN_MAIN);
}
@Override
public boolean stringPrefixAnalysis() {
return hasOption(PREFIX_ANALYSIS);
}
@Override
public boolean testCGBuilder() {
return hasOption(TEST_CGB);
}
@Override
public boolean useDefaultPolicy() {
return hasOption(CHECK_POLICY);
}
@Override
public URI getClasspath() {
return classpath;
}
@Override
public String getFilename() {
return filename;
}
@Override
public URI getAndroidLibrary() {
return androidLib;
}
@Override
public ReflectionOptions getReflectionOptions() {
return reflectionOptions;
}
@Override
public URI getSummariesURI() {
return summariesFile;
}
@Override
public boolean classHierarchyWarnings() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean cgBuilderWarnings() {
// TODO Auto-generated method stub
return true;
}
}
| 10,472
| 31.830721
| 167
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/DexDotUtil.java
|
/*
* Copyright (c) 2002 - 2006, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Steve Suh <suhsteve@gmail.com> - added cleanUpString
*/
package org.scandroid.util;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.Iterator2Collection;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.viz.DotUtil;
import com.ibm.wala.util.viz.NodeDecorator;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
public class DexDotUtil extends DotUtil {
/** possible output formats for dot */
// public static enum DotOutputType {
// PS, SVG, PDF, EPS
// }
private static final DotOutputType outputType = DotOutputType.PDF;
private static int fontSize = 6;
private static final String fontColor = "black";
private static final String fontName = "Arial";
// public static void setOutputType(DotOutputType outType) {
// outputType = outType;
// }
// public static DotOutputType getOutputType() {
// return outputType;
// }
private static String outputTypeCmdLineParam() {
switch (outputType) {
case PS:
return "-Tps";
case EPS:
return "-Teps";
case SVG:
return "-Tsvg";
case PDF:
return "-Tpdf";
default:
Assertions.UNREACHABLE();
return null;
}
}
/** Some versions of dot appear to croak on long labels. Reduce this if so. */
private static final int MAX_LABEL_LENGTH = Integer.MAX_VALUE;
/** */
public static <T> void dotify(
Graph<T> g, NodeDecorator<T> labels, String dotFile, String outputFile, String dotExe)
throws WalaException {
dotify(g, labels, null, dotFile, outputFile, dotExe);
}
public static <T> void dotify(
Graph<T> g,
NodeDecorator<T> labels,
String title,
String dotFile,
String outputFile,
String dotExe)
throws WalaException {
if (g == null) {
throw new IllegalArgumentException("g is null");
}
File f = DexDotUtil.writeDotFile(g, labels, title, dotFile);
spawnDot(dotExe, outputFile, f);
}
public static void spawnDot(String dotExe, String outputFile, File dotFile) throws WalaException {
if (dotFile == null) {
throw new IllegalArgumentException("dotFile is null");
}
String[] cmdarray = {
dotExe, outputTypeCmdLineParam(), "-o", outputFile, "-v", dotFile.getAbsolutePath()
};
BufferedInputStream output = null;
BufferedInputStream error = null;
try {
Process p = Runtime.getRuntime().exec(cmdarray);
output = new BufferedInputStream(p.getInputStream());
error = new BufferedInputStream(p.getErrorStream());
boolean repeat = true;
while (repeat) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
// just ignore and continue
}
if (output.available() > 0) {
byte[] data = new byte[output.available()];
output.read(data);
}
if (error.available() > 0) {
byte[] data = new byte[error.available()];
error.read(data);
}
try {
p.exitValue();
// if we get here, the process has terminated
repeat = false;
} catch (IllegalThreadStateException e) {
// this means the process has not yet terminated.
repeat = true;
}
}
} catch (IOException e) {
e.printStackTrace();
throw new WalaException("IOException in " + DotUtil.class);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (error != null) {
try {
error.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static <T> File writeDotFile(
Graph<T> g, NodeDecorator<T> labels, String title, String dotfile) throws WalaException {
if (g == null) {
throw new IllegalArgumentException("g is null");
}
StringBuilder dotStringBuffer = dotOutput(g, labels, title);
// retrieve the filename parameter to this component, a String
if (dotfile == null) {
throw new WalaException("internal error: null filename parameter");
}
try {
File f = new File(dotfile);
try (final FileWriter fw = new FileWriter(f)) {
fw.write(dotStringBuffer.toString());
}
return f;
} catch (Exception e) {
throw new WalaException("Error writing dot file " + dotfile, e);
}
}
/** @return StringBuffer holding dot output representing G */
public static <T> StringBuilder dotOutput(Graph<T> g, NodeDecorator<T> labels, String title)
throws WalaException {
StringBuilder result = new StringBuilder("digraph \"DirectedGraph\" {\n");
if (title != null) {
result
.append("graph [label = \"")
.append(title)
.append("\", labelloc=t, concentrate = true];");
} else {
result.append("graph [concentrate = true];");
}
String rankdir = getRankDir();
if (rankdir != null) {
result.append("rankdir=").append(rankdir).append(';');
}
String fontsizeStr = "fontsize=" + fontSize;
String fontcolorStr = ",fontcolor=" + fontColor;
String fontnameStr = ",fontname=" + fontName;
result.append("center=true;");
result.append(fontsizeStr);
result.append(";node [ color=blue,shape=\"box\"");
result.append(fontsizeStr);
result.append(fontcolorStr);
result.append(fontnameStr);
result.append("];edge [ color=black,");
result.append(fontsizeStr);
result.append(fontcolorStr);
result.append(fontnameStr);
result.append("]; \n");
Collection<T> dotNodes = computeDotNodes(g);
outputNodes(labels, result, dotNodes);
for (T n : g) {
for (T s : Iterator2Iterable.make(g.getSuccNodes(n))) {
result.append(' ');
result.append(getPort(n, labels));
result.append(" -> ");
result.append(getPort(s, labels));
result.append(" \n");
}
}
result.append("\n}");
return result;
}
private static <T> void outputNodes(
NodeDecorator<T> labels, StringBuilder result, Collection<T> dotNodes) throws WalaException {
for (T t : dotNodes) {
outputNode(labels, result, t);
}
}
private static <T> void outputNode(NodeDecorator<T> labels, StringBuilder result, T n)
throws WalaException {
result.append(" ");
result.append('\"');
result.append(getLabel(n, labels));
result.append('\"');
result.append(decorateNode(n, labels));
}
/** Compute the nodes to visualize */
private static <T> Collection<T> computeDotNodes(Graph<T> g) {
return Iterator2Collection.toSet(g.iterator());
}
private static String getRankDir() {
return null;
}
/**
* @param n node to decorate
* @param d decorating master
*/
private static <T> String decorateNode(
@SuppressWarnings("unused") T n, @SuppressWarnings("unused") NodeDecorator<T> d) {
return " [ ]\n";
}
private static <T> String getLabel(T o, NodeDecorator<T> d) throws WalaException {
String result = null;
if (d == null) {
// result = o.toString();
result = cleanUpString(o.toString());
} else {
result = d.getLabel(o);
result = result == null ? cleanUpString(o.toString()) : cleanUpString(result);
}
if (result.length() >= MAX_LABEL_LENGTH) {
result = result.substring(0, MAX_LABEL_LENGTH - 3) + "...";
}
return result;
}
private static <T> String getPort(T o, NodeDecorator<T> d) throws WalaException {
return '"' + getLabel(o, d) + '"';
}
public static int getFontSize() {
return fontSize;
}
public static void setFontSize(int fontSize) {
DexDotUtil.fontSize = fontSize;
}
private static String cleanUpString(String s) {
if (!s.isEmpty() && s.startsWith("Node: ")) {
String[] nodeString = s.split(",");
if (nodeString.length >= 3) {
String className = nodeString[1];
String methodName = nodeString[2];
return className.trim() + "\\n" + methodName.substring(0, methodName.indexOf(" > ")).trim();
}
}
return s;
}
}
| 8,818
| 28.396667
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/EmptyProgressMonitor.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.util;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
public final class EmptyProgressMonitor implements IProgressMonitor {
@Override
public void beginTask(String task, int totalWork) {}
@Override
public boolean isCanceled() {
return false;
}
@Override
public void done() {}
@Override
public void worked(int units) {}
@Override
public void subTask(String subTask) {}
@Override
public void cancel() {}
@Override
public String getCancelMessage() {
return "EmptyProgressMonitor canceled.";
}
}
| 2,473
| 31.12987
| 79
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/EntryPoints.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.util;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.core.util.strings.StringStuff;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.DefaultEntrypoint;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.types.ClassLoaderReference;
import com.ibm.wala.types.MethodReference;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.scandroid.spec.AndroidSpecs;
import org.scandroid.spec.MethodNamePattern;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class EntryPoints {
private String pathToApkFile;
private String pathToApkTool;
private String pathToJava;
private String tempFolder;
private ArrayList<String[]> ActivityIntentList;
private ArrayList<String[]> ReceiverIntentList;
private ArrayList<String[]> ServiceIntentList;
private LinkedList<Entrypoint> entries;
public void listenerEntryPoints(ClassHierarchy cha) {
ArrayList<MethodReference> entryPointMRs = new ArrayList<>();
// onLocation
entryPointMRs.add(
StringStuff.makeMethodReference(
"android.location.LocationListener.onLocationChanged(Landroid/location/Location;)V"));
for (MethodReference mr : entryPointMRs)
for (IMethod im : cha.getPossibleTargets(mr)) {
// limit to functions defined within the application
if (im.getReference()
.getDeclaringClass()
.getClassLoader()
.equals(ClassLoaderReference.Application)) {
entries.add(new DefaultEntrypoint(im, cha));
}
}
}
public static List<Entrypoint> defaultEntryPoints(ClassHierarchy cha) {
List<Entrypoint> entries = new ArrayList<>();
for (MethodNamePattern mnp : new AndroidSpecs().getEntrypointSpecs()) {
for (IMethod im : mnp.getPossibleTargets(cha)) {
// limit to functions defined within the application
if (LoaderUtils.fromLoader(im, ClassLoaderReference.Application)) {
entries.add(new DefaultEntrypoint(im, cha));
}
}
}
return entries;
}
public void activityModelEntry(ClassHierarchy cha) {
String[] methodReferences = {
"android.app.Activity.ActivityModel()V",
// find all onActivityResult functions and add them as entry points
// "android.app.Activity.onActivityResult(IILandroid/content/Intent;)V",
//
// // SERVICE ENTRY POINTS
// "android.app.Service.onCreate()V",
// "android.app.Service.onStart(Landroid/content/Intent;I)V",
// "android.app.Service.onBind(Landroid/content/Intent;)Landroid/os/IBinder;",
// "android.app.Service.onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)B"
};
for (String methodReference : methodReferences) {
MethodReference mr = StringStuff.makeMethodReference(methodReference);
for (IMethod im : cha.getPossibleTargets(mr)) {
// limit to functions defined within the application
if (im.getReference()
.getDeclaringClass()
.getClassLoader()
.equals(ClassLoaderReference.Application)) {
entries.add(new DefaultEntrypoint(im, cha));
}
}
}
}
public void addTestEntry(ClassHierarchy cha) {
String[] methodReferences = {
// "Test.Apps.Outer$PrivateInnerClass.printNum()V",
// "Test.Apps.Outer$PublicInnerClass.printNum()V"
// "Test.Apps.Outer.<init>()V"
// "Test.Apps.Outer.getNum()I"
// "Test.Apps.FixpointSolver.someMethod(LTest/Apps/GenericSink;LTest/Apps/GenericSource;)V"
// "Test.Apps.Outer$PrivateInnerClass.testParameters(LTest/Apps/GenericSink;LTest/Apps/GenericSource;)V"
"android.view.View.setOnClickListener(Landroid/view/View$OnClickListener;)V",
};
for (String methodReference : methodReferences) {
MethodReference mr = StringStuff.makeMethodReference(methodReference);
for (IMethod im : cha.getPossibleTargets(mr)) {
entries.add(new DefaultEntrypoint(im, cha));
}
}
}
public void unpackApk(String classpath) {
StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator);
pathToApkFile = st.nextToken();
// String pathToApkTool = new String(System.getProperty("user.dir").replace(" ", "\\ ") +
// File.separator + "apktool" +File.separator);
pathToApkTool = System.getProperty("user.dir") + File.separator + "apktool" + File.separator;
// String pathToJava = new String(System.getProperty("java.home").replace(" ", "\\ ") +
// File.separator + "bin" + File.separator);
pathToJava = System.getProperty("java.home") + File.separator + "bin" + File.separator;
String s = null;
// String command = new String(pathToJava + "java -jar " + pathToApkTool + "apktool.jar d -f " +
// pathToApkFile + " " + pathToApkTool + tempFolder);
// System.out.println("command: " + command);
ProcessBuilder pb =
new ProcessBuilder(
pathToJava + "java",
"-jar",
pathToApkTool + "apktool.jar",
"d",
"-f",
pathToApkFile,
pathToApkTool + tempFolder);
try {
// Process p = Runtime.getRuntime().exec(command);
Process p = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
while ((s = stdInput.readLine()) != null) {}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.err.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println( System.getProperty("user.dir") );
// System.out.println("classpath: " + st.nextToken());
}
public void readXMLFile() {
try {
File fXmlFile = new File(pathToApkTool + tempFolder + File.separator + "AndroidManifest.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
// System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
String basePackage = doc.getDocumentElement().getAttribute("package");
NodeList iList = doc.getElementsByTagName("intent-filter");
System.out.println("-----------------------");
for (int i = 0; i < iList.getLength(); i++) {
Node nNode = iList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
// System.out.println(eElement.getNodeName());
populateIntentList(basePackage, eElement);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = nlList.item(0);
return nValue.getNodeValue();
}
private void populateIntentList(String basePackage, Element eElement) {
ArrayList<String[]> IntentList;
NodeList actionList = eElement.getElementsByTagName("action");
Node parent = eElement.getParentNode();
IntentList = chooseIntentList(parent.getNodeName());
String IntentClass = parent.getAttributes().getNamedItem("android:name").getTextContent();
for (int i = 0; i < actionList.getLength(); i++) {
Node nNode = actionList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
IntentList.add(new String[2]);
IntentList.get(IntentList.size() - 1)[0] =
actionList.item(i).getAttributes().getNamedItem("android:name").getTextContent();
if (IntentClass.startsWith(basePackage))
IntentList.get(IntentList.size() - 1)[1] = IntentClass;
else {
if (IntentClass.startsWith("."))
IntentList.get(IntentList.size() - 1)[1] = basePackage + IntentClass;
else {
IntentList.get(IntentList.size() - 1)[1] = basePackage + '.' + IntentClass;
IntentList.add(new String[2]);
IntentList.get(IntentList.size() - 1)[0] =
actionList.item(i).getAttributes().getNamedItem("android:name").getTextContent();
IntentList.get(IntentList.size() - 1)[1] = IntentClass;
}
// IntentList.get(IntentList.size()-1)[1] = basePackage + (IntentClass.startsWith(".") ?
// IntentClass : "." + IntentClass);
}
// System.out.println(IntentList.get(IntentList.size()-1)[0] + " ~> " +
// IntentList.get(IntentList.size()-1)[1]);
}
}
}
@SuppressWarnings("unused")
private void populateEntryPoints(ClassHierarchy cha) {
String method = null;
IMethod im = null;
for (String[] intent : ActivityIntentList) {
// method = IntentToMethod(intent[0]);
method = "onCreate(Landroid/os/Bundle;)V";
im = cha.resolveMethod(StringStuff.makeMethodReference(intent[1] + '.' + method));
if (im != null) entries.add(new DefaultEntrypoint(im, cha));
}
for (String[] intent : ReceiverIntentList) {
// Seems that every broadcast receiver can be an entrypoints?
// method = IntentToMethod(intent[0]);
method = "onReceive(Landroid/content/Context;Landroid/content/Intent;)V";
im = cha.resolveMethod(StringStuff.makeMethodReference(intent[1] + '.' + method));
if (im != null) entries.add(new DefaultEntrypoint(im, cha));
}
// IMethod im =
// cha.resolveMethod(StringStuff.makeMethodReference("android.app.Activity.onCreate(Landroid/os/Bundle;)V"));
// entries.add(new DefaultEntrypoint(im, cha));
}
@SuppressWarnings("unused")
private static String IntentToMethod(String intent) {
if (intent.contentEquals("android.intent.action.MAIN")
|| intent.contentEquals("android.media.action.IMAGE_CAPTURE")
|| intent.contentEquals("android.media.action.VIDEO_CAPTURE")
|| intent.contentEquals("android.media.action.STILL_IMAGE_CAMERA")
|| intent.contentEquals("android.intent.action.MUSIC_PLAYER")
|| intent.contentEquals("android.media.action.VIDEO_CAMERA"))
return "onCreate(Landroid/os/Bundle;)V";
// else if (intent.contentEquals("android.intent.action.BOOT_COMPLETED") ||
// intent.contentEquals("android.appwidget.action.APPWIDGET_UPDATE") ||
// intent.contentEquals("android.provider.Telephony.SECRET_CODE") )
// return "onReceive(Landroid/content/Context;Landroid/content/Intent;)V";
else return null;
}
private ArrayList<String[]> chooseIntentList(String name) {
switch (name) {
case "receiver":
return ReceiverIntentList;
case "service":
return ServiceIntentList;
default:
return ActivityIntentList;
// throw new UnimplementedError("EntryPoints intent category not yet covered: " +
// name);
}
}
public LinkedList<Entrypoint> getEntries() {
return entries;
}
}
| 13,694
| 38.017094
| 113
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/IEntryPointSpecifier.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.util;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import java.util.List;
public interface IEntryPointSpecifier {
/** @return a list of entrypoints for the given analysis context */
List<Entrypoint> specify(AndroidAnalysisContext analysisContext);
}
| 2,286
| 44.74
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/ISCanDroidOptions.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.util;
import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions;
import java.net.URI;
/**
* @author acfoltzer
* <p>An abstraction of the options for a SCanDroid execution
*/
public interface ISCanDroidOptions {
/** @return whether to create a full call graph pdf */
boolean pdfCG();
/** @return whether to create an application-only call graph pdf */
boolean pdfPartialCG();
/** @return whether to create a call graph of application + 1 level of system calls */
boolean pdfOneLevelCG();
/** @return whether to create a system + 1 level of application call graph */
boolean systemToApkCG();
/** @return whether to print a full call graph to stdout */
boolean stdoutCG();
/** @return whether to include the Android library in flow analysis */
boolean includeLibrary();
/** @return whether to analyze each entry point separately */
boolean separateEntries();
/** @return whether to bring up a GUI to analyze domain elements for flow analysis */
boolean ifdsExplorer();
/** @return whether to look for main methods and add them as entry points */
boolean addMainEntrypoints();
/** @return whether to use ServerThread.run as the entry point for analysis */
boolean useThreadRunMain();
/** @return whether to run string prefix analysis */
boolean stringPrefixAnalysis();
/** @return whether to stop after generating the call graph */
boolean testCGBuilder();
/** @return whether to log class hierarchy warnings */
boolean classHierarchyWarnings();
/** @return whether to log call graph builder warnings */
boolean cgBuilderWarnings();
/** @return whether to check conformance to built-in policy */
boolean useDefaultPolicy();
/** @return the URI pointing to the jar or apk to analyze */
URI getClasspath();
/** @return the filename portion of the classpath to analyze */
String getFilename();
/** @return a URI to the Android library jar */
URI getAndroidLibrary();
/** @return the ReflectionOptions for this run */
ReflectionOptions getReflectionOptions();
/** @return a URI to the XML method summaries file */
URI getSummariesURI();
}
| 4,178
| 36.648649
| 100
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/LoaderUtils.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
*
* Copyright (c) 2009-2012,
*
* Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>)
* Steve Suh <suhsteve@gmail.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
package org.scandroid.util;
import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.IMethod;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.types.ClassLoaderReference;
public class LoaderUtils {
public static boolean fromLoader(CGNode node, ClassLoaderReference clr) {
IClass declClass = node.getMethod().getDeclaringClass();
ClassLoaderReference nodeClRef = declClass.getClassLoader().getReference();
return nodeClRef.equals(clr);
}
public static boolean fromLoader(IMethod method, ClassLoaderReference clr) {
IClass declClass = method.getDeclaringClass();
ClassLoaderReference nodeClRef = declClass.getClassLoader().getReference();
return nodeClRef.equals(clr);
}
public static boolean fromLoader(IClass declClass, ClassLoaderReference clr) {
ClassLoaderReference nodeClRef = declClass.getClassLoader().getReference();
return nodeClRef.equals(clr);
}
}
| 2,914
| 36.371795
| 86
|
java
|
WALA
|
WALA-master/scandroid/src/main/java/org/scandroid/util/ThrowingSSAInstructionVisitor.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released under the terms listed below.
*
*/
/*
* Copyright (c) 2009-2012,
*
* <p>Galois, Inc. (Aaron Tomb <atomb@galois.com>, Rogan Creswick <creswick@galois.com>, Adam
* Foltzer <acfoltzer@galois.com>) Steve Suh <suhsteve@gmail.com>
*
* <p>All rights reserved.
*
* <p>Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* <p>1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* <p>2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* <p>3. The names of the contributors may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.scandroid.util;
import com.ibm.wala.ssa.SSAArrayLengthInstruction;
import com.ibm.wala.ssa.SSAArrayLoadInstruction;
import com.ibm.wala.ssa.SSAArrayStoreInstruction;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSACheckCastInstruction;
import com.ibm.wala.ssa.SSAComparisonInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAConversionInstruction;
import com.ibm.wala.ssa.SSAGetCaughtExceptionInstruction;
import com.ibm.wala.ssa.SSAGetInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstanceofInstruction;
import com.ibm.wala.ssa.SSAInstruction.IVisitor;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SSALoadMetadataInstruction;
import com.ibm.wala.ssa.SSAMonitorInstruction;
import com.ibm.wala.ssa.SSANewInstruction;
import com.ibm.wala.ssa.SSAPhiInstruction;
import com.ibm.wala.ssa.SSAPiInstruction;
import com.ibm.wala.ssa.SSAPutInstruction;
import com.ibm.wala.ssa.SSAReturnInstruction;
import com.ibm.wala.ssa.SSASwitchInstruction;
import com.ibm.wala.ssa.SSAThrowInstruction;
import com.ibm.wala.ssa.SSAUnaryOpInstruction;
public class ThrowingSSAInstructionVisitor implements IVisitor {
private final RuntimeException e;
public ThrowingSSAInstructionVisitor(RuntimeException e) {
this.e = e;
}
@Override
public void visitGoto(SSAGotoInstruction instruction) {
throw e;
}
@Override
public void visitArrayLoad(SSAArrayLoadInstruction instruction) {
throw e;
}
@Override
public void visitArrayStore(SSAArrayStoreInstruction instruction) {
throw e;
}
@Override
public void visitBinaryOp(SSABinaryOpInstruction instruction) {
throw e;
}
@Override
public void visitUnaryOp(SSAUnaryOpInstruction instruction) {
throw e;
}
@Override
public void visitConversion(SSAConversionInstruction instruction) {
throw e;
}
@Override
public void visitComparison(SSAComparisonInstruction instruction) {
throw e;
}
@Override
public void visitConditionalBranch(SSAConditionalBranchInstruction instruction) {
throw e;
}
@Override
public void visitSwitch(SSASwitchInstruction instruction) {
throw e;
}
@Override
public void visitReturn(SSAReturnInstruction instruction) {
throw e;
}
@Override
public void visitGet(SSAGetInstruction instruction) {
throw e;
}
@Override
public void visitPut(SSAPutInstruction instruction) {
throw e;
}
@Override
public void visitInvoke(SSAInvokeInstruction instruction) {
throw e;
}
@Override
public void visitNew(SSANewInstruction instruction) {
throw e;
}
@Override
public void visitArrayLength(SSAArrayLengthInstruction instruction) {
throw e;
}
@Override
public void visitThrow(SSAThrowInstruction instruction) {
throw e;
}
@Override
public void visitMonitor(SSAMonitorInstruction instruction) {
throw e;
}
@Override
public void visitCheckCast(SSACheckCastInstruction instruction) {
throw e;
}
@Override
public void visitInstanceof(SSAInstanceofInstruction instruction) {
throw e;
}
@Override
public void visitPhi(SSAPhiInstruction instruction) {
throw e;
}
@Override
public void visitPi(SSAPiInstruction instruction) {
throw e;
}
@Override
public void visitGetCaughtException(SSAGetCaughtExceptionInstruction instruction) {
throw e;
}
@Override
public void visitLoadMetadata(SSALoadMetadataInstruction instruction) {
throw e;
}
}
| 5,567
| 28.460317
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/bench/AddBytecodeDebug.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.bench;
import com.ibm.wala.shrike.shrikeBT.DupInstruction;
import com.ibm.wala.shrike.shrikeBT.ExceptionHandler;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MethodEditor;
import com.ibm.wala.shrike.shrikeBT.MethodEditor.Output;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
/**
* This is a demo class.
*
* <p>Class files are taken as input arguments (or if there are none, from standard input). The
* methods in those files are instrumented: we insert a System.err.println() at ever method call,
* and a System.err.println() at every method entry.
*
* <p>In Unix, I run it like this: java -cp ~/dev/shrike/shrike
* com.ibm.wala.shrikeBT.shrikeCT.tools.Bench test.jar -o output.jar
*
* <p>The instrumented classes are placed in the directory "output" under the current directory.
* Disassembled code is written to the file "report" under the current directory.
*
* @author Rob O' Callahan
*/
public class AddBytecodeDebug {
private static OfflineInstrumenter instrumenter;
public static void main(String[] args) throws Exception {
for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter();
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args);
instrumenter.setPassUnmodifiedClasses(true);
instrumenter.beginTraversal();
ClassInstrumenter ci;
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w);
}
instrumenter.close();
}
}
}
private static void doClass(final ClassInstrumenter ci, Writer w) throws Exception {
final String className = ci.getReader().getName();
w.write("Class: " + className + '\n');
w.flush();
ci.enableFakeLineNumbers(10000);
for (int m = 0; m < ci.getReader().getMethodCount(); m++) {
MethodData d = ci.visitMethod(m);
if (d != null) {
d.setHasChanged();
MethodEditor me = new MethodEditor(d);
me.beginPass();
ExceptionHandler[][] handlers = me.getHandlers();
boolean[] putDumperAt = new boolean[handlers.length];
for (ExceptionHandler[] handler : handlers) {
for (ExceptionHandler element : handler) {
int offset = element.getHandler();
if (!putDumperAt[offset]) {
putDumperAt[offset] = true;
me.insertBefore(
offset,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(DupInstruction.make(0));
w.emit(Util.makeInvoke(Throwable.class, "printStackTrace", new Class[0]));
}
});
}
}
}
me.applyPatches();
}
}
if (ci.isChanged()) {
ClassWriter cw = ci.emitClass();
instrumenter.outputModifiedClass(ci, cw);
}
}
}
| 3,634
| 33.951923
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/bench/Bench.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.bench;
import com.ibm.wala.shrike.shrikeBT.ConditionalBranchInstruction;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.Disassembler;
import com.ibm.wala.shrike.shrikeBT.GetInstruction;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.Instruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MethodEditor;
import com.ibm.wala.shrike.shrikeBT.MethodEditor.Output;
import com.ibm.wala.shrike.shrikeBT.ReturnInstruction;
import com.ibm.wala.shrike.shrikeBT.ThrowInstruction;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.analysis.Verifier;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTDecoder;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassConstants;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.Writer;
/**
* This is a demo class.
*
* <p>Class files are taken as input arguments (or if there are none, from standard input). The
* methods in those files are instrumented: we insert a System.err.println() at ever method call,
* and a System.err.println() at every method entry.
*
* <p>In Unix, I run it like this: java -cp ~/dev/shrike/shrike
* com.ibm.wala.shrikeBT.shrikeCT.tools.Bench test.jar -o output.jar
*
* <p>The instrumented classes are placed in the directory "output" under the current directory.
* Disassembled code is written to the file "report" under the current directory.
*/
public class Bench {
private static final boolean disasm = true;
private static final boolean verify = true;
private static OfflineInstrumenter instrumenter;
private static final boolean doEntry = true;
private static boolean doExit = false;
private static boolean doException = false;
public static void main(String[] args) throws Exception {
for (int i = 0; i < 1; i++) {
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args);
if (args.length > 0) {
switch (args[0]) {
case "-doexit":
doExit = true;
break;
case "-doexception":
doExit = true;
doException = true;
break;
}
}
instrumenter = new OfflineInstrumenter();
instrumenter.setPassUnmodifiedClasses(true);
instrumenter.beginTraversal();
ClassInstrumenter ci;
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w);
}
}
instrumenter.close();
}
}
static final String fieldName = "_Bench_enable_trace";
// Keep these commonly used instructions around
static final Instruction getSysErr = Util.makeGet(System.class, "err");
static final Instruction callPrintln =
Util.makeInvoke(PrintStream.class, "println", new Class[] {String.class});
private static void doClass(final ClassInstrumenter ci, Writer w) throws Exception {
final String className = ci.getReader().getName();
w.write("Class: " + className + '\n');
w.flush();
for (int m = 0; m < ci.getReader().getMethodCount(); m++) {
MethodData d = ci.visitMethod(m);
// d could be null, e.g., if the method is abstract or native
if (d != null) {
w.write(
"Instrumenting "
+ ci.getReader().getMethodName(m)
+ ' '
+ ci.getReader().getMethodType(m)
+ ":\n");
w.flush();
if (disasm) {
w.write("Initial ShrikeBT code:\n");
new Disassembler(d).disassembleTo(w);
w.flush();
}
if (verify) {
Verifier v = new Verifier(d);
v.verify();
}
MethodEditor me = new MethodEditor(d);
me.beginPass();
if (doEntry) {
final String msg0 =
"Entering call to "
+ Util.makeClass('L' + ci.getReader().getName() + ';')
+ '.'
+ ci.getReader().getMethodName(m);
final int noTraceLabel = me.allocateLabel();
me.insertAtStart(
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(
GetInstruction.make(
Constants.TYPE_boolean,
CTDecoder.convertClassToType(className),
fieldName,
true));
w.emit(ConstantInstruction.make(0));
w.emit(
ConditionalBranchInstruction.make(
Constants.TYPE_int,
ConditionalBranchInstruction.Operator.EQ,
noTraceLabel));
w.emit(getSysErr);
w.emit(ConstantInstruction.makeString(msg0));
w.emit(callPrintln);
w.emitLabel(noTraceLabel);
}
});
}
if (doExit) {
final String msg0 =
"Exiting call to "
+ Util.makeClass('L' + ci.getReader().getName() + ';')
+ '.'
+ ci.getReader().getMethodName(m);
IInstruction[] instr = me.getInstructions();
for (int i = 0; i < instr.length; i++) {
if (instr[i] instanceof ReturnInstruction) {
final int noTraceLabel = me.allocateLabel();
me.insertBefore(
i,
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(
GetInstruction.make(
Constants.TYPE_boolean,
CTDecoder.convertClassToType(className),
fieldName,
true));
w.emit(ConstantInstruction.make(0));
w.emit(
ConditionalBranchInstruction.make(
Constants.TYPE_int,
ConditionalBranchInstruction.Operator.EQ,
noTraceLabel));
w.emit(getSysErr);
w.emit(ConstantInstruction.makeString(msg0));
w.emit(callPrintln);
w.emitLabel(noTraceLabel);
}
});
}
}
}
if (doException) {
final String msg0 =
"Exception exiting call to "
+ Util.makeClass('L' + ci.getReader().getName() + ';')
+ '.'
+ ci.getReader().getMethodName(m);
final int noTraceLabel = me.allocateLabel();
me.addMethodExceptionHandler(
null,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(
GetInstruction.make(
Constants.TYPE_boolean,
CTDecoder.convertClassToType(className),
fieldName,
true));
w.emit(ConstantInstruction.make(0));
w.emit(
ConditionalBranchInstruction.make(
Constants.TYPE_int,
ConditionalBranchInstruction.Operator.EQ,
noTraceLabel));
w.emit(getSysErr);
w.emit(ConstantInstruction.makeString(msg0));
w.emit(callPrintln);
w.emitLabel(noTraceLabel);
w.emit(ThrowInstruction.make(false));
}
});
}
// this updates the data d
me.applyPatches();
if (disasm) {
w.write("Final ShrikeBT code:\n");
new Disassembler(d).disassembleTo(w);
w.flush();
}
}
}
if (ci.isChanged()) {
ClassWriter cw = ci.emitClass();
cw.addField(
ClassConstants.ACC_PUBLIC | ClassConstants.ACC_STATIC,
fieldName,
Constants.TYPE_boolean,
new ClassWriter.Element[0]);
instrumenter.outputModifiedClass(ci, cw);
}
}
}
| 9,099
| 35.111111
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/bench/InterfaceAnalyzer.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.bench;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
/** @author roca */
public class InterfaceAnalyzer {
static final class TypeStats {
int totalOccurrences;
int methodOccurrences;
int publicMethodOccurrences;
int foreignPublicMethodOccurrences;
int lastMUID;
}
static final HashMap<String, TypeStats> typeStats = new HashMap<>();
public static void main(String[] args) throws Exception {
OfflineInstrumenter instrumenter = new OfflineInstrumenter();
try (final Writer w = new BufferedWriter(new OutputStreamWriter(System.out))) {
args = instrumenter.parseStandardArgs(args);
instrumenter.beginTraversal();
ClassInstrumenter ci;
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci.getReader());
}
instrumenter.close();
w.write("Type\t# Total\t# Method\t# Public Method\t# Public Method as Foreign\n");
for (Map.Entry<String, TypeStats> entry : typeStats.entrySet()) {
TypeStats t = entry.getValue();
w.write(
entry.getKey()
+ '\t'
+ t.totalOccurrences
+ '\t'
+ t.methodOccurrences
+ '\t'
+ t.publicMethodOccurrences
+ '\t'
+ t.foreignPublicMethodOccurrences
+ '\n');
}
}
}
static int methodUID = 0;
private static void doClass(ClassReader reader) throws Exception {
if ((reader.getAccessFlags() & Constants.ACC_INTERFACE) != 0
&& (reader.getAccessFlags() & Constants.ACC_PUBLIC) != 0) {
String cType = Util.makeType(reader.getName());
for (int m = 0; m < reader.getMethodCount(); m++) {
String sig = reader.getMethodType(m);
String[] params = Util.getParamsTypes(null, sig);
int flags = reader.getMethodAccessFlags(m);
int mUID = methodUID++;
for (String param : params) {
doType(flags, param, cType, mUID);
}
doType(flags, Util.getReturnType(sig), cType, mUID);
}
}
}
private static void doType(int flags, String type, String containerType, int mUID) {
TypeStats t = typeStats.get(type);
if (t == null) {
t = new TypeStats();
typeStats.put(type, t);
}
t.totalOccurrences++;
if (t.lastMUID != mUID) {
t.methodOccurrences++;
if ((flags & Constants.ACC_PUBLIC) != 0) {
t.publicMethodOccurrences++;
String elemType = type;
while (Util.isArrayType(elemType)) {
elemType = elemType.substring(1);
}
if (!Util.isPrimitiveType(elemType)
&& !packagePart(elemType, 2).equals(packagePart(containerType, 2))) {
t.foreignPublicMethodOccurrences++;
}
}
}
t.lastMUID = mUID;
}
private static String packagePart(String t, int count) {
String c = Util.makeClass(t);
int lastDot = -1;
for (int i = 0; i < count; i++) {
int dot = c.indexOf('.', lastDot + 1);
if (dot < 0) {
return c;
}
lastDot = dot;
}
return c.substring(0, lastDot);
}
}
| 3,886
| 29.367188
| 88
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/bench/Mangler.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.bench;
import com.ibm.wala.shrike.shrikeBT.ConditionalBranchInstruction;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.Disassembler;
import com.ibm.wala.shrike.shrikeBT.DupInstruction;
import com.ibm.wala.shrike.shrikeBT.IArrayStoreInstruction;
import com.ibm.wala.shrike.shrikeBT.IGetInstruction;
import com.ibm.wala.shrike.shrikeBT.IPutInstruction;
import com.ibm.wala.shrike.shrikeBT.LoadInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MethodEditor;
import com.ibm.wala.shrike.shrikeBT.MethodEditor.Output;
import com.ibm.wala.shrike.shrikeBT.StoreInstruction;
import com.ibm.wala.shrike.shrikeBT.SwapInstruction;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.analysis.Verifier;
import com.ibm.wala.shrike.shrikeBT.info.LocalAllocator;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Random;
/**
* This is a demo class.
*
* <p>Class files are taken as input arguments (or if there are none, from standard input). The
* methods in those files are instrumented: we insert a System.err.println() at ever method call,
* and a System.err.println() at every method entry.
*
* <p>In Unix, I run it like this: java -cp ~/dev/shrike/shrike
* com.ibm.wala.shrikeBT.shrikeCT.tools.Bench test.jar -o output.jar
*
* <p>The instrumented classes are placed in the directory "output" under the current directory.
* Disassembled code is written to the file "report" under the current directory.
*/
public class Mangler {
private static OfflineInstrumenter instrumenter;
private static final boolean verify = true;
private static final boolean disasm = true;
public static void main(String[] args) throws Exception {
for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter();
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args);
int seed;
try {
seed = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
System.err.println("Invalid number: " + args[0]);
return;
}
Random r = new Random(seed);
instrumenter.setPassUnmodifiedClasses(true);
instrumenter.beginTraversal();
instrumenter.setOutputJar(new File("output.jar"));
ClassInstrumenter ci;
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w, r);
}
}
instrumenter.close();
}
}
private static void doClass(final ClassInstrumenter ci, Writer w, final Random r)
throws Exception {
final String className = ci.getReader().getName();
w.write("Class: " + className + '\n');
w.flush();
for (int m = 0; m < ci.getReader().getMethodCount(); m++) {
MethodData d = ci.visitMethod(m);
// d could be null, e.g., if the method is abstract or native
if (d != null) {
w.write(
"Instrumenting "
+ ci.getReader().getMethodName(m)
+ ' '
+ ci.getReader().getMethodType(m)
+ ":\n");
w.flush();
if (disasm) {
w.write("Initial ShrikeBT code:\n");
new Disassembler(d).disassembleTo(w);
w.flush();
}
if (verify) {
Verifier v = new Verifier(d);
v.verify();
}
final int passes = r.nextInt(4) + 1;
for (int i = 0; i < passes; i++) {
final boolean doGet = true; // r.nextBoolean();
final boolean doPut = true; // r.nextBoolean();
final boolean doArrayStore = true; // r.nextBoolean();
final int tmpInt = LocalAllocator.allocate(d, "I");
final int tmpAny = LocalAllocator.allocate(d);
final MethodEditor me = new MethodEditor(d);
me.beginPass();
me.visitInstructions(
new MethodEditor.Visitor() {
@Override
public void visitGet(IGetInstruction instruction) {
if (doGet && !instruction.isStatic()) {
insertBefore(
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(DupInstruction.make(0));
}
});
insertAfter(
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(SwapInstruction.make());
w.emit(Util.makePut(Slots.class, "o"));
}
});
}
}
@Override
public void visitPut(IPutInstruction instruction) {
if (doPut && !instruction.isStatic()) {
insertBefore(
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(SwapInstruction.make());
w.emit(DupInstruction.make(1));
w.emit(SwapInstruction.make());
}
});
insertAfter(
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(Util.makePut(Slots.class, "o"));
}
});
}
}
@Override
public void visitArrayStore(final IArrayStoreInstruction instruction) {
if (doArrayStore) {
final int label = me.allocateLabel();
insertBefore(
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
String t = Util.getStackType(instruction.getType());
w.emit(StoreInstruction.make(t, tmpAny));
w.emit(StoreInstruction.make(Constants.TYPE_int, tmpInt));
w.emit(DupInstruction.make(0));
w.emit(LoadInstruction.make(Constants.TYPE_int, tmpInt));
w.emit(LoadInstruction.make(t, tmpAny));
if (t.equals(Constants.TYPE_int)) {
w.emit(DupInstruction.make(0));
w.emit(ConstantInstruction.make(0));
w.emit(
ConditionalBranchInstruction.make(
t, ConditionalBranchInstruction.Operator.EQ, label));
w.emit(DupInstruction.make(0));
w.emit(Util.makePut(Slots.class, "i"));
w.emitLabel(label);
}
}
});
insertAfter(
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(Util.makePut(Slots.class, "o"));
w.emit(LoadInstruction.make(Constants.TYPE_int, tmpInt));
w.emit(Util.makePut(Slots.class, "i"));
}
});
}
}
});
// this updates the data d
me.applyPatches();
}
if (disasm) {
w.write("Final ShrikeBT code:\n");
new Disassembler(d).disassembleTo(w);
w.flush();
}
}
}
if (ci.isChanged()) {
ClassWriter cw = ci.emitClass();
instrumenter.outputModifiedClass(ci, cw);
}
}
}
| 8,797
| 37.08658
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/bench/Slots.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.bench;
/** @author roca@us.ibm.com */
public class Slots {
public static Object o;
public static int i;
}
| 513
| 26.052632
| 72
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/bench/Statistics.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.bench;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.IInstruction;
import com.ibm.wala.shrike.shrikeBT.InvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.Writer;
/**
* This is a demo class.
*
* <p>Class files are taken as input arguments (or if there are none, from standard input). The
* methods in those files are instrumented: we insert a System.err.println() at ever method call,
* and a System.err.println() at every method entry.
*
* <p>In Unix, I run it like this: java -cp ~/dev/shrike/shrike
* com.ibm.wala.shrikeBT.shrikeCT.tools.Bench test.jar -o output.jar
*
* <p>The instrumented classes are placed in the directory "output" under the current directory.
* Disassembled code is written to the file "report" under the current directory.
*/
public class Statistics {
private static OfflineInstrumenter instrumenter;
public static void main(String[] args) throws Exception {
for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter();
try (Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args);
instrumenter.beginTraversal();
ClassInstrumenter ci;
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w);
}
instrumenter.close();
}
}
}
private static void doClass(final ClassInstrumenter ci, Writer w) throws Exception {
ClassReader cr = ci.getReader();
final String className = cr.getName();
w.write("Class: " + className + '\n');
boolean allPrivateConstructors = true;
boolean methodCallsConstructor = false;
boolean classInitCallsConstructor = false;
for (int m = 0; m < cr.getMethodCount(); m++) {
MethodData d = ci.visitMethod(m);
// d could be null, e.g., if the method is abstract or native
if (d != null) {
if (d.getName().equals("<init>")) {
int f = cr.getMethodAccessFlags(m);
if ((f & Constants.ACC_PRIVATE) == 0
&& ((f & Constants.ACC_PROTECTED) == 0
|| (cr.getAccessFlags() & Constants.ACC_FINAL) == 0)) {
allPrivateConstructors = false;
}
}
int constructorCalls = 0;
IInstruction[] instrs = d.getInstructions();
for (IInstruction instr : instrs) {
if (instr instanceof InvokeInstruction) {
InvokeInstruction invoke = (InvokeInstruction) instr;
if (invoke.getMethodName().equals("<init>")
&& invoke.getClassType().equals(Util.makeType(className))) {
constructorCalls++;
}
}
}
if (!d.getName().equals("<init>") && !d.getName().equals("<clinit>")) {
if (constructorCalls > 0) {
methodCallsConstructor = true;
}
} else if (d.getName().equals("<clinit>")) {
classInitCallsConstructor = true;
}
}
}
if (allPrivateConstructors && !methodCallsConstructor && classInitCallsConstructor) {
w.write("Restricted Creation\n");
}
}
}
| 3,828
| 34.453704
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/cg/OfflineDynamicCallGraph.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.cg;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction;
import com.ibm.wala.shrike.shrikeBT.Constants;
import com.ibm.wala.shrike.shrikeBT.Disassembler;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.Dispatch;
import com.ibm.wala.shrike.shrikeBT.InvokeDynamicInstruction;
import com.ibm.wala.shrike.shrikeBT.InvokeInstruction;
import com.ibm.wala.shrike.shrikeBT.LoadInstruction;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.MethodEditor;
import com.ibm.wala.shrike.shrikeBT.MethodEditor.Output;
import com.ibm.wala.shrike.shrikeBT.ReturnInstruction;
import com.ibm.wala.shrike.shrikeBT.ThrowInstruction;
import com.ibm.wala.shrike.shrikeBT.Util;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrike.shrikeBT.analysis.ClassHierarchyStore;
import com.ibm.wala.shrike.shrikeBT.analysis.Verifier;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTUtils;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.config.FileOfClasses;
import com.ibm.wala.util.config.SetOfClasses;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
/**
* Class files are taken as input arguments (or if there are none, from standard input). The methods
* in those files are instrumented: we insert a System.err.println() at ever method call, and a
* System.err.println() at every method entry.
*
* <p>The instrumented classes are placed in the directory "output" under the current directory.
* Disassembled code is written to the file "report" under the current directory.
*
* @author CHammer
* @author Julian Dolby (dolby@us.ibm.com)
* @since 10/18
*/
public class OfflineDynamicCallGraph {
private static class AddTracingToInvokes extends MethodEditor.Visitor {
@Override
public void visitInvoke(IInvokeInstruction inv) {
final String calleeClass = inv.getClassType();
final String calleeMethod = inv.getMethodName() + inv.getMethodSignature();
addInstructionExceptionHandler(
/*"java.lang.Throwable"*/ null,
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(Util.makeInvoke(runtime, "pop", new Class[] {}));
w.emit(ThrowInstruction.make(true));
}
});
insertBefore(
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(ConstantInstruction.makeString(calleeClass));
w.emit(ConstantInstruction.makeString(calleeMethod));
// target unknown
w.emit(Util.makeGet(runtime, "NULL_TAG"));
// w.emit(ConstantInstruction.make(Constants.TYPE_null, null));
w.emit(
Util.makeInvoke(
runtime,
"addToCallStack",
new Class[] {String.class, String.class, Object.class}));
}
});
insertAfter(
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(Util.makeInvoke(runtime, "pop", new Class[] {}));
}
});
}
}
private static final boolean disasm = true;
private static final boolean verify = true;
private static boolean patchExits = true;
private static boolean patchCalls = true;
private static final boolean extractCalls = true;
private static boolean extractDynamicCalls = false;
private static boolean extractConstructors = true;
private static Class<?> runtime = Runtime.class;
private static SetOfClasses filter;
private static final ClassHierarchyStore cha = new ClassHierarchyStore();
public static void main(String[] args)
throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException {
OfflineInstrumenter instrumenter;
ClassInstrumenter ci;
try (final Writer w = new BufferedWriter(new FileWriter("build/report", false))) {
for (int i = 0; i < args.length; i++) {
if ("--runtime".equals(args[i])) {
runtime = Class.forName(args[i + 1]);
} else if ("--exclusions".equals(args[i])) {
try (FileInputStream input = new FileInputStream(args[i + 1])) {
filter = new FileOfClasses(input);
}
} else if ("--dont-patch-exits".equals(args[i])) {
patchExits = false;
} else if ("--patch-calls".equals(args[i])) {
patchCalls = true;
} else if ("--extract-dynamic-calls".equals(args[i])) {
extractDynamicCalls = true;
} else if ("--extract-constructors".equals(args[i])) {
extractConstructors = true;
} else if ("--rt-jar".equals(args[i])) {
System.err.println("using " + args[i + 1] + " as stdlib");
OfflineInstrumenter libReader = new OfflineInstrumenter();
libReader.addInputJar(new File(args[i + 1]));
while ((ci = libReader.nextClass()) != null) {
CTUtils.addClassToHierarchy(cha, ci.getReader());
}
}
}
instrumenter = new OfflineInstrumenter();
args = instrumenter.parseStandardArgs(args);
instrumenter.setPassUnmodifiedClasses(true);
instrumenter.beginTraversal();
while ((ci = instrumenter.nextClass()) != null) {
CTUtils.addClassToHierarchy(cha, ci.getReader());
}
instrumenter.setClassHierarchyProvider(cha);
instrumenter.beginTraversal();
while ((ci = instrumenter.nextClass()) != null) {
ClassWriter cw = doClass(ci, w);
if (cw != null) {
instrumenter.outputModifiedClass(ci, cw);
}
}
}
instrumenter.close();
}
static ClassWriter doClass(final ClassInstrumenter ci, Writer w)
throws InvalidClassFileException, IOException, FailureException {
final String className = ci.getReader().getName();
if (filter != null && filter.contains(className)) {
return null;
}
if (disasm) {
w.write("Class: " + className + '\n');
w.flush();
}
final ClassReader r = ci.getReader();
final Map<Object, MethodData> methods = HashMapFactory.make();
for (int m = 0; m < ci.getReader().getMethodCount(); m++) {
final MethodData d = ci.visitMethod(m);
// d could be null, e.g., if the method is abstract or native
if (d != null) {
if (filter != null && filter.contains(className + '.' + ci.getReader().getMethodName(m))) {
return null;
}
if (disasm) {
w.write(
"Instrumenting "
+ ci.getReader().getMethodName(m)
+ ' '
+ ci.getReader().getMethodType(m)
+ ":\n");
w.write("Initial ShrikeBT code:\n");
new Disassembler(d).disassembleTo(w);
w.flush();
}
if (verify) {
Verifier v = new Verifier(d);
// v.setClassHierarchy(cha);
v.verify();
}
final MethodEditor me = new MethodEditor(d);
me.beginPass();
final String theClass = r.getName();
final String theMethod = r.getMethodName(m).concat(r.getMethodType(m));
final boolean isConstructor = theMethod.contains("<init>");
final boolean nonStatic = !java.lang.reflect.Modifier.isStatic(r.getMethodAccessFlags(m));
if (patchExits) {
me.addMethodExceptionHandler(
null,
new MethodEditor.Patch() {
@Override
public void emitTo(Output w) {
w.emit(ConstantInstruction.makeString(theClass));
w.emit(ConstantInstruction.makeString(theMethod));
// if (nonStatic)
// w.emit(LoadInstruction.make(Constants.TYPE_Object, 0)); //load this
// else
w.emit(Util.makeGet(runtime, "NULL_TAG"));
// w.emit(ConstantInstruction.make(Constants.TYPE_null, null));
w.emit(ConstantInstruction.make(1)); // true
w.emit(
Util.makeInvoke(
runtime,
"termination",
new Class[] {String.class, String.class, Object.class, boolean.class}));
w.emit(ThrowInstruction.make(false));
}
});
me.visitInstructions(
new MethodEditor.Visitor() {
@Override
public void visitReturn(ReturnInstruction instruction) {
insertBefore(
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(ConstantInstruction.makeString(theClass));
w.emit(ConstantInstruction.makeString(theMethod));
if (nonStatic)
w.emit(LoadInstruction.make(Constants.TYPE_Object, 0)); // load this
else w.emit(Util.makeGet(runtime, "NULL_TAG"));
// w.emit(ConstantInstruction.make(Constants.TYPE, null));
w.emit(ConstantInstruction.make(0)); // false
w.emit(
Util.makeInvoke(
runtime,
"termination",
new Class[] {
String.class, String.class, Object.class, boolean.class
}));
}
});
}
});
}
if (patchCalls) {
if (extractCalls) {
me.visitInstructions(
new AddTracingToInvokes() {
@Override
public void visitInvoke(final IInvokeInstruction inv) {
if ((!extractConstructors && inv.getMethodName().equals("<init>"))
|| (r.getAccessFlags() & Constants.ACC_INTERFACE) != 0
|| (!extractDynamicCalls && inv instanceof InvokeDynamicInstruction)) {
super.visitInvoke(inv);
} else {
this.replaceWith(
new MethodEditor.Patch() {
@Override
public void emitTo(final Output w) {
final String methodSignature =
inv.getInvocationCode().hasImplicitThis()
&& !(inv instanceof InvokeDynamicInstruction)
? '('
+ inv.getClassType()
+ inv.getMethodSignature().substring(1)
: inv.getMethodSignature();
Object key;
if (inv instanceof InvokeDynamicInstruction) {
key = inv;
} else {
key =
Pair.make(
inv.getClassType(),
Pair.make(inv.getMethodName(), methodSignature));
}
if (!methods.containsKey(key)) {
MethodData trampoline =
ci.createEmptyMethodData(
"$shrike$trampoline$" + methods.size(),
methodSignature,
Constants.ACC_STATIC | Constants.ACC_PRIVATE);
methods.put(key, trampoline);
MethodEditor me = new MethodEditor(trampoline);
me.beginPass();
me.insertAtStart(
new MethodEditor.Patch() {
private String hackType(String type) {
if ("B".equals(type)
|| "C".equals(type)
|| "S".equals(type)
|| "Z".equals(type)) {
return "I";
} else {
return type;
}
}
@Override
public void emitTo(MethodEditor.Output w) {
String[] types = Util.getParamsTypes(null, methodSignature);
for (int i = 0, local = 0; i < types.length; i++) {
String type = hackType(types[i]);
w.emit(LoadInstruction.make(type, local));
if ("J".equals(type) || "D".equals(type)) {
local += 2;
} else {
local++;
}
}
Dispatch mode = (Dispatch) inv.getInvocationCode();
if (inv instanceof InvokeDynamicInstruction) {
InvokeDynamicInstruction inst =
new InvokeDynamicInstruction(
((InvokeDynamicInstruction) inv).getOpcode(),
((InvokeDynamicInstruction) inv).getBootstrap(),
inv.getMethodName(),
inv.getMethodSignature());
w.emit(inst);
} else {
InvokeInstruction inst =
InvokeInstruction.make(
inv.getMethodSignature(),
inv.getClassType(),
inv.getMethodName(),
mode);
w.emit(inst);
}
// w.emit(ReturnInstruction.make(hackType(inv.getMethodSignature().substring(inv.getMethodSignature().indexOf(")")+1))));
}
});
me.applyPatches();
me.endPass();
me.beginPass();
me.visitInstructions(new AddTracingToInvokes());
me.applyPatches();
me.endPass();
if (verify) {
Verifier v = new Verifier(trampoline);
// v.setClassHierarchy(cha);
try {
v.verify();
} catch (FailureException e) {
throw new RuntimeException(e);
}
}
}
MethodData mt = methods.get(key);
w.emit(
InvokeInstruction.make(
mt.getSignature(),
mt.getClassType(),
mt.getName(),
Dispatch.STATIC));
}
});
}
}
});
} else {
me.visitInstructions(new AddTracingToInvokes());
}
}
me.insertAtStart(
new MethodEditor.Patch() {
@Override
public void emitTo(MethodEditor.Output w) {
w.emit(ConstantInstruction.makeString(theClass));
w.emit(ConstantInstruction.makeString(theMethod));
if (nonStatic && !isConstructor)
w.emit(LoadInstruction.make(Constants.TYPE_Object, 0)); // load this
else w.emit(Util.makeGet(runtime, "NULL_TAG"));
// w.emit(ConstantInstruction.make(Constants.TYPE_null, null));
w.emit(
Util.makeInvoke(
runtime,
"execution",
new Class[] {String.class, String.class, Object.class}));
}
});
// this updates the data d
me.applyPatches();
me.endPass();
if (disasm) {
w.write("Final ShrikeBT code:\n");
new Disassembler(d).disassembleTo(w);
w.flush();
}
if (verify && !extractConstructors) {
Verifier v = new Verifier(d);
// v.setClassHierarchy(cha);
v.verify();
}
}
}
if (ci.isChanged()) {
ClassWriter cw =
new ClassWriter() {
private final Map<Object, Integer> entries = HashMapFactory.make();
{
ConstantPoolParser p = r.getCP();
for (int i = 1; i < p.getItemCount(); i++) {
final byte itemType = p.getItemType(i);
switch (itemType) {
case CONSTANT_Integer:
entries.put(p.getCPInt(i), i);
break;
case CONSTANT_Long:
entries.put(p.getCPLong(i), i);
break;
case CONSTANT_Float:
entries.put(p.getCPFloat(i), i);
break;
case CONSTANT_Double:
entries.put(p.getCPDouble(i), i);
break;
case CONSTANT_Utf8:
entries.put(p.getCPUtf8(i), i);
break;
case CONSTANT_String:
entries.put(new CWStringItem(p.getCPString(i), CONSTANT_String), i);
break;
case CONSTANT_Class:
entries.put(new CWStringItem(p.getCPClass(i), CONSTANT_Class), i);
break;
default:
// do nothing
}
}
}
private int findExistingEntry(Object o) {
return entries.getOrDefault(o, -1);
}
@Override
protected int addCPEntry(Object o, int size) {
int entry = findExistingEntry(o);
if (entry != -1) {
return entry;
} else {
return super.addCPEntry(o, size);
}
}
};
ci.emitClass(cw);
if (patchCalls && extractCalls) {
for (MethodData trampoline : methods.values()) {
CTUtils.compileAndAddMethodToClassWriter(trampoline, cw, null);
}
}
return cw;
} else {
return null;
}
}
}
| 20,852
| 40.539841
| 161
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/cg/OnlineDynamicCallGraph.java
|
package com.ibm.wala.shrike.cg;
import com.ibm.wala.shrike.shrikeBT.analysis.Analyzer.FailureException;
import com.ibm.wala.shrike.shrikeBT.analysis.ClassHierarchyStore;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTUtils;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
public class OnlineDynamicCallGraph implements ClassFileTransformer {
private final ClassHierarchyStore cha = new ClassHierarchyStore();
private final Writer out = new PrintWriter(System.err);
public OnlineDynamicCallGraph()
throws IllegalArgumentException, IOException, InvalidClassFileException {
OfflineInstrumenter libReader = new OfflineInstrumenter();
for (String cps :
new String[] {
System.getProperty("java.class.path"), System.getProperty("sun.boot.class.path")
}) {
for (String cp : cps.split(File.pathSeparator)) {
File x = new File(cp);
if (x.exists()) {
if (x.isDirectory()) {
libReader.addInputDirectory(x, x);
} else {
libReader.addInputJar(x);
}
}
}
}
ClassInstrumenter ci;
while ((ci = libReader.nextClass()) != null) {
CTUtils.addClassToHierarchy(cha, ci.getReader());
}
}
@Override
public byte[] transform(
ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer)
throws IllegalClassFormatException {
try {
if (className.contains("com/ibm/wala")
|| className.contains("java/lang")
|| (className.contains("java/") && !className.matches("java/util/[A-Z]"))
|| className.contains("sun/")) {
return classfileBuffer;
} else {
ClassInstrumenter ci = new ClassInstrumenter(className, classfileBuffer, cha);
return OfflineDynamicCallGraph.doClass(ci, out).makeBytes();
}
} catch (InvalidClassFileException | IOException | FailureException e) {
e.printStackTrace();
System.err.println("got here with " + e.getMessage());
throw new IllegalClassFormatException(e.getMessage());
}
}
public static void premain(Instrumentation inst)
throws IllegalArgumentException, IOException, InvalidClassFileException {
inst.addTransformer(new OnlineDynamicCallGraph());
}
}
| 2,773
| 34.113924
| 90
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/cg/Runtime.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.cg;
import com.ibm.wala.util.config.FileOfClasses;
import com.ibm.wala.util.config.SetOfClasses;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayDeque;
import java.util.zip.GZIPOutputStream;
public class Runtime {
public interface Policy {
void callback(StackTraceElement[] stack, String klass, String method, Object receiver);
}
private static class DefaultCallbackPolicy implements Policy {
@Override
public void callback(StackTraceElement[] stack, String klass, String method, Object receiver) {
// stack frames: Runtime.execution(0), callee(1), caller(2)
String root =
"<clinit>".equals(stack[1].getMethodName())
? "clinit"
: "finalize".equals(stack[1].getMethodName()) ? "root" : "callbacks";
String line = root + '\t' + bashToDescriptor(klass) + '\t' + String.valueOf(method) + '\n';
synchronized (runtime) {
if (runtime.output != null) {
runtime.output.printf(line);
runtime.output.flush();
}
}
}
}
private static final Runtime runtime =
new Runtime(
System.getProperty("dynamicCGFile"),
System.getProperty("dynamicCGFilter"),
System.getProperty("policyClass", "com.ibm.wala.shrike.cg.Runtime$DefaultPolicy"));
private PrintWriter output;
private SetOfClasses filter;
private Policy handleCallback;
private final ThreadLocal<String> currentSite = new ThreadLocal<>();
private final ThreadLocal<ArrayDeque<String>> callStacks =
ThreadLocal.withInitial(
() -> {
ArrayDeque<String> callStack = new ArrayDeque<>();
callStack.push("root");
return callStack;
});
private Runtime(String fileName, String filterFileName, String policyClassName) {
try (final FileInputStream in = new FileInputStream(filterFileName)) {
filter = new FileOfClasses(in);
} catch (Exception e) {
filter = null;
}
try {
output =
new PrintWriter(
new OutputStreamWriter(
new GZIPOutputStream(new FileOutputStream(fileName)), "UTF-8"));
} catch (IOException e) {
output = new PrintWriter(System.err);
}
try {
handleCallback =
(Policy) Class.forName(policyClassName).getDeclaredConstructor().newInstance();
} catch (InstantiationException
| IllegalAccessException
| ClassNotFoundException
| IllegalArgumentException
| InvocationTargetException
| NoSuchMethodException
| SecurityException e) {
handleCallback = new DefaultCallbackPolicy();
}
java.lang.Runtime.getRuntime().addShutdownHook(new Thread(Runtime::endTrace));
}
public static void endTrace() {
synchronized (runtime) {
if (runtime.output != null) {
runtime.output.close();
runtime.output = null;
}
}
}
public static Object NULL_TAG =
new Object() {
@Override
public String toString() {
return "NULL TAG";
}
};
public static String bashToDescriptor(String className) {
if (className.startsWith("class ")) {
className = className.substring(6);
}
if (className.indexOf('.') >= 0) {
className = className.replace('.', '/');
}
return className;
}
public static void execution(String klass, String method, Object receiver) {
runtime.currentSite.set(null);
if (runtime.filter == null || !runtime.filter.contains(bashToDescriptor(klass))) {
if (runtime.output != null) {
String caller = runtime.callStacks.get().peek();
checkValid:
{
//
// check for expected caller
//
if (runtime.handleCallback != null) {
StackTraceElement[] stack = new Throwable().getStackTrace();
if (stack.length > 2) {
// frames: Runtime.execution(0), callee(1), caller(2)
StackTraceElement callerFrame = stack[2];
if (!callerFrame.getMethodName().startsWith("$")) {
if (!caller.contains(callerFrame.getMethodName())
|| !caller.contains(bashToDescriptor(callerFrame.getClassName()))) {
runtime.handleCallback.callback(stack, klass, method, receiver);
break checkValid;
}
}
}
}
String line =
(method.contains("<clinit>") ? "clinit" : String.valueOf(caller))
+ '\t'
+ bashToDescriptor(klass)
+ '\t'
+ String.valueOf(method)
+ '\n';
synchronized (runtime) {
if (runtime.output != null) {
runtime.output.printf(line);
runtime.output.flush();
}
}
}
}
}
runtime.callStacks.get().push(bashToDescriptor(klass) + '\t' + method);
}
@SuppressWarnings("unused")
public static void termination(String klass, String method, Object receiver, boolean exception) {
runtime.callStacks.get().pop();
}
public static void pop() {
if (runtime.currentSite.get() != null) {
synchronized (runtime) {
if (runtime.output != null) {
runtime.output.printf("return from " + runtime.currentSite.get() + '\n');
runtime.output.flush();
}
}
runtime.currentSite.set(null);
}
}
public static void addToCallStack(String klass, String method, Object receiver) {
String callerClass =
runtime.callStacks.get().isEmpty()
? "BLOB"
: runtime.callStacks.get().peek().split("\t")[0];
String callerMethod =
runtime.callStacks.get().isEmpty()
? "BLOB"
: runtime.callStacks.get().peek().split("\t")[1];
runtime.currentSite.set(
callerClass + '\t' + callerMethod + '\t' + klass + '\t' + method + '\t' + receiver);
// runtime.currentSite = klass + "\t" + method + "\t" + receiver;
synchronized (runtime) {
if (runtime.output != null) {
runtime.output.printf("call to " + runtime.currentSite.get() + '\n');
runtime.output.flush();
}
}
}
}
| 6,821
| 31.485714
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/copywriter/CopyWriter.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.copywriter;
import com.ibm.wala.shrike.shrikeBT.Compiler;
import com.ibm.wala.shrike.shrikeBT.Decoder.InvalidBytecodeException;
import com.ibm.wala.shrike.shrikeBT.MethodData;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTCompiler;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.CTDecoder;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.ClassInstrumenter;
import com.ibm.wala.shrike.shrikeBT.shrikeCT.OfflineInstrumenter;
import com.ibm.wala.shrike.shrikeCT.ClassConstants;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassReader.AttrIterator;
import com.ibm.wala.shrike.shrikeCT.ClassWriter;
import com.ibm.wala.shrike.shrikeCT.ClassWriter.Element;
import com.ibm.wala.shrike.shrikeCT.CodeReader;
import com.ibm.wala.shrike.shrikeCT.CodeWriter;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser;
import com.ibm.wala.shrike.shrikeCT.ConstantValueReader;
import com.ibm.wala.shrike.shrikeCT.ConstantValueWriter;
import com.ibm.wala.shrike.shrikeCT.ExceptionsReader;
import com.ibm.wala.shrike.shrikeCT.ExceptionsWriter;
import com.ibm.wala.shrike.shrikeCT.InnerClassesReader;
import com.ibm.wala.shrike.shrikeCT.InnerClassesWriter;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.shrike.shrikeCT.LocalVariableTableReader;
import com.ibm.wala.shrike.shrikeCT.LocalVariableTableWriter;
import com.ibm.wala.shrike.shrikeCT.SourceFileReader;
import com.ibm.wala.shrike.shrikeCT.SourceFileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.zip.ZipEntry;
public class CopyWriter {
private static final String USAGE =
"IBM CopyWriter Tool\n"
+ "This tool takes the following command line options:\n"
+ " <jarname> <jarname> ... Process the classes from these jars\n"
+ " -o <jarname> Put the resulting classes into <jarname>\n"
+ " -c <copyright> Make the copyright string be\n"
+ " '\u00A9 Copyright <copyright>'";
private static OfflineInstrumenter instrumenter;
public static String copyright;
public static final String copyrightAttrName = "com.ibm.Copyright";
private int replaceWith;
private int replace;
static class UnknownAttributeException extends Exception {
private static final long serialVersionUID = 8845177787110364793L;
UnknownAttributeException(String t) {
super("Attribute '" + t + "' not understood");
}
}
public static void main(String[] args) throws Exception {
if (args == null || args.length == 0) {
System.err.println(USAGE);
System.exit(1);
}
for (int i = 0; i < args.length - 1; i++) {
if (args[i] == null) {
throw new IllegalArgumentException("args[" + i + "] is null");
}
if (args[i].equals("-c")) {
copyright = "\u00A9 Copyright " + args[i + 1];
String[] newArgs = new String[args.length - 2];
System.arraycopy(args, 0, newArgs, 0, i);
System.arraycopy(args, i + 2, newArgs, i, newArgs.length - i);
args = newArgs;
break;
}
}
if (copyright == null) {
System.err.println(USAGE);
System.exit(1);
}
final ArrayList<ZipEntry> entries = new ArrayList<>();
instrumenter = new OfflineInstrumenter();
instrumenter.setManifestBuilder(entries::add);
instrumenter.parseStandardArgs(args);
instrumenter.setJARComment(copyright);
instrumenter.beginTraversal();
ClassInstrumenter ci;
CopyWriter cw = new CopyWriter();
while ((ci = instrumenter.nextClass()) != null) {
try {
cw.doClass(ci);
} catch (UnknownAttributeException ex) {
System.err.println(ex.getMessage() + " in " + instrumenter.getLastClassResourceName());
}
}
instrumenter.writeUnmodifiedClasses();
Writer w =
new OutputStreamWriter(instrumenter.addOutputJarEntry(new ZipEntry("IBM-Copyright")));
w.write(copyright + '\n');
for (ZipEntry ze : entries) {
w.write(" " + ze.getName() + '\n');
}
w.write(copyright + '\n');
w.flush();
instrumenter.endOutputJarEntry();
instrumenter.close();
}
private int transformCPIndex(int i) {
if (i == replace) {
return replaceWith;
} else {
return i;
}
}
private Element transformAttribute(ClassReader cr, int m, ClassWriter w, AttrIterator iter)
throws InvalidClassFileException, UnknownAttributeException, InvalidBytecodeException {
String name = iter.getName();
boolean needTransform = true;
if (name.equals("Synthetic") || name.equals("Deprecated") || name.equals("LineNumberTable")) {
needTransform = false;
}
int offset = iter.getRawOffset();
int end = offset + iter.getRawSize();
if (needTransform) {
needTransform = false;
for (int i = offset; i + 1 < end; i++) {
if (cr.getUShort(i) == replace) {
break;
}
}
}
if (!needTransform) {
return new ClassWriter.RawElement(cr.getBytes(), offset, end - offset);
}
switch (name) {
case "Code":
{
CodeReader r = new CodeReader(iter);
CTDecoder decoder = new CTDecoder(r);
decoder.decode();
MethodData md =
new MethodData(
decoder,
cr.getMethodAccessFlags(m),
CTDecoder.convertClassToType(cr.getName()),
cr.getMethodName(m),
cr.getMethodType(m));
CTCompiler compiler = CTCompiler.make(w, md);
compiler.compile();
if (compiler.getAuxiliaryMethods().length > 0)
throw new Error("Where did this auxiliary method come from?");
Compiler.Output out = compiler.getOutput();
CodeWriter cw = new CodeWriter(w);
cw.setMaxLocals(out.getMaxLocals());
cw.setMaxStack(out.getMaxStack());
cw.setCode(out.getCode());
cw.setRawHandlers(out.getRawHandlers());
AttrIterator iterator = new AttrIterator();
r.initAttributeIterator(iterator);
cw.setAttributes(collectAttributes(cr, m, w, iterator));
return cw;
}
case "ConstantValue":
{
ConstantValueReader r = new ConstantValueReader(iter);
ConstantValueWriter cw = new ConstantValueWriter(w);
cw.setValueCPIndex(transformCPIndex(r.getValueCPIndex()));
return cw;
}
case "SourceFile":
{
SourceFileReader r = new SourceFileReader(iter);
SourceFileWriter cw = new SourceFileWriter(w);
cw.setSourceFileCPIndex(transformCPIndex(r.getSourceFileCPIndex()));
return cw;
}
case "LocalVariableTableReader":
{
LocalVariableTableReader lr = new LocalVariableTableReader(iter);
LocalVariableTableWriter lw = new LocalVariableTableWriter(w);
int[] table = lr.getRawTable();
for (int i = 0; i < table.length; i += 5) {
table[i + 2] = transformCPIndex(table[i + 2]);
table[i + 3] = transformCPIndex(table[i + 3]);
}
lw.setRawTable(table);
return lw;
}
case "Exceptions":
{
ExceptionsReader lr = new ExceptionsReader(iter);
ExceptionsWriter lw = new ExceptionsWriter(w);
int[] table = lr.getRawTable();
Arrays.setAll(table, i -> transformCPIndex(table[i]));
lw.setRawTable(table);
return lw;
}
case "InnerClasses":
{
InnerClassesReader lr = new InnerClassesReader(iter);
InnerClassesWriter lw = new InnerClassesWriter(w);
int[] table = lr.getRawTable();
for (int i = 0; i < table.length; i += 4) {
table[i] = transformCPIndex(table[i]);
table[i + 1] = transformCPIndex(table[i + 1]);
table[i + 2] = transformCPIndex(table[i + 2]);
}
lw.setRawTable(table);
return lw;
}
}
throw new UnknownAttributeException(name);
}
private Element[] collectAttributes(ClassReader cr, int m, ClassWriter w, AttrIterator iter)
throws InvalidClassFileException, UnknownAttributeException, InvalidBytecodeException {
Element[] elems = new Element[iter.getRemainingAttributesCount()];
for (int i = 0; i < elems.length; i++) {
elems[i] = transformAttribute(cr, m, w, iter);
iter.advance();
}
return elems;
}
private static int copyEntry(ConstantPoolParser cp, ClassWriter w, int i)
throws InvalidClassFileException {
byte t = cp.getItemType(i);
switch (t) {
case ClassConstants.CONSTANT_String:
return w.addCPString(cp.getCPString(i));
case ClassConstants.CONSTANT_Class:
return w.addCPClass(cp.getCPClass(i));
case ClassConstants.CONSTANT_FieldRef:
return w.addCPFieldRef(cp.getCPRefClass(i), cp.getCPRefName(i), cp.getCPRefType(i));
case ClassConstants.CONSTANT_InterfaceMethodRef:
return w.addCPInterfaceMethodRef(
cp.getCPRefClass(i), cp.getCPRefName(i), cp.getCPRefType(i));
case ClassConstants.CONSTANT_MethodRef:
return w.addCPMethodRef(cp.getCPRefClass(i), cp.getCPRefName(i), cp.getCPRefType(i));
case ClassConstants.CONSTANT_NameAndType:
return w.addCPNAT(cp.getCPNATName(i), cp.getCPNATType(i));
case ClassConstants.CONSTANT_Integer:
return w.addCPInt(cp.getCPInt(i));
case ClassConstants.CONSTANT_Float:
return w.addCPFloat(cp.getCPFloat(i));
case ClassConstants.CONSTANT_Long:
return w.addCPLong(cp.getCPLong(i));
case ClassConstants.CONSTANT_Double:
return w.addCPDouble(cp.getCPDouble(i));
case ClassConstants.CONSTANT_Utf8:
return w.addCPUtf8(cp.getCPUtf8(i));
default:
return -1;
}
}
private void doClass(final ClassInstrumenter ci) throws Exception {
/*
* Our basic strategy is to make the first element of the constant pool be the copyright string (as a UTF8 constant pool item).
* This requires us to parse and emit any class data which might refer to that constant pool item (#1). We will assume that any
* attribute which refers to that constant pool item must contain the byte sequence '00 01', so we can just copy over any
* attributes which don't contain that byte sequence. If we detect an unknown attribute type containing the sequence '00 01',
* then we will abort.
*/
ClassReader cr = ci.getReader();
ClassWriter w = new ClassWriter();
// Make sure that when we're moving over the old constant pool,
// anytime we add a new entry it really is added and we don't just
// reuse an existing entry.
w.setForceAddCPEntries(true);
// Make the first string in the constant pool be the copyright string
int r = w.addCPUtf8(copyright);
if (r != 1) throw new Error("Invalid constant pool index: " + r);
// Now add the rest of the CP entries
ConstantPoolParser cp = cr.getCP();
int CPCount = cp.getItemCount();
if (1 < CPCount) {
final byte itemType = cp.getItemType(1);
switch (itemType) {
case ClassConstants.CONSTANT_Long:
case ClassConstants.CONSTANT_Double:
// item 1 is a double-word item, so the next real item is at 3
// to make sure item 3 is allocated at index 3, we'll need to
// insert a dummy entry at index 2
r = w.addCPUtf8("");
if (r != 2) throw new Error("Invalid constant pool index for dummy: " + r);
break;
default:
throw new UnsupportedOperationException(
String.format("unexpected constant-pool item type %s", itemType));
}
}
for (int i = 2; i < CPCount; i++) {
r = copyEntry(cp, w, i);
if (r != -1 && r != i)
throw new Error("Invalid constant pool index allocated: " + r + ", expected " + i);
}
w.setForceAddCPEntries(false);
// add CP entry we replaced
replaceWith = copyEntry(cp, w, 1);
replace = 1;
// emit class
w.setMajorVersion(cr.getMajorVersion());
w.setMinorVersion(cr.getMinorVersion());
w.setAccessFlags(cr.getAccessFlags());
w.setName(cr.getName());
w.setSuperName(cr.getSuperName());
w.setInterfaceNames(cr.getInterfaceNames());
ClassReader.AttrIterator iter = new ClassReader.AttrIterator();
int fieldCount = cr.getFieldCount();
for (int i = 0; i < fieldCount; i++) {
cr.initFieldAttributeIterator(i, iter);
w.addField(
cr.getFieldAccessFlags(i),
cr.getFieldName(i),
cr.getFieldType(i),
collectAttributes(cr, i, w, iter));
}
int methodCount = cr.getMethodCount();
for (int i = 0; i < methodCount; i++) {
cr.initMethodAttributeIterator(i, iter);
w.addMethod(
cr.getMethodAccessFlags(i),
cr.getMethodName(i),
cr.getMethodType(i),
collectAttributes(cr, i, w, iter));
}
cr.initClassAttributeIterator(iter);
for (; iter.isValid(); iter.advance()) {
w.addClassAttribute(transformAttribute(cr, 0, w, iter));
}
instrumenter.outputModifiedClass(ci, w);
}
}
| 13,750
| 35.865952
| 131
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/instrumentation/CodeScraper.java
|
package com.ibm.wala.shrike.instrumentation;
import com.ibm.wala.shrike.shrikeCT.ClassReader;
import com.ibm.wala.shrike.shrikeCT.ClassReader.AttrIterator;
import com.ibm.wala.shrike.shrikeCT.InvalidClassFileException;
import com.ibm.wala.shrike.shrikeCT.SourceFileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.ProtectionDomain;
public class CodeScraper implements ClassFileTransformer {
private static final Path prefix;
static {
try {
prefix = Files.createTempDirectory("loggedClasses");
prefix.toFile().deleteOnExit();
} catch (final IOException problem) {
throw new RuntimeException(problem);
}
System.err.println("scraping to " + prefix);
}
@Override
public byte[] transform(
ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer)
throws IllegalClassFormatException {
try {
String sourceFile = null;
ClassReader reader = new ClassReader(classfileBuffer);
AttrIterator attrs = new ClassReader.AttrIterator();
reader.initClassAttributeIterator(attrs);
for (; attrs.isValid(); attrs.advance()) {
if (attrs.getName().equals("SourceFile")) {
SourceFileReader file = new SourceFileReader(attrs);
int index = file.getSourceFileCPIndex();
sourceFile = reader.getCP().getCPUtf8(index);
}
}
if (className == null || sourceFile == null || !sourceFile.endsWith("java") || true)
try {
Path log = prefix.resolve(reader.getName() + ".class");
try (final OutputStream f = Files.newOutputStream(log)) {
f.write(classfileBuffer);
}
} catch (IOException e) {
assert false : e;
}
return classfileBuffer;
} catch (InvalidClassFileException e1) {
e1.printStackTrace();
throw new IllegalClassFormatException(e1.getLocalizedMessage());
}
}
public static void premain(Instrumentation inst) {
inst.addTransformer(new CodeScraper());
}
}
| 2,326
| 31.774648
| 90
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ArrayLengthInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents arraylength instructions. */
public final class ArrayLengthInstruction extends Instruction {
private ArrayLengthInstruction() {
super(OP_arraylength);
}
private static final ArrayLengthInstruction preallocated = new ArrayLengthInstruction();
public static ArrayLengthInstruction make() {
return preallocated;
}
@Override
public boolean equals(Object o) {
return o instanceof ArrayLengthInstruction;
}
@Override
public int hashCode() {
return 3180901;
}
@Override
public int getPoppedCount() {
return 1;
}
@Override
public String getPushedType(String[] types) {
return Constants.TYPE_int;
}
@Override
public byte getPushedWordSize() {
return 1;
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitArrayLength(this);
}
@Override
public String toString() {
return "ArrayLength()";
}
@Override
public boolean isPEI() {
return true;
}
}
| 1,417
| 20.815385
| 90
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ArrayLoadInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents the ?aload instructions. */
public final class ArrayLoadInstruction extends Instruction implements IArrayLoadInstruction {
private ArrayLoadInstruction(short opcode) {
super(opcode);
}
private static final ArrayLoadInstruction[] preallocated = preallocate();
private static ArrayLoadInstruction[] preallocate() {
ArrayLoadInstruction[] r = new ArrayLoadInstruction[OP_saload - OP_iaload + 2];
for (short i = OP_iaload; i <= OP_saload; i++) {
r[i - OP_iaload] = new ArrayLoadInstruction(i);
}
r[OP_saload - OP_iaload + 1] = r[OP_baload - OP_iaload];
return r;
}
public static ArrayLoadInstruction make(String type) throws IllegalArgumentException {
int i = Util.getTypeIndex(type);
if (i < 0 || i > TYPE_boolean_index) {
throw new IllegalArgumentException("Invalid type " + type + " for ArrayLoadInstruction");
}
return preallocated[i];
}
@Override
public boolean equals(Object o) {
if (o instanceof ArrayLoadInstruction) {
ArrayLoadInstruction i = (ArrayLoadInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
@Override
public int hashCode() {
return opcode + 9109101;
}
@Override
public int getPoppedCount() {
return 2;
}
@Override
public String toString() {
return "ArrayLoad(" + getType() + ')';
}
@Override
public String getPushedType(String[] types) throws IllegalArgumentException {
if (types == null) {
return getType();
} else {
if (types.length <= 1) {
throw new IllegalArgumentException("types.length <= 1");
}
String t = types[1];
if (t == null) {
throw new IllegalArgumentException("types[1] cannot be null");
}
if (t.startsWith("[")) {
return t.substring(1);
} else if (t.equals(TYPE_null)) {
return TYPE_null;
} else {
return TYPE_unknown;
}
}
}
@Override
public byte getPushedWordSize() {
return Util.getWordSize(getType());
}
@Override
public String getType() {
return Constants.indexedTypes[opcode - OP_iaload];
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitArrayLoad(this);
}
@Override
public boolean isPEI() {
return true;
}
/**
* Java bytecode does not permit this.
*
* @see com.ibm.wala.shrike.shrikeBT.IMemoryOperation#isAddressOf()
*/
@Override
public boolean isAddressOf() {
return false;
}
}
| 2,946
| 24.405172
| 95
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ArrayStoreInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents the ?astore instructions. */
public final class ArrayStoreInstruction extends Instruction implements IArrayStoreInstruction {
private ArrayStoreInstruction(short opcode) {
super(opcode);
}
private static final ArrayStoreInstruction[] preallocated = preallocate();
private static ArrayStoreInstruction[] preallocate() {
ArrayStoreInstruction[] r = new ArrayStoreInstruction[OP_sastore - OP_iastore + 2];
for (short i = OP_iastore; i <= OP_sastore; i++) {
r[i - OP_iastore] = new ArrayStoreInstruction(i);
}
r[OP_sastore - OP_iastore + 1] = r[OP_baload - OP_iaload];
return r;
}
public static ArrayStoreInstruction make(String type) throws IllegalArgumentException {
int i = Util.getTypeIndex(type);
if (i < 0 || i > TYPE_boolean_index) {
throw new IllegalArgumentException("Invalid type " + type + " for ArrayStoreInstruction");
}
return preallocated[i];
}
@Override
public boolean equals(Object o) {
if (o instanceof ArrayStoreInstruction) {
ArrayStoreInstruction i = (ArrayStoreInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
@Override
public int hashCode() {
return opcode + 148791;
}
@Override
public int getPoppedCount() {
return 3;
}
@Override
public String getType() {
return Constants.indexedTypes[opcode - OP_iastore];
}
@Override
public String toString() {
return "ArrayStore(" + getType() + ')';
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitArrayStore(this);
}
@Override
public boolean isPEI() {
return true;
}
}
| 2,101
| 25.948718
| 96
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/BinaryOpInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/**
* This class represents binary operator instructions for which the operands and the result all have
* the same type.
*/
public final class BinaryOpInstruction extends Instruction implements IBinaryOpInstruction {
private BinaryOpInstruction(short opcode) {
super(opcode);
}
private static final BinaryOpInstruction[] arithmeticOps = preallocateArithmeticOps();
private static final BinaryOpInstruction[] logicalOps = preallocateLogicalOps();
private static BinaryOpInstruction[] preallocateArithmeticOps() {
BinaryOpInstruction[] r = new BinaryOpInstruction[OP_drem - OP_iadd + 1];
for (short i = OP_iadd; i <= OP_drem; i++) {
r[i - OP_iadd] = new BinaryOpInstruction(i);
}
return r;
}
private static BinaryOpInstruction[] preallocateLogicalOps() {
BinaryOpInstruction[] r = new BinaryOpInstruction[OP_lxor - OP_iand + 1];
for (short i = OP_iand; i <= OP_lxor; i++) {
r[i - OP_iand] = new BinaryOpInstruction(i);
}
return r;
}
public static BinaryOpInstruction make(String type, Operator operator)
throws IllegalArgumentException {
if (operator == null) {
throw new IllegalArgumentException("operator is null");
}
int t = Util.getTypeIndex(type);
if (t < 0) {
throw new IllegalArgumentException("Invalid type for BinaryOp: " + type);
}
if (operator.compareTo(Operator.REM) <= 0) {
if (t > TYPE_double_index) {
throw new IllegalArgumentException("Invalid type for BinaryOp: " + type);
}
return arithmeticOps[(operator.ordinal() - Operator.ADD.ordinal()) * 4 + t];
} else {
if (t > TYPE_long_index) {
throw new IllegalArgumentException(
"Cannot use logical binaryOps on floating point type: " + type);
}
return logicalOps[(operator.ordinal() - Operator.AND.ordinal()) * 2 + t];
}
}
@Override
public boolean equals(Object o) {
if (o instanceof BinaryOpInstruction) {
BinaryOpInstruction i = (BinaryOpInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
@Override
public Operator getOperator() {
if (opcode < OP_iand) {
// For these opcodes, there are 4 variants (i,l,f,d)
return Operator.values()[(opcode - OP_iadd) / 4];
} else {
// For these opcodes there are 2 variants (i,l)
// Note that AND is values()[5]
return Operator.values()[5 + (opcode - OP_iand) / 2];
}
}
@Override
public int hashCode() {
return opcode + 13901901;
}
@Override
public int getPoppedCount() {
return 2;
}
@Override
public String getPushedType(String[] types) {
return getType();
}
@Override
public byte getPushedWordSize() {
return Util.getWordSize(getType());
}
@Override
public String getType() {
int t;
if (opcode < OP_iand) {
t = (opcode - OP_iadd) & 3;
} else {
t = (opcode - OP_iand) & 1;
}
return indexedTypes[t];
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitBinaryOp(this);
}
@Override
public String toString() {
return "BinaryOp(" + getType() + ',' + getOperator() + ')';
}
@Override
public boolean isPEI() {
return opcode == Constants.OP_idiv
|| opcode == Constants.OP_ldiv
|| opcode == Constants.OP_irem
|| opcode == Constants.OP_lrem;
}
@Override
public boolean throwsExceptionOnOverflow() {
return false;
}
@Override
public boolean isUnsigned() {
return false;
}
}
| 3,971
| 26.020408
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/BytecodeConstants.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/**
* Information about java byte codes that appear in the "code" attribute of a .class file.
*
* @author Bowen Alpern
* @author Derek Lieber
* @author Stephen Fink
*/
public interface BytecodeConstants {
// The following mnemonics are defined in Chapter 10 of The Java Virtual Machine Specification.
//
int JBC_nop = 0;
int JBC_aconst_null = 1;
int JBC_iconst_m1 = 2;
int JBC_iconst_0 = 3;
int JBC_iconst_1 = 4;
int JBC_iconst_2 = 5;
int JBC_iconst_3 = 6;
int JBC_iconst_4 = 7;
int JBC_iconst_5 = 8;
int JBC_lconst_0 = 9;
int JBC_lconst_1 = 10;
int JBC_fconst_0 = 11;
int JBC_fconst_1 = 12;
int JBC_fconst_2 = 13;
int JBC_dconst_0 = 14;
int JBC_dconst_1 = 15;
int JBC_bipush = 16;
int JBC_sipush = 17;
int JBC_ldc = 18;
int JBC_ldc_w = 19;
int JBC_ldc2_w = 20;
int JBC_iload = 21;
int JBC_lload = 22;
int JBC_fload = 23;
int JBC_dload = 24;
int JBC_aload = 25;
int JBC_iload_0 = 26;
int JBC_iload_1 = 27;
int JBC_iload_2 = 28;
int JBC_iload_3 = 29;
int JBC_lload_0 = 30;
int JBC_lload_1 = 31;
int JBC_lload_2 = 32;
int JBC_lload_3 = 33;
int JBC_fload_0 = 34;
int JBC_fload_1 = 35;
int JBC_fload_2 = 36;
int JBC_fload_3 = 37;
int JBC_dload_0 = 38;
int JBC_dload_1 = 39;
int JBC_dload_2 = 40;
int JBC_dload_3 = 41;
int JBC_aload_0 = 42;
int JBC_aload_1 = 43;
int JBC_aload_2 = 44;
int JBC_aload_3 = 45;
int JBC_iaload = 46;
int JBC_laload = 47;
int JBC_faload = 48;
int JBC_daload = 49;
int JBC_aaload = 50;
int JBC_baload = 51;
int JBC_caload = 52;
int JBC_saload = 53;
int JBC_istore = 54;
int JBC_lstore = 55;
int JBC_fstore = 56;
int JBC_dstore = 57;
int JBC_astore = 58;
int JBC_istore_0 = 59;
int JBC_istore_1 = 60;
int JBC_istore_2 = 61;
int JBC_istore_3 = 62;
int JBC_lstore_0 = 63;
int JBC_lstore_1 = 64;
int JBC_lstore_2 = 65;
int JBC_lstore_3 = 66;
int JBC_fstore_0 = 67;
int JBC_fstore_1 = 68;
int JBC_fstore_2 = 69;
int JBC_fstore_3 = 70;
int JBC_dstore_0 = 71;
int JBC_dstore_1 = 72;
int JBC_dstore_2 = 73;
int JBC_dstore_3 = 74;
int JBC_astore_0 = 75;
int JBC_astore_1 = 76;
int JBC_astore_2 = 77;
int JBC_astore_3 = 78;
int JBC_iastore = 79;
int JBC_lastore = 80;
int JBC_fastore = 81;
int JBC_dastore = 82;
int JBC_aastore = 83;
int JBC_bastore = 84;
int JBC_castore = 85;
int JBC_sastore = 86;
int JBC_pop = 87;
int JBC_pop2 = 88;
int JBC_dup = 89;
int JBC_dup_x1 = 90;
int JBC_dup_x2 = 91;
int JBC_dup2 = 92;
int JBC_dup2_x1 = 93;
int JBC_dup2_x2 = 94;
int JBC_swap = 95;
int JBC_iadd = 96;
int JBC_ladd = 97;
int JBC_fadd = 98;
int JBC_dadd = 99;
int JBC_isub = 100;
int JBC_lsub = 101;
int JBC_fsub = 102;
int JBC_dsub = 103;
int JBC_imul = 104;
int JBC_lmul = 105;
int JBC_fmul = 106;
int JBC_dmul = 107;
int JBC_idiv = 108;
int JBC_ldiv = 109;
int JBC_fdiv = 110;
int JBC_ddiv = 111;
int JBC_irem = 112;
int JBC_lrem = 113;
int JBC_frem = 114;
int JBC_drem = 115;
int JBC_ineg = 116;
int JBC_lneg = 117;
int JBC_fneg = 118;
int JBC_dneg = 119;
int JBC_ishl = 120;
int JBC_lshl = 121;
int JBC_ishr = 122;
int JBC_lshr = 123;
int JBC_iushr = 124;
int JBC_lushr = 125;
int JBC_iand = 126;
int JBC_land = 127;
int JBC_ior = 128;
int JBC_lor = 129;
int JBC_ixor = 130;
int JBC_lxor = 131;
int JBC_iinc = 132;
int JBC_i2l = 133;
int JBC_i2f = 134;
int JBC_i2d = 135;
int JBC_l2i = 136;
int JBC_l2f = 137;
int JBC_l2d = 138;
int JBC_f2i = 139;
int JBC_f2l = 140;
int JBC_f2d = 141;
int JBC_d2i = 142;
int JBC_d2l = 143;
int JBC_d2f = 144;
int JBC_int2byte = 145;
int JBC_int2char = 146;
int JBC_int2short = 147;
int JBC_lcmp = 148;
int JBC_fcmpl = 149;
int JBC_fcmpg = 150;
int JBC_dcmpl = 151;
int JBC_dcmpg = 152;
int JBC_ifeq = 153;
int JBC_ifne = 154;
int JBC_iflt = 155;
int JBC_ifge = 156;
int JBC_ifgt = 157;
int JBC_ifle = 158;
int JBC_if_icmpeq = 159;
int JBC_if_icmpne = 160;
int JBC_if_icmplt = 161;
int JBC_if_icmpge = 162;
int JBC_if_icmpgt = 163;
int JBC_if_icmple = 164;
int JBC_if_acmpeq = 165;
int JBC_if_acmpne = 166;
int JBC_goto = 167;
int JBC_jsr = 168;
int JBC_ret = 169;
int JBC_tableswitch = 170;
int JBC_lookupswitch = 171;
int JBC_ireturn = 172;
int JBC_lreturn = 173;
int JBC_freturn = 174;
int JBC_dreturn = 175;
int JBC_areturn = 176;
int JBC_return = 177;
int JBC_getstatic = 178;
int JBC_putstatic = 179;
int JBC_getfield = 180;
int JBC_putfield = 181;
int JBC_invokevirtual = 182;
int JBC_invokespecial = 183;
int JBC_invokestatic = 184;
int JBC_invokeinterface = 185;
int JBC_xxxunusedxxx = 186;
int JBC_new = 187;
int JBC_newarray = 188;
int JBC_anewarray = 189;
int JBC_arraylength = 190;
int JBC_athrow = 191;
int JBC_checkcast = 192;
int JBC_instanceof = 193;
int JBC_monitorenter = 194;
int JBC_monitorexit = 195;
int JBC_wide = 196;
int JBC_multianewarray = 197;
int JBC_ifnull = 198;
int JBC_ifnonnull = 199;
int JBC_goto_w = 200;
int JBC_jsr_w = 201;
int JBC_impdep1 = 254;
int JBC_impdep2 = 255;
// Length of each instruction introduced by the above bytecodes.
// -1 indicates a variable length instruction.
// -2 indicates an unused instruction.
//
byte JBC_length[] = {
1, // nop
1, // aconst_null
1, // iconst_m1
1, // iconst_0
1, // iconst_1
1, // iconst_2
1, // iconst_3
1, // iconst_4
1, // iconst_5
1, // lconst_0
1, // lconst_1
1, // fconst_0
1, // fconst_1
1, // fconst_2
1, // dconst_0
1, // dconst_1
2, // bipush
3, // sipush
2, // ldc
3, // ldc_w
3, // ldc2_w
2, // iload
2, // lload
2, // fload
2, // dload
2, // aload
1, // iload_0
1, // iload_1
1, // iload_2
1, // iload_3
1, // lload_0
1, // lload_1
1, // lload_2
1, // lload_3
1, // fload_0
1, // fload_1
1, // fload_2
1, // fload_3
1, // dload_0
1, // dload_1
1, // dload_2
1, // dload_3
1, // aload_0
1, // aload_1
1, // aload_2
1, // aload_3
1, // iaload
1, // laload
1, // faload
1, // daload
1, // aaload
1, // baload
1, // caload
1, // saload
2, // istore
2, // lstore
2, // fstore
2, // dstore
2, // astore
1, // istore_0
1, // istore_1
1, // istore_2
1, // istore_3
1, // lstore_0
1, // lstore_1
1, // lstore_2
1, // lstore_3
1, // fstore_0
1, // fstore_1
1, // fstore_2
1, // fstore_3
1, // dstore_0
1, // dstore_1
1, // dstore_2
1, // dstore_3
1, // astore_0
1, // astore_1
1, // astore_2
1, // astore_3
1, // iastore
1, // lastore
1, // fastore
1, // dastore
1, // aastore
1, // bastore
1, // castore
1, // sastore
1, // pop
1, // pop2
1, // dup
1, // dup_x1
1, // dup_x2
1, // dup2
1, // dup2_x1
1, // dup2_x2
1, // swap
1, // iadd
1, // ladd
1, // fadd
1, // dadd
1, // isub
1, // lsub
1, // fsub
1, // dsub
1, // imul
1, // lmul
1, // fmul
1, // dmul
1, // idiv
1, // ldiv
1, // fdiv
1, // ddiv
1, // irem
1, // lrem
1, // frem
1, // drem
1, // ineg
1, // lneg
1, // fneg
1, // dneg
1, // ishl
1, // lshl
1, // ishr
1, // lshr
1, // iushr
1, // lushr
1, // iand
1, // land
1, // ior
1, // lor
1, // ixor
1, // lxor
3, // iinc
1, // i2l
1, // i2f
1, // i2d
1, // l2i
1, // l2f
1, // l2d
1, // f2i
1, // f2l
1, // f2d
1, // d2i
1, // d2l
1, // d2f
1, // int2byte
1, // int2char
1, // int2short
1, // lcmp
1, // fcmpl
1, // fcmpg
1, // dcmpl
1, // dcmpg
3, // ifeq
3, // ifne
3, // iflt
3, // ifge
3, // ifgt
3, // ifle
3, // if_icmpeq
3, // if_icmpne
3, // if_icmplt
3, // if_icmpge
3, // if_icmpgt
3, // if_icmple
3, // if_acmpeq
3, // if_acmpne
3, // goto
3, // jsr
2, // ret
-1, // tableswitch
-1, // lookupswitch
1, // ireturn
1, // lreturn
1, // freturn
1, // dreturn
1, // areturn
1, // return
3, // getstatic
3, // putstatic
3, // getfield
3, // putfield
3, // invokevirtual
3, // invokenonvirtual
3, // invokestatic
5, // invokeinterface
-2, // xxxunusedxxx
3, // new
2, // newarray
3, // anewarray
1, // arraylength
1, // athrow
3, // checkcast
3, // instanceof
1, // monitorenter
1, // monitorexit
-1, // wide
4, // multianewarray
3, // ifnull
3, // ifnonnull
5, // goto_w
5, // jsr_w
};
/** Bytecode names (for debugging/printing) */
String JBC_name[] = {
"nop",
"aconst_null",
"iconst_m1",
"iconst_0",
"iconst_1",
"iconst_2",
"iconst_3",
"iconst_4",
"iconst_5",
"lconst_0",
"lconst_1",
"fconst_0",
"fconst_1",
"fconst_2",
"dconst_0",
"dconst_1",
"bipush",
"sipush",
"ldc",
"ldc_w",
"ldc2_w",
"iload",
"lload",
"fload",
"dload",
"aload",
"iload_0",
"iload_1",
"iload_2",
"iload_3",
"lload_0",
"lload_1",
"lload_2",
"lload_3",
"fload_0",
"fload_1",
"fload_2",
" fload_3",
" dload_0",
" dload_1",
" dload_2",
" dload_3",
" aload_0",
" aload_1",
" aload_2",
" aload_3",
" iaload",
" laload",
" faload",
" daload",
" aaload",
" baload",
" caload",
" saload",
" istore",
" lstore",
" fstore",
" dstore",
" astore",
" istore_0",
" istore_1",
" istore_2",
" istore_3",
" lstore_0",
" lstore_1",
" lstore_2",
" lstore_3",
" fstore_0",
" fstore_1",
" fstore_2",
" fstore_3",
" dstore_0",
" dstore_1",
" dstore_2",
" dstore_3",
" astore_0",
" astore_1",
" astore_2",
" astore_3",
"iastore",
"lastore",
"fastore",
"dastore",
"aastore",
"bastore",
"castore",
"sastore",
"pop",
"pop2",
"dup",
"dup_x1",
"dup_x2",
"dup2",
"dup2_x1",
"dup2_x2",
"swap",
"iadd",
"ladd",
"fadd",
"dadd",
"isub",
"lsub",
"fsub",
"dsub",
"imul",
"lmul",
"fmul",
"dmul",
"idiv",
"ldiv",
"fdiv",
"ddiv",
"irem",
"lrem",
"frem",
"drem",
"ineg",
"lneg",
"fneg",
"dneg",
"ishl",
"lshl",
"ishr",
"lshr",
"iushr",
"lushr",
"iand",
"land",
"ior",
"lor",
"ixor",
"lxor",
"iinc",
"i2l",
"i2f",
"i2d",
"l2i",
"l2f",
"l2d",
"f2i",
"f2l",
"f2d",
"d2i",
"d2l",
"d2f",
"int2byte",
"int2char",
"int2short",
"lcmp",
"fcmpl",
"fcmpg",
"dcmpl",
"dcmpg",
"ifeq",
"ifne",
"iflt",
"ifge",
"ifgt",
"ifle",
"if_icmpeq",
"if_icmpne",
"if_icmplt",
"if_icmpge",
"if_icmpgt",
"if_icmple",
"if_acmpeq",
"if_acmpne",
"goto",
"jsr",
"ret",
" tableswitch",
" lookupswitch",
"ireturn",
"lreturn",
"freturn",
"dreturn",
"areturn",
"return",
"getstatic",
"putstatic",
"getfield",
"putfield",
"invokevirtual",
"invokenonvirtual",
"invokestatic",
"invokeinterface",
" xxxunusedxxx",
"new",
"newarray",
"anewarray",
"arraylength",
"athrow",
"checkcast",
"instanceof",
"monitorenter",
"monitorexit",
" wide",
"multianewarray",
"ifnull",
"ifnonnull",
"goto_w",
"jsr_w",
};
}
| 12,516
| 13.77804
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/CheckCastInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents checkcast instructions. */
public final class CheckCastInstruction extends Instruction implements ITypeTestInstruction {
private final String type;
private CheckCastInstruction(String type) {
super(OP_checkcast);
this.type = type;
}
public static CheckCastInstruction make(String type) {
if (type == null) {
throw new IllegalArgumentException("type is null");
}
return new CheckCastInstruction(type.intern());
}
@Override
public boolean equals(Object o) {
if (o instanceof CheckCastInstruction) {
CheckCastInstruction i = (CheckCastInstruction) o;
return i.type.equals(type);
} else {
return false;
}
}
@Override
public int hashCode() {
return 131111 + type.hashCode();
}
@Override
public int getPoppedCount() {
return 1;
}
/** @return the type to which the operand is cast */
@Override
public String[] getTypes() {
return new String[] {type};
}
@Override
public String getPushedType(String[] types) {
return type;
}
@Override
public byte getPushedWordSize() {
return 1;
}
@Override
public void visit(IInstruction.Visitor v) {
if (v == null) {
throw new IllegalArgumentException();
}
v.visitCheckCast(this);
}
@Override
public String toString() {
return "CheckCast(" + type + ')';
}
@Override
public boolean isPEI() {
return true;
}
@Override
public boolean firstClassTypes() {
return false;
}
}
| 1,924
| 20.875
| 93
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ComparisonInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/** This class represents comparisons between floats, longs and doubles. */
public final class ComparisonInstruction extends Instruction implements IComparisonInstruction {
private ComparisonInstruction(short opcode) {
super(opcode);
}
private static final ComparisonInstruction preallocatedLCMP = new ComparisonInstruction(OP_lcmp);
private static final ComparisonInstruction[] preallocatedFloatingCompares =
preallocateFloatingCompares();
private static ComparisonInstruction[] preallocateFloatingCompares() {
ComparisonInstruction[] r = new ComparisonInstruction[OP_dcmpg - OP_fcmpl + 1];
for (short i = OP_fcmpl; i <= OP_dcmpg; i++) {
r[i - OP_fcmpl] = new ComparisonInstruction(i);
}
return r;
}
public static ComparisonInstruction make(String type, Operator operator)
throws IllegalArgumentException {
int t = Util.getTypeIndex(type);
switch (t) {
case TYPE_long_index:
if (operator != Operator.CMP) {
throw new IllegalArgumentException(
"Operator " + operator + " is not a valid comparison operator for longs");
} else {
return preallocatedLCMP;
}
case TYPE_float_index:
case TYPE_double_index:
if (operator == Operator.CMP) {
throw new IllegalArgumentException(
"Operator "
+ operator
+ " is not a valid comparison operator for floating point values");
} else {
return preallocatedFloatingCompares[
(operator.ordinal() - Operator.CMPL.ordinal()) + (t - TYPE_float_index) * 2];
}
default:
throw new IllegalArgumentException("Type " + type + " cannot be compared");
}
}
@Override
public boolean equals(Object o) {
if (o instanceof ComparisonInstruction) {
ComparisonInstruction i = (ComparisonInstruction) o;
return i.opcode == opcode;
} else {
return false;
}
}
/** @return OPR_cmp (for long), OPR_cmpl, or OPR_cmpg (for float and double) */
@Override
public Operator getOperator() {
switch (opcode) {
case OP_lcmp:
return Operator.CMP;
case OP_fcmpl:
case OP_dcmpl:
return Operator.CMPL;
case OP_dcmpg:
case OP_fcmpg:
return Operator.CMPG;
default:
throw new Error("Unknown opcode");
}
}
@Override
public String getType() {
switch (opcode) {
case OP_lcmp:
return TYPE_long;
case OP_fcmpg:
case OP_fcmpl:
return TYPE_float;
case OP_dcmpl:
case OP_dcmpg:
return TYPE_double;
default:
throw new Error("Unknown opcode");
}
}
@Override
public int hashCode() {
return opcode + 1391901;
}
@Override
public int getPoppedCount() {
return 2;
}
@Override
public String getPushedType(String[] types) {
return Constants.TYPE_boolean;
}
@Override
public byte getPushedWordSize() {
return 1;
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitComparison(this);
}
@Override
public String toString() {
return "Comparison(" + getType() + ',' + getOperator() + ')';
}
@Override
public boolean isPEI() {
return false;
}
}
| 3,712
| 26.10219
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/Compiler.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import com.ibm.wala.shrike.shrikeBT.ConstantInstruction.ClassToken;
import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction.Operator;
import com.ibm.wala.shrike.shrikeBT.analysis.ClassHierarchyProvider;
import com.ibm.wala.shrike.shrikeBT.analysis.Verifier;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser.ReferenceToken;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
/**
* This class generates Java bytecode from ShrikeBT Instructions.
*
* <p>If there are too many instructions to fit into 64K bytecodes, then we break the method up,
* generating auxiliary methods called by the main method.
*
* <p>This class is abstract; there are subclasses for specific class file access toolkits. These
* toolkits are responsible for providing ways to allocate constant pool entries.
*/
public abstract class Compiler implements Constants {
// input
private final boolean isConstructor;
private final boolean isStatic;
private final String classType;
private final String signature;
private final IInstruction[] instructions;
private final ExceptionHandler[][] handlers;
private final int[] instructionsToBytecodes;
private static final int[] noRawHandlers = new int[0];
private ClassHierarchyProvider hierarchy;
private ConstantPoolReader presetConstants;
// working
private int[] instructionsToOffsets;
private BitSet branchTargets;
private byte[][] stackWords;
private byte[] code;
// working on breaking up overlarge methods
private int allocatedLocals;
private BitSet[] liveLocals;
private int[][] backEdges;
private String[][] localTypes;
private String[][] stackTypes;
// output
private int maxLocals;
private int maxStack;
private Output mainMethod;
private ArrayList<Output> auxMethods;
/**
* Initialize a Compiler for the given method data.
*
* @param isStatic true iff the method is static
* @param classType the JVM type of the class the method belongs to
* @param signature the JVM signature of the method
* @param instructions the ShrikeBT instructions
* @param handlers the ShrikeBT exception handlers
* @param instructionsToBytecodes the map from instructions to original bytecode offsets
* @throws IllegalArgumentException if handlers is null
* @throws IllegalArgumentException if instructions is null
* @throws IllegalArgumentException if instructionsToBytecodes is null
*/
public Compiler(
boolean isConstructor,
boolean isStatic,
String classType,
String signature,
IInstruction[] instructions,
ExceptionHandler[][] handlers,
int[] instructionsToBytecodes) {
if (instructionsToBytecodes == null) {
throw new IllegalArgumentException("instructionsToBytecodes is null");
}
if (instructions == null) {
throw new IllegalArgumentException("instructions is null");
}
if (handlers == null) {
throw new IllegalArgumentException("handlers is null");
}
if (instructions.length != handlers.length) {
throw new IllegalArgumentException("Instructions/handlers length mismatch");
}
if (instructions.length != instructionsToBytecodes.length) {
throw new IllegalArgumentException("Instructions/handlers length mismatch");
}
this.isConstructor = isConstructor;
this.isStatic = isStatic;
this.classType = classType;
this.signature = signature;
this.instructions = instructions;
this.handlers = handlers;
this.instructionsToBytecodes = instructionsToBytecodes;
}
/** Extract the data for the method to be compiled from the MethodData container. */
protected Compiler(MethodData info) {
this(
info.getName().equals("<init>"),
info.getIsStatic(),
info.getClassType(),
info.getSignature(),
info.getInstructions(),
info.getHandlers(),
info.getInstructionsToBytecodes());
}
/** @return the JVM type for the class this method belongs to */
public final String getClassType() {
return classType;
}
/**
* Notify the compiler that the constants appearing in the ConstantPoolReader cp will appear in
* the final class file.
*
* <p>Instructions which were extracted from a class file with the same ConstantPoolReader can be
* written back much more efficiently if the same constant pool indices are valid in the new class
* file.
*/
public final void setPresetConstants(ConstantPoolReader cp) {
presetConstants = cp;
}
public final void setClassHierarchy(ClassHierarchyProvider h) {
this.hierarchy = h;
}
protected abstract int allocateConstantPoolInteger(int v);
protected abstract int allocateConstantPoolFloat(float v);
protected abstract int allocateConstantPoolLong(long v);
protected abstract int allocateConstantPoolDouble(double v);
protected abstract int allocateConstantPoolString(String v);
protected abstract int allocateConstantPoolClassType(String c);
protected abstract int allocateConstantPoolMethodType(String c);
protected abstract int allocateConstantPoolMethodHandle(ReferenceToken c);
protected abstract int allocateConstantPoolField(String c, String name, String type);
protected abstract int allocateConstantPoolMethod(String c, String name, String sig);
protected abstract int allocateConstantPoolInterfaceMethod(String c, String name, String sig);
protected abstract int allocateConstantPoolInvokeDynamic(
BootstrapMethod b, String name, String type);
protected abstract String createHelperMethod(boolean isStatic, String sig);
private void collectInstructionInfo() {
final BitSet s = new BitSet(instructions.length);
final BitSet localsUsed = new BitSet(32);
final BitSet localsWide = new BitSet(32);
IInstruction.Visitor visitor =
new IInstruction.Visitor() {
private void visitTargets(IInstruction instr) {
int[] ts = instr.getBranchTargets();
for (int element : ts) {
s.set(element);
}
}
@Override
public void visitGoto(GotoInstruction instruction) {
visitTargets(instruction);
}
@Override
public void visitLocalStore(IStoreInstruction instruction) {
localsUsed.set(instruction.getVarIndex());
String t = instruction.getType();
if (t.equals(TYPE_long) || t.equals(TYPE_double)) {
localsWide.set(instruction.getVarIndex());
}
}
@Override
public void visitConditionalBranch(IConditionalBranchInstruction instruction) {
visitTargets(instruction);
}
@Override
public void visitSwitch(SwitchInstruction instruction) {
visitTargets(instruction);
}
};
for (IInstruction instruction : instructions) {
instruction.visit(visitor);
}
String[] paramTypes = Util.getParamsTypes(isStatic ? null : TYPE_Object, signature);
int index = 0;
for (String t : paramTypes) {
localsUsed.set(index);
if (t.equals(TYPE_long) || t.equals(TYPE_double)) {
localsWide.set(index);
index += 2;
} else {
index++;
}
}
ExceptionHandler[] lastHS = null;
for (ExceptionHandler[] hs : handlers) {
if (hs != lastHS) {
for (ExceptionHandler element : hs) {
s.set(element.handler);
}
lastHS = hs;
}
}
this.branchTargets = s;
int maxUsed = localsUsed.length();
if (maxUsed > 0 && localsWide.get(maxUsed - 1)) {
maxUsed++;
}
this.maxLocals = maxUsed;
}
private void writeInt(int offset, int v) {
code[offset] = (byte) (v >> 24);
code[offset + 1] = (byte) (v >> 16);
code[offset + 2] = (byte) (v >> 8);
code[offset + 3] = (byte) v;
}
private void writeShort(int offset, int v) {
code[offset] = (byte) (v >> 8);
code[offset + 1] = (byte) v;
}
private void writeByte(int offset, int v) {
code[offset] = (byte) v;
}
private boolean inBasicBlock(int i, int n) {
if (i + n - 1 >= instructions.length) {
return false;
}
for (int j = i + 1; j < i + n; j++) {
if (branchTargets.get(j)) {
return false;
}
if (!Arrays.equals(handlers[j], handlers[i])) {
return false;
}
if (instructionsToBytecodes[j] != instructionsToBytecodes[i]) {
return false;
}
}
return true;
}
private void checkStackWordSize(byte[] stackWords, int stackLen) {
if (stackLen * 2 > maxStack) {
int words = 0;
for (int i = 0; i < stackLen; i++) {
words += stackWords[i];
}
if (words > maxStack) {
maxStack = words;
}
}
}
// private static int getStackDelta(Instruction instr) {
// if (instr instanceof DupInstruction) {
// return ((DupInstruction) instr).getSize();
// } else {
// return (instr.getPushedWordSize() > 0 ? 1 : 0) - instr.getPoppedCount();
// }
// }
private void computeStackWordsAt(int i, int stackLen, byte[] stackWords, boolean[] visited) {
while (!visited[i]) {
IInstruction instr = instructions[i];
if (i > 0 && !instructions[i - 1].isFallThrough()) {
byte[] newWords = new byte[stackLen];
System.arraycopy(stackWords, 0, newWords, 0, stackLen);
this.stackWords[i] = newWords;
}
visited[i] = true;
if (stackLen < instr.getPoppedCount()) {
throw new IllegalArgumentException("Stack underflow in intermediate code, at offset " + i);
}
if (instr instanceof DupInstruction) {
DupInstruction d = (DupInstruction) instr;
int size = d.getSize();
int delta = d.getDelta();
System.arraycopy(
stackWords, stackLen - size - delta, stackWords, stackLen - delta, delta + size);
System.arraycopy(stackWords, stackLen, stackWords, stackLen - size - delta, size);
stackLen += size;
checkStackWordSize(stackWords, stackLen);
} else if (instr instanceof SwapInstruction) {
// we may have to emulate this using a dup[2]_x[1,2]
// followed by a pop[2]. So update the maxStack to account for the
// temporarily larger stack size
int words = stackWords[stackLen - 1];
for (int j = 0; j < stackLen; j++) {
words += stackWords[j];
}
if (words > maxStack) {
maxStack = words;
}
byte b = stackWords[stackLen - 2];
stackWords[stackLen - 2] = stackWords[stackLen - 1];
stackWords[stackLen - 1] = b;
} else {
stackLen -= instr.getPoppedCount();
byte w = instr.getPushedWordSize();
if (w > 0) {
stackWords[stackLen] = w;
stackLen++;
checkStackWordSize(stackWords, stackLen);
}
}
int[] bt = instr.getBranchTargets();
for (int element : bt) {
int t = element;
if (t < 0 || t >= visited.length) {
throw new IllegalArgumentException(
"Branch target at offset "
+ i
+ " is out of bounds: "
+ t
+ " (max "
+ visited.length
+ ')');
}
if (!visited[t]) {
computeStackWordsAt(element, stackLen, stackWords.clone(), visited);
}
}
ExceptionHandler[] hs = handlers[i];
for (ExceptionHandler element : hs) {
int t = element.handler;
if (!visited[t]) {
byte[] newWords = stackWords.clone();
newWords[0] = 1;
computeStackWordsAt(t, 1, newWords, visited);
}
}
if (!instr.isFallThrough()) {
return;
}
i++;
}
}
private void computeStackWords() {
stackWords = new byte[instructions.length][];
maxStack = 0;
computeStackWordsAt(0, 0, new byte[instructions.length * 2], new boolean[instructions.length]);
}
abstract static class Patch {
final int instrStart;
final int instrOffset;
final int targetLabel;
Patch(int instrStart, int instrOffset, int targetLabel) {
this.instrStart = instrStart;
this.instrOffset = instrOffset;
this.targetLabel = targetLabel;
}
abstract boolean apply();
}
class ShortPatch extends Patch {
ShortPatch(int instrStart, int instrOffset, int targetLabel) {
super(instrStart, instrOffset, targetLabel);
}
@Override
boolean apply() {
int delta = instructionsToOffsets[targetLabel] - instrStart;
if ((short) delta == delta) {
writeShort(instrOffset, delta);
return true;
} else {
return false;
}
}
}
class IntPatch extends Patch {
IntPatch(int instrStart, int instrOffset, int targetLabel) {
super(instrStart, instrOffset, targetLabel);
}
@Override
boolean apply() {
writeInt(instrOffset, instructionsToOffsets[targetLabel] - instrStart);
return true;
}
}
private void insertBranchOffsetInt(
ArrayList<Patch> patches, int instrStart, int instrOffset, int targetLabel) {
if (instructionsToOffsets[targetLabel] > 0 || targetLabel == 0) {
writeInt(instrOffset, instructionsToOffsets[targetLabel] - instrStart);
} else {
patches.add(new IntPatch(instrStart, instrOffset, targetLabel));
}
}
private static boolean applyPatches(ArrayList<Patch> patches) {
for (Patch p : patches) {
if (!p.apply()) {
return false;
}
}
return true;
}
private static byte[] cachedBuf;
private static synchronized byte[] makeCodeBuf() {
if (cachedBuf != null) {
byte[] result = cachedBuf;
cachedBuf = null;
return result;
} else {
return new byte[65535];
}
}
private static synchronized void releaseCodeBuf(byte[] buf) {
cachedBuf = buf;
}
private boolean outputInstructions(
int startInstruction,
int endInstruction,
int startOffset,
boolean farBranches,
byte[] initialStack) {
instructionsToOffsets = new int[instructions.length];
code = makeCodeBuf();
ArrayList<Patch> patches = new ArrayList<>();
int curOffset = startOffset;
final int[] curOffsetRef = new int[1];
int stackLen = initialStack == null ? 0 : initialStack.length;
final int[] stackLenRef = new int[1];
final byte[] stackWords = new byte[maxStack];
if (stackLen > 0) {
System.arraycopy(initialStack, 0, stackWords, 0, stackLen);
}
final int[] instrRef = new int[1];
IInstruction.Visitor noOpcodeHandler =
new IInstruction.Visitor() {
@Override
public void visitPop(PopInstruction instruction) {
int count = instruction.getPoppedCount();
int offset = curOffsetRef[0];
int stackLen = stackLenRef[0];
while (count > 0) {
code[offset] = (byte) (stackWords[stackLen - 1] == 1 ? OP_pop : OP_pop2);
count--;
stackLen--;
offset++;
}
curOffsetRef[0] = offset;
}
@Override
public void visitDup(DupInstruction instruction) {
int size = instruction.getSize();
int delta = instruction.getDelta();
int offset = curOffsetRef[0];
int stackLen = stackLenRef[0];
int sizeWords = stackWords[stackLen - 1];
if (size == 2) {
sizeWords += stackWords[stackLen - 2];
}
int deltaWords = delta == 0 ? 0 : stackWords[stackLen - 1 - size];
if (delta == 2) {
deltaWords += stackWords[stackLen - 1 - size - 1];
}
if (sizeWords > 2 || deltaWords > 2) {
throw new IllegalArgumentException("Invalid dup size");
}
code[offset] = (byte) (OP_dup + (3 * (sizeWords - 1)) + deltaWords);
offset++;
curOffsetRef[0] = offset;
}
@Override
public void visitSwap(SwapInstruction instruction) {
int offset = curOffsetRef[0];
int stackLen = stackLenRef[0];
int topSize = stackWords[stackLen - 1];
int nextSize = stackWords[stackLen - 2];
if (topSize == 1 && nextSize == 1) {
code[offset] = (byte) OP_swap;
offset++;
} else {
code[offset] = (byte) (OP_dup + (3 * (topSize - 1)) + nextSize);
code[offset + 1] = (byte) (topSize == 1 ? OP_pop : OP_pop2);
offset += 2;
}
curOffsetRef[0] = offset;
}
};
for (int i = startInstruction; i < endInstruction; i++) {
Instruction instr = (Instruction) instructions[i];
int opcode = instr.getOpcode();
int startI = i;
instructionsToOffsets[i] = curOffset;
if (opcode != -1) {
boolean fallToConditional = false;
code[curOffset] = (byte) opcode;
curOffset++;
switch (opcode) {
case OP_iconst_0:
if (inBasicBlock(i, 2) && instructions[i + 1] instanceof ConditionalBranchInstruction) {
ConditionalBranchInstruction cbr = (ConditionalBranchInstruction) instructions[i + 1];
if (cbr.getType().equals(TYPE_int)) {
code[curOffset - 1] = (byte) (cbr.getOperator().ordinal() + OP_ifeq);
fallToConditional = true;
i++;
instr = (Instruction) instructions[i];
}
}
if (!fallToConditional) {
break;
}
// $FALL-THROUGH$
case OP_aconst_null:
if (!fallToConditional
&& inBasicBlock(i, 2)
&& instructions[i + 1] instanceof ConditionalBranchInstruction) {
ConditionalBranchInstruction cbr = (ConditionalBranchInstruction) instructions[i + 1];
if (cbr.getType().equals(TYPE_Object)) {
code[curOffset - 1] = (byte) (cbr.getOperator().ordinal() + OP_ifnull);
fallToConditional = true;
i++;
instr = (Instruction) instructions[i];
}
}
if (!fallToConditional) {
break;
}
// by Xiangyu
// $FALL-THROUGH$
case OP_ifeq:
case OP_ifge:
case OP_ifgt:
case OP_ifle:
case OP_iflt:
case OP_ifne:
{
int targetI = instr.getBranchTargets()[0];
boolean invert = false;
int iStart = curOffset - 1;
if (inBasicBlock(i, 2)
&& instr.getBranchTargets()[0] == i + 2
&& instructions[i + 1] instanceof GotoInstruction) {
invert = true;
targetI = instructions[i + 1].getBranchTargets()[0];
i++;
}
if (targetI <= i) {
int delta = instructionsToOffsets[targetI] - iStart;
if ((short) delta != delta) {
// emit "if_!XX TMP; goto_w L; TMP:"
invert = !invert;
writeShort(curOffset, 8);
code[curOffset + 2] = (byte) OP_goto_w;
writeInt(curOffset + 3, delta - 3);
curOffset += 7;
} else {
writeShort(curOffset, (short) delta);
curOffset += 2;
}
} else {
Patch p;
if (farBranches) {
// emit "if_!XX TMP; goto_w L; TMP:"
invert = !invert;
writeShort(curOffset, 8);
code[curOffset + 2] = (byte) OP_goto_w;
p = new IntPatch(curOffset + 2, curOffset + 3, targetI);
curOffset += 7;
} else {
p = new ShortPatch(iStart, curOffset, targetI);
curOffset += 2;
}
patches.add(p);
}
if (invert) {
code[iStart] = (byte) (((code[iStart] - OP_ifeq) ^ 1) + OP_ifeq);
}
break;
}
// by Xiangyu
case OP_if_icmpeq:
case OP_if_icmpge:
case OP_if_icmpgt:
case OP_if_icmple:
case OP_if_icmplt:
case OP_if_icmpne:
case OP_if_acmpeq:
case OP_if_acmpne:
{
int targetI = instr.getBranchTargets()[0];
boolean invert = false;
int iStart = curOffset - 1;
if (inBasicBlock(i, 2)
&& instr.getBranchTargets()[0] == i + 2
&& instructions[i + 1] instanceof GotoInstruction) {
invert = true;
targetI = instructions[i + 1].getBranchTargets()[0];
i++;
}
if (targetI <= i) {
int delta = instructionsToOffsets[targetI] - iStart;
if ((short) delta != delta) {
// emit "if_!XX TMP; goto_w L; TMP:"
invert = !invert;
writeShort(curOffset, 8);
code[curOffset + 2] = (byte) OP_goto_w;
writeInt(curOffset + 3, delta - 3);
curOffset += 7;
} else {
writeShort(curOffset, (short) delta);
curOffset += 2;
}
} else {
Patch p;
if (farBranches) {
// emit "if_!XX TMP; goto_w L; TMP:"
invert = !invert;
writeShort(curOffset, 8);
code[curOffset + 2] = (byte) OP_goto_w;
p = new IntPatch(curOffset + 2, curOffset + 3, targetI);
curOffset += 7;
} else {
p = new ShortPatch(iStart, curOffset, targetI);
curOffset += 2;
}
patches.add(p);
}
if (invert) {
code[iStart] = (byte) (((code[iStart] - OP_if_icmpeq) ^ 1) + OP_if_icmpeq);
}
break;
}
case OP_bipush:
writeByte(curOffset, ((ConstantInstruction.ConstInt) instr).getIntValue());
curOffset++;
break;
case OP_sipush:
writeShort(curOffset, ((ConstantInstruction.ConstInt) instr).getIntValue());
curOffset += 2;
break;
case OP_ldc_w:
{
int cpIndex;
ConstantInstruction ci = (ConstantInstruction) instr;
if (presetConstants != null && ci.getLazyConstantPool() == presetConstants) {
cpIndex = ci.getCPIndex();
} else {
String t = instr.getPushedType(null);
switch (t) {
case TYPE_int:
cpIndex =
allocateConstantPoolInteger(
((ConstantInstruction.ConstInt) instr).getIntValue());
break;
case TYPE_String:
cpIndex =
allocateConstantPoolString(
(String) ((ConstantInstruction.ConstString) instr).getValue());
break;
case TYPE_Class:
cpIndex =
allocateConstantPoolClassType(
((ClassToken) ((ConstantInstruction.ConstClass) instr).getValue())
.getTypeName());
break;
case TYPE_MethodType:
cpIndex =
allocateConstantPoolMethodType(
((String) ((ConstantInstruction.ConstMethodType) instr).getValue()));
break;
case TYPE_MethodHandle:
cpIndex =
allocateConstantPoolMethodHandle(
((ReferenceToken)
((ConstantInstruction.ConstMethodHandle) instr).getValue()));
break;
default:
cpIndex =
allocateConstantPoolFloat(
((ConstantInstruction.ConstFloat) instr).getFloatValue());
break;
}
}
if (cpIndex < 256) {
code[curOffset - 1] = (byte) OP_ldc;
code[curOffset] = (byte) cpIndex;
curOffset++;
} else {
writeShort(curOffset, cpIndex);
curOffset += 2;
}
break;
}
case OP_ldc2_w:
{
int cpIndex;
ConstantInstruction ci = (ConstantInstruction) instr;
if (presetConstants != null && ci.getLazyConstantPool() == presetConstants) {
cpIndex = ci.getCPIndex();
} else {
String t = instr.getPushedType(null);
if (t.equals(TYPE_long)) {
cpIndex =
allocateConstantPoolLong(
((ConstantInstruction.ConstLong) instr).getLongValue());
} else {
cpIndex =
allocateConstantPoolDouble(
((ConstantInstruction.ConstDouble) instr).getDoubleValue());
}
}
writeShort(curOffset, cpIndex);
curOffset += 2;
break;
}
case OP_iload_0:
case OP_iload_1:
case OP_iload_2:
case OP_iload_3:
case OP_iload:
{
if (inBasicBlock(i, 4)) {
// try to generate an OP_iinc
if (instructions[i + 1] instanceof ConstantInstruction.ConstInt
&& instructions[i + 2] instanceof BinaryOpInstruction
&& instructions[i + 3] instanceof StoreInstruction) {
LoadInstruction i0 = (LoadInstruction) instr;
ConstantInstruction.ConstInt i1 =
(ConstantInstruction.ConstInt) instructions[i + 1];
BinaryOpInstruction i2 = (BinaryOpInstruction) instructions[i + 2];
StoreInstruction i3 = (StoreInstruction) instructions[i + 3];
int c = i1.getIntValue();
int v = i0.getVarIndex();
BinaryOpInstruction.Operator op = i2.getOperator();
if ((short) c == c
&& i3.getVarIndex() == v
&& (op == Operator.ADD || op == Operator.SUB)
&& i2.getType().equals(TYPE_int)
&& i3.getType().equals(TYPE_int)) {
if (v < 256 && (byte) c == c) {
code[curOffset - 1] = (byte) OP_iinc;
writeByte(curOffset, v);
writeByte(curOffset + 1, c);
curOffset += 2;
} else {
code[curOffset - 1] = (byte) OP_wide;
code[curOffset] = (byte) OP_iinc;
writeShort(curOffset + 1, v);
writeShort(curOffset + 3, c);
curOffset += 5;
}
instructionsToOffsets[i + 1] = -1;
instructionsToOffsets[i + 2] = -1;
instructionsToOffsets[i + 3] = -1;
i += 3;
break;
}
}
}
if (opcode != OP_iload) {
break;
}
}
// $FALL-THROUGH$
case OP_lload:
case OP_fload:
case OP_dload:
case OP_aload:
{
int v = ((LoadInstruction) instr).getVarIndex();
if (v < 256) {
writeByte(curOffset, v);
curOffset++;
} else {
code[curOffset - 1] = (byte) OP_wide;
code[curOffset] = (byte) opcode;
writeShort(curOffset + 1, v);
curOffset += 3;
}
break;
}
case OP_istore:
case OP_lstore:
case OP_fstore:
case OP_dstore:
case OP_astore:
{
int v = ((StoreInstruction) instr).getVarIndex();
if (v < 256) {
writeByte(curOffset, v);
curOffset++;
} else {
code[curOffset - 1] = (byte) OP_wide;
code[curOffset] = (byte) opcode;
writeShort(curOffset + 1, v);
curOffset += 3;
}
break;
}
case OP_goto:
{
int targetI = instr.getBranchTargets()[0];
if (targetI <= i) {
int delta = instructionsToOffsets[targetI] - (curOffset - 1);
if ((short) delta != delta) {
code[curOffset - 1] = (byte) OP_goto_w;
writeInt(curOffset, delta);
curOffset += 4;
} else {
writeShort(curOffset, (short) delta);
curOffset += 2;
}
} else if (targetI == i + 1) {
// ignore noop gotos
curOffset--;
} else {
Patch p;
if (farBranches) {
code[curOffset - 1] = (byte) OP_goto_w;
p = new IntPatch(curOffset - 1, curOffset, instr.getBranchTargets()[0]);
curOffset += 4;
} else {
p = new ShortPatch(curOffset - 1, curOffset, instr.getBranchTargets()[0]);
curOffset += 2;
}
patches.add(p);
}
break;
}
case OP_lookupswitch:
{
int start = curOffset - 1;
SwitchInstruction sw = (SwitchInstruction) instr;
int[] casesAndLabels = sw.getCasesAndLabels();
while ((curOffset & 3) != 0) {
writeByte(curOffset, 0);
curOffset++;
}
if (curOffset + 4 * casesAndLabels.length + 8 > code.length) {
return false;
}
insertBranchOffsetInt(patches, start, curOffset, sw.getDefaultLabel());
writeInt(curOffset + 4, casesAndLabels.length / 2);
curOffset += 8;
for (int j = 0; j < casesAndLabels.length; j += 2) {
writeInt(curOffset, casesAndLabels[j]);
insertBranchOffsetInt(patches, start, curOffset + 4, casesAndLabels[j + 1]);
curOffset += 8;
}
break;
}
case OP_tableswitch:
{
int start = curOffset - 1;
SwitchInstruction sw = (SwitchInstruction) instr;
int[] casesAndLabels = sw.getCasesAndLabels();
while ((curOffset & 3) != 0) {
writeByte(curOffset, 0);
curOffset++;
}
if (curOffset + 2 * casesAndLabels.length + 12 > code.length) {
return false;
}
insertBranchOffsetInt(patches, start, curOffset, sw.getDefaultLabel());
writeInt(curOffset + 4, casesAndLabels[0]);
writeInt(curOffset + 8, casesAndLabels[casesAndLabels.length - 2]);
curOffset += 12;
for (int j = 0; j < casesAndLabels.length; j += 2) {
insertBranchOffsetInt(patches, start, curOffset, casesAndLabels[j + 1]);
curOffset += 4;
}
break;
}
case OP_getfield:
case OP_getstatic:
{
GetInstruction g = (GetInstruction) instr;
int cpIndex;
if (presetConstants != null && presetConstants == g.getLazyConstantPool()) {
cpIndex = ((GetInstruction.Lazy) g).getCPIndex();
} else {
cpIndex =
allocateConstantPoolField(g.getClassType(), g.getFieldName(), g.getFieldType());
}
writeShort(curOffset, cpIndex);
curOffset += 2;
break;
}
case OP_putfield:
case OP_putstatic:
{
PutInstruction p = (PutInstruction) instr;
int cpIndex;
if (presetConstants != null && presetConstants == p.getLazyConstantPool()) {
cpIndex = ((PutInstruction.Lazy) p).getCPIndex();
} else {
cpIndex =
allocateConstantPoolField(p.getClassType(), p.getFieldName(), p.getFieldType());
}
writeShort(curOffset, cpIndex);
curOffset += 2;
break;
}
case OP_invokespecial:
case OP_invokestatic:
case OP_invokevirtual:
{
InvokeInstruction inv = (InvokeInstruction) instr;
int cpIndex;
if (presetConstants != null && presetConstants == inv.getLazyConstantPool()) {
cpIndex = ((InvokeInstruction.Lazy) inv).getCPIndex();
} else {
cpIndex =
allocateConstantPoolMethod(
inv.getClassType(), inv.getMethodName(), inv.getMethodSignature());
}
writeShort(curOffset, cpIndex);
curOffset += 2;
break;
}
case OP_invokedynamic:
{
InvokeDynamicInstruction inv = (InvokeDynamicInstruction) instr;
int cpIndex;
if (presetConstants != null && presetConstants == inv.getLazyConstantPool()) {
cpIndex = ((InvokeDynamicInstruction.Lazy) inv).getCPIndex();
} else {
cpIndex =
allocateConstantPoolInvokeDynamic(
inv.getBootstrap(), inv.getMethodName(), inv.getMethodSignature());
}
writeShort(curOffset, cpIndex);
code[curOffset + 2] = 0;
code[curOffset + 3] = 0;
curOffset += 4;
break;
}
case OP_invokeinterface:
{
InvokeInstruction inv = (InvokeInstruction) instr;
String sig = inv.getMethodSignature();
int cpIndex;
if (presetConstants != null && presetConstants == inv.getLazyConstantPool()) {
cpIndex = ((InvokeInstruction.Lazy) inv).getCPIndex();
} else {
cpIndex =
allocateConstantPoolInterfaceMethod(
inv.getClassType(), inv.getMethodName(), sig);
}
writeShort(curOffset, cpIndex);
code[curOffset + 2] = (byte) (Util.getParamsWordSize(sig) + 1);
code[curOffset + 3] = 0;
curOffset += 4;
break;
}
case OP_new:
writeShort(
curOffset, allocateConstantPoolClassType(((NewInstruction) instr).getType()));
curOffset += 2;
break;
case OP_newarray:
code[curOffset] =
indexedTypes_T[Util.getTypeIndex(((NewInstruction) instr).getType().substring(1))];
curOffset++;
break;
case OP_anewarray:
writeShort(
curOffset,
allocateConstantPoolClassType(((NewInstruction) instr).getType().substring(1)));
curOffset += 2;
break;
case OP_multianewarray:
{
NewInstruction n = (NewInstruction) instr;
writeShort(curOffset, allocateConstantPoolClassType(n.getType()));
code[curOffset + 2] = (byte) n.getArrayBoundsCount();
curOffset += 3;
break;
}
case OP_checkcast:
writeShort(
curOffset,
allocateConstantPoolClassType(((CheckCastInstruction) instr).getTypes()[0]));
curOffset += 2;
break;
case OP_instanceof:
writeShort(
curOffset,
allocateConstantPoolClassType(((InstanceofInstruction) instr).getType()));
curOffset += 2;
break;
default:
// do nothing
}
} else {
stackLenRef[0] = stackLen;
curOffsetRef[0] = curOffset;
instrRef[0] = i;
instr.visit(noOpcodeHandler);
curOffset = curOffsetRef[0];
i = instrRef[0];
}
boolean haveStack = true;
while (startI <= i) {
instr = (Instruction) instructions[startI];
if (instr.isFallThrough() && haveStack) {
if (stackLen < instr.getPoppedCount()) {
throw new IllegalArgumentException(
"Stack underflow in intermediate code, at offset " + startI);
}
if (instr instanceof DupInstruction) {
DupInstruction d = (DupInstruction) instr;
int size = d.getSize();
int delta = d.getDelta();
System.arraycopy(
stackWords, stackLen - size - delta, stackWords, stackLen - delta, delta + size);
System.arraycopy(stackWords, stackLen, stackWords, stackLen - size - delta, size);
stackLen += size;
} else if (instr instanceof SwapInstruction) {
byte b = stackWords[stackLen - 1];
stackWords[stackLen - 1] = stackWords[stackLen - 2];
stackWords[stackLen - 2] = b;
} else {
stackLen -= instr.getPoppedCount();
byte w = instr.getPushedWordSize();
if (w > 0) {
stackWords[stackLen] = w;
stackLen++;
}
}
} else {
// No stack, or the instruction doesn't fall through
// try to grab the stack state at the start of the next instruction
if (startI + 1 < endInstruction) {
byte[] s = this.stackWords[startI + 1];
// if the next instruction doesn't have stack info (it's not
// reachable), then just ignore it and remember that we don't have
// stack info
if (s == null) {
haveStack = false;
} else {
stackLen = s.length;
System.arraycopy(s, 0, stackWords, 0, stackLen);
}
}
}
startI++;
}
if (curOffset > code.length - 8) {
return false;
}
if (!haveStack) {
// skip forward through the unreachable instructions until we find
// an instruction for which we know the stack state
while (i + 1 < endInstruction) {
byte[] s = this.stackWords[i + 1];
if (s != null) {
stackLen = s.length;
System.arraycopy(s, 0, stackWords, 0, stackLen);
break;
}
i++;
}
}
}
if (applyPatches(patches)) {
byte[] newCode = new byte[curOffset];
System.arraycopy(code, 0, newCode, 0, curOffset);
releaseCodeBuf(code);
code = newCode;
} else {
if (farBranches) {
throw new Error("Failed to apply patches even with farBranches on");
} else {
return outputInstructions(
startInstruction, endInstruction, startOffset, true, initialStack);
}
}
return true;
}
private int[] buildRawHandlers(int start, int end) {
int[] handlerCounts = new int[end - start];
int maxCount = 0;
for (int i = start; i < end; i++) {
int len = handlers[i].length;
handlerCounts[i - start] = len;
if (len > maxCount) {
maxCount = len;
}
}
if (maxCount == 0) {
return noRawHandlers;
} else {
ArrayList<int[]> rawHandlerList = new ArrayList<>();
for (int i = maxCount; i > 0; i--) {
for (int j = start; j < end; j++) {
if (handlerCounts[j - start] == i) {
int first = j;
ExceptionHandler h = handlers[j][handlers[j].length - i];
do {
handlerCounts[j - start]--;
j++;
} while (j < end
&& handlerCounts[j - start] == i
&& handlers[j][handlers[j].length - i].equals(h));
if (h.handler >= start && h.handler < end) {
rawHandlerList.add(
new int[] {
instructionsToOffsets[first],
j < end ? instructionsToOffsets[j] : code.length,
instructionsToOffsets[h.handler],
h.catchClass == null ? 0 : allocateConstantPoolClassType(h.catchClass)
});
}
j--;
}
}
}
int[] rawHandlers = new int[4 * rawHandlerList.size()];
int count = 0;
for (int[] element : rawHandlerList) {
System.arraycopy(element, 0, rawHandlers, count, 4);
count += 4;
}
return rawHandlers;
}
}
private int[] buildBytecodeMap(int start, int end) {
int[] r = new int[code.length];
Arrays.fill(r, -1);
for (int i = start; i < end; i++) {
int off = instructionsToOffsets[i];
if (off >= 0) {
r[off] = instructionsToBytecodes[i];
}
}
return r;
}
static class HelperPatch {
final int start;
final int length;
final Instruction[] code;
final ExceptionHandler[] handlers;
HelperPatch(int start, int length, Instruction[] code, ExceptionHandler[] handlers) {
this.start = start;
this.length = length;
this.code = code;
this.handlers = handlers;
}
}
private void addBackEdge(int from, int to) {
int[] oldEdges = backEdges[from];
if (oldEdges == null) {
backEdges[from] = new int[] {to};
} else if (oldEdges[oldEdges.length - 1] < 0) {
int left = 1;
int right = oldEdges.length - 1;
while (true) {
if (right - left < 2) {
if (oldEdges[left] >= 0) {
if (oldEdges[right] >= 0) throw new Error("Failed binary search");
left = right;
}
break;
} else {
int mid = (left + right) / 2;
if (oldEdges[mid] < 0) {
right = mid;
} else {
left = mid + 1;
}
}
}
oldEdges[left] = to;
} else {
int[] newEdges = Arrays.copyOf(oldEdges, oldEdges.length * 2);
newEdges[oldEdges.length] = to;
for (int i = oldEdges.length + 1; i < newEdges.length; i++) {
newEdges[i] = -1;
}
backEdges[from] = newEdges;
}
}
private void addLiveVar(int instruction, int index) {
while (true) {
if (liveLocals[instruction].get(index)) {
break;
}
IInstruction instr = instructions[instruction];
if (instr instanceof StoreInstruction && ((StoreInstruction) instr).getVarIndex() == index) {
break;
}
liveLocals[instruction].set(index);
int[] back = backEdges[instruction];
if (back != null) {
for (int element : back) {
addLiveVar(element, index);
}
}
if (instruction > 0 && instructions[instruction - 1].isFallThrough()) {
instruction--;
} else {
break;
}
}
}
private void makeLiveLocals() {
liveLocals = new BitSet[instructions.length];
backEdges = new int[instructions.length][];
for (int i = 0; i < instructions.length; i++) {
IInstruction instr = instructions[i];
int[] targets = instr.getBranchTargets();
for (int target : targets) {
addBackEdge(target, i);
}
ExceptionHandler[] hs = handlers[i];
for (ExceptionHandler element : hs) {
addBackEdge(element.handler, i);
}
liveLocals[i] = new BitSet();
}
for (int i = 0; i < backEdges.length; i++) {
int[] back = backEdges[i];
if (back != null && back[back.length - 1] < 0) {
int j = back.length;
while (back[j - 1] < 0) {
j--;
}
int[] newBack = new int[j];
System.arraycopy(back, 0, newBack, 0, newBack.length);
backEdges[i] = newBack;
}
}
for (int i = 0; i < instructions.length; i++) {
IInstruction instr = instructions[i];
if (instr instanceof LoadInstruction) {
addLiveVar(i, ((LoadInstruction) instr).getVarIndex());
}
}
}
private String getAndCheckLocalType(int i, int l) {
String[] lts = localTypes[i];
String t = TYPE_unknown;
if (l < lts.length) {
t = lts[l];
}
if (t.equals(TYPE_null) || t.equals(TYPE_unknown)) {
throw new IllegalArgumentException(
"Cannot split oversized method because local " + l + " is undefined at " + i);
}
return t;
}
private void allocateLocals(int count) {
if (maxLocals < allocatedLocals + count * 2) {
maxLocals = allocatedLocals + count * 2;
}
}
private HelperPatch makeHelperPatch(
int start, int len, int retVar, int unreadStack, int untouchedStack) {
String retType = retVar >= 0 ? getAndCheckLocalType(start + len, retVar) : "V";
ArrayList<Instruction> callWrapper = new ArrayList<>();
int curStackLen = stackTypes[start].length;
StringBuilder sigBuf = new StringBuilder();
sigBuf.append('(');
// spill needed stack variables to allocated locals;
allocateLocals(curStackLen - unreadStack);
for (int i = curStackLen - 1; i >= unreadStack; i--) {
if (i < untouchedStack) {
callWrapper.add(DupInstruction.make(0));
}
callWrapper.add(
StoreInstruction.make(stackTypes[start][i], allocatedLocals + 2 * (i - unreadStack)));
}
// push needed locals
BitSet liveVars = liveLocals[start];
for (int i = 0; i < liveVars.length(); i++) {
if (liveVars.get(i)) {
String t = getAndCheckLocalType(start, i);
sigBuf.append(t);
callWrapper.add(LoadInstruction.make(t, i));
if (Util.getWordSize(t) > 1) {
i++;
}
} else {
// dummy
sigBuf.append('I');
callWrapper.add(ConstantInstruction.make(0));
}
}
// push stack variables
for (int i = unreadStack; i < curStackLen; i++) {
callWrapper.add(
LoadInstruction.make(stackTypes[start][i], allocatedLocals + 2 * (i - unreadStack)));
sigBuf.append(stackTypes[start][i]);
if (Util.getWordSize(stackTypes[start][i]) == 2) {
sigBuf.append('I');
callWrapper.add(ConstantInstruction.make(0));
}
}
sigBuf.append(')');
sigBuf.append(retType);
String sig = sigBuf.toString();
String name = createHelperMethod(true, sig);
callWrapper.add(
InvokeInstruction.make(sig, classType, name, IInvokeInstruction.Dispatch.STATIC));
int savedMaxStack = maxStack;
maxStack += curStackLen - unreadStack;
int prefixLength = 4 * (curStackLen - unreadStack);
byte[] initialStack = new byte[curStackLen - unreadStack];
for (int i = 0; i < initialStack.length; i++) {
initialStack[i] = Util.getWordSize(stackTypes[start][unreadStack + i]);
}
if (!outputInstructions(start, start + len, prefixLength, false, initialStack)) {
throw new Error("Helper function is overlarge");
}
byte[] newCode = new byte[code.length + (retVar >= 0 ? 5 : 1)];
for (int i = 0; i < curStackLen - unreadStack; i++) {
int local = allocatedLocals + i * 2;
newCode[i * 4] = (byte) OP_wide;
newCode[i * 4 + 1] =
(byte) LoadInstruction.make(stackTypes[start][i + unreadStack], 500).getOpcode();
newCode[i * 4 + 2] = (byte) (local >> 8);
newCode[i * 4 + 3] = (byte) local;
}
System.arraycopy(code, prefixLength, newCode, prefixLength, code.length - prefixLength);
int suffixOffset = code.length;
if (retVar >= 0) {
newCode[suffixOffset] = (byte) OP_wide;
newCode[suffixOffset + 1] = (byte) LoadInstruction.make(retType, 500).getOpcode();
newCode[suffixOffset + 2] = (byte) (retVar >> 8);
newCode[suffixOffset + 3] = (byte) retVar;
newCode[suffixOffset + 4] = (byte) ReturnInstruction.make(retType).getOpcode();
callWrapper.add(StoreInstruction.make(retType, retVar));
} else {
newCode[suffixOffset] = (byte) ReturnInstruction.make(TYPE_void).getOpcode();
}
if (callWrapper.size() > len) {
return null;
}
int[] rawHandlers = buildRawHandlers(start, start + len);
int[] bytecodeMap = buildBytecodeMap(start, start + len);
auxMethods.add(
new Output(name, sig, newCode, rawHandlers, bytecodeMap, maxLocals, maxStack, true, null));
maxStack = savedMaxStack;
Instruction[] patch = new Instruction[callWrapper.size()];
callWrapper.toArray(patch);
ExceptionHandler[] startHS = handlers[start];
ArrayList<ExceptionHandler> newHS = new ArrayList<>();
for (ExceptionHandler element : startHS) {
int t = element.handler;
if (t < start || t >= start + len) {
newHS.add(element);
}
}
ExceptionHandler[] patchHS = new ExceptionHandler[newHS.size()];
newHS.toArray(patchHS);
return new HelperPatch(start, len, patch, patchHS);
}
private HelperPatch findBlock(int start, int len) {
while (len > 100) {
// make sure there is at most one entry
int lastInvalid = start - 1;
for (int i = start + 1; i < start + len; i++) {
int[] back = backEdges[i];
boolean outsideBranch = false;
for (int j = 0; back != null && j < back.length; j++) {
if (back[j] < start || back[j] >= start + len) {
outsideBranch = true;
break;
}
}
if (outsideBranch) {
HelperPatch p = findBlock(lastInvalid + 1, i - lastInvalid - 1);
if (p != null) {
return p;
}
lastInvalid = i;
}
}
if (lastInvalid >= start) {
return null;
}
// make sure there is at most one exit (fall through at the end)
if (!instructions[start + len - 1].isFallThrough()) {
len--;
continue;
}
lastInvalid = start - 1;
for (int i = start; i < start + len; i++) {
int[] targets = instructions[i].getBranchTargets();
boolean outsideBranch = false;
if (instructions[i] instanceof ReturnInstruction) {
outsideBranch = true;
}
for (int target : targets) {
if (target < start || target >= start + len) {
outsideBranch = true;
break;
}
}
if (outsideBranch) {
HelperPatch p = findBlock(lastInvalid + 1, i - lastInvalid - 1);
if (p != null) {
return p;
}
lastInvalid = i;
}
}
if (lastInvalid >= start) {
return null;
}
lastInvalid = start - 1;
for (int i = start; i < start + len; i++) {
boolean out = false;
ExceptionHandler[] hs = handlers[i];
for (ExceptionHandler element : hs) {
int h = element.handler;
if (h < start || h >= start + len) {
out = true;
break;
}
}
int[] targets = instructions[i].getBranchTargets();
for (int t : targets) {
if (t < start || t >= start + len) {
out = true;
break;
}
}
if (out) {
HelperPatch p = findBlock(lastInvalid + 1, i - lastInvalid - 1);
if (p != null) {
return p;
}
lastInvalid = i;
}
}
if (lastInvalid >= start) {
return null;
}
if (stackTypes[start] == null) {
while (stackTypes[start] == null && len > 0) {
start++;
len--;
}
continue;
}
// See how many stack elements at entry are still there, unchanged, at
// exit
int untouchedStack = Integer.MAX_VALUE;
// See how many elements of that part of the stack are never even read
int unreadStack = Integer.MAX_VALUE;
for (int i = start; i < start + len; i++) {
if (stackTypes[i] == null) {
untouchedStack = 0;
unreadStack = 0;
break;
}
int lowWaterMark = stackTypes[i].length - instructions[i].getPoppedCount();
unreadStack = Math.min(unreadStack, lowWaterMark);
if (instructions[i] instanceof DupInstruction) {
// dup instructions don't actually pop off/change the element they
// duplicate
lowWaterMark += instructions[i].getPoppedCount();
}
untouchedStack = Math.min(untouchedStack, lowWaterMark);
}
if (untouchedStack > unreadStack + 1
|| (untouchedStack == unreadStack + 1 && untouchedStack < stackTypes[start].length)) {
// we can only handle 1 read-but-untouched element
start++;
len--;
continue;
}
// make sure we know the type of all the stack values that must be passed
// in
boolean unknownType = false;
for (int i = unreadStack; i < untouchedStack; i++) {
String t = stackTypes[start][i];
if (t == null || t.equals(TYPE_unknown) || t.equals(TYPE_null)) {
unknownType = true;
break;
}
}
if (unknownType) {
start++;
len--;
continue;
}
// make sure outgoing stack size is no more than the untouched stack size.
if (stackTypes[start + len] == null || stackTypes[start + len].length > untouchedStack) {
// This is a little conservative. We might be able to stop sooner with a
// valid
// extractable method, because changing 'len' might mean we have more
// untouched stack elements. But we'll do this in a dumb way to avoid
// being caught in some N^2 loop looking for extractable code.
while (len > 0
&& (stackTypes[start + len] == null
|| stackTypes[start + len].length > untouchedStack)) {
len--;
}
continue;
}
// make sure at most one local is defined and live on exit
BitSet liveAtEnd = liveLocals[start + len];
boolean multipleDefs = false;
int localDefed = -1;
int firstDef = -1;
int secondDef = -1;
for (int i = start; i < start + len; i++) {
IInstruction instr = instructions[i];
if (instr instanceof StoreInstruction) {
int l = ((StoreInstruction) instr).getVarIndex();
if (liveAtEnd.get(l) && l != localDefed) {
if (localDefed < 0) {
localDefed = l;
firstDef = i;
} else {
multipleDefs = true;
secondDef = i;
break;
}
}
}
}
if (multipleDefs) {
HelperPatch p = findBlock(start, secondDef - start);
if (p != null) {
return p;
}
len = (start + len) - (firstDef + 1);
start = firstDef + 1;
continue;
}
// make sure that the same external handlers are used all the way through
ExceptionHandler[] startHS = handlers[start];
int numOuts = 0;
for (ExceptionHandler element : startHS) {
int t = element.handler;
if (t < start || t >= start + len) {
numOuts++;
}
}
boolean mismatchedHandlers = false;
int firstMismatch = -1;
for (int i = start + 1; i < start + len; i++) {
ExceptionHandler[] hs = handlers[i];
int matchingOuts = 0;
for (ExceptionHandler element : hs) {
int t = element.handler;
if (t < start || t >= start + len) {
boolean match = false;
for (ExceptionHandler element2 : startHS) {
if (element2.equals(element)) {
match = true;
break;
}
}
if (match) {
matchingOuts++;
}
}
}
if (matchingOuts != numOuts) {
firstMismatch = i;
mismatchedHandlers = true;
break;
}
}
if (mismatchedHandlers) {
HelperPatch p = findBlock(start, firstMismatch - start);
if (p != null) {
return p;
}
start = firstMismatch;
continue;
}
// all conditions satisfied, extract the code
try {
HelperPatch p = makeHelperPatch(start, len, localDefed, unreadStack, untouchedStack);
if (p == null) {
// something went wrong. Probably the code to call the helper ended up
// being
// bigger than the original code we extracted!
return null;
} else {
return p;
}
} catch (IllegalArgumentException ex) {
return null;
}
}
return null;
}
private void makeHelpers() {
int offset = 0;
ArrayList<HelperPatch> patches = new ArrayList<>();
while (offset + 5000 < instructions.length) {
HelperPatch p = findBlock(offset, 5000);
if (p != null) {
patches.add(p);
offset = p.start + p.length;
} else {
offset += 500;
}
}
for (HelperPatch p : patches) {
System.arraycopy(p.code, 0, instructions, p.start, p.code.length);
for (int j = 0; j < p.length; j++) {
int index = j + p.start;
if (j < p.code.length) {
instructions[index] = p.code[j];
} else {
instructions[index] = PopInstruction.make(0); // nop
}
handlers[index] = p.handlers;
instructionsToBytecodes[index] = -1;
}
}
}
private void makeTypes() {
Verifier v =
new Verifier(
isConstructor,
isStatic,
classType,
signature,
instructions,
handlers,
instructionsToBytecodes,
null);
if (hierarchy != null) {
v.setClassHierarchy(hierarchy);
}
try {
v.computeTypes();
} catch (Verifier.FailureException ex) {
throw new IllegalArgumentException(
"Cannot split oversized method because verification failed: " + ex.getMessage());
}
localTypes = v.getLocalTypes();
stackTypes = v.getStackTypes();
}
/**
* Do the work of generating new bytecodes.
*
* <p>In pathological cases this could throw an Error, when the code you passed in is too large to
* fit into a single JVM method and Compiler can't find a way to break it up into helper methods.
* You probably won't encounter this unless you try to make it happen :-).
*/
public final void compile() {
collectInstructionInfo();
computeStackWords();
if (!outputInstructions(0, instructions.length, 0, false, null)) {
allocatedLocals = maxLocals;
makeLiveLocals();
makeTypes();
auxMethods = new ArrayList<>();
makeHelpers();
computeStackWords();
if (!outputInstructions(0, instructions.length, 0, false, null)) {
throw new Error("Input code too large; consider breaking up your code");
}
}
mainMethod =
new Output(
null,
null,
code,
buildRawHandlers(0, instructions.length),
buildBytecodeMap(0, instructions.length),
maxLocals,
maxStack,
isStatic,
instructionsToOffsets);
instructionsToOffsets = null;
branchTargets = null;
stackWords = null;
code = null;
}
/** Get the output bytecodes and other information for the method. */
public final Output getOutput() {
return mainMethod;
}
/**
* Get bytecodes and other information for any helper methods that are required to implement the
* main method. These helpers represent code that could not be fit into the main method because of
* JVM method size constraints.
*/
public final Output[] getAuxiliaryMethods() {
if (auxMethods == null) {
return null;
} else {
Output[] r = new Output[auxMethods.size()];
auxMethods.toArray(r);
return r;
}
}
/**
* This class represents a method generated by a Compiler. One input method to the Compiler can
* generate multiple Outputs (if the input method is too big to be represented by a single method
* in the JVM, say if it requires more than 64K bytecodes).
*/
public static final class Output {
private final byte[] code;
private final int[] rawHandlers;
private final int[] newBytecodesToOldBytecodes;
private final String name;
private final String signature;
private final boolean isStatic;
private final int maxLocals;
private final int maxStack;
private final int[] instructionsToOffsets;
Output(
String name,
String signature,
byte[] code,
int[] rawHandlers,
int[] newBytecodesToOldBytecodes,
int maxLocals,
int maxStack,
boolean isStatic,
int[] instructionsToOffsets) {
this.code = code;
this.name = name;
this.signature = signature;
this.rawHandlers = rawHandlers;
this.newBytecodesToOldBytecodes = newBytecodesToOldBytecodes;
this.isStatic = isStatic;
this.maxLocals = maxLocals;
this.maxStack = maxStack;
this.instructionsToOffsets = instructionsToOffsets;
}
/** @return the actual bytecodes */
public byte[] getCode() {
return code;
}
public int[] getInstructionOffsets() {
return instructionsToOffsets;
}
/**
* @return the name of the method; either "null", if this code takes the place of the original
* method, or some string representing the name of a helper method
*/
public String getMethodName() {
return name;
}
/** @return the method signature in JVM format */
public String getMethodSignature() {
return signature;
}
/**
* @return the access flags that should be used for this method, or 0 if this is the code for
* the original method
*/
public int getAccessFlags() {
return name != null ? (ACC_PRIVATE | (isStatic ? ACC_STATIC : 0)) : 0;
}
/** @return the raw exception handler table in JVM format */
public int[] getRawHandlers() {
return rawHandlers;
}
/** @return whether the method is static */
public boolean isStatic() {
return isStatic;
}
/**
* @return a map m such that the new bytecode instruction at offset i corresponds to the
* bytecode instruction at m[i] in the original method
*/
public int[] getNewBytecodesToOldBytecodes() {
return newBytecodesToOldBytecodes;
}
/** @return the maximum stack size in words as required by the JVM */
public int getMaxStack() {
return maxStack;
}
/** @return the maximum local variable size in words as required by the JVM */
public int getMaxLocals() {
return maxLocals;
}
}
}
| 64,373
| 31.267669
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ConditionalBranchInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
/**
* This class represents conditional branches. A conditional branch tests two integers or two object
* references for some relationship, and takes the branch if the relationship holds.
*/
public final class ConditionalBranchInstruction extends Instruction
implements IConditionalBranchInstruction {
private final int label;
private ConditionalBranchInstruction(short opcode, int label) {
super(opcode);
this.label = label;
}
public static ConditionalBranchInstruction make(String type, Operator operator, int label)
throws IllegalArgumentException {
int t = Util.getTypeIndex(type);
short opcode;
switch (t) {
case TYPE_int_index:
opcode = (short) (OP_if_icmpeq + (operator.ordinal() - Operator.EQ.ordinal()));
break;
case TYPE_Object_index:
if (operator != Operator.EQ && operator != Operator.NE) {
throw new IllegalArgumentException(
"Cannot test for condition " + operator + " on a reference");
}
opcode = (short) (OP_if_acmpeq + (operator.ordinal() - Operator.EQ.ordinal()));
break;
default:
throw new IllegalArgumentException(
"Cannot conditionally branch on a value of type " + type);
}
return make(opcode, label);
}
// Relax from private to public by Xiangyu, to create ifeq
public static ConditionalBranchInstruction make(short opcode, int label)
throws IllegalArgumentException {
if (opcode < OP_ifeq || opcode > OP_if_acmpne) {
throw new IllegalArgumentException("Illegal opcode: " + opcode);
}
return new ConditionalBranchInstruction(opcode, label);
}
@Override
public boolean equals(Object o) {
if (o instanceof ConditionalBranchInstruction) {
ConditionalBranchInstruction i = (ConditionalBranchInstruction) o;
return i.opcode == opcode && i.label == label;
} else {
return false;
}
}
@Override
public String toString() {
return "ConditionalBranch(" + getType() + ',' + getOperator() + ',' + label + ')';
}
@Override
public int[] getBranchTargets() {
int[] r = {label};
return r;
}
@Override
public int getTarget() {
return label;
}
@Override
public IInstruction redirectTargets(int[] targetMap) throws IllegalArgumentException {
if (targetMap == null) {
throw new IllegalArgumentException("targetMap is null");
}
try {
return make(opcode, targetMap[label]);
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("bad target map", e);
}
}
@Override
public Operator getOperator() {
if (opcode < OP_if_acmpeq) {
return Operator.values()[opcode - OP_if_icmpeq];
} else {
return Operator.values()[opcode - OP_if_acmpeq];
}
}
@Override
public String getType() {
return opcode < OP_if_acmpeq ? TYPE_int : TYPE_Object;
}
@Override
public int hashCode() {
return 30190 * opcode + 384101 * label;
}
@Override
public int getPoppedCount() {
// Xiangyu, to support if_eq (if_ne)...
if (opcode >= Constants.OP_ifeq && opcode <= Constants.OP_ifle) return 1;
return 2;
}
@Override
public void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitConditionalBranch(this);
}
@Override
public boolean isPEI() {
return false;
}
}
| 3,788
| 27.276119
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ConstantInstruction.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
import com.ibm.wala.shrike.shrikeCT.ConstantPoolParser;
import java.util.Arrays;
/** A ConstantInstruction pushes some constant value onto the stack. */
public abstract class ConstantInstruction extends Instruction {
public static class InvokeDynamicToken {
private final BootstrapMethod bootstrapMethod;
private final String name;
private final String type;
public InvokeDynamicToken(BootstrapMethod bootstrapMethod, String name, String type) {
this.bootstrapMethod = bootstrapMethod;
this.name = name;
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bootstrapMethod == null) ? 0 : bootstrapMethod.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
InvokeDynamicToken other = (InvokeDynamicToken) obj;
if (bootstrapMethod == null) {
if (other.bootstrapMethod != null) return false;
} else if (!bootstrapMethod.equals(other.bootstrapMethod)) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
if (type == null) {
if (other.type != null) return false;
} else if (!type.equals(other.type)) return false;
return true;
}
}
public static class ClassToken {
private final String typeName;
ClassToken(String typeName) {
this.typeName = typeName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((typeName == null) ? 0 : typeName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ClassToken other = (ClassToken) obj;
if (typeName == null) {
if (other.typeName != null) return false;
} else if (!typeName.equals(other.typeName)) return false;
return true;
}
public String getTypeName() {
return typeName;
}
}
public ConstantInstruction(short opcode) {
super(opcode);
}
ConstantPoolReader getLazyConstantPool() {
return null;
}
int getCPIndex() {
return 0;
}
static final class ConstNull extends ConstantInstruction {
private ConstNull() {
super(OP_aconst_null);
}
private static final ConstNull preallocated = new ConstNull();
static ConstNull makeInternal() {
return preallocated;
}
@Override
public Object getValue() {
return null;
}
@Override
public String getType() {
return TYPE_null;
}
}
static class ConstInt extends ConstantInstruction {
protected int value;
private static final ConstInt[] preallocated = preallocate();
protected ConstInt(short opcode, int value) {
super(opcode);
this.value = value;
}
private static ConstInt[] preallocate() {
ConstInt[] r = new ConstInt[256];
Arrays.setAll(r, i -> new ConstInt(OP_bipush, i - 128));
for (int i = -1; i <= 5; i++) {
r[i + 128] = new ConstInt((short) (i - -1 + OP_iconst_m1), i);
}
return r;
}
static ConstInt makeInternal(int i) {
if (((byte) i) == i) {
return preallocated[i + 128];
} else if (((short) i) == i) {
return new ConstInt(OP_sipush, i);
} else {
return new ConstInt(OP_ldc_w, i);
}
}
@Override
public final Object getValue() {
return getIntValue();
}
@Override
public final String getType() {
return TYPE_int;
}
public int getIntValue() {
return value;
}
}
static final class LazyInt extends ConstInt {
private final ConstantPoolReader cp;
private final int index;
private boolean isSet;
private LazyInt(short opcode, ConstantPoolReader cp, int index) {
super(opcode, 0);
this.cp = cp;
this.index = index;
this.isSet = false;
}
@Override
public int getIntValue() {
if (!isSet) {
value = cp.getConstantPoolInteger(index);
isSet = true;
}
return value;
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
static class ConstLong extends ConstantInstruction {
protected long value;
private static final ConstLong[] preallocated = preallocate();
protected ConstLong(short opcode, long value) {
super(opcode);
this.value = value;
}
private static ConstLong[] preallocate() {
ConstLong[] r = {new ConstLong(OP_lconst_0, 0), new ConstLong(OP_lconst_1, 1)};
return r;
}
static ConstLong makeInternal(long v) {
if (v == 0 || v == 1) {
return preallocated[(int) v];
} else {
return new ConstLong(OP_ldc2_w, v);
}
}
@Override
public final Object getValue() {
return getLongValue();
}
@Override
public final String getType() {
return TYPE_long;
}
public long getLongValue() {
return value;
}
}
static final class LazyLong extends ConstLong {
private final ConstantPoolReader cp;
private final int index;
private boolean isSet;
private LazyLong(short opcode, ConstantPoolReader cp, int index) {
super(opcode, 0);
this.cp = cp;
this.index = index;
this.isSet = false;
}
@Override
public long getLongValue() {
if (!isSet) {
value = cp.getConstantPoolLong(index);
isSet = true;
}
return value;
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
static class ConstFloat extends ConstantInstruction {
protected float value;
private static final ConstFloat[] preallocated = preallocate();
protected ConstFloat(short opcode, float value) {
super(opcode);
this.value = value;
}
private static ConstFloat[] preallocate() {
ConstFloat[] r = {
new ConstFloat(OP_fconst_0, 0),
new ConstFloat(OP_fconst_1, 1),
new ConstFloat(OP_fconst_2, 2)
};
return r;
}
static ConstFloat makeInternal(float v) {
if (v == 0.0 || v == 1.0 || v == 2.0) {
return preallocated[(int) v];
} else {
return new ConstFloat(OP_ldc_w, v);
}
}
@Override
public final Object getValue() {
return getFloatValue();
}
@Override
public final String getType() {
return TYPE_float;
}
public float getFloatValue() {
return value;
}
}
static final class LazyFloat extends ConstFloat {
private final ConstantPoolReader cp;
private final int index;
private boolean isSet;
private LazyFloat(short opcode, ConstantPoolReader cp, int index) {
super(opcode, 0.0f);
this.cp = cp;
this.index = index;
this.isSet = false;
}
@Override
public float getFloatValue() {
if (!isSet) {
value = cp.getConstantPoolFloat(index);
isSet = true;
}
return value;
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
static class ConstDouble extends ConstantInstruction {
protected double value;
private static final ConstDouble[] preallocated = preallocate();
protected ConstDouble(short opcode, double value) {
super(opcode);
this.value = value;
}
private static ConstDouble[] preallocate() {
ConstDouble[] r = {new ConstDouble(OP_dconst_0, 0), new ConstDouble(OP_dconst_1, 1)};
return r;
}
static ConstDouble makeInternal(double v) {
if (v == 0.0 || v == 1.0) {
return preallocated[(int) v];
} else {
return new ConstDouble(OP_ldc2_w, v);
}
}
@Override
public final Object getValue() {
return getDoubleValue();
}
@Override
public final String getType() {
return TYPE_double;
}
public double getDoubleValue() {
return value;
}
}
static final class LazyDouble extends ConstDouble {
private final ConstantPoolReader cp;
private final int index;
private boolean isSet;
private LazyDouble(short opcode, ConstantPoolReader cp, int index) {
super(opcode, 0.0);
this.cp = cp;
this.index = index;
this.isSet = false;
}
@Override
public double getDoubleValue() {
if (!isSet) {
value = cp.getConstantPoolDouble(index);
isSet = true;
}
return value;
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
static class ConstString extends ConstantInstruction {
protected String value;
protected ConstString(short opcode, String value) {
super(opcode);
this.value = value;
}
static ConstString makeInternal(String v) {
return new ConstString(OP_ldc_w, v);
}
@Override
public Object getValue() {
return value;
}
@Override
public final String getType() {
return TYPE_String;
}
}
static final class LazyString extends ConstString {
private final ConstantPoolReader cp;
private final int index;
private LazyString(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null);
this.cp = cp;
this.index = index;
}
@Override
public Object getValue() {
if (value == null) {
value = cp.getConstantPoolString(index);
}
return value;
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
static class ConstClass extends ConstantInstruction {
protected String typeName;
protected ConstClass(short opcode, String typeName) {
super(opcode);
this.typeName = typeName;
}
static ConstClass makeInternal(String v) {
return new ConstClass(OP_ldc_w, v);
}
@Override
public Object getValue() {
return new ClassToken(typeName);
}
@Override
public final String getType() {
return TYPE_Class;
}
@Override
public boolean isPEI() {
// load of a class constant may trigger a ClassNotFoundException
return true;
}
}
static final class LazyClass extends ConstClass {
private final ConstantPoolReader cp;
private final int index;
private LazyClass(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null);
this.cp = cp;
this.index = index;
}
@Override
public Object getValue() {
if (typeName == null) {
typeName = cp.getConstantPoolClassType(index);
}
return new ClassToken(typeName);
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
static class ConstMethodType extends ConstantInstruction {
protected String descriptor;
ConstMethodType(short opcode, String descriptor) {
super(opcode);
this.descriptor = descriptor;
}
@Override
public Object getValue() {
return descriptor;
}
@Override
public String getType() {
return TYPE_MethodType;
}
}
static class LazyMethodType extends ConstMethodType {
private final ConstantPoolReader cp;
private final int index;
LazyMethodType(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null);
this.cp = cp;
this.index = index;
}
@Override
public Object getValue() {
if (descriptor == null) {
descriptor = cp.getConstantPoolMethodType(index);
}
return descriptor;
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
static class ConstMethodHandle extends ConstantInstruction {
protected Object value;
public ConstMethodHandle(short opcode, Object value) {
super(opcode);
this.value = value;
}
@Override
public Object getValue() {
return value;
}
@Override
public String getType() {
return TYPE_MethodHandle;
}
}
static class LazyMethodHandle extends ConstMethodHandle {
private final ConstantPoolReader cp;
private final int index;
LazyMethodHandle(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null);
this.cp = cp;
this.index = index;
}
@Override
public Object getValue() {
if (value == null) {
String className = cp.getConstantPoolHandleClassType(getCPIndex());
String eltName = cp.getConstantPoolHandleName(getCPIndex());
String eltDesc = cp.getConstantPoolHandleType(getCPIndex());
byte kind = cp.getConstantPoolHandleKind(getCPIndex());
value = new ConstantPoolParser.ReferenceToken(kind, className, eltName, eltDesc);
}
return value;
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
static class ConstInvokeDynamic extends ConstantInstruction {
protected Object value;
public ConstInvokeDynamic(short opcode, Object value) {
super(opcode);
this.value = value;
}
@Override
public Object getValue() {
return value;
}
@Override
public String getType() {
return null;
}
}
static class LazyInvokeDynamic extends ConstMethodHandle {
private final ConstantPoolReader cp;
private final int index;
LazyInvokeDynamic(short opcode, ConstantPoolReader cp, int index) {
super(opcode, null);
this.cp = cp;
this.index = index;
}
@Override
public Object getValue() {
if (value == null) {
BootstrapMethod bootstrap = cp.getConstantPoolDynamicBootstrap(index);
String name = cp.getConstantPoolDynamicName(index);
String type = cp.getConstantPoolDynamicType(index);
value = new InvokeDynamicToken(bootstrap, name, type);
}
return value;
}
@Override
public ConstantPoolReader getLazyConstantPool() {
return cp;
}
@Override
public int getCPIndex() {
return index;
}
}
/** @return the constant value pushed: an Integer, a Long, a Float, a Double, a String, or null */
public abstract Object getValue();
/** @return the type of the value pushed */
public abstract String getType();
public static ConstantInstruction make(String type, Object constant)
throws IllegalArgumentException {
if (type == null && constant != null) {
throw new IllegalArgumentException("(type == null) and (constant != null)");
}
if (constant == null) {
return ConstNull.makeInternal();
} else if (type.equals(TYPE_String)) {
return makeString((String) constant);
} else if (type.equals(TYPE_Class)) {
return makeClass((String) constant);
} else {
try {
switch (Util.getTypeIndex(type)) {
case TYPE_int_index:
return make(((Number) constant).intValue());
case TYPE_long_index:
return make(((Number) constant).longValue());
case TYPE_float_index:
return make(((Number) constant).floatValue());
case TYPE_double_index:
return make(((Number) constant).doubleValue());
default:
throw new IllegalArgumentException("Invalid type for constant: " + type);
}
} catch (ClassCastException e) {
throw new IllegalArgumentException(e);
}
}
}
public static ConstantInstruction make(int i) {
return ConstInt.makeInternal(i);
}
public static ConstantInstruction make(long l) {
return ConstLong.makeInternal(l);
}
public static ConstantInstruction make(float f) {
return ConstFloat.makeInternal(f);
}
public static ConstantInstruction make(double d) {
return ConstDouble.makeInternal(d);
}
public static ConstantInstruction makeString(String s) {
return s == null
? (ConstantInstruction) ConstNull.makeInternal()
: (ConstantInstruction) ConstString.makeInternal(s);
}
public static ConstantInstruction makeClass(String s) {
return ConstClass.makeInternal(s);
}
public static ConstantInstruction make(ConstantPoolReader cp, int index) {
switch (cp.getConstantPoolItemType(index)) {
case CONSTANT_Integer:
return new LazyInt(OP_ldc_w, cp, index);
case CONSTANT_Long:
return new LazyLong(OP_ldc2_w, cp, index);
case CONSTANT_Float:
return new LazyFloat(OP_ldc_w, cp, index);
case CONSTANT_Double:
return new LazyDouble(OP_ldc2_w, cp, index);
case CONSTANT_String:
return new LazyString(OP_ldc_w, cp, index);
case CONSTANT_Class:
return new LazyClass(OP_ldc_w, cp, index);
case CONSTANT_MethodHandle:
return new LazyMethodHandle(OP_ldc_w, cp, index);
case CONSTANT_MethodType:
return new LazyMethodType(OP_ldc_w, cp, index);
case CONSTANT_InvokeDynamic:
return new LazyInvokeDynamic(OP_ldc_w, cp, index);
default:
return null;
}
}
@Override
public final boolean equals(Object o) {
if (o instanceof ConstantInstruction) {
ConstantInstruction i = (ConstantInstruction) o;
if (!i.getType().equals(getType())) {
return false;
}
if (i.getValue() == null) {
if (getValue() == null) {
return true;
} else {
return false;
}
} else {
if (getValue() == null) {
return false;
} else {
return i.getValue().equals(getValue());
}
}
} else {
return false;
}
}
@Override
public final String getPushedType(String[] types) {
return getType();
}
@Override
public final byte getPushedWordSize() {
return Util.getWordSize(getType());
}
@Override
public final int hashCode() {
int v = getValue() == null ? 0 : getValue().hashCode();
return getType().hashCode() + 14411 * v;
}
@Override
public final void visit(IInstruction.Visitor v) throws NullPointerException {
v.visitConstant(this);
}
private static String quote(Object o) {
if (o instanceof String) {
String s = (String) o;
StringBuilder buf = new StringBuilder("\"");
int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
buf.append('\\');
buf.append(ch);
break;
case '\n':
buf.append("\\\n");
break;
case '\t':
buf.append("\\\t");
break;
default:
buf.append(ch);
}
}
buf.append('\"');
return buf.toString();
} else if (o == null) {
return "null";
} else {
return o.toString();
}
}
@Override
public final String toString() {
return "Constant(" + getType() + ',' + quote(getValue()) + ')';
}
@Override
public boolean isPEI() {
return false;
}
}
| 20,506
| 22.680139
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/shrikeBT/ConstantPoolReader.java
|
/*
* Copyright (c) 2002,2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.shrikeBT;
import com.ibm.wala.shrike.shrikeCT.BootstrapMethodsReader.BootstrapMethod;
/**
* This class provides read-only access to a constant pool. It gets subclassed for each class
* reader/editor toolkit you want to work with.
*/
public abstract class ConstantPoolReader {
/**
* Retrieve the JVM constant pool item type (a Constants.CONSTANT_xxx value). This method should
* be overriden by a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract int getConstantPoolItemType(int index);
/**
* Retrieve the value of a CONSTANT_Integer constant pool item. This method should be overriden by
* a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract int getConstantPoolInteger(int index);
/**
* Retrieve the value of a CONSTANT_Float constant pool item. This method should be overriden by a
* toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract float getConstantPoolFloat(int index);
/**
* Retrieve the value of a CONSTANT_Long constant pool item. This method should be overriden by a
* toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract long getConstantPoolLong(int index);
/**
* Retrieve the value of a CONSTANT_Double constant pool item. This method should be overriden by
* a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract double getConstantPoolDouble(int index);
/**
* Retrieve the value of a CONSTANT_String constant pool item. This method should be overriden by
* a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolString(int index);
/**
* Retrieve the value of a CONSTANT_MethodType constant pool item. This method should be overriden
* by a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolMethodType(int index);
/**
* Retrieve the value of a CONSTANT_Class constant pool item in JVM internal class format (e.g.,
* java/lang/Object). This method should be overriden by a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolClassType(int index);
/**
* Retrieve the class part of a CONSTANT_FieldRef, CONSTANT_MethodRef, or
* CONSTANT_InterfaceMethodRef constant pool item, in JVM internal class format (e.g.,
* java/lang/Object). This method should be overriden by a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolMemberClassType(int index);
/**
* Retrieve the name part of a CONSTANT_FieldRef, CONSTANT_MethodRef, or
* CONSTANT_InterfaceMethodRef constant pool item, This method should be overriden by a
* toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolMemberName(int index);
/**
* Retrieve the type part of a CONSTANT_FieldRef, CONSTANT_MethodRef, or
* CONSTANT_InterfaceMethodRef constant pool item, in JVM internal type format (e.g.,
* Ljava/lang/Object;). This method should be overriden by a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolMemberType(int index);
/**
* Retrieve the class part of the CONSTANT_FieldRef, CONSTANT_MethodRef, or
* CONSTANT_InterfaceMethodRef constant pool item pointed to by a CONSTANT_MethodHandle entry.
* This method should be overriden by a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolHandleClassType(int index);
/**
* Retrieve the name part of the CONSTANT_FieldRef, CONSTANT_MethodRef, or
* CONSTANT_InterfaceMethodRef constant pool item pointed to by a CONSTANT_MethodHandle entry.
* This method should be overriden by a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolHandleName(int index);
/**
* Retrieve the type part of the CONSTANT_FieldRef, CONSTANT_MethodRef, or
* CONSTANT_InterfaceMethodRef constant pool item pointed to by a CONSTANT_MethodHandle entry.
* This method should be overriden by a toolkit-specific subclass.
*
* @param index the constant pool item to examine
*/
public abstract String getConstantPoolHandleType(int index);
public abstract byte getConstantPoolHandleKind(int index);
public abstract BootstrapMethod getConstantPoolDynamicBootstrap(int index);
public abstract String getConstantPoolDynamicName(int index);
public abstract String getConstantPoolDynamicType(int index);
}
| 5,367
| 35.767123
| 100
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.