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
soot
soot-master/src/test/java/soot/asm/backend/targets/Arrays.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class Arrays { void doBool(){ boolean[] bool = new boolean[3]; boolean boolv = bool[1]; bool[0] = boolv; } void doByte(){ byte[] b = new byte[4]; byte bv = b[1]; b[0] = bv; } void doChar(){ char[] c = new char[5]; char cv = c[1]; c[0] = cv; } void doDouble(){ double[] d = new double[6]; double dv = d[1]; d[0] = dv; } void doFloat(){ float[] f = new float[7]; float fv = f[1]; f[0] = fv; } void doInt(){ int[] i = new int[8]; int iv = i[1]; i[0] = iv; } void doLong(){ long[] l = new long[9]; long lv = l[1]; l[0] = lv; } void doShort(){ short[] s = new short[10]; short sv = s[1]; s[0] = sv; } void doObject(){ Object[] o = new Object[11]; Object ov = o[1]; o[0] = ov; o[3] = null; } void doString(){ String[] str = new String[12]; String strv = str[1]; str[0] = strv; } void doIntInt(){ int[][] ii = new int[3][3]; int[] iiv = ii[1]; ii[0] = iiv; int iiiv = ii[2][1]; ii[1][2] = iiiv; } void doObjectObject(){ Object[][] oo = new Object[4][4]; Object[] oov = oo[1]; oo[0] = oov; Object ooov = oo[2][1]; oo[1][2] = ooov; } }
2,057
16.589744
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/Bean.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class Bean { private int f; public int getF() { return this.f; } public void setF(int f) { this.f = f; } public void checkAndSetF(int f) { if (f >= 0) { this.f = f; } else { throw new IllegalArgumentException(); } } }
1,104
24.113636
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/Comparable.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public interface Comparable extends Measurable { int LESS = -1; int EQUAL = 0; int GREATER = 1; int compareTo(Object o); }
980
30.645161
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/CompareArithmeticInstructions2.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * @author Tobias Hamann */ public class CompareArithmeticInstructions2 { int i = 2; float f = 221349.01213123213213213123213213124764573f; double d = 2123996.12312312312312312323421612334; long l = 2; byte b = 2; char c = 4; short s = 3; void comparei(int i1) { if (i >= i1) { i = 2; } if (i < i1) { i = 1; } } void comparef(float f1) { if (f >= f1) { f = 2.0f; } if (f < f1) { f = 1.0f; } } void compared(double d1) { if (d >= d1) { d = 2.0; } if (d < d1) { d = 1.0; } } void comparel(long l1) { if (l >= l1) { l = 2; } if (l < l1) { l = 1; } } void compareb(byte b1) { if (b >= b1) { b = 2; } if (b < b1) { b = 1; } } void comparec(char c1) { if (c >= c1) { c = 2; } if (c < c1) { c = 3; } } void compares(short s1) { if (s >= s1) { s = 1; } if (s < s1) { s = 3; } } }
2,115
19.745098
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/CompareArithmeticInstuctions.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * @author Tobias Hamann */ public class CompareArithmeticInstuctions { int i = 2; float f = 221349.01213123213213213123213213124764573f; double d = 2123996.12312312312312312323421612334; long l = 2; byte b = 2; char c = 4; short s = 3; void comparei(int i1) { if (i <= i1) { i = 2; } if (i > i1) { i = 1; } } void comparef(float f1) { if (f <= f1) { f = 2.0f; } if (f > f1) { f = 1.0f; } } void compared(double d1) { if (d <= d1) { d = 2.0; } if (d > d1) { d = 1.0; } } void comparel(long l1) { if (l <= l1) { l = 2; } if (l > l1) { l = 1; } } void compareb(byte b1) { if (b <= b1) { b = 2; } if (b > b1) { b = 1; } } void comparec(char c1) { if (c <= c1) { c = 2; } if (c > c1) { c = 3; } } void compares(short s1) { if (s <= s1) { s = 1; } if (s > s1) { s = 3; } } }
2,113
19.72549
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/CompareInstructions.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * @author Tobias Hamann */ public class CompareInstructions { int i = 2; float f = 221349.01213123213213213123213213124764573f; double d = 2123996.12312312312312312323421612334; long l = 2; byte b = 2; boolean bool = true; char c = 4; short s = 3; Object o; void comparei(int i1) { if (i == i1) { i = 2; } if (i != i1) { i = 1; } } void comparef(float f1) { if (f == f1) { f = 0.0f; } if (f != f1) { f = 1.0f; } } void compared(double d1) { if (d == d1) { d = 2.0; } if (d != d1) { d = 1.0; } } void comparel(long l1) { if (l == l1) { l = 2; } if (l != l1) { l = 1; } } void compareb(byte b1) { if (b == b1) { b = 2; } if (b != b1) { b = 1; } } void compareBool(boolean bool1) { if (bool == bool1) { bool = true; } if (bool != bool1) { bool = false; } } void comparec(char c1) { if (c == c1) { c = 2; } if (c != c1) { c = 3; } } void compares(short s1) { if (s == s1) { s = 1; } if (s != s1) { s = 3; } } void comparenull(Object o1) { if (o == null){ o = new Object(); } if (o1 != null){ o = null; } } }
2,460
19.172131
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/ConstantPool.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class ConstantPool { public static final String s1 = "H:mm:ss.SSS"; public static final String s2 = null; public static final Object o1 = "O"; public static final Object o2 = null; public static final Object o3 = 123; public static final Object o4 = 1234l; public static final Object o5 = 123.3d; public static final int i1 = 123; public static final int i2 = new Integer(123); public static final long l1 = 12233l; public static final long l2 = 123; public static final long l3 = new Long(12341l); public static final double d1 = 123.142; public static final double d2 = 1234.123f; public static final double d3 = new Double(1234.123); }
1,521
31.382979
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/ControlStructures.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; public class ControlStructures { List<Integer> result; protected List<Integer> get(int i){ result = new ArrayList<Integer>(); switch(i){ case 1: result.add(1); break; case 2: result.add(2); case 3: result.add(3); break; default: result.add(null); } switch(i){ case 1: result.add(1); case 10: result.add(10); case 100: result.add(100); case 1000: result.add(1000); default: result.add(null); } return result; } }
1,397
20.507692
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/Dups.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class Dups { public Object dup(){ Object o = new Object(); return o; } public long dubl(){ long l = 1234; l = l + l; return l; } }
1,010
24.923077
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/ExceptionMethods.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public interface ExceptionMethods { public void foo() throws NullPointerException; }
939
32.571429
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/ExtendedArithmeticLib.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class ExtendedArithmeticLib { private int i1; private float f1; private long l1; private double d1; private short s1; private byte b1; private int i2; private float f2; private long l2; private double d2; private int i3; private float f3; private long l3; private double d3; public void doMod() { i1 = i2 % i3; f1 = f2 % f3; l1 = l2 % l3; d1 = d2 % d3; } public void doSub() { i1 = i2 - i3; f1 = f2 - f3; l1 = l2 - l3; d1 = d2 - d3; } public int doINeg(int i) { return -i; } public int doCNeg(char c) { return -c; } public int doSNeg(short s) { return -s; } public int doBNeg(byte b) { return -b; } public long doLNeg(long l) { return l; } public double doDNeg(double d) { return -d; } public float doFNeg(float f) { return -f; } public int doInc() { int j = 0; for (int i = 0; i < 100; i++) { j+=4; } return j; } }
1,764
17.776596
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/InnerClass.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class InnerClass { private class Inner{ static final int a= 3; } public int getA(){ return Inner.a; } public void doInner(){ new Measurable() { }; } }
1,035
23.666667
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/InnerStaticClass.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class InnerStaticClass { public static class Inner { static final int a = 3; } public int getA() { return Inner.a; } public void doInner() { new Measurable() { }; } }
1,060
24.261905
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/InstanceOfCasts.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class InstanceOfCasts { public boolean isMeasurable(Object o) { return o instanceof Measurable; } public Measurable[] convertMeasurableArray(Object[] o) { if (o instanceof Measurable[]) { return (Measurable[]) o; } return null; } }
1,109
28.210526
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/LineNumbers.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class LineNumbers { public static void main(String[] args) { return; } }
938
29.290323
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/LogicalOperations.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class LogicalOperations { private int i1; private boolean b1; private long l1; private int i2; private boolean b2; private long l2; public void doAnd(){ i1 = i2 & i1; l1 = l2 & l1; b1 = b2 & b1; } public void doOr(){ i1 = i2 | i1; l1 = l2 | l1; b1 = b2 | b1; } public void doXOr(){ i1 = i2 ^ i1; l1 = l2 ^ l1; b1 = b2 ^ b1; } public void doInv(){ i1 = ~i2; l1 = ~i2; } public void doShl(){ i1 = i1 << i2; l1 = l1 << l2; } public void doShr(){ i1 = i1 >> i2; l1 = l1 >> l2; } public void doUShr(){ i1 = i1 >>> i2; l1 = l1 >>> l2; } }
1,464
19.068493
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/Measurable.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public interface Measurable { }
886
30.678571
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/Modifiers.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public abstract strictfp class Modifiers { private volatile int i; private final int j = 213; private transient int k; public final void a(){ } public synchronized void b(){ } public static void c(){ } void d(){ } protected void e(){ } abstract void f(); private native void g(); }
1,169
21.941176
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/Monitor.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class Monitor { Object o; public void doSth(){ synchronized (o) { } System.out.println(); } }
976
24.710526
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/MyAnnotatedAnnotation.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public @interface MyAnnotatedAnnotation { MyTestAnnotation value(); }
924
32.035714
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/MyEnum.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public enum MyEnum { JA, NEIN; }
891
28.733333
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/MyTestAnnotation.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.annotation.Generated; @Retention(RetentionPolicy.RUNTIME) @Generated(value="forTesting") public @interface MyTestAnnotation { int iVal(); float fVal(); long lVal(); double dVal(); boolean zVal(); byte bVal(); short sVal(); String strVal(); Class<AnnotatedClass> rVal(); int[] iAVal(); String [] sAVal(); }
1,269
27.222222
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/Returns.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class Returns { public Object getNull(){ return null; } public Object[] getObjectArray(){ return new Object[4]; } public int[] getIntArray(){ return new int[4]; } }
1,044
25.125
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/Stores.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class Stores { public int doSth(){ int i; double d; float f; short s; boolean b; byte bb; long l; char c; Object o; int[] a; i = 2343249; d = 3.14324; f = 3.143f; s = 4636; b = System.currentTimeMillis() > 0; bb = (byte) i; l = 314435665; c = 123; o = new Object(); a = new int[3]; a[1] = 24355764; System.out.println(i + d + f + s + "" +b + bb + l + c + " " + o); return i; } }
1,301
21.448276
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/TryCatch.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class TryCatch { int doSth(Object o){ int i = 0; try{ o.notify(); i = 1; } catch (NullPointerException e){ i = -1; } finally { return i; } } }
1,030
24.775
71
java
soot
soot-master/src/test/java/soot/asm/backend/targets/nullTypes.java
package soot.asm.backend.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * @author Tobias Hamann */ public class nullTypes { Integer doStuff(Integer i) { if (i == null) { return null; } return 1; } }
1,032
26.184211
71
java
soot
soot-master/src/test/java/soot/baf/ASMBackendMockingTest.java
package soot.baf; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import static org.objectweb.asm.Opcodes.*; import static org.powermock.api.mockito.PowerMockito.doCallRealMethod; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import soot.IntType; import soot.LongType; import soot.Type; import soot.Unit; import soot.VoidType; import soot.baf.internal.BDup1_x1Inst; import soot.baf.internal.BDup1_x2Inst; import soot.baf.internal.BDup2Inst; import soot.baf.internal.BDup2_x1Inst; import soot.baf.internal.BDup2_x2Inst; import soot.baf.internal.BJSRInst; import soot.baf.internal.BNopInst; import soot.baf.internal.BPopInst; import soot.baf.internal.BSwapInst; import soot.util.backend.ASMBackendUtils; @PrepareForTest(ASMBackendUtils.class) @RunWith(PowerMockRunner.class) @PowerMockIgnore({"javax.management.", "com.sun.org.apache.xerces.", "javax.xml.", "org.xml.", "org.w3c.dom.", "com.sun.org.apache.xalan.", "javax.activation.*"}) public class ASMBackendMockingTest { private MethodVisitor mv; private BafASMBackend sut; @Before public void setUp() throws Exception { mv = mock(MethodVisitor.class); sut = mock(BafASMBackend.class); doCallRealMethod().when(sut).generateInstruction(any(MethodVisitor.class), any(Inst.class)); } @Test public void testNOPInst(){ Inst inst = new BNopInst(); sut.generateInstruction(mv, inst); verify(mv).visitInsn(NOP); } @Test public void testJSRInst(){ Unit target = mock(Inst.class); Inst inst = new BJSRInst(target); Label label = mock(Label.class); when(sut.getBranchTargetLabel(target)).thenReturn(label); sut.generateInstruction(mv, inst); verify(mv).visitJumpInsn(JSR, label); } @Test public void testSwapInst(){ Type fromType = mock(Type.class); Type toType = mock(Type.class); Inst inst = new BSwapInst(fromType, toType); sut.generateInstruction(mv, inst); verify(mv).visitInsn(SWAP); } @Test public void testPop2Inst(){ Type type = mock(LongType.class); PopInst inst = new BPopInst(type); sut.generateInstruction(mv, inst); verify(mv).visitInsn(POP2); } @Test public void testDup2Inst1(){ Type aOp1Type = mock(IntType.class); Type aOp2Type = mock(IntType.class); Inst inst = new BDup2Inst(aOp1Type, aOp2Type); sut.generateInstruction(mv, inst); verify(mv).visitInsn(DUP2); } @Test public void testDup2Inst2(){ Type aOp1Type = mock(LongType.class); Type aOp2Type = mock(LongType.class); Inst inst = new BDup2Inst(aOp1Type, aOp2Type); sut.generateInstruction(mv, inst); verify(mv, times(2)).visitInsn(DUP2); } @Test public void testDup2Inst3(){ Type aOp1Type = mock(LongType.class); Type aOp2Type = mock(IntType.class); Inst inst = new BDup2Inst(aOp1Type, aOp2Type); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP2); inOrder.verify(mv).visitInsn(DUP); } @Test public void testDup2Inst4(){ Type aOp1Type = mock(IntType.class); Type aOp2Type = mock(LongType.class); Inst inst = new BDup2Inst(aOp1Type, aOp2Type); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP); inOrder.verify(mv).visitInsn(DUP2); } @Test public void testDup_x1Inst1(){ Type aOpType = mock(IntType.class); Type aUnderType = mock(IntType.class); Inst inst = new BDup1_x1Inst(aOpType, aUnderType); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP_X1); } @Test public void testDup_x1Inst2(){ Type aOpType = mock(IntType.class); Type aUnderType = mock(LongType.class); Inst inst = new BDup1_x1Inst(aOpType, aUnderType); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP_X2); } @Test public void testDup_x1Inst3(){ Type aOpType = mock(LongType.class); Type aUnderType = mock(IntType.class); Inst inst = new BDup1_x1Inst(aOpType, aUnderType); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP2_X1); } @Test public void testDup_x1Inst4(){ Type aOpType = mock(LongType.class); Type aUnderType = mock(LongType.class); Inst inst = new BDup1_x1Inst(aOpType, aUnderType); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP2_X2); } @Test public void testDup_x2Inst1(){ Type aOpType = mock(IntType.class); Type aUnder1Type = mock(IntType.class); Type aUnder2Type = mock(IntType.class); Inst inst = new BDup1_x2Inst(aOpType, aUnder1Type, aUnder2Type); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP_X2); } @Test(expected = RuntimeException.class) public void testDup_x2Inst2(){ Type aOpType = mock(IntType.class); Type aUnder1Type = mock(LongType.class); Type aUnder2Type = mock(IntType.class); Inst inst = new BDup1_x2Inst(aOpType, aUnder1Type, aUnder2Type); sut.generateInstruction(mv, inst); } @Test public void testDup_x2Inst3(){ Type aOpType = mock(LongType.class); Type aUnder1Type = mock(IntType.class); Type aUnder2Type = mock(IntType.class); Inst inst = new BDup1_x2Inst(aOpType, aUnder1Type, aUnder2Type); sut.generateInstruction(mv, inst); verify(mv).visitInsn(DUP2_X2); } @Test(expected = RuntimeException.class) public void testDup_x2Inst4(){ Type aOpType = mock(LongType.class); Type aUnder1Type = mock(LongType.class); Type aUnder2Type = mock(IntType.class); Inst inst = new BDup1_x2Inst(aOpType, aUnder1Type, aUnder2Type); sut.generateInstruction(mv, inst); } @Test(expected = RuntimeException.class) public void testDup2_x1Inst1(){ Type aOp1Type = mock(IntType.class); Type aOp2Type = mock(LongType.class); Type aUnderType = mock(IntType.class); Inst inst = new BDup2_x1Inst(aOp1Type, aOp2Type, aUnderType); sut.generateInstruction(mv, inst); } @Test public void testDup2_x1Inst2(){ Type aOp1Type = mock(IntType.class); Type aOp2Type = mock(IntType.class); Type aUnderType = mock(IntType.class); Inst inst = new BDup2_x1Inst(aOp1Type, aOp2Type, aUnderType); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP2_X1); } @Test public void testDup2_x1Inst3(){ Type aOp1Type = mock(IntType.class); Type aOp2Type = mock(IntType.class); Type aUnderType = mock(LongType.class); Inst inst = new BDup2_x1Inst(aOp1Type, aOp2Type, aUnderType); sut.generateInstruction(mv, inst); InOrder inOrder = inOrder(mv); inOrder.verify(mv).visitInsn(DUP2_X2); } @Test(expected = RuntimeException.class) public void testDup2_x2Inst1(){ Type aOp1Type = mock(LongType.class); Type aOp2Type = mock(IntType.class); Type aUnder1Type = mock(IntType.class); Type aUnder2Type = mock(IntType.class); Inst inst = new BDup2_x2Inst(aOp1Type, aOp2Type, aUnder1Type, aUnder2Type); sut.generateInstruction(mv, inst); } @Test(expected = RuntimeException.class) public void testDup2_x2Inst2(){ Type aOp1Type = mock(IntType.class); Type aOp2Type = mock(IntType.class); Type aUnder1Type = mock(IntType.class); Type aUnder2Type = mock(LongType.class); Inst inst = new BDup2_x2Inst(aOp1Type, aOp2Type, aUnder1Type, aUnder2Type); sut.generateInstruction(mv, inst); } @Test public void testDup2_x2Inst3(){ Type aOp1Type = mock(IntType.class); Type aOp2Type = mock(IntType.class); Type aUnder1Type = mock(IntType.class); Type aUnder2Type = mock(IntType.class); Inst inst = new BDup2_x2Inst(aOp1Type, aOp2Type, aUnder1Type, aUnder2Type); sut.generateInstruction(mv, inst); verify(mv).visitInsn(DUP2_X2); } @Test(expected = RuntimeException.class) public void testDup2_x2Inst4(){ Type aOp1Type = mock(IntType.class); Type aOp2Type = mock(VoidType.class); Type aUnder1Type = mock(IntType.class); Type aUnder2Type = mock(IntType.class); Inst inst = new BDup2_x2Inst(aOp1Type, aOp2Type, aUnder1Type, aUnder2Type); sut.generateInstruction(mv, inst); } }
9,522
25.67507
97
java
soot
soot-master/src/test/java/soot/java10/LoadingTest.java
/*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ package soot.java10; import static org.junit.Assert.assertTrue; import com.google.common.base.Optional; import org.junit.Test; import org.junit.experimental.categories.Category; import soot.G; import soot.Main; import soot.Scene; import soot.SootClass; import soot.SootModuleResolver; import soot.options.Options; import categories.Java11Test; /** * Tests the loading of Java 9 to 11 Modules. * * @author Andreas Dann */ @Category(Java11Test.class) public class LoadingTest { /** * load a JDK9to11 class by naming its module */ @Test public void testLoadingJava9to11Class() { G.reset(); Options.v().set_soot_modulepath("VIRTUAL_FS_FOR_JDK"); Scene.v().loadBasicClasses(); SootClass klass1 = SootModuleResolver.v().resolveClass("java.lang.invoke.VarHandle", SootClass.BODIES, Optional.of("java.base")); assertTrue(klass1.getName().equals("java.lang.invoke.VarHandle")); assertTrue(klass1.moduleName.equals("java.base")); SootClass klass2 = SootModuleResolver.v().resolveClass("java.lang.invoke.ConstantBootstraps", SootClass.BODIES, Optional.of("java.base")); assertTrue(klass2.getName().equals("java.lang.invoke.ConstantBootstraps")); assertTrue(klass2.moduleName.equals("java.base")); Scene.v().loadNecessaryClasses(); } /** * load a JDK9 class using the CI */ @Test public void testLoadingJava9ClassFromCI() { G.reset(); Main.main(new String[] { "-soot-modulepath", "VIRTUAL_FS_FOR_JDK", "-pp", "-src-prec", "only-class", "java.lang.invoke.VarHandle" }); SootClass klass = Scene.v().getSootClass("java.lang.invoke.VarHandle"); assertTrue(klass.getName().equals("java.lang.invoke.VarHandle")); assertTrue(klass.moduleName.equals("java.base")); } /** * load a JDK11 class using the CI */ @Test public void testLoadingJava11ClassFromCI() { G.reset(); Main.main(new String[] { "-soot-modulepath", "VIRTUAL_FS_FOR_JDK", "-pp", "-src-prec", "only-class", "java.lang.invoke.ConstantBootstraps" }); SootClass klass = Scene.v().getSootClass("java.lang.invoke.ConstantBootstraps"); assertTrue(klass.getName().equals("java.lang.invoke.ConstantBootstraps")); assertTrue(klass.moduleName.equals("java.base")); } }
3,093
29.633663
120
java
soot
soot-master/src/test/java/soot/java9/LoadingTest.java
/*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2014 Raja Vallee-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ package soot.java9; import static org.junit.Assert.assertTrue; import com.google.common.base.Optional; import com.google.common.io.Files; import java.io.File; import org.junit.Test; import org.junit.experimental.categories.Category; import soot.G; import soot.Main; import soot.Scene; import soot.SootClass; import soot.SootModuleResolver; import soot.options.Options; /** * Tests the loading of Java 9 Modules. * * @author Andreas Dann */ @Category(categories.Java9Test.class) public class LoadingTest { /** * load a JDK9 class by naming its module */ @Test public void testLoadingJava9Class() { G.reset(); File tempDir = Files.createTempDir(); Options.v().set_soot_modulepath(tempDir.getAbsolutePath()); Options.v().set_prepend_classpath(true); Scene.v().loadBasicClasses(); SootClass klass = SootModuleResolver.v().resolveClass("java.lang.invoke.VarHandle", SootClass.BODIES, Optional.of("java.base")); assertTrue(klass.getName().equals("java.lang.invoke.VarHandle")); assertTrue(klass.moduleName.equals("java.base")); } /** * load a JDK9 class using the CI */ @Test public void testLoadingJava9ClassFromCI() { G.reset(); File tempDir = Files.createTempDir(); Main.main(new String[] { "-soot-modulepath", tempDir.getAbsolutePath(),"-pp", "-src-prec", "only-class", "java.lang.invoke.VarHandle" }); SootClass klass = Scene.v().getSootClass("java.lang.invoke.VarHandle"); assertTrue(klass.getName().equals("java.lang.invoke.VarHandle")); assertTrue(klass.moduleName.equals("java.base")); } }
2,426
27.892857
120
java
soot
soot-master/src/test/java/soot/jbco/jimpleTransformations/ClassRenamerTest.java
/*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 1999 Raja Vallee-Rai * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ package soot.jbco.jimpleTransformations; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import java.util.Map; import org.junit.Test; public class ClassRenamerTest { @Test public void getName() { assertThat(ClassRenamer.v().getName(), equalTo(ClassRenamer.name)); } @Test public void getDependencies() { assertThat(ClassRenamer.v().getDependencies(), equalTo(new String[] { ClassRenamer.name })); } @Test public void getPackageName() { assertNull(ClassRenamer.getPackageName("")); assertNull(ClassRenamer.getPackageName(null)); assertNull(ClassRenamer.getPackageName(".")); assertNull(ClassRenamer.getPackageName("ClassName")); assertEquals("com.sable", ClassRenamer.getPackageName("com.sable.Soot")); } @Test public void getClassName() { assertNull(ClassRenamer.getClassName("")); assertNull(ClassRenamer.getClassName(null)); assertNull(ClassRenamer.getClassName(".")); assertEquals("ClassName", ClassRenamer.getClassName("ClassName")); assertEquals("Soot", ClassRenamer.getClassName("com.sable.Soot")); assertNull(ClassRenamer.getClassName("com.sable.")); } @Test public void getOrAddNewName_cachingName() { ClassRenamer.v().setRemovePackages(false); ClassRenamer.v().setRenamePackages(false); final String newName = ClassRenamer.v().getOrAddNewName(null, "ClassName"); assertThat(newName, not(containsString("."))); Map<String, String> mapping = ClassRenamer.v().getClassNameMapping((pOldName, pNewName) -> pOldName.equals("ClassName")); assertThat(mapping, hasEntry("ClassName", newName)); assertThat(mapping.size(), equalTo(1)); assertThat(ClassRenamer.v().getOrAddNewName(null, "ClassName"), equalTo(newName)); mapping = ClassRenamer.v().getClassNameMapping((pOldName, pNewName) -> pOldName.equals("ClassName")); assertThat(mapping, hasEntry("ClassName", newName)); assertThat(mapping.size(), equalTo(1)); } @Test public void getOrAddNewName_cachingPackage() { ClassRenamer.v().setRemovePackages(false); ClassRenamer.v().setRenamePackages(false); final String newName = ClassRenamer.v().getOrAddNewName("pac.age", "ClassName"); assertThat(newName, allOf(startsWith("pac.age."), not(endsWith("ClassName")))); assertThat(newName.split("\\.").length, equalTo(3)); assertThat(ClassRenamer.v().getOrAddNewName("pac.age", "ClassName"), equalTo(newName)); } @Test public void getOrAddNewName_nullClassName() { ClassRenamer.v().setRemovePackages(false); ClassRenamer.v().setRenamePackages(false); final String newName = ClassRenamer.v().getOrAddNewName("pac.age", null); assertThat(newName, startsWith("pac.age.")); assertThat(newName.split("\\.").length, equalTo(3)); assertThat(ClassRenamer.v().getOrAddNewName("pac.age", null), not(equalTo(newName))); } @Test public void getOrAddNewName_renamePackage() { ClassRenamer.v().setRemovePackages(false); ClassRenamer.v().setRenamePackages(true); final String newName = ClassRenamer.v().getOrAddNewName("pac.age.getOrAddNewName_renamePackage", "ClassName"); assertThat(newName, allOf(not(startsWith("pac.age.getOrAddNewName_renamePackage.")), not(endsWith("ClassName")))); assertThat(newName.split("\\.").length, equalTo(4)); assertThat(ClassRenamer.v().getOrAddNewName("pac.age.getOrAddNewName_renamePackage", "ClassName"), equalTo(newName)); } @Test public void getOrAddNewName_renamePackage_nullPackage() { ClassRenamer.v().setRemovePackages(false); ClassRenamer.v().setRenamePackages(true); final String newName = ClassRenamer.v().getOrAddNewName(null, "ClassName"); assertThat(newName, allOf(not(endsWith("ClassName")), not(containsString(".")))); final String newName0 = ClassRenamer.v().getOrAddNewName(null, "ClassName"); assertThat(newName0, equalTo(newName)); // package names and class names are equal final String newName1 = ClassRenamer.v().getOrAddNewName(null, "ClassName1"); assertThat(newName1, not(equalTo(newName))); assertThat(newName1.split("\\.").length, equalTo(2)); assertThat(newName.split("\\.")[0], equalTo(newName.split("\\.")[0])); // package names are equal } @Test public void getOrAddNewName_removePackage() { ClassRenamer.v().setRemovePackages(true); String newName = ClassRenamer.v().getOrAddNewName("a.b.c", "ClassName"); assertThat(newName, allOf(not(endsWith("ClassName")), not(containsString(".")))); String packageName = "a.b.c"; for (int i = 0; i < 100; i++) { packageName = packageName + ".p" + i; newName = ClassRenamer.v().getOrAddNewName(packageName, "ClassName"); assertThat(newName, allOf(not(endsWith("ClassName")), not(containsString(".")))); } } }
5,991
36.685535
125
java
soot
soot-master/src/test/java/soot/jimple/MethodHandleTest.java
package soot.jimple; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import org.junit.Test; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import soot.G; import soot.Main; /** * @author Alex Betra, */ public class MethodHandleTest { @Test public void testConstant() throws Throwable { // First generate a classfile with a MethodHnadle ClassWriter cv = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cv.visit(Opcodes.V1_7, Opcodes.ACC_PUBLIC, "HelloMethodHandles", null, Type.getInternalName(Object.class), null); MethodVisitor mv = cv.visitMethod(Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC, "getSquareRoot", Type.getMethodDescriptor(Type.getType(java.lang.invoke.MethodHandle.class)), null, null); mv.visitCode(); mv.visitLdcInsn(new Handle(Opcodes.H_INVOKESTATIC, Type.getInternalName(Math.class), "sqrt", Type.getMethodDescriptor(Type.DOUBLE_TYPE, Type.DOUBLE_TYPE), false)); mv.visitInsn(Opcodes.ARETURN); mv.visitEnd(); cv.visitEnd(); File tempDir = Files.createTempDir(); File classFile = new File(tempDir, "HelloMethodHandles.class"); Files.write(cv.toByteArray(), classFile); G.reset(); String[] commandLine = { "-pp", "-cp", tempDir.getAbsolutePath(), "-O", "HelloMethodHandles", }; System.out.println("Command Line: " + Arrays.toString(commandLine)); Main.main(commandLine); Class<?> clazz = validateClassFile("HelloMethodHandles"); java.lang.invoke.MethodHandle methodHandle = (java.lang.invoke.MethodHandle) clazz.getMethod("getSquareRoot").invoke(null); assertThat((Double) methodHandle.invoke(16.0), equalTo(4.0)); } @Test public void testInvoke() throws IOException, ClassNotFoundException { // First generate a classfile with a MethodHnadle ClassWriter cv = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cv.visit(Opcodes.V1_7, Opcodes.ACC_PUBLIC, "UniformDistribution", null, Type.getInternalName(Object.class), null); MethodVisitor mv = cv.visitMethod(Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC, "sample", Type.getMethodDescriptor(Type.DOUBLE_TYPE, Type.getType(java.lang.invoke.MethodHandle.class) /* rng method */, Type.DOUBLE_TYPE /* max */), null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); // load MethodHandle mv.visitInsn(Opcodes.ACONST_NULL); // null string... (just to test signatures with class names) // Call MethodHandle.invoke() with polymorphic signature: ()D mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(java.lang.invoke.MethodHandle.class), "invoke", Type.getMethodDescriptor(Type.DOUBLE_TYPE, Type.getType(String.class)), false); mv.visitVarInsn(Opcodes.DLOAD, 1); mv.visitInsn(Opcodes.DMUL); mv.visitInsn(Opcodes.DRETURN); mv.visitEnd(); cv.visitEnd(); File tempDir = Files.createTempDir(); File classFile = new File(tempDir, "UniformDistribution.class"); Files.write(cv.toByteArray(), classFile); G.reset(); String[] commandLine = { "-pp", "-cp", tempDir.getAbsolutePath(), "-O", "UniformDistribution" }; System.out.println("Command Line: " + Arrays.toString(commandLine)); Main.main(commandLine); validateClassFile("UniformDistribution"); } private Class<?> validateClassFile(String className) throws MalformedURLException, ClassNotFoundException { // Make sure the classfile is actually valid... URLClassLoader classLoader = new URLClassLoader(new URL[] { new File("sootOutput").toURI().toURL() }); return classLoader.loadClass(className); } }
4,834
33.29078
121
java
soot
soot-master/src/test/java/soot/jimple/toolkit/callgraph/TypeBasedReflectionModelTest.java
package soot.jimple.toolkit.callgraph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static soot.SootClass.BODIES; import static soot.SootClass.HIERARCHY; import java.util.Collections; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import soot.ArrayType; import soot.G; import soot.Local; import soot.Modifier; import soot.PackManager; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.Value; import soot.VoidType; import soot.jimple.IntConstant; import soot.jimple.Jimple; import soot.jimple.JimpleBody; import soot.jimple.StaticInvokeExpr; import soot.jimple.StringConstant; import soot.jimple.VirtualInvokeExpr; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.options.Options; /** * This class contains tests for {@link soot.jimple.toolkits.callgraph.OnFlyCallGraphBuilder.TypeBasedReflectionModel}. * * @author Manuel Benz * created on 01.08.17 */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TypeBasedReflectionModelTest { /** * Checks if the reflection model accepts a string constant as base of a call to Method.invoke. */ @Test public void constantBase() { genericLocalVsStringConstantTest(true); } /** * Checks if the reflection model accepts a local as base of a call to Method.invoke. */ @Test public void localBase() { genericLocalVsStringConstantTest(false); } @Test public void staticBase() { //TODO } private void genericLocalVsStringConstantTest(boolean useConstantBase) { resetSoot(); Options.v().set_allow_phantom_refs(true); Options.v().set_whole_program(true); Options.v().set_no_bodies_for_excluded(true); Scene.v().loadBasicClasses(); SootClass tc = setUpTestClass(useConstantBase); Scene.v().addClass(tc); tc.setApplicationClass(); Scene.v().setMainClass(tc); Scene.v().forceResolve(tc.getName(), BODIES); Scene.v().loadNecessaryClasses(); Options.v().setPhaseOption("cg.spark", "on"); Options.v().setPhaseOption("cg", "types-for-invoke:true"); // this option is necessary to get constant bases working Options.v().setPhaseOption("wjpp.cimbt", "enabled:true"); Options.v().setPhaseOption("wjpp.cimbt","verbose:true"); PackManager.v().getPack("wjpp").apply(); PackManager.v().getPack("cg").apply(); CallGraph callGraph = Scene.v().getCallGraph(); boolean found = false; for (Edge edge : callGraph) { if (edge.getSrc().method().getSignature().contains("main") && edge.getTgt().method().getSignature().contains("concat")) { found = true; break; } } Assert.assertTrue("There should be an edge from main to String.concat after resolution of the target of Method.invoke, but none found", found); } private void resetSoot() { G.reset(); Scene.v().releaseCallGraph(); Scene.v().releasePointsToAnalysis(); Scene.v().releaseReachableMethods(); G.v().resetSpark(); } private SootClass setUpTestClass(boolean useConstantBase) { SootClass cl = new SootClass("soot.test.ReflectiveBase", Modifier.PUBLIC); SootMethod m = new SootMethod("main", Collections.singletonList((Type) ArrayType.v(Scene.v().getType("java.lang.String"), 1)), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); cl.addMethod(m); cl.setApplicationClass(); cl.setResolvingLevel(HIERARCHY); JimpleBody b = Jimple.v().newBody(m); // add parameter local Local arg = Jimple.v().newLocal("l0", ArrayType.v(RefType.v("java.lang.String"), 1)); b.getLocals().add(arg); b.getUnits().add(Jimple.v().newIdentityStmt(arg, Jimple.v().newParameterRef(ArrayType.v (RefType.v("java.lang.String"), 1), 0))); // get class StaticInvokeExpr getClass = Jimple.v().newStaticInvokeExpr( Scene.v().getMethod("<java.lang.Class: java.lang.Class forName(java.lang.String)>").makeRef(), StringConstant.v("java.lang.String")); Local clz = Jimple.v().newLocal("clz", Scene.v().getType("java.lang.Class")); b.getLocals().add(clz); b.getUnits().add(Jimple.v().newAssignStmt(clz, getClass)); // get declared method VirtualInvokeExpr concat = Jimple.v().newVirtualInvokeExpr(clz, Scene.v().getMethod("<java.lang.Class: java.lang.reflect.Method getDeclaredMethod(java.lang.String,java.lang.Class[])>").makeRef(), StringConstant.v("concat"), clz); Local method = Jimple.v().newLocal("method", Scene.v().getType("java.lang.reflect.Method")); b.getLocals().add(method); b.getUnits().add(Jimple.v().newAssignStmt(method, concat)); // prepare base object for reflective call String baseString = "Reflective call base "; Value base; if (useConstantBase) base = StringConstant.v(baseString); else { Local l = Jimple.v().newLocal("base", Scene.v().getType("java.lang.String")); base = l; b.getLocals().add(l); b.getUnits().add(Jimple.v().newAssignStmt(l, StringConstant.v(baseString))); } // prepare argument for reflective invocation of concat method Local l = Jimple.v().newLocal("arg", Scene.v().getType("java.lang.String")); b.getLocals().add(l); b.getUnits().add(Jimple.v().newAssignStmt(l, StringConstant.v("concat"))); // prepare arg array Local argArray = Jimple.v().newLocal("argArray", ArrayType.v(Scene.v().getType("java.lang.Object"), 1)); b.getLocals().add(argArray); b.getUnits().add(Jimple.v().newAssignStmt(argArray, Jimple.v().newNewArrayExpr(Scene.v().getType("java.lang.Object"), IntConstant.v(1)))); b.getUnits().add(Jimple.v().newAssignStmt(Jimple.v().newArrayRef(argArray, IntConstant.v(0)), l)); // invoke reflective method b.getUnits().add(Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(method, Scene.v().getMethod("<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>").makeRef(), base, argArray))); b.getUnits().add(Jimple.v().newReturnVoidStmt()); b.validate(); m.setActiveBody(b); return cl; } }
7,494
35.207729
151
java
soot
soot-master/src/test/java/soot/jimple/toolkits/scalar/DeadAssignmentEliminatorTest.java
package soot.jimple.toolkits.scalar; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2020 Raja Vallee-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Before; import org.junit.Test; import soot.ArrayType; import soot.DoubleType; import soot.G; import soot.IntType; import soot.Local; import soot.Modifier; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.UnitPatchingChain; import soot.jimple.Jimple; import soot.jimple.JimpleBody; import soot.jimple.NullConstant; import soot.options.Options; import soot.util.Chain; /** * Tests for the dead assignment eliminator. */ public class DeadAssignmentEliminatorTest { /** * Initializes Soot. */ @Before public void initialize() { // load necessary classes G.reset(); Options o = Options.v(); o.set_whole_program(true); Scene.v().loadNecessaryClasses(); Scene.v().loadClassAndSupport("java.lang.Object"); Scene.v().loadClassAndSupport("java.lang.String"); Scene.v().loadClassAndSupport("java.lang.Number"); } /** * Tests if the eliminator keeps array length expression which might cause NPEs. */ @Test public void keepArrayLength() { // create test method and body SootClass cl = new SootClass("TestClass", Modifier.PUBLIC); SootMethod method = new SootMethod("testMethod", Collections.singletonList(RefType.v("java.lang.Object")), ArrayType.v(IntType.v(), 1), Modifier.PUBLIC); cl.addMethod(method); JimpleBody body = Jimple.v().newBody(method); method.setActiveBody(body); // create locals Chain<Local> locals = body.getLocals(); Local a = Jimple.v().newLocal("a", ArrayType.v(IntType.v(), 1)); locals.add(a); Local b = Jimple.v().newLocal("b", IntType.v()); locals.add(b); // create code UnitPatchingChain units = body.getUnits(); Unit identity0 = Jimple.v().newIdentityStmt(a, Jimple.v().newParameterRef(RefType.v("java.lang.Object"), 0)); units.add(identity0); Unit cast0 = Jimple.v().newAssignStmt(b, Jimple.v().newLengthExpr(a)); units.add(cast0); Unit ret = Jimple.v().newReturnStmt(b); units.add(ret); // execute transform DeadAssignmentEliminator.v().internalTransform(body, "testPhase", Collections.emptyMap()); // check resulting code (length statement should be preserved) Iterator<Unit> it = units.iterator(); assertEquals(identity0, it.next()); assertEquals(cast0, it.next()); assertEquals(ret, it.next()); assertEquals(3, units.size()); } /** * Tests if the eliminator keeps casts which can throw ClassCastExceptions. */ @Test public void keepEssentialCast() { // create test method and body SootClass cl = new SootClass("TestClass", Modifier.PUBLIC); SootMethod method = new SootMethod("testMethod", Collections.singletonList(RefType.v("java.lang.Object")), ArrayType.v(IntType.v(), 1), Modifier.PUBLIC); cl.addMethod(method); JimpleBody body = Jimple.v().newBody(method); method.setActiveBody(body); // create locals Chain<Local> locals = body.getLocals(); Local a = Jimple.v().newLocal("a", IntType.v()); locals.add(a); Local b = Jimple.v().newLocal("b", IntType.v()); locals.add(b); Local c = Jimple.v().newLocal("c", IntType.v()); locals.add(c); Local d = Jimple.v().newLocal("d", IntType.v()); locals.add(d); // create code UnitPatchingChain units = body.getUnits(); Unit identity0 = Jimple.v().newIdentityStmt(a, Jimple.v().newParameterRef(RefType.v("java.lang.Object"), 0)); units.add(identity0); Unit cast0 = Jimple.v().newAssignStmt(b, Jimple.v().newCastExpr(a, ArrayType.v(IntType.v(), 1))); units.add(cast0); Unit cast1 = Jimple.v().newAssignStmt(c, Jimple.v().newCastExpr(a, RefType.v("java.lang.Number"))); units.add(cast1); Unit cast2 = Jimple.v().newAssignStmt(d, Jimple.v().newCastExpr(NullConstant.v(), RefType.v("java.lang.Number"))); units.add(cast2); Unit ret = Jimple.v().newReturnStmt(b); units.add(ret); // execute transform DeadAssignmentEliminator.v().internalTransform(body, "testPhase", Collections.emptyMap()); // check resulting code (cast should be removed) Iterator<Unit> it = units.iterator(); assertEquals(identity0, it.next()); assertEquals(cast0, it.next()); assertEquals(cast1, it.next()); assertEquals(ret, it.next()); assertEquals(4, units.size()); } /** * Tests if the eliminator removes primitive casts which cannot throw ClassCastExceptions. */ @Test public void removePrimitiveCast() { // create test method and body SootClass cl = new SootClass("TestClass", Modifier.PUBLIC); SootMethod method = new SootMethod("testMethod", Arrays.asList(IntType.v(), IntType.v()), IntType.v(), Modifier.PUBLIC); cl.addMethod(method); JimpleBody body = Jimple.v().newBody(method); method.setActiveBody(body); // create locals Chain<Local> locals = body.getLocals(); Local a = Jimple.v().newLocal("a", IntType.v()); locals.add(a); Local b = Jimple.v().newLocal("b", IntType.v()); locals.add(b); Local c = Jimple.v().newLocal("c", IntType.v()); locals.add(c); Local d = Jimple.v().newLocal("d", DoubleType.v()); locals.add(d); // create code UnitPatchingChain units = body.getUnits(); Unit identity0 = Jimple.v().newIdentityStmt(a, Jimple.v().newParameterRef(IntType.v(), 0)); units.add(identity0); Unit identity1 = Jimple.v().newIdentityStmt(b, Jimple.v().newParameterRef(IntType.v(), 1)); units.add(identity1); Unit addition = Jimple.v().newAssignStmt(c, Jimple.v().newAddExpr(a, b)); units.add(addition); Unit cast = Jimple.v().newAssignStmt(d, Jimple.v().newCastExpr(a, DoubleType.v())); units.add(cast); Unit ret = Jimple.v().newReturnStmt(c); units.add(ret); // execute transform DeadAssignmentEliminator.v().internalTransform(body, "testPhase", Collections.emptyMap()); // check resulting code (cast should be removed) Iterator<Unit> it = units.iterator(); assertEquals(identity0, it.next()); assertEquals(identity1, it.next()); assertEquals(addition, it.next()); assertEquals(ret, it.next()); assertEquals(4, units.size()); } }
7,171
33.315789
124
java
soot
soot-master/src/test/java/soot/jimple/toolkits/typing/TypingMinimizeTest.java
package soot.jimple.toolkits.typing; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.hamcrest.Matchers.containsInAnyOrder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.G; import soot.Local; import soot.Modifier; import soot.Scene; import soot.SootClass; import soot.Type; import soot.jimple.internal.JimpleLocal; import soot.jimple.toolkits.typing.fast.BytecodeHierarchy; import soot.jimple.toolkits.typing.fast.DefaultTypingStrategy; import soot.jimple.toolkits.typing.fast.ITypingStrategy; import soot.jimple.toolkits.typing.fast.Typing; import soot.options.Options; /** * JUnit-Tests for the {@link Typing#minimize(List, soot.jimple.toolkits.typing.fast.IHierarchy)} method. * * For each test we generate a simple synthetic class hierarchy and some {@link Typing}s we minimize afterwards and check the * result. * * @author Fabian Brenner, Jan Peter Stotz */ public class TypingMinimizeTest { /****************************************************** * Analysis of 29 Android apps with multiple typings: ****************************************************** * * Most common Classes for Typings: * * <pre> * java.io.Serializable: 4308 * java.lang.Comparable: 4163 * java.util.RandomAccess: 238 * java.util.AbstractList: 138 * java.lang.Object: 188 * android.view.View: 109 * java.util.List: 172 * java.lang.Number: 198 * java.lang.Cloneable: 102 * </pre> * * ---> mostly Java and Android Classes (mostly Interfaces) * *********************************************** * * ---> Common Pairs: * * [I] = 771 [A, I] = 357 [B, I] = 80 [I, O]= 79 [A, I, O] = 40 * * Most common Typing-Class-Pair: * * <pre> * 2 LocalType: $u8#772 unknown value:java.io.Serializable * 2 LocalType: $u2#523 unknown value:java.lang.Comparable * * 8 LocalType: $u4#62 unknown value:java.io.Serializable * 9 LocalType: $u11#39 unknown value:java.lang.Number * 9 LocalType: $u2#23 unknown value:java.lang.Comparable * * 1 LocalType: $u1#18 unknown value:java.util.RandomAccess * 1 LocalType: $u0#7 unknown value:java.util.List * 2 LocalType: $u1#18 unknown value:java.util.AbstractList * 0 LocalType: $u2#9 unknown value:java.lang.Object * * 0 LocalType: $u1#4 unknown value:java.lang.Cloneable * 1 LocalType: $u1#4 unknown value:java.io.Serializable * 2 LocalType: $u1#4 unknown value:java.util.AbstractMap * * 0 LocalType: $u0#6 unknown * 1 LocalType: $u0#6 unknown value:com.facebook.ads.internal.view.c.c.c * 2 LocalType: $u0#6 unknown value:android.view.TextureView * * 0 LocalType: $u9#8 unknown value:java.lang.Object * 1 LocalType: $u9#8 unknown * 2 LocalType: $u9#8 unknown value:android.widget.Adapter * </pre> * ********************************************** * * ---> If Typing-Classes are related, then: * * 1. (Java) Interface and AbstractClass 2. JavaClass and Abstract 3. Interface and Interface * * */ private static final Logger logger = LoggerFactory.getLogger(TypingMinimizeTest.class); Type stringType; Type integerType; Type serializableType; Type comparableType; Type numberType; Type cloneableType; Type processType; Type randomAccessType; Type listType; Type abstractListType; Type abstractMapType; Type objectType; // generated Types Type interfaceType; Type abstractClass_Interface1Type; Type abstractClass_Interface2Type; Type class_AbstractInterfaceClassType; Type class_InterfaceType; Type interfaceInterfaceType; Type abstractType; Type class_AbstractType; Type fatherClassType; Type childClassType; @Before public void init() { G.reset(); Options o = Options.v(); o.prepend_classpath(); o.set_include_all(true); o.set_whole_program(true); Scene.v().loadNecessaryClasses(); Scene.v().loadClassAndSupport("java.lang.Object"); generateClasses(); } private void generateClasses() { SootClass sClass = new SootClass("Interface", Modifier.INTERFACE); Scene.v().addClass(sClass); sClass = new SootClass("AbstractClass_Interface1", Modifier.ABSTRACT); sClass.setSuperclass(Scene.v().getSootClass("java.lang.Object")); sClass.addInterface(Scene.v().getSootClass("Interface")); Scene.v().addClass(sClass); sClass = new SootClass("AbstractClass_Interface2", Modifier.ABSTRACT); sClass.setSuperclass(Scene.v().getSootClass("AbstractClass_Interface1")); Scene.v().addClass(sClass); sClass = new SootClass("InterfaceInterface", Modifier.INTERFACE); sClass.addInterface(Scene.v().getSootClass("Interface")); Scene.v().addClass(sClass); sClass = new SootClass("Class_Interface", Modifier.PUBLIC); sClass.addInterface(Scene.v().getSootClass("Interface")); Scene.v().addClass(sClass); sClass = new SootClass("Class_AbstractInterfaceClass", Modifier.PUBLIC); sClass.setSuperclass(Scene.v().getSootClass("AbstractClass_Interface2")); Scene.v().addClass(sClass); sClass = new SootClass("Abstract", Modifier.ABSTRACT); sClass.setSuperclass(Scene.v().getSootClass("java.lang.Object")); Scene.v().addClass(sClass); sClass = new SootClass("Class_Abstract", Modifier.ABSTRACT); sClass.setSuperclass(Scene.v().getSootClass("Abstract")); Scene.v().addClass(sClass); sClass = new SootClass("FatherClass", Modifier.ABSTRACT); sClass.setSuperclass(Scene.v().getSootClass("java.lang.Object")); Scene.v().addClass(sClass); sClass = new SootClass("ChildClass", Modifier.ABSTRACT); sClass.setSuperclass(Scene.v().getSootClass("FatherClass")); Scene.v().addClass(sClass); stringType = Scene.v().getType("java.lang.String"); integerType = Scene.v().getType("java.lang.Integer"); serializableType = Scene.v().getType("java.io.Serializable"); comparableType = Scene.v().getType("java.lang.Comparable"); numberType = Scene.v().getType("java.lang.Number"); cloneableType = Scene.v().getType("java.lang.Cloneable"); processType = Scene.v().getType("java.lang.Process"); randomAccessType = Scene.v().getType("java.util.RandomAccess"); listType = Scene.v().getType("java.util.List"); abstractListType = Scene.v().getType("java.util.AbstractList"); abstractMapType = Scene.v().getType("java.util.AbstractMap"); objectType = Scene.v().getType("java.lang.Object"); interfaceType = Scene.v().getType("Interface"); abstractClass_Interface1Type = Scene.v().getType("AbstractClass_Interface1"); abstractClass_Interface2Type = Scene.v().getType("AbstractClass_Interface2"); class_AbstractInterfaceClassType = Scene.v().getType("Class_AbstractInterfaceClass"); class_InterfaceType = Scene.v().getType("Class_Interface"); interfaceInterfaceType = Scene.v().getType("InterfaceInterface"); abstractType = Scene.v().getType("Abstract"); class_AbstractType = Scene.v().getType("Class_Abstract"); fatherClassType = Scene.v().getType("FatherClass"); childClassType = Scene.v().getType("ChildClass"); } @Test public void testMostCommonTypingPairs_1() { logger.debug("Starting Object Random Minimize"); List<Typing> typingList = new ArrayList<>(); Type Type1 = serializableType; Type Type2 = comparableType; Local x1 = new JimpleLocal("$x1", null); Typing resultTyping; Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, Type1); typingList.add(typing1); resultTyping = typing1; Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, Type2); typingList.add(typing2); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(2, typingList.size()); assertEquals(resultTyping, typingList.get(0)); } private ITypingStrategy getTypingStrategy() { return new DefaultTypingStrategy(); } @Test public void testMostCommonTypingPairs_2() { logger.debug("Starting Object Random Minimize"); List<Typing> typingList = new ArrayList<>(); Type Type1 = serializableType; Type Type2 = comparableType; Type Type3 = numberType; Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, Type1); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, Type2); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, Type3); typingList.add(typing3); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(2, typingList.size()); assertThat(typingList, containsInAnyOrder(typing2, typing3)); } @Test public void testMostCommonTypingPairs_3() { List<Typing> typingList = new ArrayList<>(); Type Type1 = randomAccessType; Type Type2 = listType; Type Type3 = abstractListType; Type Type4 = objectType; Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, Type1); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, Type2); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, Type3); typingList.add(typing3); Typing typing4 = new Typing(Arrays.asList(x1)); typing4.set(x1, Type4); typingList.add(typing4); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(2, typingList.size()); assertThat(typingList, containsInAnyOrder(typing1, typing3)); } @Test public void testMostCommonTypingPairs_4() { List<Typing> typingList = new ArrayList<>(); Type Type1 = cloneableType; Type Type2 = serializableType; Type Type3 = abstractMapType; Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, Type1); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, Type2); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, Type3); typingList.add(typing3); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(3, typingList.size()); } /** * In this test, no minimization can take place with the current minimization method. Because "Serializable" and * "Comparable" are on the same hierarchy level and can be used for any local in any typing. This leads, for example, to * the 16384 typings of the Telegram app. */ @Test public void testHugeCommonTypingPair() { List<Typing> typingList = new ArrayList<>(); Type Type1 = serializableType; Type Type2 = comparableType; Local x1 = new JimpleLocal("$x1", null); Local x2 = new JimpleLocal("$x2", null); Local x3 = new JimpleLocal("$x3", null); Typing typing1 = new Typing(Arrays.asList(x1, x2, x3)); typing1.set(x1, Type1); typing1.set(x2, Type1); typing1.set(x3, Type1); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1, x2, x3)); typing2.set(x1, Type2); typing2.set(x2, Type1); typing2.set(x3, Type1); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1, x2, x3)); typing3.set(x1, Type1); typing3.set(x2, Type2); typing3.set(x3, Type1); typingList.add(typing3); Typing typing4 = new Typing(Arrays.asList(x1, x2, x3)); typing4.set(x1, Type1); typing4.set(x2, Type1); typing4.set(x3, Type2); typingList.add(typing4); Typing typing5 = new Typing(Arrays.asList(x1, x2, x3)); typing5.set(x1, Type2); typing5.set(x2, Type2); typing5.set(x3, Type1); typingList.add(typing5); Typing typing6 = new Typing(Arrays.asList(x1, x2, x3)); typing6.set(x1, Type2); typing6.set(x2, Type1); typing6.set(x3, Type2); typingList.add(typing6); Typing typing7 = new Typing(Arrays.asList(x1, x2, x3)); typing7.set(x1, Type1); typing7.set(x2, Type2); typing7.set(x3, Type2); typingList.add(typing7); Typing typing8 = new Typing(Arrays.asList(x1, x2, x3)); typing8.set(x1, Type2); typing8.set(x2, Type2); typing8.set(x3, Type2); typingList.add(typing8); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(8, typingList.size()); assertThat(typingList, containsInAnyOrder(typing1, typing2, typing3, typing4, typing5, typing6, typing7, typing8)); } @Test public void testAbstractInterfaceTyping() { List<Typing> typingList = new ArrayList<>(); Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, interfaceType); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, abstractClass_Interface2Type); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, class_AbstractInterfaceClassType); typingList.add(typing3); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(1, typingList.size()); assertThat(typingList, containsInAnyOrder(typing3)); } @Test public void testAbstractAbstractTyping() { logger.debug("Starting Object Random Minimize"); List<Typing> typingList = new ArrayList<>(); Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, interfaceType); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, abstractClass_Interface1Type); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, abstractClass_Interface2Type); typingList.add(typing3); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(1, typingList.size()); assertThat(typingList, containsInAnyOrder(typing3)); } @Test public void testJavaInterfaceTyping() { List<Typing> typingList = new ArrayList<>(); Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, interfaceType); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, integerType); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, numberType); typingList.add(typing3); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(2, typingList.size()); assertThat(typingList, containsInAnyOrder(typing2, typing1)); } @Test public void testInterfaceInterfaceTyping() { List<Typing> typingList = new ArrayList<>(); Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, interfaceType); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, interfaceInterfaceType); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, numberType); typingList.add(typing3); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(2, typingList.size()); assertThat(typingList, containsInAnyOrder(typing2, typing3)); } /** * All Types of Classes with a relationship * * Object --> StringType Comparable --> StringType AbstractClass_Interface1Type --> AbstractClass_Interface2Type --> * Class_AbstractInterfaceClassType */ @Test public void testAllRelatedClassesTyping() { List<Typing> typingList = new ArrayList<>(); Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, objectType); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, stringType); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, comparableType); typingList.add(typing3); Typing typing4 = new Typing(Arrays.asList(x1)); typing4.set(x1, abstractClass_Interface2Type); typingList.add(typing4); Typing typing5 = new Typing(Arrays.asList(x1)); typing5.set(x1, class_AbstractInterfaceClassType); typingList.add(typing5); Typing typing6 = new Typing(Arrays.asList(x1)); typing6.set(x1, abstractClass_Interface1Type); typingList.add(typing6); Typing typing7 = new Typing(Arrays.asList(x1)); typing7.set(x1, class_InterfaceType); typingList.add(typing7); Typing typing8 = new Typing(Arrays.asList(x1)); typing8.set(x1, abstractType); typingList.add(typing8); Typing typing9 = new Typing(Arrays.asList(x1)); typing9.set(x1, class_AbstractType); typingList.add(typing9); Typing typing10 = new Typing(Arrays.asList(x1)); typing10.set(x1, fatherClassType); typingList.add(typing10); Typing typing11 = new Typing(Arrays.asList(x1)); typing11.set(x1, childClassType); typingList.add(typing11); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(5, typingList.size()); assertThat(typingList, containsInAnyOrder(typing2, typing5, typing7, typing9, typing11)); } /** * All Classes which aren't related to each other (except Object) */ @Test public void testAllNonRelatedClassesTyping() { List<Typing> typingList = new ArrayList<>(); Local x1 = new JimpleLocal("$x1", null); Typing typing1 = new Typing(Arrays.asList(x1)); typing1.set(x1, objectType); typingList.add(typing1); Typing typing2 = new Typing(Arrays.asList(x1)); typing2.set(x1, stringType); typingList.add(typing2); Typing typing3 = new Typing(Arrays.asList(x1)); typing3.set(x1, cloneableType); typingList.add(typing3); Typing typing4 = new Typing(Arrays.asList(x1)); typing4.set(x1, integerType); typingList.add(typing4); Typing typing5 = new Typing(Arrays.asList(x1)); typing5.set(x1, processType); typingList.add(typing5); Typing typing6 = new Typing(Arrays.asList(x1)); typing6.set(x1, interfaceType); typingList.add(typing6); Typing typing7 = new Typing(Arrays.asList(x1)); typing7.set(x1, abstractType); typingList.add(typing7); Typing typing8 = new Typing(Arrays.asList(x1)); typing8.set(x1, fatherClassType); typingList.add(typing8); getTypingStrategy().minimize(typingList, new BytecodeHierarchy()); assertEquals(7, typingList.size()); assertThat(typingList, containsInAnyOrder(typing2, typing3, typing4, typing5, typing6, typing7, typing8)); } }
19,758
29.586687
125
java
soot
soot-master/src/test/java/soot/toolkits/exceptions/ExceptionTestUtility.java
package soot.toolkits.exceptions; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import soot.AnySubType; import soot.RefLikeType; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.options.Options; /** * Class which packages together some objects useful in unit tests of exception * handling. */ public class ExceptionTestUtility { // Individual Throwable types for our tests: final RefType THROWABLE; final RefType EXCEPTION; final RefType RUNTIME_EXCEPTION; final RefType ARITHMETIC_EXCEPTION; final RefType ARRAY_STORE_EXCEPTION; final RefType CLASS_CAST_EXCEPTION; final RefType ILLEGAL_MONITOR_STATE_EXCEPTION; final RefType INDEX_OUT_OF_BOUNDS_EXCEPTION; final RefType ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION; final RefType STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION; final RefType NEGATIVE_ARRAY_SIZE_EXCEPTION; final RefType NULL_POINTER_EXCEPTION; final RefType ERROR; final RefType LINKAGE_ERROR; final RefType CLASS_CIRCULARITY_ERROR; final RefType CLASS_FORMAT_ERROR; final RefType UNSUPPORTED_CLASS_VERSION_ERROR; final RefType EXCEPTION_IN_INITIALIZER_ERROR; final RefType INCOMPATIBLE_CLASS_CHANGE_ERROR; final RefType ABSTRACT_METHOD_ERROR; final RefType ILLEGAL_ACCESS_ERROR; final RefType INSTANTIATION_ERROR; final RefType NO_SUCH_FIELD_ERROR; final RefType NO_SUCH_METHOD_ERROR; final RefType NO_CLASS_DEF_FOUND_ERROR; final RefType UNSATISFIED_LINK_ERROR; final RefType VERIFY_ERROR; final RefType THREAD_DEATH; final RefType VIRTUAL_MACHINE_ERROR; final RefType INTERNAL_ERROR; final RefType OUT_OF_MEMORY_ERROR; final RefType STACK_OVERFLOW_ERROR; final RefType UNKNOWN_ERROR; final RefType AWT_ERROR; final RefType UNDECLARED_THROWABLE_EXCEPTION; final RefType UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION; final RefType PHANTOM_EXCEPTION1; final RefType PHANTOM_EXCEPTION2; // The universe of all Throwable types for our tests: final Set<RefType> ALL_TEST_THROWABLES; // Set that matches the representation of all Throwables used // internally by ThrowableSet: final Set<RefLikeType> ALL_THROWABLES_REP; // Some useful subsets of our Throwable universe: final Set<RefLikeType> VM_ERRORS; final Set<RefLikeType> VM_ERRORS_PLUS_SUPERTYPES; final Set<RefLikeType> VM_AND_RESOLVE_CLASS_ERRORS; final Set<RefLikeType> VM_AND_RESOLVE_CLASS_ERRORS_PLUS_SUPERTYPES; final Set<RefLikeType> VM_AND_RESOLVE_FIELD_ERRORS; final Set<RefLikeType> VM_AND_RESOLVE_FIELD_ERRORS_PLUS_SUPERTYPES; final Set<RefLikeType> VM_AND_RESOLVE_METHOD_ERRORS; final Set<RefLikeType> VM_AND_RESOLVE_METHOD_ERRORS_PLUS_SUPERTYPES; final Set<RefLikeType> ALL_TEST_ERRORS; final Set<RefLikeType> ALL_TEST_ERRORS_PLUS_SUPERTYPES; final Set<RefLikeType> PERENNIAL_THROW_EXCEPTIONS; final Set<RefLikeType> PERENNIAL_THROW_EXCEPTIONS_PLUS_SUPERTYPES; final Set<RefLikeType> THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE; final Set<RefLikeType> THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUPERTYPES; final Set<RefLikeType> THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUBTYPES; final Set<RefLikeType> THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUBTYPES_PLUS_SUPERTYPES; // Sets that match the representations of subsets of Errors used // internally by ThrowableSet: final Set<RefLikeType> VM_AND_RESOLVE_CLASS_ERRORS_REP; final Set<RefLikeType> VM_AND_RESOLVE_FIELD_ERRORS_REP; final Set<RefLikeType> VM_AND_RESOLVE_METHOD_ERRORS_REP; final Set<RefLikeType> ALL_ERRORS_REP; ExceptionTestUtility() { Options.v().set_prepend_classpath(true); THROWABLE = Scene.v().getRefType("java.lang.Throwable"); ERROR = Scene.v().getRefType("java.lang.Error"); Scene.v().forceResolve("java.lang.Exception", SootClass.BODIES); EXCEPTION = Scene.v().getRefType("java.lang.Exception"); // runtime exceptions. RUNTIME_EXCEPTION = Scene.v().getRefType("java.lang.RuntimeException"); ARITHMETIC_EXCEPTION = Scene.v().getRefType( "java.lang.ArithmeticException"); ARRAY_STORE_EXCEPTION = Scene.v().getRefType( "java.lang.ArrayStoreException"); CLASS_CAST_EXCEPTION = Scene.v().getRefType( "java.lang.ClassCastException"); ILLEGAL_MONITOR_STATE_EXCEPTION = Scene.v().getRefType( "java.lang.IllegalMonitorStateException"); INDEX_OUT_OF_BOUNDS_EXCEPTION = Scene.v().getRefType( "java.lang.IndexOutOfBoundsException"); ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION = Scene.v().getRefType( "java.lang.ArrayIndexOutOfBoundsException"); Scene.v().forceResolve("java.lang.StringIndexOutOfBoundsException", SootClass.BODIES); STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION = Scene.v().getRefType( "java.lang.StringIndexOutOfBoundsException"); NEGATIVE_ARRAY_SIZE_EXCEPTION = Scene.v().getRefType( "java.lang.NegativeArraySizeException"); NULL_POINTER_EXCEPTION = Scene.v().getRefType( "java.lang.NullPointerException"); // linkage errors. LINKAGE_ERROR = Scene.v().getRefType("java.lang.LinkageError"); CLASS_CIRCULARITY_ERROR = Scene.v().getRefType( "java.lang.ClassCircularityError"); CLASS_FORMAT_ERROR = Scene.v().getRefType("java.lang.ClassFormatError"); Scene.v().forceResolve("java.lang.UnsupportedClassVersionError", SootClass.BODIES); UNSUPPORTED_CLASS_VERSION_ERROR = Scene.v().getRefType( "java.lang.UnsupportedClassVersionError"); EXCEPTION_IN_INITIALIZER_ERROR = Scene.v().getRefType( "java.lang.ExceptionInInitializerError"); INCOMPATIBLE_CLASS_CHANGE_ERROR = Scene.v().getRefType( "java.lang.IncompatibleClassChangeError"); ABSTRACT_METHOD_ERROR = Scene.v().getRefType( "java.lang.AbstractMethodError"); ILLEGAL_ACCESS_ERROR = Scene.v().getRefType( "java.lang.IllegalAccessError"); INSTANTIATION_ERROR = Scene.v().getRefType( "java.lang.InstantiationError"); NO_SUCH_FIELD_ERROR = Scene.v() .getRefType("java.lang.NoSuchFieldError"); NO_SUCH_METHOD_ERROR = Scene.v().getRefType( "java.lang.NoSuchMethodError"); NO_CLASS_DEF_FOUND_ERROR = Scene.v().getRefType( "java.lang.NoClassDefFoundError"); UNSATISFIED_LINK_ERROR = Scene.v().getRefType( "java.lang.UnsatisfiedLinkError"); VERIFY_ERROR = Scene.v().getRefType("java.lang.VerifyError"); // Token non-linkage Error (in the sense that it is not among // Errors that the VM might throw itself during linkage---any // error could be generated during linking by a static // initializer). Scene.v().forceResolve("java.awt.AWTError", SootClass.BODIES); AWT_ERROR = Scene.v().getRefType("java.awt.AWTError"); // VM errors: INTERNAL_ERROR = Scene.v().getRefType("java.lang.InternalError"); OUT_OF_MEMORY_ERROR = Scene.v() .getRefType("java.lang.OutOfMemoryError"); STACK_OVERFLOW_ERROR = Scene.v().getRefType( "java.lang.StackOverflowError"); UNKNOWN_ERROR = Scene.v().getRefType("java.lang.UnknownError"); THREAD_DEATH = Scene.v().getRefType("java.lang.ThreadDeath"); Scene.v().forceResolve("java.lang.VirtualMachineError", SootClass.BODIES); VIRTUAL_MACHINE_ERROR = Scene.v().getRefType( "java.lang.VirtualMachineError"); // Two Throwables that our test statements will never throw (except // for invoke statements--in the absence of interprocedural analysis, // we have to assume they can throw anything). Scene.v().forceResolve( "java.lang.reflect.UndeclaredThrowableException", SootClass.BODIES); UNDECLARED_THROWABLE_EXCEPTION = Scene.v().getRefType( "java.lang.reflect.UndeclaredThrowableException"); Scene.v().forceResolve("javax.swing.UnsupportedLookAndFeelException", SootClass.BODIES); UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION = Scene.v().getRefType( "javax.swing.UnsupportedLookAndFeelException"); boolean oldPhantoms = Options.v().allow_phantom_refs(); Options.v().set_allow_phantom_refs(true); Scene.v().forceResolve( "de.ecspride.NonExistingExceptionToTestPhantoms1", SootClass.BODIES); PHANTOM_EXCEPTION1 = Scene.v().getRefType( "de.ecspride.NonExistingExceptionToTestPhantoms1"); Scene.v().forceResolve( "de.ecspride.NonExistingExceptionToTestPhantoms2", SootClass.BODIES); PHANTOM_EXCEPTION2 = Scene.v().getRefType( "de.ecspride.NonExistingExceptionToTestPhantoms2"); Options.v().set_allow_phantom_refs(oldPhantoms); VM_ERRORS = Collections .unmodifiableSet(new ExceptionHashSet<RefLikeType>(Arrays .asList(new RefLikeType[] { THREAD_DEATH, INTERNAL_ERROR, OUT_OF_MEMORY_ERROR, STACK_OVERFLOW_ERROR, UNKNOWN_ERROR, }))); Set<RefLikeType> temp = new ExceptionHashSet<RefLikeType>(VM_ERRORS); temp.add(VIRTUAL_MACHINE_ERROR); temp.add(ERROR); temp.add(THROWABLE); VM_ERRORS_PLUS_SUPERTYPES = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_ERRORS); temp.add(CLASS_CIRCULARITY_ERROR); temp.add(ILLEGAL_ACCESS_ERROR); temp.add(INCOMPATIBLE_CLASS_CHANGE_ERROR); temp.add(LINKAGE_ERROR); temp.add(NO_CLASS_DEF_FOUND_ERROR); temp.add(VERIFY_ERROR); Set<RefLikeType> tempForRep = new ExceptionHashSet<RefLikeType>(temp); tempForRep.add(AnySubType.v(CLASS_FORMAT_ERROR)); VM_AND_RESOLVE_CLASS_ERRORS_REP = Collections .unmodifiableSet(tempForRep); temp.add(CLASS_FORMAT_ERROR); temp.add(UNSUPPORTED_CLASS_VERSION_ERROR); VM_AND_RESOLVE_CLASS_ERRORS = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_AND_RESOLVE_CLASS_ERRORS); temp.add(VIRTUAL_MACHINE_ERROR); temp.add(ERROR); temp.add(THROWABLE); VM_AND_RESOLVE_CLASS_ERRORS_PLUS_SUPERTYPES = Collections .unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>( VM_AND_RESOLVE_CLASS_ERRORS_REP); temp.add(NO_SUCH_FIELD_ERROR); VM_AND_RESOLVE_FIELD_ERRORS_REP = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_AND_RESOLVE_CLASS_ERRORS); temp.add(NO_SUCH_FIELD_ERROR); VM_AND_RESOLVE_FIELD_ERRORS = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_AND_RESOLVE_FIELD_ERRORS); temp.add(VIRTUAL_MACHINE_ERROR); temp.add(ERROR); temp.add(THROWABLE); VM_AND_RESOLVE_FIELD_ERRORS_PLUS_SUPERTYPES = Collections .unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>( VM_AND_RESOLVE_CLASS_ERRORS_REP); temp.add(ABSTRACT_METHOD_ERROR); temp.add(NO_SUCH_METHOD_ERROR); temp.add(UNSATISFIED_LINK_ERROR); VM_AND_RESOLVE_METHOD_ERRORS_REP = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_AND_RESOLVE_CLASS_ERRORS); temp.add(ABSTRACT_METHOD_ERROR); temp.add(NO_SUCH_METHOD_ERROR); temp.add(UNSATISFIED_LINK_ERROR); VM_AND_RESOLVE_METHOD_ERRORS = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_AND_RESOLVE_METHOD_ERRORS); temp.add(VIRTUAL_MACHINE_ERROR); temp.add(ERROR); temp.add(THROWABLE); VM_AND_RESOLVE_METHOD_ERRORS_PLUS_SUPERTYPES = Collections .unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>( VM_AND_RESOLVE_METHOD_ERRORS_PLUS_SUPERTYPES); temp.add(AnySubType.v(Scene.v().getRefType("java.lang.Error"))); ALL_ERRORS_REP = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_AND_RESOLVE_METHOD_ERRORS); temp.add(NO_SUCH_FIELD_ERROR); temp.add(EXCEPTION_IN_INITIALIZER_ERROR); temp.add(INSTANTIATION_ERROR); temp.add(AWT_ERROR); ALL_TEST_ERRORS = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(ALL_TEST_ERRORS); temp.add(VIRTUAL_MACHINE_ERROR); temp.add(ERROR); temp.add(THROWABLE); ALL_TEST_ERRORS_PLUS_SUPERTYPES = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_ERRORS); temp.add(ILLEGAL_MONITOR_STATE_EXCEPTION); temp.add(NULL_POINTER_EXCEPTION); PERENNIAL_THROW_EXCEPTIONS = Collections.unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(VM_ERRORS_PLUS_SUPERTYPES); temp.add(ILLEGAL_MONITOR_STATE_EXCEPTION); temp.add(NULL_POINTER_EXCEPTION); temp.add(RUNTIME_EXCEPTION); temp.add(EXCEPTION); PERENNIAL_THROW_EXCEPTIONS_PLUS_SUPERTYPES = Collections .unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>(PERENNIAL_THROW_EXCEPTIONS); temp.add(INCOMPATIBLE_CLASS_CHANGE_ERROR); THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE = Collections .unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>( PERENNIAL_THROW_EXCEPTIONS_PLUS_SUPERTYPES); temp.add(INCOMPATIBLE_CLASS_CHANGE_ERROR); temp.add(LINKAGE_ERROR); THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUPERTYPES = Collections .unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>( THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE); temp.add(ABSTRACT_METHOD_ERROR); temp.add(ILLEGAL_ACCESS_ERROR); temp.add(INSTANTIATION_ERROR); ; temp.add(NO_SUCH_FIELD_ERROR); temp.add(NO_SUCH_METHOD_ERROR); THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUBTYPES = Collections .unmodifiableSet(temp); temp = new ExceptionHashSet<RefLikeType>( THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUPERTYPES); temp.add(ABSTRACT_METHOD_ERROR); temp.add(ILLEGAL_ACCESS_ERROR); temp.add(INSTANTIATION_ERROR); ; temp.add(NO_SUCH_FIELD_ERROR); temp.add(NO_SUCH_METHOD_ERROR); THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUBTYPES_PLUS_SUPERTYPES = Collections .unmodifiableSet(temp); ExceptionHashSet<RefType> tempTest = new ExceptionHashSet<RefType>( Arrays.asList(new RefType[] { THROWABLE, EXCEPTION, RUNTIME_EXCEPTION, ARITHMETIC_EXCEPTION, ARRAY_STORE_EXCEPTION, CLASS_CAST_EXCEPTION, ILLEGAL_MONITOR_STATE_EXCEPTION, INDEX_OUT_OF_BOUNDS_EXCEPTION, ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION, STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION, NEGATIVE_ARRAY_SIZE_EXCEPTION, NULL_POINTER_EXCEPTION, ERROR, LINKAGE_ERROR, CLASS_CIRCULARITY_ERROR, CLASS_FORMAT_ERROR, UNSUPPORTED_CLASS_VERSION_ERROR, EXCEPTION_IN_INITIALIZER_ERROR, INCOMPATIBLE_CLASS_CHANGE_ERROR, ABSTRACT_METHOD_ERROR, ILLEGAL_ACCESS_ERROR, INSTANTIATION_ERROR, NO_SUCH_FIELD_ERROR, NO_SUCH_METHOD_ERROR, NO_CLASS_DEF_FOUND_ERROR, UNSATISFIED_LINK_ERROR, VERIFY_ERROR, THREAD_DEATH, VIRTUAL_MACHINE_ERROR, INTERNAL_ERROR, OUT_OF_MEMORY_ERROR, STACK_OVERFLOW_ERROR, UNKNOWN_ERROR, AWT_ERROR, UNDECLARED_THROWABLE_EXCEPTION, UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION, })); ALL_TEST_THROWABLES = Collections.unmodifiableSet(tempTest); temp = new ExceptionHashSet<RefLikeType>(); temp.add(AnySubType.v(Scene.v().getRefType("java.lang.Throwable"))); ALL_THROWABLES_REP = Collections.unmodifiableSet(temp); } /** * Verifies that the argument <code>set</code> is catchable as any of the * exceptions in <code>members</code>. * * @param set * <code>ThrowableSet</code> whose membership is being checked. * * @param members * A {@link List} of {@link RefType} objects representing * Throwable classes. * */ public boolean catchableAsAllOf(ThrowableSet set, List<RefType> members) { boolean result = true; for (RefType member : members) { result = result && set.catchableAs(member); } return result; } /** * Verifies that the argument <code>set</code> is not catchable as any of * the exceptions in <code>members</code>. * * @param set * <code>ThrowableSet</code> whose membership is being checked. * * @param members * A {@link List} of {@link RefType} objects representing * Throwable classes. * */ public boolean catchableAsNoneOf(ThrowableSet set, List<RefType> members) { boolean result = true; for (RefType member : members) { result = result && (!set.catchableAs(member)); } return result; } /** * Verifies that the argument <code>set</code> is catchable as any of the * exceptions in <code>members</code>, but not as any other of the * exceptions ALL_TEST_THROWABLES. * * @param set * <code>ThrowableSet</code> whose membership is being checked. * * @param members * A {@link List} of {@link RefType} objects representing * Throwable classes. * */ public boolean catchableOnlyAs(ThrowableSet set, List<RefType> members) { boolean result = true; for (RefType member : members) { result = result && (set.catchableAs(member)); } for (RefType e : ALL_TEST_THROWABLES) { if (!members.contains(e)) { result = result && (!set.catchableAs(e)); } } return result; } /** * Returns a Set representation of the subset of ALL_TEST_THROWABLES which * are catchable by the argument <code>ThrowableSet</code> (for use in * assertions about the catchable exceptions. * * @param thrownSet * <code>ThrowableSet</code> representing some set of possible * exceptions. */ public Set<RefType> catchableSubset(ThrowableSet thrownSet) { Set<RefType> result = new ExceptionHashSet<RefType>( ALL_TEST_THROWABLES.size()); for (RefType e : ALL_TEST_THROWABLES) { if (thrownSet.catchableAs(e)) { result.add(e); } } return result; } /** * Checks that the internal representation of the exceptions in an argument * {@link ThrowableSet} matches expectations. * * @param thrownSet * {@link ThrowableSet} whose contents are being checked. * * @param expectedIncludes * contains the collection of {@link RefType} and * {@link AnySubType} objects that are expected to be included in * <code>thrownSet</code>. * * @param expectedExcludes * contains the collection of {@link RefType} and * {@link AnySubType} objects that are expected to be excluded * from <code>thrownSet</code>. * * @return <code>true</code> if <code>thrownSet</code> and * <code>expected</code> have the same members. */ public static boolean sameMembers( Set<? extends RefLikeType> expectedIncluded, Set<AnySubType> expectedExcluded, ThrowableSet thrownSet) { if ((expectedIncluded.size() != thrownSet.typesIncluded().size()) || (expectedExcluded.size() != thrownSet.typesExcluded().size()) || (!expectedIncluded.containsAll(thrownSet.typesIncluded())) || (!expectedExcluded.containsAll(thrownSet.typesExcluded()))) { System.out.println("\nExpected included:" + expectedIncluded.toString() + "\nExpected excluded:" + expectedExcluded.toString() + "\nActual:\n" + thrownSet.toString()); return false; } else { return true; } } public static class ExceptionHashSet<T extends RefLikeType> extends HashSet<T> { // The only difference between this and a standard HashSet is that // we override the toString() method to make ExceptionHashSets // easier to compare when they appear in JUnit assertion failure // messages. /** * */ private static final long serialVersionUID = -6292805977547117980L; ExceptionHashSet() { super(); } ExceptionHashSet(Collection<T> c) { super(c); } ExceptionHashSet(int initialCapacity) { super(initialCapacity); } public String toString() { StringBuffer result = new StringBuffer(); RefLikeType[] contents = (RefLikeType[]) this.toArray(); Comparator<RefLikeType> comparator = new Comparator<RefLikeType>() { public int compare(RefLikeType o1, RefLikeType o2) { // The order doesn't matter, so long as it is consistent. return o1.toString().compareTo(o2.toString()); } }; Arrays.sort(contents, comparator); result.append("\nExceptionHashSet<"); for (int i = 0; i < contents.length; i++) { result.append("\n\t"); result.append(contents[i].toString()); result.append("<"); result.append(Integer.toHexString(contents[i].hashCode())); result.append(">"); } result.append("\n>ExceptionHashSet"); return result.toString(); } } }
20,767
33.962963
91
java
soot
soot-master/src/test/java/soot/toolkits/exceptions/MethodThrowableSetTest.java
package soot.toolkits.exceptions; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import soot.AnySubType; import soot.G; import soot.PackManager; import soot.RefLikeType; import soot.Scene; import soot.SootMethod; import soot.options.Options; public class MethodThrowableSetTest { private static String TARGET_CLASS = "soot.toolkits.exceptions.targets.MethodThrowableSetClass"; private static String EXCEPTION_CLASS = "soot.toolkits.exceptions.targets.MyException"; private static ExceptionTestUtility testUtility; @BeforeClass public static void setUp() throws IOException { // Initialize Soot G.reset(); List<String> processDir = new ArrayList<>(); File f = new File("./target/test-classes"); if (f.exists()) processDir.add(f.getCanonicalPath()); Options.v().set_process_dir(processDir); Options.v().set_src_prec(Options.src_prec_only_class); Options.v().set_allow_phantom_refs(true); Options.v().set_output_format(Options.output_format_none); Options.v().set_drop_bodies_after_load(false); Scene.v().addBasicClass(TARGET_CLASS); Scene.v().loadNecessaryClasses(); testUtility = new ExceptionTestUtility(); PackManager.v().runPacks(); } /** * Derived class to allow access to some protected members */ @Ignore private static class ThrowAnalysisForTest extends UnitThrowAnalysis { public ThrowAnalysisForTest() { super(true); } @Override public ThrowableSet mightThrow(SootMethod sm) { return super.mightThrow(sm); } } /** * Retrieves all exceptions that can potentially be thrown by the method with the given signature * * @param methodSig * The signature of the method for which to retrieve the exceptions * @return The exceptions that the method with the given signature can possibly throw */ private ThrowableSet getExceptionsForMethod(String methodSig) { SootMethod sm = Scene.v().getMethod(methodSig); ThrowAnalysisForTest ta = new ThrowAnalysisForTest(); return ta.mightThrow(sm); } @Test public void simpleExceptionTest1() { ThrowableSet ts = getExceptionsForMethod("<soot.toolkits.exceptions.targets.MethodThrowableSetClass: void foo()>"); Set<RefLikeType> expected = new HashSet<RefLikeType>(); expected.addAll(testUtility.VM_ERRORS); expected.add(testUtility.ARITHMETIC_EXCEPTION); expected.add(testUtility.NULL_POINTER_EXCEPTION); Assert.assertTrue(ExceptionTestUtility.sameMembers(expected, Collections.<AnySubType>emptySet(), ts)); } @Test public void simpleExceptionTest2() { ThrowableSet ts = getExceptionsForMethod("<soot.toolkits.exceptions.targets.MethodThrowableSetClass: void bar()>"); Set<RefLikeType> expected = new HashSet<RefLikeType>(); expected.addAll(testUtility.VM_ERRORS); expected.add(testUtility.ARITHMETIC_EXCEPTION); expected.add(testUtility.NULL_POINTER_EXCEPTION); Assert.assertTrue(ExceptionTestUtility.sameMembers(expected, Collections.<AnySubType>emptySet(), ts)); } @Test public void simpleExceptionTest3() { ThrowableSet ts = getExceptionsForMethod("<soot.toolkits.exceptions.targets.MethodThrowableSetClass: void tool()>"); Set<RefLikeType> expected = new HashSet<RefLikeType>(); expected.addAll(testUtility.VM_ERRORS); expected.add(testUtility.ARITHMETIC_EXCEPTION); expected.add(testUtility.NULL_POINTER_EXCEPTION); expected.add(testUtility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); Assert.assertTrue(ExceptionTestUtility.sameMembers(expected, Collections.<AnySubType>emptySet(), ts)); } @Test public void getAllExceptionTest1() { ThrowableSet ts = getExceptionsForMethod("<soot.toolkits.exceptions.targets.MethodThrowableSetClass: void getAllException()>"); Set<RefLikeType> expected = new HashSet<RefLikeType>(); expected.addAll(testUtility.VM_ERRORS); Assert.assertTrue(ExceptionTestUtility.sameMembers(expected, Collections.<AnySubType>emptySet(), ts)); } @Test public void getMyExceptionTest1() { ThrowableSet ts = getExceptionsForMethod("<soot.toolkits.exceptions.targets.MethodThrowableSetClass: void getMyException()>"); Set<RefLikeType> expected = new HashSet<RefLikeType>(); expected.add(AnySubType.v(testUtility.ERROR)); // for NewExpr expected.add(testUtility.ILLEGAL_MONITOR_STATE_EXCEPTION); expected.add(testUtility.NULL_POINTER_EXCEPTION); // MyException is caught, i.e., does not escape from the method Assert.assertTrue(ExceptionTestUtility.sameMembers(expected, Collections.<AnySubType>emptySet(), ts)); } @Test public void nestedTryCatchTest1() { ThrowableSet ts = getExceptionsForMethod("<soot.toolkits.exceptions.targets.MethodThrowableSetClass: void nestedTry()>"); Set<RefLikeType> expected = new HashSet<RefLikeType>(); expected.addAll(testUtility.VM_ERRORS); expected.add(testUtility.ARITHMETIC_EXCEPTION); expected.add(testUtility.NULL_POINTER_EXCEPTION); expected.add(testUtility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); Assert.assertTrue(ExceptionTestUtility.sameMembers(expected, Collections.<AnySubType>emptySet(), ts)); } @Test public void recursionTest1() { ThrowableSet ts = getExceptionsForMethod("<soot.toolkits.exceptions.targets.MethodThrowableSetClass: void recursion()>"); Set<RefLikeType> expected = new HashSet<RefLikeType>(); expected.addAll(testUtility.VM_ERRORS); Assert.assertTrue(ExceptionTestUtility.sameMembers(expected, Collections.<AnySubType>emptySet(), ts)); } @Test public void unitInCatchBlockTest1() { ThrowableSet ts = getExceptionsForMethod("<soot.toolkits.exceptions.targets.MethodThrowableSetClass: void unitInCatchBlock()>"); Set<RefLikeType> expected = new HashSet<RefLikeType>(); expected.addAll(testUtility.VM_ERRORS); expected.add(testUtility.ARITHMETIC_EXCEPTION); Assert.assertTrue(ExceptionTestUtility.sameMembers(expected, Collections.<AnySubType>emptySet(), ts)); } }
7,089
33.754902
125
java
soot
soot-master/src/test/java/soot/toolkits/exceptions/ThrowableSetTest.java
package soot.toolkits.exceptions; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Arrays; 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.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import soot.AnySubType; import soot.G; import soot.RefLikeType; import soot.RefType; import soot.Scene; import soot.toolkits.exceptions.ExceptionTestUtility.ExceptionHashSet; import junit.framework.AssertionFailedError; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ThrowableSetTest { static { G.reset(); Scene.v().loadBasicClasses(); } final static boolean DUMP_INTERNALS = false; final ThrowableSet.Manager mgr = ThrowableSet.Manager.v(); // A class for verifying that the sizeToSetsMap // follows our expectations. static class ExpectedSizeToSets { private Map<Integer, Set<SetPair>> expectedMap = new HashMap<Integer, Set<SetPair>>(); // from Integer to Set. private static class SetPair { Set<RefLikeType> included; Set<AnySubType> excluded; SetPair(Set<RefLikeType> included, Set<AnySubType> excluded) { this.included = included; this.excluded = excluded; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (! (o instanceof SetPair)) { return false; } SetPair sp = (SetPair) o; return ( this.included.equals(sp.included) && this.excluded.equals(sp.excluded)); } @Override public int hashCode() { int result = 31; result = (37 * result) + included.hashCode(); result = (37 * result) + excluded.hashCode(); return result; } @Override public String toString() { return ( super.toString() + System.getProperty("line.separator") + "+[" + included.toString() + ']' + "-[" + excluded.toString() + ']'); } } ExpectedSizeToSets() { // The empty set. this.add(Collections.<RefLikeType>emptySet(), Collections.<AnySubType>emptySet()); // All Throwables set. Set<RefLikeType> temp = new ExceptionHashSet<RefLikeType>(); temp.add(AnySubType.v(Scene.v().getRefType("java.lang.Throwable"))); this.add(temp, Collections.<AnySubType>emptySet()); // VM errors set. temp = new ExceptionHashSet<RefLikeType>(); temp.add(Scene.v().getRefType("java.lang.InternalError")); temp.add(Scene.v().getRefType("java.lang.OutOfMemoryError")); temp.add(Scene.v().getRefType("java.lang.StackOverflowError")); temp.add(Scene.v().getRefType("java.lang.UnknownError")); temp.add(Scene.v().getRefType("java.lang.ThreadDeath")); this.add(temp, Collections.<AnySubType>emptySet()); // Resolve Class errors set. Set<RefLikeType> classErrors = new ExceptionHashSet<RefLikeType>(); classErrors.add(Scene.v().getRefType("java.lang.ClassCircularityError")); classErrors.add(AnySubType.v(Scene.v().getRefType("java.lang.ClassFormatError"))); classErrors.add(Scene.v().getRefType("java.lang.IllegalAccessError")); classErrors.add(Scene.v().getRefType("java.lang.IncompatibleClassChangeError")); classErrors.add(Scene.v().getRefType("java.lang.LinkageError")); classErrors.add(Scene.v().getRefType("java.lang.NoClassDefFoundError")); classErrors.add(Scene.v().getRefType("java.lang.VerifyError")); this.add(classErrors, Collections.<AnySubType>emptySet()); // Resolve Field errors set. temp = new ExceptionHashSet<RefLikeType>(classErrors); temp.add(Scene.v().getRefType("java.lang.NoSuchFieldError")); this.add(temp, Collections.<AnySubType>emptySet()); // Resolve method errors set. temp = new ExceptionHashSet<RefLikeType>(classErrors); temp.add(Scene.v().getRefType("java.lang.AbstractMethodError")); temp.add(Scene.v().getRefType("java.lang.NoSuchMethodError")); temp.add(Scene.v().getRefType("java.lang.UnsatisfiedLinkError")); this.add(temp, Collections.<AnySubType>emptySet()); // Initialization errors set. temp = new ExceptionHashSet<RefLikeType>(); temp.add(AnySubType.v(Scene.v().getRefType("java.lang.Error"))); this.add(temp, Collections.<AnySubType>emptySet()); } void add(Set<RefLikeType> inclusions, Set<AnySubType> exclusions) { int key = inclusions.size() + exclusions.size(); Set<SetPair> values = expectedMap.get(key); if (values == null) { values = new HashSet<SetPair>(); expectedMap.put(key, values); } // Make sure we have our own copies of the sets. values.add(newSetPair(inclusions,exclusions)); } void addAndCheck(Set<RefLikeType> inclusions, Set<AnySubType> exclusions) { add(inclusions, exclusions); assertTrue(match()); } SetPair newSetPair(Collection<RefLikeType> inclusions, Collection<AnySubType> exclusions) { return new SetPair(new ExceptionHashSet<RefLikeType>(inclusions), new ExceptionHashSet<AnySubType>(exclusions)); } boolean match() { final Collection<ThrowableSet> toCompare = ThrowableSet.Manager.v().getThrowableSets(); int sum = 0; for (Collection<SetPair> expectedValues : expectedMap.values()) { sum += expectedValues.size(); } assertEquals(sum, toCompare.size()); for (ThrowableSet actual : toCompare) { Collection<RefLikeType> included = actual.typesIncluded(); Collection<AnySubType> excluded = actual.typesExcluded(); SetPair actualPair = newSetPair(included, excluded); int key = included.size() + excluded.size(); assertTrue("Undefined SetPair found", expectedMap.get(key).contains(actualPair)); } boolean result = true; if (DUMP_INTERNALS) { if (! result) System.err.println("!!!ExpectedSizeToSets.match() FAILED!!!"); System.err.println("expectedMap:"); System.err.println(expectedMap); System.err.println("actualMap:"); System.err.println(toCompare); System.err.flush(); } return result; } } private static ExpectedSizeToSets expectedSizeToSets; // A class to check that memoized results match what we expect. // Admittedly, this amounts to a reimplementation of the memoized // structures within ThrowableSet -- I'm hoping that the two // implementations will have different bugs! static class ExpectedMemoizations { Map<ThrowableSet, Map<Object, ThrowableSet>> throwableSetToMemoized = new HashMap<ThrowableSet, Map<Object, ThrowableSet>>(); void checkAdd(ThrowableSet lhs, Object rhs, ThrowableSet result) { // rhs should be either a ThrowableSet or a RefType. Map<Object, ThrowableSet> actualMemoized = lhs.getMemoizedAdds(); assertTrue(actualMemoized.get(rhs) == result); Map<Object, ThrowableSet> expectedMemoized = throwableSetToMemoized.get(lhs); if (expectedMemoized == null) { expectedMemoized = new HashMap<Object, ThrowableSet>(); throwableSetToMemoized.put(lhs, expectedMemoized); } expectedMemoized.put(rhs, result); assertEquals(expectedMemoized, actualMemoized); } } private static ExpectedMemoizations expectedMemoizations; private static ExceptionTestUtility util; @BeforeClass public static void setUp() { expectedSizeToSets = new ExpectedSizeToSets(); expectedMemoizations = new ExpectedMemoizations(); util = new ExceptionTestUtility(); } /** * Asserts that the membership in the component sets of a * ThrowableSet correspond to expectations. * * @param s The set to be checked. * * @param included the {@link Set} of RefLikeTypes * expected to be in included in <code>s</code>. * * @param excluded an {@link Set} of RefLikeTypes * expected to be excluded from <code>s</code>. * * @throws AssertionFailedError if <code>s</code> does not * contain the types in <code>included</code> except for those * in <code>excluded</code>. */ public static void assertSameMembers(ThrowableSet s, Set<? extends RefLikeType> included, Set<AnySubType> excluded) { assertTrue(ExceptionTestUtility.sameMembers(included, excluded, s)); } /** * Asserts that the membership in the component sets of a * ThrowableSet correspond to expectations. * * @param s The set to be checked. * * @param included an array containing the RefLikeTypes * expected to be in included in <code>s</code>. * * @param excluded an array containing the RefLikeTypes * expected to be excluded from <code>s</code>. * * @throws AssertionFailedError if <code>s</code> does not * contain the types in <code>included</code> except for those * in <code>excluded</code>. */ public static void assertSameMembers(ThrowableSet s, RefLikeType[] included, AnySubType[] excluded) { assertTrue(ExceptionTestUtility.sameMembers( new ExceptionHashSet<RefLikeType>(Arrays.asList(included)), new ExceptionHashSet<AnySubType>(Arrays.asList(excluded)), s)); } /** * Asserts that the membership in the component sets of a * ThrowableSet.Pair correspond to expectations. * * @param p The pair to be checked. * * @param caughtIncluded the set of {@link RefLikeType}s * expected to be in included in <code>p.getCaught()</code>. * * @param caughtExcluded the set of <code>RefLikeType</code>s * expected to be excluded from <code>p.getCaught()</code>. * * @param uncaughtIncluded the set of <code>RefLikeType</code>s * expected to be in included in <code>p.getUncaught()</code>. * * @param uncaughtExcluded the set of <code>RefLikeType</code>s * expected to be excluded from <code>p.getUncaught()</code>. * * @throws AssertionFailedError if <code>s</code> does not * contain the types in <code>included</code> except for those * in <code>excluded</code>. */ public static void assertSameMembers(ThrowableSet.Pair p, Set<? extends RefLikeType> caughtIncluded, Set<AnySubType> caughtExcluded, Set<? extends RefLikeType> uncaughtIncluded, Set<AnySubType> uncaughtExcluded) { assertSameMembers(p.getCaught(), caughtIncluded, caughtExcluded); assertSameMembers(p.getUncaught(), uncaughtIncluded, uncaughtExcluded); } /** * Asserts that the membership in the component sets of a * ThrowableSet.Pair correspond to expectations. * * @param p The pair to be checked. * * @param caughtIncluded an array containing the {@link RefLikeType}s * expected to be in included in <code>p.getCaught()</code>. * * @param caughtExcluded an array containing the <code>RefLikeType</code>s * expected to be excluded from <code>p.getCaught()</code>. * * @param uncaughtIncluded an array containing the <code>RefLikeType</code>s * expected to be in included in <code>p.getUncaught()</code>. * * @param uncaughtExcluded an array containing the <code>RefLikeType</code>s * expected to be excluded from <code>p.getUncaught()</code>. * * @throws AssertionFailedError if <code>s</code> does not * contain the types in <code>included</code> except for those * in <code>excluded</code>. */ public static void assertSameMembers(ThrowableSet.Pair p, RefLikeType[] caughtIncluded, AnySubType[] caughtExcluded, RefLikeType[] uncaughtIncluded, AnySubType[] uncaughtExcluded) { assertSameMembers(p.getCaught(), caughtIncluded, caughtExcluded); assertSameMembers(p.getUncaught(), uncaughtIncluded, uncaughtExcluded); } private ThrowableSet checkAdd(ThrowableSet lhs, Object rhs, Set<RefLikeType> expectedIncluded, Set<AnySubType> expectedExcluded, ThrowableSet actualResult) { // Utility routine used by the next three add()s. assertSameMembers(actualResult, expectedIncluded, expectedExcluded); expectedSizeToSets.addAndCheck(expectedIncluded, expectedExcluded); expectedMemoizations.checkAdd(lhs, rhs, actualResult); return actualResult; } private ThrowableSet checkAdd(ThrowableSet lhs, Object rhs, Set<RefLikeType> expectedResult, ThrowableSet actualResult) { // Utility routine used by the next three add()s. return checkAdd(lhs, rhs, expectedResult, Collections.<AnySubType>emptySet(), actualResult); } private ThrowableSet add(ThrowableSet lhs, ThrowableSet rhs, Set<RefLikeType> expectedIncluded, Set<AnySubType> expectedExcluded) { // Add rhs to lhs, checking the results. ThrowableSet actualResult = lhs.add(rhs); return checkAdd(lhs, rhs, expectedIncluded, expectedExcluded, actualResult); } private ThrowableSet add(ThrowableSet lhs, ThrowableSet rhs, Set<RefLikeType> expectedResult) { // Add rhs to lhs, checking the results. return add(lhs, rhs, expectedResult, Collections.<AnySubType>emptySet()); } private ThrowableSet add(ThrowableSet lhs, RefType rhs, Set<RefLikeType> expectedResult) { // Add rhs to lhs, checking the results. ThrowableSet actualResult = lhs.add(rhs); return checkAdd(lhs, rhs, expectedResult, actualResult); } private ThrowableSet add(ThrowableSet lhs, AnySubType rhs, Set<RefLikeType> expectedResult) { // Add rhs to lhs, checking the results. ThrowableSet actualResult = lhs.add(rhs); return checkAdd(lhs, rhs, expectedResult, actualResult); } @Test public void test_01_InitialState() { if (DUMP_INTERNALS) { System.err.println("\n\ntestInitialState()"); } assertTrue(expectedSizeToSets.match()); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_02_SingleInstance0() { if (DUMP_INTERNALS) { System.err.println("\n\ntestSingleInstance0()"); } Set<RefLikeType> expected = new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.UNDECLARED_THROWABLE_EXCEPTION, })); ThrowableSet set0 = add(mgr.EMPTY, util.UNDECLARED_THROWABLE_EXCEPTION, expected); ThrowableSet set1 = add(mgr.EMPTY, util.UNDECLARED_THROWABLE_EXCEPTION, expected); assertTrue("The same ThrowableSet object should represent two sets containing the same single class.", set0 == set1); Set<RefType> catchable = new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.UNDECLARED_THROWABLE_EXCEPTION, util.RUNTIME_EXCEPTION, util.EXCEPTION, util.THROWABLE, })); assertEquals("Should be catchable only as UndeclaredThrowableException and its superclasses", catchable, util.catchableSubset(set0)); ThrowableSet.Pair catchableAs = set0.whichCatchableAs(util.LINKAGE_ERROR); assertEquals(mgr.EMPTY, catchableAs.getCaught()); assertEquals(set0, catchableAs.getUncaught()); catchableAs = set0.whichCatchableAs(util.UNDECLARED_THROWABLE_EXCEPTION); assertEquals(catchableAs.getCaught(), set0); assertEquals(catchableAs.getUncaught(), mgr.EMPTY); catchableAs = set0.whichCatchableAs(util.RUNTIME_EXCEPTION); assertEquals(catchableAs.getCaught(), set0); assertEquals(catchableAs.getUncaught(), mgr.EMPTY); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_03_SingleInstance1() { if (DUMP_INTERNALS) { System.err.println("\n\ntestSingleInstance1()"); } Set<RefLikeType> expected0 = new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.UNDECLARED_THROWABLE_EXCEPTION, })); Set<RefLikeType> expected1 = new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION, })); Set<RefLikeType> expectedResult = new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.UNDECLARED_THROWABLE_EXCEPTION, util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION, })); ThrowableSet set0 = add(mgr.EMPTY, util.UNDECLARED_THROWABLE_EXCEPTION, expected0); ThrowableSet set0a = add(set0, util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION, expectedResult); ThrowableSet set1 = add(mgr.EMPTY, util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION, expected1); ThrowableSet set1a = add(set1, util.UNDECLARED_THROWABLE_EXCEPTION, expectedResult); assertTrue("The same ThrowableSet object should represent two sets containing the same two exceptions, even if added in different orders.", set0a == set1a); Set<RefLikeType> catchable = new ExceptionHashSet<RefLikeType>(expectedResult); catchable.add(util.RUNTIME_EXCEPTION); catchable.add(util.EXCEPTION); catchable.add(util.THROWABLE); assertEquals("Should be catchable only as UndeclaredThrowableException " + "UnsupportedLookAndFeelException and superclasses", catchable, util.catchableSubset(set0a)); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_04_AddingSubclasses() { if (DUMP_INTERNALS) { System.err.println("\n\ntestAddingSubclasses()"); } Set<RefLikeType> expected = new ExceptionHashSet<RefLikeType>(); expected.add(util.INDEX_OUT_OF_BOUNDS_EXCEPTION); ThrowableSet set0 = add(mgr.EMPTY, util.INDEX_OUT_OF_BOUNDS_EXCEPTION, expected); expected.clear(); expected.add(AnySubType.v(util.INDEX_OUT_OF_BOUNDS_EXCEPTION)); ThrowableSet set1 = add(mgr.EMPTY, AnySubType.v(util.INDEX_OUT_OF_BOUNDS_EXCEPTION), expected); assertTrue("ThrowableSet should distinguish the case where a single exception includes subclasses from that where it does not.", set0 != set1); Set<RefLikeType> catchable = new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.INDEX_OUT_OF_BOUNDS_EXCEPTION, util.RUNTIME_EXCEPTION, util.EXCEPTION, util.THROWABLE, })); assertEquals(catchable, util.catchableSubset(set0)); catchable.add(util.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); catchable.add(util.STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION); assertEquals(catchable, util.catchableSubset(set1)); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_05_AddingSets0() { if (DUMP_INTERNALS) { System.err.println("\n\ntestAddingSets0()"); } Set<RefLikeType> expected = new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.INDEX_OUT_OF_BOUNDS_EXCEPTION, })); ThrowableSet set0 = add(mgr.EMPTY, util.INDEX_OUT_OF_BOUNDS_EXCEPTION, expected); expected.clear(); expected.add(AnySubType.v(util.INDEX_OUT_OF_BOUNDS_EXCEPTION)); ThrowableSet set1 = add(mgr.EMPTY, AnySubType.v(util.INDEX_OUT_OF_BOUNDS_EXCEPTION), expected); ThrowableSet result = add(set1, set0, expected); assertTrue("{AnySubType(E)} union {E} should equal {AnySubType(E)}", result == set1); result = add(set1, set0, expected); assertTrue("{E} union {AnySubType(E)} should equal {AnySubType(E)}", result == set1); if (DUMP_INTERNALS) { System.err.println("testAddingSets0()"); printAllSets(); } } @Test public void test_06_AddingSets1() { Set<RefLikeType> expected = new ExceptionHashSet<RefLikeType>(util.VM_ERRORS); expected.add(util.UNDECLARED_THROWABLE_EXCEPTION); ThrowableSet set0 = add(mgr.VM_ERRORS, util.UNDECLARED_THROWABLE_EXCEPTION, expected); expected.add(util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION); set0 = add(set0, util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION, expected); ThrowableSet set1 = mgr.INITIALIZATION_ERRORS; expected = new ExceptionHashSet<RefLikeType>(); expected.add(AnySubType.v(util.ERROR)); assertSameMembers(set1, expected, Collections.<AnySubType>emptySet()); expected.add(util.UNDECLARED_THROWABLE_EXCEPTION); expected.add(util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION); ThrowableSet result0 = add(set0, set1, expected); ThrowableSet result1 = add(set1, set0, expected); assertTrue("Adding sets should be commutative.", result0 == result1); Set<RefLikeType> catchable = new ExceptionHashSet<RefLikeType>(util.ALL_TEST_ERRORS_PLUS_SUPERTYPES); catchable.add(util.UNDECLARED_THROWABLE_EXCEPTION); catchable.add(util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION); catchable.add(util.RUNTIME_EXCEPTION);// Superclasses of catchable.add(util.EXCEPTION); // others. catchable.add(util.ERROR); catchable.add(util.THROWABLE); assertEquals(catchable, util.catchableSubset(result0)); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_07_AddingSets2() { Set<RefLikeType> expected = new ExceptionHashSet<RefLikeType>(util.VM_ERRORS); expected.add(util.UNDECLARED_THROWABLE_EXCEPTION); ThrowableSet set0 = add(mgr.VM_ERRORS, util.UNDECLARED_THROWABLE_EXCEPTION, expected); expected.add(util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION); set0 = add(set0, util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION, expected); ThrowableSet set1 = mgr.INITIALIZATION_ERRORS; expected = new ExceptionHashSet<RefLikeType>(); expected.add(AnySubType.v(util.ERROR)); assertSameMembers(set1, expected, Collections.<AnySubType>emptySet()); expected.add(util.UNDECLARED_THROWABLE_EXCEPTION); expected.add(util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION); ThrowableSet result0 = add(set0, set1, expected); ThrowableSet result1 = add(set1, set0, expected); assertTrue("Adding sets should be commutative.", result0 == result1); Set<RefLikeType> catchable = new ExceptionHashSet<RefLikeType>(util.ALL_TEST_ERRORS_PLUS_SUPERTYPES); catchable.add(util.UNDECLARED_THROWABLE_EXCEPTION); catchable.add(util.UNSUPPORTED_LOOK_AND_FEEL_EXCEPTION); catchable.add(util.RUNTIME_EXCEPTION);// Superclasses of catchable.add(util.EXCEPTION); // others. catchable.add(util.ERROR); catchable.add(util.THROWABLE); assertEquals(catchable, util.catchableSubset(result0)); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_08_WhichCatchable0() { if (DUMP_INTERNALS) { System.err.println("\n\ntestWhichCatchable0()"); } Set<RefLikeType> expected = new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.UNDECLARED_THROWABLE_EXCEPTION, })); ThrowableSet set0 = add(mgr.EMPTY, util.UNDECLARED_THROWABLE_EXCEPTION, expected); Set<RefLikeType> catchable = new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.UNDECLARED_THROWABLE_EXCEPTION, util.RUNTIME_EXCEPTION, util.EXCEPTION, util.THROWABLE, })); ThrowableSet.Pair catchableAs = set0.whichCatchableAs(util.LINKAGE_ERROR); assertEquals(mgr.EMPTY, catchableAs.getCaught()); assertEquals(set0, catchableAs.getUncaught()); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getCaught())); assertEquals(catchable, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.UNDECLARED_THROWABLE_EXCEPTION)); catchableAs = set0.whichCatchableAs(util.UNDECLARED_THROWABLE_EXCEPTION); assertEquals(catchableAs.getCaught(), set0); assertEquals(catchableAs.getUncaught(), mgr.EMPTY); assertEquals(catchable, util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.RUNTIME_EXCEPTION)); catchableAs = set0.whichCatchableAs(util.RUNTIME_EXCEPTION); assertEquals(catchableAs.getCaught(), set0); assertEquals(catchableAs.getUncaught(), mgr.EMPTY); assertEquals(catchable, util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.EXCEPTION)); catchableAs = set0.whichCatchableAs(util.EXCEPTION); assertEquals(catchableAs.getCaught(), set0); assertEquals(catchableAs.getUncaught(), mgr.EMPTY); assertEquals(catchable, util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.THROWABLE)); catchableAs = set0.whichCatchableAs(util.THROWABLE); assertEquals(catchableAs.getCaught(), set0); assertEquals(catchableAs.getUncaught(), mgr.EMPTY); assertEquals(catchable, util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(! set0.catchableAs(util.ERROR)); catchableAs = set0.whichCatchableAs(util.ERROR); assertEquals(catchableAs.getCaught(), mgr.EMPTY); assertEquals(catchableAs.getUncaught(), set0); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getCaught())); assertEquals(catchable, util.catchableSubset(catchableAs.getUncaught())); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_09_WhichCatchable1() { if (DUMP_INTERNALS) { System.err.println("\n\ntestWhichCatchable1()"); } ThrowableSet set0 = mgr.EMPTY.add(util.LINKAGE_ERROR); Set<RefType> catcherTypes = new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.LINKAGE_ERROR, util.ERROR, util.THROWABLE, })); assertTrue(set0.catchableAs(util.ERROR)); ThrowableSet.Pair catchableAs = set0.whichCatchableAs(util.ERROR); assertEquals(set0, catchableAs.getCaught()); assertEquals(mgr.EMPTY, catchableAs.getUncaught()); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.LINKAGE_ERROR)); catchableAs = set0.whichCatchableAs(util.LINKAGE_ERROR); assertEquals(set0, catchableAs.getCaught()); assertEquals(mgr.EMPTY, catchableAs.getUncaught()); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(! set0.catchableAs(util.INCOMPATIBLE_CLASS_CHANGE_ERROR)); catchableAs = set0.whichCatchableAs(util.INCOMPATIBLE_CLASS_CHANGE_ERROR); assertEquals(mgr.EMPTY, catchableAs.getCaught()); assertEquals(set0, catchableAs.getUncaught()); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getCaught())); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getUncaught())); assertTrue(! set0.catchableAs(util.INSTANTIATION_ERROR)); catchableAs = set0.whichCatchableAs(util.INSTANTIATION_ERROR); assertEquals(mgr.EMPTY, catchableAs.getCaught()); assertEquals(set0, catchableAs.getUncaught()); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getCaught())); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getUncaught())); assertTrue(! set0.catchableAs(util.INTERNAL_ERROR)); catchableAs = set0.whichCatchableAs(util.INTERNAL_ERROR); assertEquals(mgr.EMPTY, catchableAs.getCaught()); assertEquals(set0, catchableAs.getUncaught()); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getCaught())); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getUncaught())); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_10_WhichCatchable2() { if (DUMP_INTERNALS) { System.err.println("\n\ntestWhichCatchable2()"); } ThrowableSet set0 = mgr.EMPTY.add(AnySubType.v(util.LINKAGE_ERROR)); Set<RefType> catcherTypes = new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.INCOMPATIBLE_CLASS_CHANGE_ERROR, util.ABSTRACT_METHOD_ERROR, util.ILLEGAL_ACCESS_ERROR, util.INSTANTIATION_ERROR, util.NO_SUCH_FIELD_ERROR, util.NO_SUCH_METHOD_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.LINKAGE_ERROR, util.ERROR, util.THROWABLE, })); assertTrue(set0.catchableAs(util.ERROR)); ThrowableSet.Pair catchableAs = set0.whichCatchableAs(util.ERROR); assertEquals(set0, catchableAs.getCaught()); assertEquals(mgr.EMPTY, catchableAs.getUncaught()); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.LINKAGE_ERROR)); catchableAs = set0.whichCatchableAs(util.LINKAGE_ERROR); assertEquals(set0, catchableAs.getCaught()); assertEquals(mgr.EMPTY, catchableAs.getUncaught()); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.INCOMPATIBLE_CLASS_CHANGE_ERROR)); catchableAs = set0.whichCatchableAs(util.INCOMPATIBLE_CLASS_CHANGE_ERROR); Set<AnySubType> expectedCaughtIncluded = new ExceptionHashSet<AnySubType>( Arrays.asList(new AnySubType[] {AnySubType.v(util.INCOMPATIBLE_CLASS_CHANGE_ERROR)})); Set<AnySubType> expectedCaughtExcluded = Collections.emptySet(); Set<AnySubType> expectedUncaughtIncluded = new ExceptionHashSet<AnySubType>( Arrays.asList(new AnySubType[] {AnySubType.v(util.LINKAGE_ERROR)})); Set<AnySubType> expectedUncaughtExcluded = expectedCaughtIncluded; assertSameMembers(catchableAs, expectedCaughtIncluded, expectedCaughtExcluded, expectedUncaughtIncluded, expectedUncaughtExcluded); catcherTypes = new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.INCOMPATIBLE_CLASS_CHANGE_ERROR, util.ABSTRACT_METHOD_ERROR, util.ILLEGAL_ACCESS_ERROR, util.INSTANTIATION_ERROR, util.NO_SUCH_FIELD_ERROR, util.NO_SUCH_METHOD_ERROR, util.LINKAGE_ERROR, util.ERROR, util.THROWABLE, })); Set<RefType> noncatcherTypes = new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.LINKAGE_ERROR, util.ERROR, util.THROWABLE, })); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getCaught())); assertEquals(noncatcherTypes, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.INSTANTIATION_ERROR)); catchableAs = set0.whichCatchableAs(util.INSTANTIATION_ERROR); expectedCaughtIncluded = new ExceptionHashSet<AnySubType>( Arrays.asList(new AnySubType[] {AnySubType.v(util.INSTANTIATION_ERROR)})); expectedCaughtExcluded = Collections.emptySet(); expectedUncaughtExcluded = expectedCaughtIncluded; assertSameMembers(catchableAs, expectedCaughtIncluded, expectedCaughtExcluded, expectedUncaughtIncluded, expectedUncaughtExcluded); catcherTypes = new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.INSTANTIATION_ERROR, util.INCOMPATIBLE_CLASS_CHANGE_ERROR, util.LINKAGE_ERROR, util.ERROR, util.THROWABLE, })); noncatcherTypes = new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.ABSTRACT_METHOD_ERROR, util.ILLEGAL_ACCESS_ERROR, util.NO_SUCH_FIELD_ERROR, util.NO_SUCH_METHOD_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.INCOMPATIBLE_CLASS_CHANGE_ERROR, util.LINKAGE_ERROR, util.ERROR, util.THROWABLE, })); assertEquals(catcherTypes, util.catchableSubset(catchableAs.getCaught())); assertEquals(noncatcherTypes, util.catchableSubset(catchableAs.getUncaught())); assertTrue(! set0.catchableAs(util.INTERNAL_ERROR)); catchableAs = set0.whichCatchableAs(util.INTERNAL_ERROR); assertEquals(mgr.EMPTY, catchableAs.getCaught()); assertEquals(set0, catchableAs.getUncaught()); noncatcherTypes = new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.ABSTRACT_METHOD_ERROR, util.ILLEGAL_ACCESS_ERROR, util.INCOMPATIBLE_CLASS_CHANGE_ERROR, util.NO_SUCH_FIELD_ERROR, util.NO_SUCH_METHOD_ERROR, util.INSTANTIATION_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.INCOMPATIBLE_CLASS_CHANGE_ERROR, util.LINKAGE_ERROR, util.ERROR, util.THROWABLE, })); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getCaught())); assertEquals(noncatcherTypes, util.catchableSubset(catchableAs.getUncaught())); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_11_WhichCatchable3() { if (DUMP_INTERNALS) { System.err.println("\n\ntestWhichCatchable3()"); } ThrowableSet set0 = mgr.EMPTY; set0 = set0.add(AnySubType.v(util.ERROR)); assertTrue(set0.catchableAs(util.INCOMPATIBLE_CLASS_CHANGE_ERROR)); ThrowableSet.Pair catchableAs = set0.whichCatchableAs(util.INCOMPATIBLE_CLASS_CHANGE_ERROR); Set<AnySubType> expectedCaughtIncluded = new ExceptionHashSet<AnySubType>( Arrays.asList(new AnySubType[] {AnySubType.v(util.INCOMPATIBLE_CLASS_CHANGE_ERROR)})); Set<AnySubType> expectedCaughtExcluded = Collections.emptySet(); Set<AnySubType> expectedUncaughtIncluded = new ExceptionHashSet<AnySubType>( Arrays.asList(new AnySubType[] {AnySubType.v(util.ERROR)})); Set<AnySubType> expectedUncaughtExcluded = expectedCaughtIncluded; assertTrue(ExceptionTestUtility.sameMembers(expectedCaughtIncluded, expectedCaughtExcluded, catchableAs.getCaught())); assertTrue(ExceptionTestUtility.sameMembers(expectedUncaughtIncluded, expectedUncaughtExcluded, catchableAs.getUncaught())); assertEquals(new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.THROWABLE, util.ERROR, util.LINKAGE_ERROR, util.INCOMPATIBLE_CLASS_CHANGE_ERROR, util.ABSTRACT_METHOD_ERROR, util.INSTANTIATION_ERROR, util.ILLEGAL_ACCESS_ERROR, util.NO_SUCH_FIELD_ERROR, util.NO_SUCH_METHOD_ERROR,})), util.catchableSubset(catchableAs.getCaught())); assertEquals(new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.THROWABLE, util.ERROR, util.AWT_ERROR, util.LINKAGE_ERROR, util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.THREAD_DEATH, util.VIRTUAL_MACHINE_ERROR, util.INTERNAL_ERROR, util.OUT_OF_MEMORY_ERROR, util.STACK_OVERFLOW_ERROR, util.UNKNOWN_ERROR,})), util.catchableSubset(catchableAs.getUncaught())); set0 = catchableAs.getUncaught(); assertTrue(set0.catchableAs(util.THROWABLE)); catchableAs = set0.whichCatchableAs(util.THROWABLE); assertEquals(set0, catchableAs.getCaught()); assertEquals(mgr.EMPTY, catchableAs.getUncaught()); assertEquals(new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.THROWABLE, util.ERROR, util.AWT_ERROR, util.LINKAGE_ERROR, util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.THREAD_DEATH, util.VIRTUAL_MACHINE_ERROR, util.INTERNAL_ERROR, util.OUT_OF_MEMORY_ERROR, util.STACK_OVERFLOW_ERROR, util.UNKNOWN_ERROR,})), util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.ERROR)); catchableAs = set0.whichCatchableAs(util.ERROR); assertEquals(set0, catchableAs.getCaught()); assertEquals(mgr.EMPTY, catchableAs.getUncaught()); assertEquals(new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.THROWABLE, util.ERROR, util.AWT_ERROR, util.LINKAGE_ERROR, util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.THREAD_DEATH, util.VIRTUAL_MACHINE_ERROR, util.INTERNAL_ERROR, util.OUT_OF_MEMORY_ERROR, util.STACK_OVERFLOW_ERROR, util.UNKNOWN_ERROR,})), util.catchableSubset(catchableAs.getCaught())); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getUncaught())); assertTrue(set0.catchableAs(util.LINKAGE_ERROR)); catchableAs = set0.whichCatchableAs(util.LINKAGE_ERROR); expectedCaughtIncluded = new ExceptionHashSet<AnySubType>( Arrays.asList(new AnySubType[] {AnySubType.v(util.LINKAGE_ERROR)})); expectedCaughtExcluded = new ExceptionHashSet<AnySubType>( Arrays.asList(new AnySubType[] {AnySubType.v(util.INCOMPATIBLE_CLASS_CHANGE_ERROR)})); expectedUncaughtIncluded = new ExceptionHashSet<AnySubType>( Arrays.asList(new AnySubType[] {AnySubType.v(util.ERROR)})); expectedUncaughtExcluded = expectedCaughtIncluded; assertTrue(ExceptionTestUtility.sameMembers(expectedCaughtIncluded, expectedCaughtExcluded, catchableAs.getCaught())); assertTrue(ExceptionTestUtility.sameMembers(expectedUncaughtIncluded, expectedUncaughtExcluded, catchableAs.getUncaught())); assertEquals(new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.THROWABLE, util.ERROR, util.LINKAGE_ERROR, util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR,})), util.catchableSubset(catchableAs.getCaught())); assertEquals(new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.THROWABLE, util.ERROR, util.AWT_ERROR, util.THREAD_DEATH, util.VIRTUAL_MACHINE_ERROR, util.INTERNAL_ERROR, util.OUT_OF_MEMORY_ERROR, util.STACK_OVERFLOW_ERROR, util.UNKNOWN_ERROR,})), util.catchableSubset(catchableAs.getUncaught())); assertTrue(! set0.catchableAs(util.INCOMPATIBLE_CLASS_CHANGE_ERROR)); catchableAs = set0.whichCatchableAs(util.INCOMPATIBLE_CLASS_CHANGE_ERROR); assertEquals(mgr.EMPTY, catchableAs.getCaught()); assertEquals(set0, catchableAs.getUncaught()); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getCaught())); assertEquals(new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.THROWABLE, util.ERROR, util.LINKAGE_ERROR, util.AWT_ERROR, util.THREAD_DEATH, util.VIRTUAL_MACHINE_ERROR, util.INTERNAL_ERROR, util.OUT_OF_MEMORY_ERROR, util.STACK_OVERFLOW_ERROR, util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.UNKNOWN_ERROR,})), util.catchableSubset(catchableAs.getUncaught())); catchableAs = set0.whichCatchableAs(util.ILLEGAL_ACCESS_ERROR); assertEquals(mgr.EMPTY, catchableAs.getCaught()); assertEquals(set0, catchableAs.getUncaught()); assertEquals(Collections.EMPTY_SET, util.catchableSubset(catchableAs.getCaught())); assertEquals(new ExceptionHashSet<RefType>(Arrays.asList(new RefType[] { util.THROWABLE, util.ERROR, util.LINKAGE_ERROR, util.AWT_ERROR, util.THREAD_DEATH, util.VIRTUAL_MACHINE_ERROR, util.INTERNAL_ERROR, util.OUT_OF_MEMORY_ERROR, util.STACK_OVERFLOW_ERROR, util.CLASS_CIRCULARITY_ERROR, util.CLASS_FORMAT_ERROR, util.UNSUPPORTED_CLASS_VERSION_ERROR, util.EXCEPTION_IN_INITIALIZER_ERROR, util.NO_CLASS_DEF_FOUND_ERROR, util.UNSATISFIED_LINK_ERROR, util.VERIFY_ERROR, util.UNKNOWN_ERROR,})), util.catchableSubset(catchableAs.getUncaught())); if (DUMP_INTERNALS) { printAllSets(); } } @Test public void test_12_WhichCatchable10() { if (DUMP_INTERNALS) { System.err.println("\n\ntestWhichCatchable3()"); } ThrowableSet set0 = mgr.EMPTY; set0 = set0.add(AnySubType.v(util.THROWABLE)); assertTrue(set0.catchableAs(util.ARITHMETIC_EXCEPTION)); ThrowableSet.Pair catchableAs = set0.whichCatchableAs(util.ARITHMETIC_EXCEPTION); assertSameMembers(catchableAs, new RefLikeType[] { AnySubType.v(util.ARITHMETIC_EXCEPTION), }, new AnySubType[] { }, new RefLikeType[] { AnySubType.v(util.THROWABLE), }, new AnySubType[] { AnySubType.v(util.ARITHMETIC_EXCEPTION), }); assertEquals(new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.THROWABLE, util.EXCEPTION, util.RUNTIME_EXCEPTION, util.ARITHMETIC_EXCEPTION,})), util.catchableSubset(catchableAs.getCaught())); HashSet<RefLikeType> expectedUncaught = new HashSet<RefLikeType>(util.ALL_TEST_THROWABLES); expectedUncaught.remove(util.ARITHMETIC_EXCEPTION); assertEquals(expectedUncaught, util.catchableSubset(catchableAs.getUncaught())); set0 = catchableAs.getUncaught(); assertTrue(set0.catchableAs(util.ABSTRACT_METHOD_ERROR)); catchableAs = set0.whichCatchableAs(util.ABSTRACT_METHOD_ERROR); assertSameMembers(catchableAs, new RefLikeType[] { AnySubType.v(util.ABSTRACT_METHOD_ERROR), }, new AnySubType[] { }, new RefLikeType[] { AnySubType.v(util.THROWABLE), }, new AnySubType[] { AnySubType.v(util.ARITHMETIC_EXCEPTION), AnySubType.v(util.ABSTRACT_METHOD_ERROR), }); assertEquals(new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.THROWABLE, util.ERROR, util.LINKAGE_ERROR, util.INCOMPATIBLE_CLASS_CHANGE_ERROR, util.ABSTRACT_METHOD_ERROR,})), util.catchableSubset(catchableAs.getCaught())); expectedUncaught.remove(util.ABSTRACT_METHOD_ERROR); assertEquals(expectedUncaught, util.catchableSubset(catchableAs.getUncaught())); set0 = catchableAs.getUncaught(); assertTrue(set0.catchableAs(util.RUNTIME_EXCEPTION)); catchableAs = set0.whichCatchableAs(util.RUNTIME_EXCEPTION); assertSameMembers(catchableAs, new RefLikeType[] { AnySubType.v(util.RUNTIME_EXCEPTION), }, new AnySubType[] { AnySubType.v(util.ARITHMETIC_EXCEPTION), }, new RefLikeType[] { AnySubType.v(util.THROWABLE), }, new AnySubType[] { AnySubType.v(util.RUNTIME_EXCEPTION), AnySubType.v(util.ABSTRACT_METHOD_ERROR), }); assertEquals(new ExceptionHashSet<RefLikeType>(Arrays.asList(new RefLikeType[] { util.THROWABLE, util.EXCEPTION, util.RUNTIME_EXCEPTION, util.ARRAY_STORE_EXCEPTION, util.CLASS_CAST_EXCEPTION, util.ILLEGAL_MONITOR_STATE_EXCEPTION, util.INDEX_OUT_OF_BOUNDS_EXCEPTION, util.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION, util.STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION, util.NEGATIVE_ARRAY_SIZE_EXCEPTION, util.NULL_POINTER_EXCEPTION, util.UNDECLARED_THROWABLE_EXCEPTION})), util.catchableSubset(catchableAs.getCaught())); expectedUncaught.remove(util.RUNTIME_EXCEPTION); expectedUncaught.remove(util.ARRAY_STORE_EXCEPTION); expectedUncaught.remove(util.CLASS_CAST_EXCEPTION); expectedUncaught.remove(util.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedUncaught.remove(util.INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedUncaught.remove(util.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedUncaught.remove(util.STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedUncaught.remove(util.NEGATIVE_ARRAY_SIZE_EXCEPTION); expectedUncaught.remove(util.NULL_POINTER_EXCEPTION); expectedUncaught.remove(util.UNDECLARED_THROWABLE_EXCEPTION); assertEquals(expectedUncaught, util.catchableSubset(catchableAs.getUncaught())); } @Test public void test_13_AddAfterWhichCatchableAs0() { if (DUMP_INTERNALS) { System.err.println("\n\ntestAddAfterWhichCatchable0()"); } ThrowableSet anyError = mgr.EMPTY.add(AnySubType.v(util.ERROR)); assertTrue(anyError.catchableAs(util.LINKAGE_ERROR)); ThrowableSet.Pair catchableAs = anyError.whichCatchableAs(util.LINKAGE_ERROR); assertSameMembers(catchableAs, new RefLikeType[] { AnySubType.v(util.LINKAGE_ERROR), }, new AnySubType[] { }, new RefLikeType[] { AnySubType.v(util.ERROR), }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR), }); ThrowableSet anyErrorMinusLinkage = catchableAs.getUncaught(); try { ThrowableSet anyErrorMinusLinkagePlusIncompatibleClassChange = anyErrorMinusLinkage.add(util.INCOMPATIBLE_CLASS_CHANGE_ERROR); fail("add(IncompatiableClassChangeError) after removing LinkageError should currently generate an exception"); // Following documents what we would like to be able to implement: assertSameMembers(anyErrorMinusLinkagePlusIncompatibleClassChange, new RefLikeType[] { AnySubType.v(util.ERROR), util.INCOMPATIBLE_CLASS_CHANGE_ERROR, }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR), }); } catch (ThrowableSet.AlreadyHasExclusionsException e) { // this is what should happen. } try { ThrowableSet anyErrorMinusLinkagePlusAnyIncompatibleClassChange = anyErrorMinusLinkage.add(AnySubType.v(util.INCOMPATIBLE_CLASS_CHANGE_ERROR)); fail("add(AnySubType.v(IncompatiableClassChangeError)) after removing LinkageError should currently generate an exception"); // Following documents what we would like to be able to implement: assertSameMembers(anyErrorMinusLinkagePlusAnyIncompatibleClassChange, new RefLikeType[] { AnySubType.v(util.ERROR), AnySubType.v(util.INCOMPATIBLE_CLASS_CHANGE_ERROR), }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR), }); } catch (ThrowableSet.AlreadyHasExclusionsException e) { // this is what should happen. } // Add types that should not change the set. ThrowableSet sameSet = anyErrorMinusLinkage.add(util.VIRTUAL_MACHINE_ERROR); assertTrue(sameSet == anyErrorMinusLinkage); assertSameMembers(sameSet, new RefLikeType[] { AnySubType.v(util.ERROR), }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR), }); sameSet = anyErrorMinusLinkage.add(AnySubType.v(util.VIRTUAL_MACHINE_ERROR)); assertTrue(sameSet == anyErrorMinusLinkage); assertSameMembers(sameSet, new RefLikeType[] { AnySubType.v(util.ERROR), }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR), }); ThrowableSet anyErrorMinusLinkagePlusArrayIndex = anyErrorMinusLinkage.add(util.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); assertSameMembers(anyErrorMinusLinkagePlusArrayIndex, new RefLikeType[] { AnySubType.v(util.ERROR), util.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION, }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR), }); ThrowableSet anyErrorMinusLinkagePlusAnyIndex = anyErrorMinusLinkagePlusArrayIndex.add(AnySubType.v(util.INDEX_OUT_OF_BOUNDS_EXCEPTION)); assertSameMembers(anyErrorMinusLinkagePlusAnyIndex, new RefLikeType[] { AnySubType.v(util.ERROR), AnySubType.v(util.INDEX_OUT_OF_BOUNDS_EXCEPTION), }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR), }); ThrowableSet anyErrorMinusLinkagePlusAnyRuntime = anyErrorMinusLinkagePlusAnyIndex.add(AnySubType.v(util.RUNTIME_EXCEPTION)); assertSameMembers(anyErrorMinusLinkagePlusAnyRuntime, new RefLikeType[] { AnySubType.v(util.ERROR), AnySubType.v(util.RUNTIME_EXCEPTION), }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR), }); try { ThrowableSet anyErrorMinusLinkagePlusAnyRuntimePlusError = anyErrorMinusLinkagePlusAnyRuntime.add(AnySubType.v(util.ERROR)); fail("add(AnySubType(Error)) after removing LinkageError should currently generate an exception."); // This documents what we would like to implement: assertSameMembers(anyErrorMinusLinkagePlusAnyRuntimePlusError, new RefLikeType[] { AnySubType.v(util.ERROR), AnySubType.v(util.RUNTIME_EXCEPTION), }, new AnySubType[] { }); } catch (ThrowableSet.AlreadyHasExclusionsException e) { // This is what should happen. } try { ThrowableSet anyErrorMinusLinkagePlusAnyRuntimePlusLinkageError = anyErrorMinusLinkagePlusAnyRuntime.add(AnySubType.v(util.LINKAGE_ERROR)); fail("add(AnySubType(LinkageError)) after removing LinkageError should currently generate an exception."); // This documents what we would like to implement: assertSameMembers(anyErrorMinusLinkagePlusAnyRuntimePlusLinkageError, new RefLikeType[] { AnySubType.v(util.ERROR), AnySubType.v(util.RUNTIME_EXCEPTION), }, new AnySubType[] { }); } catch (ThrowableSet.AlreadyHasExclusionsException e) { // This is what should happen. } } @Test public void test_14_WhichCatchablePhantom0() { if (DUMP_INTERNALS) { System.err.println("\n\ntestWhichCatchablePhantom0()"); } ThrowableSet anyError = mgr.EMPTY.add(AnySubType.v(util.ERROR)); assertSameMembers(anyError.whichCatchableAs(util.LINKAGE_ERROR), new RefLikeType[] { AnySubType.v(util.LINKAGE_ERROR) }, new AnySubType[] {}, new RefLikeType[] { AnySubType.v(util.ERROR) }, new AnySubType[] { AnySubType.v(util.LINKAGE_ERROR) }); assertSameMembers(anyError.whichCatchableAs(util.PHANTOM_EXCEPTION1), new RefLikeType[] {}, new AnySubType[] {}, new RefLikeType[] { AnySubType.v(util.ERROR) }, new AnySubType[] {}); assertTrue(anyError.catchableAs(util.LINKAGE_ERROR)); assertFalse(anyError.catchableAs(util.PHANTOM_EXCEPTION1)); ThrowableSet phantomOnly = mgr.EMPTY.add(util.PHANTOM_EXCEPTION1); assertSameMembers(phantomOnly.whichCatchableAs(util.LINKAGE_ERROR), new RefLikeType[] {}, new AnySubType[] {}, new RefLikeType[] { util.PHANTOM_EXCEPTION1 }, new AnySubType[] {}); assertSameMembers(phantomOnly.whichCatchableAs(util.PHANTOM_EXCEPTION2), new RefLikeType[] {}, new AnySubType[] {}, new RefLikeType[] { util.PHANTOM_EXCEPTION1 }, new AnySubType[] {}); assertSameMembers(phantomOnly.whichCatchableAs(util.PHANTOM_EXCEPTION1), new RefLikeType[] { util.PHANTOM_EXCEPTION1 }, new AnySubType[] {}, new RefLikeType[] {}, new AnySubType[] {}); assertFalse(phantomOnly.catchableAs(util.LINKAGE_ERROR)); assertTrue(phantomOnly.catchableAs(util.PHANTOM_EXCEPTION1)); assertFalse(phantomOnly.catchableAs(util.PHANTOM_EXCEPTION2)); ThrowableSet bothPhantoms = phantomOnly.add(util.PHANTOM_EXCEPTION2); assertSameMembers(bothPhantoms.whichCatchableAs(util.PHANTOM_EXCEPTION1), new RefLikeType[] { util.PHANTOM_EXCEPTION1 }, new AnySubType[] {}, new RefLikeType[] { util.PHANTOM_EXCEPTION2 }, new AnySubType[] {}); assertSameMembers(bothPhantoms.whichCatchableAs(util.PHANTOM_EXCEPTION2), new RefLikeType[] { util.PHANTOM_EXCEPTION2 }, new AnySubType[] {}, new RefLikeType[] { util.PHANTOM_EXCEPTION1 }, new AnySubType[] {}); assertFalse(bothPhantoms.catchableAs(util.LINKAGE_ERROR)); assertTrue(bothPhantoms.catchableAs(util.PHANTOM_EXCEPTION1)); assertTrue(bothPhantoms.catchableAs(util.PHANTOM_EXCEPTION2)); ThrowableSet bothPhantoms2 = phantomOnly.add(util.PHANTOM_EXCEPTION2); assertTrue(bothPhantoms == bothPhantoms2); ThrowableSet throwableOnly = mgr.EMPTY.add(util.THROWABLE); assertFalse(throwableOnly.catchableAs(util.PHANTOM_EXCEPTION1)); ThrowableSet allThrowables = mgr.EMPTY.add(AnySubType.v(util.THROWABLE)); assertTrue(allThrowables.catchableAs(util.PHANTOM_EXCEPTION1)); } @Test public void test_14_WhichCatchablePhantom1() { if (DUMP_INTERNALS) { System.err.println("\n\ntestWhichCatchablePhantom1()"); } ThrowableSet phantomOnly = mgr.EMPTY.add(AnySubType.v(util.PHANTOM_EXCEPTION1)); assertSameMembers(phantomOnly.whichCatchableAs(util.LINKAGE_ERROR), new RefLikeType[] {}, new AnySubType[] {}, new RefLikeType[] { AnySubType.v(util.PHANTOM_EXCEPTION1) }, new AnySubType[] {}); assertSameMembers(phantomOnly.whichCatchableAs(util.PHANTOM_EXCEPTION2), new RefLikeType[] {}, new AnySubType[] {}, new RefLikeType[] { AnySubType.v(util.PHANTOM_EXCEPTION1) }, new AnySubType[] {}); assertSameMembers(phantomOnly.whichCatchableAs(util.PHANTOM_EXCEPTION1), new RefLikeType[] { AnySubType.v(util.PHANTOM_EXCEPTION1) }, new AnySubType[] {}, new RefLikeType[] {}, new AnySubType[] {}); assertFalse(phantomOnly.catchableAs(util.LINKAGE_ERROR)); assertTrue(phantomOnly.catchableAs(util.PHANTOM_EXCEPTION1)); assertFalse(phantomOnly.catchableAs(util.PHANTOM_EXCEPTION2)); ThrowableSet bothPhantoms = phantomOnly.add(AnySubType.v(util.PHANTOM_EXCEPTION2)); assertSameMembers(bothPhantoms.whichCatchableAs(util.PHANTOM_EXCEPTION1), new RefLikeType[] { AnySubType.v(util.PHANTOM_EXCEPTION1) }, new AnySubType[] {}, new RefLikeType[] { AnySubType.v(util.PHANTOM_EXCEPTION2) }, new AnySubType[] {}); assertSameMembers(bothPhantoms.whichCatchableAs(util.PHANTOM_EXCEPTION2), new RefLikeType[] { AnySubType.v(util.PHANTOM_EXCEPTION2) }, new AnySubType[] {}, new RefLikeType[] { AnySubType.v(util.PHANTOM_EXCEPTION1) }, new AnySubType[] {}); assertFalse(bothPhantoms.catchableAs(util.LINKAGE_ERROR)); assertTrue(bothPhantoms.catchableAs(util.PHANTOM_EXCEPTION1)); assertTrue(bothPhantoms.catchableAs(util.PHANTOM_EXCEPTION2)); ThrowableSet bothPhantoms2 = phantomOnly.add(AnySubType.v(util.PHANTOM_EXCEPTION2)); assertTrue(bothPhantoms == bothPhantoms2); } void printAllSets() { for (ThrowableSet s : mgr.getThrowableSets()) { System.err.println(s.toString()); System.err.println("\n\tMemoized Adds:"); for (Map.Entry<Object, ThrowableSet> entry : s.getMemoizedAdds().entrySet()) { System.err.print(' '); if (entry.getKey() instanceof ThrowableSet) { System.err.print(((ThrowableSet) entry.getKey()).toBriefString()); } else { System.err.print(entry.getKey().toString()); } System.err.print('='); System.err.print(entry.getValue().toBriefString()); System.err.print('\n'); } } } /* // Suite that uses a prescribed order, rather than whatever // order reflection produces. public static Test cannedSuite() { TestSuite suite = new TestSuite(); suite.addTest(new ThrowableSetTest("testInitialState")); suite.addTest(new ThrowableSetTest("testSingleInstance0")); suite.addTest(new ThrowableSetTest("testSingleInstance1")); suite.addTest(new ThrowableSetTest("testAddingSubclasses")); suite.addTest(new ThrowableSetTest("testAddingSets0")); suite.addTest(new ThrowableSetTest("testAddingSets1")); TestSetup setup = new ThrowableSetTestSetup(suite); return setup; } public static Test reflectionSuite() { TestSuite suite = new TestSuite(ThrowableSetTest.class); TestSetup setup = new ThrowableSetTestSetup(suite); return setup; } public static Test suite() { Scene.v().loadBasicClasses(); return reflectionSuite(); } public static void main(String arg[]) { if (arg.length > 0) { jdkLocation = arg[0]; } Scene.v().loadBasicClasses(); junit.textui.TestRunner.run(reflectionSuite()); System.out.println(ThrowableSet.Manager.v().reportInstrumentation()); } */ }
56,058
34.570431
141
java
soot
soot-master/src/test/java/soot/toolkits/exceptions/UnitThrowAnalysisTest.java
package soot.toolkits.exceptions; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import soot.AnySubType; import soot.ArrayType; import soot.DoubleType; import soot.FloatType; import soot.IntType; import soot.Local; import soot.LongType; import soot.Modifier; import soot.RefLikeType; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootFieldRef; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.Value; import soot.VoidType; import soot.grimp.Grimp; import soot.jimple.ArrayRef; import soot.jimple.DivExpr; import soot.jimple.DoubleConstant; import soot.jimple.FloatConstant; import soot.jimple.IfStmt; import soot.jimple.InstanceFieldRef; import soot.jimple.IntConstant; import soot.jimple.Jimple; import soot.jimple.LongConstant; import soot.jimple.RemExpr; import soot.jimple.StaticFieldRef; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.jimple.ThrowStmt; import soot.jimple.VirtualInvokeExpr; import soot.toolkits.exceptions.ExceptionTestUtility.ExceptionHashSet; public class UnitThrowAnalysisTest { static { Scene.v().loadBasicClasses(); } class ImmaculateInvokeUnitThrowAnalysis extends UnitThrowAnalysis { // A variant of UnitThrowAnalysis which assumes that invoked // methods will never throw any exceptions, rather than that // they might throw anything Throwable. This allows us to // test that individual arguments to invocations are being // examined. protected ThrowableSet mightThrow(SootMethod m) { return ThrowableSet.Manager.v().EMPTY; } } UnitThrowAnalysis unitAnalysis; UnitThrowAnalysis immaculateAnalysis; // A collection of Grimp values and expressions used in various tests: protected StaticFieldRef floatStaticFieldRef; protected Local floatLocal; protected FloatConstant floatConstant; protected Local floatConstantLocal; protected InstanceFieldRef floatInstanceFieldRef; protected ArrayRef floatArrayRef; protected VirtualInvokeExpr floatVirtualInvoke; protected StaticInvokeExpr floatStaticInvoke; private ExceptionTestUtility utility; @Before public void setUp() { unitAnalysis = new UnitThrowAnalysis(); immaculateAnalysis = new ImmaculateInvokeUnitThrowAnalysis(); // Ensure the Exception classes we need are represented in Soot: utility = new ExceptionTestUtility(); List voidList = new ArrayList(); SootClass bogusClass = new SootClass("BogusClass"); bogusClass.addMethod(Scene.v().makeSootMethod("floatFunction", voidList, FloatType.v())); bogusClass.addMethod(Scene.v().makeSootMethod("floatFunction", Arrays.asList(new Type[] { FloatType.v(), FloatType.v(), }), FloatType.v(), Modifier.STATIC)); SootFieldRef nanFieldRef = Scene.v().makeFieldRef(Scene.v().getSootClass("java.lang.Float"), "NaN", FloatType.v(), true); floatStaticFieldRef = Grimp.v().newStaticFieldRef(nanFieldRef); floatLocal = Grimp.v().newLocal("local", FloatType.v()); floatConstant = FloatConstant.v(33.42f); floatConstantLocal = Grimp.v().newLocal("local", RefType.v("soot.jimple.FloatConstant")); SootFieldRef valueFieldRef = Scene.v().makeFieldRef(bogusClass, "value", FloatType.v(), false); floatInstanceFieldRef = Grimp.v().newInstanceFieldRef(floatConstantLocal, valueFieldRef); floatArrayRef = Grimp.v().newArrayRef(Jimple.v().newLocal("local1", FloatType.v()), IntConstant.v(0)); floatVirtualInvoke = Grimp.v().newVirtualInvokeExpr(floatConstantLocal, Scene.v().makeMethodRef(bogusClass, "floatFunction", voidList, FloatType.v(), false), voidList); floatStaticInvoke = Grimp.v().newStaticInvokeExpr( Scene.v().makeMethodRef(bogusClass, "floatFunction", Arrays.asList(new Type[] { FloatType.v(), FloatType.v(), }), FloatType.v(), true), Arrays.asList(new Value[] { floatStaticFieldRef, floatArrayRef, })); } @Test public void testJBreakpointStmt() { Stmt s = Grimp.v().newBreakpointStmt(); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGBreakpointStmt() { Stmt s = Grimp.v().newBreakpointStmt(); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Ignore("Fails") @Test public void testJInvokeStmt() { List voidList = new ArrayList(); Stmt s = Jimple.v().newInvokeStmt( Jimple.v().newVirtualInvokeExpr(Jimple.v().newLocal("local1", RefType.v("java.lang.Object")), Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.Object"), "wait", voidList, VoidType.v(), false), voidList)); ExceptionHashSet expectedRep = new ExceptionHashSet(utility.VM_AND_RESOLVE_METHOD_ERRORS_REP); expectedRep.add(utility.NULL_POINTER_EXCEPTION); ExceptionHashSet expectedCatch = new ExceptionHashSet(utility.VM_AND_RESOLVE_METHOD_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertTrue( ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, immaculateAnalysis.mightThrow(s))); assertEquals(expectedCatch, utility.catchableSubset(immaculateAnalysis.mightThrow(s))); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_THROWABLES_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.ALL_TEST_THROWABLES, utility.catchableSubset(unitAnalysis.mightThrow(s))); SootClass bogusClass = new SootClass("BogusClass"); bogusClass.addMethod(Scene.v().makeSootMethod("emptyMethod", voidList, VoidType.v(), Modifier.STATIC)); s = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr( Scene.v().makeMethodRef(bogusClass, "emptyMethod", voidList, VoidType.v(), true), voidList)); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_ERRORS_REP, Collections.EMPTY_SET, immaculateAnalysis.mightThrow(s))); assertEquals(utility.ALL_TEST_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(immaculateAnalysis.mightThrow(s))); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_THROWABLES_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.ALL_TEST_THROWABLES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Ignore("Fails") @Test public void testGInvokeStmt() { List voidList = new ArrayList(); Stmt s = Grimp.v().newInvokeStmt( Grimp.v().newVirtualInvokeExpr(Grimp.v().newLocal("local1", RefType.v("java.lang.Object")), Scene.v().makeMethodRef(Scene.v().getSootClass("java.lang.Object"), "wait", voidList, VoidType.v(), false), voidList)); ExceptionHashSet expectedRep = new ExceptionHashSet(utility.VM_AND_RESOLVE_METHOD_ERRORS_REP); expectedRep.add(utility.NULL_POINTER_EXCEPTION); ExceptionHashSet expectedCatch = new ExceptionHashSet(utility.VM_AND_RESOLVE_METHOD_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertTrue( ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, immaculateAnalysis.mightThrow(s))); assertEquals(expectedCatch, utility.catchableSubset(immaculateAnalysis.mightThrow(s))); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_THROWABLES_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.ALL_TEST_THROWABLES, utility.catchableSubset(unitAnalysis.mightThrow(s))); SootClass bogusClass = new SootClass("BogusClass"); bogusClass.addMethod(Scene.v().makeSootMethod("emptyMethod", voidList, VoidType.v(), Modifier.STATIC)); s = Jimple.v().newInvokeStmt(Jimple.v().newStaticInvokeExpr( Scene.v().makeMethodRef(bogusClass, "emptyMethod", voidList, VoidType.v(), true), voidList)); s = Grimp.v().newInvokeStmt(Grimp.v().newStaticInvokeExpr( Scene.v().makeMethodRef(bogusClass, "emptyMethod", voidList, VoidType.v(), true), voidList)); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_ERRORS_REP, Collections.EMPTY_SET, immaculateAnalysis.mightThrow(s))); assertEquals(utility.ALL_TEST_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(immaculateAnalysis.mightThrow(s))); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_THROWABLES_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.ALL_TEST_THROWABLES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJAssignStmt() { // local0 = 0 Stmt s = Jimple.v().newAssignStmt(Jimple.v().newLocal("local0", IntType.v()), IntConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); ArrayRef arrayRef = Jimple.v().newArrayRef( Jimple.v().newLocal("local1", ArrayType.v(RefType.v("java.lang.Object"), 1)), IntConstant.v(0)); Local scalarRef = Jimple.v().newLocal("local2", RefType.v("java.lang.Object")); // local2 = local1[0] s = Jimple.v().newAssignStmt(scalarRef, arrayRef); Set<RefLikeType> expectedRep = new ExceptionHashSet<RefLikeType>(utility.VM_ERRORS); expectedRep.add(utility.NULL_POINTER_EXCEPTION); expectedRep.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.<AnySubType>emptySet(), unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); // local1[0] = local2 s = Jimple.v().newAssignStmt(arrayRef, scalarRef); expectedRep.add(utility.ARRAY_STORE_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); expectedCatch.add(utility.ARRAY_STORE_EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGAssignStmt() { // local0 = 0 Stmt s = Grimp.v().newAssignStmt(Grimp.v().newLocal("local0", IntType.v()), IntConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); ArrayRef arrayRef = Grimp.v().newArrayRef( Grimp.v().newLocal("local1", ArrayType.v(RefType.v("java.lang.Object"), 1)), IntConstant.v(0)); Local scalarRef = Grimp.v().newLocal("local2", RefType.v("java.lang.Object")); // local2 = local1[0] s = Grimp.v().newAssignStmt(scalarRef, arrayRef); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.NULL_POINTER_EXCEPTION); expectedRep.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); // local1[0] = local2 s = Grimp.v().newAssignStmt(arrayRef, scalarRef); expectedRep.add(utility.ARRAY_STORE_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); expectedCatch.add(utility.ARRAY_STORE_EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJIdentityStmt() { Stmt s = Jimple.v().newIdentityStmt(Grimp.v().newLocal("local0", IntType.v()), Jimple.v().newCaughtExceptionRef()); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); s = Jimple.v().newIdentityStmt(Grimp.v().newLocal("local0", RefType.v("java.lang.NullPointerException")), Jimple.v().newThisRef(RefType.v("java.lang.NullPointerException"))); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); s = Jimple.v().newIdentityStmt(Grimp.v().newLocal("local0", RefType.v("java.lang.NullPointerException")), Jimple.v().newParameterRef(RefType.v("java.lang.NullPointerException"), 0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGIdentityStmt() { Stmt s = Grimp.v().newIdentityStmt(Grimp.v().newLocal("local0", IntType.v()), Grimp.v().newCaughtExceptionRef()); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); s = Grimp.v().newIdentityStmt(Grimp.v().newLocal("local0", RefType.v("java.lang.NullPointerException")), Grimp.v().newThisRef(RefType.v("java.lang.NullPointerException"))); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); s = Grimp.v().newIdentityStmt(Grimp.v().newLocal("local0", RefType.v("java.lang.NullPointerException")), Grimp.v().newParameterRef(RefType.v("java.lang.NullPointerException"), 0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJEnterMonitorStmt() { Stmt s = Jimple.v().newEnterMonitorStmt(StringConstant.v("test")); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedRep.add(utility.NULL_POINTER_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGEnterMonitorStmt() { Stmt s = Grimp.v().newEnterMonitorStmt(StringConstant.v("test")); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedRep.add(utility.NULL_POINTER_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJExitMonitorStmt() { Stmt s = Jimple.v().newExitMonitorStmt(StringConstant.v("test")); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedRep.add(utility.NULL_POINTER_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGExitMonitorStmt() { Stmt s = Grimp.v().newExitMonitorStmt(StringConstant.v("test")); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedRep.add(utility.NULL_POINTER_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJGotoStmt() { Stmt nop = Jimple.v().newNopStmt(); Stmt s = Jimple.v().newGotoStmt(nop); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGGotoStmt() { Stmt nop = Grimp.v().newNopStmt(); Stmt s = Grimp.v().newGotoStmt(nop); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJIfStmt() { IfStmt s = Jimple.v().newIfStmt(Jimple.v().newEqExpr(IntConstant.v(1), IntConstant.v(1)), (Unit) null); s.setTarget(s); // A very tight infinite loop. assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGIfStmt() { IfStmt s = Grimp.v().newIfStmt(Grimp.v().newEqExpr(IntConstant.v(1), IntConstant.v(1)), (Unit) null); s.setTarget(s); // A very tight infinite loop. assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJLookupSwitchStmt() { Stmt target = Jimple.v().newAssignStmt(Jimple.v().newLocal("local0", IntType.v()), IntConstant.v(0)); Stmt s = Jimple.v().newLookupSwitchStmt(IntConstant.v(1), Collections.singletonList(IntConstant.v(1)), Collections.singletonList(target), target); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGLookupSwitchStmt() { Stmt target = Grimp.v().newAssignStmt(Grimp.v().newLocal("local0", IntType.v()), IntConstant.v(0)); Stmt s = Grimp.v().newLookupSwitchStmt(IntConstant.v(1), Arrays.asList(new Value[] { IntConstant.v(1) }), Arrays.asList(new Unit[] { target }), target); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJNopStmt() { Stmt s = Jimple.v().newNopStmt(); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); } @Test public void testGNopStmt() { Stmt s = Grimp.v().newNopStmt(); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); } @Ignore("Fails") @Test public void testJReturnStmt() { Stmt s = Jimple.v().newReturnStmt(IntConstant.v(1)); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Ignore("Fails") @Test public void testGReturnStmt() { Stmt s = Grimp.v().newReturnStmt(IntConstant.v(1)); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Ignore("Fails") @Test public void testJReturnVoidStmt() { Stmt s = Jimple.v().newReturnVoidStmt(); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Ignore("Fails") @Test public void testGReturnVoidStmt() { Stmt s = Grimp.v().newReturnVoidStmt(); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.ILLEGAL_MONITOR_STATE_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJTableSwitchStmt() { Stmt target = Jimple.v().newAssignStmt(Jimple.v().newLocal("local0", IntType.v()), IntConstant.v(0)); Stmt s = Jimple.v().newTableSwitchStmt(IntConstant.v(1), 0, 1, Arrays.asList(new Unit[] { target }), target); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGTableSwitchStmt() { Stmt target = Grimp.v().newAssignStmt(Grimp.v().newLocal("local0", IntType.v()), IntConstant.v(0)); Stmt s = Grimp.v().newTableSwitchStmt(IntConstant.v(1), 0, 1, Arrays.asList(new Unit[] { target }), target); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJThrowStmt() { // First test with an argument that is included in // PERENNIAL_THROW_EXCEPTIONS. ThrowStmt s = Jimple.v() .newThrowStmt(Jimple.v().newLocal("local0", RefType.v("java.lang.NullPointerException"))); Set expectedRep = new ExceptionHashSet(utility.PERENNIAL_THROW_EXCEPTIONS); expectedRep.remove(utility.NULL_POINTER_EXCEPTION); expectedRep.add(AnySubType.v(utility.NULL_POINTER_EXCEPTION)); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.PERENNIAL_THROW_EXCEPTIONS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); // Throw a local of type IncompatibleClassChangeError. Local local = Jimple.v().newLocal("local1", utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); s.setOp(local); expectedRep = new ExceptionHashSet(utility.THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE); expectedRep.remove(utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); expectedRep.add(AnySubType.v(utility.INCOMPATIBLE_CLASS_CHANGE_ERROR)); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUBTYPES_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); // Throw a local of unknown type. local = Jimple.v().newLocal("local1", soot.UnknownType.v()); s.setOp(local); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_THROWABLES_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.ALL_TEST_THROWABLES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testGThrowStmt() { ThrowStmt s = Grimp.v().newThrowStmt(Grimp.v().newLocal("local0", RefType.v("java.util.zip.ZipException"))); Set expectedRep = new ExceptionHashSet(utility.PERENNIAL_THROW_EXCEPTIONS); expectedRep.add(AnySubType.v(Scene.v().getRefType("java.util.zip.ZipException"))); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); Set expectedCatch = new ExceptionHashSet(utility.PERENNIAL_THROW_EXCEPTIONS_PLUS_SUPERTYPES); // We don't need to add java.util.zip.ZipException, since it is not // in the universe of test Throwables. assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(s))); // Now throw a new IncompatibleClassChangeError. s = Grimp.v().newThrowStmt(Grimp.v().newNewInvokeExpr(utility.INCOMPATIBLE_CLASS_CHANGE_ERROR, Scene.v().makeMethodRef(utility.INCOMPATIBLE_CLASS_CHANGE_ERROR.getSootClass(), "void <init>", Collections.EMPTY_LIST, VoidType.v(), false), new ArrayList())); assertTrue(ExceptionTestUtility.sameMembers(utility.THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); // Throw a local of type IncompatibleClassChangeError. Local local = Grimp.v().newLocal("local1", utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); s.setOp(local); expectedRep = new ExceptionHashSet(utility.PERENNIAL_THROW_EXCEPTIONS); expectedRep.remove(utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); expectedRep.add(AnySubType.v(utility.INCOMPATIBLE_CLASS_CHANGE_ERROR)); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.THROW_PLUS_INCOMPATIBLE_CLASS_CHANGE_PLUS_SUBTYPES_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(s))); // Throw a local of unknown type. local = Jimple.v().newLocal("local1", soot.UnknownType.v()); s.setOp(local); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_THROWABLES_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(s))); assertEquals(utility.ALL_TEST_THROWABLES, utility.catchableSubset(unitAnalysis.mightThrow(s))); } @Test public void testJArrayRef() { ArrayRef arrayRef = Jimple.v().newArrayRef( Jimple.v().newLocal("local1", ArrayType.v(RefType.v("java.lang.Object"), 1)), IntConstant.v(0)); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.NULL_POINTER_EXCEPTION); expectedRep.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(arrayRef))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(arrayRef))); } @Test public void testGArrayRef() { ArrayRef arrayRef = Grimp.v().newArrayRef( Grimp.v().newLocal("local1", ArrayType.v(RefType.v("java.lang.Object"), 1)), IntConstant.v(0)); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.NULL_POINTER_EXCEPTION); expectedRep.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(arrayRef))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(arrayRef))); } @Test public void testJDivExpr() { Set vmAndArithmetic = new ExceptionHashSet(utility.VM_ERRORS); vmAndArithmetic.add(utility.ARITHMETIC_EXCEPTION); Set vmAndArithmeticAndSupertypes = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); vmAndArithmeticAndSupertypes.add(utility.ARITHMETIC_EXCEPTION); vmAndArithmeticAndSupertypes.add(utility.RUNTIME_EXCEPTION); vmAndArithmeticAndSupertypes.add(utility.EXCEPTION); Local intLocal = Jimple.v().newLocal("intLocal", IntType.v()); Local longLocal = Jimple.v().newLocal("longLocal", LongType.v()); Local floatLocal = Jimple.v().newLocal("floatLocal", FloatType.v()); Local doubleLocal = Jimple.v().newLocal("doubleLocal", DoubleType.v()); DivExpr v = Jimple.v().newDivExpr(intLocal, IntConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(intLocal, IntConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(IntConstant.v(0), IntConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(intLocal, intLocal); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(longLocal, LongConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(longLocal, LongConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(LongConstant.v(0), LongConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(longLocal, longLocal); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(floatLocal, FloatConstant.v(0.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(floatLocal, FloatConstant.v(2.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(FloatConstant.v(0), FloatConstant.v(2.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(floatLocal, floatLocal); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(doubleLocal, DoubleConstant.v(0.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(doubleLocal, DoubleConstant.v(2.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(DoubleConstant.v(0), DoubleConstant.v(2.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newDivExpr(doubleLocal, doubleLocal); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testGDivExpr() { Set vmAndArithmetic = new ExceptionHashSet(utility.VM_ERRORS); vmAndArithmetic.add(utility.ARITHMETIC_EXCEPTION); Set vmAndArithmeticAndSupertypes = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); vmAndArithmeticAndSupertypes.add(utility.ARITHMETIC_EXCEPTION); vmAndArithmeticAndSupertypes.add(utility.RUNTIME_EXCEPTION); vmAndArithmeticAndSupertypes.add(utility.EXCEPTION); Local intLocal = Grimp.v().newLocal("intLocal", IntType.v()); Local longLocal = Grimp.v().newLocal("longLocal", LongType.v()); Local floatLocal = Grimp.v().newLocal("floatLocal", FloatType.v()); Local doubleLocal = Grimp.v().newLocal("doubleLocal", DoubleType.v()); DivExpr v = Grimp.v().newDivExpr(intLocal, IntConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(intLocal, IntConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(IntConstant.v(0), IntConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(intLocal, intLocal); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(Grimp.v().newAddExpr(intLocal, intLocal), Grimp.v().newMulExpr(intLocal, intLocal)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(longLocal, LongConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(longLocal, LongConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(LongConstant.v(0), LongConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(longLocal, longLocal); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(Grimp.v().newAddExpr(longLocal, longLocal), Grimp.v().newMulExpr(longLocal, longLocal)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(floatLocal, FloatConstant.v(0.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(floatLocal, FloatConstant.v(2.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(FloatConstant.v(0), FloatConstant.v(2.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(floatLocal, floatLocal); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(doubleLocal, DoubleConstant.v(0.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(doubleLocal, DoubleConstant.v(2.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(DoubleConstant.v(0), DoubleConstant.v(2.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newDivExpr(doubleLocal, doubleLocal); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testJRemExpr() { Set vmAndArithmetic = new ExceptionHashSet(utility.VM_ERRORS); vmAndArithmetic.add(utility.ARITHMETIC_EXCEPTION); Set vmAndArithmeticAndSupertypes = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); vmAndArithmeticAndSupertypes.add(utility.ARITHMETIC_EXCEPTION); vmAndArithmeticAndSupertypes.add(utility.RUNTIME_EXCEPTION); vmAndArithmeticAndSupertypes.add(utility.EXCEPTION); Local intLocal = Jimple.v().newLocal("intLocal", IntType.v()); Local longLocal = Jimple.v().newLocal("longLocal", LongType.v()); Local floatLocal = Jimple.v().newLocal("floatLocal", FloatType.v()); Local doubleLocal = Jimple.v().newLocal("doubleLocal", DoubleType.v()); RemExpr v = Jimple.v().newRemExpr(intLocal, IntConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(intLocal, IntConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(IntConstant.v(0), IntConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(intLocal, intLocal); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(longLocal, LongConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(longLocal, LongConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(LongConstant.v(0), LongConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(longLocal, longLocal); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(floatLocal, FloatConstant.v(0.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(floatLocal, FloatConstant.v(2.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(FloatConstant.v(0), FloatConstant.v(2.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(floatLocal, floatLocal); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(doubleLocal, DoubleConstant.v(0.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(doubleLocal, DoubleConstant.v(2.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(DoubleConstant.v(0), DoubleConstant.v(2.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newRemExpr(doubleLocal, doubleLocal); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testGRemExpr() { Set vmAndArithmetic = new ExceptionHashSet(utility.VM_ERRORS); vmAndArithmetic.add(utility.ARITHMETIC_EXCEPTION); Set vmAndArithmeticAndSupertypes = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); vmAndArithmeticAndSupertypes.add(utility.ARITHMETIC_EXCEPTION); vmAndArithmeticAndSupertypes.add(utility.RUNTIME_EXCEPTION); vmAndArithmeticAndSupertypes.add(utility.EXCEPTION); Local intLocal = Grimp.v().newLocal("intLocal", IntType.v()); Local longLocal = Grimp.v().newLocal("longLocal", LongType.v()); Local floatLocal = Grimp.v().newLocal("floatLocal", FloatType.v()); Local doubleLocal = Grimp.v().newLocal("doubleLocal", DoubleType.v()); RemExpr v = Grimp.v().newRemExpr(intLocal, IntConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(intLocal, IntConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(IntConstant.v(0), IntConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(intLocal, intLocal); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(Grimp.v().newAddExpr(intLocal, intLocal), Grimp.v().newMulExpr(intLocal, intLocal)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(longLocal, LongConstant.v(0)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(longLocal, LongConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(LongConstant.v(0), LongConstant.v(2)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(longLocal, longLocal); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(Grimp.v().newAddExpr(longLocal, longLocal), Grimp.v().newMulExpr(longLocal, longLocal)); assertTrue( ExceptionTestUtility.sameMembers(vmAndArithmetic, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(vmAndArithmeticAndSupertypes, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(floatLocal, FloatConstant.v(0.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(floatLocal, FloatConstant.v(2.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(FloatConstant.v(0), FloatConstant.v(2.0f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(floatLocal, floatLocal); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(doubleLocal, DoubleConstant.v(0.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(doubleLocal, DoubleConstant.v(2.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(DoubleConstant.v(0), DoubleConstant.v(2.0)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newRemExpr(doubleLocal, doubleLocal); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testJBinOpExp() { Value v = Jimple.v().newAddExpr(IntConstant.v(456), Jimple.v().newLocal("local", IntType.v())); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newOrExpr(Jimple.v().newLocal("local", LongType.v()), LongConstant.v(33)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newLeExpr(Jimple.v().newLocal("local", FloatType.v()), FloatConstant.v(33.42f)); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Jimple.v().newEqExpr(DoubleConstant.v(-33.45e-3), Jimple.v().newLocal("local", DoubleType.v())); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Ignore("Fails") @Test public void testGBinOpExp() { Value v = Grimp.v().newAddExpr(floatStaticFieldRef, floatConstant); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_ERRORS_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.ALL_TEST_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newOrExpr(v, floatConstant); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_ERRORS_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.ALL_TEST_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); Set expectedRep = new ExceptionHashSet(utility.ALL_ERRORS_REP); expectedRep.add(utility.NULL_POINTER_EXCEPTION); Set expectedCatch = new ExceptionHashSet(utility.ALL_TEST_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); v = Grimp.v().newLeExpr(floatInstanceFieldRef, v); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(v))); v = Grimp.v().newEqExpr(v, floatVirtualInvoke); assertTrue( ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, immaculateAnalysis.mightThrow(v))); assertEquals(expectedCatch, utility.catchableSubset(immaculateAnalysis.mightThrow(v))); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_THROWABLES_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.ALL_TEST_THROWABLES, utility.catchableSubset(unitAnalysis.mightThrow(v))); expectedRep.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION); expectedCatch.add(utility.INDEX_OUT_OF_BOUNDS_EXCEPTION); v = Grimp.v().newNeExpr(v, floatStaticInvoke); assertEquals(expectedCatch, utility.catchableSubset(immaculateAnalysis.mightThrow(v))); assertEquals(expectedCatch, utility.catchableSubset(immaculateAnalysis.mightThrow(v))); assertTrue(ExceptionTestUtility.sameMembers(utility.ALL_THROWABLES_REP, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.ALL_TEST_THROWABLES, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testJCastExpr() { // First an upcast that can be statically proved safe. Value v = Jimple.v().newCastExpr(Jimple.v().newLocal("local", utility.INCOMPATIBLE_CLASS_CHANGE_ERROR), utility.LINKAGE_ERROR); Set expectedRep = new ExceptionHashSet(utility.VM_AND_RESOLVE_CLASS_ERRORS_REP); Set expectedCatch = new ExceptionHashSet(utility.VM_AND_RESOLVE_CLASS_ERRORS_PLUS_SUPERTYPES); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(v))); // Then a vacuous cast which can be statically proved safe. v = Jimple.v().newCastExpr(Jimple.v().newLocal("local", utility.LINKAGE_ERROR), utility.LINKAGE_ERROR); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(v))); // Finally a downcast which is not necessarily safe: v = Jimple.v().newCastExpr(Jimple.v().newLocal("local", utility.LINKAGE_ERROR), utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); expectedRep.add(utility.CLASS_CAST_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); expectedCatch.add(utility.CLASS_CAST_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testGCastExpr() { // First an upcast that can be statically proved safe. Value v = Grimp.v().newCastExpr(Jimple.v().newLocal("local", utility.INCOMPATIBLE_CLASS_CHANGE_ERROR), utility.LINKAGE_ERROR); Set expectedRep = new ExceptionHashSet(utility.VM_AND_RESOLVE_CLASS_ERRORS_REP); Set expectedCatch = new ExceptionHashSet(utility.VM_AND_RESOLVE_CLASS_ERRORS_PLUS_SUPERTYPES); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(v))); // Then a vacuous cast which can be statically proved safe. v = Jimple.v().newCastExpr(Jimple.v().newLocal("local", utility.LINKAGE_ERROR), utility.LINKAGE_ERROR); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(v))); // Finally a downcast which is not necessarily safe: v = Jimple.v().newCastExpr(Jimple.v().newLocal("local", utility.LINKAGE_ERROR), utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); expectedRep.add(utility.CLASS_CAST_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); expectedCatch.add(utility.CLASS_CAST_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testGInstanceFieldRef() { Local local = Grimp.v().newLocal("local", utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); Set expectedRep = new ExceptionHashSet(utility.VM_AND_RESOLVE_FIELD_ERRORS_REP); expectedRep.add(utility.NULL_POINTER_EXCEPTION); Set expectedCatch = new ExceptionHashSet(utility.VM_AND_RESOLVE_FIELD_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); Value v = Grimp.v().newInstanceFieldRef(local, Scene.v().makeFieldRef(utility.THROWABLE.getSootClass(), "detailMessage", RefType.v("java.lang.String"), false)); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testStringConstant() { Value v = StringConstant.v("test"); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(v))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(v))); } @Test public void testJLocal() { Local local = Jimple.v().newLocal("local1", utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(local))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(local))); } @Test public void testGLocal() { Local local = Grimp.v().newLocal("local1", utility.INCOMPATIBLE_CLASS_CHANGE_ERROR); assertTrue(ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(local))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(local))); } @Test public void testBAddInst() { soot.baf.AddInst i = soot.baf.Baf.v().newAddInst(IntType.v()); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(i))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(i))); } @Test public void testBAndInst() { soot.baf.AndInst i = soot.baf.Baf.v().newAndInst(IntType.v()); assertTrue( ExceptionTestUtility.sameMembers(utility.VM_ERRORS, Collections.EMPTY_SET, unitAnalysis.mightThrow(i))); assertEquals(utility.VM_ERRORS_PLUS_SUPERTYPES, utility.catchableSubset(unitAnalysis.mightThrow(i))); } @Test public void testBArrayLengthInst() { soot.baf.ArrayLengthInst i = soot.baf.Baf.v().newArrayLengthInst(); Set expectedRep = new ExceptionHashSet(utility.VM_ERRORS); expectedRep.add(utility.NULL_POINTER_EXCEPTION); assertTrue(ExceptionTestUtility.sameMembers(expectedRep, Collections.EMPTY_SET, unitAnalysis.mightThrow(i))); Set expectedCatch = new ExceptionHashSet(utility.VM_ERRORS_PLUS_SUPERTYPES); expectedCatch.add(utility.NULL_POINTER_EXCEPTION); expectedCatch.add(utility.RUNTIME_EXCEPTION); expectedCatch.add(utility.EXCEPTION); assertEquals(expectedCatch, utility.catchableSubset(unitAnalysis.mightThrow(i))); } }
63,824
49.058824
114
java
soot
soot-master/src/test/java/soot/toolkits/exceptions/targets/MethodThrowableSetClass.java
package soot.toolkits.exceptions.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class MethodThrowableSetClass { class target{ public target(){ } public int foo(int a, int b){ try{ a = 0; int c = b/a; return a + b; }catch(ArithmeticException e){ e.printStackTrace(); return 0; } } } public static target c; public void recursion(){ try{ int a = 0; int b = 1; int c = 0; recursion(); c = a/b; }catch(ArithmeticException e){ e.printStackTrace(); }catch(OutOfMemoryError e){ e.printStackTrace(); } } public void nestedTry() { try{ int array[] = new int[10]; int b = 0; int c = array[9]/b; try{ c = 3/b; }catch(ArithmeticException e){ e.printStackTrace(); } }catch(NegativeArraySizeException e){ e.printStackTrace(); } } public void unitInCatchBlock(){ try{ int a = 0; int b = 0; int c = a/b; }catch(ArithmeticException e){ int a0 = 0; int b0 = 0; int c0 = a0/b0; e.printStackTrace(); } } public void foo(){ try{ bar(); }catch(StackOverflowError e){ e.printStackTrace(); }catch(ThreadDeath e){ e.printStackTrace(); } } private void bar(){ try{ tool(); }catch(ArrayIndexOutOfBoundsException e){ e.printStackTrace(); } } public void tool(){ try{ int array[] = new int[10]; int d = 0; int c = array[0]/d; }catch(NegativeArraySizeException e){ e.printStackTrace(); } } public void getAllException(){ try{ tool(); }catch(Error e){ e.printStackTrace(); }catch(RuntimeException e){ e.printStackTrace(); } } public void getMyException() { try{ throw new MyException(); }catch(MyException e){ e.printStackTrace(); } } }
2,552
18.052239
71
java
soot
soot-master/src/test/java/soot/toolkits/exceptions/targets/MyException.java
package soot.toolkits.exceptions.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ class MyException extends Exception { /** * */ private static final long serialVersionUID = -2558104998880463435L; }
987
28.939394
71
java
soot
soot-master/src/test/java/soot/toolkits/graph/EnhancedUnitGraphTest.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2019 Shawn Meier * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import soot.G; import soot.PackManager; import soot.Scene; import soot.SootClass; import soot.Transform; import soot.Unit; import soot.UnitPatchingChain; import soot.options.Options; import soot.toolkits.graph.pdg.EnhancedUnitGraph; public class EnhancedUnitGraphTest { private static EnhancedUnitGraphTestUtility testUtility; private static String TARGET_CLASS = "soot.toolkits.graph.targets.TestException"; @BeforeClass public static void setUp() throws IOException { G.reset(); List<String> processDir = new ArrayList<>(); File f = new File("./target/test-classes"); if (f.exists()) { processDir.add(f.getCanonicalPath()); } Options.v().set_process_dir(processDir); Options.v().set_src_prec(Options.src_prec_only_class); Options.v().set_allow_phantom_refs(true); Options.v().set_output_format(Options.output_format_none); Options.v().set_drop_bodies_after_load(false); Scene.v().addBasicClass(TARGET_CLASS); Scene.v().loadNecessaryClasses(); Options.v().set_prepend_classpath(true); Scene.v().forceResolve("soot.toolkits.graph.targets.TestException", SootClass.BODIES); testUtility = new EnhancedUnitGraphTestUtility(); PackManager.v().getPack("jtp").add(new Transform("jtp.TestEnhancedGraphUtility", testUtility)); PackManager.v().runPacks(); } @Test public void exceptionIsReachable() { EnhancedUnitGraph unitGraph = testUtility.getUnitGraph(); UnitPatchingChain allUnits = unitGraph.body.getUnits(); int targetUnitsFound = 0; for (Unit u : allUnits) { if (u.toString().contains("@caughtexception")) { assert (unitGraph.unitToPreds.get(u).size() > 0); ++targetUnitsFound; } } assert (targetUnitsFound == 2); } }
2,747
29.876404
99
java
soot
soot-master/src/test/java/soot/toolkits/graph/EnhancedUnitGraphTestUtility.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2019 Shawn Meier * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.Body; import soot.BodyTransformer; import soot.toolkits.graph.pdg.EnhancedUnitGraph; public class EnhancedUnitGraphTestUtility extends BodyTransformer { private EnhancedUnitGraph unitGraph = null; protected void internalTransform(Body body, String phase, java.util.Map<String, String> options) { String methodSig = body.getMethod().getSignature(); if (methodSig.contains("soot.toolkits.graph.targets.TestException") && body.getMethod().getName().contains("main")) { unitGraph = new EnhancedUnitGraph(body); } } public EnhancedUnitGraph getUnitGraph() { return unitGraph; } }
1,454
32.068182
100
java
soot
soot-master/src/test/java/soot/toolkits/graph/GraphComparer.java
/** * This class is a piece of test infrastructure. It compares various * varieties of control flow graphs. */ package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Body; import soot.BriefUnitPrinter; import soot.CompilationDeathException; import soot.LabeledUnitPrinter; import soot.Trap; import soot.Unit; import soot.options.Options; import soot.toolkits.graph.ExceptionalUnitGraph.ExceptionDest; import soot.util.Chain; public class GraphComparer { private static final Logger logger = LoggerFactory.getLogger(GraphComparer.class); DirectedGraph g1; DirectedGraph g2; /** * Utility interface for keeping track of graph nodes which * are considered to represent equivalent nodes in * the two graphs being compared. */ interface EquivalenceRegistry { /** * @param node a node in one graph. * @return the equivalent node from the other graph. */ Object getEquiv(Object node); } EquivalenceRegistry equivalences = null; /** * {@link EquivalenceRegistry} for comparing two {@link UnitGraph}s * Since the same {@link Unit}s are stored as nodes in both graphs, * equivalence is the same as object equality. */ class EquivalentUnitRegistry implements EquivalenceRegistry { /** * @param node a graph node that represents a {@link Unit}. * @return <tt>node</tt>. */ public Object getEquiv(Object node) { return node; } } /** * {@link EquivalenceRegistry} for comparing two {@link BlockGraph}s. * Two blocks are considered equivalent if they contain exactly the same * list of {@link Unit}s, in the same order. */ static class EquivalentBlockRegistry implements EquivalenceRegistry { private Map equivalenceMap = new HashMap(); /** * Create an {@link EquivalentBlockRegistry} which records the * equivalent blocks in two graphs whose nodes are blocks. To * allow the use of graphs that are loaded from alternate * class paths, the parameters are not required to be instances of * {@link BlockGraph}. They just have to be {@link * DirectedGraph}s whose nodes are instances of some class * that has an <tt>iterator()</tt> method that iterates over * the {@link Unit}s in that block. * * @param g1 The first graph to register. * @param g2 The second graph to register. * @throws IllegalArgumentException if a given {@link Unit} appears * in more than one block of either of the graphs. */ EquivalentBlockRegistry(DirectedGraph g1, DirectedGraph g2) { Map g1UnitToBlock = blockGraphToUnitMap(g1); // We don't need this // map, but we want // to confirm that no // Unit appears in // multiple Blocks. Map g2UnitToBlock = blockGraphToUnitMap(g2); for (Iterator g1it = g1.iterator(); g1it.hasNext(); ) { Object g1Block = g1it.next(); List g1Units = getUnits(g1Block); Object g2Block = g2UnitToBlock.get(g1Units.get(0)); List g2Units = getUnits(g2Block); if (g1Units.equals(g2Units)) { equivalenceMap.put(g1Block, g2Block); equivalenceMap.put(g2Block, g1Block); } } } /** * @param node a graph node that represents a {@link Block}. * @return the node from the other graph being compared which * represents the same block, or <tt>null</tt> if there * is no such node. */ public Object getEquiv(Object node) { return equivalenceMap.get(node); } /** * Return a map from a {@link Unit} in the body represented by * a {@link BlockGraph} to the graph node representing the * block containing that {@link Unit}. * * @param g a graph whose nodes represent lists of {@link Unit}s. * The nodes must have an <tt>iterator()</tt> method which * will iterate over the {@link Unit}s represented by the * node. * @return a {@link Map} from {@link Unit}s to {@link Object}s * that are the graph nodes containing those {@link Unit}s. * @throws IllegalArgumentException should any node of <tt>g</tt> * lack an <tt>iterator()</tt> method or should * any {@link Unit} appear in * more than one node of the graph. */ private static Map blockGraphToUnitMap(DirectedGraph g) throws IllegalArgumentException { Map result = new HashMap(); for (Iterator blockIt = g.iterator(); blockIt.hasNext(); ) { Object block = blockIt.next(); List units = getUnits(block); for (Iterator unitIt = units.iterator(); unitIt.hasNext(); ) { Unit unit = (Unit) unitIt.next(); if (result.containsKey(unit)) { throw new IllegalArgumentException("blockGraphToUnitMap(): adding " + unit.toString() + " twice"); } result.put(unit, block); } } return result; } /** * Return the {@link List} of {@link Unit}s represented by an * object which has an <tt>iterator()</tt> method which * iterates over {@link Unit}s. * * @param block the object which contains a list of {@link Unit}s. * @return the list of {@link Unit}s. */ private static List getUnits(Object block) { Class blockClass = block.getClass(); Class[] emptyParams = new Class[0]; List result = new ArrayList(); try { Method iterMethod = blockClass.getMethod("iterator", emptyParams); for (Iterator it = (Iterator) iterMethod.invoke(block, new Object[0]); it.hasNext(); ) { Unit unit = (Unit) it.next(); result.add(unit); } } catch (NoSuchMethodException e) { throw new IllegalArgumentException("GraphComparer.getUnits(): node lacks iterator() method."); } catch (IllegalAccessException e) { throw new IllegalArgumentException("GraphComparer.getUnits(): inaccessible iterator() method."); } catch (java.lang.reflect.InvocationTargetException e) { throw new IllegalArgumentException("GraphComparer.getUnits(): failed iterator() invocation."); } return result; } } /** * Utility interface for checking whether two graphs of particular types * differ only in the ways we would expect from two graphs * of those types that represent the same {@link Body}. */ interface TypedGraphComparer { /** * @return true if the two graphs represented by this comparer * differ only in expected ways. */ boolean onlyExpectedDiffs(); } TypedGraphComparer subcomparer = null; /** * Return a class that implements <tt>TypedGraphComparer</tt> for * the two graphs being compared by this <tt>GraphComparer</tt>, * or <tt>null</tt>, if there is no comparer available to compare * their types. */ TypedGraphComparer TypedGraphComparerFactory() { class TypeAssignments { // Note that "Alt" graphs are loaded from an alternate // class path, so we need ugly, fragile, special-purpose // hacks to recognize them. ExceptionalUnitGraph exceptionalUnitGraph = null; boolean omitExceptingUnitEdges; ClassicCompleteUnitGraph classicCompleteUnitGraph = null; TrapUnitGraph trapUnitGraph = null; BriefBlockGraph briefBlockGraph = null; ClassicCompleteBlockGraph classicCompleteBlockGraph = null; DirectedGraph altCompleteBlockGraph = null; DirectedGraph altBriefBlockGraph = null; ArrayRefBlockGraph arrayRefBlockGraph = null; DirectedGraph altArrayRefBlockGraph = null; ZonedBlockGraph zonedBlockGraph = null; DirectedGraph altZonedBlockGraph = null; TypeAssignments(DirectedGraph g1, DirectedGraph g2) { this.add(g1); this.add(g2); } // The type-specific add() routine provides a means to // specify the value of omitExceptingUnitEdges // for ExceptionalUnitGraph. We are counting on the // callers to keep straight whether the graph was created // with a non-default value for // omitExceptingUnitEdges, since it doesn't seem // worth saving the value of the boolean used with each // ExceptionalUnitGraph constructed. void add(ExceptionalUnitGraph g, boolean omitExceptingUnitEdges) { this.exceptionalUnitGraph = g; this.omitExceptingUnitEdges = omitExceptingUnitEdges; } void add(DirectedGraph g) { if (g instanceof CompleteUnitGraph) { this.add((ExceptionalUnitGraph) g, false); } else if (g instanceof ExceptionalUnitGraph) { this.add((ExceptionalUnitGraph) g, Options.v().omit_excepting_unit_edges()); } else if (g instanceof ClassicCompleteUnitGraph) { classicCompleteUnitGraph = (ClassicCompleteUnitGraph) g; } else if (g.getClass().getName().endsWith(".CompleteUnitGraph")) { } else if (g instanceof TrapUnitGraph) { trapUnitGraph = (TrapUnitGraph) g; } else if (g.getClass().getName().endsWith(".TrapUnitGraph")) { } else if (g instanceof BriefUnitGraph) { } else if (g.getClass().getName().endsWith(".BriefUnitGraph")) { } else if (g instanceof ExceptionalBlockGraph) { } else if (g instanceof ClassicCompleteBlockGraph) { classicCompleteBlockGraph = (ClassicCompleteBlockGraph) g; } else if (g.getClass().getName().endsWith(".CompleteBlockGraph")) { altCompleteBlockGraph = g; } else if (g instanceof BriefBlockGraph) { briefBlockGraph = (BriefBlockGraph) g; } else if (g.getClass().getName().endsWith(".BriefBlockGraph")) { altBriefBlockGraph = g; } else if (g instanceof ArrayRefBlockGraph) { arrayRefBlockGraph = (ArrayRefBlockGraph) g; } else if (g.getClass().getName().endsWith(".ArrayRefBlockGraph")) { altArrayRefBlockGraph = g; } else if (g instanceof ZonedBlockGraph) { zonedBlockGraph = (ZonedBlockGraph) g; } else if (g.getClass().getName().endsWith(".ZonedBlockGraph")) { altZonedBlockGraph = g; } else { throw new IllegalStateException("GraphComparer.add(): don't know how to add(" + g.getClass().getName() + ')'); } } } TypeAssignments subtypes = new TypeAssignments(g1, g2); if (subtypes.exceptionalUnitGraph != null && subtypes.classicCompleteUnitGraph != null) { return new ExceptionalToClassicCompleteUnitGraphComparer( subtypes.exceptionalUnitGraph, subtypes.classicCompleteUnitGraph, subtypes.omitExceptingUnitEdges); } if (subtypes.exceptionalUnitGraph != null && subtypes.trapUnitGraph != null) { return new ExceptionalToTrapUnitGraphComparer(subtypes.exceptionalUnitGraph, subtypes.trapUnitGraph, subtypes.omitExceptingUnitEdges); } if (subtypes.classicCompleteBlockGraph != null && subtypes.altCompleteBlockGraph != null) { return new BlockToAltBlockGraphComparer(subtypes.classicCompleteBlockGraph, subtypes.altCompleteBlockGraph); } if (subtypes.briefBlockGraph != null && subtypes.altBriefBlockGraph != null) { return new BlockToAltBlockGraphComparer(subtypes.briefBlockGraph, subtypes.altBriefBlockGraph); } if (subtypes.arrayRefBlockGraph != null && subtypes.altArrayRefBlockGraph != null) { return new BlockToAltBlockGraphComparer(subtypes.arrayRefBlockGraph, subtypes.altArrayRefBlockGraph); } if (subtypes.zonedBlockGraph != null && subtypes.altZonedBlockGraph != null) { return new BlockToAltBlockGraphComparer(subtypes.zonedBlockGraph, subtypes.altZonedBlockGraph); } return null; } public GraphComparer(DirectedGraph g1, DirectedGraph g2) { // Since we may be comparing graphs of classes loaded // from alternate class paths, we'll use conventions in // the class names to recognize BlockGraphs. this.g1 = g1; this.g2 = g2; String g1ClassName = g1.getClass().getName(); String g2ClassName = g2.getClass().getName(); if (g1ClassName.endsWith("BlockGraph") && g2ClassName.endsWith("BlockGraph")) { equivalences = new EquivalentBlockRegistry(g1, g2); } else { equivalences = new EquivalentUnitRegistry(); } subcomparer = TypedGraphComparerFactory(); } /** * Checks that the two graphs in the GraphComparer differ only in * ways that the GraphComparer expects that they should differ, * given the types of graphs they are, assuming that the two * graphs represent the same body. */ public boolean onlyExpectedDiffs() { if (subcomparer == null) { return equal(); } else { return subcomparer.onlyExpectedDiffs(); } } /** * Checks if a graph's edge set is consistent. * * @param g the {@link DirectedGraph} whose edge set is to be * checked. * * @return <tt>true</tt> if <tt>g</tt>'s edge set is consistent * (meaning that <tt>x</tt> is recorded as a predecessor of <tt>y</tt> * if and only if <tt>y</tt> is recorded as a successor of <tt>x</tt>). */ public static boolean consistentGraph(DirectedGraph g) { for (Iterator nodeIt = g.iterator(); nodeIt.hasNext(); ) { Object node = nodeIt.next(); for (Iterator predIt = g.getPredsOf(node).iterator(); predIt.hasNext(); ) { Object pred = predIt.next(); if (! g.getSuccsOf(pred).contains(node)) { return false; } } for (Iterator succIt = g.getSuccsOf(node).iterator(); succIt.hasNext(); ) { Object succ = succIt.next(); if (! g.getPredsOf(succ).contains(node)) { return false; } } } return true; } /** * Compares this {@link GraphComparer}'s two {@link DirectedGraph}s. * * @return <tt>true</tt> if the two graphs have * the same nodes, the same lists of heads and tails, and the * same sets of edges, <tt>false</tt> otherwise. */ public boolean equal() { if ((! consistentGraph(g1)) || (! consistentGraph(g2))) { throw new CompilationDeathException( CompilationDeathException.COMPILATION_ABORTED, "Cannot compare inconsistent graphs"); } if (! equivLists(g1.getHeads(), g2.getHeads())) { return false; } if (! equivLists(g1.getTails(), g2.getTails())) { return false; } return equivPredsAndSuccs(); } /** * <p>Compares the predecessors and successors of corresponding * nodes of this {@link GraphComparer}'s two {@link * DirectedGraph}s. This is factored out for sharing by {@link * #equal()} and {@link BlockToAltBlockGraphComparer#onlyExpectedDiffs}. * * @return <tt>true</tt> if the predecessors and successors of each * node in one graph are equivalent to the predecessors and successors * of the equivalent node in the other graph. */ protected boolean equivPredsAndSuccs() { if (g1.size() != g2.size()) { return false; } // We know the two graphs have the same size, so we only need // to iterate through one's nodes to see if the two match. for (Iterator g1it = g1.iterator(); g1it.hasNext(); ) { Object g1node = g1it.next(); try { if (! equivLists(g1.getSuccsOf(g1node), g2.getSuccsOf(equivalences.getEquiv(g1node)))) { return false; } if (! equivLists(g1.getPredsOf(g1node), g2.getPredsOf(equivalences.getEquiv(g1node)))) { return false; } } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().startsWith("Invalid unit ")) { return false; } else { throw e; } } } return true; } /** * Report the differences between the two {@link DirectedGraph}s. * * @param graph1Label a string to be used to identify the first * graph (<tt>g1</tt> in the call to {@link * GraphComparer#GraphComparer()}) in the report of differences. * * @param graph2Label a string to be used to identify the second * graph (<tt>g2</tt> in the call to {@link * GraphComparer@GraphComparer()}) in the report of differences . * * @return a {@link String} summarizing the differences * between the two graphs. */ public String diff(String graph1Label, String graph2Label) { StringBuffer report = new StringBuffer(); LabeledUnitPrinter printer1 = makeUnitPrinter(g1); LabeledUnitPrinter printer2 = makeUnitPrinter(g2); diffList(report, printer1, printer2, "HEADS", g1.getHeads(), g2.getHeads()); diffList(report, printer1, printer2, "TAILS", g1.getTails(), g2.getTails()); for (Iterator g1it = g1.iterator(); g1it.hasNext(); ) { Object g1node = g1it.next(); Object g2node = equivalences.getEquiv(g1node); String g1string = nodeToString(g1node, printer1); List g1succs = g1.getSuccsOf(g1node); List g1preds = g1.getPredsOf(g1node); List g2succs = null; List g2preds = null; try { if (g2node != null) { g2preds = g2.getPredsOf(g2node); } } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().startsWith("Invalid unit ")) { // No preds entry for g1node in g2 } else { throw e; } } diffList(report, printer1, printer2, g1string + " PREDS", g1preds, g2preds); try { if (g2node != null) { g2succs = g2.getSuccsOf(g2node); } } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().startsWith("Invalid unit ")) { // No succs entry for g1node in g2 } else { throw e; } } diffList(report, printer1, printer2, g1string + " SUCCS", g1succs, g2succs); } for (Iterator g2it = g2.iterator(); g2it.hasNext(); ) { // In this loop we Only need to report the cases where // there is no g1 entry at all, cases where there is an // entry in both graphs but with differing lists of preds // or succs will have already been reported by the loop over // g1's nodes. Object g2node = g2it.next(); Object g1node = equivalences.getEquiv(g2node); String g2string = nodeToString(g2node, printer2); List g2succs = g2.getSuccsOf(g2node); List g2preds = g2.getPredsOf(g2node); try { if (g1node != null) { g1.getPredsOf(g1node); } } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().startsWith("Invalid unit ")) { diffList(report, printer1, printer2, g2string + " PREDS", null, g2preds); } else { throw e; } } try { if (g1node != null) { g1.getSuccsOf(g1node); } } catch (RuntimeException e) { if (e.getMessage() != null && e.getMessage().startsWith("Invalid unit ")) { diffList(report, printer1, printer2, g2string + " SUCCS" , null, g2succs); } else { throw e; } } } if (report.length() > 0) { String leader1 = "*** "; String leader2 = "\n--- "; String leader3 = "\n"; StringBuffer result = new StringBuffer(leader1.length() + graph1Label.length() + leader2.length() + graph2Label.length() + leader3.length() + report.length()); result.append(leader1) .append(graph1Label) .append(leader2) .append(graph2Label) .append(leader3) .append(report); return result.toString(); } else { return ""; } } /** * Class for comparing a {@link TrapUnitGraph} to an {@link * ExceptionalUnitGraph}. */ class ExceptionalToTrapUnitGraphComparer implements TypedGraphComparer { protected ExceptionalUnitGraph exceptional; protected TrapUnitGraph cOrT; // ClassicCompleteUnitGraph Or TrapUnitGraph. protected boolean omitExceptingUnitEdges; /** * Indicates whether {@link #predOfTrappedThrower()} should * return false for edges from head to tail when the only one * of head's successors which throws an exception caught by * tail is the first unit trapped by tail (this distinguishes * ClassicCompleteUnitGraph from TrapUnitGraph). */ protected boolean predOfTrappedThrowerScreensFirstTrappedUnit; ExceptionalToTrapUnitGraphComparer(ExceptionalUnitGraph exceptional, TrapUnitGraph cOrT, boolean omitExceptingUnitEdges) { this.exceptional = exceptional; this.cOrT = cOrT; this.omitExceptingUnitEdges = omitExceptingUnitEdges; this.predOfTrappedThrowerScreensFirstTrappedUnit = false; } public boolean onlyExpectedDiffs() { if (exceptional.size() != cOrT.size()) { if (Options.v().verbose()) logger.debug("ExceptionalToTrapUnitComparer.onlyExpectedDiffs(): sizes differ" + exceptional.size() + " " + cOrT.size()); return false; } if (! (exceptional.getHeads().containsAll(cOrT.getHeads()) && cOrT.getHeads().containsAll(exceptional.getHeads())) ) { if (Options.v().verbose()) logger.debug("ExceptionalToTrapUnitComparer.onlyExpectedDiffs(): heads differ"); return false; } if (! (exceptional.getTails().containsAll(cOrT.getTails()))) { return false; } for (Iterator<Unit> tailIt = exceptional.getTails().iterator(); tailIt.hasNext(); ) { Unit tail = tailIt.next(); if ((! cOrT.getTails().contains(tail)) && (! trappedReturnOrThrow(tail))) { if (Options.v().verbose()) logger.debug("ExceptionalToTrapUnitComparer.onlyExpectedDiffs(): " + tail.toString() + " is not a tail in cOrT, but not a trapped Return or Throw either"); return false; } } // Since we've already confirmed that the two graphs have // the same number of nodes, we only need to iterate through // the nodes of one of them --- if they don't have exactly the same // set of nodes, this single iteration will reveal some // node in cOrT that is not in exceptional. for (Iterator nodeIt = cOrT.iterator(); nodeIt.hasNext(); ) { Unit node = (Unit) nodeIt.next(); try { List cOrTSuccs = cOrT.getSuccsOf(node); List exceptionalSuccs = exceptional.getSuccsOf(node); for (Iterator it = cOrTSuccs.iterator(); it.hasNext(); ) { Unit cOrTSucc = (Unit) it.next(); if ((! exceptionalSuccs.contains(cOrTSucc)) && (! cannotReallyThrowTo(node, cOrTSucc))) { if (Options.v().verbose()) logger.debug("ExceptionalToTrapUnitComparer.onlyExpectedDiffs(): " + cOrTSucc.toString() + " is not exceptional successor of " + node.toString() + " even though " + node.toString() + " can throw to it"); return false; } } for (Iterator it = exceptionalSuccs.iterator(); it.hasNext(); ) { Unit exceptionalSucc = (Unit) it.next(); if ((! cOrTSuccs.contains(exceptionalSucc)) && (! predOfTrappedThrower(node, exceptionalSucc))) { if (Options.v().verbose()) logger.debug("ExceptionalToTrapUnitComparer.onlyExpectedDiffs(): " + exceptionalSucc.toString() + " is not TrapUnitGraph successor of " + node.toString() + " even though " + node.toString() + " is not a predOfTrappedThrower or predOfTrapBegin"); return false; } } List cOrTPreds = cOrT.getPredsOf(node); List exceptionalPreds = exceptional.getPredsOf(node); for (Iterator it = cOrTPreds.iterator(); it.hasNext(); ) { Unit cOrTPred = (Unit) it.next(); if ((! exceptionalPreds.contains(cOrTPred)) && (! cannotReallyThrowTo(cOrTPred, node))) { if (Options.v().verbose()) logger.debug("ExceptionalToTrapUnitComparer.onlyExpectedDiffs(): " + cOrTPred.toString() + " is not ExceptionalUnitGraph predecessor of " + node.toString() + " even though " + cOrTPred.toString() + " can throw to " + node.toString()); return false; } } for (Iterator it = exceptionalPreds.iterator(); it.hasNext(); ) { Unit exceptionalPred = (Unit) it.next(); if ((! cOrTPreds.contains(exceptionalPred)) && (! predOfTrappedThrower(exceptionalPred, node))) { if (Options.v().verbose()) logger.debug("ExceptionalToTrapUnitComparer.onlyExpectedDiffs(): " + exceptionalPred.toString() + " is not COrTUnitGraph predecessor of " + node.toString() + " even though " + exceptionalPred.toString() + " is not a predOfTrappedThrower"); return false; } } } catch (RuntimeException e) { logger.error(e.getMessage(), e); if (e.getMessage() != null && e.getMessage().startsWith("Invalid unit ")) { if (Options.v().verbose()) logger.debug("ExceptionalToTrapUnitComparer.onlyExpectedDiffs(): " + node.toString() + " is not in ExceptionalUnitGraph at all"); // node is not in exceptional graph. return false; } else { throw e; } } } return true; } /** * <p>A utility method for confirming that a node which is * considered a tail by a {@link ExceptionalUnitGraph} but not by the * corresponding {@link TrapUnitGraph} or {@link * ClassicCompleteUnitGraph} is a return instruction or throw * instruction with a {@link Trap} handler as its successor in the * {@link TrapUnitGraph} or {@link ClassicCompleteUnitGraph}.</p> * * @param node the node which is considered a tail by * <tt>exceptional</tt> but not by <tt>cOrT</tt>. * * @return <tt>true</tt> if <tt>node</tt> is a return instruction * which has a trap handler as its successor in <tt>cOrT</tt>.\ */ protected boolean trappedReturnOrThrow(Unit node) { if (! ((node instanceof soot.jimple.ReturnStmt) || (node instanceof soot.jimple.ReturnVoidStmt) || (node instanceof soot.baf.ReturnInst) || (node instanceof soot.baf.ReturnVoidInst) || (node instanceof soot.jimple.ThrowStmt) || (node instanceof soot.baf.ThrowInst))) { return false; } List succsUnaccountedFor = new ArrayList(cOrT.getSuccsOf(node)); if (succsUnaccountedFor.size() <= 0) { return false; } for (Iterator trapIt = cOrT.getBody().getTraps().iterator(); trapIt.hasNext(); ) { Trap trap = (Trap) trapIt.next(); succsUnaccountedFor.remove(trap.getHandlerUnit()); } return (succsUnaccountedFor.size() == 0); } /** * A utility method for confirming that an edge which is in a * {@link TrapUnitGraph} or {@link ClassicCompleteUnitGraph} but * not the corresponding {@link ExceptionalUnitGraph} satisfies the * criterion we would expect of such an edge: that it leads from a * unit to a handler, that the unit might be expected to trap to * the handler based solely on the range of Units trapped by the * handler, but that there is no way for the particular exception * that the handler catches to be thrown at this point. * * @param head the graph node that the edge leaves. * @param tail the graph node that the edge leads to. * @return true if <tt>head</tt> cannot really be associated with * an exception that <tt>tail</tt> catches, false otherwise. */ protected boolean cannotReallyThrowTo(Unit head, Unit tail) { List tailsTraps = returnHandlersTraps(tail); // Check if head is in one of the traps' protected // area, but either cannot throw an exception that the // trap catches, or is not included in ExceptionalUnitGraph // because it has no side-effects: Collection headsDests = exceptional.getExceptionDests(head); for (Iterator it = tailsTraps.iterator(); it.hasNext(); ) { Trap tailsTrap = (Trap) it.next(); if (amongTrappedUnits(head, tailsTrap) && ((! destCollectionIncludes(headsDests, tailsTrap)) || ((! ExceptionalUnitGraph.mightHaveSideEffects(head)) && omitExceptingUnitEdges))) { return true; } } return false; } /** * A utility method for determining if a {@link Unit} is among * those protected by a particular {@link Trap}.. * * @param unit the {@link Unit} being asked about. * * @param trap the {@link Trap} being asked about. * * @return <tt>true</tt> if <tt>unit</tt> is protected by * <tt>trap</tt>, false otherwise. */ protected boolean amongTrappedUnits(Unit unit, Trap trap) { Chain units = exceptional.getBody().getUnits(); for (Iterator it = units.iterator(trap.getBeginUnit(), units.getPredOf(trap.getEndUnit())); it.hasNext(); ) { Unit u = (Unit) it.next(); if (u == unit) { return true; } } return false; } /** * A utility method for confirming that an edge which is in a * {@link CompleteUnitGraph} but not the corresponding {@link * TrapUnitGraph} satisfies the criteria we would expect of such * an edge: that the tail of the edge is a {@link Trap} handler, * and that the head of the edge is not itself in the * <tt>Trap</tt>'s protected area, but is the predecessor of a * {@link Unit}, call it <tt>u</tt>, such that <tt>u</tt> is a * <tt>Unit</tt> in the <tt>Trap</tt>'s protected area and * <tt>u</tt> might throw an exception that the <tt>Trap</tt> * catches. * * @param head the graph node that the edge leaves. * @param tail the graph node that the edge leads to. * @return a {@link List} of {@link Trap}s such that <tt>head</tt> is * a predecessor of a {@link Unit} that might throw an exception * caught by {@link Trap}. */ protected boolean predOfTrappedThrower(Unit head, Unit tail) { // First, ensure that tail is a handler. List tailsTraps = returnHandlersTraps(tail); if (tailsTraps.size() == 0) { if (Options.v().verbose()) logger.debug("trapsReachedViaEdge(): " + tail.toString() + " is not a trap handler"); return false; } // Build a list of Units, other than head itself, which, if // they threw a caught exception, would cause // CompleteUnitGraph to add an edge from head to the tail: List possibleThrowers = new ArrayList(exceptional.getSuccsOf(head)); possibleThrowers.remove(tail); // This method wouldn't have been possibleThrowers.remove(head); // called if tail was not in // g.getSuccsOf(head). // We need to screen out Traps that catch exceptions from // head itself, since they should be in both CompleteUnitGraph // and TrapUnitGraph. List headsCatchers = new ArrayList(); for (Iterator it = exceptional.getExceptionDests(head).iterator(); it.hasNext(); ) { ExceptionDest dest = (ExceptionDest) it.next(); headsCatchers.add(dest.getTrap()); } // Now ensure that one of the possibleThrowers might throw // an exception caught by one of tail's Traps, // screening out combinations where possibleThrower is the // first trapped Unit, if screenFirstTrappedUnit is true. for (Iterator throwerIt = possibleThrowers.iterator(); throwerIt.hasNext(); ) { Unit thrower = (Unit) throwerIt.next(); Collection dests = exceptional.getExceptionDests(thrower); for (Iterator destIt = dests.iterator(); destIt.hasNext(); ) { ExceptionDest dest = (ExceptionDest) destIt.next(); Trap trap = dest.getTrap(); if (tailsTraps.contains(trap)) { if (headsCatchers.contains(trap)) { throw new RuntimeException("trapsReachedViaEdge(): somehow there is no TrapUnitGraph edge from " + head + " to " + tail + " even though the former throws an exception caught by the latter!"); } else if ((! predOfTrappedThrowerScreensFirstTrappedUnit) || (thrower != trap.getBeginUnit())) { return true; } } } } return false; } /** * Utility method that returns all the {@link Trap}s whose * handlers begin with a particular {@link Unit}. * * @param handler the handler {@link Unit} whose {@link Trap}s are * to be returned. * @return a {@link List} of {@link Trap}s with <code>handler</code> * as their handler's first {@link Unit}. The list may be empty. */ protected List returnHandlersTraps(Unit handler) { Body body = exceptional.getBody(); List result = null; for (Iterator it = body.getTraps().iterator(); it.hasNext(); ) { Trap trap = (Trap) it.next(); if (trap.getHandlerUnit() == handler) { if (result == null) { result = new ArrayList(); } result.add(trap); } } if (result == null) { result = Collections.EMPTY_LIST; } return result; } } /** * Class for comparing an {@link ExceptionalUnitGraph} to a {@link * ClassicCompleteUnitGraph} . Since {@link * ClassicCompleteUnitGraph} is a subclass of {@link * TrapUnitGraph}, this class makes only minor adjustments to its * parent. */ class ExceptionalToClassicCompleteUnitGraphComparer extends ExceptionalToTrapUnitGraphComparer { ExceptionalToClassicCompleteUnitGraphComparer(ExceptionalUnitGraph exceptional, ClassicCompleteUnitGraph trap, boolean omitExceptingUnitEdges) { super(exceptional, trap, omitExceptingUnitEdges); this.predOfTrappedThrowerScreensFirstTrappedUnit = true; } protected boolean cannotReallyThrowTo(Unit head, Unit tail) { if (Options.v().verbose()) logger.debug("ExceptionalToClassicCompleteUnitGraphComparer.cannotReallyThrowTo() called."); if (super.cannotReallyThrowTo(head, tail)) { return true; } else { // A ClassicCompleteUnitGraph will consider the predecessors // of the first trapped Unit as predecessors of the Trap's // handler. List headsSuccs = exceptional.getSuccsOf(head); List tailsTraps = returnHandlersTraps(tail); for (Iterator it = tailsTraps.iterator(); it.hasNext(); ) { Trap tailsTrap = (Trap) it.next(); Unit tailsFirstTrappedUnit = tailsTrap.getBeginUnit(); if (headsSuccs.contains(tailsFirstTrappedUnit)) { Collection succsDests = exceptional.getExceptionDests(tailsFirstTrappedUnit); if ((! destCollectionIncludes(succsDests, tailsTrap)) || (! CompleteUnitGraph.mightHaveSideEffects(tailsFirstTrappedUnit))) { return true; } } } return false; } } } /** * Class for Comparing a {@link BriefBlockGraph}, {@link * ArrayRefBlockGraph}, or {@link ZonedBlockGraph} to an {@link * AltBriefBlockGraph}, {@link AltArrayRefBlockGraph}, or {@link * AltZonedBlockGraph}, respectively. The two should differ only * in that the <tt>Alt</tt> variants have empty tail lists. */ class BlockToAltBlockGraphComparer implements TypedGraphComparer { DirectedGraph reg; // The regular BlockGraph. DirectedGraph alt; // The Alt BlockGraph. BlockToAltBlockGraphComparer(DirectedGraph reg, DirectedGraph alt) { this.reg = reg; this.alt = alt; } public boolean onlyExpectedDiffs() { if (reg.size() != alt.size()) { return false; } if (! equivLists(reg.getHeads(), alt.getHeads())) { return false; } if (alt.getTails().size() != 0) { return false; } return equivPredsAndSuccs(); } } /** * A utility method for determining if a {@link Collection} * of {@link CompleteUnitGraph#ExceptionDest} contains * one which leads to a specified {@link Trap}. * * @param dests the {@link Collection} of {@link * CompleteUnitGraph#ExceptionDest}s to search. * * @param trap the {@link Trap} to search for. * * @return <tt>true</tt> if <tt>dests</tt> contains * <tt>trap</tt> as a destination, false otherwise. */ private static boolean destCollectionIncludes(Collection dests, Trap trap) { for (Iterator destIt = dests.iterator(); destIt.hasNext(); ) { ExceptionDest dest = (ExceptionDest) destIt.next(); if (dest.getTrap() == trap) { return true; } } return false; } /** * Utility method to return the {@link Body} associated with a * {@link DirectedGraph}, if there is one. * * @param g the graph for which to return a {@link Body}. * * @return the {@link Body} represented by <tt>g</tt>, if <tt>g</tt> * is a control flow graph, or <tt>null</tt> if <tt>g</tt> is not a * control flow graph. */ private static Body getGraphsBody(DirectedGraph g) { Body result = null; if (g instanceof UnitGraph) { result = ((UnitGraph) g).getBody(); } else if (g instanceof BlockGraph) { result = ((BlockGraph) g).getBody(); } return result; } /** * Utility method that returns a {@link LabeledUnitPrinter} for printing * the {@link Unit}s in graph. * * @param g the graph for which to return a {@link LabeledUnitPrinter}. * @return A {@link LabeledUnitPrinter} for printing the {@link Unit}s in * <tt>g</tt> if <tt>g</tt> is a control flow graph. Returns * <tt>null</tt> if <tt>g</tt> is not a control flow graph. */ private static LabeledUnitPrinter makeUnitPrinter(DirectedGraph g) { Body b = getGraphsBody(g); if (b == null) { return null; } else { BriefUnitPrinter printer = new BriefUnitPrinter(b); printer.noIndent(); return printer; } } /** * Utility method to return a {@link String} representation of a * graph node. * * @param node an {@link Object} representing a node in a * {@link DirectedGraph}. * * @param printer either a {@link LabeledUnitPrinter} for printing the * {@link Unit}s in the graph represented by <tt>node</tt>'s * graph, if node is part of a control flow graph, or <tt>null</tt>, if * <tt>node</tt> is not part of a control flow graph. * * @return a {@link String} representation of <tt>node</tt>. */ private static String nodeToString(Object node, LabeledUnitPrinter printer) { String result = null; if (printer == null) { result = node.toString(); } else if (node instanceof Unit) { ((Unit) node).toString(printer); result = printer.toString(); } else if (node instanceof Block) { StringBuffer buffer = new StringBuffer(); Iterator units = ((Block) node).iterator(); while (units.hasNext()) { Unit unit = (Unit) units.next(); String targetLabel = (String) printer.labels().get(unit); if (targetLabel != null) { buffer.append(targetLabel) .append(": "); } unit.toString(printer); buffer.append(printer.toString()).append("; "); } result = buffer.toString(); } return result; } /** * A utility method for reporting the differences between two lists * of graph nodes. The lists are usually the result of calling * <tt>getHeads()</tt>, <tt>getTails()</tt>, <tt>getSuccsOf()</tt> * or <tt>getPredsOf()</tt> on each of two graphs being compared. * * @param buffer a {@link StringBuffer} to which to append the * description of differences. * * @param printer1 a {@link LabeledUnitPrinter} to be used to format * any {@link Unit}s found in <tt>list1</tt>. * * @param printer2 a {@link LabeledUnitPrinter} to be used to format * any {@link Unit}s found in <tt>list2</tt>. * * @param label a string characterizing these lists. * * @param list1 the list from the first graph, or <tt>null</tt> if * this list is missing in the first graph. * * @param list2 the list from the second graph, or <tt>null</tt> if * this list is missing in the second graph. */ private void diffList(StringBuffer buffer, LabeledUnitPrinter printer1, LabeledUnitPrinter printer2, String label, List list1, List list2) { if (! equivLists(list1, list2)) { buffer.append("*********\n"); if (list1 == null) { buffer.append("+ "); list1 = Collections.EMPTY_LIST; } else if (list2 == null) { buffer.append("- "); list2 = Collections.EMPTY_LIST; } else { buffer.append(" "); } buffer.append(label) .append(":\n"); for (Iterator it = list1.iterator(); it.hasNext(); ) { Object list1Node = it.next(); Object list2Node = equivalences.getEquiv(list1Node); if (list2.contains(list2Node)) { buffer.append(" "); } else { buffer.append("- "); } buffer.append(nodeToString(list1Node, printer1)).append("\n"); } for (Iterator it = list2.iterator(); it.hasNext(); ) { Object list2Node = it.next(); Object list1Node = equivalences.getEquiv(list2Node); if (! list1.contains(list1Node)) { buffer.append("+ ") .append(nodeToString(list2Node,printer2)) .append("\n"); } } buffer.append("---------\n"); } } /** * Utility method that determines if two lists of nodes are equivalent. * * @param list1 The first list of nodes. * @param list2 The second list of nodes. * @return <tt>true</tt> if the equivalent of each node in <tt>list1</tt> * is found in <tt>list2</tt>, and vice versa. */ private boolean equivLists(List list1, List list2) { if (list1 == null) { return (list2 == null); } else if (list2 == null) { return false; } if (list1.size() != list2.size()) { return false; } for (Iterator i = list1.iterator(); i.hasNext(); ) { if (! list2.contains(equivalences.getEquiv(i.next()))) { return false; } } // Since getEquiv() should be symmetric, and we've confirmed that // the lists are the same size, the next loop shouldn't really // be necessary. But just in case something is fouled up, we // include this loop as an assertion check. for (Iterator i = list2.iterator(); i.hasNext(); ) { if (! list1.contains(equivalences.getEquiv(i.next()))) { throw new IllegalArgumentException("equivLists: " + list2.toString() + " contains all the equivalents of " + list1.toString() + ", but the reverse is not true."); } } return true; } }
42,282
33.601473
249
java
soot
soot-master/src/test/java/soot/toolkits/graph/PseudoTopologicalOrdererTest.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class PseudoTopologicalOrdererTest extends PseudoTopologicalOrdererTestBase { public PseudoTopologicalOrdererTest() { super(new PseudoTopologicalOrderer<Node>()); } }
1,031
32.290323
84
java
soot
soot-master/src/test/java/soot/toolkits/graph/PseudoTopologicalOrdererTestBase.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; public class PseudoTopologicalOrdererTestBase { // Use a single global instance to ensure the implementation is safe for reuse private final Orderer<Node> orderer; public PseudoTopologicalOrdererTestBase(Orderer<Node> orderer) { this.orderer = orderer; } @Test public void testOrder1() { // linear graph of 10 nodes Node n0 = new Node(0); Node n1 = new Node(1); n0.addkid(n1); Node n2 = new Node(2); n1.addkid(n2); Node n3 = new Node(3); n2.addkid(n3); Node n4 = new Node(4); n3.addkid(n4); Node n5 = new Node(5); n4.addkid(n5); Node n6 = new Node(6); n5.addkid(n6); Node n7 = new Node(7); n6.addkid(n7); Node n8 = new Node(8); n7.addkid(n8); Node n9 = new Node(9); n8.addkid(n9); Graph g = new Graph(n0); { Assert.assertEquals(10, g.size()); } { List<Node> order = orderer.newList(g, false); Assert.assertEquals(10, order.size()); Assert.assertEquals(Arrays.asList(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9), order); } { List<Node> order = orderer.newList(g, true); Assert.assertEquals(10, order.size()); Assert.assertEquals(Arrays.asList(n9, n8, n7, n6, n5, n4, n3, n2, n1, n0), order); } // System.out.println("Completed testOrder1()"); } @Test public void testOrder2() { // simple binary tree Node n0 = new Node(0); Node n1 = new Node(1); Node n2 = new Node(2); n0.addkid(n1); n0.addkid(n2); Graph g = new Graph(n0); { Assert.assertEquals(3, g.size()); } { List<Node> order = orderer.newList(g, false); Assert.assertEquals(3, order.size()); Assert.assertTrue(order.containsAll(Arrays.asList(n0, n1, n2))); Assert.assertEquals(n0, order.get(0)); // NOTE: the other 2 could be in either order since they are siblings } { List<Node> order = orderer.newList(g, true); Assert.assertEquals(3, order.size()); Assert.assertTrue(order.containsAll(Arrays.asList(n0, n1, n2))); Assert.assertEquals(n0, order.get(order.size() - 1)); // NOTE: the other 2 could be in either order since they are siblings } // System.out.println("Completed testOrder2()"); } @Test public void testOrder3() { // larger binary tree Node n0 = new Node(0); Node n1 = new Node(1); Node n2 = new Node(2); n0.addkid(n1); n0.addkid(n2); Node n3 = new Node(3); Node n4 = new Node(4); Node n5 = new Node(5); Node n6 = new Node(6); n1.addkid(n3); n1.addkid(n4); n2.addkid(n5); n2.addkid(n6); Node n7 = new Node(7); Node n8 = new Node(8); Node n9 = new Node(9); Node n10 = new Node(10); Node n11 = new Node(11); Node n12 = new Node(12); Node n13 = new Node(13); Node n14 = new Node(14); n3.addkid(n7); n3.addkid(n8); n4.addkid(n9); n4.addkid(n10); n5.addkid(n11); n5.addkid(n12); n6.addkid(n13); n6.addkid(n14); Graph g = new Graph(n0); { Assert.assertEquals(15, g.size()); } { List<Node> order = orderer.newList(g, false); Assert.assertEquals(15, order.size()); Assert.assertTrue(order.containsAll(Arrays.asList(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14))); // Check for topological sort property: edge (i,j) implies i is before j in the order // - n0 comes before all others Assert.assertEquals(n0, order.get(0)); // - n1 comes before the entire left hand sub-tree Assert.assertTrue(order.indexOf(n1) < order.indexOf(n3)); Assert.assertTrue(order.indexOf(n1) < order.indexOf(n4)); Assert.assertTrue(order.indexOf(n1) < order.indexOf(n7)); Assert.assertTrue(order.indexOf(n1) < order.indexOf(n8)); Assert.assertTrue(order.indexOf(n1) < order.indexOf(n9)); Assert.assertTrue(order.indexOf(n1) < order.indexOf(n10)); // - n2 comes before the entire right hand sub-tree Assert.assertTrue(order.indexOf(n2) < order.indexOf(n5)); Assert.assertTrue(order.indexOf(n2) < order.indexOf(n6)); Assert.assertTrue(order.indexOf(n2) < order.indexOf(n11)); Assert.assertTrue(order.indexOf(n2) < order.indexOf(n12)); Assert.assertTrue(order.indexOf(n2) < order.indexOf(n13)); Assert.assertTrue(order.indexOf(n2) < order.indexOf(n14)); // - n3 comes before n7 and n8 Assert.assertTrue(order.indexOf(n3) < order.indexOf(n7)); Assert.assertTrue(order.indexOf(n3) < order.indexOf(n8)); // - n4 comes before n9 and n10 Assert.assertTrue(order.indexOf(n4) < order.indexOf(n9)); Assert.assertTrue(order.indexOf(n4) < order.indexOf(n10)); // - n5 comes before n11 and n12 Assert.assertTrue(order.indexOf(n5) < order.indexOf(n11)); Assert.assertTrue(order.indexOf(n5) < order.indexOf(n12)); // - n6 comes before n13 and n14 Assert.assertTrue(order.indexOf(n6) < order.indexOf(n13)); Assert.assertTrue(order.indexOf(n6) < order.indexOf(n14)); } { List<Node> order = orderer.newList(g, true); Assert.assertEquals(15, order.size()); Assert.assertTrue(order.containsAll(Arrays.asList(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14))); // Check for reverse topological sort property: edge (i,j) implies j is before i in the order // - n0 comes after all others Assert.assertEquals(n0, order.get(order.size() - 1)); // - n1 comes after the entire left hand sub-tree Assert.assertTrue(order.indexOf(n1) > order.indexOf(n3)); Assert.assertTrue(order.indexOf(n1) > order.indexOf(n4)); Assert.assertTrue(order.indexOf(n1) > order.indexOf(n7)); Assert.assertTrue(order.indexOf(n1) > order.indexOf(n8)); Assert.assertTrue(order.indexOf(n1) > order.indexOf(n9)); Assert.assertTrue(order.indexOf(n1) > order.indexOf(n10)); // - n2 comes after the entire right hand sub-tree Assert.assertTrue(order.indexOf(n2) > order.indexOf(n5)); Assert.assertTrue(order.indexOf(n2) > order.indexOf(n6)); Assert.assertTrue(order.indexOf(n2) > order.indexOf(n11)); Assert.assertTrue(order.indexOf(n2) > order.indexOf(n12)); Assert.assertTrue(order.indexOf(n2) > order.indexOf(n13)); Assert.assertTrue(order.indexOf(n2) > order.indexOf(n14)); // - n3 comes after n7 and n8 Assert.assertTrue(order.indexOf(n3) > order.indexOf(n7)); Assert.assertTrue(order.indexOf(n3) > order.indexOf(n8)); // - n4 comes after n9 and n10 Assert.assertTrue(order.indexOf(n4) > order.indexOf(n9)); Assert.assertTrue(order.indexOf(n4) > order.indexOf(n10)); // - n5 comes after n11 and n12 Assert.assertTrue(order.indexOf(n5) > order.indexOf(n11)); Assert.assertTrue(order.indexOf(n5) > order.indexOf(n12)); // - n6 comes after n13 and n14 Assert.assertTrue(order.indexOf(n6) > order.indexOf(n13)); Assert.assertTrue(order.indexOf(n6) > order.indexOf(n14)); } // System.out.println("Completed testOrder3()"); } @Test public void testOrder4() { // graph with a loop and non-tree structures Node n0 = new Node(0); Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); Node n5 = new Node(5); Node n6 = new Node(6); n0.addkid(n1); n1.addkid(n2); n2.addkid(n3); n3.addkid(n4); n4.addkid(n5); n5.addkid(n6); n3.addkid(n1); n2.addkid(n6); Graph g = new Graph(n0); { Assert.assertEquals(7, g.size()); } { List<Node> order = orderer.newList(g, false); Assert.assertEquals(7, order.size()); Assert.assertTrue(order.containsAll(Arrays.asList(n0, n1, n2, n3, n4, n5, n6))); // NOTE: n0 must come first and n4, n5, n6 must be the tail but the others can be any order Assert.assertEquals(n0, order.get(0)); Assert.assertEquals(n4, order.get(4)); Assert.assertEquals(n5, order.get(5)); Assert.assertEquals(n6, order.get(6)); } { List<Node> order = orderer.newList(g, true); Assert.assertEquals(7, order.size()); Assert.assertTrue(order.containsAll(Arrays.asList(n0, n1, n2, n3, n4, n5, n6))); // NOTE: n0 must come last and n6, n5, n4 must be the head but the others can be any order Assert.assertEquals(n0, order.get(6)); Assert.assertEquals(n4, order.get(2)); Assert.assertEquals(n5, order.get(1)); Assert.assertEquals(n6, order.get(0)); } // System.out.println("Completed testOrder4()"); } @Test public void testOrder5_threadSafety() { final int n = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(n); ArrayList<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < n; i++) { futures.add(executor.submit(this::testOrder1)); futures.add(executor.submit(this::testOrder2)); futures.add(executor.submit(this::testOrder3)); futures.add(executor.submit(this::testOrder4)); } Assert.assertEquals(n * 4, futures.size()); try { executor.shutdown(); executor.awaitTermination(60, TimeUnit.SECONDS); for (Future<?> f : futures) { Assert.assertTrue(f.isDone()); Assert.assertFalse(f.isCancelled()); } } catch (InterruptedException e) { Assert.fail(e.getMessage()); } finally { if (!executor.isTerminated()) { // Cancel non-finished tasks, clear cache, and shutdown for (Future<?> f : futures) { f.cancel(true); } executor.shutdownNow(); } } } }
10,809
34.326797
123
java
soot
soot-master/src/test/java/soot/toolkits/graph/SCCFastTest.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.List; import org.junit.Assert; import org.junit.Test; public class SCCFastTest { @Test public void testSCC1() { Node rootNode = new Node(0); Node left0 = new Node(1); Node left1 = new Node(2); Graph g = new Graph(rootNode); rootNode.addkid(left0); rootNode.addkid(left1); StronglyConnectedComponentsFast<Node> scc = new StronglyConnectedComponentsFast<Node>(g); Assert.assertTrue(scc.getTrueComponents().isEmpty()); } @Test public void testSCC2() { Node rootNode = new Node(0); Node left0 = new Node(1); Node left1 = new Node(2); Node left0a = new Node(3); Node left0b = new Node(4); Graph g = new Graph(rootNode); rootNode.addkid(left0); rootNode.addkid(left1); left0.addkid(left0a); left0a.addkid(left0b); left0b.addkid(left0); StronglyConnectedComponentsFast<Node> scc = new StronglyConnectedComponentsFast<Node>(g); Assert.assertEquals(1, scc.getTrueComponents().size()); List<Node> nodes = scc.getTrueComponents().get(0); Assert.assertEquals(3, nodes.size()); } }
1,896
27.742424
91
java
soot
soot-master/src/test/java/soot/toolkits/graph/SlowPseudoTopologicalOrdererTest.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class SlowPseudoTopologicalOrdererTest extends PseudoTopologicalOrdererTestBase { public SlowPseudoTopologicalOrdererTest() { super(new SlowPseudoTopologicalOrderer<Node>()); } }
1,043
32.677419
88
java
soot
soot-master/src/test/java/soot/toolkits/graph/TestDominance.java
package soot.toolkits.graph; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (c) 2014 Tim Henderson, Case Western Reserve University * Cleveland, Ohio 44106 * All Rights Reserved. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import java.util.ArrayList; 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.Set; import org.junit.Test; import soot.toolkits.graph.pdg.MHGDominatorTree; public class TestDominance { public Set<Integer> kid_ids(DominatorNode<Node> dn) { Set<Integer> kids = new HashSet<Integer>(); for (DominatorNode<Node> dkid : dn.getChildren()) { Node kid = dkid.getGode(); kids.add(kid.id); } return kids; } public Map<Integer,DominatorNode<Node>> kid_map(DominatorNode<Node> dn) { Map<Integer,DominatorNode<Node>> kids = new HashMap<Integer,DominatorNode<Node>>(); for (DominatorNode<Node> dkid : dn.getChildren()) { Node kid = dkid.getGode(); kids.put(kid.id, dkid); } return kids; } @Test public void TestSimpleDiamond() { Node x = new Node(4); Node n = new Node(1).addkid((new Node(2)).addkid(x)).addkid((new Node(3)).addkid(x)); Graph g = new Graph(n); MHGDominatorsFinder<Node> finder = new MHGDominatorsFinder<Node>(g); DominatorTree<Node> tree = new DominatorTree<Node>(finder); assertThat(tree.getHeads().size(), is(1)); DominatorNode<Node> head = tree.getHeads().get(0); assertThat(head.getGode().id, is(1)); Set<Integer> kids = kid_ids(head); assertThat(kids.size(), is(3)); assertThat(kids, containsInAnyOrder(2, 3, 4)); } @Test public void TestAcyclicCFG() { Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); Node n5 = new Node(5); Node n6 = new Node(6); Node n7 = new Node(7); Node n8 = new Node(8); Node n9 = new Node(9); Node n10 = new Node(10); Node n11 = new Node(11); n1.addkid(n2).addkid(n3); n2.addkid(n9); n3.addkid(n4).addkid(n5); n4.addkid(n9); n5.addkid(n6).addkid(n10); n6.addkid(n7).addkid(n8); n7.addkid(n10); n8.addkid(n10); n9.addkid(n11); n10.addkid(n11); Graph g = new Graph(n1); MHGDominatorsFinder<Node> finder = new MHGDominatorsFinder<Node>(g); DominatorTree<Node> tree = new DominatorTree<Node>(finder); assertThat(tree.getHeads().size(), is(1)); DominatorNode<Node> n = tree.getHeads().get(0); assertThat(n.getGode().id, is(1)); Set<Integer> kids = kid_ids(n); assertThat(kids.size(), is(4)); assertThat(kids, containsInAnyOrder(2, 3, 9, 11)); Map<Integer, DominatorNode<Node>> KM = kid_map(n); DominatorNode<Node> m = KM.get(2); kids = kid_ids(m); assertThat(kids.size(), is(0)); m = KM.get(9); kids = kid_ids(m); assertThat(kids.size(), is(0)); m = KM.get(11); kids = kid_ids(m); assertThat(kids.size(), is(0)); n = KM.get(3); kids = kid_ids(n); assertThat(kids.size(), is(2)); assertThat(kids, containsInAnyOrder(4, 5)); KM = kid_map(n); m = KM.get(4); kids = kid_ids(m); assertThat(kids.size(), is(0)); n = KM.get(5); kids = kid_ids(n); assertThat(kids.size(), is(2)); assertThat(kids, containsInAnyOrder(6, 10)); KM = kid_map(n); m = KM.get(10); kids = kid_ids(m); assertThat(kids.size(), is(0)); n = KM.get(6); kids = kid_ids(n); assertThat(kids.size(), is(2)); assertThat(kids, containsInAnyOrder(7, 8)); KM = kid_map(n); m = KM.get(7); kids = kid_ids(m); assertThat(kids.size(), is(0)); m = KM.get(8); kids = kid_ids(m); assertThat(kids.size(), is(0)); } @Test public void TestMultiTailedPostDom() { Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); Node n5 = new Node(5); Node n6 = new Node(6); n1.addkid(n2).addkid(n3); n3.addkid(n4).addkid(n5); n4.addkid(n6); n5.addkid(n6); Graph g = new Graph(n1); MHGDominatorsFinder<Node> finder = new MHGDominatorsFinder<Node>(g); MHGDominatorTree<Node> tree = new MHGDominatorTree<Node>(finder); assertThat(tree.getHeads().size(), is(1)); DominatorNode<Node> n = tree.getHeads().get(0); assertThat(n.getGode().id, is(1)); Set<Integer> kids = kid_ids(n); assertThat(kids.size(), is(2)); assertThat(kids, containsInAnyOrder(2, 3)); Map<Integer, DominatorNode<Node>> KM = kid_map(n); DominatorNode<Node> m = KM.get(2); kids = kid_ids(m); assertThat(kids.size(), is(0)); n = KM.get(3); kids = kid_ids(n); assertThat(kids.size(), is(3)); assertThat(kids, containsInAnyOrder(4, 5, 6)); KM = kid_map(n); m = KM.get(4); kids = kid_ids(m); assertThat(kids.size(), is(0)); m = KM.get(5); kids = kid_ids(m); assertThat(kids.size(), is(0)); m = KM.get(6); kids = kid_ids(m); assertThat(kids.size(), is(0)); // ---------- now post-dom -------------- MHGPostDominatorsFinder<Node> pfinder = new MHGPostDominatorsFinder<Node>(g); tree = new MHGDominatorTree<Node>(pfinder); Map<Integer,DominatorNode<Node>> heads = new HashMap<Integer,DominatorNode<Node>>(); for (DominatorNode<Node> dhead : tree.getHeads()) { Node head = dhead.getGode(); heads.put(head.id, dhead); } Set<Integer> head_ids = heads.keySet(); assertThat(head_ids.size(), is(3)); assertThat(head_ids, containsInAnyOrder(1, 2, 6)); m = heads.get(1); kids = kid_ids(m); assertThat(kids.size(), is(0)); m = heads.get(2); kids = kid_ids(m); assertThat(kids.size(), is(0)); n = heads.get(6); kids = kid_ids(n); assertThat(kids.size(), is(3)); assertThat(kids, containsInAnyOrder(3, 4, 5)); KM = kid_map(n); m = KM.get(3); kids = kid_ids(m); assertThat(kids.size(), is(0)); m = KM.get(4); kids = kid_ids(m); assertThat(kids.size(), is(0)); m = KM.get(5); kids = kid_ids(m); assertThat(kids.size(), is(0)); } } class Graph implements DirectedGraph<Node> { Node root; List<Node> nodes; List<Node> tails = new ArrayList<Node>(); public Graph(Node root) { this.root = root; for (Node n : this) { if (n.succs.size() == 0) { tails.add(n); } } } /** * Returns a list of entry points for this graph. */ public List<Node> getHeads() { return Collections.singletonList(this.root); } /** Returns a list of exit points for this graph. */ public List<Node> getTails() { return tails; } /** * Returns a list of predecessors for the given node in the graph. */ public List<Node> getPredsOf(Node s){ return ((Node)s).preds; } /** * Returns a list of successors for the given node in the graph. */ public List<Node> getSuccsOf(Node s) { return ((Node)s).succs; } /** * Returns the node count for this graph. */ public int size() { if (this.nodes == null) { this.nodes = this.dfs(this.root); } return this.nodes.size(); } /** * Returns an iterator for the nodes in this graph. No specific ordering * of the nodes is guaranteed. */ public Iterator<Node> iterator() { if (this.nodes == null) { this.nodes = this.dfs(this.root); } Iterator<Node> i = this.nodes.iterator(); return i; } public List<Node> dfs(Node root) { List<Node> list = new ArrayList<Node>(); Set<Node> seen = new HashSet<Node>(); dfs_visit(root, seen, list); return list; } void dfs_visit(Node node, Set<Node> seen, List<Node> list) { seen.add(node); list.add(node); for (Node kid : node.succs) { if (!seen.contains(kid)) { dfs_visit(kid, seen, list); } } for (Node parent : node.preds) { if (!seen.contains(parent)) { dfs_visit(parent, seen, list); } } } } class Node { int id; List<Node> preds = new ArrayList<Node>(); List<Node> succs = new ArrayList<Node>(); public Node(int id) { this.id = id; } public Node addkid(Node kid) { kid.preds.add(this); this.succs.add(kid); return this; } public int hashCode() { return this.id; } public boolean Equals(Object o) { if (o == null) { return false; } else if (o instanceof Node) { return this.Equals((Node)o); } return false; } public boolean Equals(Node o) { if (o == null) { return false; } return this.id == o.id; } }
10,498
26.701847
93
java
soot
soot-master/src/test/java/soot/toolkits/graph/targets/TestException.java
package soot.toolkits.graph.targets; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2019 Shawn Meier * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ public class TestException { public static void main(String[] args) { int a = 0; int b = 0; try { a = a / b; } catch (Exception e) { a = Math.abs(-1); } finally { b = 0; } } }
1,118
25.642857
71
java
soot
soot-master/src/test/java/soot/toolkits/purity/BinarySearchTree.java
package soot.toolkits.purity; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * This example is from the article A Combined Pointer and Purity Analysis for * Java Programs" by Alexandru Salcianu and Martin Rinard. * It is supposed to demonstrate the purity analysis (-annot-purity) * * by Antoine Mine, 2005/02/08 */ import java.util.HashSet; import java.util.LinkedList; import java.util.Set; public class BinarySearchTree { Node root; int size; static class Node { Node left; Node right; Comparable info; } static final class Wrapper { Object o; Wrapper(Object o) { this.o = o; } public boolean equals(Object o) { if (!(o instanceof Wrapper)) return false; return this.o == ((Wrapper)o).o; } public int hashCode() { return System.identityHashCode(o); } } boolean repOk() { if (root==null) return size==0; if (!isTree()) return false; if (numNodes(root)!=size) return false; if (!isOrdered(root,null,null)) return false; return true; } boolean isTree() { Set visited = new HashSet(); visited.add(new Wrapper(root)); LinkedList workList = new LinkedList(); workList.add(root); while (!workList.isEmpty()) { Node current = (Node)workList.removeFirst(); if (current.left!=null) { if (!visited.add(new Wrapper(current.left))) return false; workList.add(current.left); } if (current.right!=null) { if (!visited.add(new Wrapper(current.right))) return false; workList.add(current.right); } } return true; } int numNodes(Node n) { if (n==null) return 0; return 1 + numNodes(n.left) + numNodes(n.right); } boolean isOrdered(Node n, Comparable min, Comparable max) { if ((min!=null && n.info.compareTo(min)<=0) || (max!=null && n.info.compareTo(max)>=0)) return false; if (n.left!=null) if (!isOrdered(n.left,min,n.info)) return false; if (n.right!=null) if (!isOrdered(n.right,n.info,max)) return false; return true; } static Node create(int i) { if (i==0) return null; Node n = new Node(); n.left = create(i-1); n.right = create(i-1); return n; } public static void main(String[] args) { BinarySearchTree x = new BinarySearchTree(); x.root = create(5); x.repOk(); } }
3,032
24.487395
78
java
soot
soot-master/src/test/java/soot/toolkits/purity/PurityTest.java
package soot.toolkits.purity; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Ignore; /** * This example is from the article "A Combined Pointer and Purity Analysis for * Java Programs" by Alexandru Salcianu and Martin Rinard. * It is supposed to demonstrate the purity analysis (-annot-purity) * * by Antoine Mine, 2005/02/08 */ class List { Cell head = null; void add(Object e) { head = new Cell(e,head); } Iterator iterator() { return new ListItr(head); } } class Cell { Object data; Cell next; Cell(Object d, Cell n) { data = d; next = n; } } interface Iterator { boolean hasNext(); Object next(); } class ListItr implements Iterator { Cell cell; ListItr(Cell head) { cell = head; } public boolean hasNext() { return cell != null; } public Object next() { Object result = cell.data; cell = cell.next; return result; } } class Point { float x,y; Point(float x,float y) { this.x = x; this.y = y; } void flip() { float t = x; x = y; y = t; } void print() { System.out.print("("+x+","+y+")"); } } @Ignore("not a real test!") public class PurityTest { static float sumX(List list) { float s = 0; Iterator it = list.iterator(); while (it.hasNext()) { Point p = (Point) it.next(); s += p.x; } return s; } static void flipAll(List list) { Iterator it = list.iterator(); while (it.hasNext()) { Point p = (Point) it.next(); p.flip(); } } static void print(List list) { Iterator it = list.iterator(); System.out.print("["); while (it.hasNext()) { Point p = (Point) it.next(); p.print(); if (it.hasNext()) System.out.print(";"); } System.out.println("]"); } public static void main(String args[]) { List list = new List(); list.add(new Point(1,2)); list.add(new Point(2,3)); list.add(new Point(3,4)); print(list); System.out.println("sum="+sumX(list)); sumX(list); print(list); flipAll(list); print(list); } }
2,834
18.155405
79
java
soot
soot-master/src/test/java/soot/toolkits/scalar/ArrayPackedSetTest.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import java.util.Iterator; import org.junit.Before; import org.junit.Test; public class ArrayPackedSetTest { FlowUniverse<Integer> universe; BoundedFlowSet<Integer> a; @Before public void init() { Integer[] aa = {1,2,3,4,5,6,7,8,9}; universe = new ArrayFlowUniverse<Integer>(aa); a = new ArrayPackedSet<Integer>(universe); } @Test public void testEmptySet() { FlowSet<Integer> e = a.emptySet(); assertNotSame(a, e); assertTrue(e.isEmpty()); for (int i : universe) { assertFalse(e.contains(i)); } } @Test public void testAdd() { FlowSet<Integer> e = a.emptySet(); for (int i : universe) { assertFalse(e.contains(i)); e.add(i); assertTrue(e.contains(i)); } } @Test public void testRemove() { FlowSet<Integer> e = a.topSet(); for (int i : universe) { assertTrue(e.contains(i)); e.remove(i); assertFalse(e.contains(i)); } } @Test public void testEmptySetNewInstance() { assertNotSame(a.emptySet(), a.emptySet()); } @Test public void testTopSetNewInstance() { assertNotSame(a.topSet(), a.topSet()); } @Test public void testTopSet() { FlowSet<Integer> e = a.topSet(); assertNotSame(a, e); assertFalse(e.isEmpty()); assertEquals(universe.size(), e.size()); for (int i : universe) { assertTrue(e.contains(i)); } } @Test public void testIteratorFull() { FlowSet<Integer> e = a.topSet(); Iterator<Integer> it = universe.iterator(); for (int i : e) { assertEquals(it.next().intValue(), i); } assertFalse(it.hasNext()); } @Test public void testToListFull() { FlowSet<Integer> e = a.topSet(); assertArrayEquals(universe.toArray(), e.toList().toArray()); } @Test public void testToListEmpty() { FlowSet<Integer> e = a.emptySet(); assertArrayEquals(new Object[0], e.toList().toArray()); } @Test public void testToList() { FlowSet<Integer> e = a.emptySet(); Integer[] t = {3,7,33}; for (int i : t) e.add(i); assertEquals(t.length, e.size()); assertArrayEquals(t, e.toList().toArray()); } @Test public void testIterator() { FlowSet<Integer> e = a.emptySet(); Integer[] t = {3,6,7,8,12}; for (int i : t) e.add(i); int j = 0; for (int i : e) assertEquals(t[j++].intValue(), i); } @Test public void testCopy() { FlowSet<Integer> e1 = a.emptySet(); FlowSet<Integer> e2 = a.topSet(); e2.copy(e1); assertEquals(e1, e2); } @Test public void testClear() { FlowSet<Integer> e = a.topSet(); assertFalse(e.isEmpty()); e.clear(); assertTrue(e.isEmpty()); for (int i : universe) { assertFalse(e.contains(i)); } } @Test public void testComplement() { BoundedFlowSet<Integer> e1 = (BoundedFlowSet<Integer>) a.emptySet(); FlowSet<Integer> e2 = a.topSet(); assertTrue(e1.isEmpty()); assertEquals(0, e1.size()); assertEquals(universe.size(), e2.size()); e1.complement(); assertEquals(e1, e2); assertNotSame(e1, e2); } @Test public void testComplement2() { BoundedFlowSet<Integer> e = (BoundedFlowSet<Integer>) a.emptySet(); for (int i : universe) { if ( (i % 3) == 0 ) { e.add(i); } } for (int i : universe) { if ( (i % 3) == 0 ) { assertTrue(e.contains(i)); } else { assertFalse(e.contains(i)); } } e.complement(); for (int i : universe) { if ( (i % 3) == 0 ) { assertFalse(e.contains(i)); } else { assertTrue(e.contains(i)); } } } }
4,483
19.663594
71
java
soot
soot-master/src/test/java/soot/toolkits/scalar/ArraySparseSetTest.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Arrays; import java.util.Iterator; import org.junit.Assert; import org.junit.Test; public class ArraySparseSetTest { @Test public void testBug11() { ArraySparseSet<String> ars1 = new ArraySparseSet<String>(); ars1.add("a"); ars1.add("b"); ArraySparseSet<String> ars2 = new ArraySparseSet<String>(); ars2.add("b"); ars2.add("a"); Assert.assertEquals(ars1, ars2); Assert.assertEquals(ars1.hashCode(), ars2.hashCode()); } @Test public void testBug12() { ArraySparseSet<String> ars1 = new ArraySparseSet<String>(); ars1.add("a"); ars1.add("b"); ArrayPackedSet<String> aps = new ArrayPackedSet<String>( new CollectionFlowUniverse<String>(Arrays.asList("a","b"))); aps.add("b"); aps.add("a"); Assert.assertEquals(ars1, aps); Assert.assertEquals(ars1.hashCode(), aps.hashCode()); } @Test public void testIterator() { ArraySparseSet<String> ars1 = new ArraySparseSet<String>(); ars1.add("a"); ars1.add("b"); ars1.add("c"); // remove element c Iterator<String> it = ars1.iterator(); while (it.hasNext()) { String element = it.next(); if (element.equals("c")) it.remove(); } // check size Assert.assertEquals(2, ars1.size()); // check remaining elements boolean aFound = false; boolean bFound = false; for (String element : ars1) { if (element.equals("a")) { Assert.assertFalse(aFound); aFound = true; } if (element.equals("b")) { Assert.assertFalse(bFound); bFound = true; } } Assert.assertTrue(aFound); Assert.assertTrue(bFound); } }
2,430
23.555556
71
java
soot
soot-master/src/test/java/soot/toolkits/scalar/CombinedDUAnalysisTest.java
package soot.toolkits.scalar; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.HashSet; import java.util.List; import org.junit.Test; import soot.Local; import soot.Unit; import soot.toolkits.graph.UnitGraph; public class CombinedDUAnalysisTest { public static CombinedAnalysis v(final UnitGraph graph) { return new CombinedAnalysis() { CombinedDUAnalysis combined = new CombinedDUAnalysis(graph); SimpleLocalDefs defs = new SimpleLocalDefs(graph); SimpleLocalUses uses = new SimpleLocalUses(graph, defs); SimpleLiveLocals live = new SimpleLiveLocals(graph); @Override public List<Unit> getDefsOfAt(Local l, Unit s) { HashSet<Unit> hs1 = new HashSet<Unit>(combined.getDefsOfAt(l, s)); HashSet<Unit> hs2 = new HashSet<Unit>(defs.getDefsOfAt(l, s)); if (!hs1.equals(hs2)) { throw new RuntimeException("Defs of " + l + " in " + s + "\ncombined: " + hs1 + "\nsimple: " + hs2); } return combined.getDefsOfAt(l, s); } @Override public List<UnitValueBoxPair> getUsesOf(Unit u) { HashSet<UnitValueBoxPair> hs1 = new HashSet<UnitValueBoxPair>(combined.getUsesOf(u)); HashSet<UnitValueBoxPair> hs2 = new HashSet<UnitValueBoxPair>(uses.getUsesOf(u)); if (!hs1.equals(hs2)) { throw new RuntimeException("Uses of " + u + "\ncombined: " + hs1 + "\nsimple: " + hs2); } return combined.getUsesOf(u); } @Override public List<Local> getLiveLocalsBefore(Unit u) { HashSet<Local> hs1 = new HashSet<Local>(combined.getLiveLocalsBefore(u)); HashSet<Local> hs2 = new HashSet<Local>(live.getLiveLocalsBefore(u)); if (!hs1.equals(hs2)) { throw new RuntimeException("llb of " + u + "\ncombined: " + hs1 + "\nsimple: " + hs2); } return combined.getLiveLocalsBefore(u); } @Override public List<Local> getLiveLocalsAfter(Unit u) { HashSet<Local> hs1 = new HashSet<Local>(combined.getLiveLocalsAfter(u)); HashSet<Local> hs2 = new HashSet<Local>(live.getLiveLocalsAfter(u)); if (!hs1.equals(hs2)) { throw new RuntimeException("lla of " + u + "\ncombined: " + hs1 + "\nsimple: " + hs2); } return combined.getLiveLocalsAfter(u); } @Override public List<Unit> getDefsOf(Local l) { HashSet<Unit> hs1 = new HashSet<Unit>(combined.getDefsOf(l)); HashSet<Unit> hs2 = new HashSet<Unit>(defs.getDefsOf(l)); if (!hs1.equals(hs2)) { throw new RuntimeException("Defs of " + l + "\ncombined: " + hs1 + "\nsimple: " + hs2); } return combined.getDefsOf(l); } }; } @Test public void test() { // TODO: build a proper test harness } }
3,570
34.356436
110
java
soot
soot-master/src/test/java/soot/util/BitVector_intersects_Test.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * JUnit test suite for the BitVector.intersects() method * @Author Quentin Sabah */ public class BitVector_intersects_Test extends TestCase { public BitVector_intersects_Test(String name) { super(name); } public void testEmptyBitvectorDontIntersectsItself() { BitVector a = new BitVector(); assertFalse(a.intersects(a)); } public void testEmptyBitVectorsDontIntersects() { BitVector a = new BitVector(); BitVector b = new BitVector(); assertFalse(a.intersects(b)); assertFalse(b.intersects(a)); } public void testEquallySizedEmptyBitVectorsDontIntersects() { BitVector a = new BitVector(1024); BitVector b = new BitVector(1024); assertFalse(a.intersects(b)); assertFalse(b.intersects(a)); } public void testNotEquallySizedEmptyBitVectorsDontIntersects() { BitVector a = new BitVector(2048); BitVector b = new BitVector(1024); assertFalse(a.intersects(b)); assertFalse(b.intersects(a)); } public void testSizedEmptyBitVectorDontIntersectsItself() { BitVector a = new BitVector(1024); assertFalse(a.intersects(a)); } public void testNonOverlappingBitVectorsDontIntersects() { BitVector a = new BitVector(); BitVector b = new BitVector(); int i; for(i = 0; i < 512; i++) { if(i % 2 == 0) a.set(i); else b.set(i); } assertFalse(a.intersects(b)); assertFalse(b.intersects(a)); } public void testNotEquallySizedNonOverlappingBitVectorsDontIntersects() { BitVector a = new BitVector(); BitVector b = new BitVector(); int i; for(i = 0; i < 512; i++) { a.set(i); } for(; i < 1024; i++) { b.set(i); } assertFalse(a.intersects(b)); assertFalse(b.intersects(a)); } public void testNonEmptyBitVectorIntersectsItself() { BitVector a = new BitVector(); a.set(337); assertTrue(a.intersects(a)); } public void testNotEquallySizedOverlappingBitVectorsIntersects() { BitVector a = new BitVector(1024); BitVector b = new BitVector(512); a.set(337); b.set(337); assertTrue(a.intersects(b)); assertTrue(b.intersects(a)); a.clear(337); b.clear(337); for(int i = 0; i < 512; i++) { a.set(i); b.set(i); assertTrue(a.intersects(b)); assertTrue(b.intersects(a)); a.clear(i); b.clear(i); } } public static Test suite() { TestSuite suite = new TestSuite(BitVector_intersects_Test.class); return suite; } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
3,521
25.681818
75
java
soot
soot-master/src/test/java/soot/util/LargePriorityQueueTest.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; import org.junit.After; import org.junit.Before; import org.junit.Test; public class LargePriorityQueueTest { Integer[] universe1; Integer[] clone; Queue<Integer> q; @Before public void initUniverse() { universe1 = new Integer[MediumPriorityQueue.MAX_CAPACITY+64]; for (int j = 0; j < universe1.length; j++) universe1[j] = j; clone = Arrays.copyOf(universe1, universe1.length); } @After public void postconditionUniverseNotModified() { assertArrayEquals(clone, universe1); } @After public void postconditionInstanceOfLargePriorityQueue() { assertTrue(q instanceof LargePriorityQueue); } @Test public void testDeleteFirst() { q = PriorityQueue.of(universe1); assertTrue(q.remove(universe1[0])); assertEquals(q.peek(), universe1[1]); assertEquals(q.poll(), universe1[1]); } @Test public void testNew() { q = PriorityQueue.of(universe1); assertEquals(universe1.length, q.size()); assertFalse(q.isEmpty()); } @Test public void testPollAll() { q = PriorityQueue.of(universe1); int i = 0; while (!q.isEmpty()) assertEquals(universe1[i++], q.poll()); } @Test public void testPoll2() { q = PriorityQueue.noneOf(universe1); for (int i=0;i<universe1.length;i+=3) q.add(universe1[i]); int i = -3; while (!q.isEmpty()) { Object e = universe1[i+=3]; assertEquals(e, q.peek()); assertEquals(e, q.poll()); } } @Test public void testPeekPollAll() { q = PriorityQueue.of(universe1); while (!q.isEmpty()) assertEquals(q.peek(), q.poll()); } @Test public void testOffer() { q = PriorityQueue.of(universe1); int i = 0; assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); q.add(universe1[i=0]); assertEquals(universe1[i++], q.poll()); } @Test public void testMixedAddDelete() { q = PriorityQueue.noneOf(universe1); Integer z = universe1[0]; Integer x = universe1[666]; assertTrue(q.add(z)); assertFalse(q.offer(z)); assertTrue(q.contains(z)); assertTrue(q.add(x)); for (Integer i : universe1) assertEquals((i == z || i == x), q.contains(i)); assertTrue(q.remove(z)); for (Integer i : universe1) assertEquals(i == x, q.contains(i)); assertEquals(x, q.peek()); assertEquals(x, q.poll()); } @Test public void testOfferAlreadyInQueue() { q = PriorityQueue.of(universe1); for ( Integer i : universe1 ) { assertFalse(q.offer(i)); } } @Test public void testClear() { q = PriorityQueue.of(universe1); q.clear(); assertEquals(q.size(), 0); assertTrue(q.isEmpty()); assertNull(q.peek()); assertNull(q.poll()); for (Integer i : universe1) assertFalse(q.contains(i)); } @Test(expected=NoSuchElementException.class) public void testOfferNotInUniverse() { q = PriorityQueue.of(universe1); q.offer(-999); } @Test(expected=NullPointerException.class) public void testOfferNull() { q = PriorityQueue.of(universe1); q.offer(null); } @Test public void testRemoveNull() { q = PriorityQueue.of(universe1); assertFalse(q.remove(null)); } @Test public void testIteratorAll() { q = PriorityQueue.of(universe1); int j = 0; for (Integer i : q) { assertEquals(universe1[j++], i); } } @Test(expected=ConcurrentModificationException.class) public void testIteratorDelete() { q = PriorityQueue.of(universe1); int j = 0; for (Integer i : q) { assertEquals(universe1[j++], i); assertTrue(q.remove(universe1[universe1.length-1])); } } @Test public void testIteratorRemove() { q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { Integer i = it.next(); assertTrue(q.contains(i)); it.remove(); assertFalse(q.contains(i)); } } @Test(expected=NoSuchElementException.class) public void testIteratorOutOfBounds() { q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { it.next(); } it.next(); } @Test(expected=IllegalStateException.class) public void testIteratorDoubleRemove() { q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { it.next(); it.remove(); it.remove(); } } @Test(expected=IllegalStateException.class) public void testIteratorBeforeFirst() { q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); it.remove(); } @Test() public void testIteratorHole1() { q = PriorityQueue.of(universe1); int hole = 7; assertTrue(q.remove(universe1[hole])); assertFalse(q.contains(universe1[hole])); int j = 0; for (Integer i : q) { if (j==hole)j++; assertEquals(universe1[j++], i); } } }
6,398
22.43956
71
java
soot
soot-master/src/test/java/soot/util/MediumPriorityQueueTest.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; import org.junit.After; import org.junit.Before; import org.junit.Test; public class MediumPriorityQueueTest { Integer[] universe1; Integer[] clone; Queue<Integer> q; @Before public void initUniverse() { universe1 = new Integer[MediumPriorityQueue.MAX_CAPACITY-63]; for (int j = 0; j < universe1.length; j++) universe1[j] = j; clone = Arrays.copyOf(universe1, universe1.length); } @After public void postconditionUniverseNotModified() { assertArrayEquals(clone, universe1); } @After public void postconditionInstanceOfMediumPriorityQueue() { assertTrue(q instanceof MediumPriorityQueue); } @Test public void testDeleteFirst() { q = PriorityQueue.of(universe1); assertTrue(q.remove(universe1[0])); assertEquals(q.peek(), universe1[1]); assertEquals(q.poll(), universe1[1]); } @Test public void testNew() { q = PriorityQueue.of(universe1); assertEquals(universe1.length, q.size()); assertFalse(q.isEmpty()); } @Test public void testPollAll() { q = PriorityQueue.of(universe1); int i = 0; while (!q.isEmpty()) assertEquals(universe1[i++], q.poll()); } @Test public void testPoll2() { q = PriorityQueue.noneOf(universe1); for (int i=0;i<universe1.length;i+=3) q.add(universe1[i]); int i = -3; while (!q.isEmpty()) { Object e = universe1[i+=3]; assertEquals(e, q.peek()); assertEquals(e, q.poll()); } } @Test public void testPeekPollAll() { q = PriorityQueue.of(universe1); while (!q.isEmpty()) assertEquals(q.peek(), q.poll()); } @Test public void testOffer() { q = PriorityQueue.of(universe1); int i = 0; assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); q.add(universe1[i=0]); assertEquals(universe1[i++], q.poll()); } @Test public void testMixedAddDelete() { q = PriorityQueue.noneOf(universe1); Integer z = universe1[0]; Integer x = universe1[666]; assertTrue(q.add(z)); assertFalse(q.offer(z)); assertTrue(q.contains(z)); assertTrue(q.add(x)); for (Integer i : universe1) assertEquals((i == z || i == x), q.contains(i)); assertTrue(q.remove(z)); for (Integer i : universe1) assertEquals(i == x, q.contains(i)); assertEquals(x, q.peek()); assertEquals(x, q.poll()); } @Test public void testOfferAlreadyInQueue() { q = PriorityQueue.of(universe1); for ( Integer i : universe1 ) { assertFalse(q.offer(i)); } } @Test public void testClear() { q = PriorityQueue.of(universe1); q.clear(); assertEquals(q.size(), 0); assertTrue(q.isEmpty()); assertNull(q.peek()); assertNull(q.poll()); for (Integer i : universe1) assertFalse(q.contains(i)); } @Test(expected=NoSuchElementException.class) public void testOfferNotInUniverse() { q = PriorityQueue.of(universe1); q.offer(-999); } @Test(expected=NullPointerException.class) public void testOfferNull() { q = PriorityQueue.of(universe1); q.offer(null); } @Test public void testRemoveNull() { q = PriorityQueue.of(universe1); assertFalse(q.remove(null)); } @Test public void testIteratorAll() { q = PriorityQueue.of(universe1); int j = 0; for (Integer i : q) { assertEquals(universe1[j++], i); } } @Test(expected=ConcurrentModificationException.class) public void testIteratorDelete() { q = PriorityQueue.of(universe1); int j = 0; for (Integer i : q) { assertEquals(universe1[j++], i); assertTrue(q.remove(universe1[universe1.length-1])); } } @Test public void testIteratorRemove() { q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { Integer i = it.next(); assertTrue(q.contains(i)); it.remove(); assertFalse(q.contains(i)); } } @Test(expected=NoSuchElementException.class) public void testIteratorOutOfBounds() { q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { it.next(); } it.next(); } @Test(expected=IllegalStateException.class) public void testIteratorDoubleRemove() { q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { it.next(); it.remove(); it.remove(); } } @Test(expected=IllegalStateException.class) public void testIteratorBeforeFirst() { q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); it.remove(); } @Test() public void testIteratorHole1() { q = PriorityQueue.of(universe1); int hole = 7; assertTrue(q.remove(universe1[hole])); assertFalse(q.contains(universe1[hole])); int j = 0; for (Integer i : q) { if (j==hole)j++; assertEquals(universe1[j++], i); } } }
6,033
21.102564
71
java
soot
soot-master/src/test/java/soot/util/SmallPriorityQueueTest.java
package soot.util; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; import org.junit.Test; public class SmallPriorityQueueTest { Integer[] universe1 = new Integer[] {1,2,3,4,5,6,7,8,9,10,11,12,13,15}; @Test public void testDeleteFirst() { Queue<Integer> q = PriorityQueue.of(universe1); assertTrue(q.remove(universe1[0])); assertEquals(q.peek(), universe1[1]); assertEquals(q.poll(), universe1[1]); } @Test public void testNew() { Queue<Integer> q = PriorityQueue.of(universe1); assertEquals(universe1.length, q.size()); assertFalse(q.isEmpty()); } @Test public void testInstance() { assertTrue(PriorityQueue.of(universe1) instanceof SmallPriorityQueue); } @Test public void testMixedAddDelete() { int second = 6; Queue<Integer> q = PriorityQueue.noneOf(universe1); assertTrue(q.add(universe1[0])); assertFalse(q.offer(universe1[0])); assertTrue(q.add(universe1[second])); assertTrue(q.remove(universe1[0])); assertEquals(q.peek(), universe1[second]); assertEquals(q.poll(), universe1[second]); } @Test public void testOfferAlreadyInQueue() { Queue<Integer> q = PriorityQueue.of(universe1); for ( Integer i : universe1 ) { assertFalse(q.offer(i)); } } @Test public void testClear() { Queue<Integer> q = PriorityQueue.of(universe1); q.clear(); assertEquals(q.size(), 0); assertTrue(q.isEmpty()); assertNull(q.peek()); assertNull(q.poll()); for (Integer i : universe1) assertFalse(q.contains(i)); } @Test(expected=NoSuchElementException.class) public void testOfferNotInUniverse() { Queue<Integer> q = PriorityQueue.of(universe1); q.offer(999); } @Test(expected=NullPointerException.class) public void testOfferNull() { Queue<Integer> q = PriorityQueue.of(universe1); q.offer(null); } @Test public void testRemoveNull() { Queue<Integer> q = PriorityQueue.of(universe1); assertFalse(q.remove(null)); } @Test public void testIteratorAll() { Queue<Integer> q = PriorityQueue.of(universe1); int j = 0; for (Integer i : q) { assertEquals(universe1[j++], i); } } @Test(expected=ConcurrentModificationException.class) public void testIteratorDelete() { Queue<Integer> q = PriorityQueue.of(universe1); int j = 0; for (Integer i : q) { assertEquals(universe1[j++], i); assertTrue(q.remove(universe1[universe1.length-1])); } } @Test public void testOffer() { Queue<Integer> q = PriorityQueue.of(universe1); int i = 0; assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); assertEquals(universe1[i++], q.poll()); q.add(universe1[i=0]); assertEquals(universe1[i++], q.poll()); } @Test public void testIteratorRemove() { Queue<Integer> q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { Integer i = it.next(); assertTrue(q.contains(i)); it.remove(); assertFalse(q.contains(i)); } } @Test(expected=NoSuchElementException.class) public void testIteratorOutOfBounds() { Queue<Integer> q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { it.next(); } it.next(); } @Test(expected=IllegalStateException.class) public void testIteratorDoubleRemove() { Queue<Integer> q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); while (it.hasNext()) { it.next(); it.remove(); it.remove(); } } @Test(expected=IllegalStateException.class) public void testIteratorBeforeFirst() { Queue<Integer> q = PriorityQueue.of(universe1); Iterator<Integer> it = q.iterator(); it.remove(); } @Test() public void testIteratorHole1() { Queue<Integer> q = PriorityQueue.of(universe1); int hole = 7; assertTrue(q.remove(universe1[hole])); int j = 0; for (Integer i : q) { if (j==hole)j++; assertEquals(universe1[j++], i); } } }
5,038
23.342995
72
java
soot
soot-master/src/test/java/soot/util/backend/SootASMClassWriterTest.java
package soot.util.backend; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import static org.junit.Assert.assertEquals; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.UnknownType; @PrepareForTest({ Scene.class, UnknownType.class, RefType.class }) @RunWith(PowerMockRunner.class) @PowerMockIgnore({"javax.management.", "com.sun.org.apache.xerces.", "javax.xml.", "org.xml.", "org.w3c.dom.", "com.sun.org.apache.xalan.", "javax.activation.*"}) public class SootASMClassWriterTest { private Scene scene; private SootClass sc1; private SootClass sc2; private SootClass object; private SootClass commonSuperClass; private RefType type1; private RefType type2; private RefType objectType; SootASMClassWriter cw; @Before public void setUp() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { mockStatic(Scene.class); mockStatic(RefType.class); mockStatic(UnknownType.class); scene = mock(Scene.class); when(Scene.v()).thenReturn(scene); UnknownType unknown = mock(UnknownType.class); when(UnknownType.v()).thenReturn(unknown); sc1 = mockClass("A"); sc2 = mockClass("B"); type1 = RefType.v("A"); type2 = RefType.v("B"); object = mockClass("java.lang.Object"); objectType = mock(RefType.class); when(object.getType()).thenReturn(objectType); when(Scene.v().getObjectType()).thenReturn(objectType); when(objectType.getSootClass()).thenReturn(object); when(objectType.getClassName()).thenReturn("java.lang.Object"); when(type1.merge(type2, scene)).thenCallRealMethod(); commonSuperClass = mockClass("C"); commonSuperClass.setResolvingLevel(SootClass.HIERARCHY); when(commonSuperClass.getSuperclass()).thenReturn(object); when(commonSuperClass.getSuperclassUnsafe()).thenReturn(object); cw = mock(SootASMClassWriter.class); when(cw.getCommonSuperClass("A", "B")).thenCallRealMethod(); } @Test public void testGetCommonSuperClassNormal() { when(sc1.getSuperclass()).thenReturn(commonSuperClass); when(sc2.getSuperclass()).thenReturn(commonSuperClass); when(sc1.getSuperclassUnsafe()).thenReturn(commonSuperClass); when(sc2.getSuperclassUnsafe()).thenReturn(commonSuperClass); assertEquals("C", cw.getCommonSuperClass("A", "B")); } @Test public void testGetCommonSuperClassTransitive() { SootClass sc11 = mockClass("AA"); SootClass sc21 = mockClass("BB"); when(sc11.getSuperclass()).thenReturn(commonSuperClass); when(sc21.getSuperclass()).thenReturn(commonSuperClass); when(sc11.getSuperclassUnsafe()).thenReturn(commonSuperClass); when(sc21.getSuperclassUnsafe()).thenReturn(commonSuperClass); when(sc1.getSuperclass()).thenReturn(sc11); when(sc2.getSuperclass()).thenReturn(sc21); when(sc1.getSuperclassUnsafe()).thenReturn(sc11); when(sc2.getSuperclassUnsafe()).thenReturn(sc21); assertEquals("C", cw.getCommonSuperClass("A", "B")); } @Test public void testGetCommonSuperClassPhantomClass() { SootClass sc11 = mockClass("AA"); when(sc11.isPhantomClass()).thenReturn(true); when(sc11.hasSuperclass()).thenReturn(false); when(sc11.getSuperclass()).thenReturn(null); when(sc11.getSuperclassUnsafe()).thenReturn(null); when(sc1.getSuperclass()).thenReturn(sc11); when(sc2.getSuperclass()).thenReturn(commonSuperClass); when(sc1.getSuperclassUnsafe()).thenReturn(sc11); when(sc2.getSuperclassUnsafe()).thenReturn(commonSuperClass); assertEquals("java/lang/Object", cw.getCommonSuperClass("A", "B")); } @Test public void testGetCommonSuperClassTransitivePhantomClass() { SootClass sc = mockClass("CC"); when(sc.isPhantomClass()).thenReturn(true); when(sc.hasSuperclass()).thenReturn(false); when(sc.getSuperclass()).thenReturn(null); when(sc.getSuperclassUnsafe()).thenReturn(null); when(sc1.getSuperclass()).thenReturn(commonSuperClass); when(sc2.getSuperclass()).thenReturn(commonSuperClass); when(commonSuperClass.getSuperclass()).thenReturn(sc); when(sc1.getSuperclassUnsafe()).thenReturn(commonSuperClass); when(sc2.getSuperclassUnsafe()).thenReturn(commonSuperClass); when(commonSuperClass.getSuperclassUnsafe()).thenReturn(sc); assertEquals("C", cw.getCommonSuperClass("A", "B")); } private SootClass mockClass(String name) { SootClass sc = mock(SootClass.class); RefType type = mock(RefType.class); when(sc.getName()).thenReturn(name); when(sc.getType()).thenReturn(type); when(sc.hasSuperclass()).thenReturn(true); when(sc.resolvingLevel()).thenReturn(SootClass.HIERARCHY); when(scene.getSootClass(name)).thenReturn(sc); when(RefType.v(name)).thenReturn(type); Whitebox.setInternalState(type, "className", name); when(type.getClassName()).thenCallRealMethod(); return sc; } }
6,024
31.219251
101
java
soot
soot-master/src/test/java/soot/util/queue/ChunkedQueueTest.java
package soot.util.queue; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 - 2018 Raja Vallée-Rai and others * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import org.junit.Assert; import org.junit.Test; public class ChunkedQueueTest { @Test public void simpleQueueTest() { ChunkedQueue<String> queue = new ChunkedQueue<>(); queue.add("Hello World"); QueueReader<String> rdr = queue.reader(); queue.add("Test"); Assert.assertTrue(rdr.hasNext()); Assert.assertEquals(rdr.next(), "Test"); Assert.assertFalse(rdr.hasNext()); } @Test public void emptyQueueTest() { ChunkedQueue<String> queue = new ChunkedQueue<>(); queue.add("Hello World"); queue.add("Test"); QueueReader<String> rdr = queue.reader(); Assert.assertFalse(rdr.hasNext()); } @Test public void removeFromQueueTest() { ChunkedQueue<String> queue = new ChunkedQueue<>(); QueueReader<String> rdr = queue.reader(); queue.add("Hello World"); queue.add("Test"); Assert.assertTrue(rdr.hasNext()); rdr.remove("Hello World"); Assert.assertTrue(rdr.hasNext()); rdr.remove("Test"); Assert.assertFalse(rdr.hasNext()); } @Test public void removeFromQueueTest2() { ChunkedQueue<String> queue = new ChunkedQueue<>(); QueueReader<String> rdr = queue.reader(); queue.add("Hello World"); queue.add("Test"); rdr.remove("Hello World"); rdr.remove("Test"); Assert.assertFalse(rdr.hasNext()); } @Test public void removeFromQueueTest3() { ChunkedQueue<String> queue = new ChunkedQueue<>(); QueueReader<String> rdr = queue.reader(); queue.add("Hello World"); queue.add("Test"); queue.add("Foo"); rdr.remove("Hello World"); rdr.remove("Test"); Assert.assertEquals(rdr.next(), "Foo"); } @Test public void removeFromQueueTest4() { ChunkedQueue<String> queue = new ChunkedQueue<>(); QueueReader<String> rdr = queue.reader(); queue.add("Hello World"); queue.add("Test"); queue.add("Foo"); rdr.remove("Hello World"); rdr.remove("Test"); Assert.assertEquals(rdr.hasNext(), true); Assert.assertEquals(rdr.next(), "Foo"); } @Test public void removeFromQueueAndGetTest() { ChunkedQueue<String> queue = new ChunkedQueue<>(); QueueReader<String> rdr = queue.reader(); queue.add("Hello World"); queue.add("Test"); Assert.assertTrue(rdr.hasNext()); rdr.remove("Hello World"); Assert.assertTrue(rdr.hasNext()); Assert.assertEquals(rdr.next(), "Test"); Assert.assertFalse(rdr.hasNext()); } @Test public void readerRemoveTest() { ChunkedQueue<String> queue = new ChunkedQueue<>(); QueueReader<String> rdr = queue.reader(); QueueReader<String> rdr2 = queue.reader(); queue.add("Hello World"); queue.add("Test"); Assert.assertTrue(rdr.hasNext()); Assert.assertEquals(rdr.next(), "Hello World"); rdr.remove(); Assert.assertTrue(rdr.hasNext()); Assert.assertEquals(rdr.next(), "Test"); Assert.assertFalse(rdr.hasNext()); Assert.assertTrue(rdr2.hasNext()); Assert.assertEquals(rdr2.next(), "Test"); Assert.assertFalse(rdr2.hasNext()); } @Test public void removeFromLargeQueueTest() { ChunkedQueue<String> queue = new ChunkedQueue<>(); QueueReader<String> rdr = queue.reader(); for (int i = 0; i < 100; i++) queue.add("Hello World " + i); Assert.assertTrue(rdr.hasNext()); rdr.remove("Hello World 90"); Assert.assertTrue(rdr.hasNext()); Assert.assertEquals(rdr.next(), "Hello World 0"); Assert.assertTrue(rdr.hasNext()); } }
4,122
27.047619
71
java
soot
soot-master/src/test/resources/Clinit/src/soot/A.java
package soot; public class A implements IA { private static String a; static { a = "A"; System.out.println("<soot.A: void clinit()>"); } }
147
13.8
48
java
soot
soot-master/src/test/resources/Clinit/src/soot/A1.java
package soot; public class A1 extends A { public String a1 = "A1"; }
71
11
27
java
soot
soot-master/src/test/resources/Clinit/src/soot/IA.java
package soot; public interface IA { public static String x = "x"; }
71
11
31
java
soot
soot-master/src/test/resources/Clinit/src/soot/Main.java
package soot; public class Main { public static void main(String[] args) { A1 a1 = new A1(); // query? => EntryPoints::clinitOf(A1). // should return "<soot.A: void clinit()>" and "<soot.IA: void clinit()>" // but current implementation will return an empty set. System.out.println(a1.a1); } }
310
21.214286
75
java
soot
soot-master/src/test/resources/SimpleClass/Example.java
public class Example{ public void foo(){ int a = 0; int b = 2; bar(a, b); } public void bar(int a, int b){ int c = a*b; int d = 0; System.out.println(c); } }
224
14
34
java
soot
soot-master/tutorial/addattributes/Main.java
/* Soot - a J*va Optimization and Annotation Framework * Copyright (C) 1997-2000 Raja Vallee-Rai * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ /* This example is writen by Feng Qian. */ package ashes.examples.addattributes; import soot.*; import soot.tagkit.*; import java.util.*; /** Annotation example, adds a "Hello World!" string * as method attribute to each method. */ public class Main { public static void main(String[] args) { /* adds the transformer. */ PackManager.v().getPack("jtp").add(new Transform("annotexample", AnnExampleWrapper.v())); /* invokes Soot */ soot.Main.main(args); } } class AnnExampleWrapper extends BodyTransformer { private static AnnExampleWrapper instance = new AnnExampleWrapper(); private AnnExampleWrapper() {}; public static AnnExampleWrapper v() { return instance; } public void internalTransform(Body body, String phaseName, Map options) { SootMethod method = body.getMethod(); String attr = new String("Hello world!"); Tag example = new GenericAttribute("Example", attr.getBytes()); method.addTag(example); } }
2,173
27.605263
75
java
soot
soot-master/tutorial/createclass/Main.java
/* Soot - a J*va Optimization Framework * Copyright (C) 1997-1999 Raja Vallee-Rai * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ //package ashes.examples.createclass; import soot.*; import soot.jimple.*; import soot.options.Options; import soot.util.*; import java.io.*; import java.util.*; /** Example of using Soot to create a classfile from scratch. * The 'createclass' example creates a HelloWorld class file using Soot. * It proceeds as follows: * * - Create a SootClass <code>HelloWorld</code> extending java.lang.Object. * * - Create a 'main' method and add it to the class. * * - Create an empty JimpleBody and add it to the 'main' method. * * - Add locals and statements to JimpleBody. * * - Write the result out to a class file. */ public class Main { public static void main(String[] args) throws FileNotFoundException, IOException { SootClass sClass; SootMethod method; // Resolve dependencies Scene.v().loadClassAndSupport("java.lang.Object"); Scene.v().loadClassAndSupport("java.lang.System"); // Declare 'public class HelloWorld' sClass = new SootClass("HelloWorld", Modifier.PUBLIC); // 'extends Object' sClass.setSuperclass(Scene.v().getSootClass("java.lang.Object")); Scene.v().addClass(sClass); // Create the method, public static void main(String[]) method = new SootMethod("main", Arrays.asList(new Type[] {ArrayType.v(RefType.v("java.lang.String"), 1)}), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); sClass.addMethod(method); // Create the method body { // create empty body JimpleBody body = Jimple.v().newBody(method); method.setActiveBody(body); Chain units = body.getUnits(); Local arg, tmpRef; // Add some locals, java.lang.String l0 arg = Jimple.v().newLocal("l0", ArrayType.v(RefType.v("java.lang.String"), 1)); body.getLocals().add(arg); // Add locals, java.io.printStream tmpRef tmpRef = Jimple.v().newLocal("tmpRef", RefType.v("java.io.PrintStream")); body.getLocals().add(tmpRef); // add "l0 = @parameter0" units.add(Jimple.v().newIdentityStmt(arg, Jimple.v().newParameterRef(ArrayType.v(RefType.v("java.lang.String"), 1), 0))); // add "tmpRef = java.lang.System.out" units.add(Jimple.v().newAssignStmt(tmpRef, Jimple.v().newStaticFieldRef( Scene.v().getField("<java.lang.System: java.io.PrintStream out>").makeRef()))); // insert "tmpRef.println("Hello world!")" { SootMethod toCall = Scene.v().getMethod("<java.io.PrintStream: void println(java.lang.String)>"); units.add(Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(tmpRef, toCall.makeRef(), StringConstant.v("Hello world!")))); } // insert "return" units.add(Jimple.v().newReturnVoidStmt()); } String fileName = SourceLocator.v().getFileNameFor(sClass, Options.output_format_class); OutputStream streamOut = new JasminOutputStream( new FileOutputStream(fileName)); PrintWriter writerOut = new PrintWriter( new OutputStreamWriter(streamOut)); JasminClass jasminClass = new soot.jimple.JasminClass(sClass); jasminClass.print(writerOut); writerOut.flush(); streamOut.close(); } }
4,800
37.717742
145
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/GenHelloWorld.java
package dk.brics.soot; import soot.*; import soot.jimple.*; import soot.options.*; import soot.util.*; import soot.dava.*; import soot.grimp.*; import java.util.Arrays; import java.io.*; public class GenHelloWorld { public static void main(String[] args) { System.out.println("Generating class..."); SootClass sClass = generateClass(); System.out.println("Writing class file..."); write(sClass, Options.output_format_class); System.out.println("Writing jimple file..."); write(sClass, Options.output_format_jimple); System.out.println("Writing java file..."); // Need to convert the jimple body to grimp before I can convert to dava GrimpBody gBody = Grimp.v().newBody(sClass.getMethodByName("main").getActiveBody(), "gb"); DavaBody davaBody = Dava.v().newBody(gBody); sClass.getMethodByName("main").setActiveBody(davaBody); write(sClass, Options.output_format_dava); System.out.println("Done"); } public static SootClass generateClass() { // Load dependencies Scene.v().loadClassAndSupport("java.lang.Object"); Scene.v().loadClassAndSupport("java.lang.System"); Scene.v().loadNecessaryClasses(); // Create the class HelloWorld as a public class that extends Object SootClass sClass = new SootClass("HelloWorld", Modifier.PUBLIC); sClass.setSuperclass(Scene.v().getSootClass("java.lang.Object")); Scene.v().addClass(sClass); // Create: public static void main(String[]) SootMethod mainMethod = new SootMethod("main", Arrays.asList(new Type[] {ArrayType.v(RefType.v("java.lang.String"), 1)}), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC); sClass.addMethod(mainMethod); // Generate dava body from the jimple body JimpleBody jimpleBody = createJimpleBody(mainMethod); // Set the jimple body as the active one mainMethod.setActiveBody(jimpleBody); return sClass; } private static JimpleBody createJimpleBody(SootMethod method) { // Create a body for the main method and set it as the active body JimpleBody body = Jimple.v().newBody(method); // Create a local to hold the main method argument // Note: In general for any use of objects or basic-types, must generate a local to // hold that in the method body Local frm1 = Jimple.v().newLocal("frm1", ArrayType.v(RefType.v("java.lang.String"), 1)); body.getLocals().add(frm1); // Create a local to hold the PrintStream System.out Local tmpRef = Jimple.v().newLocal("tmpRef", RefType.v("java.io.PrintStream")); body.getLocals().add(tmpRef); // Create a unit (or statement) that assigns main's formal param into the local arg PatchingChain<Unit> units = body.getUnits(); units.add(Jimple.v().newIdentityStmt(frm1, Jimple.v().newParameterRef(ArrayType.v (RefType.v("java.lang.String"), 1), 0))); // Create a unit that assigns System.out to the local tmpRef units.add(Jimple.v().newAssignStmt(tmpRef, Jimple.v().newStaticFieldRef(Scene.v().getField ("<java.lang.System: java.io.PrintStream out>").makeRef()))); // Create the call to tmpRef.println("Hello world!") SootMethod toCall = Scene.v().getMethod ("<java.io.PrintStream: void println(java.lang.String)>"); units.add(Jimple.v().newInvokeStmt (Jimple.v().newVirtualInvokeExpr (tmpRef, toCall.makeRef(), StringConstant.v("Hello world!")))); // Add an empty return statement units.add(Jimple.v().newReturnVoidStmt()); return body; } private static void write(SootClass sClass, int output_format) { OutputStream streamOut = null; try { String filename = SourceLocator.v().getFileNameFor(sClass, output_format); if (output_format == Options.output_format_class) streamOut = new JasminOutputStream(new FileOutputStream(filename)); else streamOut = new FileOutputStream(filename); PrintWriter writerOut = new PrintWriter(new OutputStreamWriter(streamOut)); if (output_format == Options.output_format_class) { JasminClass jasClass = new JasminClass(sClass); jasClass.print(writerOut); } else if (output_format == Options.output_format_jimple) Printer.v().printTo(sClass, writerOut); else if (output_format == Options.output_format_dava) DavaPrinter.v().printTo(sClass, writerOut); writerOut.flush(); writerOut.close(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { if (streamOut != null) try { streamOut.close(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } }
4,556
34.325581
92
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/RunLiveAnalysis.java
package dk.brics.soot; import soot.*; import soot.options.Options; import soot.toolkits.graph.*; import soot.toolkits.scalar.*; import java.io.File; import java.util.List; public class RunLiveAnalysis { public static void main(String[] args) { args = new String[] {"testers.LiveVarsClass"}; if (args.length == 0) { System.out.println("Usage: java RunLiveAnalysis class_to_analyse"); System.exit(0); } String sep = File.separator; String pathSep = File.pathSeparator; String path = System.getProperty("java.home") + sep + "lib" + sep + "rt.jar"; path += pathSep + "." + sep + "tutorial" + sep + "guide" + sep + "examples" + sep + "analysis_framework" + sep + "src"; Options.v().set_soot_classpath(path); SootClass sClass = Scene.v().loadClassAndSupport(args[0]); sClass.setApplicationClass(); Scene.v().loadNecessaryClasses(); for (SootMethod m : sClass.getMethods()) { Body b = m.retrieveActiveBody(); System.out.println("======================================="); System.out.println(m.getName()); UnitGraph graph = new ExceptionalUnitGraph(b); SimpleLiveLocals sll = new SimpleLiveLocals(graph); for (Unit u : graph) { List<Local> before = sll.getLiveLocalsBefore(u); List<Local> after = sll.getLiveLocalsAfter(u); UnitPrinter up = new NormalUnitPrinter(b); up.setIndent(""); System.out.println("---------------------------------------"); u.toString(up); System.out.println(up.output()); System.out.print("Live in: {"); sep = ""; for (Local l : before) { System.out.print(sep); System.out.print(l.getName() + ": " + l.getType()); sep = ", "; } System.out.println("}"); System.out.print("Live out: {"); sep = ""; for (Local l : after) { System.out.print(sep); System.out.print(l.getName() + ": " + l.getType()); sep = ", "; } System.out.println("}"); System.out.println("---------------------------------------"); } System.out.println("======================================="); } } }
2,095
28.111111
70
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/RunVeryBusyAnalysis.java
package dk.brics.soot; import java.io.File; import java.util.List; import dk.brics.soot.analyses.SimpleVeryBusyExpressions; import dk.brics.soot.analyses.VeryBusyExpressions; import soot.Body; import soot.NormalUnitPrinter; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Unit; import soot.UnitPrinter; import soot.options.Options; import soot.toolkits.graph.ExceptionalUnitGraph; import soot.toolkits.graph.UnitGraph; import soot.jimple.internal.*; public class RunVeryBusyAnalysis { public static void main(String[] args) { args = new String[] {"testers.VeryBusyClass"}; if (args.length == 0) { System.out.println("Usage: java RunVeryBusyAnalysis class_to_analyse"); System.exit(0); } String sep = File.separator; String pathSep = File.pathSeparator; String path = System.getProperty("java.home") + sep + "lib" + sep + "rt.jar"; path += pathSep + "." + sep + "tutorial" + sep + "guide" + sep + "examples" + sep + "analysis_framework" + sep + "src"; Options.v().set_soot_classpath(path); SootClass sClass = Scene.v().loadClassAndSupport(args[0]); sClass.setApplicationClass(); Scene.v().loadNecessaryClasses(); for (SootMethod m : sClass.getMethods()) { Body b = m.retrieveActiveBody(); System.out.println("======================================="); System.out.println(m.toString()); UnitGraph graph = new ExceptionalUnitGraph(b); VeryBusyExpressions vbe = new SimpleVeryBusyExpressions(graph); for (Unit u : graph) { List<AbstractBinopExpr> before = vbe.getBusyExpressionsBefore(u); List<AbstractBinopExpr> after = vbe.getBusyExpressionsAfter(u); UnitPrinter up = new NormalUnitPrinter(b); up.setIndent(""); System.out.println("---------------------------------------"); u.toString(up); System.out.println(up.output()); System.out.print("Busy in: {"); sep = ""; for (AbstractBinopExpr e : before) { System.out.print(sep); System.out.print(e.toString()); sep = ", "; } System.out.println("}"); System.out.print("Busy out: {"); sep = ""; for (AbstractBinopExpr e : after) { System.out.print(sep); System.out.print(e.toString()); sep = ", "; } System.out.println("}"); System.out.println("---------------------------------------"); } System.out.println("======================================="); } } }
2,448
28.865854
74
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/analyses/FlowAnalysisTemplate.java
package dk.brics.soot.analyses; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.scalar.BackwardFlowAnalysis; // Change to extend ForwardFlowAnalysis or others as appropriate public class FlowAnalysisTemplate<N, A> extends BackwardFlowAnalysis<N, A> { public FlowAnalysisTemplate(DirectedGraph<N> g) { super(g); // some other initializations doAnalysis(); } @Override protected void merge(A in1, A in2, A out) { // must analysis => out <- in1 union in2 // may analysis => out <- in1 intersection in2 } @Override protected void copy(A source, A dest) { // copy from source to dest } @Override protected A newInitialFlow() { // return e.g., the empty set return null; } @Override protected A entryInitialFlow() { // return e.g., the empty set return null; } @Override protected void flowThrough(A in, N node, A out) { // perform flow from in to out, through node } }
926
21.071429
76
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/analyses/SimpleVeryBusyExpressions.java
package dk.brics.soot.analyses; import java.util.*; import dk.brics.soot.flowsets.ValueArraySparseSet; import soot.Local; import soot.Unit; import soot.ValueBox; import soot.jimple.BinopExpr; import soot.jimple.internal.AbstractBinopExpr; import soot.toolkits.graph.DirectedGraph; import soot.toolkits.scalar.BackwardFlowAnalysis; import soot.toolkits.scalar.FlowSet; public class SimpleVeryBusyExpressions implements VeryBusyExpressions { private Map<Unit, List<AbstractBinopExpr>> unitToExpressionsAfter; private Map<Unit, List<AbstractBinopExpr>> unitToExpressionsBefore; public SimpleVeryBusyExpressions(DirectedGraph<Unit> graph) { SimpleVeryBusyAnalysis analysis = new SimpleVeryBusyAnalysis(graph); unitToExpressionsAfter = new HashMap<Unit, List<AbstractBinopExpr>>(graph.size() * 2 + 1, 0.7f); unitToExpressionsBefore = new HashMap<Unit, List<AbstractBinopExpr>>(graph.size() * 2 + 1, 0.7f); for (Unit s : graph) { FlowSet set = (FlowSet) analysis.getFlowBefore(s); unitToExpressionsBefore.put(s, Collections.unmodifiableList(set.toList())); set = (FlowSet) analysis.getFlowAfter(s); unitToExpressionsAfter.put(s, Collections.unmodifiableList(set.toList())); } } public List<AbstractBinopExpr> getBusyExpressionsAfter(Unit s) { return unitToExpressionsAfter.get(s); } public List<AbstractBinopExpr> getBusyExpressionsBefore(Unit s) { List<AbstractBinopExpr> foo = unitToExpressionsBefore.get(s); return foo; } } /** * Performs a naiive version of a very-busy expressions analysis. * * @author rni Einarsson */ class SimpleVeryBusyAnalysis extends BackwardFlowAnalysis<Unit, FlowSet> { /** * Just for clarity. */ private FlowSet emptySet; public SimpleVeryBusyAnalysis(DirectedGraph<Unit> g) { // First obligation super(g); // NOTE: Would have expected to get the same results using a // regular ArraySparseSet, perhaps containing duplicates of // equivalent expressions. But that was not the case, results // are incorrect if using ArraySparseSet. This is because // we use intersection instead to merge sets, // and the ArraySparseSet.intersection implementation uses the method // contains to determine whether both sets contain the same element. // The contains method only compares references for equality. // (i.e. only if both sets contain the same reference is it included // in the intersecting set) emptySet = new ValueArraySparseSet(); // NOTE: It's possible to build up the kill and gen sets of each of // the nodes in the graph in advance. But in order to do so we // would have to build the universe set first. This requires an // extra pass through the unit graph, so we generate the kill and // gen sets lazily instead. // Second obligation doAnalysis(); } /** * This method performs the actual joining of successor nodes * (i.e. doAnalysis calls this method for each successor, * if there are more than one, of the current node). Since very * busy expressions is a <u>must</u> analysis we join by intersecting. * @param in1 a flow set flowing into the node * @param in2 a flow set flowing into the node * @param out the merged set */ @Override protected void merge(FlowSet in1, FlowSet in2, FlowSet out) { in1.intersection(in2, out); } @Override protected void copy(FlowSet source, FlowSet dest) { source.copy(dest); } /** * Used to initialize the in and out sets for each node. In * our case we want to build up the sets as we go, so we * initialize with the empty set. * </p><p> * Note: If we had information about all the possible values * the sets could contain, we could initialize with that and * then remove values during the analysis. * @return an empty set */ @Override protected FlowSet newInitialFlow() { return emptySet.clone(); } /** * Returns a flow set representing the initial set of the entry * node. In our case the entry node is the last node and it * should contain the empty set. * @return an empty set */ @Override protected FlowSet entryInitialFlow() { return emptySet.clone(); } /** * Adds to the out set the values that flow through the node * d from the in set. * </p><p> * This method has two phases, a kill phase and a gen phase. * The kill phase performs the following:<br /> * out = (in - expressions containing a reference to any local * defined in the node) union out.<br /> * The gen phase performs the following:<br /> * out = out union binary operator expressions used in the * node. * @param in the in-set of the current node * @param node the current node of the control flow graph * @param out the out-set of the current node */ @Override protected void flowThrough(FlowSet in, Unit node, FlowSet out) { // out <- (in - expr containing locals defined in d) union out kill(in, node, out); // out <- out union expr used in d gen(out, node); } /** * Performs kills by generating a killSet and then performing<br/> * outSet <- inSet - killSet<br/> * The kill set is generated by iterating over the def-boxes * of the unit. For each local defined in the unit we iterate * over the binopExps in the inSet, and check whether they use * that local. If so, it is added to the kill set. * @param inSet the set flowing into the unit * @param u the unit being flown through * @param outSet the set flowing out of the unit */ private void kill(FlowSet inSet, Unit u, FlowSet outSet) { FlowSet kills = emptySet.clone(); for (ValueBox defBox : u.getDefBoxes()) { if (defBox.getValue() instanceof Local) { Iterator<BinopExpr> inIt = inSet.iterator(); while (inIt.hasNext()) { BinopExpr e = inIt.next(); Iterator<ValueBox> eIt = e.getUseBoxes().iterator(); while (eIt.hasNext()) { ValueBox useBox = eIt.next(); if (useBox.getValue() instanceof Local && useBox.getValue().equivTo(defBox.getValue())) kills.add(e); } } } } inSet.difference(kills, outSet); } /** * Performs gens by iterating over the units use-boxes. * If the value of a use-box is a binopExp then we add * it to the outSet. * @param outSet the set flowing out of the unit * @param u the unit being flown through */ private void gen(FlowSet outSet, Unit u) { for (ValueBox useBox : u.getUseBoxes()) { if (useBox.getValue() instanceof BinopExpr) outSet.add(useBox.getValue()); } } }
6,456
31.285
99
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/analyses/VeryBusyExpressions.java
package dk.brics.soot.analyses; import java.util.List; import soot.Unit; import soot.jimple.internal.AbstractBinopExpr; /** * Provides an interface for querying the expressions that are very busy * before and after a unit in a method. * @author rni Einarsson */ public interface VeryBusyExpressions { /** * Returns the list of expressions that are very busy before the specified * Unit. * @param s the Unit that defines this query. * @return a list of expressions that are busy before the specified unit in the method. */ public List<AbstractBinopExpr> getBusyExpressionsBefore(Unit s); /** * Returns the list of expressions that are very busy after the specified * Unit. * @param s the Unit that defines this query. * @return a list of expressions that are very busy after the specified unit in the method. */ public List<AbstractBinopExpr> getBusyExpressionsAfter(Unit s); }
973
31.466667
97
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/annotations/TagBusyExpressions.java
package dk.brics.soot.annotations; import dk.brics.soot.transformations.VeryBusyExpsTagger; import soot.*; public class TagBusyExpressions { public static void main(String[] args) { PackManager.v().getPack("jtp").add(new Transform("jtp." + VeryBusyExpsTagger.PHASE_NAME, VeryBusyExpsTagger.v())); Main.main(args); } }
340
20.3125
56
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/flowsets/ValueArraySparseSet.java
package dk.brics.soot.flowsets; import java.util.Arrays; import java.util.List; import soot.toolkits.scalar.AbstractFlowSet; import soot.toolkits.scalar.FlowSet; import soot.EquivTo; /** * This class is the exact copy of soot.toolkits.scalar.ArraySparseSet with two exceptions. * <ol> * <li>The contains method has been modified to check whether the element being compared * implements the soot.EquivTo interface, and if so then use the soot.EquivTo.equivTo * method for comparison.<br/> * soot.Value extends soot.EquivTo, so it only makes sense to take advantage of that * instead of using the more naiive equals method inherited from Object (only comparing * references).</li> * <li>All fields and methods declared as private, changed to protected.</li> * </ol> * @author Changes made by rni Einarsson * */public class ValueArraySparseSet extends AbstractFlowSet { protected static final int DEFAULT_SIZE = 8; protected int numElements; protected int maxElements; protected Object[] elements; public ValueArraySparseSet() { maxElements = DEFAULT_SIZE; elements = new Object[DEFAULT_SIZE]; numElements = 0; } protected ValueArraySparseSet(ValueArraySparseSet other) { numElements = other.numElements; maxElements = other.maxElements; elements = (Object[]) other.elements.clone(); } /** Returns true if flowSet is the same type of flow set as this. */ protected boolean sameType(Object flowSet) { return (flowSet instanceof ValueArraySparseSet); } public ValueArraySparseSet clone() { return new ValueArraySparseSet(this); } public Object emptySet() { return new ValueArraySparseSet(); } public void clear() { numElements = 0; } public int size() { return numElements; } public boolean isEmpty() { return numElements == 0; } /** Returns a unbacked list of elements in this set. */ public List<Object> toList() { Object[] copiedElements = new Object[numElements]; System.arraycopy(elements, 0, copiedElements, 0, numElements); return Arrays.asList(copiedElements); } /* * Expand array only when necessary, pointed out by Florian Loitsch March * 08, 2002 */ public void add(Object e) { /* Expand only if necessary! and removes one if too:) */ // Add element if (!contains(e)) { // Expand array if necessary if (numElements == maxElements) doubleCapacity(); elements[numElements++] = (Object)e; } } protected void doubleCapacity() { int newSize = maxElements * 2; Object[] newElements = new Object[newSize]; System.arraycopy(elements, 0, newElements, 0, numElements); elements = newElements; maxElements = newSize; } public void remove(Object obj) { int i = 0; while (i < this.numElements) { if (elements[i].equals(obj)) { elements[i] = elements[--numElements]; return; } else i++; } } public void union(FlowSet otherFlow, FlowSet destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ValueArraySparseSet other = (ValueArraySparseSet) otherFlow; ValueArraySparseSet dest = (ValueArraySparseSet) destFlow; // For the special case that dest == other if (dest == other) { for (int i = 0; i < this.numElements; i++) dest.add(this.elements[i]); } // Else, force that dest starts with contents of this else { if (this != dest) copy(dest); for (int i = 0; i < other.numElements; i++) dest.add(other.elements[i]); } } else super.union(otherFlow, destFlow); } public void intersection(FlowSet otherFlow, FlowSet destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ValueArraySparseSet other = (ValueArraySparseSet) otherFlow; ValueArraySparseSet dest = (ValueArraySparseSet) destFlow; ValueArraySparseSet workingSet; if (dest == other || dest == this) workingSet = new ValueArraySparseSet(); else { workingSet = dest; workingSet.clear(); } for (int i = 0; i < this.numElements; i++) { if (other.contains(this.elements[i])) workingSet.add(this.elements[i]); } if (workingSet != dest) workingSet.copy(dest); } else super.intersection(otherFlow, destFlow); } public void difference(FlowSet otherFlow, FlowSet destFlow) { if (sameType(otherFlow) && sameType(destFlow)) { ValueArraySparseSet other = (ValueArraySparseSet) otherFlow; ValueArraySparseSet dest = (ValueArraySparseSet) destFlow; ValueArraySparseSet workingSet; if (dest == other || dest == this) workingSet = new ValueArraySparseSet(); else { workingSet = dest; workingSet.clear(); } for (int i = 0; i < this.numElements; i++) { if (!other.contains(this.elements[i])) workingSet.add(this.elements[i]); } if (workingSet != dest) workingSet.copy(dest); } else super.difference(otherFlow, destFlow); } public boolean contains(Object obj) { for (int i = 0; i < numElements; i++) if (elements[i] instanceof EquivTo && ((EquivTo) elements[i]).equivTo(obj)) return true; else if (elements[i].equals(obj)) return true; return false; } public boolean equals(Object otherFlow) { if (sameType(otherFlow)) { ValueArraySparseSet other = (ValueArraySparseSet) otherFlow; if (other.numElements != this.numElements) return false; int size = this.numElements; // Make sure that thisFlow is contained in otherFlow for (int i = 0; i < size; i++) if (!other.contains(this.elements[i])) return false; /* * both arrays have the same size, no element appears twice in one * array, all elements of ThisFlow are in otherFlow -> they are * equal! we don't need to test again! // Make sure that otherFlow * is contained in ThisFlow for(int i = 0; i < size; i++) * if(!this.contains(other.elements[i])) return false; */ return true; } else return super.equals(otherFlow); } public void copy(FlowSet destFlow) { if (sameType(destFlow)) { ValueArraySparseSet dest = (ValueArraySparseSet) destFlow; while (dest.maxElements < this.maxElements) dest.doubleCapacity(); dest.numElements = this.numElements; System.arraycopy(this.elements, 0, dest.elements, 0, this.numElements); } else super.copy(destFlow); } }
6,220
25.699571
91
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/dk/brics/soot/transformations/VeryBusyExpsTagger.java
package dk.brics.soot.transformations; import java.util.Map; import dk.brics.soot.analyses.SimpleVeryBusyExpressions; import dk.brics.soot.analyses.VeryBusyExpressions; import soot.*; import soot.tagkit.ColorTag; import soot.tagkit.StringTag; import soot.toolkits.graph.ExceptionalUnitGraph; public class VeryBusyExpsTagger extends BodyTransformer { public static final String PHASE_NAME = "vbetagger"; public static final String TAG_TYPE = "Busy Expressions"; // NOTE: According to SOOT coding rules, this is not the correct way of // providing a singleton. Instead one should add the class name to // %SOOTHOME/src/singletons.list and then run: // %SOOTHOME/src/make_singletons > soot/src/soot/Singletons.java // and then provide: // 1. public VeryBusyExpsTagger(Singletons.G.global g) {} // 2. public static VeryBusyExpsTagger v() {return G.v().<singleton_name>} // This is so that when resetting soot by calling G.v().reset() this // class will also be reset. (But there's nothing to reset here so // I'll ignore that for now :) ) private static VeryBusyExpsTagger instance = new VeryBusyExpsTagger(); private VeryBusyExpsTagger() {} public static VeryBusyExpsTagger v() {return instance;} /** * Adds <code>StringTag</code>s and <code>ColorTag</code>s to the body * in the interest of using Eclipse to relay information to the user.<br/> * Every unit that has a busy expression flowing out of it, gets a * <code>StringTag</code> describing that fact (per expression). * If an expression that is busy out of that unit is also used within * it, then we add a <code>ColorTag</code> to that expression. * @param b the body to transform * @param phaseName the name of the phase this transform belongs to * @param options any options to this transform (in this case always empty) */ protected void internalTransform(Body b, String phaseName, Map options) { VeryBusyExpressions vbe = new SimpleVeryBusyExpressions(new ExceptionalUnitGraph(b)); for (Unit u : b.getUnits()) { for (Value v : vbe.getBusyExpressionsAfter(u)) { u.addTag(new StringTag("Busy expression: " + v, TAG_TYPE)); for (ValueBox use : u.getUseBoxes()) { if (use.getValue().equivTo(v)) use.addTag(new ColorTag(ColorTag.RED, TAG_TYPE)); } } } } }
2,302
39.403509
87
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/testers/LiveVarsClass.java
package testers; public class LiveVarsClass { public static void main(String[] args) { int x, y, z; x = 10; while (x > 1) { y = x/2; if (y > 3) x = x - y; z = x - 4; if (z > 0) x = x/2; z = z - 1; } System.out.println(x); } }
254
14
41
java
soot
soot-master/tutorial/guide/examples/analysis_framework/src/testers/VeryBusyClass.java
package testers; public class VeryBusyClass { public static void main(String[] args) { int x = 10; int a = x - 1; int b = x - 2; while (x > 0) { System.out.println(a*b - x); x = x - 1; } System.out.println(a*b); } }
239
13.117647
42
java
soot
soot-master/tutorial/guide/examples/call_graph/src/dk/brics/soot/callgraphs/CallGraphExample.java
package dk.brics.soot.callgraphs; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import soot.MethodOrMethodContext; import soot.PackManager; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootMethod; import soot.Transform; import soot.jimple.toolkits.callgraph.CHATransformer; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Targets; public class CallGraphExample { public static void main(String[] args) { List<String> argsList = new ArrayList<String>(Arrays.asList(args)); argsList.addAll(Arrays.asList(new String[]{ "-w", "-main-class", "testers.CallGraphs",//main-class "testers.CallGraphs",//argument classes "testers.A" // })); PackManager.v().getPack("wjtp").add(new Transform("wjtp.myTrans", new SceneTransformer() { @Override protected void internalTransform(String phaseName, Map options) { CHATransformer.v().transform(); SootClass a = Scene.v().getSootClass("testers.A"); SootMethod src = Scene.v().getMainClass().getMethodByName("doStuff"); CallGraph cg = Scene.v().getCallGraph(); Iterator<MethodOrMethodContext> targets = new Targets(cg.edgesOutOf(src)); while (targets.hasNext()) { SootMethod tgt = (SootMethod)targets.next(); System.out.println(src + " may call " + tgt); } } })); args = argsList.toArray(new String[0]); soot.Main.main(args); } }
1,632
27.649123
94
java
soot
soot-master/tutorial/guide/examples/call_graph/src/testers/CallGraphs.java
package testers; public class CallGraphs { public static void main(String[] args) { doStuff(); } public static void doStuff() { new A().foo(); } } class A { public void foo() { bar(); } public void bar() { } }
229
9.454545
41
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/foo/Foo.java
package dk.brics.soot.intermediate.foo; public class Foo { private int i; public Foo() { i = 7; } public void foo(int j) { i = j; } public int getInt() { return i; } }
191
8.6
39
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/foo/FooTest.java
package dk.brics.soot.intermediate.foo; public class FooTest { public static void main(String[] args) { FooTest ft = new FooTest(); System.out.println(ft.test()); } public int test() { Foo f = new Foo(); f.foo(9); FooTest ft = new FooTest(); f = g(42); int i = m(f); return f.getInt(); } public int m(Foo f) { int s = f.getInt(); return s; } public Foo g(int x) { Foo d = new Foo(); d.foo(x); return d; } }
454
13.21875
41
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/foonalasys/FooCallgraphCreator.java
package dk.brics.soot.intermediate.foonalasys; import dk.brics.soot.intermediate.representation.Method; import soot.util.dot.DotGraph; public class FooCallgraphCreator { public FooCallgraphCreator(Method[] methods) { // TODO Auto-generated constructor stub } public DotGraph getCallGraphAsDot() { return null; } }
327
18.294118
56
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/foonalasys/Foonalasys.java
package dk.brics.soot.intermediate.foonalasys; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import dk.brics.soot.intermediate.representation.Method; import dk.brics.soot.intermediate.representation.Statement; import dk.brics.soot.intermediate.translation.JavaTranslator; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.ValueBox; import soot.jimple.toolkits.callgraph.CallGraph; import soot.util.dot.DotGraph; /** A <code>Foonalysis</code> object encapsulates a foonalysis performed * on a collection of classes. * The class also contains some convenience methods for loading and traversing * the classes to be analyzed.<p> */ public class Foonalasys { private static final boolean DEBUG = false; private JavaTranslator jt; private Map/*<ValueBox,String>*/ sourcefile_map; private Map/*<ValueBox,String>*/ class_map; private Map/*<ValueBox,String>*/ method_map; private Map/*<ValueBox,Integer>*/ line_map; // Make sure we get line numbers static { soot.Scene.v().loadBasicClasses(); soot.options.Options.v().parse(new String[] { "-keep-line-number" }); } /** Performs a foonalysis on the current application classes. * @throws IOException */ public Foonalasys() { jt = new JavaTranslator(); debug("Translating classes to intermediate form..."); Method[] methods = jt.translateApplicationClasses(); for (Method m: methods) { System.out.println("Method: "+m.getName()+":"); Collection<Statement> stmts = m.getEntry().getSuccs(); printStmts(stmts); System.out.println("------------------------"); } debug("Foonalasys done"); } private void printStmts(Collection<Statement> stmts) { for (Statement stmt: stmts) { System.out.println("stmt: "+" "+stmt); printStmts(stmt.getSuccs()); } } /** Returns the name of the source file containing the given expression. * @param box the expression. * @return the source file name. */ public final String getSourceFile(ValueBox box) { return (String)sourcefile_map.get(box); } /** Returns the name of the class containing the given expression. * @param box the expression. * @return the fully qualified class name. */ public final String getClassName(ValueBox box) { return (String)class_map.get(box); } /** Returns the name of the method containing the given expression. * @param box the expression. * @return the method name. */ public final String getMethodName(ValueBox box) { return (String)method_map.get(box); } /** Returns the source line number of the given expression. * @param box the expression. * @return the line number. */ public final int getLineNumber(ValueBox box) { return ((Integer)line_map.get(box)).intValue(); } /** Loads the named class into the Soot scene, * marks it as an application class, and generates bodies * for all of its concrete methods. * @param name the fully qualified name of the class to be loaded. */ public static void loadClass(String name) { SootClass c = Scene.v().loadClassAndSupport(name); c.setApplicationClass(); Iterator mi = c.getMethods().iterator(); while (mi.hasNext()) { SootMethod sm = (SootMethod)mi.next(); if (sm.isConcrete()) { sm.retrieveActiveBody(); } } } private void debug(String s) { if (DEBUG) { System.err.println(s); } } }
3,621
28.688525
79
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/main/Main.java
package dk.brics.soot.intermediate.main; import java.io.IOException; import dk.brics.soot.intermediate.foonalasys.*; public class Main { public static void main(String[] args) throws IOException { String program_name = null; long time0 = System.currentTimeMillis(); System.out.println("Loading classes..."); for (int i = 0 ; i < args.length ; i++) { String classname = args[i]; if (classname.endsWith(".class")) { classname = classname.substring(0,classname.length()-6).replace('/','.'); } Foonalasys.loadClass(classname); if (program_name == null) { program_name = classname; } } long time1 = System.currentTimeMillis(); System.out.println("Analyzing..."); System.out.flush(); Foonalasys fn = new Foonalasys(); long time2 = System.currentTimeMillis(); long time3 = System.currentTimeMillis(); System.out.println("Loading time: "+time(time1-time0)); System.out.println("Analysis time: "+time(time2-time1)); System.out.println("Extraction time: "+time(time3-time2)); } private static String time(long t) { return t/1000 + "." + String.valueOf(1000+(t%1000)).substring(1); } }
1,166
24.369565
77
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/FooAssignment.java
package dk.brics.soot.intermediate.representation; public class FooAssignment extends Statement { @Override public <T> T process(StatementProcessor<T> v) { return v.dispatch(this); } }
194
16.727273
50
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/FooInit.java
package dk.brics.soot.intermediate.representation; public class FooInit extends Statement { @Override public <T> T process(StatementProcessor<T> v) { return v.dispatch(this); } }
187
16.090909
50
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/FooMethodCall.java
package dk.brics.soot.intermediate.representation; public class FooMethodCall extends MethodCall { public FooMethodCall(Method target) { super(target, new Variable[0]); } @Override public <T> T process(StatementProcessor<T> v) { return v.dispatch(this); } }
271
17.133333
50
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/Method.java
package dk.brics.soot.intermediate.representation; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import soot.SootMethod; public class Method { private String name = ""; private Variable[] params; private List<Statement> sl; private Set<Return> rs; private List<MethodCall> sites; private MethodHead entry; public Method(String name, Variable[] params) { this.name = name; this.params = params; sl = new LinkedList<Statement>(); rs = new HashSet<Return>(); sites = new LinkedList<MethodCall>(); entry = new MethodHead(params); } public MethodHead getEntry() { return this.entry; } /** Adds the given statement to the list of statements for this method. * @param s the statement to add. */ public void addStatement(Statement s) { s.setIndex(sl.size()); sl.add(s); s.setMethod(this); if (s instanceof Return) { rs.add((Return) s); } if (s instanceof MethodCall) { MethodCall mc = (MethodCall) s; mc.getTarget().sites.add(mc); } } public String getName() { return name; } public String toString() { String result = ""; for (Statement s: sl) { result += s.toString()+"\n"; } return result; } }
1,319
20.639344
75
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/MethodCall.java
package dk.brics.soot.intermediate.representation; public abstract class MethodCall extends Statement { /** The target method */ private Method target; /** The arguments given */ private Variable[] args; public MethodCall(Method target, Variable[] args) { this.target = target; this.args = args; } public Method getTarget() { return target; } public Variable[] getArgs() { return args; } public void setArgs(Variable[] args) { this.args = args; } }
517
16.266667
55
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/MethodHead.java
package dk.brics.soot.intermediate.representation; public class MethodHead extends Statement { /** The parameter variables for the method */ public Variable[] params; public MethodHead(Variable[] params) { this.params = params; } @Override public <T> T process(StatementProcessor<T> v) { return v.dispatch(this); } public String toString() { String res = ""; for (Variable v: params) { res += v; } return res; } }
461
16.769231
50
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/Nop.java
package dk.brics.soot.intermediate.representation; public class Nop extends Statement { @Override public <T> T process(StatementProcessor<T> v) { return v.dispatch(this); } }
183
15.727273
50
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/Return.java
package dk.brics.soot.intermediate.representation; public class Return extends Statement { @Override public <T> T process(StatementProcessor<T> v) { return v.dispatch(this); } }
187
16.090909
50
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/SomeMethodCall.java
package dk.brics.soot.intermediate.representation; public class SomeMethodCall extends MethodCall { public SomeMethodCall(Method target, Variable[] args) { super(target, args); } @Override public <T> T process(StatementProcessor<T> v) { return v.dispatch(this); } }
281
16.625
56
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/Statement.java
package dk.brics.soot.intermediate.representation; import java.util.*; import dk.brics.soot.intermediate.representation.Variable.Type; /** Superclass of all statements. * <p> * A statements belongs to the body of some method. * It has control flow edges to and from other statements. */ public abstract class Statement { private Collection<Statement> succs; private Collection<Statement> preds; /* The method whose body contains this statement. */ protected Method method; protected int index; /* * The target variable for assignment statements */ protected Variable assignmentTarget; public Statement() { succs = new LinkedList<Statement>(); preds = new LinkedList<Statement>(); this.assignmentTarget = new Variable(Type.OTHER); } /** Adds a control flow edge from this statement to the given. * @param s the target statement of the edge. */ public void addSucc(Statement s) { succs.add(s); s.addPred(this); } void addPred(Statement s) { preds.add(s); } /** Returns all targets of control flow edges * originating from this node. * @return a collection of {@link dk.brics.soot.intermediate.Statement} objects. */ public Collection<Statement> getSuccs() { return succs; } /** Returns all origins of control flow edges * going to this node. * @return a collection of {@link dk.brics.soot.intermediate.Statement} objects. */ public Collection<Statement> getPreds() { return preds; } /** * Set the method whose body contains this statement. */ void setMethod(Method m) { method = m; } /** * Returns the method whose body contains this statement. * @return the method. */ public Method getMethod() { return method; } void setIndex(int index) { this.index = index; } /** Returns the index of this statement, indicating the sequence * number in which the statement was added to its method. * @return the index. */ public int getIndex() { return index; } /** Returns a string representation of this statement. * This is handled by a {@link dk.brics.soot.intermediate.ToStringVisitor}. * @return the statement as a string. */ public String toString() { ToStringVisitor tsv = new ToStringVisitor(); return process(tsv); } /** * Visit this statement by the given statement visitor. * This will invoke the corresponding method in the visitor. * @param <T> return type * @param v Entry processor * @return result from processor */ abstract public <T> T process(StatementProcessor<T> v); public Variable getAssignmentTarget() { return assignmentTarget; } public void setAssignmentTarget(Variable assignmentTarget) { this.assignmentTarget = assignmentTarget; } }
2,729
23.375
82
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/StatementProcessor.java
package dk.brics.soot.intermediate.representation; public class StatementProcessor<T> { /** * Constructs a new Statement processor. */ public StatementProcessor() {} /** * Processes an {@link FooMethodCall}. * This invokes {@link #pre(Statment)}, * if that returns null then {@link #process(FooMethodCall)} is invoked, * Finally, {@link #post(Statement, Object)} is invoked. * @param s Statement * @return result */ public T dispatch(FooMethodCall s) { T t = pre(s); if (t == null) t = process(s); post(s, t); return t; } /** * Processes an {@link SomeMethodCall}. * This invokes {@link #pre(Statment)}, * if that returns null then {@link #process(SomeMethodCall)} is invoked, * Finally, {@link #post(Statement, Object)} is invoked. * @param s Statement * @return result */ public T dispatch(SomeMethodCall s) { T t = pre(s); if (t == null) t = process(s); post(s, t); return t; } /** * Processes an {@link FooInit}. * This invokes {@link #pre(Statment)}, * if that returns null then {@link #process(FooInit)} is invoked, * Finally, {@link #post(Statement, Object)} is invoked. * @param s Statement * @return result */ public T dispatch(FooInit s) { T t = pre(s); if (t == null) t = process(s); post(s, t); return t; } /** * Processes an {@link FooAssignment}. * This invokes {@link #pre(Statment)}, * if that returns null then {@link #process(FooAssignment)} is invoked, * Finally, {@link #post(Statement, Object)} is invoked. * @param s Statement * @return result */ public T dispatch(FooAssignment s) { T t = pre(s); if (t == null) t = process(s); post(s, t); return t; } /** * Processes an {@link Return}. * This invokes {@link #pre(Statment)}, * if that returns null then {@link #process(Return)} is invoked, * Finally, {@link #post(Statement, Object)} is invoked. * @param s Statement * @return result */ public T dispatch(Return s) { T t = pre(s); if (t == null) t = process(s); post(s, t); return t; } /** * Processes an {@link Nop}. * This invokes {@link #pre(Statment)}, * if that returns null then {@link #process(Nop)} is invoked, * Finally, {@link #post(Statement, Object)} is invoked. * @param s Statement * @return result */ public T dispatch(Nop s) { T t = pre(s); if (t == null) t = process(s); post(s, t); return t; } /** * Processes an {@link MethodHead}. * This invokes {@link #pre(Statment)}, * if that returns null then {@link #process(MethodHead)} is invoked, * Finally, {@link #post(Statement, Object)} is invoked. * @param s Statement * @return result */ public T dispatch(MethodHead s) { T t = pre(s); if (t == null) t = process(s); post(s, t); return t; } /** * Method to be invoked for processing an {@link FooMethodCall}. * By default, nothing happens and null is returned. * @param s current Statement * @return result */ public T process(FooMethodCall s) { return null; } /** * Method to be invoked for processing an {@link SomeMethodCall}. * By default, nothing happens and null is returned. * @param s current Statement * @return result */ public T process(SomeMethodCall s) { return null; } /** * Method to be invoked for processing an {@link FooInit}. * By default, nothing happens and null is returned. * @param s current Statement * @return result */ public T process(FooInit s) { return null; } /** * Method to be invoked for processing an {@link FooAssignment}. * By default, nothing happens and null is returned. * @param s current Statement * @return result */ public T process(FooAssignment s) { return null; } /** * Method to be invoked for processing an {@link Return}. * By default, nothing happens and null is returned. * @param s current Statement * @return result */ public T process(Return s) { return null; } /** * Method to be invoked for processing an {@link Nop}. * By default, nothing happens and null is returned. * @param s current Statement * @return result */ public T process(Nop s) { return null; } /** * Method to be invoked for processing an {@link MethodHead}. * By default, nothing happens and null is returned. * @param s current Statement * @return result */ public T process(MethodHead s) { return null; } /** * Method to be invoked for preprocessing a {@link Statement}. * By default, nothing happens and null is returned. * @param s current Statement * @return result */ public T pre(Statement s) { return null; } /** * Method to be invoked for postprocessing a {@link Statement}. * By default, nothing happens. * @param s current Statment * @param t result from <code>process</code> */ public void post(Statement s, T t) {} }
4,881
21.706977
75
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/ToStringVisitor.java
package dk.brics.soot.intermediate.representation; public class ToStringVisitor extends StatementProcessor<String> { @Override public String process(FooMethodCall s) { return ""+s.getAssignmentTarget()+" = "+s.getTarget().getName()+"()"; } @Override public String process(SomeMethodCall s) { return ""+s.getTarget().getName()+"("+getArgs(s.getArgs())+")"; } private String getArgs(Variable[] args) { String s = ""; for (Variable v: args) { //System.err.println(v); s += v.toString()+", "; } if (s.length()>2) return s.substring(0, s.length()-2); return s; } @Override public String process(FooInit s) { return ""+s.getAssignmentTarget()+" = new Foo();"; } @Override public String process(FooAssignment s) { return ""+"f = f"; } @Override public String process(Return s) { if (s.getAssignmentTarget() != null) return "return "+s.getAssignmentTarget(); return "return"; } @Override public String process(Nop s) { return "nop"; } @Override public String process(MethodHead s) { return "methodhead"; } }
1,076
19.320755
71
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/representation/Variable.java
package dk.brics.soot.intermediate.representation; public class Variable { public enum Type {OTHER, FOO}; public Type type; public Variable(Type type) { this.type = type; } public String toString() { switch (this.type) { case FOO: return "Foo f"; case OTHER: return "Other f"; } return "null"; } }
327
13.909091
50
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/translation/ExprTranslator.java
package dk.brics.soot.intermediate.translation; import java.util.Collections; import java.util.Iterator; import java.util.List; import soot.IntType; import soot.Local; import soot.RefType; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.Value; import soot.ValueBox; import soot.jimple.ArrayRef; import soot.jimple.InstanceFieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InterfaceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.NewExpr; import soot.jimple.NullConstant; import soot.jimple.ParameterRef; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticFieldRef; import soot.jimple.StaticInvokeExpr; import soot.jimple.StringConstant; import soot.jimple.VirtualInvokeExpr; import dk.brics.soot.intermediate.representation.FooAssignment; import dk.brics.soot.intermediate.representation.FooInit; import dk.brics.soot.intermediate.representation.FooMethodCall; import dk.brics.soot.intermediate.representation.Method; import dk.brics.soot.intermediate.representation.SomeMethodCall; import dk.brics.soot.intermediate.representation.Nop; import dk.brics.soot.intermediate.representation.Statement; import dk.brics.soot.intermediate.representation.Variable; public class ExprTranslator extends soot.jimple.AbstractJimpleValueSwitch { private JavaTranslator jt; private StmtTranslator st; private Variable res_var; public ExprTranslator(JavaTranslator jt, StmtTranslator st) { this.jt = jt; this.st = st; } // Called for any type of value public void translateExpr(Variable var, ValueBox box) { Value val = box.getValue(); Variable temp = res_var; res_var = var; val.apply(this); res_var = temp; } public void caseLocal(Local expr) { assign(res_var, st.getLocalVariable(expr)); } public void caseArrayRef(ArrayRef expr) { jt.notSupported("Array references are not supported"); } public void caseInstanceFieldRef(InstanceFieldRef expr) { jt.notSupported("Instance field references are not supported"); } public void caseStaticFieldRef(StaticFieldRef expr) { st.addStatement(new Nop()); } public void caseParameterRef(ParameterRef expr) { st.addStatement(new Nop()); } public void caseNullConstant(NullConstant expr) { jt.notSupported("The null constant is not supported"); } public void caseStringConstant(StringConstant expr) { jt.notSupported("String constants are not supported"); } public void caseNewExpr(NewExpr expr) { st.addStatement(new Nop()); } public void caseSpecialInvokeExpr(SpecialInvokeExpr expr) { // Constructor calls, maybe Variable bvar = st.getLocalVariable((Local)expr.getBase()); SootMethod m = expr.getMethod(); if (m.getName().equals("<init>")) { SootClass dc = m.getDeclaringClass(); if (isFoo(dc)) { FooInit fi = new FooInit(); fi.setAssignmentTarget(bvar); st.addStatement(fi); return; } } handleCall(expr, expr.getMethod()); } public void caseStaticInvokeExpr(StaticInvokeExpr expr) { handleCall(expr, expr.getMethod()); } public void caseInterfaceInvokeExpr(InterfaceInvokeExpr expr) { caseInstanceInvokeExpr(expr); } public void caseVirtualInvokeExpr(VirtualInvokeExpr expr) { caseInstanceInvokeExpr(expr); } void caseInstanceInvokeExpr(InstanceInvokeExpr expr) { List<SootMethod> targets = jt.getTargetsOf(expr); if (targets.isEmpty()) { // This is a call to an interface method or abstract method // with no available implementations. // You could use instruction target as target. jt.notSupported("We don't support abstract methods"); } for (SootMethod target: targets) { boolean special = handleSpecialCall(expr, target); if (!special) { handleCall(expr, target); } } } void assign(Variable lvar, Variable rvar) { switch (lvar.type) { case FOO: FooAssignment fa = new FooAssignment(); fa.setAssignmentTarget(lvar); st.addStatement(fa); return; } } boolean isString(Type t) { return t.equals(RefType.v(JavaTranslator.FOOQUALIFIEDNAME)); } boolean isFoo(SootClass c) { return c.getName().equals(JavaTranslator.FOOQUALIFIEDNAME); } boolean isStringBuffer(Type t) { return t.equals(RefType.v(JavaTranslator.FOOQUALIFIEDNAME)); } boolean isStringBuffer(SootClass c) { return c.getName().equals(JavaTranslator.FOOQUALIFIEDNAME); } // For a single target, foo-type or not, non-special void handleCall(InvokeExpr expr, SootMethod target) { SootClass dc = target.getDeclaringClass(); if (jt.isApplicationClass(dc)) { if (!dc.isInterface()) { // Target in an application class. // Setup call to translated method. Method method = jt.methodsignaturToMethod.get(target.getSignature()); SomeMethodCall smc = new SomeMethodCall(method, getArgs(target)); st.addStatement(smc); } else { // Call to interface method or abstract method as target. // Only occurs if no implementions are found. // Arguments are evaluated and nothing is returned. jt.notSupported("We don't support interface calls"); } } else { // Target in non-application class. // We should Escape all arguments and corrupt result. // So this might not be what we want. Method method = new Method(target.getName(), getArgs(target)); SomeMethodCall smc = new SomeMethodCall(method, getArgs(target)); st.addStatement(smc); return; } } // any type boolean handleSpecialCall(InstanceInvokeExpr expr, SootMethod target) { String mn = target.getName(); int np = target.getParameterCount(); SootClass dc = target.getDeclaringClass(); // Is it a method in a Foo object? if (isFoo(dc)) { if (mn.equals("foo") && np == 1){ Variable lvar = new Variable(Variable.Type.FOO); Method foo = new Method("foo", new Variable[0]); FooMethodCall fmc = new FooMethodCall(foo); fmc.setAssignmentTarget(lvar); st.addStatement(fmc); return true; } // Unknown Foo method return false; } // Not a special call return false; } public Variable[] getArgs(SootMethod target) { Variable[] vars = new Variable[target.getParameterCount()]; for (int i= 0; i<target.getParameterCount(); i++) { vars[i] = jt.makeVariable(target.getParameterType(i)); } return vars; } }
6,296
27.493213
75
java
soot
soot-master/tutorial/guide/examples/intermediate_representation/src/dk/brics/soot/intermediate/translation/JavaTranslator.java
package dk.brics.soot.intermediate.translation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import soot.ArrayType; import soot.Hierarchy; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.Value; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import soot.toolkits.graph.CompleteUnitGraph; import dk.brics.soot.intermediate.representation.Method; import dk.brics.soot.intermediate.representation.Statement; import dk.brics.soot.intermediate.representation.Variable; @SuppressWarnings("unchecked") public class JavaTranslator { private Hierarchy h; private List<Method> methods = new LinkedList<Method>(); StmtTranslator st; Map<String,Method> methodsignaturToMethod = new HashMap<String, Method>(); public static final String FOOQUALIFIEDNAME = "dk.brics.soot.intermediate.foo.Foo"; public Method[] translateApplicationClasses() { h = new Hierarchy(); makeMethods(); translate(); return methods.toArray(new Method[0]); } private void translate() { st = new StmtTranslator(this); Collection<SootClass> app = Scene.v().getApplicationClasses(); for (SootClass ac: app) { st.setCurrentClass(ac); List<SootMethod> sootMethods = ac.getMethods(); for (SootMethod sm: sootMethods) { if (sm.isConcrete()) { Method method = methodsignaturToMethod.get(sm.getSignature()); st.setCurrentMethod(sm); CompleteUnitGraph cug = new CompleteUnitGraph(sm.retrieveActiveBody()); Iterator si = cug.iterator(); while (si.hasNext()) { Stmt stmt = (Stmt)si.next(); st.translateStmt(stmt); } //System.err.println("Setting up link between entry and first stmt of the method..."); si = cug.getHeads().iterator(); while (si.hasNext()) { Stmt stmt = (Stmt)si.next(); method.getEntry().addSucc(st.getFirst(stmt)); } si = cug.iterator(); //System.err.println("Setting up link between the last statement and the first statement..."); while (si.hasNext()) { Stmt stmt = (Stmt)si.next(); Iterator si2 = cug.getSuccsOf(stmt).iterator(); while (si2.hasNext()) { Stmt stmt2 = (Stmt)si2.next(); st.getLast(stmt).addSucc(st.getFirst(stmt2)); } } // System.err.println("!!!!!!!!!!!!!!!!!!"+sm.getName()+"!!!!!!!!!!!!!!!!!!!!"); // si = cug.iterator(); // while (si.hasNext()) { // Stmt stmt = (Stmt)si.next(); // System.err.println("The stmt: "+stmt+" translates to "+st.getFirst(stmt)); // //System.err.println(st.getFirst(stmt).getSuccs()); // } // System.err.println("######################################"); } } } } void makeMethods() { Collection<SootClass> app = Scene.v().getApplicationClasses(); for(SootClass ac: app) { List<SootMethod> sootMethods = ac.getMethods(); for (SootMethod sm: sootMethods) { List<Variable> vars = new LinkedList<Variable>(); List<Type> params = sm.getParameterTypes(); for (Type pt: params) { Variable v = makeVariable(pt); vars.add(v); } Variable[] var_array = (Variable[])vars.toArray(new Variable[0]); Method m = new Method(sm.getName(), var_array); methods.add(m); methodsignaturToMethod.put(sm.getSignature(), m); } } } Variable makeVariable(Value v) { return makeVariable(v.getType()); } Variable makeVariable(Type t) { Variable.Type type = getType(t); return new Variable(type); } public boolean isFooType(Value v) { return isFooType(v.getType()); } public boolean isFooType(Type t) { return getType(t) != Variable.Type.OTHER; } public List<SootMethod> getTargetsOf(InvokeExpr expr) { if (expr instanceof InstanceInvokeExpr) { return getTargetsOf(((InstanceInvokeExpr)expr).getBase(), expr.getMethod()); } List<SootMethod> targets = new ArrayList(1); targets.add(expr.getMethod()); return targets; } public List<SootMethod> getTargetsOf(Value v, SootMethod m) { SootClass rc; Type t = v.getType(); if (t instanceof ArrayType) { rc = Scene.v().getSootClass("java.lang.Object"); } else { rc = ((RefType)v.getType()).getSootClass(); } List<SootMethod> targets = h.resolveAbstractDispatch(rc, m); return targets; } private Variable.Type getType(Type t) { if (t instanceof RefType) { if (((RefType)t).getSootClass().getName().equals(FOOQUALIFIEDNAME)) { return Variable.Type.FOO; } } if (t instanceof ArrayType) { return Variable.Type.OTHER; } return Variable.Type.OTHER; } boolean isApplicationClass(SootClass c) { Iterator aci = Scene.v().getApplicationClasses().iterator(); while (aci.hasNext()) { SootClass ac = (SootClass)aci.next(); if (c.getName().equals(ac.getName())) { return true; } } return false; } public void notSupported(String msg) { System.err.println(msg); System.exit(5); } }
5,132
28.164773
99
java