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

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