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.

InstructionList.java 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  1. package org.aspectj.apache.bcel.generic;
  2. /* ====================================================================
  3. * The Apache Software License, Version 1.1
  4. *
  5. * Copyright (c) 2001 The Apache Software Foundation. All rights
  6. * reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. The end-user documentation included with the redistribution,
  21. * if any, must include the following acknowledgment:
  22. * "This product includes software developed by the
  23. * Apache Software Foundation (http://www.apache.org/)."
  24. * Alternately, this acknowledgment may appear in the software itself,
  25. * if and wherever such third-party acknowledgments normally appear.
  26. *
  27. * 4. The names "Apache" and "Apache Software Foundation" and
  28. * "Apache BCEL" must not be used to endorse or promote products
  29. * derived from this software without prior written permission. For
  30. * written permission, please contact apache@apache.org.
  31. *
  32. * 5. Products derived from this software may not be called "Apache",
  33. * "Apache BCEL", nor may "Apache" appear in their name, without
  34. * prior written permission of the Apache Software Foundation.
  35. *
  36. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  40. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  43. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  44. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  46. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. * ====================================================================
  49. *
  50. * This software consists of voluntary contributions made by many
  51. * individuals on behalf of the Apache Software Foundation. For more
  52. * information on the Apache Software Foundation, please see
  53. * <http://www.apache.org/>.
  54. */
  55. import java.io.ByteArrayOutputStream;
  56. import java.io.DataOutputStream;
  57. import java.io.IOException;
  58. import java.io.Serializable;
  59. import java.util.ArrayList;
  60. import java.util.HashMap;
  61. import java.util.Iterator;
  62. import java.util.Set;
  63. import org.aspectj.apache.bcel.Constants;
  64. import org.aspectj.apache.bcel.classfile.Constant;
  65. import org.aspectj.apache.bcel.classfile.ConstantPool;
  66. import org.aspectj.apache.bcel.util.ByteSequence;
  67. /**
  68. * This class is a container for a list of <a href="Instruction.html">Instruction</a> objects. Instructions can be appended,
  69. * inserted, moved, deleted, etc.. Instructions are being wrapped into <a href="InstructionHandle.html">InstructionHandles</a>
  70. * objects that are returned upon append/insert operations. They give the user (read only) access to the list structure, such that
  71. * it can be traversed and manipulated in a controlled way.
  72. *
  73. * A list is finally dumped to a byte code array with <a href="#getByteCode()">getByteCode</a>.
  74. *
  75. * @version $Id: InstructionList.java,v 1.12 2011/09/02 22:33:04 aclement Exp $
  76. * @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
  77. * @author Abraham Nevado
  78. * @see Instruction
  79. * @see InstructionHandle
  80. * @see BranchHandle
  81. */
  82. public class InstructionList implements Serializable {
  83. private InstructionHandle start = null, end = null;
  84. private int length = 0;
  85. private int[] positions; // byte code offsets corresponding to instructions
  86. public InstructionList() {
  87. }
  88. public InstructionList(Instruction i) {
  89. append(i);
  90. }
  91. public boolean isEmpty() {
  92. return start == null;
  93. } // && end == null
  94. public static InstructionHandle findHandle(InstructionHandle[] ihs, int[] pos, int count, int target) {
  95. return findHandle(ihs, pos, count, target, false);
  96. }
  97. /**
  98. * Find the target instruction (handle) that corresponds to the given target position (byte code offset).
  99. *
  100. * @param ihs array of instruction handles, i.e. il.getInstructionHandles()
  101. * @param pos array of positions corresponding to ihs, i.e. il.getInstructionPositions()
  102. * @param count length of arrays
  103. * @param target target position to search for
  104. * @return target position's instruction handle if available
  105. */
  106. public static InstructionHandle findHandle(InstructionHandle[] ihs, int[] pos, int count, int target,
  107. boolean returnClosestIfNoExactMatch) {
  108. int l = 0, r = count - 1;
  109. // Do a binary search since the pos array is ordered
  110. int i, j;
  111. do {
  112. i = (l + r) / 2;
  113. j = pos[i];
  114. if (j == target) {
  115. return ihs[i]; // found it
  116. } else if (target < j) {
  117. r = i - 1; // else constrain search area
  118. } else {
  119. l = i + 1; // target > j
  120. }
  121. } while (l <= r);
  122. if (returnClosestIfNoExactMatch) {
  123. i = (l + r) / 2;
  124. if (i < 0) {
  125. i = 0;
  126. }
  127. return ihs[i];
  128. }
  129. return null;
  130. }
  131. /**
  132. * Get instruction handle for instruction at byte code position pos. This only works properly, if the list is freshly
  133. * initialized from a byte array or setPositions() has been called before this method.
  134. *
  135. * @param pos byte code position to search for
  136. * @return target position's instruction handle if available
  137. */
  138. public InstructionHandle findHandle(int pos) {
  139. InstructionHandle[] ihs = getInstructionHandles();
  140. return findHandle(ihs, positions, length, pos);
  141. }
  142. public InstructionHandle[] getInstructionsAsArray() {
  143. return getInstructionHandles();
  144. }
  145. public InstructionHandle findHandle(int pos, InstructionHandle[] instructionArray) {
  146. return findHandle(instructionArray, positions, length, pos);
  147. }
  148. public InstructionHandle findHandle(int pos, InstructionHandle[] instructionArray, boolean useClosestApproximationIfNoExactFound) {
  149. return findHandle(instructionArray, positions, length, pos, useClosestApproximationIfNoExactFound);
  150. }
  151. /**
  152. * Initialize instruction list from byte array.
  153. *
  154. * @param code byte array containing the instructions
  155. */
  156. public InstructionList(byte[] code) {
  157. ByteSequence bytes = new ByteSequence(code);
  158. InstructionHandle[] ihs = new InstructionHandle[code.length];
  159. int[] pos = new int[code.length]; // Can't be more than that
  160. int count = 0; // Contains actual length
  161. /*
  162. * Pass 1: Create an object for each byte code and append them to the list.
  163. */
  164. try {
  165. while (bytes.available() > 0) {
  166. // Remember byte offset and associate it with the instruction
  167. int off = bytes.getIndex();
  168. pos[count] = off;
  169. /*
  170. * Read one instruction from the byte stream, the byte position is set accordingly.
  171. */
  172. Instruction i = Instruction.readInstruction(bytes);
  173. InstructionHandle ih;
  174. if (i instanceof InstructionBranch) {
  175. ih = append((InstructionBranch) i);
  176. } else {
  177. ih = append(i);
  178. }
  179. ih.setPosition(off);
  180. ihs[count] = ih;
  181. count++;
  182. }
  183. } catch (IOException e) {
  184. throw new ClassGenException(e.toString());
  185. }
  186. positions = new int[count]; // Trim to proper size
  187. System.arraycopy(pos, 0, positions, 0, count);
  188. /*
  189. * Pass 2: Look for BranchInstruction and update their targets, i.e., convert offsets to instruction handles.
  190. */
  191. // OPTIMIZE better way of doing this? keep little map from earlier from pos -> instruction handle?
  192. for (int i = 0; i < count; i++) {
  193. if (ihs[i] instanceof BranchHandle) {
  194. InstructionBranch bi = (InstructionBranch) ihs[i].instruction;
  195. int target = bi.positionOfThisInstruction + bi.getIndex(); /*
  196. * Byte code position: relative -> absolute.
  197. */
  198. // Search for target position
  199. InstructionHandle ih = findHandle(ihs, pos, count, target);
  200. if (ih == null) {
  201. throw new ClassGenException("Couldn't find target for branch: " + bi);
  202. }
  203. bi.setTarget(ih); // Update target
  204. // If it is a Select instruction, update all branch targets
  205. if (bi instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH
  206. InstructionSelect s = (InstructionSelect) bi;
  207. int[] indices = s.getIndices();
  208. for (int j = 0; j < indices.length; j++) {
  209. target = bi.positionOfThisInstruction + indices[j];
  210. ih = findHandle(ihs, pos, count, target);
  211. if (ih == null) {
  212. throw new ClassGenException("Couldn't find target for switch: " + bi);
  213. }
  214. s.setTarget(j, ih); // Update target
  215. }
  216. }
  217. }
  218. }
  219. }
  220. /**
  221. * Append another list after instruction (handle) ih contained in this list. Consumes argument list, i.e., it becomes empty.
  222. *
  223. * @param appendTo where to append the instruction list
  224. * @param appendee Instruction list to append to this one
  225. * @return instruction handle pointing to the <B>first</B> appended instruction
  226. */
  227. public InstructionHandle append(InstructionHandle appendTo, InstructionList appendee) {
  228. assert appendee != null;
  229. if (appendee.isEmpty()) {
  230. return appendTo;
  231. }
  232. InstructionHandle next = appendTo.next;
  233. InstructionHandle ret = appendee.start;
  234. appendTo.next = appendee.start;
  235. appendee.start.prev = appendTo;
  236. appendee.end.next = next;
  237. if (next != null) {
  238. next.prev = appendee.end;
  239. } else {
  240. end = appendee.end; // Update end ...
  241. }
  242. length += appendee.length; // Update length
  243. appendee.clear();
  244. return ret;
  245. }
  246. /**
  247. * Append another list after instruction i contained in this list. Consumes argument list, i.e., it becomes empty.
  248. *
  249. * @param i where to append the instruction list
  250. * @param il Instruction list to append to this one
  251. * @return instruction handle pointing to the <B>first</B> appended instruction
  252. */
  253. public InstructionHandle append(Instruction i, InstructionList il) {
  254. InstructionHandle ih;
  255. if ((ih = findInstruction2(i)) == null) {
  256. throw new ClassGenException("Instruction " + i + " is not contained in this list.");
  257. }
  258. return append(ih, il);
  259. }
  260. /**
  261. * Append another list to this one. Consumes argument list, i.e., it becomes empty.
  262. *
  263. * @param il list to append to end of this list
  264. * @return instruction handle of the <B>first</B> appended instruction
  265. */
  266. public InstructionHandle append(InstructionList il) {
  267. assert il != null;
  268. if (il.isEmpty()) {
  269. return null;
  270. }
  271. if (isEmpty()) {
  272. start = il.start;
  273. end = il.end;
  274. length = il.length;
  275. il.clear();
  276. return start;
  277. } else {
  278. return append(end, il); // was end.instruction
  279. }
  280. }
  281. /**
  282. * Append an instruction to the end of this list.
  283. *
  284. * @param ih instruction to append
  285. */
  286. private void append(InstructionHandle ih) {
  287. if (isEmpty()) {
  288. start = end = ih;
  289. ih.next = ih.prev = null;
  290. } else {
  291. end.next = ih;
  292. ih.prev = end;
  293. ih.next = null;
  294. end = ih;
  295. }
  296. length++; // Update length
  297. }
  298. /**
  299. * Append an instruction to the end of this list.
  300. *
  301. * @param i instruction to append
  302. * @return instruction handle of the appended instruction
  303. */
  304. public InstructionHandle append(Instruction i) {
  305. InstructionHandle ih = InstructionHandle.getInstructionHandle(i);
  306. append(ih);
  307. return ih;
  308. }
  309. public InstructionHandle appendDUP() {
  310. InstructionHandle ih = InstructionHandle.getInstructionHandle(InstructionConstants.DUP);
  311. append(ih);
  312. return ih;
  313. }
  314. public InstructionHandle appendNOP() {
  315. InstructionHandle ih = InstructionHandle.getInstructionHandle(InstructionConstants.NOP);
  316. append(ih);
  317. return ih;
  318. }
  319. public InstructionHandle appendPOP() {
  320. InstructionHandle ih = InstructionHandle.getInstructionHandle(InstructionConstants.POP);
  321. append(ih);
  322. return ih;
  323. }
  324. /**
  325. * Append a branch instruction to the end of this list.
  326. *
  327. * @param i branch instruction to append
  328. * @return branch instruction handle of the appended instruction
  329. */
  330. public BranchHandle append(InstructionBranch i) {
  331. BranchHandle ih = BranchHandle.getBranchHandle(i);
  332. append(ih);
  333. return ih;
  334. }
  335. /**
  336. * Append a single instruction j after another instruction i, which must be in this list of course!
  337. *
  338. * @param i Instruction in list
  339. * @param j Instruction to append after i in list
  340. * @return instruction handle of the first appended instruction
  341. */
  342. public InstructionHandle append(Instruction i, Instruction j) {
  343. return append(i, new InstructionList(j));
  344. }
  345. /**
  346. * Append an instruction after instruction (handle) ih contained in this list.
  347. *
  348. * @param ih where to append the instruction list
  349. * @param i Instruction to append
  350. * @return instruction handle pointing to the <B>first</B> appended instruction
  351. */
  352. public InstructionHandle append(InstructionHandle ih, Instruction i) {
  353. return append(ih, new InstructionList(i));
  354. }
  355. /**
  356. * Append an instruction after instruction (handle) ih contained in this list.
  357. *
  358. * @param ih where to append the instruction list
  359. * @param i Instruction to append
  360. * @return instruction handle pointing to the <B>first</B> appended instruction
  361. */
  362. public BranchHandle append(InstructionHandle ih, InstructionBranch i) {
  363. BranchHandle bh = BranchHandle.getBranchHandle(i);
  364. InstructionList il = new InstructionList();
  365. il.append(bh);
  366. append(ih, il);
  367. return bh;
  368. }
  369. /**
  370. * Insert another list before Instruction handle ih contained in this list. Consumes argument list, i.e., it becomes empty.
  371. *
  372. * @param i where to append the instruction list
  373. * @param il Instruction list to insert
  374. * @return instruction handle of the first inserted instruction
  375. */
  376. public InstructionHandle insert(InstructionHandle ih, InstructionList il) {
  377. if (il == null) {
  378. throw new ClassGenException("Inserting null InstructionList");
  379. }
  380. if (il.isEmpty()) {
  381. return ih;
  382. }
  383. InstructionHandle prev = ih.prev, ret = il.start;
  384. ih.prev = il.end;
  385. il.end.next = ih;
  386. il.start.prev = prev;
  387. if (prev != null) {
  388. prev.next = il.start;
  389. } else {
  390. start = il.start; // Update start ...
  391. }
  392. length += il.length; // Update length
  393. il.clear();
  394. return ret;
  395. }
  396. /**
  397. * Insert another list.
  398. *
  399. * @param il list to insert before start of this list
  400. * @return instruction handle of the first inserted instruction
  401. */
  402. public InstructionHandle insert(InstructionList il) {
  403. if (isEmpty()) {
  404. append(il); // Code is identical for this case
  405. return start;
  406. } else {
  407. return insert(start, il);
  408. }
  409. }
  410. /**
  411. * Insert an instruction at start of this list.
  412. *
  413. * @param ih instruction to insert
  414. */
  415. private void insert(InstructionHandle ih) {
  416. if (isEmpty()) {
  417. start = end = ih;
  418. ih.next = ih.prev = null;
  419. } else {
  420. start.prev = ih;
  421. ih.next = start;
  422. ih.prev = null;
  423. start = ih;
  424. }
  425. length++;
  426. }
  427. /**
  428. * Insert another list before Instruction i contained in this list. Consumes argument list, i.e., it becomes empty.
  429. *
  430. * @param i where to append the instruction list
  431. * @param il Instruction list to insert
  432. * @return instruction handle pointing to the first inserted instruction, i.e., il.getStart()
  433. */
  434. public InstructionHandle insert(Instruction i, InstructionList il) {
  435. InstructionHandle ih;
  436. if ((ih = findInstruction1(i)) == null) {
  437. throw new ClassGenException("Instruction " + i + " is not contained in this list.");
  438. }
  439. return insert(ih, il);
  440. }
  441. /**
  442. * Insert an instruction at start of this list.
  443. *
  444. * @param i instruction to insert
  445. * @return instruction handle of the inserted instruction
  446. */
  447. public InstructionHandle insert(Instruction i) {
  448. InstructionHandle ih = InstructionHandle.getInstructionHandle(i);
  449. insert(ih);
  450. return ih;
  451. }
  452. /**
  453. * Insert a branch instruction at start of this list.
  454. *
  455. * @param i branch instruction to insert
  456. * @return branch instruction handle of the appended instruction
  457. */
  458. public BranchHandle insert(InstructionBranch i) {
  459. BranchHandle ih = BranchHandle.getBranchHandle(i);
  460. insert(ih);
  461. return ih;
  462. }
  463. /**
  464. * Insert a single instruction j before another instruction i, which must be in this list of course!
  465. *
  466. * @param i Instruction in list
  467. * @param j Instruction to insert before i in list
  468. * @return instruction handle of the first inserted instruction
  469. */
  470. public InstructionHandle insert(Instruction i, Instruction j) {
  471. return insert(i, new InstructionList(j));
  472. }
  473. /**
  474. * Insert an instruction before instruction (handle) ih contained in this list.
  475. *
  476. * @param ih where to insert to the instruction list
  477. * @param i Instruction to insert
  478. * @return instruction handle of the first inserted instruction
  479. */
  480. public InstructionHandle insert(InstructionHandle ih, Instruction i) {
  481. return insert(ih, new InstructionList(i));
  482. }
  483. /**
  484. * Insert an instruction before instruction (handle) ih contained in this list.
  485. *
  486. * @param ih where to insert to the instruction list
  487. * @param i Instruction to insert
  488. * @return instruction handle of the first inserted instruction
  489. */
  490. public BranchHandle insert(InstructionHandle ih, InstructionBranch i) {
  491. BranchHandle bh = BranchHandle.getBranchHandle(i);
  492. InstructionList il = new InstructionList();
  493. il.append(bh);
  494. insert(ih, il);
  495. return bh;
  496. }
  497. /**
  498. * Take all instructions (handles) from "start" to "end" and append them after the new location "target". Of course, "end" must
  499. * be after "start" and target must not be located withing this range. If you want to move something to the start of the list
  500. * use null as value for target.<br>
  501. * Any instruction targeters pointing to handles within the block, keep their targets.
  502. *
  503. * @param start of moved block
  504. * @param end of moved block
  505. * @param target of moved block
  506. */
  507. public void move(InstructionHandle start, InstructionHandle end, InstructionHandle target) {
  508. // Step 1: Check constraints
  509. if (start == null || end == null) {
  510. throw new ClassGenException("Invalid null handle: From " + start + " to " + end);
  511. }
  512. if (target == start || target == end) {
  513. throw new ClassGenException("Invalid range: From " + start + " to " + end + " contains target " + target);
  514. }
  515. for (InstructionHandle ih = start; ih != end.next; ih = ih.next) {
  516. if (ih == null) {
  517. throw new ClassGenException("Invalid range: From " + start + " to " + end);
  518. } else if (ih == target) {
  519. throw new ClassGenException("Invalid range: From " + start + " to " + end + " contains target " + target);
  520. }
  521. }
  522. // Step 2: Temporarily remove the given instructions from the list
  523. InstructionHandle prev = start.prev, next = end.next;
  524. if (prev != null) {
  525. prev.next = next;
  526. } else {
  527. this.start = next;
  528. }
  529. if (next != null) {
  530. next.prev = prev;
  531. } else {
  532. this.end = prev;
  533. }
  534. start.prev = end.next = null;
  535. // Step 3: append after target
  536. if (target == null) { // append to start of list
  537. end.next = this.start;
  538. this.start = start;
  539. } else {
  540. next = target.next;
  541. target.next = start;
  542. start.prev = target;
  543. end.next = next;
  544. if (next != null) {
  545. next.prev = end;
  546. }
  547. }
  548. }
  549. /**
  550. * Move a single instruction (handle) to a new location.
  551. *
  552. * @param ih moved instruction
  553. * @param target new location of moved instruction
  554. */
  555. public void move(InstructionHandle ih, InstructionHandle target) {
  556. move(ih, ih, target);
  557. }
  558. /**
  559. * Remove from instruction 'prev' to instruction 'next' both contained in this list.
  560. *
  561. * If careAboutLostTargeters is true then this method will throw a TargetLostException when one of the removed instruction
  562. * handles is still being targeted.
  563. *
  564. * @param prev where to start deleting (predecessor, exclusive)
  565. * @param next where to end deleting (successor, exclusive)
  566. */
  567. private void remove(InstructionHandle prev, InstructionHandle next, boolean careAboutLostTargeters) throws TargetLostException {
  568. InstructionHandle first, last; // First and last deleted instruction
  569. if (prev == null && next == null) { // singleton list
  570. first = last = start;
  571. start = end = null;
  572. } else {
  573. if (prev == null) { // At start of list
  574. first = start;
  575. start = next;
  576. } else {
  577. first = prev.next;
  578. prev.next = next;
  579. }
  580. if (next == null) { // At end of list
  581. last = end;
  582. end = prev;
  583. } else {
  584. last = next.prev;
  585. next.prev = prev;
  586. }
  587. }
  588. first.prev = null; // Completely separated from rest of list
  589. last.next = null;
  590. if (!careAboutLostTargeters) {
  591. return;
  592. }
  593. ArrayList<InstructionHandle> target_vec = new ArrayList<InstructionHandle>();
  594. for (InstructionHandle ih = first; ih != null; ih = ih.next) {
  595. ih.getInstruction().dispose(); // e.g. BranchInstructions release their targets
  596. }
  597. StringBuffer buf = new StringBuffer("{ ");
  598. for (InstructionHandle ih = first; ih != null; ih = next) {
  599. next = ih.next;
  600. length--;
  601. Set<InstructionTargeter> targeters = ih.getTargeters();
  602. boolean isOK = false;
  603. Iterator<InstructionTargeter> tIter = targeters.iterator();
  604. while (tIter.hasNext()) {
  605. InstructionTargeter instructionTargeter = tIter.next();
  606. if (instructionTargeter.getClass().getName().endsWith("ShadowRange")
  607. || instructionTargeter.getClass().getName().endsWith("ExceptionRange")
  608. || instructionTargeter.getClass().getName().endsWith("LineNumberTag")) {
  609. isOK = true;
  610. } else {
  611. System.out.println(instructionTargeter.getClass());
  612. }
  613. }
  614. if (!isOK) {
  615. target_vec.add(ih);
  616. buf.append(ih.toString(true) + " ");
  617. ih.next = ih.prev = null;
  618. } else {
  619. ih.dispose();
  620. }
  621. // if (ih.hasTargeters()) { // Still got targeters?
  622. // InstructionTargeter[] targeters = ih.getTargeters();
  623. // boolean isOK = false;
  624. // for (int i = 0; i < targeters.length; i++) {
  625. // InstructionTargeter instructionTargeter = targeters[i];
  626. // if (instructionTargeter.getClass().getName().endsWith("ShadowRange")
  627. // || instructionTargeter.getClass().getName().endsWith("ExceptionRange")
  628. // || instructionTargeter.getClass().getName().endsWith("LineNumberTag")) {
  629. // isOK = true;
  630. // } else {
  631. // System.out.println(instructionTargeter.getClass());
  632. // }
  633. // }
  634. // if (!isOK) {
  635. // target_vec.add(ih);
  636. // buf.append(ih.toString(true) + " ");
  637. // ih.next = ih.prev = null;
  638. // } else {
  639. // ih.dispose();
  640. // }
  641. // } else {
  642. // ih.dispose();
  643. // }
  644. }
  645. buf.append("}");
  646. if (!target_vec.isEmpty()) {
  647. InstructionHandle[] targeted = new InstructionHandle[target_vec.size()];
  648. target_vec.toArray(targeted);
  649. throw new TargetLostException(targeted, buf.toString());
  650. }
  651. }
  652. /**
  653. * Remove instruction from this list. The corresponding Instruction handles must not be reused!
  654. *
  655. * @param ih instruction (handle) to remove
  656. */
  657. public void delete(InstructionHandle ih) throws TargetLostException {
  658. remove(ih.prev, ih.next, false);
  659. }
  660. /**
  661. * Remove instruction from this list. The corresponding Instruction handles must not be reused!
  662. *
  663. * @param i instruction to remove
  664. */
  665. // public void delete(Instruction i) throws TargetLostException {
  666. // InstructionHandle ih;
  667. //
  668. // if((ih = findInstruction1(i)) == null)
  669. // throw new ClassGenException("Instruction " + i +
  670. // " is not contained in this list.");
  671. // delete(ih);
  672. // }
  673. /**
  674. * Remove instructions from instruction `from' to instruction `to' contained in this list. The user must ensure that `from' is
  675. * an instruction before `to', or risk havoc. The corresponding Instruction handles must not be reused!
  676. *
  677. * @param from where to start deleting (inclusive)
  678. * @param to where to end deleting (inclusive)
  679. */
  680. public void delete(InstructionHandle from, InstructionHandle to) throws TargetLostException {
  681. remove(from.prev, to.next, false);
  682. }
  683. /**
  684. * Remove instructions from instruction `from' to instruction `to' contained in this list. The user must ensure that `from' is
  685. * an instruction before `to', or risk havoc. The corresponding Instruction handles must not be reused!
  686. *
  687. * @param from where to start deleting (inclusive)
  688. * @param to where to end deleting (inclusive)
  689. */
  690. public void delete(Instruction from, Instruction to) throws TargetLostException {
  691. InstructionHandle from_ih, to_ih;
  692. if ((from_ih = findInstruction1(from)) == null) {
  693. throw new ClassGenException("Instruction " + from + " is not contained in this list.");
  694. }
  695. if ((to_ih = findInstruction2(to)) == null) {
  696. throw new ClassGenException("Instruction " + to + " is not contained in this list.");
  697. }
  698. delete(from_ih, to_ih);
  699. }
  700. /**
  701. * Search for given Instruction reference, start at beginning of list.
  702. *
  703. * @param i instruction to search for
  704. * @return instruction found on success, null otherwise
  705. */
  706. private InstructionHandle findInstruction1(Instruction i) {
  707. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  708. if (ih.instruction == i) {
  709. return ih;
  710. }
  711. }
  712. return null;
  713. }
  714. /**
  715. * Search for given Instruction reference, start at end of list
  716. *
  717. * @param i instruction to search for
  718. * @return instruction found on success, null otherwise
  719. */
  720. private InstructionHandle findInstruction2(Instruction i) {
  721. for (InstructionHandle ih = end; ih != null; ih = ih.prev) {
  722. if (ih.instruction == i) {
  723. return ih;
  724. }
  725. }
  726. return null;
  727. }
  728. public boolean contains(InstructionHandle i) {
  729. if (i == null) {
  730. return false;
  731. }
  732. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  733. if (ih == i) {
  734. return true;
  735. }
  736. }
  737. return false;
  738. }
  739. public boolean contains(Instruction i) {
  740. return findInstruction1(i) != null;
  741. }
  742. public void setPositions() {
  743. setPositions(false);
  744. }
  745. /**
  746. * Give all instructions their position number (offset in byte stream), i.e., make the list ready to be dumped.
  747. *
  748. * @param check Perform sanity checks, e.g. if all targeted instructions really belong to this list
  749. */
  750. public void setPositions(boolean check) {
  751. int maxAdditionalBytes = 0;
  752. int index = 0, count = 0;
  753. int[] pos = new int[length];
  754. // Pass 0: Sanity checks
  755. if (check) {
  756. checkInstructionList();
  757. }
  758. // Pass 1: Set position numbers and sum up the maximum number of bytes an
  759. // instruction may be shifted.
  760. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  761. Instruction i = ih.instruction;
  762. ih.setPosition(index);
  763. pos[count++] = index;
  764. /*
  765. * Get an estimate about how many additional bytes may be added, because BranchInstructions may have variable length
  766. * depending on the target offset (short vs. int) or alignment issues (TABLESWITCH and LOOKUPSWITCH).
  767. */
  768. switch (i.opcode) {
  769. case Constants.JSR:
  770. case Constants.GOTO:
  771. maxAdditionalBytes += 2;
  772. break;
  773. case Constants.TABLESWITCH:
  774. case Constants.LOOKUPSWITCH:
  775. maxAdditionalBytes += 3;
  776. break;
  777. }
  778. index += i.getLength();
  779. }
  780. // OPTIMIZE positions will only move around if there have been expanding instructions
  781. // if (max_additional_bytes==0...) {
  782. //
  783. // }
  784. /*
  785. * Pass 2: Expand the variable-length (Branch)Instructions depending on the target offset (short or int) and ensure that
  786. * branch targets are within this list.
  787. */
  788. boolean nonZeroOffset = false;
  789. int offset = 0;
  790. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  791. if (ih instanceof BranchHandle) {
  792. offset += ((BranchHandle) ih).updatePosition(offset, maxAdditionalBytes);
  793. if (offset != 0) {
  794. nonZeroOffset = true;
  795. }
  796. }
  797. }
  798. if (nonZeroOffset) {
  799. /*
  800. * Pass 3: Update position numbers (which may have changed due to the preceding expansions), like pass 1.
  801. */
  802. index = count = 0;
  803. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  804. Instruction i = ih.instruction;
  805. ih.setPosition(index);
  806. pos[count++] = index;
  807. index += i.getLength();
  808. }
  809. }
  810. positions = new int[count]; // Trim to proper size
  811. System.arraycopy(pos, 0, positions, 0, count);
  812. }
  813. private void checkInstructionList() {
  814. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  815. Instruction i = ih.instruction;
  816. if (i instanceof InstructionBranch) { // target instruction within list?
  817. Instruction inst = ((InstructionBranch) i).getTarget().instruction;
  818. if (!contains(inst)) {
  819. throw new ClassGenException("Branch target of " + Constants.OPCODE_NAMES[i.opcode] + ":" + inst
  820. + " not in instruction list");
  821. }
  822. if (i instanceof InstructionSelect) {
  823. InstructionHandle[] targets = ((InstructionSelect) i).getTargets();
  824. for (InstructionHandle target : targets) {
  825. inst = target.instruction;
  826. if (!contains(inst)) {
  827. throw new ClassGenException("Branch target of " + Constants.OPCODE_NAMES[i.opcode] + ":" + inst
  828. + " not in instruction list");
  829. }
  830. }
  831. }
  832. if (!(ih instanceof BranchHandle)) {
  833. throw new ClassGenException("Branch instruction " + Constants.OPCODE_NAMES[i.opcode] + ":" + inst
  834. + " not contained in BranchHandle.");
  835. }
  836. }
  837. }
  838. }
  839. /**
  840. * When everything is finished, use this method to convert the instruction list into an array of bytes.
  841. *
  842. * @return the byte code ready to be dumped
  843. */
  844. public byte[] getByteCode() {
  845. // Update position indices of instructions
  846. setPositions();
  847. ByteArrayOutputStream b = new ByteArrayOutputStream();
  848. DataOutputStream out = new DataOutputStream(b);
  849. try {
  850. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  851. Instruction i = ih.instruction;
  852. i.dump(out); // Traverse list
  853. }
  854. } catch (IOException e) {
  855. System.err.println(e);
  856. return null;
  857. }
  858. byte[] byteCode = b.toByteArray();
  859. if (byteCode.length > Constants.MAX_CODE_SIZE) {
  860. throw new ClassGenException("Code size too big: " + byteCode.length);
  861. }
  862. return byteCode;
  863. }
  864. /**
  865. * @return an array of instructions without target information for branch instructions.
  866. */
  867. public Instruction[] getInstructions() {
  868. ByteSequence bytes = new ByteSequence(getByteCode());
  869. ArrayList<Instruction> instructions = new ArrayList<Instruction>();
  870. try {
  871. while (bytes.available() > 0) {
  872. instructions.add(Instruction.readInstruction(bytes));
  873. }
  874. } catch (IOException e) {
  875. throw new ClassGenException(e.toString());
  876. }
  877. Instruction[] result = new Instruction[instructions.size()];
  878. instructions.toArray(result);
  879. return result;
  880. }
  881. @Override
  882. public String toString() {
  883. return toString(true);
  884. }
  885. /**
  886. * @param verbose toggle output format
  887. * @return String containing all instructions in this list.
  888. */
  889. public String toString(boolean verbose) {
  890. StringBuffer buf = new StringBuffer();
  891. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  892. buf.append(ih.toString(verbose) + "\n");
  893. }
  894. return buf.toString();
  895. }
  896. /**
  897. * @return Enumeration that lists all instructions (handles)
  898. */
  899. public Iterator iterator() {
  900. return new Iterator() {
  901. private InstructionHandle ih = start;
  902. public Object next() {
  903. InstructionHandle i = ih;
  904. ih = ih.next;
  905. return i;
  906. }
  907. public void remove() {
  908. throw new UnsupportedOperationException();
  909. }
  910. public boolean hasNext() {
  911. return ih != null;
  912. }
  913. };
  914. }
  915. /**
  916. * @return array containing all instructions (handles)
  917. */
  918. public InstructionHandle[] getInstructionHandles() {
  919. InstructionHandle[] ihs = new InstructionHandle[length];
  920. InstructionHandle ih = start;
  921. for (int i = 0; i < length; i++) {
  922. ihs[i] = ih;
  923. ih = ih.next;
  924. }
  925. return ihs;
  926. }
  927. /**
  928. * Get positions (offsets) of all instructions in the list. This relies on that the list has been freshly created from an byte
  929. * code array, or that setPositions() has been called. Otherwise this may be inaccurate.
  930. *
  931. * @return array containing all instruction's offset in byte code
  932. */
  933. public int[] getInstructionPositions() {
  934. return positions;
  935. }
  936. /**
  937. * @return complete, i.e., deep copy of this list
  938. */
  939. public InstructionList copy() {
  940. HashMap<InstructionHandle, InstructionHandle> map = new HashMap<InstructionHandle, InstructionHandle>();
  941. InstructionList il = new InstructionList();
  942. /*
  943. * Pass 1: Make copies of all instructions, append them to the new list and associate old instruction references with the
  944. * new ones, i.e., a 1:1 mapping.
  945. */
  946. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  947. Instruction i = ih.instruction;
  948. Instruction c = i.copy(); // Use clone for shallow copy
  949. if (c instanceof InstructionBranch) {
  950. map.put(ih, il.append((InstructionBranch) c));
  951. } else {
  952. map.put(ih, il.append(c));
  953. }
  954. }
  955. /*
  956. * Pass 2: Update branch targets.
  957. */
  958. InstructionHandle ih = start;
  959. InstructionHandle ch = il.start;
  960. while (ih != null) {
  961. Instruction i = ih.instruction;
  962. Instruction c = ch.instruction;
  963. if (i instanceof InstructionBranch) {
  964. InstructionBranch bi = (InstructionBranch) i;
  965. InstructionBranch bc = (InstructionBranch) c;
  966. InstructionHandle itarget = bi.getTarget(); // old target
  967. // New target is in hash map
  968. bc.setTarget(map.get(itarget));
  969. if (bi instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH
  970. InstructionHandle[] itargets = ((InstructionSelect) bi).getTargets();
  971. InstructionHandle[] ctargets = ((InstructionSelect) bc).getTargets();
  972. for (int j = 0; j < itargets.length; j++) { // Update all targets
  973. ctargets[j] = map.get(itargets[j]);
  974. }
  975. }
  976. }
  977. ih = ih.next;
  978. ch = ch.next;
  979. }
  980. return il;
  981. }
  982. /**
  983. * Replace all references to the old constant pool with references to the new constant pool
  984. */
  985. public void replaceConstantPool(ConstantPool old_cp, ConstantPool new_cp) {
  986. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  987. Instruction i = ih.instruction;
  988. if (i.isConstantPoolInstruction()) {
  989. InstructionCP ci = (InstructionCP) i;
  990. Constant c = old_cp.getConstant(ci.getIndex());
  991. ci.setIndex(new_cp.addConstant(c, old_cp));
  992. }
  993. }
  994. }
  995. private void clear() {
  996. start = end = null;
  997. length = 0;
  998. }
  999. /**
  1000. * Delete contents of list. Provides better memory utilization, because the system then may reuse the instruction handles. This
  1001. * method is typically called right after <href="MethodGen.html#getMethod()">MethodGen.getMethod()</a>.
  1002. */
  1003. public void dispose() {
  1004. // Traverse in reverse order, because ih.next is overwritten
  1005. for (InstructionHandle ih = end; ih != null; ih = ih.prev) {
  1006. /*
  1007. * Causes BranchInstructions to release target and targeters, because it calls dispose() on the contained instruction.
  1008. */
  1009. ih.dispose();
  1010. }
  1011. clear();
  1012. }
  1013. /**
  1014. * @return start of list
  1015. */
  1016. public InstructionHandle getStart() {
  1017. return start;
  1018. }
  1019. /**
  1020. * @return end of list
  1021. */
  1022. public InstructionHandle getEnd() {
  1023. return end;
  1024. }
  1025. /**
  1026. * @return length of list (Number of instructions, not bytes)
  1027. */
  1028. public int getLength() {
  1029. return length;
  1030. }
  1031. /**
  1032. * @return length of list (Number of instructions, not bytes)
  1033. */
  1034. public int size() {
  1035. return length;
  1036. }
  1037. /**
  1038. * Redirect all references from old_target to new_target, i.e., update targets of branch instructions.
  1039. *
  1040. * @param old_target the old target instruction handle
  1041. * @param new_target the new target instruction handle
  1042. */
  1043. public void redirectBranches(InstructionHandle old_target, InstructionHandle new_target) {
  1044. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  1045. Instruction i = ih.getInstruction();
  1046. if (i instanceof InstructionBranch) {
  1047. InstructionBranch b = (InstructionBranch) i;
  1048. InstructionHandle target = b.getTarget();
  1049. if (target == old_target) {
  1050. b.setTarget(new_target);
  1051. }
  1052. if (b instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH
  1053. InstructionHandle[] targets = ((InstructionSelect) b).getTargets();
  1054. for (int j = 0; j < targets.length; j++) {
  1055. if (targets[j] == old_target) {
  1056. ((InstructionSelect) b).setTarget(j, new_target);
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. }
  1063. /**
  1064. * Redirect all references of local variables from old_target to new_target.
  1065. *
  1066. * @param lg array of local variables
  1067. * @param old_target the old target instruction handle
  1068. * @param new_target the new target instruction handle
  1069. * @see MethodGen
  1070. */
  1071. public void redirectLocalVariables(LocalVariableGen[] lg, InstructionHandle old_target, InstructionHandle new_target) {
  1072. for (LocalVariableGen localVariableGen : lg) {
  1073. InstructionHandle start = localVariableGen.getStart();
  1074. InstructionHandle end = localVariableGen.getEnd();
  1075. if (start == old_target) {
  1076. localVariableGen.setStart(new_target);
  1077. }
  1078. if (end == old_target) {
  1079. localVariableGen.setEnd(new_target);
  1080. }
  1081. }
  1082. }
  1083. /**
  1084. * Redirect all references of exception handlers from old_target to new_target.
  1085. *
  1086. * @param exceptions array of exception handlers
  1087. * @param old_target the old target instruction handle
  1088. * @param new_target the new target instruction handle
  1089. * @see MethodGen
  1090. */
  1091. public void redirectExceptionHandlers(CodeExceptionGen[] exceptions, InstructionHandle old_target, InstructionHandle new_target) {
  1092. for (CodeExceptionGen exception : exceptions) {
  1093. if (exception.getStartPC() == old_target) {
  1094. exception.setStartPC(new_target);
  1095. }
  1096. if (exception.getEndPC() == old_target) {
  1097. exception.setEndPC(new_target);
  1098. }
  1099. if (exception.getHandlerPC() == old_target) {
  1100. exception.setHandlerPC(new_target);
  1101. }
  1102. }
  1103. }
  1104. }