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 18KB

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