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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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(localsTypes[i], dest.localsTypes[i]);
  201. if (mergeStack) {
  202. n = stackTop;
  203. for (int i = 0; i < n; i++)
  204. dest.stackTypes[i] = merge(stackTypes[i], dest.stackTypes[i]);
  205. }
  206. }
  207. private TypeData merge(TypeData src, TypeData target) throws BadBytecode {
  208. if (src == target)
  209. return target;
  210. else if (target instanceof TypeData.ClassName
  211. || target instanceof TypeData.BasicType) // a parameter
  212. return target;
  213. else if (target instanceof TypeData.AbsTypeVar) {
  214. ((TypeData.AbsTypeVar)target).merge(src);
  215. return target;
  216. }
  217. else
  218. throw new RuntimeException("fatal: this should never happen");
  219. }
  220. private void recordStackMap(TypedBlock target)
  221. throws BadBytecode
  222. {
  223. TypeData[] tStackTypes = TypeData.make(stackTypes.length);
  224. int st = stackTop;
  225. recordTypeData(st, stackTypes, tStackTypes);
  226. recordStackMap0(target, st, tStackTypes);
  227. }
  228. private void recordStackMap(TypedBlock target, int exceptionType)
  229. throws BadBytecode
  230. {
  231. TypeData[] tStackTypes = TypeData.make(stackTypes.length);
  232. tStackTypes[0] = toExceptionType(exceptionType).join();
  233. recordStackMap0(target, 1, tStackTypes);
  234. }
  235. private TypeData.ClassName toExceptionType(int exceptionType) {
  236. String type;
  237. if (exceptionType == 0) // for finally clauses
  238. type= "java.lang.Throwable";
  239. else
  240. type = cpool.getClassInfo(exceptionType);
  241. return new TypeData.ClassName(type);
  242. }
  243. private void recordStackMap0(TypedBlock target, int st, TypeData[] tStackTypes)
  244. throws BadBytecode
  245. {
  246. int n = localsTypes.length;
  247. TypeData[] tLocalsTypes = TypeData.make(n);
  248. int k = recordTypeData(n, localsTypes, tLocalsTypes);
  249. target.setStackMap(st, tStackTypes, k, tLocalsTypes);
  250. }
  251. protected static int recordTypeData(int n, TypeData[] srcTypes, TypeData[] destTypes) {
  252. int k = -1;
  253. for (int i = 0; i < n; i++) {
  254. TypeData t = srcTypes[i];
  255. destTypes[i] = t.join();
  256. if (t != TOP)
  257. k = i + 1; // t might be long or double.
  258. }
  259. return k + 1;
  260. }
  261. protected static void copyTypeData(int n, TypeData[] srcTypes, TypeData[] destTypes) {
  262. for (int i = 0; i < n; i++)
  263. destTypes[i] = srcTypes[i];
  264. }
  265. // Phase 1.5
  266. /*
  267. * Javac may generate an exception handler that catches only an exception
  268. * thrown within the handler itself. It is dead code.
  269. */
  270. private void findDeadCatchers(byte[] code, TypedBlock[] blocks) throws BadBytecode {
  271. int len = blocks.length;
  272. for (int i = 0; i < len; i++) {
  273. TypedBlock block = blocks[i];
  274. if (block.localsTypes == null) { // if block is dead code
  275. BasicBlock.Catch handler = block.toCatch;
  276. while (handler != null)
  277. if (handler.body == block) {
  278. BasicBlock.Catch handler2
  279. = new BasicBlock.Catch(block, handler.typeIndex, null);
  280. traceException(code, handler2);
  281. break;
  282. }
  283. else
  284. handler = handler.next;
  285. }
  286. }
  287. }
  288. // Phase 2
  289. /*
  290. * This method first finds strongly connected components (SCCs)
  291. * on a graph made by TypeData by Tarjan's algorithm.
  292. * SCCs are TypeData nodes sharing the same type.
  293. * Since SCCs are found in the topologically sorted order,
  294. * their types are also fixed when they are found.
  295. */
  296. private void fixTypes(byte[] code, TypedBlock[] blocks) throws NotFoundException, BadBytecode {
  297. ArrayList preOrder = new ArrayList();
  298. int len = blocks.length;
  299. int index = 0;
  300. for (int i = 0; i < len; i++) {
  301. TypedBlock block = blocks[i];
  302. if (block.localsTypes == null) // if block is dead code
  303. fixDeadcode(code, block);
  304. else {
  305. int n = block.localsTypes.length;
  306. for (int j = 0; j < n; j++)
  307. index = block.localsTypes[j].dfs(preOrder, index, classPool);
  308. n = block.stackTop;
  309. for (int j = 0; j < n; j++)
  310. index = block.stackTypes[j].dfs(preOrder, index, classPool);
  311. }
  312. }
  313. }
  314. private void fixDeadcode(byte[] code, TypedBlock block) throws BadBytecode {
  315. int pos = block.position;
  316. int len = block.length - 3;
  317. if (len < 0)
  318. throw new BadBytecode("dead code detected at " + pos
  319. + ". No stackmap table generated.");
  320. for (int k = 0; k < len; k++)
  321. code[pos + k] = Bytecode.NOP;
  322. code[pos + len] = (byte)Bytecode.GOTO;
  323. ByteArray.write16bit(-len, code, pos + len + 1);
  324. }
  325. // Phase 3
  326. public StackMapTable toStackMap(TypedBlock[] blocks) {
  327. StackMapTable.Writer writer = new StackMapTable.Writer(32);
  328. int n = blocks.length;
  329. TypedBlock prev = blocks[0];
  330. int offsetDelta = prev.length;
  331. if (prev.incoming > 0) { // the first instruction is a branch target.
  332. writer.sameFrame(0);
  333. offsetDelta--;
  334. }
  335. for (int i = 1; i < n; i++) {
  336. TypedBlock bb = blocks[i];
  337. if (isTarget(bb, blocks[i - 1])) {
  338. bb.resetNumLocals();
  339. int diffL = stackMapDiff(prev.numLocals, prev.localsTypes,
  340. bb.numLocals, bb.localsTypes);
  341. toStackMapBody(writer, bb, diffL, offsetDelta, prev);
  342. offsetDelta = bb.length - 1;
  343. prev = bb;
  344. }
  345. else if (bb.incoming == 0) {
  346. // dead code.
  347. writer.sameFrame(offsetDelta);
  348. offsetDelta = bb.length - 1;
  349. prev = bb;
  350. }
  351. else
  352. offsetDelta += bb.length;
  353. }
  354. return writer.toStackMapTable(cpool);
  355. }
  356. /**
  357. * Returns true if cur is a branch target.
  358. */
  359. private boolean isTarget(TypedBlock cur, TypedBlock prev) {
  360. int in = cur.incoming;
  361. if (in > 1)
  362. return true;
  363. else if (in < 1)
  364. return false;
  365. return prev.stop;
  366. }
  367. private void toStackMapBody(StackMapTable.Writer writer, TypedBlock bb,
  368. int diffL, int offsetDelta, TypedBlock prev) {
  369. // if diffL is -100, two TypeData arrays do not share
  370. // any elements.
  371. int stackTop = bb.stackTop;
  372. if (stackTop == 0) {
  373. if (diffL == 0) {
  374. writer.sameFrame(offsetDelta);
  375. return;
  376. }
  377. else if (0 > diffL && diffL >= -3) {
  378. writer.chopFrame(offsetDelta, -diffL);
  379. return;
  380. }
  381. else if (0 < diffL && diffL <= 3) {
  382. int[] data = new int[diffL];
  383. int[] tags = fillStackMap(bb.numLocals - prev.numLocals,
  384. prev.numLocals, data,
  385. bb.localsTypes);
  386. writer.appendFrame(offsetDelta, tags, data);
  387. return;
  388. }
  389. }
  390. else if (stackTop == 1 && diffL == 0) {
  391. TypeData td = bb.stackTypes[0];
  392. writer.sameLocals(offsetDelta, td.getTypeTag(), td.getTypeData(cpool));
  393. return;
  394. }
  395. else if (stackTop == 2 && diffL == 0) {
  396. TypeData td = bb.stackTypes[0];
  397. if (td.is2WordType()) {
  398. // bb.stackTypes[1] must be TOP.
  399. writer.sameLocals(offsetDelta, td.getTypeTag(), td.getTypeData(cpool));
  400. return;
  401. }
  402. }
  403. int[] sdata = new int[stackTop];
  404. int[] stags = fillStackMap(stackTop, 0, sdata, bb.stackTypes);
  405. int[] ldata = new int[bb.numLocals];
  406. int[] ltags = fillStackMap(bb.numLocals, 0, ldata, bb.localsTypes);
  407. writer.fullFrame(offsetDelta, ltags, ldata, stags, sdata);
  408. }
  409. private int[] fillStackMap(int num, int offset, int[] data, TypeData[] types) {
  410. int realNum = diffSize(types, offset, offset + num);
  411. ConstPool cp = cpool;
  412. int[] tags = new int[realNum];
  413. int j = 0;
  414. for (int i = 0; i < num; i++) {
  415. TypeData td = types[offset + i];
  416. tags[j] = td.getTypeTag();
  417. data[j] = td.getTypeData(cp);
  418. if (td.is2WordType())
  419. i++;
  420. j++;
  421. }
  422. return tags;
  423. }
  424. private static int stackMapDiff(int oldTdLen, TypeData[] oldTd,
  425. int newTdLen, TypeData[] newTd)
  426. {
  427. int diff = newTdLen - oldTdLen;
  428. int len;
  429. if (diff > 0)
  430. len = oldTdLen;
  431. else
  432. len = newTdLen;
  433. if (stackMapEq(oldTd, newTd, len))
  434. if (diff > 0)
  435. return diffSize(newTd, len, newTdLen);
  436. else
  437. return -diffSize(oldTd, len, oldTdLen);
  438. else
  439. return -100;
  440. }
  441. private static boolean stackMapEq(TypeData[] oldTd, TypeData[] newTd, int len) {
  442. for (int i = 0; i < len; i++) {
  443. if (!oldTd[i].eq(newTd[i]))
  444. return false;
  445. }
  446. return true;
  447. }
  448. private static int diffSize(TypeData[] types, int offset, int len) {
  449. int num = 0;
  450. while (offset < len) {
  451. TypeData td = types[offset++];
  452. num++;
  453. if (td.is2WordType())
  454. offset++;
  455. }
  456. return num;
  457. }
  458. // Phase 3 for J2ME
  459. public StackMap toStackMap2(ConstPool cp, TypedBlock[] blocks) {
  460. StackMap.Writer writer = new StackMap.Writer();
  461. int n = blocks.length; // should be > 0
  462. boolean[] effective = new boolean[n];
  463. TypedBlock prev = blocks[0];
  464. // Is the first instruction a branch target?
  465. effective[0] = prev.incoming > 0;
  466. int num = effective[0] ? 1 : 0;
  467. for (int i = 1; i < n; i++) {
  468. TypedBlock bb = blocks[i];
  469. if (effective[i] = isTarget(bb, blocks[i - 1])) {
  470. bb.resetNumLocals();
  471. prev = bb;
  472. num++;
  473. }
  474. }
  475. if (num == 0)
  476. return null;
  477. writer.write16bit(num);
  478. for (int i = 0; i < n; i++)
  479. if (effective[i])
  480. writeStackFrame(writer, cp, blocks[i].position, blocks[i]);
  481. return writer.toStackMap(cp);
  482. }
  483. private void writeStackFrame(StackMap.Writer writer, ConstPool cp, int offset, TypedBlock tb) {
  484. writer.write16bit(offset);
  485. writeVerifyTypeInfo(writer, cp, tb.localsTypes, tb.numLocals);
  486. writeVerifyTypeInfo(writer, cp, tb.stackTypes, tb.stackTop);
  487. }
  488. private void writeVerifyTypeInfo(StackMap.Writer writer, ConstPool cp, TypeData[] types, int num) {
  489. int numDWord = 0;
  490. for (int i = 0; i < num; i++) {
  491. TypeData td = types[i];
  492. if (td != null && td.is2WordType()) {
  493. numDWord++;
  494. i++;
  495. }
  496. }
  497. writer.write16bit(num - numDWord);
  498. for (int i = 0; i < num; i++) {
  499. TypeData td = types[i];
  500. writer.writeVerifyTypeInfo(td.getTypeTag(), td.getTypeData(cp));
  501. if (td.is2WordType())
  502. i++;
  503. }
  504. }
  505. }