PageRenderTime 52ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/ded/soot/soot-2.3.0/src/soot/jimple/spark/ondemand/genericutil/Util.java

https://gitlab.com/hounge.mobile/apkinspector
Java | 461 lines | 277 code | 52 blank | 132 comment | 56 complexity | f342d537ee918a064e9842bca85492c5 MD5 | raw file
  1. /* Soot - a J*va Optimization Framework
  2. * Copyright (C) 2007 Manu Sridharan
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  17. * Boston, MA 02111-1307, USA.
  18. */
  19. package soot.jimple.spark.ondemand.genericutil;
  20. import java.io.ByteArrayOutputStream;
  21. import java.io.PrintWriter;
  22. import java.lang.reflect.Field;
  23. import java.math.BigInteger;
  24. import java.security.Permission;
  25. import java.util.ArrayList;
  26. import java.util.BitSet;
  27. import java.util.Collection;
  28. import java.util.HashSet;
  29. import java.util.Iterator;
  30. import java.util.LinkedList;
  31. import java.util.List;
  32. import java.util.Random;
  33. import java.util.Set;
  34. /**
  35. * Miscellaneous utility functions.
  36. */
  37. public class Util {
  38. /** The empty {@link BitSet}. */
  39. public static final BitSet EMPTY_BITSET = new BitSet();
  40. /** Factorial */
  41. public static long fact(long n_) {
  42. long result = 1;
  43. for (long i = 1; i <= n_; i++)
  44. result *= i;
  45. return result;
  46. }
  47. /** Factorial */
  48. public static BigInteger fact(BigInteger n_) {
  49. BigInteger result = BigInteger.ONE;
  50. for (BigInteger i = BigInteger.ONE; i.compareTo(n_) <= 0; i = i.add(BigInteger.ONE))
  51. result = result.multiply(i);
  52. return result;
  53. }
  54. /**
  55. * Factorial on doubles; avoids overflow problems present when using integers.
  56. *
  57. * @param n_
  58. * arg on which to compute factorial
  59. * @return (<code>double</code> approximation to) factorial of largest
  60. * positive integer <= (n_ + epsilon)
  61. */
  62. public static double fact(double n_) {
  63. n_ += 1e-6;
  64. double result = 1.0;
  65. for (double i = 1; i <= n_; i += 1.0)
  66. result *= i;
  67. return result;
  68. }
  69. /** Factorial */
  70. public static int fact(int n_) {
  71. int result = 1;
  72. for (int i = 1; i <= n_; i++)
  73. result *= i;
  74. return result;
  75. }
  76. /** Binary log: finds the smallest power k such that 2^k>=n */
  77. public static int binaryLogUp(int n_) {
  78. int k = 0;
  79. while ((1 << k) < n_)
  80. k++;
  81. return k;
  82. }
  83. /** Binary log: finds the smallest power k such that 2^k>=n */
  84. public static int binaryLogUp(long n_) {
  85. int k = 0;
  86. while ((1 << k) < n_)
  87. k++;
  88. return k;
  89. }
  90. /** Convert an int[] to a {@link String} for printing */
  91. public static String str(int[] ints_) {
  92. StringBuffer s = new StringBuffer();
  93. s.append("[");
  94. for (int i = 0; i < ints_.length; i++) {
  95. if (i > 0)
  96. s.append(", ");
  97. s.append(ints_[i]);
  98. }
  99. s.append("]");
  100. return s.toString();
  101. }
  102. public static String objArrayToString(Object[] o) {
  103. return objArrayToString(o, "[", "]", ", ");
  104. }
  105. public static String objArrayToString(Object[] o, String start, String end, String sep) {
  106. StringBuffer s = new StringBuffer();
  107. s.append(start);
  108. for (int i = 0; i < o.length; i++) {
  109. if (o[i] != null) {
  110. if (i > 0)
  111. s.append(sep);
  112. s.append(o[i].toString());
  113. }
  114. }
  115. s.append(end);
  116. return s.toString();
  117. }
  118. /** Get a {@link String} representation of a {@link Throwable}. */
  119. public static String str(Throwable thrown_) {
  120. // create a memory buffer to which to dump the trace
  121. ByteArrayOutputStream traceDump = new ByteArrayOutputStream();
  122. PrintWriter w = new PrintWriter(traceDump);
  123. thrown_.printStackTrace(w);
  124. w.close();
  125. return traceDump.toString();
  126. }
  127. /**
  128. * Test whether <em>some</em> element of the given {@link Collection}
  129. * satisfies the given {@link Predicate}.
  130. */
  131. public static <T> boolean forSome(Collection<T> c_, Predicate<T> p_) {
  132. for (T t : c_) {
  133. if (p_.test(t)) {
  134. return true;
  135. }
  136. }
  137. return false;
  138. }
  139. /**
  140. * Test whether <em>some</em> element of the given {@link Collection}
  141. * satisfies the given {@link Predicate}.
  142. *
  143. * @return The first element satisfying the predicate; otherwise null.
  144. */
  145. public static <T> T find(Collection<T> c_, Predicate<T> p_) {
  146. for (Iterator<T> iter = c_.iterator(); iter.hasNext();) {
  147. T obj = iter.next();
  148. if (p_.test(obj))
  149. return obj;
  150. }
  151. return null;
  152. }
  153. /**
  154. * Test whether <em>some</em> element of the given {@link Collection}
  155. * satisfies the given {@link Predicate}.
  156. *
  157. * @return All the elements satisfying the predicate
  158. */
  159. public static <T> Collection<T> findAll(Collection<T> c_, Predicate<T> p_) {
  160. Collection<T> result = new LinkedList<T>();
  161. for (Iterator<T> iter = c_.iterator(); iter.hasNext();) {
  162. T obj = iter.next();
  163. if (p_.test(obj))
  164. result.add(obj);
  165. }
  166. return result;
  167. }
  168. /**
  169. * Test whether <em>all</em> elements of the given {@link Collection}
  170. * satisfy the given {@link Predicate}.
  171. */
  172. public static <T> boolean forAll(Collection<T> c_, Predicate<T> p_) {
  173. for (T t : c_) {
  174. if (!p_.test(t))
  175. return false;
  176. }
  177. return true;
  178. }
  179. /**
  180. * Perform an action for all elements in a collection.
  181. *
  182. * @param c_
  183. * the collection
  184. * @param v_
  185. * the visitor defining the action
  186. */
  187. public static <T> void doForAll(Collection<T> c_, ObjectVisitor<T> v_) {
  188. for (Iterator<T> iter = c_.iterator(); iter.hasNext();)
  189. v_.visit(iter.next());
  190. }
  191. /**
  192. * Map a list: generate a new list with each element mapped. The new list is
  193. * always an {@link ArrayList}; it would have been more precise to use
  194. * {@link java.lang.reflect reflection} to create a list of the same type as
  195. * 'srcList', but reflection works really slowly in some implementations, so
  196. * it's best to avoid it.
  197. */
  198. public static <T, U> List<U> map(List<T> srcList, Mapper<T, U> mapper_) {
  199. ArrayList<U> result = new ArrayList<U>();
  200. for (Iterator<T> srcIter = srcList.iterator(); srcIter.hasNext();)
  201. result.add(mapper_.map(srcIter.next()));
  202. return result;
  203. }
  204. /**
  205. * Filter a collection: generate a new list from an existing collection,
  206. * consisting of the elements satisfying some predicate. The new list is
  207. * always an {@link ArrayList}; it would have been more precise to use
  208. * {@link java.lang.reflect reflection} to create a list of the same type as
  209. * 'srcList', but reflection works really slowly in some implementations, so
  210. * it's best to avoid it.
  211. */
  212. public static <T> List<T> filter(Collection<T> src_, Predicate<T> pred_) {
  213. ArrayList<T> result = new ArrayList<T>();
  214. for (Iterator<T> srcIter = src_.iterator(); srcIter.hasNext();) {
  215. T curElem = srcIter.next();
  216. if (pred_.test(curElem))
  217. result.add(curElem);
  218. }
  219. return result;
  220. }
  221. /**
  222. * Filter a collection according to some predicate, placing the result in a
  223. * List
  224. *
  225. * @param src_
  226. * collection to be filtered
  227. * @param pred_
  228. * the predicate
  229. * @param result_
  230. * the list for the result. assumed to be empty
  231. */
  232. public static <T> void filter(Collection<T> src_, Predicate<T> pred_, List<T> result_) {
  233. for (T t : src_) {
  234. if (pred_.test(t)) {
  235. result_.add(t);
  236. }
  237. }
  238. }
  239. /**
  240. * Map a set: generate a new set with each element mapped. The new set is
  241. * always a {@link HashSet}; it would have been more precise to use
  242. * {@link java.lang.reflect reflection} to create a set of the same type as
  243. * 'srcSet', but reflection works really slowly in some implementations, so
  244. * it's best to avoid it.
  245. */
  246. public static <T, U> Set<U> mapToSet(Collection<T> srcSet, Mapper<T, U> mapper_) {
  247. HashSet<U> result = new HashSet<U>();
  248. for (Iterator<T> srcIter = srcSet.iterator(); srcIter.hasNext();)
  249. result.add(mapper_.map(srcIter.next()));
  250. return result;
  251. }
  252. /*
  253. * Grow an int[] -- i.e. allocate a new array of the given size, with the
  254. * initial segment equal to this int[].
  255. */
  256. public static int[] realloc(int[] data_, int newSize_) {
  257. if (data_.length < newSize_) {
  258. int[] newData = new int[newSize_];
  259. System.arraycopy(data_, 0, newData, 0, data_.length);
  260. return newData;
  261. } else
  262. return data_;
  263. }
  264. /** Clear a {@link BitSet}. */
  265. public static void clear(BitSet bitSet_) {
  266. bitSet_.and(EMPTY_BITSET);
  267. }
  268. /** Replace all occurrences of a given substring in a given {@link String}. */
  269. public static String replaceAll(String str_, String sub_, String newSub_) {
  270. if (str_.indexOf(sub_) == -1)
  271. return str_;
  272. int subLen = sub_.length();
  273. int idx;
  274. StringBuffer result = new StringBuffer(str_);
  275. while ((idx = result.toString().indexOf(sub_)) >= 0)
  276. result.replace(idx, idx + subLen, newSub_);
  277. return result.toString();
  278. }
  279. /** Remove all occurrences of a given substring in a given {@link String} */
  280. public static String removeAll(String str_, String sub_) {
  281. return replaceAll(str_, sub_, "");
  282. }
  283. /** Generate strings with fully qualified names or not */
  284. public static final boolean FULLY_QUALIFIED_NAMES = false;
  285. /** Write object fields to string */
  286. public static String objectFieldsToString(Object obj) {
  287. // Temporarily disable the security manager
  288. SecurityManager oldsecurity = System.getSecurityManager();
  289. System.setSecurityManager(new SecurityManager() {
  290. public void checkPermission(Permission perm) {
  291. }
  292. });
  293. Class c = obj.getClass();
  294. StringBuffer buf = new StringBuffer(FULLY_QUALIFIED_NAMES ? c.getName() : removePackageName(c.getName()));
  295. while (c != Object.class) {
  296. Field[] fields = c.getDeclaredFields();
  297. if (fields.length > 0)
  298. buf = buf.append(" (");
  299. for (int i = 0; i < fields.length; i++) {
  300. // Make this field accessible
  301. fields[i].setAccessible(true);
  302. try {
  303. Class type = fields[i].getType();
  304. String name = fields[i].getName();
  305. Object value = fields[i].get(obj);
  306. // name=value : type
  307. buf = buf.append(name);
  308. buf = buf.append("=");
  309. buf = buf.append(value == null ? "null" : value.toString());
  310. buf = buf.append(" : ");
  311. buf = buf.append(FULLY_QUALIFIED_NAMES ? type.getName() : removePackageName(type.getName()));
  312. } catch (IllegalAccessException e) {
  313. e.printStackTrace();
  314. }
  315. buf = buf.append(i + 1 >= fields.length ? ")" : ",");
  316. }
  317. c = c.getSuperclass();
  318. }
  319. // Reinstate the security manager
  320. System.setSecurityManager(oldsecurity);
  321. return buf.toString();
  322. }
  323. /** Remove the package name from a fully qualified class name */
  324. public static String removePackageName(String fully_qualified_name_) {
  325. if (fully_qualified_name_ == null)
  326. return null;
  327. int lastdot = fully_qualified_name_.lastIndexOf('.');
  328. if (lastdot < 0) {
  329. return "";
  330. } else {
  331. return fully_qualified_name_.substring(lastdot + 1);
  332. }
  333. }
  334. /**
  335. * @return
  336. */
  337. public static int hashArray(Object[] objs) {
  338. // stolen from java.util.AbstractList
  339. int ret = 1;
  340. for (int i = 0; i < objs.length; i++) {
  341. ret = 31 * ret + (objs[i] == null ? 0 : objs[i].hashCode());
  342. }
  343. return ret;
  344. }
  345. public static boolean arrayContains(Object[] arr, Object obj, int size) {
  346. assert obj != null;
  347. for (int i = 0; i < size; i++) {
  348. if (arr[i] != null && arr[i].equals(obj))
  349. return true;
  350. }
  351. return false;
  352. }
  353. public static String toStringNull(Object o) {
  354. return o == null ? "" : "[" + o.toString() + "]";
  355. }
  356. /**
  357. * checks if two sets have a non-empty intersection
  358. *
  359. * @param s1
  360. * @param s2
  361. * @return <code>true</code> if the sets intersect; <code>false</code>
  362. * otherwise
  363. */
  364. public static <T> boolean intersecting(final Set<T> s1, final Set<T> s2) {
  365. return forSome(s1, new Predicate<T>() {
  366. public boolean test(T obj) {
  367. return s2.contains(obj);
  368. }
  369. });
  370. }
  371. public static boolean stringContains(String str, String subStr) {
  372. return str.indexOf(subStr) != -1;
  373. }
  374. public static int getInt(Integer i) {
  375. return (i == null) ? 0 : i;
  376. }
  377. /**
  378. * given the name of a class C, returns the name of the top-most enclosing
  379. * class of class C. For example, given A$B$C, the method returns A
  380. *
  381. * @param typeStr
  382. * @return
  383. */
  384. public static String topLevelTypeString(String typeStr) {
  385. int dollarIndex = typeStr.indexOf('$');
  386. String topLevelTypeStr = dollarIndex == -1 ? typeStr : typeStr.substring(0, dollarIndex);
  387. return topLevelTypeStr;
  388. }
  389. public static <T> void addIfNotNull(T val, Collection<T> vals) {
  390. if (val != null) {
  391. vals.add(val);
  392. }
  393. }
  394. public static <T> List<T> pickNAtRandom(List<T> vals, int n, long seed) {
  395. if (vals.size() <= n) {
  396. return vals;
  397. }
  398. HashSet<T> elems = new HashSet<T>();
  399. Random rand = new Random(seed);
  400. for (int i = 0; i < n; i++) {
  401. boolean added = true;
  402. do {
  403. int randIndex = rand.nextInt(n);
  404. added = elems.add(vals.get(randIndex));
  405. } while (!added);
  406. }
  407. return new ArrayList<T>(elems);
  408. }
  409. } // class Util