You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MapMaker.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later,
  9. * or the Apache License Version 2.0.
  10. *
  11. * Software distributed under the License is distributed on an "AS IS" basis,
  12. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. * for the specific language governing rights and limitations under the
  14. * License.
  15. */
  16. package javassist.bytecode.stackmap;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. import javassist.ClassPool;
  20. import javassist.NotFoundException;
  21. import javassist.bytecode.BadBytecode;
  22. import javassist.bytecode.ByteArray;
  23. import javassist.bytecode.Bytecode;
  24. import javassist.bytecode.CodeAttribute;
  25. import javassist.bytecode.ConstPool;
  26. import javassist.bytecode.MethodInfo;
  27. import javassist.bytecode.StackMap;
  28. import javassist.bytecode.StackMapTable;
  29. /**
  30. * Stack map maker.
  31. */
  32. public class MapMaker extends Tracer {
  33. /*
  34. public static void main(String[] args) throws Exception {
  35. boolean useMain2 = args[0].equals("0");
  36. if (useMain2 && args.length > 1) {
  37. main2(args);
  38. return;
  39. }
  40. for (int i = 0; i < args.length; i++)
  41. main1(args[i]);
  42. }
  43. public static void main1(String className) throws Exception {
  44. ClassPool cp = ClassPool.getDefault();
  45. //javassist.CtClass cc = cp.get(className);
  46. javassist.CtClass cc = cp.makeClass(new java.io.FileInputStream(className));
  47. System.out.println(className);
  48. ClassFile cf = cc.getClassFile();
  49. java.util.List minfos = cf.getMethods();
  50. for (int i = 0; i < minfos.size(); i++) {
  51. MethodInfo minfo = (MethodInfo)minfos.get(i);
  52. CodeAttribute ca = minfo.getCodeAttribute();
  53. if (ca != null)
  54. ca.setAttribute(make(cp, minfo));
  55. }
  56. cc.writeFile("tmp");
  57. }
  58. public static void main2(String[] args) throws Exception {
  59. ClassPool cp = ClassPool.getDefault();
  60. //javassist.CtClass cc = cp.get(args[1]);
  61. javassist.CtClass cc = cp.makeClass(new java.io.FileInputStream(args[1]));
  62. MethodInfo minfo;
  63. if (args[2].equals("_init_"))
  64. minfo = cc.getDeclaredConstructors()[0].getMethodInfo();
  65. // minfo = cc.getClassInitializer().getMethodInfo();
  66. else
  67. minfo = cc.getDeclaredMethod(args[2]).getMethodInfo();
  68. CodeAttribute ca = minfo.getCodeAttribute();
  69. if (ca == null) {
  70. System.out.println("abstarct method");
  71. return;
  72. }
  73. TypedBlock[] blocks = TypedBlock.makeBlocks(minfo, ca, false);
  74. MapMaker mm = new MapMaker(cp, minfo, ca);
  75. mm.make(blocks, ca.getCode());
  76. for (int i = 0; i < blocks.length; i++)
  77. System.out.println(blocks[i]);
  78. }
  79. */
  80. /**
  81. * Computes the stack map table of the given method and returns it.
  82. * It returns null if the given method does not have to have a
  83. * stack map table or it includes JSR.
  84. */
  85. public static StackMapTable make(ClassPool classes, MethodInfo minfo)
  86. throws BadBytecode
  87. {
  88. CodeAttribute ca = minfo.getCodeAttribute();
  89. if (ca == null)
  90. return null;
  91. TypedBlock[] blocks;
  92. try {
  93. blocks = TypedBlock.makeBlocks(minfo, ca, true);
  94. }
  95. catch (BasicBlock.JsrBytecode e) {
  96. return null;
  97. }
  98. if (blocks == null)
  99. return null;
  100. MapMaker mm = new MapMaker(classes, minfo, ca);
  101. try {
  102. mm.make(blocks, ca.getCode());
  103. }
  104. catch (BadBytecode bb) {
  105. throw new BadBytecode(minfo, bb);
  106. }
  107. return mm.toStackMap(blocks);
  108. }
  109. /**
  110. * Computes the stack map table for J2ME.
  111. * It returns null if the given method does not have to have a
  112. * stack map table or it includes JSR.
  113. */
  114. public static StackMap make2(ClassPool classes, MethodInfo minfo)
  115. throws BadBytecode
  116. {
  117. CodeAttribute ca = minfo.getCodeAttribute();
  118. if (ca == null)
  119. return null;
  120. TypedBlock[] blocks;
  121. try {
  122. blocks = TypedBlock.makeBlocks(minfo, ca, true);
  123. }
  124. catch (BasicBlock.JsrBytecode e) {
  125. return null;
  126. }
  127. if (blocks == null)
  128. return null;
  129. MapMaker mm = new MapMaker(classes, minfo, ca);
  130. try {
  131. mm.make(blocks, ca.getCode());
  132. }
  133. catch (BadBytecode bb) {
  134. throw new BadBytecode(minfo, bb);
  135. }
  136. return mm.toStackMap2(minfo.getConstPool(), blocks);
  137. }
  138. public MapMaker(ClassPool classes, MethodInfo minfo, CodeAttribute ca) {
  139. super(classes, minfo.getConstPool(),
  140. ca.getMaxStack(), ca.getMaxLocals(),
  141. TypedBlock.getRetType(minfo.getDescriptor()));
  142. }
  143. protected MapMaker(MapMaker old) { super(old); }
  144. /**
  145. * Runs an analyzer (Phase 1 and 2).
  146. */
  147. void make(TypedBlock[] blocks, byte[] code)
  148. throws BadBytecode
  149. {
  150. make(code, blocks[0]);
  151. findDeadCatchers(code, blocks);
  152. try {
  153. fixTypes(code, blocks);
  154. } catch (NotFoundException e) {
  155. throw new BadBytecode("failed to resolve types", e);
  156. }
  157. }
  158. // Phase 1
  159. private void make(byte[] code, TypedBlock tb)
  160. throws BadBytecode
  161. {
  162. copyTypeData(tb.stackTop, tb.stackTypes, stackTypes);
  163. stackTop = tb.stackTop;
  164. copyTypeData(tb.localsTypes.length, tb.localsTypes, localsTypes);
  165. traceException(code, tb.toCatch);
  166. int pos = tb.position;
  167. int end = pos + tb.length;
  168. while (pos < end) {
  169. pos += doOpcode(pos, code);
  170. traceException(code, tb.toCatch);
  171. }
  172. if (tb.exit != null) {
  173. for (int i = 0; i < tb.exit.length; i++) {
  174. TypedBlock e = (TypedBlock)tb.exit[i];
  175. if (e.alreadySet())
  176. mergeMap(e, true);
  177. else {
  178. recordStackMap(e);
  179. MapMaker maker = new MapMaker(this);
  180. maker.make(code, e);
  181. }
  182. }
  183. }
  184. }
  185. private void traceException(byte[] code, TypedBlock.Catch handler)
  186. throws BadBytecode
  187. {
  188. while (handler != null) {
  189. TypedBlock tb = (TypedBlock)handler.body;
  190. if (tb.alreadySet()) {
  191. mergeMap(tb, false);
  192. if (tb.stackTop < 1)
  193. throw new BadBytecode("bad catch clause: " + handler.typeIndex);
  194. tb.stackTypes[0] = merge(toExceptionType(handler.typeIndex),
  195. tb.stackTypes[0]);
  196. }
  197. else {
  198. recordStackMap(tb, handler.typeIndex);
  199. MapMaker maker = new MapMaker(this);
  200. maker.make(code, tb);
  201. }
  202. handler = handler.next;
  203. }
  204. }
  205. private void mergeMap(TypedBlock dest, boolean mergeStack) throws BadBytecode {
  206. int n = localsTypes.length;
  207. for (int i = 0; i < n; i++)
  208. dest.localsTypes[i] = merge(validateTypeData(localsTypes, n, i),
  209. dest.localsTypes[i]);
  210. if (mergeStack) {
  211. n = stackTop;
  212. for (int i = 0; i < n; i++)
  213. dest.stackTypes[i] = merge(stackTypes[i], dest.stackTypes[i]);
  214. }
  215. }
  216. private TypeData merge(TypeData src, TypeData target) throws BadBytecode {
  217. if (src == target)
  218. return target;
  219. else if (target instanceof TypeData.ClassName
  220. || target instanceof TypeData.BasicType) // a parameter
  221. return target;
  222. else if (target instanceof TypeData.AbsTypeVar) {
  223. ((TypeData.AbsTypeVar)target).merge(src);
  224. return target;
  225. }
  226. else
  227. throw new RuntimeException("fatal: this should never happen");
  228. }
  229. private void recordStackMap(TypedBlock target)
  230. throws BadBytecode
  231. {
  232. TypeData[] tStackTypes = TypeData.make(stackTypes.length);
  233. int st = stackTop;
  234. recordTypeData(st, stackTypes, tStackTypes);
  235. recordStackMap0(target, st, tStackTypes);
  236. }
  237. private void recordStackMap(TypedBlock target, int exceptionType)
  238. throws BadBytecode
  239. {
  240. TypeData[] tStackTypes = TypeData.make(stackTypes.length);
  241. tStackTypes[0] = toExceptionType(exceptionType).join();
  242. recordStackMap0(target, 1, tStackTypes);
  243. }
  244. private TypeData.ClassName toExceptionType(int exceptionType) {
  245. String type;
  246. if (exceptionType == 0) // for finally clauses
  247. type= "java.lang.Throwable";
  248. else
  249. type = cpool.getClassInfo(exceptionType);
  250. return new TypeData.ClassName(type);
  251. }
  252. private void recordStackMap0(TypedBlock target, int st, TypeData[] tStackTypes)
  253. throws BadBytecode
  254. {
  255. int n = localsTypes.length;
  256. TypeData[] tLocalsTypes = TypeData.make(n);
  257. int k = recordTypeData(n, localsTypes, tLocalsTypes);
  258. target.setStackMap(st, tStackTypes, k, tLocalsTypes);
  259. }
  260. protected static int recordTypeData(int n, TypeData[] srcTypes, TypeData[] destTypes) {
  261. int k = -1;
  262. for (int i = 0; i < n; i++) {
  263. TypeData t = validateTypeData(srcTypes, n, i);
  264. destTypes[i] = t.join();
  265. if (t != TOP)
  266. k = i + 1; // t might be long or double.
  267. }
  268. return k + 1;
  269. }
  270. protected static void copyTypeData(int n, TypeData[] srcTypes, TypeData[] destTypes) {
  271. System.arraycopy(srcTypes, 0, destTypes, 0, n);
  272. }
  273. private static TypeData validateTypeData(TypeData[] data, int length, int index) {
  274. TypeData td = data[index];
  275. if (td.is2WordType() && index + 1 < length)
  276. if (data[index + 1] != TOP)
  277. return TOP;
  278. return td;
  279. }
  280. // Phase 1.5
  281. /*
  282. * Javac may generate an exception handler that catches only the exception
  283. * thrown within the handler itself. It is dead code.
  284. * See javassist.JvstTest4.testJIRA195().
  285. */
  286. private void findDeadCatchers(byte[] code, TypedBlock[] blocks) throws BadBytecode {
  287. int len = blocks.length;
  288. for (int i = 0; i < len; i++) {
  289. TypedBlock block = blocks[i];
  290. if (!block.alreadySet()) {
  291. fixDeadcode(code, block);
  292. BasicBlock.Catch handler = block.toCatch;
  293. if (handler != null) {
  294. TypedBlock tb = (TypedBlock)handler.body;
  295. if (!tb.alreadySet()) {
  296. // tb is a handler that catches only the exceptions
  297. // thrown from dead code.
  298. recordStackMap(tb, handler.typeIndex);
  299. fixDeadcode(code, tb);
  300. tb.incoming = 1;
  301. }
  302. }
  303. }
  304. }
  305. }
  306. private void fixDeadcode(byte[] code, TypedBlock block) throws BadBytecode {
  307. int pos = block.position;
  308. int len = block.length - 3;
  309. if (len < 0) {
  310. // if the dead-code length is shorter than 3 bytes.
  311. if (len == -1)
  312. code[pos] = Bytecode.NOP;
  313. code[pos + block.length - 1] = (byte)Bytecode.ATHROW;
  314. block.incoming = 1;
  315. recordStackMap(block, 0);
  316. return;
  317. }
  318. // if block.incomping > 0, all the incoming edges are from
  319. // other dead code blocks. So set block.incoming to 0.
  320. block.incoming = 0;
  321. for (int k = 0; k < len; k++)
  322. code[pos + k] = Bytecode.NOP;
  323. code[pos + len] = (byte)Bytecode.GOTO;
  324. ByteArray.write16bit(-len, code, pos + len + 1);
  325. }
  326. // Phase 2
  327. /*
  328. * This method first finds strongly connected components (SCCs)
  329. * in a TypeData graph by Tarjan's algorithm.
  330. * SCCs are TypeData nodes sharing the same type.
  331. * Since SCCs are found in the topologically sorted order,
  332. * their types are also fixed when they are found.
  333. */
  334. private void fixTypes(byte[] code, TypedBlock[] blocks) throws NotFoundException, BadBytecode {
  335. List<TypeData> preOrder = new ArrayList<TypeData>();
  336. int len = blocks.length;
  337. int index = 0;
  338. for (int i = 0; i < len; i++) {
  339. TypedBlock block = blocks[i];
  340. if (block.alreadySet()) { // if block is not dead code
  341. int n = block.localsTypes.length;
  342. for (int j = 0; j < n; j++)
  343. index = block.localsTypes[j].dfs(preOrder, index, classPool);
  344. n = block.stackTop;
  345. for (int j = 0; j < n; j++)
  346. index = block.stackTypes[j].dfs(preOrder, index, classPool);
  347. }
  348. }
  349. }
  350. // Phase 3
  351. public StackMapTable toStackMap(TypedBlock[] blocks) {
  352. StackMapTable.Writer writer = new StackMapTable.Writer(32);
  353. int n = blocks.length;
  354. TypedBlock prev = blocks[0];
  355. int offsetDelta = prev.length;
  356. if (prev.incoming > 0) { // the first instruction is a branch target.
  357. writer.sameFrame(0);
  358. offsetDelta--;
  359. }
  360. for (int i = 1; i < n; i++) {
  361. TypedBlock bb = blocks[i];
  362. if (isTarget(bb, blocks[i - 1])) {
  363. bb.resetNumLocals();
  364. int diffL = stackMapDiff(prev.numLocals, prev.localsTypes,
  365. bb.numLocals, bb.localsTypes);
  366. toStackMapBody(writer, bb, diffL, offsetDelta, prev);
  367. offsetDelta = bb.length - 1;
  368. prev = bb;
  369. }
  370. else if (bb.incoming == 0) {
  371. // dead code.
  372. writer.sameFrame(offsetDelta);
  373. offsetDelta = bb.length - 1;
  374. }
  375. else
  376. offsetDelta += bb.length;
  377. }
  378. return writer.toStackMapTable(cpool);
  379. }
  380. /**
  381. * Returns true if cur is a branch target.
  382. */
  383. private boolean isTarget(TypedBlock cur, TypedBlock prev) {
  384. int in = cur.incoming;
  385. if (in > 1)
  386. return true;
  387. else if (in < 1)
  388. return false;
  389. return prev.stop;
  390. }
  391. private void toStackMapBody(StackMapTable.Writer writer, TypedBlock bb,
  392. int diffL, int offsetDelta, TypedBlock prev) {
  393. // if diffL is -100, two TypeData arrays do not share
  394. // any elements.
  395. int stackTop = bb.stackTop;
  396. if (stackTop == 0) {
  397. if (diffL == 0) {
  398. writer.sameFrame(offsetDelta);
  399. return;
  400. }
  401. else if (0 > diffL && diffL >= -3) {
  402. writer.chopFrame(offsetDelta, -diffL);
  403. return;
  404. }
  405. else if (0 < diffL && diffL <= 3) {
  406. int[] data = new int[diffL];
  407. int[] tags = fillStackMap(bb.numLocals - prev.numLocals,
  408. prev.numLocals, data,
  409. bb.localsTypes);
  410. writer.appendFrame(offsetDelta, tags, data);
  411. return;
  412. }
  413. }
  414. else if (stackTop == 1 && diffL == 0) {
  415. TypeData td = bb.stackTypes[0];
  416. writer.sameLocals(offsetDelta, td.getTypeTag(), td.getTypeData(cpool));
  417. return;
  418. }
  419. else if (stackTop == 2 && diffL == 0) {
  420. TypeData td = bb.stackTypes[0];
  421. if (td.is2WordType()) {
  422. // bb.stackTypes[1] must be TOP.
  423. writer.sameLocals(offsetDelta, td.getTypeTag(), td.getTypeData(cpool));
  424. return;
  425. }
  426. }
  427. int[] sdata = new int[stackTop];
  428. int[] stags = fillStackMap(stackTop, 0, sdata, bb.stackTypes);
  429. int[] ldata = new int[bb.numLocals];
  430. int[] ltags = fillStackMap(bb.numLocals, 0, ldata, bb.localsTypes);
  431. writer.fullFrame(offsetDelta, ltags, ldata, stags, sdata);
  432. }
  433. private int[] fillStackMap(int num, int offset, int[] data, TypeData[] types) {
  434. int realNum = diffSize(types, offset, offset + num);
  435. ConstPool cp = cpool;
  436. int[] tags = new int[realNum];
  437. int j = 0;
  438. for (int i = 0; i < num; i++) {
  439. TypeData td = types[offset + i];
  440. tags[j] = td.getTypeTag();
  441. data[j] = td.getTypeData(cp);
  442. if (td.is2WordType())
  443. i++;
  444. j++;
  445. }
  446. return tags;
  447. }
  448. private static int stackMapDiff(int oldTdLen, TypeData[] oldTd,
  449. int newTdLen, TypeData[] newTd)
  450. {
  451. int diff = newTdLen - oldTdLen;
  452. int len;
  453. if (diff > 0)
  454. len = oldTdLen;
  455. else
  456. len = newTdLen;
  457. if (stackMapEq(oldTd, newTd, len))
  458. if (diff > 0)
  459. return diffSize(newTd, len, newTdLen);
  460. else
  461. return -diffSize(oldTd, len, oldTdLen);
  462. return -100;
  463. }
  464. private static boolean stackMapEq(TypeData[] oldTd, TypeData[] newTd, int len) {
  465. for (int i = 0; i < len; i++) {
  466. if (!oldTd[i].eq(newTd[i]))
  467. return false;
  468. }
  469. return true;
  470. }
  471. private static int diffSize(TypeData[] types, int offset, int len) {
  472. int num = 0;
  473. while (offset < len) {
  474. TypeData td = types[offset++];
  475. num++;
  476. if (td.is2WordType())
  477. offset++;
  478. }
  479. return num;
  480. }
  481. // Phase 3 for J2ME
  482. public StackMap toStackMap2(ConstPool cp, TypedBlock[] blocks) {
  483. StackMap.Writer writer = new StackMap.Writer();
  484. int n = blocks.length; // should be > 0
  485. boolean[] effective = new boolean[n];
  486. TypedBlock prev = blocks[0];
  487. // Is the first instruction a branch target?
  488. effective[0] = prev.incoming > 0;
  489. int num = effective[0] ? 1 : 0;
  490. for (int i = 1; i < n; i++) {
  491. TypedBlock bb = blocks[i];
  492. if (effective[i] = isTarget(bb, blocks[i - 1])) {
  493. bb.resetNumLocals();
  494. prev = bb;
  495. num++;
  496. }
  497. }
  498. if (num == 0)
  499. return null;
  500. writer.write16bit(num);
  501. for (int i = 0; i < n; i++)
  502. if (effective[i])
  503. writeStackFrame(writer, cp, blocks[i].position, blocks[i]);
  504. return writer.toStackMap(cp);
  505. }
  506. private void writeStackFrame(StackMap.Writer writer, ConstPool cp, int offset, TypedBlock tb) {
  507. writer.write16bit(offset);
  508. writeVerifyTypeInfo(writer, cp, tb.localsTypes, tb.numLocals);
  509. writeVerifyTypeInfo(writer, cp, tb.stackTypes, tb.stackTop);
  510. }
  511. private void writeVerifyTypeInfo(StackMap.Writer writer, ConstPool cp, TypeData[] types, int num) {
  512. int numDWord = 0;
  513. for (int i = 0; i < num; i++) {
  514. TypeData td = types[i];
  515. if (td != null && td.is2WordType()) {
  516. numDWord++;
  517. i++;
  518. }
  519. }
  520. writer.write16bit(num - numDWord);
  521. for (int i = 0; i < num; i++) {
  522. TypeData td = types[i];
  523. writer.writeVerifyTypeInfo(td.getTypeTag(), td.getTypeData(cp));
  524. if (td.is2WordType())
  525. i++;
  526. }
  527. }
  528. }