Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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