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

12 years ago
13 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
12 years ago
15 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
15 years ago
14 years ago
14 years ago
15 years ago
15 years ago
15 years ago
15 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  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<>();
  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. for (InstructionTargeter instructionTargeter : targeters) {
  604. if (instructionTargeter.getClass().getName().endsWith("ShadowRange")
  605. || instructionTargeter.getClass().getName().endsWith("ExceptionRange")
  606. || instructionTargeter.getClass().getName().endsWith("LineNumberTag")) {
  607. isOK = true;
  608. } else {
  609. System.out.println(instructionTargeter.getClass());
  610. }
  611. }
  612. if (!isOK) {
  613. target_vec.add(ih);
  614. buf.append(ih.toString(true) + " ");
  615. ih.next = ih.prev = null;
  616. } else {
  617. ih.dispose();
  618. }
  619. // if (ih.hasTargeters()) { // Still got targeters?
  620. // InstructionTargeter[] targeters = ih.getTargeters();
  621. // boolean isOK = false;
  622. // for (int i = 0; i < targeters.length; i++) {
  623. // InstructionTargeter instructionTargeter = targeters[i];
  624. // if (instructionTargeter.getClass().getName().endsWith("ShadowRange")
  625. // || instructionTargeter.getClass().getName().endsWith("ExceptionRange")
  626. // || instructionTargeter.getClass().getName().endsWith("LineNumberTag")) {
  627. // isOK = true;
  628. // } else {
  629. // System.out.println(instructionTargeter.getClass());
  630. // }
  631. // }
  632. // if (!isOK) {
  633. // target_vec.add(ih);
  634. // buf.append(ih.toString(true) + " ");
  635. // ih.next = ih.prev = null;
  636. // } else {
  637. // ih.dispose();
  638. // }
  639. // } else {
  640. // ih.dispose();
  641. // }
  642. }
  643. buf.append("}");
  644. if (!target_vec.isEmpty()) {
  645. InstructionHandle[] targeted = new InstructionHandle[target_vec.size()];
  646. target_vec.toArray(targeted);
  647. throw new TargetLostException(targeted, buf.toString());
  648. }
  649. }
  650. /**
  651. * Remove instruction from this list. The corresponding Instruction handles must not be reused!
  652. *
  653. * @param ih instruction (handle) to remove
  654. */
  655. public void delete(InstructionHandle ih) throws TargetLostException {
  656. remove(ih.prev, ih.next, false);
  657. }
  658. /**
  659. * Remove instruction from this list. The corresponding Instruction handles must not be reused!
  660. *
  661. * @param i instruction to remove
  662. */
  663. // public void delete(Instruction i) throws TargetLostException {
  664. // InstructionHandle ih;
  665. //
  666. // if((ih = findInstruction1(i)) == null)
  667. // throw new ClassGenException("Instruction " + i +
  668. // " is not contained in this list.");
  669. // delete(ih);
  670. // }
  671. /**
  672. * Remove instructions from instruction `from' to instruction `to' contained in this list. The user must ensure that `from' is
  673. * an instruction before `to', or risk havoc. The corresponding Instruction handles must not be reused!
  674. *
  675. * @param from where to start deleting (inclusive)
  676. * @param to where to end deleting (inclusive)
  677. */
  678. public void delete(InstructionHandle from, InstructionHandle to) throws TargetLostException {
  679. remove(from.prev, to.next, false);
  680. }
  681. /**
  682. * Remove instructions from instruction `from' to instruction `to' contained in this list. The user must ensure that `from' is
  683. * an instruction before `to', or risk havoc. The corresponding Instruction handles must not be reused!
  684. *
  685. * @param from where to start deleting (inclusive)
  686. * @param to where to end deleting (inclusive)
  687. */
  688. public void delete(Instruction from, Instruction to) throws TargetLostException {
  689. InstructionHandle from_ih, to_ih;
  690. if ((from_ih = findInstruction1(from)) == null) {
  691. throw new ClassGenException("Instruction " + from + " is not contained in this list.");
  692. }
  693. if ((to_ih = findInstruction2(to)) == null) {
  694. throw new ClassGenException("Instruction " + to + " is not contained in this list.");
  695. }
  696. delete(from_ih, to_ih);
  697. }
  698. /**
  699. * Search for given Instruction reference, start at beginning of list.
  700. *
  701. * @param i instruction to search for
  702. * @return instruction found on success, null otherwise
  703. */
  704. private InstructionHandle findInstruction1(Instruction i) {
  705. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  706. if (ih.instruction == i) {
  707. return ih;
  708. }
  709. }
  710. return null;
  711. }
  712. /**
  713. * Search for given Instruction reference, start at end of list
  714. *
  715. * @param i instruction to search for
  716. * @return instruction found on success, null otherwise
  717. */
  718. private InstructionHandle findInstruction2(Instruction i) {
  719. for (InstructionHandle ih = end; ih != null; ih = ih.prev) {
  720. if (ih.instruction == i) {
  721. return ih;
  722. }
  723. }
  724. return null;
  725. }
  726. public boolean contains(InstructionHandle i) {
  727. if (i == null) {
  728. return false;
  729. }
  730. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  731. if (ih == i) {
  732. return true;
  733. }
  734. }
  735. return false;
  736. }
  737. public boolean contains(Instruction i) {
  738. return findInstruction1(i) != null;
  739. }
  740. public void setPositions() {
  741. setPositions(false);
  742. }
  743. /**
  744. * Give all instructions their position number (offset in byte stream), i.e., make the list ready to be dumped.
  745. *
  746. * @param check Perform sanity checks, e.g. if all targeted instructions really belong to this list
  747. */
  748. public void setPositions(boolean check) {
  749. int maxAdditionalBytes = 0;
  750. int index = 0, count = 0;
  751. int[] pos = new int[length];
  752. // Pass 0: Sanity checks
  753. if (check) {
  754. checkInstructionList();
  755. }
  756. // Pass 1: Set position numbers and sum up the maximum number of bytes an
  757. // instruction may be shifted.
  758. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  759. Instruction i = ih.instruction;
  760. ih.setPosition(index);
  761. pos[count++] = index;
  762. /*
  763. * Get an estimate about how many additional bytes may be added, because BranchInstructions may have variable length
  764. * depending on the target offset (short vs. int) or alignment issues (TABLESWITCH and LOOKUPSWITCH).
  765. */
  766. switch (i.opcode) {
  767. case Constants.JSR:
  768. case Constants.GOTO:
  769. maxAdditionalBytes += 2;
  770. break;
  771. case Constants.TABLESWITCH:
  772. case Constants.LOOKUPSWITCH:
  773. maxAdditionalBytes += 3;
  774. break;
  775. }
  776. index += i.getLength();
  777. }
  778. // OPTIMIZE positions will only move around if there have been expanding instructions
  779. // if (max_additional_bytes==0...) {
  780. //
  781. // }
  782. /*
  783. * Pass 2: Expand the variable-length (Branch)Instructions depending on the target offset (short or int) and ensure that
  784. * branch targets are within this list.
  785. */
  786. boolean nonZeroOffset = false;
  787. int offset = 0;
  788. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  789. if (ih instanceof BranchHandle) {
  790. offset += ((BranchHandle) ih).updatePosition(offset, maxAdditionalBytes);
  791. if (offset != 0) {
  792. nonZeroOffset = true;
  793. }
  794. }
  795. }
  796. if (nonZeroOffset) {
  797. /*
  798. * Pass 3: Update position numbers (which may have changed due to the preceding expansions), like pass 1.
  799. */
  800. index = count = 0;
  801. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  802. Instruction i = ih.instruction;
  803. ih.setPosition(index);
  804. pos[count++] = index;
  805. index += i.getLength();
  806. }
  807. }
  808. positions = new int[count]; // Trim to proper size
  809. System.arraycopy(pos, 0, positions, 0, count);
  810. }
  811. private void checkInstructionList() {
  812. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  813. Instruction i = ih.instruction;
  814. if (i instanceof InstructionBranch) { // target instruction within list?
  815. Instruction inst = ((InstructionBranch) i).getTarget().instruction;
  816. if (!contains(inst)) {
  817. throw new ClassGenException("Branch target of " + Constants.OPCODE_NAMES[i.opcode] + ":" + inst
  818. + " not in instruction list");
  819. }
  820. if (i instanceof InstructionSelect) {
  821. InstructionHandle[] targets = ((InstructionSelect) i).getTargets();
  822. for (InstructionHandle target : targets) {
  823. inst = target.instruction;
  824. if (!contains(inst)) {
  825. throw new ClassGenException("Branch target of " + Constants.OPCODE_NAMES[i.opcode] + ":" + inst
  826. + " not in instruction list");
  827. }
  828. }
  829. }
  830. if (!(ih instanceof BranchHandle)) {
  831. throw new ClassGenException("Branch instruction " + Constants.OPCODE_NAMES[i.opcode] + ":" + inst
  832. + " not contained in BranchHandle.");
  833. }
  834. }
  835. }
  836. }
  837. /**
  838. * When everything is finished, use this method to convert the instruction list into an array of bytes.
  839. *
  840. * @return the byte code ready to be dumped
  841. */
  842. public byte[] getByteCode() {
  843. // Update position indices of instructions
  844. setPositions();
  845. ByteArrayOutputStream b = new ByteArrayOutputStream();
  846. DataOutputStream out = new DataOutputStream(b);
  847. try {
  848. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  849. Instruction i = ih.instruction;
  850. i.dump(out); // Traverse list
  851. }
  852. } catch (IOException e) {
  853. System.err.println(e);
  854. return null;
  855. }
  856. byte[] byteCode = b.toByteArray();
  857. if (byteCode.length > Constants.MAX_CODE_SIZE) {
  858. throw new ClassGenException("Code size too big: " + byteCode.length);
  859. }
  860. return byteCode;
  861. }
  862. /**
  863. * @return an array of instructions without target information for branch instructions.
  864. */
  865. public Instruction[] getInstructions() {
  866. ByteSequence bytes = new ByteSequence(getByteCode());
  867. ArrayList<Instruction> instructions = new ArrayList<>();
  868. try {
  869. while (bytes.available() > 0) {
  870. instructions.add(Instruction.readInstruction(bytes));
  871. }
  872. } catch (IOException e) {
  873. throw new ClassGenException(e.toString());
  874. }
  875. Instruction[] result = new Instruction[instructions.size()];
  876. instructions.toArray(result);
  877. return result;
  878. }
  879. @Override
  880. public String toString() {
  881. return toString(true);
  882. }
  883. /**
  884. * @param verbose toggle output format
  885. * @return String containing all instructions in this list.
  886. */
  887. public String toString(boolean verbose) {
  888. StringBuffer buf = new StringBuffer();
  889. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  890. buf.append(ih.toString(verbose) + "\n");
  891. }
  892. return buf.toString();
  893. }
  894. /**
  895. * @return Enumeration that lists all instructions (handles)
  896. */
  897. public Iterator iterator() {
  898. return new Iterator() {
  899. private InstructionHandle ih = start;
  900. public Object next() {
  901. InstructionHandle i = ih;
  902. ih = ih.next;
  903. return i;
  904. }
  905. public void remove() {
  906. throw new UnsupportedOperationException();
  907. }
  908. public boolean hasNext() {
  909. return ih != null;
  910. }
  911. };
  912. }
  913. /**
  914. * @return array containing all instructions (handles)
  915. */
  916. public InstructionHandle[] getInstructionHandles() {
  917. InstructionHandle[] ihs = new InstructionHandle[length];
  918. InstructionHandle ih = start;
  919. for (int i = 0; i < length; i++) {
  920. ihs[i] = ih;
  921. ih = ih.next;
  922. }
  923. return ihs;
  924. }
  925. /**
  926. * Get positions (offsets) of all instructions in the list. This relies on that the list has been freshly created from an byte
  927. * code array, or that setPositions() has been called. Otherwise this may be inaccurate.
  928. *
  929. * @return array containing all instruction's offset in byte code
  930. */
  931. public int[] getInstructionPositions() {
  932. return positions;
  933. }
  934. /**
  935. * @return complete, i.e., deep copy of this list
  936. */
  937. public InstructionList copy() {
  938. HashMap<InstructionHandle, InstructionHandle> map = new HashMap<>();
  939. InstructionList il = new InstructionList();
  940. /*
  941. * Pass 1: Make copies of all instructions, append them to the new list and associate old instruction references with the
  942. * new ones, i.e., a 1:1 mapping.
  943. */
  944. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  945. Instruction i = ih.instruction;
  946. Instruction c = i.copy(); // Use clone for shallow copy
  947. if (c instanceof InstructionBranch) {
  948. map.put(ih, il.append((InstructionBranch) c));
  949. } else {
  950. map.put(ih, il.append(c));
  951. }
  952. }
  953. /*
  954. * Pass 2: Update branch targets.
  955. */
  956. InstructionHandle ih = start;
  957. InstructionHandle ch = il.start;
  958. while (ih != null) {
  959. Instruction i = ih.instruction;
  960. Instruction c = ch.instruction;
  961. if (i instanceof InstructionBranch) {
  962. InstructionBranch bi = (InstructionBranch) i;
  963. InstructionBranch bc = (InstructionBranch) c;
  964. InstructionHandle itarget = bi.getTarget(); // old target
  965. // New target is in hash map
  966. bc.setTarget(map.get(itarget));
  967. if (bi instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH
  968. InstructionHandle[] itargets = ((InstructionSelect) bi).getTargets();
  969. InstructionHandle[] ctargets = ((InstructionSelect) bc).getTargets();
  970. for (int j = 0; j < itargets.length; j++) { // Update all targets
  971. ctargets[j] = map.get(itargets[j]);
  972. }
  973. }
  974. }
  975. ih = ih.next;
  976. ch = ch.next;
  977. }
  978. return il;
  979. }
  980. /**
  981. * Replace all references to the old constant pool with references to the new constant pool
  982. */
  983. public void replaceConstantPool(ConstantPool old_cp, ConstantPool new_cp) {
  984. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  985. Instruction i = ih.instruction;
  986. if (i.isConstantPoolInstruction()) {
  987. InstructionCP ci = (InstructionCP) i;
  988. Constant c = old_cp.getConstant(ci.getIndex());
  989. ci.setIndex(new_cp.addConstant(c, old_cp));
  990. }
  991. }
  992. }
  993. private void clear() {
  994. start = end = null;
  995. length = 0;
  996. }
  997. /**
  998. * Delete contents of list. Provides better memory utilization, because the system then may reuse the instruction handles. This
  999. * method is typically called right after <href="MethodGen.html#getMethod()">MethodGen.getMethod()</a>.
  1000. */
  1001. public void dispose() {
  1002. // Traverse in reverse order, because ih.next is overwritten
  1003. for (InstructionHandle ih = end; ih != null; ih = ih.prev) {
  1004. /*
  1005. * Causes BranchInstructions to release target and targeters, because it calls dispose() on the contained instruction.
  1006. */
  1007. ih.dispose();
  1008. }
  1009. clear();
  1010. }
  1011. /**
  1012. * @return start of list
  1013. */
  1014. public InstructionHandle getStart() {
  1015. return start;
  1016. }
  1017. /**
  1018. * @return end of list
  1019. */
  1020. public InstructionHandle getEnd() {
  1021. return end;
  1022. }
  1023. /**
  1024. * @return length of list (Number of instructions, not bytes)
  1025. */
  1026. public int getLength() {
  1027. return length;
  1028. }
  1029. /**
  1030. * @return length of list (Number of instructions, not bytes)
  1031. */
  1032. public int size() {
  1033. return length;
  1034. }
  1035. /**
  1036. * Redirect all references from old_target to new_target, i.e., update targets of branch instructions.
  1037. *
  1038. * @param old_target the old target instruction handle
  1039. * @param new_target the new target instruction handle
  1040. */
  1041. public void redirectBranches(InstructionHandle old_target, InstructionHandle new_target) {
  1042. for (InstructionHandle ih = start; ih != null; ih = ih.next) {
  1043. Instruction i = ih.getInstruction();
  1044. if (i instanceof InstructionBranch) {
  1045. InstructionBranch b = (InstructionBranch) i;
  1046. InstructionHandle target = b.getTarget();
  1047. if (target == old_target) {
  1048. b.setTarget(new_target);
  1049. }
  1050. if (b instanceof InstructionSelect) { // Either LOOKUPSWITCH or TABLESWITCH
  1051. InstructionHandle[] targets = ((InstructionSelect) b).getTargets();
  1052. for (int j = 0; j < targets.length; j++) {
  1053. if (targets[j] == old_target) {
  1054. ((InstructionSelect) b).setTarget(j, new_target);
  1055. }
  1056. }
  1057. }
  1058. }
  1059. }
  1060. }
  1061. /**
  1062. * Redirect all references of local variables from old_target to new_target.
  1063. *
  1064. * @param lg array of local variables
  1065. * @param old_target the old target instruction handle
  1066. * @param new_target the new target instruction handle
  1067. * @see MethodGen
  1068. */
  1069. public void redirectLocalVariables(LocalVariableGen[] lg, InstructionHandle old_target, InstructionHandle new_target) {
  1070. for (LocalVariableGen localVariableGen : lg) {
  1071. InstructionHandle start = localVariableGen.getStart();
  1072. InstructionHandle end = localVariableGen.getEnd();
  1073. if (start == old_target) {
  1074. localVariableGen.setStart(new_target);
  1075. }
  1076. if (end == old_target) {
  1077. localVariableGen.setEnd(new_target);
  1078. }
  1079. }
  1080. }
  1081. /**
  1082. * Redirect all references of exception handlers from old_target to new_target.
  1083. *
  1084. * @param exceptions array of exception handlers
  1085. * @param old_target the old target instruction handle
  1086. * @param new_target the new target instruction handle
  1087. * @see MethodGen
  1088. */
  1089. public void redirectExceptionHandlers(CodeExceptionGen[] exceptions, InstructionHandle old_target, InstructionHandle new_target) {
  1090. for (CodeExceptionGen exception : exceptions) {
  1091. if (exception.getStartPC() == old_target) {
  1092. exception.setStartPC(new_target);
  1093. }
  1094. if (exception.getEndPC() == old_target) {
  1095. exception.setEndPC(new_target);
  1096. }
  1097. if (exception.getHandlerPC() == old_target) {
  1098. exception.setHandlerPC(new_target);
  1099. }
  1100. }
  1101. }
  1102. }