diff --git a/.gitignore b/.gitignore index a8f62996..505a0967 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ .DS_Store *.iml /out/ +/target/ diff --git a/libs/Krakatau-11.zip b/libs/Krakatau-11.jar similarity index 100% rename from libs/Krakatau-11.zip rename to libs/Krakatau-11.jar diff --git a/libs/annotations-17.0.0.jar b/libs/annotations-17.0.0.jar deleted file mode 100644 index 477f7d02..00000000 Binary files a/libs/annotations-17.0.0.jar and /dev/null differ diff --git a/libs/apktool_2.3.0.jar b/libs/apktool_2.3.0.jar deleted file mode 100644 index 8f838ef2..00000000 Binary files a/libs/apktool_2.3.0.jar and /dev/null differ diff --git a/libs/apktool_2.5.0.jar b/libs/apktool_2.5.0.jar new file mode 100644 index 00000000..577e3f80 Binary files /dev/null and b/libs/apktool_2.5.0.jar differ diff --git a/libs/asm-9.1.jar b/libs/asm-9.1.jar deleted file mode 100644 index 82380198..00000000 Binary files a/libs/asm-9.1.jar and /dev/null differ diff --git a/libs/asm-analysis-9.1.jar b/libs/asm-analysis-9.1.jar deleted file mode 100644 index f97d1244..00000000 Binary files a/libs/asm-analysis-9.1.jar and /dev/null differ diff --git a/libs/asm-commons-9.1.jar b/libs/asm-commons-9.1.jar deleted file mode 100644 index 9d78d4ec..00000000 Binary files a/libs/asm-commons-9.1.jar and /dev/null differ diff --git a/libs/asm-tree-9.1.jar b/libs/asm-tree-9.1.jar deleted file mode 100644 index 0375862d..00000000 Binary files a/libs/asm-tree-9.1.jar and /dev/null differ diff --git a/libs/asm-util-9.1.jar b/libs/asm-util-9.1.jar deleted file mode 100644 index a746c57c..00000000 Binary files a/libs/asm-util-9.1.jar and /dev/null differ diff --git a/libs/cfr-0.145.jar b/libs/cfr-0.145.jar deleted file mode 100644 index ddf1602f..00000000 Binary files a/libs/cfr-0.145.jar and /dev/null differ diff --git a/libs/cfr-license.txt b/libs/cfr-license.txt deleted file mode 100644 index 0e856931..00000000 --- a/libs/cfr-license.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2011-2019 Lee Benfield - https://www.benf.org/other/cfr - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/libs/cloning-1.9.12.jar b/libs/cloning-1.9.12.jar deleted file mode 100644 index 162bf38b..00000000 Binary files a/libs/cloning-1.9.12.jar and /dev/null differ diff --git a/libs/commons-cli-1.4.jar b/libs/commons-cli-1.4.jar deleted file mode 100644 index 22deb308..00000000 Binary files a/libs/commons-cli-1.4.jar and /dev/null differ diff --git a/libs/commons-codec-1.12.jar b/libs/commons-codec-1.12.jar deleted file mode 100644 index 531478ea..00000000 Binary files a/libs/commons-codec-1.12.jar and /dev/null differ diff --git a/libs/commons-compiler.jar b/libs/commons-compiler.jar deleted file mode 100644 index 46cd6630..00000000 Binary files a/libs/commons-compiler.jar and /dev/null differ diff --git a/libs/commons-compress-1.18.jar b/libs/commons-compress-1.18.jar deleted file mode 100644 index e401046b..00000000 Binary files a/libs/commons-compress-1.18.jar and /dev/null differ diff --git a/libs/commons-io-2.4.jar b/libs/commons-io-2.4.jar deleted file mode 100644 index 90035a4f..00000000 Binary files a/libs/commons-io-2.4.jar and /dev/null differ diff --git a/libs/commons-lang3-3.3.2.jar b/libs/commons-lang3-3.3.2.jar deleted file mode 100644 index bb069797..00000000 Binary files a/libs/commons-lang3-3.3.2.jar and /dev/null differ diff --git a/libs/commons-license.txt b/libs/commons-license.txt deleted file mode 100644 index d955a86d..00000000 --- a/libs/commons-license.txt +++ /dev/null @@ -1,11 +0,0 @@ -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file diff --git a/libs/dx-1.16.jar b/libs/dx-1.16.jar deleted file mode 100644 index 6e468ce7..00000000 Binary files a/libs/dx-1.16.jar and /dev/null differ diff --git a/libs/enjarify-3.zip b/libs/enjarify-3.jar similarity index 100% rename from libs/enjarify-3.zip rename to libs/enjarify-3.jar diff --git a/libs/fernflower-2019.jar b/libs/fernflower-2019.jar deleted file mode 100644 index a90e3273..00000000 Binary files a/libs/fernflower-2019.jar and /dev/null differ diff --git a/libs/fernflower-license.txt b/libs/fernflower-license.txt deleted file mode 100644 index d955a86d..00000000 --- a/libs/fernflower-license.txt +++ /dev/null @@ -1,11 +0,0 @@ -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file diff --git a/libs/gson-2.8.5.jar b/libs/gson-2.8.5.jar deleted file mode 100644 index 0d5baf3f..00000000 Binary files a/libs/gson-2.8.5.jar and /dev/null differ diff --git a/libs/imgscalr-lib-4.2.jar b/libs/imgscalr-lib-4.2.jar deleted file mode 100644 index bb7a406b..00000000 Binary files a/libs/imgscalr-lib-4.2.jar and /dev/null differ diff --git a/libs/imgscalr-license.txt b/libs/imgscalr-license.txt deleted file mode 100644 index 7a4a3ea2..00000000 --- a/libs/imgscalr-license.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/libs/janino-license.txt b/libs/janino-license.txt deleted file mode 100644 index 9df4ca68..00000000 --- a/libs/janino-license.txt +++ /dev/null @@ -1 +0,0 @@ -http://opensource.org/licenses/BSD-3-Clause \ No newline at end of file diff --git a/libs/janino.jar b/libs/janino.jar deleted file mode 100644 index 79b946df..00000000 Binary files a/libs/janino.jar and /dev/null differ diff --git a/libs/jgraphx-license.txt b/libs/jgraphx-license.txt deleted file mode 100644 index fdb59b00..00000000 --- a/libs/jgraphx-license.txt +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2001-2014, JGraph Ltd -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the JGraph nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL JGRAPH BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/libs/jgraphx.jar b/libs/jgraphx.jar deleted file mode 100644 index e70d4c82..00000000 Binary files a/libs/jgraphx.jar and /dev/null differ diff --git a/libs/objenesis-3.0.1.jar b/libs/objenesis-3.0.1.jar deleted file mode 100644 index 8521c847..00000000 Binary files a/libs/objenesis-3.0.1.jar and /dev/null differ diff --git a/libs/procyon-decompiler-0.5.34.jar b/libs/procyon-decompiler-0.5.34.jar deleted file mode 100644 index a2acbd97..00000000 Binary files a/libs/procyon-decompiler-0.5.34.jar and /dev/null differ diff --git a/libs/procyon-license.txt b/libs/procyon-license.txt deleted file mode 100644 index a453e432..00000000 --- a/libs/procyon-license.txt +++ /dev/null @@ -1,55 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of this License; and - - -You must cause any modified files to carry prominent notices stating that You changed the files; and - - -You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and - - -If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. -You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. \ No newline at end of file diff --git a/libs/rsyntaxtextarea-license.txt b/libs/rsyntaxtextarea-license.txt deleted file mode 100644 index f0f2d4c7..00000000 --- a/libs/rsyntaxtextarea-license.txt +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2012, Robert Futrell -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the author nor the names of its contributors may - be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/libs/rsyntaxtextarea.jar b/libs/rsyntaxtextarea.jar deleted file mode 100644 index e6f415ce..00000000 Binary files a/libs/rsyntaxtextarea.jar and /dev/null differ diff --git a/libs/slf4j-api-1.7.26.jar b/libs/slf4j-api-1.7.26.jar deleted file mode 100644 index d2f27ace..00000000 Binary files a/libs/slf4j-api-1.7.26.jar and /dev/null differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..b8af4a33 --- /dev/null +++ b/pom.xml @@ -0,0 +1,282 @@ + + 4.0.0 + + de.femtopedia + bytecodeviewer + 2.9.23 + + + + com.android + android + 5.1 + system + ${project.basedir}/libs/android-5.1.jar + + + org.jetbrains + annotations + 20.1.0 + + + com.brut + apktool + 2.5.0 + system + ${project.basedir}/libs/apktool_2.5.0.jar + + + org.ow2.asm + asm + 9.1 + + + org.ow2.asm + asm-analysis + 9.1 + + + org.ow2.asm + asm-commons + 9.1 + + + org.ow2.asm + asm-tree + 9.1 + + + org.ow2.asm + asm-util + 9.1 + + + eu.bibl + byteanalysis + 1.0 + system + ${project.basedir}/libs/byteanalysis-1.0.jar + + + org.benf + cfr + 0.151 + + + uk.com.robust-it + cloning + 1.9.12 + + + commons-cli + commons-cli + 1.4 + + + commons-codec + commons-codec + 1.15 + + + org.codehaus.janino + commons-compiler + 3.1.3 + + + org.apache.commons + commons-compress + 1.20 + + + commons-io + commons-io + 2.8.0 + + + org.apache.commons + commons-lang3 + 3.12.0 + + + com.googlecode + d2jar + 1.0 + system + ${project.basedir}/libs/d2jar-lib-obf.jar + + + com.rover12421.android + dx + 1.16 + + + enjarify + enjarify + 3 + system + ${project.basedir}/libs/enjarify-3.jar + + + org.jboss.windup.decompiler + decompiler-fernflower + 5.1.3.Final + + + com.google.code.gson + gson + 2.8.6 + + + org.imgscalr + imgscalr-lib + 4.2 + + + jadx + jadx-core + 1.0 + system + ${project.basedir}/libs/jadx-core.jar + + + org.codehaus.janino + janino + 3.1.3 + + + com.jd + jd-gui + 1.0.0-RC4 + system + ${project.basedir}/libs/jd-gui-1.0.0-RC4.jar + + + org.tinyjee.jgraphx + jgraphx + 3.4.1.3 + + + krakatau + krakatau + 11 + system + ${project.basedir}/libs/Krakatau-11.jar + + + org.objenesis + objenesis + 3.2 + test + + + org.bitbucket.mstrobel + procyon-core + 0.5.36 + + + org.bitbucket.mstrobel + procyon-expressions + 0.5.36 + + + org.bitbucket.mstrobel + procyon-reflection + 0.5.36 + + + org.bitbucket.mstrobel + procyon-compilertools + 0.5.36 + + + com.fifesoft + rsyntaxtextarea + 3.1.2 + + + org.slf4j + slf4j-api + 1.7.30 + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + + + true + the.bytecode.club.bytecodeviewer.BytecodeViewer + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 8 + 8 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.2.0 + + 8 + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.2 + + + package + + shade + + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + com.googlecode.addjars-maven-plugin + addjars-maven-plugin + 1.0.5 + + + + add-jars + + + + + ${basedir}/libs + + + + + + + + + + \ No newline at end of file diff --git a/src/LICENSES/ASM.txt b/src/main/java/LICENSES/ASM.txt similarity index 100% rename from src/LICENSES/ASM.txt rename to src/main/java/LICENSES/ASM.txt diff --git a/src/LICENSES/Apache License 2.0.txt b/src/main/java/LICENSES/Apache License 2.0.txt similarity index 100% rename from src/LICENSES/Apache License 2.0.txt rename to src/main/java/LICENSES/Apache License 2.0.txt diff --git a/src/LICENSES/BCV.txt b/src/main/java/LICENSES/BCV.txt similarity index 98% rename from src/LICENSES/BCV.txt rename to src/main/java/LICENSES/BCV.txt index 60e7b895..c1005cad 100644 --- a/src/LICENSES/BCV.txt +++ b/src/main/java/LICENSES/BCV.txt @@ -1,638 +1,638 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - - Bytecode Viewer - Java & Android Reverse Engineering Suite - Copyright (C) 2014 Kalen "Konloch" Kinloch - http://bytecodeviewer.com - http://the.bytecode.club - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + + Bytecode Viewer - Java & Android Reverse Engineering Suite + Copyright (C) 2014 Kalen "Konloch" Kinloch - http://bytecodeviewer.com - http://the.bytecode.club + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see . \ No newline at end of file diff --git a/src/LICENSES/ByteAnalysis.txt b/src/main/java/LICENSES/ByteAnalysis.txt similarity index 100% rename from src/LICENSES/ByteAnalysis.txt rename to src/main/java/LICENSES/ByteAnalysis.txt diff --git a/src/LICENSES/CFR.txt b/src/main/java/LICENSES/CFR.txt similarity index 100% rename from src/LICENSES/CFR.txt rename to src/main/java/LICENSES/CFR.txt diff --git a/src/LICENSES/JD.txt b/src/main/java/LICENSES/JD.txt similarity index 100% rename from src/LICENSES/JD.txt rename to src/main/java/LICENSES/JD.txt diff --git a/src/LICENSES/JGraphX.txt b/src/main/java/LICENSES/JGraphX.txt similarity index 100% rename from src/LICENSES/JGraphX.txt rename to src/main/java/LICENSES/JGraphX.txt diff --git a/src/LICENSES/Janino.txt b/src/main/java/LICENSES/Janino.txt similarity index 100% rename from src/LICENSES/Janino.txt rename to src/main/java/LICENSES/Janino.txt diff --git a/src/LICENSES/RSyntaxTextArea.txt b/src/main/java/LICENSES/RSyntaxTextArea.txt similarity index 100% rename from src/LICENSES/RSyntaxTextArea.txt rename to src/main/java/LICENSES/RSyntaxTextArea.txt diff --git a/src/LICENSES/license.txt b/src/main/java/LICENSES/license.txt similarity index 100% rename from src/LICENSES/license.txt rename to src/main/java/LICENSES/license.txt diff --git a/src/LICENSES/smali.txt b/src/main/java/LICENSES/smali.txt similarity index 100% rename from src/LICENSES/smali.txt rename to src/main/java/LICENSES/smali.txt diff --git a/src/com/jhe/hexed/JHexEditor.java b/src/main/java/com/jhe/hexed/JHexEditor.java similarity index 100% rename from src/com/jhe/hexed/JHexEditor.java rename to src/main/java/com/jhe/hexed/JHexEditor.java diff --git a/src/com/jhe/hexed/JHexEditorASCII.java b/src/main/java/com/jhe/hexed/JHexEditorASCII.java similarity index 97% rename from src/com/jhe/hexed/JHexEditorASCII.java rename to src/main/java/com/jhe/hexed/JHexEditorASCII.java index b69c1fbf..a2f7ce91 100644 --- a/src/com/jhe/hexed/JHexEditorASCII.java +++ b/src/main/java/com/jhe/hexed/JHexEditorASCII.java @@ -135,7 +135,12 @@ public class JHexEditorASCII extends JComponent implements MouseListener, debug("keyReleased(" + e + ")"); } + @SuppressWarnings("deprecation") public boolean isFocusTraversable() { return true; } + + public boolean isFocusable() { + return true; + } } diff --git a/src/com/jhe/hexed/JHexEditorHEX.java b/src/main/java/com/jhe/hexed/JHexEditorHEX.java similarity index 97% rename from src/com/jhe/hexed/JHexEditorHEX.java rename to src/main/java/com/jhe/hexed/JHexEditorHEX.java index 718fffb6..b0a1954d 100644 --- a/src/com/jhe/hexed/JHexEditorHEX.java +++ b/src/main/java/com/jhe/hexed/JHexEditorHEX.java @@ -148,7 +148,12 @@ public class JHexEditorHEX extends JComponent implements MouseListener, debug("keyReleased(" + e + ")"); } + @SuppressWarnings("deprecation") public boolean isFocusTraversable() { return true; } + + public boolean isFocusable() { + return true; + } } diff --git a/src/jd/cli/Main.java b/src/main/java/jd/cli/Main.java similarity index 100% rename from src/jd/cli/Main.java rename to src/main/java/jd/cli/Main.java diff --git a/src/jd/cli/loader/BaseLoader.java b/src/main/java/jd/cli/loader/BaseLoader.java similarity index 100% rename from src/jd/cli/loader/BaseLoader.java rename to src/main/java/jd/cli/loader/BaseLoader.java diff --git a/src/jd/cli/loader/DirectoryLoader.java b/src/main/java/jd/cli/loader/DirectoryLoader.java similarity index 100% rename from src/jd/cli/loader/DirectoryLoader.java rename to src/main/java/jd/cli/loader/DirectoryLoader.java diff --git a/src/jd/cli/loader/JarLoader.java b/src/main/java/jd/cli/loader/JarLoader.java similarity index 100% rename from src/jd/cli/loader/JarLoader.java rename to src/main/java/jd/cli/loader/JarLoader.java diff --git a/src/jd/cli/loader/LoaderManager.java b/src/main/java/jd/cli/loader/LoaderManager.java similarity index 100% rename from src/jd/cli/loader/LoaderManager.java rename to src/main/java/jd/cli/loader/LoaderManager.java diff --git a/src/jd/cli/preferences/CommonPreferences.java b/src/main/java/jd/cli/preferences/CommonPreferences.java similarity index 100% rename from src/jd/cli/preferences/CommonPreferences.java rename to src/main/java/jd/cli/preferences/CommonPreferences.java diff --git a/src/jd/cli/printer/html/HtmlPrinter.java b/src/main/java/jd/cli/printer/html/HtmlPrinter.java similarity index 100% rename from src/jd/cli/printer/html/HtmlPrinter.java rename to src/main/java/jd/cli/printer/html/HtmlPrinter.java diff --git a/src/jd/cli/printer/text/PlainTextPrinter.java b/src/main/java/jd/cli/printer/text/PlainTextPrinter.java similarity index 100% rename from src/jd/cli/printer/text/PlainTextPrinter.java rename to src/main/java/jd/cli/printer/text/PlainTextPrinter.java diff --git a/src/jd/cli/util/ClassFileUtil.java b/src/main/java/jd/cli/util/ClassFileUtil.java similarity index 100% rename from src/jd/cli/util/ClassFileUtil.java rename to src/main/java/jd/cli/util/ClassFileUtil.java diff --git a/src/jd/cli/util/CommonTypeNameUtil.java b/src/main/java/jd/cli/util/CommonTypeNameUtil.java similarity index 100% rename from src/jd/cli/util/CommonTypeNameUtil.java rename to src/main/java/jd/cli/util/CommonTypeNameUtil.java diff --git a/src/jd/cli/util/VersionUtil.java b/src/main/java/jd/cli/util/VersionUtil.java similarity index 100% rename from src/jd/cli/util/VersionUtil.java rename to src/main/java/jd/cli/util/VersionUtil.java diff --git a/src/me/konloch/kontainer/io/DiskReader.java b/src/main/java/me/konloch/kontainer/io/DiskReader.java similarity index 100% rename from src/me/konloch/kontainer/io/DiskReader.java rename to src/main/java/me/konloch/kontainer/io/DiskReader.java diff --git a/src/me/konloch/kontainer/io/DiskWriter.java b/src/main/java/me/konloch/kontainer/io/DiskWriter.java similarity index 100% rename from src/me/konloch/kontainer/io/DiskWriter.java rename to src/main/java/me/konloch/kontainer/io/DiskWriter.java diff --git a/src/me/konloch/kontainer/io/HTTPRequest.java b/src/main/java/me/konloch/kontainer/io/HTTPRequest.java similarity index 100% rename from src/me/konloch/kontainer/io/HTTPRequest.java rename to src/main/java/me/konloch/kontainer/io/HTTPRequest.java diff --git a/src/org/objectweb/asm/ClassReader.java b/src/main/java/org/objectweb/asm/ClassReader.java similarity index 97% rename from src/org/objectweb/asm/ClassReader.java rename to src/main/java/org/objectweb/asm/ClassReader.java index 4de37e9a..a8dc6672 100644 --- a/src/org/objectweb/asm/ClassReader.java +++ b/src/main/java/org/objectweb/asm/ClassReader.java @@ -1,3633 +1,3633 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package org.objectweb.asm; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * A parser to make a {@link ClassVisitor} visit a ClassFile structure, as defined in the Java - * Virtual Machine Specification (JVMS). This class parses the ClassFile content and calls the - * appropriate visit methods of a given {@link ClassVisitor} for each field, method and bytecode - * instruction encountered. - * - * @see JVMS 4 - * @author Eric Bruneton - * @author Eugene Kuleshov - */ -public class ClassReader { - - /** - * A flag to skip the Code attributes. If this flag is set the Code attributes are neither parsed - * nor visited. - */ - public static final int SKIP_CODE = 1; - - /** - * A flag to skip the SourceFile, SourceDebugExtension, LocalVariableTable, LocalVariableTypeTable - * and LineNumberTable attributes. If this flag is set these attributes are neither parsed nor - * visited (i.e. {@link ClassVisitor#visitSource}, {@link MethodVisitor#visitLocalVariable} and - * {@link MethodVisitor#visitLineNumber} are not called). - */ - public static final int SKIP_DEBUG = 2; - - /** - * A flag to skip the StackMap and StackMapTable attributes. If this flag is set these attributes - * are neither parsed nor visited (i.e. {@link MethodVisitor#visitFrame} is not called). This flag - * is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is used: it avoids visiting frames - * that will be ignored and recomputed from scratch. - */ - public static final int SKIP_FRAMES = 4; - - /** - * A flag to expand the stack map frames. By default stack map frames are visited in their - * original format (i.e. "expanded" for classes whose version is less than V1_6, and "compressed" - * for the other classes). If this flag is set, stack map frames are always visited in expanded - * format (this option adds a decompression/compression step in ClassReader and ClassWriter which - * degrades performance quite a lot). - */ - public static final int EXPAND_FRAMES = 8; - - /** - * A flag to expand the ASM specific instructions into an equivalent sequence of standard bytecode - * instructions. When resolving a forward jump it may happen that the signed 2 bytes offset - * reserved for it is not sufficient to store the bytecode offset. In this case the jump - * instruction is replaced with a temporary ASM specific instruction using an unsigned 2 bytes - * offset (see {@link Label#resolve}). This internal flag is used to re-read classes containing - * such instructions, in order to replace them with standard instructions. In addition, when this - * flag is used, goto_w and jsr_w are not converted into goto and jsr, to make sure that - * infinite loops where a goto_w is replaced with a goto in ClassReader and converted back to a - * goto_w in ClassWriter cannot occur. - */ - static final int EXPAND_ASM_INSNS = 256; - - /** The size of the temporary byte array used to read class input streams chunk by chunk. */ - private static final int INPUT_STREAM_DATA_CHUNK_SIZE = 4096; - - /** - * A byte array containing the JVMS ClassFile structure to be parsed. - * - * @deprecated Use {@link #readByte(int)} and the other read methods instead. This field will - * eventually be deleted. - */ - @Deprecated - // DontCheck(MemberName): can't be renamed (for backward binary compatibility). - public final byte[] b; - - /** - * A byte array containing the JVMS ClassFile structure to be parsed. The content of this array - * must not be modified. This field is intended for {@link Attribute} sub classes, and is normally - * not needed by class visitors. - * - *

NOTE: the ClassFile structure can start at any offset within this array, i.e. it does not - * necessarily start at offset 0. Use {@link #getItem} and {@link #header} to get correct - * ClassFile element offsets within this byte array. - */ - final byte[] classFileBuffer; - - /** - * The offset in bytes, in {@link #classFileBuffer}, of each cp_info entry of the ClassFile's - * constant_pool array, plus one. In other words, the offset of constant pool entry i is - * given by cpInfoOffsets[i] - 1, i.e. its cp_info's tag field is given by b[cpInfoOffsets[i] - - * 1]. - */ - private final int[] cpInfoOffsets; - - /** - * The String objects corresponding to the CONSTANT_Utf8 constant pool items. This cache avoids - * multiple parsing of a given CONSTANT_Utf8 constant pool item. - */ - private final String[] constantUtf8Values; - - /** - * The ConstantDynamic objects corresponding to the CONSTANT_Dynamic constant pool items. This - * cache avoids multiple parsing of a given CONSTANT_Dynamic constant pool item. - */ - private final ConstantDynamic[] constantDynamicValues; - - /** - * The start offsets in {@link #classFileBuffer} of each element of the bootstrap_methods array - * (in the BootstrapMethods attribute). - * - * @see JVMS - * 4.7.23 - */ - private final int[] bootstrapMethodOffsets; - - /** - * A conservative estimate of the maximum length of the strings contained in the constant pool of - * the class. - */ - private final int maxStringLength; - - /** The offset in bytes of the ClassFile's access_flags field. */ - public final int header; - - // ----------------------------------------------------------------------------------------------- - // Constructors - // ----------------------------------------------------------------------------------------------- - - /** - * Constructs a new {@link ClassReader} object. - * - * @param classFile the JVMS ClassFile structure to be read. - */ - public ClassReader(final byte[] classFile) { - this(classFile, 0, classFile.length); - } - - /** - * Constructs a new {@link ClassReader} object. - * - * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read. - * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read. - * @param classFileLength the length in bytes of the ClassFile to be read. - */ - public ClassReader( - final byte[] classFileBuffer, - final int classFileOffset, - final int classFileLength) { // NOPMD(UnusedFormalParameter) used for backward compatibility. - this(classFileBuffer, classFileOffset, /* checkClassVersion = */ true); - } - - /** - * Constructs a new {@link ClassReader} object. This internal constructor must not be exposed - * as a public API. - * - * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read. - * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read. - * @param checkClassVersion whether to check the class version or not. - */ - ClassReader( - final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion) { - this.classFileBuffer = classFileBuffer; - this.b = classFileBuffer; - // Check the class' major_version. This field is after the magic and minor_version fields, which - // use 4 and 2 bytes respectively. - if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V17) { - throw new IllegalArgumentException( - "Unsupported class file major version " + readShort(classFileOffset + 6)); - } - // Create the constant pool arrays. The constant_pool_count field is after the magic, - // minor_version and major_version fields, which use 4, 2 and 2 bytes respectively. - int constantPoolCount = readUnsignedShort(classFileOffset + 8); - cpInfoOffsets = new int[constantPoolCount]; - constantUtf8Values = new String[constantPoolCount]; - // Compute the offset of each constant pool entry, as well as a conservative estimate of the - // maximum length of the constant pool strings. The first constant pool entry is after the - // magic, minor_version, major_version and constant_pool_count fields, which use 4, 2, 2 and 2 - // bytes respectively. - int currentCpInfoIndex = 1; - int currentCpInfoOffset = classFileOffset + 10; - int currentMaxStringLength = 0; - boolean hasBootstrapMethods = false; - boolean hasConstantDynamic = false; - // The offset of the other entries depend on the total size of all the previous entries. - while (currentCpInfoIndex < constantPoolCount) { - cpInfoOffsets[currentCpInfoIndex++] = currentCpInfoOffset + 1; - int cpInfoSize; - switch (classFileBuffer[currentCpInfoOffset]) { - case Symbol.CONSTANT_FIELDREF_TAG: - case Symbol.CONSTANT_METHODREF_TAG: - case Symbol.CONSTANT_INTERFACE_METHODREF_TAG: - case Symbol.CONSTANT_INTEGER_TAG: - case Symbol.CONSTANT_FLOAT_TAG: - case Symbol.CONSTANT_NAME_AND_TYPE_TAG: - cpInfoSize = 5; - break; - case Symbol.CONSTANT_DYNAMIC_TAG: - cpInfoSize = 5; - hasBootstrapMethods = true; - hasConstantDynamic = true; - break; - case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG: - cpInfoSize = 5; - hasBootstrapMethods = true; - break; - case Symbol.CONSTANT_LONG_TAG: - case Symbol.CONSTANT_DOUBLE_TAG: - cpInfoSize = 9; - currentCpInfoIndex++; - break; - case Symbol.CONSTANT_UTF8_TAG: - cpInfoSize = 3 + readUnsignedShort(currentCpInfoOffset + 1); - if (cpInfoSize > currentMaxStringLength) { - // The size in bytes of this CONSTANT_Utf8 structure provides a conservative estimate - // of the length in characters of the corresponding string, and is much cheaper to - // compute than this exact length. - currentMaxStringLength = cpInfoSize; - } - break; - case Symbol.CONSTANT_METHOD_HANDLE_TAG: - cpInfoSize = 4; - break; - case Symbol.CONSTANT_CLASS_TAG: - case Symbol.CONSTANT_STRING_TAG: - case Symbol.CONSTANT_METHOD_TYPE_TAG: - case Symbol.CONSTANT_PACKAGE_TAG: - case Symbol.CONSTANT_MODULE_TAG: - cpInfoSize = 3; - break; - default: - throw new IllegalArgumentException(); - } - currentCpInfoOffset += cpInfoSize; - } - maxStringLength = currentMaxStringLength; - // The Classfile's access_flags field is just after the last constant pool entry. - header = currentCpInfoOffset; - - // Allocate the cache of ConstantDynamic values, if there is at least one. - constantDynamicValues = hasConstantDynamic ? new ConstantDynamic[constantPoolCount] : null; - - // Read the BootstrapMethods attribute, if any (only get the offset of each method). - bootstrapMethodOffsets = - hasBootstrapMethods ? readBootstrapMethodsAttribute(currentMaxStringLength) : null; - } - - /** - * Constructs a new {@link ClassReader} object. - * - * @param inputStream an input stream of the JVMS ClassFile structure to be read. This input - * stream must contain nothing more than the ClassFile structure itself. It is read from its - * current position to its end. - * @throws IOException if a problem occurs during reading. - */ - public ClassReader(final InputStream inputStream) throws IOException { - this(readStream(inputStream, false)); - } - - /** - * Constructs a new {@link ClassReader} object. - * - * @param className the fully qualified name of the class to be read. The ClassFile structure is - * retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}. - * @throws IOException if an exception occurs during reading. - */ - public ClassReader(final String className) throws IOException { - this( - readStream( - ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + ".class"), true)); - } - - /** - * Reads the given input stream and returns its content as a byte array. - * - * @param inputStream an input stream. - * @param close true to close the input stream after reading. - * @return the content of the given input stream. - * @throws IOException if a problem occurs during reading. - */ - private static byte[] readStream(final InputStream inputStream, final boolean close) - throws IOException { - if (inputStream == null) { - throw new IOException("Class not found"); - } - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE]; - int bytesRead; - while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) { - outputStream.write(data, 0, bytesRead); - } - outputStream.flush(); - return outputStream.toByteArray(); - } finally { - if (close) { - inputStream.close(); - } - } - } - - // ----------------------------------------------------------------------------------------------- - // Accessors - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the class's access flags (see {@link Opcodes}). This value may not reflect Deprecated - * and Synthetic flags when bytecode is before 1.5 and those flags are represented by attributes. - * - * @return the class access flags. - * @see ClassVisitor#visit(int, int, String, String, String, String[]) - */ - public int getAccess() { - return readUnsignedShort(header); - } - - /** - * Returns the internal name of the class (see {@link Type#getInternalName()}). - * - * @return the internal class name. - * @see ClassVisitor#visit(int, int, String, String, String, String[]) - */ - public String getClassName() { - // this_class is just after the access_flags field (using 2 bytes). - return readClass(header + 2, new char[maxStringLength]); - } - - /** - * Returns the internal of name of the super class (see {@link Type#getInternalName()}). For - * interfaces, the super class is {@link Object}. - * - * @return the internal name of the super class, or {@literal null} for {@link Object} class. - * @see ClassVisitor#visit(int, int, String, String, String, String[]) - */ - public String getSuperName() { - // super_class is after the access_flags and this_class fields (2 bytes each). - return readClass(header + 4, new char[maxStringLength]); - } - - /** - * Returns the internal names of the implemented interfaces (see {@link Type#getInternalName()}). - * - * @return the internal names of the directly implemented interfaces. Inherited implemented - * interfaces are not returned. - * @see ClassVisitor#visit(int, int, String, String, String, String[]) - */ - public String[] getInterfaces() { - // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each). - int currentOffset = header + 6; - int interfacesCount = readUnsignedShort(currentOffset); - String[] interfaces = new String[interfacesCount]; - if (interfacesCount > 0) { - char[] charBuffer = new char[maxStringLength]; - for (int i = 0; i < interfacesCount; ++i) { - currentOffset += 2; - interfaces[i] = readClass(currentOffset, charBuffer); - } - } - return interfaces; - } - - // ----------------------------------------------------------------------------------------------- - // Public methods - // ----------------------------------------------------------------------------------------------- - - /** - * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this - * {@link ClassReader}. - * - * @param classVisitor the visitor that must visit this class. - * @param parsingOptions the options to use to parse this class. One or more of {@link - * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}. - */ - public void accept(final ClassVisitor classVisitor, final int parsingOptions) { - accept(classVisitor, new Attribute[0], parsingOptions); - } - - /** - * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this - * {@link ClassReader}. - * - * @param classVisitor the visitor that must visit this class. - * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of - * the class. Any attribute whose type is not equal to the type of one the prototypes will not - * be parsed: its byte array value will be passed unchanged to the ClassWriter. This may - * corrupt it if this value contains references to the constant pool, or has syntactic or - * semantic links with a class element that has been transformed by a class adapter between - * the reader and the writer. - * @param parsingOptions the options to use to parse this class. One or more of {@link - * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}. - */ - public void accept( - final ClassVisitor classVisitor, - final Attribute[] attributePrototypes, - final int parsingOptions) { - Context context = new Context(); - context.attributePrototypes = attributePrototypes; - context.parsingOptions = parsingOptions; - context.charBuffer = new char[maxStringLength]; - - // Read the access_flags, this_class, super_class, interface_count and interfaces fields. - char[] charBuffer = context.charBuffer; - int currentOffset = header; - int accessFlags = readUnsignedShort(currentOffset); - String thisClass = readClass(currentOffset + 2, charBuffer); - String superClass = readClass(currentOffset + 4, charBuffer); - String[] interfaces = new String[readUnsignedShort(currentOffset + 6)]; - currentOffset += 8; - for (int i = 0; i < interfaces.length; ++i) { - interfaces[i] = readClass(currentOffset, charBuffer); - currentOffset += 2; - } - - // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS). - // Attribute offsets exclude the attribute_name_index and attribute_length fields. - // - The offset of the InnerClasses attribute, or 0. - int innerClassesOffset = 0; - // - The offset of the EnclosingMethod attribute, or 0. - int enclosingMethodOffset = 0; - // - The string corresponding to the Signature attribute, or null. - String signature = null; - // - The string corresponding to the SourceFile attribute, or null. - String sourceFile = null; - // - The string corresponding to the SourceDebugExtension attribute, or null. - String sourceDebugExtension = null; - // - The offset of the RuntimeVisibleAnnotations attribute, or 0. - int runtimeVisibleAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. - int runtimeInvisibleAnnotationsOffset = 0; - // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. - int runtimeVisibleTypeAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. - int runtimeInvisibleTypeAnnotationsOffset = 0; - // - The offset of the Module attribute, or 0. - int moduleOffset = 0; - // - The offset of the ModulePackages attribute, or 0. - int modulePackagesOffset = 0; - // - The string corresponding to the ModuleMainClass attribute, or null. - String moduleMainClass = null; - // - The string corresponding to the NestHost attribute, or null. - String nestHostClass = null; - // - The offset of the NestMembers attribute, or 0. - int nestMembersOffset = 0; - // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). - // This list in the reverse order or their order in the ClassFile structure. - Attribute attributes = null; - - int currentAttributeOffset = getFirstAttributeOffset(); - for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentAttributeOffset, charBuffer); - int attributeLength = readInt(currentAttributeOffset + 2); - currentAttributeOffset += 6; - // The tests are sorted in decreasing frequency order (based on frequencies observed on - // typical classes). - if (Constants.SOURCE_FILE.equals(attributeName)) { - sourceFile = readUTF8(currentAttributeOffset, charBuffer); - } else if (Constants.INNER_CLASSES.equals(attributeName)) { - innerClassesOffset = currentAttributeOffset; - } else if (Constants.ENCLOSING_METHOD.equals(attributeName)) { - enclosingMethodOffset = currentAttributeOffset; - } else if (Constants.NEST_HOST.equals(attributeName)) { - nestHostClass = readClass(currentAttributeOffset, charBuffer); - } else if (Constants.NEST_MEMBERS.equals(attributeName)) { - nestMembersOffset = currentAttributeOffset; - } else if (Constants.SIGNATURE.equals(attributeName)) { - signature = readUTF8(currentAttributeOffset, charBuffer); - } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleAnnotationsOffset = currentAttributeOffset; - } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset; - } else if (Constants.DEPRECATED.equals(attributeName)) { - accessFlags |= Opcodes.ACC_DEPRECATED; - } else if (Constants.SYNTHETIC.equals(attributeName)) { - accessFlags |= Opcodes.ACC_SYNTHETIC; - } else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) { - sourceDebugExtension = - readUtf(currentAttributeOffset, attributeLength, new char[attributeLength]); - } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleAnnotationsOffset = currentAttributeOffset; - } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset; - } else if (Constants.MODULE.equals(attributeName)) { - moduleOffset = currentAttributeOffset; - } else if (Constants.MODULE_MAIN_CLASS.equals(attributeName)) { - moduleMainClass = readClass(currentAttributeOffset, charBuffer); - } else if (Constants.MODULE_PACKAGES.equals(attributeName)) { - modulePackagesOffset = currentAttributeOffset; - } else if (!Constants.BOOTSTRAP_METHODS.equals(attributeName)) { - // The BootstrapMethods attribute is read in the constructor. - Attribute attribute = - readAttribute( - attributePrototypes, - attributeName, - currentAttributeOffset, - attributeLength, - charBuffer, - -1, - null); - attribute.nextAttribute = attributes; - attributes = attribute; - } - currentAttributeOffset += attributeLength; - } - - // Visit the class declaration. The minor_version and major_version fields start 6 bytes before - // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition). - classVisitor.visit( - readInt(cpInfoOffsets[1] - 7), accessFlags, thisClass, signature, superClass, interfaces); - - // Visit the SourceFile and SourceDebugExtenstion attributes. - if ((parsingOptions & SKIP_DEBUG) == 0 - && (sourceFile != null || sourceDebugExtension != null)) { - classVisitor.visitSource(sourceFile, sourceDebugExtension); - } - - // Visit the Module, ModulePackages and ModuleMainClass attributes. - if (moduleOffset != 0) { - readModuleAttributes( - classVisitor, context, moduleOffset, modulePackagesOffset, moduleMainClass); - } - - // Visit the NestHost attribute. - if (nestHostClass != null) { - classVisitor.visitNestHost(nestHostClass); - } - - // Visit the EnclosingMethod attribute. - if (enclosingMethodOffset != 0) { - String className = readClass(enclosingMethodOffset, charBuffer); - int methodIndex = readUnsignedShort(enclosingMethodOffset + 2); - String name = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex], charBuffer); - String type = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex] + 2, charBuffer); - classVisitor.visitOuterClass(className, name, type); - } - - // Visit the RuntimeVisibleAnnotations attribute. - if (runtimeVisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleAnnotations attribute. - if (runtimeInvisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeVisibleTypeAnnotations attribute. - if (runtimeVisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - classVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleTypeAnnotations attribute. - if (runtimeInvisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - classVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the non standard attributes. - while (attributes != null) { - // Copy and reset the nextAttribute field so that it can also be used in ClassWriter. - Attribute nextAttribute = attributes.nextAttribute; - attributes.nextAttribute = null; - classVisitor.visitAttribute(attributes); - attributes = nextAttribute; - } - - // Visit the NestedMembers attribute. - if (nestMembersOffset != 0) { - int numberOfNestMembers = readUnsignedShort(nestMembersOffset); - int currentNestMemberOffset = nestMembersOffset + 2; - while (numberOfNestMembers-- > 0) { - classVisitor.visitNestMember(readClass(currentNestMemberOffset, charBuffer)); - currentNestMemberOffset += 2; - } - } - - // Visit the InnerClasses attribute. - if (innerClassesOffset != 0) { - int numberOfClasses = readUnsignedShort(innerClassesOffset); - int currentClassesOffset = innerClassesOffset + 2; - while (numberOfClasses-- > 0) { - classVisitor.visitInnerClass( - readClass(currentClassesOffset, charBuffer), - readClass(currentClassesOffset + 2, charBuffer), - readUTF8(currentClassesOffset + 4, charBuffer), - readUnsignedShort(currentClassesOffset + 6)); - currentClassesOffset += 8; - } - } - - // Visit the fields and methods. - int fieldsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (fieldsCount-- > 0) { - currentOffset = readField(classVisitor, context, currentOffset); - } - int methodsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (methodsCount-- > 0) { - currentOffset = readMethod(classVisitor, context, currentOffset); - } - - // Visit the end of the class. - classVisitor.visitEnd(); - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse modules, fields and methods - // ---------------------------------------------------------------------------------------------- - - /** - * Reads the Module, ModulePackages and ModuleMainClass attributes and visit them. - * - * @param classVisitor the current class visitor - * @param context information about the class being parsed. - * @param moduleOffset the offset of the Module attribute (excluding the attribute_info's - * attribute_name_index and attribute_length fields). - * @param modulePackagesOffset the offset of the ModulePackages attribute (excluding the - * attribute_info's attribute_name_index and attribute_length fields), or 0. - * @param moduleMainClass the string corresponding to the ModuleMainClass attribute, or null. - */ - private void readModuleAttributes( - final ClassVisitor classVisitor, - final Context context, - final int moduleOffset, - final int modulePackagesOffset, - final String moduleMainClass) { - char[] buffer = context.charBuffer; - - // Read the module_name_index, module_flags and module_version_index fields and visit them. - int currentOffset = moduleOffset; - String moduleName = readModule(currentOffset, buffer); - int moduleFlags = readUnsignedShort(currentOffset + 2); - String moduleVersion = readUTF8(currentOffset + 4, buffer); - currentOffset += 6; - ModuleVisitor moduleVisitor = classVisitor.visitModule(moduleName, moduleFlags, moduleVersion); - if (moduleVisitor == null) { - return; - } - - // Visit the ModuleMainClass attribute. - if (moduleMainClass != null) { - moduleVisitor.visitMainClass(moduleMainClass); - } - - // Visit the ModulePackages attribute. - if (modulePackagesOffset != 0) { - int packageCount = readUnsignedShort(modulePackagesOffset); - int currentPackageOffset = modulePackagesOffset + 2; - while (packageCount-- > 0) { - moduleVisitor.visitPackage(readPackage(currentPackageOffset, buffer)); - currentPackageOffset += 2; - } - } - - // Read the 'requires_count' and 'requires' fields. - int requiresCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (requiresCount-- > 0) { - // Read the requires_index, requires_flags and requires_version fields and visit them. - String requires = readModule(currentOffset, buffer); - int requiresFlags = readUnsignedShort(currentOffset + 2); - String requiresVersion = readUTF8(currentOffset + 4, buffer); - currentOffset += 6; - moduleVisitor.visitRequire(requires, requiresFlags, requiresVersion); - } - - // Read the 'exports_count' and 'exports' fields. - int exportsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (exportsCount-- > 0) { - // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields - // and visit them. - String exports = readPackage(currentOffset, buffer); - int exportsFlags = readUnsignedShort(currentOffset + 2); - int exportsToCount = readUnsignedShort(currentOffset + 4); - currentOffset += 6; - String[] exportsTo = null; - if (exportsToCount != 0) { - exportsTo = new String[exportsToCount]; - for (int i = 0; i < exportsToCount; ++i) { - exportsTo[i] = readModule(currentOffset, buffer); - currentOffset += 2; - } - } - moduleVisitor.visitExport(exports, exportsFlags, exportsTo); - } - - // Reads the 'opens_count' and 'opens' fields. - int opensCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (opensCount-- > 0) { - // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them. - String opens = readPackage(currentOffset, buffer); - int opensFlags = readUnsignedShort(currentOffset + 2); - int opensToCount = readUnsignedShort(currentOffset + 4); - currentOffset += 6; - String[] opensTo = null; - if (opensToCount != 0) { - opensTo = new String[opensToCount]; - for (int i = 0; i < opensToCount; ++i) { - opensTo[i] = readModule(currentOffset, buffer); - currentOffset += 2; - } - } - moduleVisitor.visitOpen(opens, opensFlags, opensTo); - } - - // Read the 'uses_count' and 'uses' fields. - int usesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (usesCount-- > 0) { - moduleVisitor.visitUse(readClass(currentOffset, buffer)); - currentOffset += 2; - } - - // Read the 'provides_count' and 'provides' fields. - int providesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (providesCount-- > 0) { - // Read the provides_index, provides_with_count and provides_with_index fields and visit them. - String provides = readClass(currentOffset, buffer); - int providesWithCount = readUnsignedShort(currentOffset + 2); - currentOffset += 4; - String[] providesWith = new String[providesWithCount]; - for (int i = 0; i < providesWithCount; ++i) { - providesWith[i] = readClass(currentOffset, buffer); - currentOffset += 2; - } - moduleVisitor.visitProvide(provides, providesWith); - } - - // Visit the end of the module attributes. - moduleVisitor.visitEnd(); - } - - /** - * Reads a JVMS field_info structure and makes the given visitor visit it. - * - * @param classVisitor the visitor that must visit the field. - * @param context information about the class being parsed. - * @param fieldInfoOffset the start offset of the field_info structure. - * @return the offset of the first byte following the field_info structure. - */ - private int readField( - final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) { - char[] charBuffer = context.charBuffer; - - // Read the access_flags, name_index and descriptor_index fields. - int currentOffset = fieldInfoOffset; - int accessFlags = readUnsignedShort(currentOffset); - String name = readUTF8(currentOffset + 2, charBuffer); - String descriptor = readUTF8(currentOffset + 4, charBuffer); - currentOffset += 6; - - // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS). - // Attribute offsets exclude the attribute_name_index and attribute_length fields. - // - The value corresponding to the ConstantValue attribute, or null. - Object constantValue = null; - // - The string corresponding to the Signature attribute, or null. - String signature = null; - // - The offset of the RuntimeVisibleAnnotations attribute, or 0. - int runtimeVisibleAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. - int runtimeInvisibleAnnotationsOffset = 0; - // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. - int runtimeVisibleTypeAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. - int runtimeInvisibleTypeAnnotationsOffset = 0; - // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). - // This list in the reverse order or their order in the ClassFile structure. - Attribute attributes = null; - - int attributesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (attributesCount-- > 0) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentOffset, charBuffer); - int attributeLength = readInt(currentOffset + 2); - currentOffset += 6; - // The tests are sorted in decreasing frequency order (based on frequencies observed on - // typical classes). - if (Constants.CONSTANT_VALUE.equals(attributeName)) { - int constantvalueIndex = readUnsignedShort(currentOffset); - constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer); - } else if (Constants.SIGNATURE.equals(attributeName)) { - signature = readUTF8(currentOffset, charBuffer); - } else if (Constants.DEPRECATED.equals(attributeName)) { - accessFlags |= Opcodes.ACC_DEPRECATED; - } else if (Constants.SYNTHETIC.equals(attributeName)) { - accessFlags |= Opcodes.ACC_SYNTHETIC; - } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleTypeAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleTypeAnnotationsOffset = currentOffset; - } else { - Attribute attribute = - readAttribute( - context.attributePrototypes, - attributeName, - currentOffset, - attributeLength, - charBuffer, - -1, - null); - attribute.nextAttribute = attributes; - attributes = attribute; - } - currentOffset += attributeLength; - } - - // Visit the field declaration. - FieldVisitor fieldVisitor = - classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue); - if (fieldVisitor == null) { - return currentOffset; - } - - // Visit the RuntimeVisibleAnnotations attribute. - if (runtimeVisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleAnnotations attribute. - if (runtimeInvisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeVisibleTypeAnnotations attribute. - if (runtimeVisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - fieldVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleTypeAnnotations attribute. - if (runtimeInvisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - fieldVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the non standard attributes. - while (attributes != null) { - // Copy and reset the nextAttribute field so that it can also be used in FieldWriter. - Attribute nextAttribute = attributes.nextAttribute; - attributes.nextAttribute = null; - fieldVisitor.visitAttribute(attributes); - attributes = nextAttribute; - } - - // Visit the end of the field. - fieldVisitor.visitEnd(); - return currentOffset; - } - - /** - * Reads a JVMS method_info structure and makes the given visitor visit it. - * - * @param classVisitor the visitor that must visit the method. - * @param context information about the class being parsed. - * @param methodInfoOffset the start offset of the method_info structure. - * @return the offset of the first byte following the method_info structure. - */ - private int readMethod( - final ClassVisitor classVisitor, final Context context, final int methodInfoOffset) { - char[] charBuffer = context.charBuffer; - - // Read the access_flags, name_index and descriptor_index fields. - int currentOffset = methodInfoOffset; - context.currentMethodAccessFlags = readUnsignedShort(currentOffset); - context.currentMethodName = readUTF8(currentOffset + 2, charBuffer); - context.currentMethodDescriptor = readUTF8(currentOffset + 4, charBuffer); - currentOffset += 6; - - // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS). - // Attribute offsets exclude the attribute_name_index and attribute_length fields. - // - The offset of the Code attribute, or 0. - int codeOffset = 0; - // - The offset of the Exceptions attribute, or 0. - int exceptionsOffset = 0; - // - The strings corresponding to the Exceptions attribute, or null. - String[] exceptions = null; - // - Whether the method has a Synthetic attribute. - boolean synthetic = false; - // - The constant pool index contained in the Signature attribute, or 0. - int signatureIndex = 0; - // - The offset of the RuntimeVisibleAnnotations attribute, or 0. - int runtimeVisibleAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. - int runtimeInvisibleAnnotationsOffset = 0; - // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0. - int runtimeVisibleParameterAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0. - int runtimeInvisibleParameterAnnotationsOffset = 0; - // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. - int runtimeVisibleTypeAnnotationsOffset = 0; - // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. - int runtimeInvisibleTypeAnnotationsOffset = 0; - // - The offset of the AnnotationDefault attribute, or 0. - int annotationDefaultOffset = 0; - // - The offset of the MethodParameters attribute, or 0. - int methodParametersOffset = 0; - // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). - // This list in the reverse order or their order in the ClassFile structure. - Attribute attributes = null; - - int attributesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (attributesCount-- > 0) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentOffset, charBuffer); - int attributeLength = readInt(currentOffset + 2); - currentOffset += 6; - // The tests are sorted in decreasing frequency order (based on frequencies observed on - // typical classes). - if (Constants.CODE.equals(attributeName)) { - if ((context.parsingOptions & SKIP_CODE) == 0) { - codeOffset = currentOffset; - } - } else if (Constants.EXCEPTIONS.equals(attributeName)) { - exceptionsOffset = currentOffset; - exceptions = new String[readUnsignedShort(exceptionsOffset)]; - int currentExceptionOffset = exceptionsOffset + 2; - for (int i = 0; i < exceptions.length; ++i) { - exceptions[i] = readClass(currentExceptionOffset, charBuffer); - currentExceptionOffset += 2; - } - } else if (Constants.SIGNATURE.equals(attributeName)) { - signatureIndex = readUnsignedShort(currentOffset); - } else if (Constants.DEPRECATED.equals(attributeName)) { - context.currentMethodAccessFlags |= Opcodes.ACC_DEPRECATED; - } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleTypeAnnotationsOffset = currentOffset; - } else if (Constants.ANNOTATION_DEFAULT.equals(attributeName)) { - annotationDefaultOffset = currentOffset; - } else if (Constants.SYNTHETIC.equals(attributeName)) { - synthetic = true; - context.currentMethodAccessFlags |= Opcodes.ACC_SYNTHETIC; - } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleTypeAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) { - runtimeVisibleParameterAnnotationsOffset = currentOffset; - } else if (Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) { - runtimeInvisibleParameterAnnotationsOffset = currentOffset; - } else if (Constants.METHOD_PARAMETERS.equals(attributeName)) { - methodParametersOffset = currentOffset; - } else { - Attribute attribute = - readAttribute( - context.attributePrototypes, - attributeName, - currentOffset, - attributeLength, - charBuffer, - -1, - null); - attribute.nextAttribute = attributes; - attributes = attribute; - } - currentOffset += attributeLength; - } - - // Visit the method declaration. - MethodVisitor methodVisitor = - classVisitor.visitMethod( - context.currentMethodAccessFlags, - context.currentMethodName, - context.currentMethodDescriptor, - signatureIndex == 0 ? null : readUtf(signatureIndex, charBuffer), - exceptions); - if (methodVisitor == null) { - return currentOffset; - } - - // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method - // adapter between the reader and the writer. In this case, it might be possible to copy - // the method attributes directly into the writer. If so, return early without visiting - // the content of these attributes. - if (methodVisitor instanceof MethodWriter) { - MethodWriter methodWriter = (MethodWriter) methodVisitor; - if (methodWriter.canCopyMethodAttributes( - this, - synthetic, - (context.currentMethodAccessFlags & Opcodes.ACC_DEPRECATED) != 0, - readUnsignedShort(methodInfoOffset + 4), - signatureIndex, - exceptionsOffset)) { - methodWriter.setMethodAttributesSource(methodInfoOffset, currentOffset - methodInfoOffset); - return currentOffset; - } - } - - // Visit the MethodParameters attribute. - if (methodParametersOffset != 0) { - int parametersCount = readByte(methodParametersOffset); - int currentParameterOffset = methodParametersOffset + 1; - while (parametersCount-- > 0) { - // Read the name_index and access_flags fields and visit them. - methodVisitor.visitParameter( - readUTF8(currentParameterOffset, charBuffer), - readUnsignedShort(currentParameterOffset + 2)); - currentParameterOffset += 4; - } - } - - // Visit the AnnotationDefault attribute. - if (annotationDefaultOffset != 0) { - AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault(); - readElementValue(annotationVisitor, annotationDefaultOffset, null, charBuffer); - if (annotationVisitor != null) { - annotationVisitor.visitEnd(); - } - } - - // Visit the RuntimeVisibleAnnotations attribute. - if (runtimeVisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleAnnotations attribute. - if (runtimeInvisibleAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeVisibleTypeAnnotations attribute. - if (runtimeVisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - methodVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeInvisibleTypeAnnotations attribute. - if (runtimeInvisibleTypeAnnotationsOffset != 0) { - int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); - int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; - while (numAnnotations-- > 0) { - // Parse the target_type, target_info and target_path fields. - currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentAnnotationOffset = - readElementValues( - methodVisitor.visitTypeAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - } - - // Visit the RuntimeVisibleParameterAnnotations attribute. - if (runtimeVisibleParameterAnnotationsOffset != 0) { - readParameterAnnotations( - methodVisitor, context, runtimeVisibleParameterAnnotationsOffset, /* visible = */ true); - } - - // Visit the RuntimeInvisibleParameterAnnotations attribute. - if (runtimeInvisibleParameterAnnotationsOffset != 0) { - readParameterAnnotations( - methodVisitor, - context, - runtimeInvisibleParameterAnnotationsOffset, - /* visible = */ false); - } - - // Visit the non standard attributes. - while (attributes != null) { - // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. - Attribute nextAttribute = attributes.nextAttribute; - attributes.nextAttribute = null; - methodVisitor.visitAttribute(attributes); - attributes = nextAttribute; - } - - // Visit the Code attribute. - if (codeOffset != 0) { - methodVisitor.visitCode(); - readCode(methodVisitor, context, codeOffset); - } - - // Visit the end of the method. - methodVisitor.visitEnd(); - return currentOffset; - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse a Code attribute - // ---------------------------------------------------------------------------------------------- - - /** - * Reads a JVMS 'Code' attribute and makes the given visitor visit it. - * - * @param methodVisitor the visitor that must visit the Code attribute. - * @param context information about the class being parsed. - * @param codeOffset the start offset in {@link #classFileBuffer} of the Code attribute, excluding - * its attribute_name_index and attribute_length fields. - */ - private void readCode( - final MethodVisitor methodVisitor, final Context context, final int codeOffset) { - int currentOffset = codeOffset; - - // Read the max_stack, max_locals and code_length fields. - final byte[] classBuffer = classFileBuffer; - final char[] charBuffer = context.charBuffer; - final int majorVersion = readUnsignedShort(6); - final int minorVersion = readUnsignedShort(4); - - final int maxStack; - final int maxLocals; - final int codeLength; - - if (majorVersion == 45 && minorVersion <= 2) { - maxStack = readByte(currentOffset); - maxLocals = readByte(currentOffset + 1); - codeLength = readUnsignedShort(currentOffset + 2); - currentOffset += 4; - } else { - maxStack = readUnsignedShort(currentOffset); - maxLocals = readUnsignedShort(currentOffset + 2); - codeLength = readInt(currentOffset + 4); - currentOffset += 8; - } - - // Read the bytecode 'code' array to create a label for each referenced instruction. - final int bytecodeStartOffset = currentOffset; - final int bytecodeEndOffset = currentOffset + codeLength; - final Label[] labels = context.currentMethodLabels = new Label[codeLength + 1]; - while (currentOffset < bytecodeEndOffset) { - final int bytecodeOffset = currentOffset - bytecodeStartOffset; - final int opcode = classBuffer[currentOffset] & 0xFF; - switch (opcode) { - case Opcodes.NOP: - case Opcodes.ACONST_NULL: - case Opcodes.ICONST_M1: - case Opcodes.ICONST_0: - case Opcodes.ICONST_1: - case Opcodes.ICONST_2: - case Opcodes.ICONST_3: - case Opcodes.ICONST_4: - case Opcodes.ICONST_5: - case Opcodes.LCONST_0: - case Opcodes.LCONST_1: - case Opcodes.FCONST_0: - case Opcodes.FCONST_1: - case Opcodes.FCONST_2: - case Opcodes.DCONST_0: - case Opcodes.DCONST_1: - case Opcodes.IALOAD: - case Opcodes.LALOAD: - case Opcodes.FALOAD: - case Opcodes.DALOAD: - case Opcodes.AALOAD: - case Opcodes.BALOAD: - case Opcodes.CALOAD: - case Opcodes.SALOAD: - case Opcodes.IASTORE: - case Opcodes.LASTORE: - case Opcodes.FASTORE: - case Opcodes.DASTORE: - case Opcodes.AASTORE: - case Opcodes.BASTORE: - case Opcodes.CASTORE: - case Opcodes.SASTORE: - case Opcodes.POP: - case Opcodes.POP2: - case Opcodes.DUP: - case Opcodes.DUP_X1: - case Opcodes.DUP_X2: - case Opcodes.DUP2: - case Opcodes.DUP2_X1: - case Opcodes.DUP2_X2: - case Opcodes.SWAP: - case Opcodes.IADD: - case Opcodes.LADD: - case Opcodes.FADD: - case Opcodes.DADD: - case Opcodes.ISUB: - case Opcodes.LSUB: - case Opcodes.FSUB: - case Opcodes.DSUB: - case Opcodes.IMUL: - case Opcodes.LMUL: - case Opcodes.FMUL: - case Opcodes.DMUL: - case Opcodes.IDIV: - case Opcodes.LDIV: - case Opcodes.FDIV: - case Opcodes.DDIV: - case Opcodes.IREM: - case Opcodes.LREM: - case Opcodes.FREM: - case Opcodes.DREM: - case Opcodes.INEG: - case Opcodes.LNEG: - case Opcodes.FNEG: - case Opcodes.DNEG: - case Opcodes.ISHL: - case Opcodes.LSHL: - case Opcodes.ISHR: - case Opcodes.LSHR: - case Opcodes.IUSHR: - case Opcodes.LUSHR: - case Opcodes.IAND: - case Opcodes.LAND: - case Opcodes.IOR: - case Opcodes.LOR: - case Opcodes.IXOR: - case Opcodes.LXOR: - case Opcodes.I2L: - case Opcodes.I2F: - case Opcodes.I2D: - case Opcodes.L2I: - case Opcodes.L2F: - case Opcodes.L2D: - case Opcodes.F2I: - case Opcodes.F2L: - case Opcodes.F2D: - case Opcodes.D2I: - case Opcodes.D2L: - case Opcodes.D2F: - case Opcodes.I2B: - case Opcodes.I2C: - case Opcodes.I2S: - case Opcodes.LCMP: - case Opcodes.FCMPL: - case Opcodes.FCMPG: - case Opcodes.DCMPL: - case Opcodes.DCMPG: - case Opcodes.IRETURN: - case Opcodes.LRETURN: - case Opcodes.FRETURN: - case Opcodes.DRETURN: - case Opcodes.ARETURN: - case Opcodes.RETURN: - case Opcodes.ARRAYLENGTH: - case Opcodes.ATHROW: - case Opcodes.MONITORENTER: - case Opcodes.MONITOREXIT: - case Constants.ILOAD_0: - case Constants.ILOAD_1: - case Constants.ILOAD_2: - case Constants.ILOAD_3: - case Constants.LLOAD_0: - case Constants.LLOAD_1: - case Constants.LLOAD_2: - case Constants.LLOAD_3: - case Constants.FLOAD_0: - case Constants.FLOAD_1: - case Constants.FLOAD_2: - case Constants.FLOAD_3: - case Constants.DLOAD_0: - case Constants.DLOAD_1: - case Constants.DLOAD_2: - case Constants.DLOAD_3: - case Constants.ALOAD_0: - case Constants.ALOAD_1: - case Constants.ALOAD_2: - case Constants.ALOAD_3: - case Constants.ISTORE_0: - case Constants.ISTORE_1: - case Constants.ISTORE_2: - case Constants.ISTORE_3: - case Constants.LSTORE_0: - case Constants.LSTORE_1: - case Constants.LSTORE_2: - case Constants.LSTORE_3: - case Constants.FSTORE_0: - case Constants.FSTORE_1: - case Constants.FSTORE_2: - case Constants.FSTORE_3: - case Constants.DSTORE_0: - case Constants.DSTORE_1: - case Constants.DSTORE_2: - case Constants.DSTORE_3: - case Constants.ASTORE_0: - case Constants.ASTORE_1: - case Constants.ASTORE_2: - case Constants.ASTORE_3: - currentOffset += 1; - break; - case Opcodes.IFEQ: - case Opcodes.IFNE: - case Opcodes.IFLT: - case Opcodes.IFGE: - case Opcodes.IFGT: - case Opcodes.IFLE: - case Opcodes.IF_ICMPEQ: - case Opcodes.IF_ICMPNE: - case Opcodes.IF_ICMPLT: - case Opcodes.IF_ICMPGE: - case Opcodes.IF_ICMPGT: - case Opcodes.IF_ICMPLE: - case Opcodes.IF_ACMPEQ: - case Opcodes.IF_ACMPNE: - case Opcodes.GOTO: - case Opcodes.JSR: - case Opcodes.IFNULL: - case Opcodes.IFNONNULL: - createLabel(bytecodeOffset + readShort(currentOffset + 1), labels); - currentOffset += 3; - break; - case Constants.ASM_IFEQ: - case Constants.ASM_IFNE: - case Constants.ASM_IFLT: - case Constants.ASM_IFGE: - case Constants.ASM_IFGT: - case Constants.ASM_IFLE: - case Constants.ASM_IF_ICMPEQ: - case Constants.ASM_IF_ICMPNE: - case Constants.ASM_IF_ICMPLT: - case Constants.ASM_IF_ICMPGE: - case Constants.ASM_IF_ICMPGT: - case Constants.ASM_IF_ICMPLE: - case Constants.ASM_IF_ACMPEQ: - case Constants.ASM_IF_ACMPNE: - case Constants.ASM_GOTO: - case Constants.ASM_JSR: - case Constants.ASM_IFNULL: - case Constants.ASM_IFNONNULL: - createLabel(bytecodeOffset + readUnsignedShort(currentOffset + 1), labels); - currentOffset += 3; - break; - case Constants.GOTO_W: - case Constants.JSR_W: - case Constants.ASM_GOTO_W: - createLabel(bytecodeOffset + readInt(currentOffset + 1), labels); - currentOffset += 5; - break; - case Constants.WIDE: - switch (classBuffer[currentOffset + 1] & 0xFF) { - case Opcodes.ILOAD: - case Opcodes.FLOAD: - case Opcodes.ALOAD: - case Opcodes.LLOAD: - case Opcodes.DLOAD: - case Opcodes.ISTORE: - case Opcodes.FSTORE: - case Opcodes.ASTORE: - case Opcodes.LSTORE: - case Opcodes.DSTORE: - case Opcodes.RET: - currentOffset += 4; - break; - case Opcodes.IINC: - currentOffset += 6; - break; - default: - throw new IllegalArgumentException(); - } - break; - case Opcodes.TABLESWITCH: - // Skip 0 to 3 padding bytes. - currentOffset += 4 - (bytecodeOffset & 3); - // Read the default label and the number of table entries. - createLabel(bytecodeOffset + readInt(currentOffset), labels); - int numTableEntries = readInt(currentOffset + 8) - readInt(currentOffset + 4) + 1; - currentOffset += 12; - // Read the table labels. - while (numTableEntries-- > 0) { - createLabel(bytecodeOffset + readInt(currentOffset), labels); - currentOffset += 4; - } - break; - case Opcodes.LOOKUPSWITCH: - // Skip 0 to 3 padding bytes. - currentOffset += 4 - (bytecodeOffset & 3); - // Read the default label and the number of switch cases. - createLabel(bytecodeOffset + readInt(currentOffset), labels); - int numSwitchCases = readInt(currentOffset + 4); - currentOffset += 8; - // Read the switch labels. - while (numSwitchCases-- > 0) { - createLabel(bytecodeOffset + readInt(currentOffset + 4), labels); - currentOffset += 8; - } - break; - case Opcodes.ILOAD: - case Opcodes.LLOAD: - case Opcodes.FLOAD: - case Opcodes.DLOAD: - case Opcodes.ALOAD: - case Opcodes.ISTORE: - case Opcodes.LSTORE: - case Opcodes.FSTORE: - case Opcodes.DSTORE: - case Opcodes.ASTORE: - case Opcodes.RET: - case Opcodes.BIPUSH: - case Opcodes.NEWARRAY: - case Opcodes.LDC: - currentOffset += 2; - break; - case Opcodes.SIPUSH: - case Constants.LDC_W: - case Constants.LDC2_W: - case Opcodes.GETSTATIC: - case Opcodes.PUTSTATIC: - case Opcodes.GETFIELD: - case Opcodes.PUTFIELD: - case Opcodes.INVOKEVIRTUAL: - case Opcodes.INVOKESPECIAL: - case Opcodes.INVOKESTATIC: - case Opcodes.NEW: - case Opcodes.ANEWARRAY: - case Opcodes.CHECKCAST: - case Opcodes.INSTANCEOF: - case Opcodes.IINC: - currentOffset += 3; - break; - case Opcodes.INVOKEINTERFACE: - case Opcodes.INVOKEDYNAMIC: - currentOffset += 5; - break; - case Opcodes.MULTIANEWARRAY: - currentOffset += 4; - break; - default: - throw new IllegalArgumentException(); - } - } - - // Read the 'exception_table_length' and 'exception_table' field to create a label for each - // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks. - int exceptionTableLength = readUnsignedShort(currentOffset); - currentOffset += 2; - while (exceptionTableLength-- > 0) { - Label start = createLabel(readUnsignedShort(currentOffset), labels); - Label end = createLabel(readUnsignedShort(currentOffset + 2), labels); - Label handler = createLabel(readUnsignedShort(currentOffset + 4), labels); - String catchType = readUTF8(cpInfoOffsets[readUnsignedShort(currentOffset + 6)], charBuffer); - currentOffset += 8; - methodVisitor.visitTryCatchBlock(start, end, handler, catchType); - } - - // Read the Code attributes to create a label for each referenced instruction (the variables - // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the - // attribute_name_index and attribute_length fields. - // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0. - // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is - // updated after each stack_map_frame is read. - int stackMapFrameOffset = 0; - // - The end offset of the StackMap[Table] attribute, or 0. - int stackMapTableEndOffset = 0; - // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not. - boolean compressedFrames = true; - // - The offset of the LocalVariableTable attribute, or 0. - int localVariableTableOffset = 0; - // - The offset of the LocalVariableTypeTable attribute, or 0. - int localVariableTypeTableOffset = 0; - // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations - // attribute, or null. - int[] visibleTypeAnnotationOffsets = null; - // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations - // attribute, or null. - int[] invisibleTypeAnnotationOffsets = null; - // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). - // This list in the reverse order or their order in the ClassFile structure. - Attribute attributes = null; - - int attributesCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (attributesCount-- > 0) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentOffset, charBuffer); - int attributeLength = readInt(currentOffset + 2); - currentOffset += 6; - if (Constants.LOCAL_VARIABLE_TABLE.equals(attributeName)) { - if ((context.parsingOptions & SKIP_DEBUG) == 0) { - localVariableTableOffset = currentOffset; - // Parse the attribute to find the corresponding (debug only) labels. - int currentLocalVariableTableOffset = currentOffset; - int localVariableTableLength = readUnsignedShort(currentLocalVariableTableOffset); - currentLocalVariableTableOffset += 2; - while (localVariableTableLength-- > 0) { - int startPc = readUnsignedShort(currentLocalVariableTableOffset); - createDebugLabel(startPc, labels); - int length = readUnsignedShort(currentLocalVariableTableOffset + 2); - createDebugLabel(startPc + length, labels); - // Skip the name_index, descriptor_index and index fields (2 bytes each). - currentLocalVariableTableOffset += 10; - } - } - } else if (Constants.LOCAL_VARIABLE_TYPE_TABLE.equals(attributeName)) { - localVariableTypeTableOffset = currentOffset; - // Here we do not extract the labels corresponding to the attribute content. We assume they - // are the same or a subset of those of the LocalVariableTable attribute. - } else if (Constants.LINE_NUMBER_TABLE.equals(attributeName)) { - if ((context.parsingOptions & SKIP_DEBUG) == 0) { - // Parse the attribute to find the corresponding (debug only) labels. - int currentLineNumberTableOffset = currentOffset; - int lineNumberTableLength = readUnsignedShort(currentLineNumberTableOffset); - currentLineNumberTableOffset += 2; - while (lineNumberTableLength-- > 0) { - int startPc = readUnsignedShort(currentLineNumberTableOffset); - int lineNumber = readUnsignedShort(currentLineNumberTableOffset + 2); - currentLineNumberTableOffset += 4; - createDebugLabel(startPc, labels); - labels[startPc].addLineNumber(lineNumber); - } - } - } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - visibleTypeAnnotationOffsets = - readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ true); - // Here we do not extract the labels corresponding to the attribute content. This would - // require a full parsing of the attribute, which would need to be repeated when parsing - // the bytecode instructions (see below). Instead, the content of the attribute is read one - // type annotation at a time (i.e. after a type annotation has been visited, the next type - // annotation is read), and the labels it contains are also extracted one annotation at a - // time. This assumes that type annotations are ordered by increasing bytecode offset. - } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { - invisibleTypeAnnotationOffsets = - readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ false); - // Same comment as above for the RuntimeVisibleTypeAnnotations attribute. - } else if (Constants.STACK_MAP_TABLE.equals(attributeName)) { - if ((context.parsingOptions & SKIP_FRAMES) == 0) { - stackMapFrameOffset = currentOffset + 2; - stackMapTableEndOffset = currentOffset + attributeLength; - } - // Here we do not extract the labels corresponding to the attribute content. This would - // require a full parsing of the attribute, which would need to be repeated when parsing - // the bytecode instructions (see below). Instead, the content of the attribute is read one - // frame at a time (i.e. after a frame has been visited, the next frame is read), and the - // labels it contains are also extracted one frame at a time. Thanks to the ordering of - // frames, having only a "one frame lookahead" is not a problem, i.e. it is not possible to - // see an offset smaller than the offset of the current instruction and for which no Label - // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map - // table without a full decoding (see below). - } else if ("StackMap".equals(attributeName)) { - if ((context.parsingOptions & SKIP_FRAMES) == 0) { - stackMapFrameOffset = currentOffset + 2; - stackMapTableEndOffset = currentOffset + attributeLength; - compressedFrames = false; - } - // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute, - // although this is not guaranteed by the attribute format. This allows an incremental - // extraction of the labels corresponding to this attribute (see the comment above for the - // StackMapTable attribute). - } else { - Attribute attribute = - readAttribute( - context.attributePrototypes, - attributeName, - currentOffset, - attributeLength, - charBuffer, - codeOffset, - labels); - attribute.nextAttribute = attributes; - attributes = attribute; - } - currentOffset += attributeLength; - } - - // Initialize the context fields related to stack map frames, and generate the first - // (implicit) stack map frame, if needed. - final boolean expandFrames = (context.parsingOptions & EXPAND_FRAMES) != 0; - if (stackMapFrameOffset != 0) { - // The bytecode offset of the first explicit frame is not offset_delta + 1 but only - // offset_delta. Setting the implicit frame offset to -1 allows us to use of the - // "offset_delta + 1" rule in all cases. - context.currentFrameOffset = -1; - context.currentFrameType = 0; - context.currentFrameLocalCount = 0; - context.currentFrameLocalCountDelta = 0; - context.currentFrameLocalTypes = new Object[maxLocals]; - context.currentFrameStackCount = 0; - context.currentFrameStackTypes = new Object[maxStack]; - if (expandFrames) { - computeImplicitFrame(context); - } - // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the - // stack map table, we look for 3 consecutive bytes that "look like" an UNINITIALIZED type - // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset). - // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare, - // and the only consequence will be the creation of an unneeded label. This is better than - // creating a label for each NEW instruction, and faster than fully decoding the whole stack - // map table. - for (int offset = stackMapFrameOffset; offset < stackMapTableEndOffset - 2; ++offset) { - if (classBuffer[offset] == Frame.ITEM_UNINITIALIZED) { - int potentialBytecodeOffset = readUnsignedShort(offset + 1); - if (potentialBytecodeOffset >= 0 - && potentialBytecodeOffset < codeLength - && (classBuffer[bytecodeStartOffset + potentialBytecodeOffset] & 0xFF) - == Opcodes.NEW) { - createLabel(potentialBytecodeOffset, labels); - } - } - } - } - if (expandFrames && (context.parsingOptions & EXPAND_ASM_INSNS) != 0) { - // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method - // does not currently have any frame. These inserted frames must be computed by simulating the - // effect of the bytecode instructions, one by one, starting from the implicit first frame. - // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To - // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is - // computed in MethodWriter). - methodVisitor.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null); - } - - // Visit the bytecode instructions. First, introduce state variables for the incremental parsing - // of the type annotations. - - // Index of the next runtime visible type annotation to read (in the - // visibleTypeAnnotationOffsets array). - int currentVisibleTypeAnnotationIndex = 0; - // The bytecode offset of the next runtime visible type annotation to read, or -1. - int currentVisibleTypeAnnotationBytecodeOffset = - getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, 0); - // Index of the next runtime invisible type annotation to read (in the - // invisibleTypeAnnotationOffsets array). - int currentInvisibleTypeAnnotationIndex = 0; - // The bytecode offset of the next runtime invisible type annotation to read, or -1. - int currentInvisibleTypeAnnotationBytecodeOffset = - getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, 0); - - // Whether a F_INSERT stack map frame must be inserted before the current instruction. - boolean insertFrame = false; - - // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr - // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific - // instructions). - final int wideJumpOpcodeDelta = - (context.parsingOptions & EXPAND_ASM_INSNS) == 0 ? Constants.WIDE_JUMP_OPCODE_DELTA : 0; - - currentOffset = bytecodeStartOffset; - while (currentOffset < bytecodeEndOffset) { - final int currentBytecodeOffset = currentOffset - bytecodeStartOffset; - - // Visit the label and the line number(s) for this bytecode offset, if any. - Label currentLabel = labels[currentBytecodeOffset]; - if (currentLabel != null) { - currentLabel.accept(methodVisitor, (context.parsingOptions & SKIP_DEBUG) == 0); - } - - // Visit the stack map frame for this bytecode offset, if any. - while (stackMapFrameOffset != 0 - && (context.currentFrameOffset == currentBytecodeOffset - || context.currentFrameOffset == -1)) { - // If there is a stack map frame for this offset, make methodVisitor visit it, and read the - // next stack map frame if there is one. - if (context.currentFrameOffset != -1) { - if (!compressedFrames || expandFrames) { - methodVisitor.visitFrame( - Opcodes.F_NEW, - context.currentFrameLocalCount, - context.currentFrameLocalTypes, - context.currentFrameStackCount, - context.currentFrameStackTypes); - } else { - methodVisitor.visitFrame( - context.currentFrameType, - context.currentFrameLocalCountDelta, - context.currentFrameLocalTypes, - context.currentFrameStackCount, - context.currentFrameStackTypes); - } - // Since there is already a stack map frame for this bytecode offset, there is no need to - // insert a new one. - insertFrame = false; - } - if (stackMapFrameOffset < stackMapTableEndOffset) { - stackMapFrameOffset = - readStackMapFrame(stackMapFrameOffset, compressedFrames, expandFrames, context); - } else { - stackMapFrameOffset = 0; - } - } - - // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to - // true during the previous iteration. The actual frame content is computed in MethodWriter. - if (insertFrame) { - if ((context.parsingOptions & EXPAND_FRAMES) != 0) { - methodVisitor.visitFrame(Constants.F_INSERT, 0, null, 0, null); - } - insertFrame = false; - } - - // Visit the instruction at this bytecode offset. - int opcode = classBuffer[currentOffset] & 0xFF; - switch (opcode) { - case Opcodes.NOP: - case Opcodes.ACONST_NULL: - case Opcodes.ICONST_M1: - case Opcodes.ICONST_0: - case Opcodes.ICONST_1: - case Opcodes.ICONST_2: - case Opcodes.ICONST_3: - case Opcodes.ICONST_4: - case Opcodes.ICONST_5: - case Opcodes.LCONST_0: - case Opcodes.LCONST_1: - case Opcodes.FCONST_0: - case Opcodes.FCONST_1: - case Opcodes.FCONST_2: - case Opcodes.DCONST_0: - case Opcodes.DCONST_1: - case Opcodes.IALOAD: - case Opcodes.LALOAD: - case Opcodes.FALOAD: - case Opcodes.DALOAD: - case Opcodes.AALOAD: - case Opcodes.BALOAD: - case Opcodes.CALOAD: - case Opcodes.SALOAD: - case Opcodes.IASTORE: - case Opcodes.LASTORE: - case Opcodes.FASTORE: - case Opcodes.DASTORE: - case Opcodes.AASTORE: - case Opcodes.BASTORE: - case Opcodes.CASTORE: - case Opcodes.SASTORE: - case Opcodes.POP: - case Opcodes.POP2: - case Opcodes.DUP: - case Opcodes.DUP_X1: - case Opcodes.DUP_X2: - case Opcodes.DUP2: - case Opcodes.DUP2_X1: - case Opcodes.DUP2_X2: - case Opcodes.SWAP: - case Opcodes.IADD: - case Opcodes.LADD: - case Opcodes.FADD: - case Opcodes.DADD: - case Opcodes.ISUB: - case Opcodes.LSUB: - case Opcodes.FSUB: - case Opcodes.DSUB: - case Opcodes.IMUL: - case Opcodes.LMUL: - case Opcodes.FMUL: - case Opcodes.DMUL: - case Opcodes.IDIV: - case Opcodes.LDIV: - case Opcodes.FDIV: - case Opcodes.DDIV: - case Opcodes.IREM: - case Opcodes.LREM: - case Opcodes.FREM: - case Opcodes.DREM: - case Opcodes.INEG: - case Opcodes.LNEG: - case Opcodes.FNEG: - case Opcodes.DNEG: - case Opcodes.ISHL: - case Opcodes.LSHL: - case Opcodes.ISHR: - case Opcodes.LSHR: - case Opcodes.IUSHR: - case Opcodes.LUSHR: - case Opcodes.IAND: - case Opcodes.LAND: - case Opcodes.IOR: - case Opcodes.LOR: - case Opcodes.IXOR: - case Opcodes.LXOR: - case Opcodes.I2L: - case Opcodes.I2F: - case Opcodes.I2D: - case Opcodes.L2I: - case Opcodes.L2F: - case Opcodes.L2D: - case Opcodes.F2I: - case Opcodes.F2L: - case Opcodes.F2D: - case Opcodes.D2I: - case Opcodes.D2L: - case Opcodes.D2F: - case Opcodes.I2B: - case Opcodes.I2C: - case Opcodes.I2S: - case Opcodes.LCMP: - case Opcodes.FCMPL: - case Opcodes.FCMPG: - case Opcodes.DCMPL: - case Opcodes.DCMPG: - case Opcodes.IRETURN: - case Opcodes.LRETURN: - case Opcodes.FRETURN: - case Opcodes.DRETURN: - case Opcodes.ARETURN: - case Opcodes.RETURN: - case Opcodes.ARRAYLENGTH: - case Opcodes.ATHROW: - case Opcodes.MONITORENTER: - case Opcodes.MONITOREXIT: - methodVisitor.visitInsn(opcode); - currentOffset += 1; - break; - case Constants.ILOAD_0: - case Constants.ILOAD_1: - case Constants.ILOAD_2: - case Constants.ILOAD_3: - case Constants.LLOAD_0: - case Constants.LLOAD_1: - case Constants.LLOAD_2: - case Constants.LLOAD_3: - case Constants.FLOAD_0: - case Constants.FLOAD_1: - case Constants.FLOAD_2: - case Constants.FLOAD_3: - case Constants.DLOAD_0: - case Constants.DLOAD_1: - case Constants.DLOAD_2: - case Constants.DLOAD_3: - case Constants.ALOAD_0: - case Constants.ALOAD_1: - case Constants.ALOAD_2: - case Constants.ALOAD_3: - opcode -= Constants.ILOAD_0; - methodVisitor.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3); - currentOffset += 1; - break; - case Constants.ISTORE_0: - case Constants.ISTORE_1: - case Constants.ISTORE_2: - case Constants.ISTORE_3: - case Constants.LSTORE_0: - case Constants.LSTORE_1: - case Constants.LSTORE_2: - case Constants.LSTORE_3: - case Constants.FSTORE_0: - case Constants.FSTORE_1: - case Constants.FSTORE_2: - case Constants.FSTORE_3: - case Constants.DSTORE_0: - case Constants.DSTORE_1: - case Constants.DSTORE_2: - case Constants.DSTORE_3: - case Constants.ASTORE_0: - case Constants.ASTORE_1: - case Constants.ASTORE_2: - case Constants.ASTORE_3: - opcode -= Constants.ISTORE_0; - methodVisitor.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3); - currentOffset += 1; - break; - case Opcodes.IFEQ: - case Opcodes.IFNE: - case Opcodes.IFLT: - case Opcodes.IFGE: - case Opcodes.IFGT: - case Opcodes.IFLE: - case Opcodes.IF_ICMPEQ: - case Opcodes.IF_ICMPNE: - case Opcodes.IF_ICMPLT: - case Opcodes.IF_ICMPGE: - case Opcodes.IF_ICMPGT: - case Opcodes.IF_ICMPLE: - case Opcodes.IF_ACMPEQ: - case Opcodes.IF_ACMPNE: - case Opcodes.GOTO: - case Opcodes.JSR: - case Opcodes.IFNULL: - case Opcodes.IFNONNULL: - methodVisitor.visitJumpInsn( - opcode, labels[currentBytecodeOffset + readShort(currentOffset + 1)]); - currentOffset += 3; - break; - case Constants.GOTO_W: - case Constants.JSR_W: - methodVisitor.visitJumpInsn( - opcode - wideJumpOpcodeDelta, - labels[currentBytecodeOffset + readInt(currentOffset + 1)]); - currentOffset += 5; - break; - case Constants.ASM_IFEQ: - case Constants.ASM_IFNE: - case Constants.ASM_IFLT: - case Constants.ASM_IFGE: - case Constants.ASM_IFGT: - case Constants.ASM_IFLE: - case Constants.ASM_IF_ICMPEQ: - case Constants.ASM_IF_ICMPNE: - case Constants.ASM_IF_ICMPLT: - case Constants.ASM_IF_ICMPGE: - case Constants.ASM_IF_ICMPGT: - case Constants.ASM_IF_ICMPLE: - case Constants.ASM_IF_ACMPEQ: - case Constants.ASM_IF_ACMPNE: - case Constants.ASM_GOTO: - case Constants.ASM_JSR: - case Constants.ASM_IFNULL: - case Constants.ASM_IFNONNULL: - { - // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO - // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx with IFNOTxxx GOTO_W L:..., - // where IFNOTxxx is the "opposite" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and - // where designates the instruction just after the GOTO_W. - // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and - // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL. - opcode = - opcode < Constants.ASM_IFNULL - ? opcode - Constants.ASM_OPCODE_DELTA - : opcode - Constants.ASM_IFNULL_OPCODE_DELTA; - Label target = labels[currentBytecodeOffset + readUnsignedShort(currentOffset + 1)]; - if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { - // Replace GOTO with GOTO_W and JSR with JSR_W. - methodVisitor.visitJumpInsn(opcode + Constants.WIDE_JUMP_OPCODE_DELTA, target); - } else { - // Compute the "opposite" of opcode. This can be done by flipping the least - // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ - // (with a pre and post offset by 1). - opcode = opcode < Opcodes.GOTO ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1; - Label endif = createLabel(currentBytecodeOffset + 3, labels); - methodVisitor.visitJumpInsn(opcode, endif); - methodVisitor.visitJumpInsn(Constants.GOTO_W, target); - // endif designates the instruction just after GOTO_W, and is visited as part of the - // next instruction. Since it is a jump target, we need to insert a frame here. - insertFrame = true; - } - currentOffset += 3; - break; - } - case Constants.ASM_GOTO_W: - // Replace ASM_GOTO_W with GOTO_W. - methodVisitor.visitJumpInsn( - Constants.GOTO_W, labels[currentBytecodeOffset + readInt(currentOffset + 1)]); - // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns - // IFNOTxxx ASM_GOTO_W L:..., see MethodWriter), so we need to insert a frame - // here. - insertFrame = true; - currentOffset += 5; - break; - case Constants.WIDE: - opcode = classBuffer[currentOffset + 1] & 0xFF; - if (opcode == Opcodes.IINC) { - methodVisitor.visitIincInsn( - readUnsignedShort(currentOffset + 2), readShort(currentOffset + 4)); - currentOffset += 6; - } else { - methodVisitor.visitVarInsn(opcode, readUnsignedShort(currentOffset + 2)); - currentOffset += 4; - } - break; - case Opcodes.TABLESWITCH: - { - // Skip 0 to 3 padding bytes. - currentOffset += 4 - (currentBytecodeOffset & 3); - // Read the instruction. - Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)]; - int low = readInt(currentOffset + 4); - int high = readInt(currentOffset + 8); - currentOffset += 12; - Label[] table = new Label[high - low + 1]; - for (int i = 0; i < table.length; ++i) { - table[i] = labels[currentBytecodeOffset + readInt(currentOffset)]; - currentOffset += 4; - } - methodVisitor.visitTableSwitchInsn(low, high, defaultLabel, table); - break; - } - case Opcodes.LOOKUPSWITCH: - { - // Skip 0 to 3 padding bytes. - currentOffset += 4 - (currentBytecodeOffset & 3); - // Read the instruction. - Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)]; - int numPairs = readInt(currentOffset + 4); - currentOffset += 8; - int[] keys = new int[numPairs]; - Label[] values = new Label[numPairs]; - for (int i = 0; i < numPairs; ++i) { - keys[i] = readInt(currentOffset); - values[i] = labels[currentBytecodeOffset + readInt(currentOffset + 4)]; - currentOffset += 8; - } - methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, values); - break; - } - case Opcodes.ILOAD: - case Opcodes.LLOAD: - case Opcodes.FLOAD: - case Opcodes.DLOAD: - case Opcodes.ALOAD: - case Opcodes.ISTORE: - case Opcodes.LSTORE: - case Opcodes.FSTORE: - case Opcodes.DSTORE: - case Opcodes.ASTORE: - case Opcodes.RET: - methodVisitor.visitVarInsn(opcode, classBuffer[currentOffset + 1] & 0xFF); - currentOffset += 2; - break; - case Opcodes.BIPUSH: - case Opcodes.NEWARRAY: - methodVisitor.visitIntInsn(opcode, classBuffer[currentOffset + 1]); - currentOffset += 2; - break; - case Opcodes.SIPUSH: - methodVisitor.visitIntInsn(opcode, readShort(currentOffset + 1)); - currentOffset += 3; - break; - case Opcodes.LDC: - methodVisitor.visitLdcInsn(readConst(classBuffer[currentOffset + 1] & 0xFF, charBuffer)); - currentOffset += 2; - break; - case Constants.LDC_W: - case Constants.LDC2_W: - methodVisitor.visitLdcInsn(readConst(readUnsignedShort(currentOffset + 1), charBuffer)); - currentOffset += 3; - break; - case Opcodes.GETSTATIC: - case Opcodes.PUTSTATIC: - case Opcodes.GETFIELD: - case Opcodes.PUTFIELD: - case Opcodes.INVOKEVIRTUAL: - case Opcodes.INVOKESPECIAL: - case Opcodes.INVOKESTATIC: - case Opcodes.INVOKEINTERFACE: - { - int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)]; - int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; - String owner = readClass(cpInfoOffset, charBuffer); - String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); - String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); - if (opcode < Opcodes.INVOKEVIRTUAL) { - methodVisitor.visitFieldInsn(opcode, owner, name, descriptor); - } else { - boolean isInterface = - classBuffer[cpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG; - methodVisitor.visitMethodInsn(opcode, owner, name, descriptor, isInterface); - } - if (opcode == Opcodes.INVOKEINTERFACE) { - currentOffset += 5; - } else { - currentOffset += 3; - } - break; - } - case Opcodes.INVOKEDYNAMIC: - { - int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)]; - int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; - String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); - String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); - int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)]; - Handle handle = - (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); - Object[] bootstrapMethodArguments = - new Object[readUnsignedShort(bootstrapMethodOffset + 2)]; - bootstrapMethodOffset += 4; - for (int i = 0; i < bootstrapMethodArguments.length; i++) { - bootstrapMethodArguments[i] = - readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); - bootstrapMethodOffset += 2; - } - methodVisitor.visitInvokeDynamicInsn( - name, descriptor, handle, bootstrapMethodArguments); - currentOffset += 5; - break; - } - case Opcodes.NEW: - case Opcodes.ANEWARRAY: - case Opcodes.CHECKCAST: - case Opcodes.INSTANCEOF: - methodVisitor.visitTypeInsn(opcode, readClass(currentOffset + 1, charBuffer)); - currentOffset += 3; - break; - case Opcodes.IINC: - methodVisitor.visitIincInsn( - classBuffer[currentOffset + 1] & 0xFF, classBuffer[currentOffset + 2]); - currentOffset += 3; - break; - case Opcodes.MULTIANEWARRAY: - methodVisitor.visitMultiANewArrayInsn( - readClass(currentOffset + 1, charBuffer), classBuffer[currentOffset + 3] & 0xFF); - currentOffset += 4; - break; - default: - throw new AssertionError(); - } - - // Visit the runtime visible instruction annotations, if any. - while (visibleTypeAnnotationOffsets != null - && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets.length - && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) { - if (currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) { - // Parse the target_type, target_info and target_path fields. - int currentAnnotationOffset = - readTypeAnnotationTarget( - context, visibleTypeAnnotationOffsets[currentVisibleTypeAnnotationIndex]); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - readElementValues( - methodVisitor.visitInsnAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ true), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - currentVisibleTypeAnnotationBytecodeOffset = - getTypeAnnotationBytecodeOffset( - visibleTypeAnnotationOffsets, ++currentVisibleTypeAnnotationIndex); - } - - // Visit the runtime invisible instruction annotations, if any. - while (invisibleTypeAnnotationOffsets != null - && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets.length - && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) { - if (currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) { - // Parse the target_type, target_info and target_path fields. - int currentAnnotationOffset = - readTypeAnnotationTarget( - context, invisibleTypeAnnotationOffsets[currentInvisibleTypeAnnotationIndex]); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); - currentAnnotationOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - readElementValues( - methodVisitor.visitInsnAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - annotationDescriptor, - /* visible = */ false), - currentAnnotationOffset, - /* named = */ true, - charBuffer); - } - currentInvisibleTypeAnnotationBytecodeOffset = - getTypeAnnotationBytecodeOffset( - invisibleTypeAnnotationOffsets, ++currentInvisibleTypeAnnotationIndex); - } - } - if (labels[codeLength] != null) { - methodVisitor.visitLabel(labels[codeLength]); - } - - // Visit LocalVariableTable and LocalVariableTypeTable attributes. - if (localVariableTableOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) { - // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable. - int[] typeTable = null; - if (localVariableTypeTableOffset != 0) { - typeTable = new int[readUnsignedShort(localVariableTypeTableOffset) * 3]; - currentOffset = localVariableTypeTableOffset + 2; - int typeTableIndex = typeTable.length; - while (typeTableIndex > 0) { - // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'. - typeTable[--typeTableIndex] = currentOffset + 6; - typeTable[--typeTableIndex] = readUnsignedShort(currentOffset + 8); - typeTable[--typeTableIndex] = readUnsignedShort(currentOffset); - currentOffset += 10; - } - } - int localVariableTableLength = readUnsignedShort(localVariableTableOffset); - currentOffset = localVariableTableOffset + 2; - while (localVariableTableLength-- > 0) { - int startPc = readUnsignedShort(currentOffset); - int length = readUnsignedShort(currentOffset + 2); - String name = readUTF8(currentOffset + 4, charBuffer); - String descriptor = readUTF8(currentOffset + 6, charBuffer); - int index = readUnsignedShort(currentOffset + 8); - currentOffset += 10; - String signature = null; - if (typeTable != null) { - for (int i = 0; i < typeTable.length; i += 3) { - if (typeTable[i] == startPc && typeTable[i + 1] == index) { - signature = readUTF8(typeTable[i + 2], charBuffer); - break; - } - } - } - methodVisitor.visitLocalVariable( - name, descriptor, signature, labels[startPc], labels[startPc + length], index); - } - } - - // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute. - if (visibleTypeAnnotationOffsets != null) { - for (int typeAnnotationOffset : visibleTypeAnnotationOffsets) { - int targetType = readByte(typeAnnotationOffset); - if (targetType == TypeReference.LOCAL_VARIABLE - || targetType == TypeReference.RESOURCE_VARIABLE) { - // Parse the target_type, target_info and target_path fields. - currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentOffset, charBuffer); - currentOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - readElementValues( - methodVisitor.visitLocalVariableAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - context.currentLocalVariableAnnotationRangeStarts, - context.currentLocalVariableAnnotationRangeEnds, - context.currentLocalVariableAnnotationRangeIndices, - annotationDescriptor, - /* visible = */ true), - currentOffset, - /* named = */ true, - charBuffer); - } - } - } - - // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute. - if (invisibleTypeAnnotationOffsets != null) { - for (int typeAnnotationOffset : invisibleTypeAnnotationOffsets) { - int targetType = readByte(typeAnnotationOffset); - if (targetType == TypeReference.LOCAL_VARIABLE - || targetType == TypeReference.RESOURCE_VARIABLE) { - // Parse the target_type, target_info and target_path fields. - currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset); - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentOffset, charBuffer); - currentOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - readElementValues( - methodVisitor.visitLocalVariableAnnotation( - context.currentTypeAnnotationTarget, - context.currentTypeAnnotationTargetPath, - context.currentLocalVariableAnnotationRangeStarts, - context.currentLocalVariableAnnotationRangeEnds, - context.currentLocalVariableAnnotationRangeIndices, - annotationDescriptor, - /* visible = */ false), - currentOffset, - /* named = */ true, - charBuffer); - } - } - } - - // Visit the non standard attributes. - while (attributes != null) { - // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. - Attribute nextAttribute = attributes.nextAttribute; - attributes.nextAttribute = null; - methodVisitor.visitAttribute(attributes); - attributes = nextAttribute; - } - - // Visit the max stack and max locals values. - methodVisitor.visitMaxs(maxStack, maxLocals); - } - - /** - * Returns the label corresponding to the given bytecode offset. The default implementation of - * this method creates a label for the given offset if it has not been already created. - * - * @param bytecodeOffset a bytecode offset in a method. - * @param labels the already created labels, indexed by their offset. If a label already exists - * for bytecodeOffset this method must not create a new one. Otherwise it must store the new - * label in this array. - * @return a non null Label, which must be equal to labels[bytecodeOffset]. - */ - protected Label readLabel(final int bytecodeOffset, final Label[] labels) { - if (labels[bytecodeOffset] == null) { - labels[bytecodeOffset] = new Label(); - } - return labels[bytecodeOffset]; - } - - /** - * Creates a label without the {@link Label#FLAG_DEBUG_ONLY} flag set, for the given bytecode - * offset. The label is created with a call to {@link #readLabel} and its {@link - * Label#FLAG_DEBUG_ONLY} flag is cleared. - * - * @param bytecodeOffset a bytecode offset in a method. - * @param labels the already created labels, indexed by their offset. - * @return a Label without the {@link Label#FLAG_DEBUG_ONLY} flag set. - */ - private Label createLabel(final int bytecodeOffset, final Label[] labels) { - Label label = readLabel(bytecodeOffset, labels); - label.flags &= ~Label.FLAG_DEBUG_ONLY; - return label; - } - - /** - * Creates a label with the {@link Label#FLAG_DEBUG_ONLY} flag set, if there is no already - * existing label for the given bytecode offset (otherwise does nothing). The label is created - * with a call to {@link #readLabel}. - * - * @param bytecodeOffset a bytecode offset in a method. - * @param labels the already created labels, indexed by their offset. - */ - private void createDebugLabel(final int bytecodeOffset, final Label[] labels) { - if (labels[bytecodeOffset] == null) { - readLabel(bytecodeOffset, labels).flags |= Label.FLAG_DEBUG_ONLY; - } - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse annotations, type annotations and parameter annotations - // ---------------------------------------------------------------------------------------------- - - /** - * Parses a Runtime[In]VisibleTypeAnnotations attribute to find the offset of each type_annotation - * entry it contains, to find the corresponding labels, and to visit the try catch block - * annotations. - * - * @param methodVisitor the method visitor to be used to visit the try catch block annotations. - * @param context information about the class being parsed. - * @param runtimeTypeAnnotationsOffset the start offset of a Runtime[In]VisibleTypeAnnotations - * attribute, excluding the attribute_info's attribute_name_index and attribute_length fields. - * @param visible true if the attribute to parse is a RuntimeVisibleTypeAnnotations attribute, - * false it is a RuntimeInvisibleTypeAnnotations attribute. - * @return the start offset of each entry of the Runtime[In]VisibleTypeAnnotations_attribute's - * 'annotations' array field. - */ - private int[] readTypeAnnotations( - final MethodVisitor methodVisitor, - final Context context, - final int runtimeTypeAnnotationsOffset, - final boolean visible) { - char[] charBuffer = context.charBuffer; - int currentOffset = runtimeTypeAnnotationsOffset; - // Read the num_annotations field and create an array to store the type_annotation offsets. - int[] typeAnnotationsOffsets = new int[readUnsignedShort(currentOffset)]; - currentOffset += 2; - // Parse the 'annotations' array field. - for (int i = 0; i < typeAnnotationsOffsets.length; ++i) { - typeAnnotationsOffsets[i] = currentOffset; - // Parse the type_annotation's target_type and the target_info fields. The size of the - // target_info field depends on the value of target_type. - int targetType = readInt(currentOffset); - switch (targetType >>> 24) { - case TypeReference.LOCAL_VARIABLE: - case TypeReference.RESOURCE_VARIABLE: - // A localvar_target has a variable size, which depends on the value of their table_length - // field. It also references bytecode offsets, for which we need labels. - int tableLength = readUnsignedShort(currentOffset + 1); - currentOffset += 3; - while (tableLength-- > 0) { - int startPc = readUnsignedShort(currentOffset); - int length = readUnsignedShort(currentOffset + 2); - // Skip the index field (2 bytes). - currentOffset += 6; - createLabel(startPc, context.currentMethodLabels); - createLabel(startPc + length, context.currentMethodLabels); - } - break; - case TypeReference.CAST: - case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: - case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: - case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: - case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: - currentOffset += 4; - break; - case TypeReference.CLASS_EXTENDS: - case TypeReference.CLASS_TYPE_PARAMETER_BOUND: - case TypeReference.METHOD_TYPE_PARAMETER_BOUND: - case TypeReference.THROWS: - case TypeReference.EXCEPTION_PARAMETER: - case TypeReference.INSTANCEOF: - case TypeReference.NEW: - case TypeReference.CONSTRUCTOR_REFERENCE: - case TypeReference.METHOD_REFERENCE: - currentOffset += 3; - break; - case TypeReference.CLASS_TYPE_PARAMETER: - case TypeReference.METHOD_TYPE_PARAMETER: - case TypeReference.METHOD_FORMAL_PARAMETER: - case TypeReference.FIELD: - case TypeReference.METHOD_RETURN: - case TypeReference.METHOD_RECEIVER: - default: - // TypeReference type which can't be used in Code attribute, or which is unknown. - throw new IllegalArgumentException(); - } - // Parse the rest of the type_annotation structure, starting with the target_path structure - // (whose size depends on its path_length field). - int pathLength = readByte(currentOffset); - if ((targetType >>> 24) == TypeReference.EXCEPTION_PARAMETER) { - // Parse the target_path structure and create a corresponding TypePath. - TypePath path = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset); - currentOffset += 1 + 2 * pathLength; - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentOffset, charBuffer); - currentOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentOffset = - readElementValues( - methodVisitor.visitTryCatchAnnotation( - targetType & 0xFFFFFF00, path, annotationDescriptor, visible), - currentOffset, - /* named = */ true, - charBuffer); - } else { - // We don't want to visit the other target_type annotations, so we just skip them (which - // requires some parsing because the element_value_pairs array has a variable size). First, - // skip the target_path structure: - currentOffset += 3 + 2 * pathLength; - // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them - // with a null AnnotationVisitor). - currentOffset = - readElementValues( - /* annotationVisitor = */ null, currentOffset, /* named = */ true, charBuffer); - } - } - return typeAnnotationsOffsets; - } - - /** - * Returns the bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or - * -1 if there is no such type_annotation of if it does not have a bytecode offset. - * - * @param typeAnnotationOffsets the offset of each 'type_annotation' entry in a - * Runtime[In]VisibleTypeAnnotations attribute, or null. - * @param typeAnnotationIndex the index a 'type_annotation' entry in typeAnnotationOffsets. - * @return bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or -1 - * if there is no such type_annotation of if it does not have a bytecode offset. - */ - private int getTypeAnnotationBytecodeOffset( - final int[] typeAnnotationOffsets, final int typeAnnotationIndex) { - if (typeAnnotationOffsets == null - || typeAnnotationIndex >= typeAnnotationOffsets.length - || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) { - return -1; - } - return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1); - } - - /** - * Parses the header of a JVMS type_annotation structure to extract its target_type, target_info - * and target_path (the result is stored in the given context), and returns the start offset of - * the rest of the type_annotation structure. - * - * @param context information about the class being parsed. This is where the extracted - * target_type and target_path must be stored. - * @param typeAnnotationOffset the start offset of a type_annotation structure. - * @return the start offset of the rest of the type_annotation structure. - */ - private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) { - int currentOffset = typeAnnotationOffset; - // Parse and store the target_type structure. - int targetType = readInt(typeAnnotationOffset); - switch (targetType >>> 24) { - case TypeReference.CLASS_TYPE_PARAMETER: - case TypeReference.METHOD_TYPE_PARAMETER: - case TypeReference.METHOD_FORMAL_PARAMETER: - targetType &= 0xFFFF0000; - currentOffset += 2; - break; - case TypeReference.FIELD: - case TypeReference.METHOD_RETURN: - case TypeReference.METHOD_RECEIVER: - targetType &= 0xFF000000; - currentOffset += 1; - break; - case TypeReference.LOCAL_VARIABLE: - case TypeReference.RESOURCE_VARIABLE: - targetType &= 0xFF000000; - int tableLength = readUnsignedShort(currentOffset + 1); - currentOffset += 3; - context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength]; - context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength]; - context.currentLocalVariableAnnotationRangeIndices = new int[tableLength]; - for (int i = 0; i < tableLength; ++i) { - int startPc = readUnsignedShort(currentOffset); - int length = readUnsignedShort(currentOffset + 2); - int index = readUnsignedShort(currentOffset + 4); - currentOffset += 6; - context.currentLocalVariableAnnotationRangeStarts[i] = - createLabel(startPc, context.currentMethodLabels); - context.currentLocalVariableAnnotationRangeEnds[i] = - createLabel(startPc + length, context.currentMethodLabels); - context.currentLocalVariableAnnotationRangeIndices[i] = index; - } - break; - case TypeReference.CAST: - case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: - case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: - case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: - case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: - targetType &= 0xFF0000FF; - currentOffset += 4; - break; - case TypeReference.CLASS_EXTENDS: - case TypeReference.CLASS_TYPE_PARAMETER_BOUND: - case TypeReference.METHOD_TYPE_PARAMETER_BOUND: - case TypeReference.THROWS: - case TypeReference.EXCEPTION_PARAMETER: - targetType &= 0xFFFFFF00; - currentOffset += 3; - break; - case TypeReference.INSTANCEOF: - case TypeReference.NEW: - case TypeReference.CONSTRUCTOR_REFERENCE: - case TypeReference.METHOD_REFERENCE: - targetType &= 0xFF000000; - currentOffset += 3; - break; - default: - throw new IllegalArgumentException(); - } - context.currentTypeAnnotationTarget = targetType; - // Parse and store the target_path structure. - int pathLength = readByte(currentOffset); - context.currentTypeAnnotationTargetPath = - pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset); - // Return the start offset of the rest of the type_annotation structure. - return currentOffset + 1 + 2 * pathLength; - } - - /** - * Reads a Runtime[In]VisibleParameterAnnotations attribute and makes the given visitor visit it. - * - * @param methodVisitor the visitor that must visit the parameter annotations. - * @param context information about the class being parsed. - * @param runtimeParameterAnnotationsOffset the start offset of a - * Runtime[In]VisibleParameterAnnotations attribute, excluding the attribute_info's - * attribute_name_index and attribute_length fields. - * @param visible true if the attribute to parse is a RuntimeVisibleParameterAnnotations - * attribute, false it is a RuntimeInvisibleParameterAnnotations attribute. - */ - private void readParameterAnnotations( - final MethodVisitor methodVisitor, - final Context context, - final int runtimeParameterAnnotationsOffset, - final boolean visible) { - int currentOffset = runtimeParameterAnnotationsOffset; - int numParameters = classFileBuffer[currentOffset++] & 0xFF; - methodVisitor.visitAnnotableParameterCount(numParameters, visible); - char[] charBuffer = context.charBuffer; - for (int i = 0; i < numParameters; ++i) { - int numAnnotations = readUnsignedShort(currentOffset); - currentOffset += 2; - while (numAnnotations-- > 0) { - // Parse the type_index field. - String annotationDescriptor = readUTF8(currentOffset, charBuffer); - currentOffset += 2; - // Parse num_element_value_pairs and element_value_pairs and visit these values. - currentOffset = - readElementValues( - methodVisitor.visitParameterAnnotation(i, annotationDescriptor, visible), - currentOffset, - /* named = */ true, - charBuffer); - } - } - } - - /** - * Reads the element values of a JVMS 'annotation' structure and makes the given visitor visit - * them. This method can also be used to read the values of the JVMS 'array_value' field of an - * annotation's 'element_value'. - * - * @param annotationVisitor the visitor that must visit the values. - * @param annotationOffset the start offset of an 'annotation' structure (excluding its type_index - * field) or of an 'array_value' structure. - * @param named if the annotation values are named or not. This should be true to parse the values - * of a JVMS 'annotation' structure, and false to parse the JVMS 'array_value' of an - * annotation's element_value. - * @param charBuffer the buffer used to read strings in the constant pool. - * @return the end offset of the JVMS 'annotation' or 'array_value' structure. - */ - private int readElementValues( - final AnnotationVisitor annotationVisitor, - final int annotationOffset, - final boolean named, - final char[] charBuffer) { - int currentOffset = annotationOffset; - // Read the num_element_value_pairs field (or num_values field for an array_value). - int numElementValuePairs = readUnsignedShort(currentOffset); - currentOffset += 2; - if (named) { - // Parse the element_value_pairs array. - while (numElementValuePairs-- > 0) { - String elementName = readUTF8(currentOffset, charBuffer); - currentOffset = - readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer); - } - } else { - // Parse the array_value array. - while (numElementValuePairs-- > 0) { - currentOffset = - readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer); - } - } - if (annotationVisitor != null) { - annotationVisitor.visitEnd(); - } - return currentOffset; - } - - /** - * Reads a JVMS 'element_value' structure and makes the given visitor visit it. - * - * @param annotationVisitor the visitor that must visit the element_value structure. - * @param elementValueOffset the start offset in {@link #classFileBuffer} of the element_value - * structure to be read. - * @param elementName the name of the element_value structure to be read, or {@literal null}. - * @param charBuffer the buffer used to read strings in the constant pool. - * @return the end offset of the JVMS 'element_value' structure. - */ - private int readElementValue( - final AnnotationVisitor annotationVisitor, - final int elementValueOffset, - final String elementName, - final char[] charBuffer) { - int currentOffset = elementValueOffset; - if (annotationVisitor == null) { - switch (classFileBuffer[currentOffset] & 0xFF) { - case 'e': // enum_const_value - return currentOffset + 5; - case '@': // annotation_value - return readElementValues(null, currentOffset + 3, /* named = */ true, charBuffer); - case '[': // array_value - return readElementValues(null, currentOffset + 1, /* named = */ false, charBuffer); - default: - return currentOffset + 3; - } - } - switch (classFileBuffer[currentOffset++] & 0xFF) { - case 'B': // const_value_index, CONSTANT_Integer - annotationVisitor.visit( - elementName, (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); - currentOffset += 2; - break; - case 'C': // const_value_index, CONSTANT_Integer - annotationVisitor.visit( - elementName, (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); - currentOffset += 2; - break; - case 'D': // const_value_index, CONSTANT_Double - case 'F': // const_value_index, CONSTANT_Float - case 'I': // const_value_index, CONSTANT_Integer - case 'J': // const_value_index, CONSTANT_Long - annotationVisitor.visit( - elementName, readConst(readUnsignedShort(currentOffset), charBuffer)); - currentOffset += 2; - break; - case 'S': // const_value_index, CONSTANT_Integer - annotationVisitor.visit( - elementName, (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); - currentOffset += 2; - break; - - case 'Z': // const_value_index, CONSTANT_Integer - annotationVisitor.visit( - elementName, - readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]) == 0 - ? Boolean.FALSE - : Boolean.TRUE); - currentOffset += 2; - break; - case 's': // const_value_index, CONSTANT_Utf8 - annotationVisitor.visit(elementName, readUTF8(currentOffset, charBuffer)); - currentOffset += 2; - break; - case 'e': // enum_const_value - annotationVisitor.visitEnum( - elementName, - readUTF8(currentOffset, charBuffer), - readUTF8(currentOffset + 2, charBuffer)); - currentOffset += 4; - break; - case 'c': // class_info - annotationVisitor.visit(elementName, Type.getType(readUTF8(currentOffset, charBuffer))); - currentOffset += 2; - break; - case '@': // annotation_value - currentOffset = - readElementValues( - annotationVisitor.visitAnnotation(elementName, readUTF8(currentOffset, charBuffer)), - currentOffset + 2, - true, - charBuffer); - break; - case '[': // array_value - int numValues = readUnsignedShort(currentOffset); - currentOffset += 2; - if (numValues == 0) { - return readElementValues( - annotationVisitor.visitArray(elementName), - currentOffset - 2, - /* named = */ false, - charBuffer); - } - switch (classFileBuffer[currentOffset] & 0xFF) { - case 'B': - byte[] byteValues = new byte[numValues]; - for (int i = 0; i < numValues; i++) { - byteValues[i] = (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, byteValues); - break; - case 'Z': - boolean[] booleanValues = new boolean[numValues]; - for (int i = 0; i < numValues; i++) { - booleanValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]) != 0; - currentOffset += 3; - } - annotationVisitor.visit(elementName, booleanValues); - break; - case 'S': - short[] shortValues = new short[numValues]; - for (int i = 0; i < numValues; i++) { - shortValues[i] = (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, shortValues); - break; - case 'C': - char[] charValues = new char[numValues]; - for (int i = 0; i < numValues; i++) { - charValues[i] = (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, charValues); - break; - case 'I': - int[] intValues = new int[numValues]; - for (int i = 0; i < numValues; i++) { - intValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, intValues); - break; - case 'J': - long[] longValues = new long[numValues]; - for (int i = 0; i < numValues; i++) { - longValues[i] = readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); - currentOffset += 3; - } - annotationVisitor.visit(elementName, longValues); - break; - case 'F': - float[] floatValues = new float[numValues]; - for (int i = 0; i < numValues; i++) { - floatValues[i] = - Float.intBitsToFloat( - readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)])); - currentOffset += 3; - } - annotationVisitor.visit(elementName, floatValues); - break; - case 'D': - double[] doubleValues = new double[numValues]; - for (int i = 0; i < numValues; i++) { - doubleValues[i] = - Double.longBitsToDouble( - readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)])); - currentOffset += 3; - } - annotationVisitor.visit(elementName, doubleValues); - break; - default: - currentOffset = - readElementValues( - annotationVisitor.visitArray(elementName), - currentOffset - 2, - /* named = */ false, - charBuffer); - break; - } - break; - default: - throw new IllegalArgumentException(); - } - return currentOffset; - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse stack map frames - // ---------------------------------------------------------------------------------------------- - - /** - * Computes the implicit frame of the method currently being parsed (as defined in the given - * {@link Context}) and stores it in the given context. - * - * @param context information about the class being parsed. - */ - private void computeImplicitFrame(final Context context) { - String methodDescriptor = context.currentMethodDescriptor; - Object[] locals = context.currentFrameLocalTypes; - int numLocal = 0; - if ((context.currentMethodAccessFlags & Opcodes.ACC_STATIC) == 0) { - if ("".equals(context.currentMethodName)) { - locals[numLocal++] = Opcodes.UNINITIALIZED_THIS; - } else { - locals[numLocal++] = readClass(header + 2, context.charBuffer); - } - } - // Parse the method descriptor, one argument type descriptor at each iteration. Start by - // skipping the first method descriptor character, which is always '('. - int currentMethodDescritorOffset = 1; - while (true) { - int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset; - switch (methodDescriptor.charAt(currentMethodDescritorOffset++)) { - case 'Z': - case 'C': - case 'B': - case 'S': - case 'I': - locals[numLocal++] = Opcodes.INTEGER; - break; - case 'F': - locals[numLocal++] = Opcodes.FLOAT; - break; - case 'J': - locals[numLocal++] = Opcodes.LONG; - break; - case 'D': - locals[numLocal++] = Opcodes.DOUBLE; - break; - case '[': - while (methodDescriptor.charAt(currentMethodDescritorOffset) == '[') { - ++currentMethodDescritorOffset; - } - if (methodDescriptor.charAt(currentMethodDescritorOffset) == 'L') { - ++currentMethodDescritorOffset; - while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') { - ++currentMethodDescritorOffset; - } - } - locals[numLocal++] = - methodDescriptor.substring( - currentArgumentDescriptorStartOffset, ++currentMethodDescritorOffset); - break; - case 'L': - while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') { - ++currentMethodDescritorOffset; - } - locals[numLocal++] = - methodDescriptor.substring( - currentArgumentDescriptorStartOffset + 1, currentMethodDescritorOffset++); - break; - default: - context.currentFrameLocalCount = numLocal; - return; - } - } - } - - /** - * Reads a JVMS 'stack_map_frame' structure and stores the result in the given {@link Context} - * object. This method can also be used to read a full_frame structure, excluding its frame_type - * field (this is used to parse the legacy StackMap attributes). - * - * @param stackMapFrameOffset the start offset in {@link #classFileBuffer} of the - * stack_map_frame_value structure to be read, or the start offset of a full_frame structure - * (excluding its frame_type field). - * @param compressed true to read a 'stack_map_frame' structure, false to read a 'full_frame' - * structure without its frame_type field. - * @param expand if the stack map frame must be expanded. See {@link #EXPAND_FRAMES}. - * @param context where the parsed stack map frame must be stored. - * @return the end offset of the JVMS 'stack_map_frame' or 'full_frame' structure. - */ - private int readStackMapFrame( - final int stackMapFrameOffset, - final boolean compressed, - final boolean expand, - final Context context) { - int currentOffset = stackMapFrameOffset; - final char[] charBuffer = context.charBuffer; - final Label[] labels = context.currentMethodLabels; - int frameType; - if (compressed) { - // Read the frame_type field. - frameType = classFileBuffer[currentOffset++] & 0xFF; - } else { - frameType = Frame.FULL_FRAME; - context.currentFrameOffset = -1; - } - int offsetDelta; - context.currentFrameLocalCountDelta = 0; - if (frameType < Frame.SAME_LOCALS_1_STACK_ITEM_FRAME) { - offsetDelta = frameType; - context.currentFrameType = Opcodes.F_SAME; - context.currentFrameStackCount = 0; - } else if (frameType < Frame.RESERVED) { - offsetDelta = frameType - Frame.SAME_LOCALS_1_STACK_ITEM_FRAME; - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels); - context.currentFrameType = Opcodes.F_SAME1; - context.currentFrameStackCount = 1; - } else if (frameType >= Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { - offsetDelta = readUnsignedShort(currentOffset); - currentOffset += 2; - if (frameType == Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels); - context.currentFrameType = Opcodes.F_SAME1; - context.currentFrameStackCount = 1; - } else if (frameType >= Frame.CHOP_FRAME && frameType < Frame.SAME_FRAME_EXTENDED) { - context.currentFrameType = Opcodes.F_CHOP; - context.currentFrameLocalCountDelta = Frame.SAME_FRAME_EXTENDED - frameType; - context.currentFrameLocalCount -= context.currentFrameLocalCountDelta; - context.currentFrameStackCount = 0; - } else if (frameType == Frame.SAME_FRAME_EXTENDED) { - context.currentFrameType = Opcodes.F_SAME; - context.currentFrameStackCount = 0; - } else if (frameType < Frame.FULL_FRAME) { - int local = expand ? context.currentFrameLocalCount : 0; - for (int k = frameType - Frame.SAME_FRAME_EXTENDED; k > 0; k--) { - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameLocalTypes, local++, charBuffer, labels); - } - context.currentFrameType = Opcodes.F_APPEND; - context.currentFrameLocalCountDelta = frameType - Frame.SAME_FRAME_EXTENDED; - context.currentFrameLocalCount += context.currentFrameLocalCountDelta; - context.currentFrameStackCount = 0; - } else { - final int numberOfLocals = readUnsignedShort(currentOffset); - currentOffset += 2; - context.currentFrameType = Opcodes.F_FULL; - context.currentFrameLocalCountDelta = numberOfLocals; - context.currentFrameLocalCount = numberOfLocals; - for (int local = 0; local < numberOfLocals; ++local) { - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameLocalTypes, local, charBuffer, labels); - } - final int numberOfStackItems = readUnsignedShort(currentOffset); - currentOffset += 2; - context.currentFrameStackCount = numberOfStackItems; - for (int stack = 0; stack < numberOfStackItems; ++stack) { - currentOffset = - readVerificationTypeInfo( - currentOffset, context.currentFrameStackTypes, stack, charBuffer, labels); - } - } - } else { - throw new IllegalArgumentException(); - } - context.currentFrameOffset += offsetDelta + 1; - createLabel(context.currentFrameOffset, labels); - return currentOffset; - } - - /** - * Reads a JVMS 'verification_type_info' structure and stores it at the given index in the given - * array. - * - * @param verificationTypeInfoOffset the start offset of the 'verification_type_info' structure to - * read. - * @param frame the array where the parsed type must be stored. - * @param index the index in 'frame' where the parsed type must be stored. - * @param charBuffer the buffer used to read strings in the constant pool. - * @param labels the labels of the method currently being parsed, indexed by their offset. If the - * parsed type is an ITEM_Uninitialized, a new label for the corresponding NEW instruction is - * stored in this array if it does not already exist. - * @return the end offset of the JVMS 'verification_type_info' structure. - */ - private int readVerificationTypeInfo( - final int verificationTypeInfoOffset, - final Object[] frame, - final int index, - final char[] charBuffer, - final Label[] labels) { - int currentOffset = verificationTypeInfoOffset; - int tag = classFileBuffer[currentOffset++] & 0xFF; - switch (tag) { - case Frame.ITEM_TOP: - frame[index] = Opcodes.TOP; - break; - case Frame.ITEM_INTEGER: - frame[index] = Opcodes.INTEGER; - break; - case Frame.ITEM_FLOAT: - frame[index] = Opcodes.FLOAT; - break; - case Frame.ITEM_DOUBLE: - frame[index] = Opcodes.DOUBLE; - break; - case Frame.ITEM_LONG: - frame[index] = Opcodes.LONG; - break; - case Frame.ITEM_NULL: - frame[index] = Opcodes.NULL; - break; - case Frame.ITEM_UNINITIALIZED_THIS: - frame[index] = Opcodes.UNINITIALIZED_THIS; - break; - case Frame.ITEM_OBJECT: - frame[index] = readClass(currentOffset, charBuffer); - currentOffset += 2; - break; - case Frame.ITEM_UNINITIALIZED: - frame[index] = createLabel(readUnsignedShort(currentOffset), labels); - currentOffset += 2; - break; - default: - throw new IllegalArgumentException(); - } - return currentOffset; - } - - // ---------------------------------------------------------------------------------------------- - // Methods to parse attributes - // ---------------------------------------------------------------------------------------------- - - /** - * Returns the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array - * field entry. - * - * @return the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array - * field entry. - */ - final int getFirstAttributeOffset() { - // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes - // each), as well as the interfaces array field (2 bytes per interface). - int currentOffset = header + 8 + readUnsignedShort(header + 6) * 2; - - // Read the fields_count field. - int fieldsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - // Skip the 'fields' array field. - while (fieldsCount-- > 0) { - // Invariant: currentOffset is the offset of a field_info structure. - // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the - // attributes_count field. - int attributesCount = readUnsignedShort(currentOffset + 6); - currentOffset += 8; - // Skip the 'attributes' array field. - while (attributesCount-- > 0) { - // Invariant: currentOffset is the offset of an attribute_info structure. - // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip - // this many bytes, plus 6 for the attribute_name_index and attribute_length fields - // (yielding the total size of the attribute_info structure). - currentOffset += 6 + readInt(currentOffset + 2); - } - } - - // Skip the methods_count and 'methods' fields, using the same method as above. - int methodsCount = readUnsignedShort(currentOffset); - currentOffset += 2; - while (methodsCount-- > 0) { - int attributesCount = readUnsignedShort(currentOffset + 6); - currentOffset += 8; - while (attributesCount-- > 0) { - currentOffset += 6 + readInt(currentOffset + 2); - } - } - - // Skip the ClassFile's attributes_count field. - return currentOffset + 2; - } - - /** - * Reads the BootstrapMethods attribute to compute the offset of each bootstrap method. - * - * @param maxStringLength a conservative estimate of the maximum length of the strings contained - * in the constant pool of the class. - * @return the offsets of the bootstrap methods. - */ - private int[] readBootstrapMethodsAttribute(final int maxStringLength) { - char[] charBuffer = new char[maxStringLength]; - int currentAttributeOffset = getFirstAttributeOffset(); - int[] currentBootstrapMethodOffsets = null; - for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { - // Read the attribute_info's attribute_name and attribute_length fields. - String attributeName = readUTF8(currentAttributeOffset, charBuffer); - int attributeLength = readInt(currentAttributeOffset + 2); - currentAttributeOffset += 6; - if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) { - // Read the num_bootstrap_methods field and create an array of this size. - currentBootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)]; - // Compute and store the offset of each 'bootstrap_methods' array field entry. - int currentBootstrapMethodOffset = currentAttributeOffset + 2; - for (int j = 0; j < currentBootstrapMethodOffsets.length; ++j) { - currentBootstrapMethodOffsets[j] = currentBootstrapMethodOffset; - // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each), - // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2). - currentBootstrapMethodOffset += - 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2; - } - return currentBootstrapMethodOffsets; - } - currentAttributeOffset += attributeLength; - } - throw new IllegalArgumentException(); - } - - /** - * Reads a non standard JVMS 'attribute' structure in {@link #classFileBuffer}. - * - * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of - * the class. Any attribute whose type is not equal to the type of one the prototypes will not - * be parsed: its byte array value will be passed unchanged to the ClassWriter. - * @param type the type of the attribute. - * @param offset the start offset of the JVMS 'attribute' structure in {@link #classFileBuffer}. - * The 6 attribute header bytes (attribute_name_index and attribute_length) are not taken into - * account here. - * @param length the length of the attribute's content (excluding the 6 attribute header bytes). - * @param charBuffer the buffer to be used to read strings in the constant pool. - * @param codeAttributeOffset the start offset of the enclosing Code attribute in {@link - * #classFileBuffer}, or -1 if the attribute to be read is not a code attribute. The 6 - * attribute header bytes (attribute_name_index and attribute_length) are not taken into - * account here. - * @param labels the labels of the method's code, or {@literal null} if the attribute to be read - * is not a code attribute. - * @return the attribute that has been read. - */ - private Attribute readAttribute( - final Attribute[] attributePrototypes, - final String type, - final int offset, - final int length, - final char[] charBuffer, - final int codeAttributeOffset, - final Label[] labels) { - for (Attribute attributePrototype : attributePrototypes) { - if (attributePrototype.type.equals(type)) { - return attributePrototype.read( - this, offset, length, charBuffer, codeAttributeOffset, labels); - } - } - return new Attribute(type).read(this, offset, length, null, -1, null); - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods: low level parsing - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the number of entries in the class's constant pool table. - * - * @return the number of entries in the class's constant pool table. - */ - public int getItemCount() { - return cpInfoOffsets.length; - } - - /** - * Returns the start offset in this {@link ClassReader} of a JVMS 'cp_info' structure (i.e. a - * constant pool entry), plus one. This method is intended for {@link Attribute} sub classes, - * and is normally not needed by class generators or adapters. - * - * @param constantPoolEntryIndex the index a constant pool entry in the class's constant pool - * table. - * @return the start offset in this {@link ClassReader} of the corresponding JVMS 'cp_info' - * structure, plus one. - */ - public int getItem(final int constantPoolEntryIndex) { - return cpInfoOffsets[constantPoolEntryIndex]; - } - - /** - * Returns a conservative estimate of the maximum length of the strings contained in the class's - * constant pool table. - * - * @return a conservative estimate of the maximum length of the strings contained in the class's - * constant pool table. - */ - public int getMaxStringLength() { - return maxStringLength; - } - - /** - * Reads a byte value in this {@link ClassReader}. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start offset of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public int readByte(final int offset) { - return classFileBuffer[offset] & 0xFF; - } - - /** - * Reads an unsigned short value in this {@link ClassReader}. This method is intended for - * {@link Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start index of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public int readUnsignedShort(final int offset) { - byte[] classBuffer = classFileBuffer; - return ((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF); - } - - /** - * Reads a signed short value in this {@link ClassReader}. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start offset of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public short readShort(final int offset) { - byte[] classBuffer = classFileBuffer; - return (short) (((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF)); - } - - /** - * Reads a signed int value in this {@link ClassReader}. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start offset of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public int readInt(final int offset) { - byte[] classBuffer = classFileBuffer; - return ((classBuffer[offset] & 0xFF) << 24) - | ((classBuffer[offset + 1] & 0xFF) << 16) - | ((classBuffer[offset + 2] & 0xFF) << 8) - | (classBuffer[offset + 3] & 0xFF); - } - - /** - * Reads a signed long value in this {@link ClassReader}. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param offset the start offset of the value to be read in this {@link ClassReader}. - * @return the read value. - */ - public long readLong(final int offset) { - long l1 = readInt(offset); - long l0 = readInt(offset + 4) & 0xFFFFFFFFL; - return (l1 << 32) | l0; - } - - /** - * Reads a CONSTANT_Utf8 constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose - * value is the index of a CONSTANT_Utf8 entry in the class's constant pool table. - * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Utf8 entry. - */ - // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). - public String readUTF8(final int offset, final char[] charBuffer) { - int constantPoolEntryIndex = readUnsignedShort(offset); - if (offset == 0 || constantPoolEntryIndex == 0) { - return null; - } - return readUtf(constantPoolEntryIndex, charBuffer); - } - - /** - * Reads a CONSTANT_Utf8 constant pool entry in {@link #classFileBuffer}. - * - * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pool - * table. - * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Utf8 entry. - */ - final String readUtf(final int constantPoolEntryIndex, final char[] charBuffer) { - String value = constantUtf8Values[constantPoolEntryIndex]; - if (value != null) { - return value; - } - int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; - return constantUtf8Values[constantPoolEntryIndex] = - readUtf(cpInfoOffset + 2, readUnsignedShort(cpInfoOffset), charBuffer); - } - - /** - * Reads an UTF8 string in {@link #classFileBuffer}. - * - * @param utfOffset the start offset of the UTF8 string to be read. - * @param utfLength the length of the UTF8 string to be read. - * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified UTF8 string. - */ - private String readUtf(final int utfOffset, final int utfLength, final char[] charBuffer) { - int currentOffset = utfOffset; - int endOffset = currentOffset + utfLength; - int strLength = 0; - byte[] classBuffer = classFileBuffer; - while (currentOffset < endOffset) { - int currentByte = classBuffer[currentOffset++]; - if ((currentByte & 0x80) == 0) { - charBuffer[strLength++] = (char) (currentByte & 0x7F); - } else if ((currentByte & 0xE0) == 0xC0) { - charBuffer[strLength++] = - (char) (((currentByte & 0x1F) << 6) + (classBuffer[currentOffset++] & 0x3F)); - } else { - charBuffer[strLength++] = - (char) - (((currentByte & 0xF) << 12) - + ((classBuffer[currentOffset++] & 0x3F) << 6) - + (classBuffer[currentOffset++] & 0x3F)); - } - } - return new String(charBuffer, 0, strLength); - } - - /** - * Reads a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or - * CONSTANT_Package constant pool entry in {@link #classFileBuffer}. This method is intended - * for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in {@link #classFileBuffer}, whose - * value is the index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, - * CONSTANT_Module or CONSTANT_Package entry in class's constant pool table. - * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified constant pool entry. - */ - private String readStringish(final int offset, final char[] charBuffer) { - // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry - // designated by the first two bytes of this cp_info. - return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer); - } - - /** - * Reads a CONSTANT_Class constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose - * value is the index of a CONSTANT_Class entry in class's constant pool table. - * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Class entry. - */ - public String readClass(final int offset, final char[] charBuffer) { - return readStringish(offset, charBuffer); - } - - /** - * Reads a CONSTANT_Module constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose - * value is the index of a CONSTANT_Module entry in class's constant pool table. - * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Module entry. - */ - public String readModule(final int offset, final char[] charBuffer) { - return readStringish(offset, charBuffer); - } - - /** - * Reads a CONSTANT_Package constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose - * value is the index of a CONSTANT_Package entry in class's constant pool table. - * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the String corresponding to the specified CONSTANT_Package entry. - */ - public String readPackage(final int offset, final char[] charBuffer) { - return readStringish(offset, charBuffer); - } - - /** - * Reads a CONSTANT_Dynamic constant pool entry in {@link #classFileBuffer}. - * - * @param constantPoolEntryIndex the index of a CONSTANT_Dynamic entry in the class's constant - * pool table. - * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the ConstantDynamic corresponding to the specified CONSTANT_Dynamic entry. - */ - private ConstantDynamic readConstantDynamic( - final int constantPoolEntryIndex, final char[] charBuffer) { - ConstantDynamic constantDynamic = constantDynamicValues[constantPoolEntryIndex]; - if (constantDynamic != null) { - return constantDynamic; - } - int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; - int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; - String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); - String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); - int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)]; - Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); - Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)]; - bootstrapMethodOffset += 4; - for (int i = 0; i < bootstrapMethodArguments.length; i++) { - bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); - bootstrapMethodOffset += 2; - } - return constantDynamicValues[constantPoolEntryIndex] = - new ConstantDynamic(name, descriptor, handle, bootstrapMethodArguments); - } - - /** - * Reads a numeric or string constant pool entry in this {@link ClassReader}. This method is - * intended for {@link Attribute} sub classes, and is normally not needed by class generators or - * adapters. - * - * @param constantPoolEntryIndex the index of a CONSTANT_Integer, CONSTANT_Float, CONSTANT_Long, - * CONSTANT_Double, CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, - * CONSTANT_MethodHandle or CONSTANT_Dynamic entry in the class's constant pool. - * @param charBuffer the buffer to be used to read strings. This buffer must be sufficiently - * large. It is not automatically resized. - * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String}, - * {@link Type}, {@link Handle} or {@link ConstantDynamic} corresponding to the specified - * constant pool entry. - */ - public Object readConst(final int constantPoolEntryIndex, final char[] charBuffer) { - int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; - switch (classFileBuffer[cpInfoOffset - 1]) { - case Symbol.CONSTANT_INTEGER_TAG: - return readInt(cpInfoOffset); - case Symbol.CONSTANT_FLOAT_TAG: - return Float.intBitsToFloat(readInt(cpInfoOffset)); - case Symbol.CONSTANT_LONG_TAG: - return readLong(cpInfoOffset); - case Symbol.CONSTANT_DOUBLE_TAG: - return Double.longBitsToDouble(readLong(cpInfoOffset)); - case Symbol.CONSTANT_CLASS_TAG: - return Type.getObjectType(readUTF8(cpInfoOffset, charBuffer)); - case Symbol.CONSTANT_STRING_TAG: - return readUTF8(cpInfoOffset, charBuffer); - case Symbol.CONSTANT_METHOD_TYPE_TAG: - return Type.getMethodType(readUTF8(cpInfoOffset, charBuffer)); - case Symbol.CONSTANT_METHOD_HANDLE_TAG: - int referenceKind = readByte(cpInfoOffset); - int referenceCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 1)]; - int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(referenceCpInfoOffset + 2)]; - String owner = readClass(referenceCpInfoOffset, charBuffer); - String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); - String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); - boolean isInterface = - classFileBuffer[referenceCpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG; - return new Handle(referenceKind, owner, name, descriptor, isInterface); - case Symbol.CONSTANT_DYNAMIC_TAG: - return readConstantDynamic(constantPoolEntryIndex, charBuffer); - default: - throw new IllegalArgumentException(); - } - } -} +// ASM: a very small and fast Java bytecode manipulation framework +// Copyright (c) 2000-2011 INRIA, France Telecom +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 3. Neither the name of the copyright holders nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +// THE POSSIBILITY OF SUCH DAMAGE. +package org.objectweb.asm; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * A parser to make a {@link ClassVisitor} visit a ClassFile structure, as defined in the Java + * Virtual Machine Specification (JVMS). This class parses the ClassFile content and calls the + * appropriate visit methods of a given {@link ClassVisitor} for each field, method and bytecode + * instruction encountered. + * + * @see JVMS 4 + * @author Eric Bruneton + * @author Eugene Kuleshov + */ +public class ClassReader { + + /** + * A flag to skip the Code attributes. If this flag is set the Code attributes are neither parsed + * nor visited. + */ + public static final int SKIP_CODE = 1; + + /** + * A flag to skip the SourceFile, SourceDebugExtension, LocalVariableTable, LocalVariableTypeTable + * and LineNumberTable attributes. If this flag is set these attributes are neither parsed nor + * visited (i.e. {@link ClassVisitor#visitSource}, {@link MethodVisitor#visitLocalVariable} and + * {@link MethodVisitor#visitLineNumber} are not called). + */ + public static final int SKIP_DEBUG = 2; + + /** + * A flag to skip the StackMap and StackMapTable attributes. If this flag is set these attributes + * are neither parsed nor visited (i.e. {@link MethodVisitor#visitFrame} is not called). This flag + * is useful when the {@link ClassWriter#COMPUTE_FRAMES} option is used: it avoids visiting frames + * that will be ignored and recomputed from scratch. + */ + public static final int SKIP_FRAMES = 4; + + /** + * A flag to expand the stack map frames. By default stack map frames are visited in their + * original format (i.e. "expanded" for classes whose version is less than V1_6, and "compressed" + * for the other classes). If this flag is set, stack map frames are always visited in expanded + * format (this option adds a decompression/compression step in ClassReader and ClassWriter which + * degrades performance quite a lot). + */ + public static final int EXPAND_FRAMES = 8; + + /** + * A flag to expand the ASM specific instructions into an equivalent sequence of standard bytecode + * instructions. When resolving a forward jump it may happen that the signed 2 bytes offset + * reserved for it is not sufficient to store the bytecode offset. In this case the jump + * instruction is replaced with a temporary ASM specific instruction using an unsigned 2 bytes + * offset (see {@link Label#resolve}). This internal flag is used to re-read classes containing + * such instructions, in order to replace them with standard instructions. In addition, when this + * flag is used, goto_w and jsr_w are not converted into goto and jsr, to make sure that + * infinite loops where a goto_w is replaced with a goto in ClassReader and converted back to a + * goto_w in ClassWriter cannot occur. + */ + static final int EXPAND_ASM_INSNS = 256; + + /** The size of the temporary byte array used to read class input streams chunk by chunk. */ + private static final int INPUT_STREAM_DATA_CHUNK_SIZE = 4096; + + /** + * A byte array containing the JVMS ClassFile structure to be parsed. + * + * @deprecated Use {@link #readByte(int)} and the other read methods instead. This field will + * eventually be deleted. + */ + @Deprecated + // DontCheck(MemberName): can't be renamed (for backward binary compatibility). + public final byte[] b; + + /** + * A byte array containing the JVMS ClassFile structure to be parsed. The content of this array + * must not be modified. This field is intended for {@link Attribute} sub classes, and is normally + * not needed by class visitors. + * + *

NOTE: the ClassFile structure can start at any offset within this array, i.e. it does not + * necessarily start at offset 0. Use {@link #getItem} and {@link #header} to get correct + * ClassFile element offsets within this byte array. + */ + final byte[] classFileBuffer; + + /** + * The offset in bytes, in {@link #classFileBuffer}, of each cp_info entry of the ClassFile's + * constant_pool array, plus one. In other words, the offset of constant pool entry i is + * given by cpInfoOffsets[i] - 1, i.e. its cp_info's tag field is given by b[cpInfoOffsets[i] - + * 1]. + */ + private final int[] cpInfoOffsets; + + /** + * The String objects corresponding to the CONSTANT_Utf8 constant pool items. This cache avoids + * multiple parsing of a given CONSTANT_Utf8 constant pool item. + */ + private final String[] constantUtf8Values; + + /** + * The ConstantDynamic objects corresponding to the CONSTANT_Dynamic constant pool items. This + * cache avoids multiple parsing of a given CONSTANT_Dynamic constant pool item. + */ + private final ConstantDynamic[] constantDynamicValues; + + /** + * The start offsets in {@link #classFileBuffer} of each element of the bootstrap_methods array + * (in the BootstrapMethods attribute). + * + * @see JVMS + * 4.7.23 + */ + private final int[] bootstrapMethodOffsets; + + /** + * A conservative estimate of the maximum length of the strings contained in the constant pool of + * the class. + */ + private final int maxStringLength; + + /** The offset in bytes of the ClassFile's access_flags field. */ + public final int header; + + // ----------------------------------------------------------------------------------------------- + // Constructors + // ----------------------------------------------------------------------------------------------- + + /** + * Constructs a new {@link ClassReader} object. + * + * @param classFile the JVMS ClassFile structure to be read. + */ + public ClassReader(final byte[] classFile) { + this(classFile, 0, classFile.length); + } + + /** + * Constructs a new {@link ClassReader} object. + * + * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read. + * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read. + * @param classFileLength the length in bytes of the ClassFile to be read. + */ + public ClassReader( + final byte[] classFileBuffer, + final int classFileOffset, + final int classFileLength) { // NOPMD(UnusedFormalParameter) used for backward compatibility. + this(classFileBuffer, classFileOffset, /* checkClassVersion = */ true); + } + + /** + * Constructs a new {@link ClassReader} object. This internal constructor must not be exposed + * as a public API. + * + * @param classFileBuffer a byte array containing the JVMS ClassFile structure to be read. + * @param classFileOffset the offset in byteBuffer of the first byte of the ClassFile to be read. + * @param checkClassVersion whether to check the class version or not. + */ + ClassReader( + final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion) { + this.classFileBuffer = classFileBuffer; + this.b = classFileBuffer; + // Check the class' major_version. This field is after the magic and minor_version fields, which + // use 4 and 2 bytes respectively. + if (checkClassVersion && readShort(classFileOffset + 6) > Opcodes.V17) { + throw new IllegalArgumentException( + "Unsupported class file major version " + readShort(classFileOffset + 6)); + } + // Create the constant pool arrays. The constant_pool_count field is after the magic, + // minor_version and major_version fields, which use 4, 2 and 2 bytes respectively. + int constantPoolCount = readUnsignedShort(classFileOffset + 8); + cpInfoOffsets = new int[constantPoolCount]; + constantUtf8Values = new String[constantPoolCount]; + // Compute the offset of each constant pool entry, as well as a conservative estimate of the + // maximum length of the constant pool strings. The first constant pool entry is after the + // magic, minor_version, major_version and constant_pool_count fields, which use 4, 2, 2 and 2 + // bytes respectively. + int currentCpInfoIndex = 1; + int currentCpInfoOffset = classFileOffset + 10; + int currentMaxStringLength = 0; + boolean hasBootstrapMethods = false; + boolean hasConstantDynamic = false; + // The offset of the other entries depend on the total size of all the previous entries. + while (currentCpInfoIndex < constantPoolCount) { + cpInfoOffsets[currentCpInfoIndex++] = currentCpInfoOffset + 1; + int cpInfoSize; + switch (classFileBuffer[currentCpInfoOffset]) { + case Symbol.CONSTANT_FIELDREF_TAG: + case Symbol.CONSTANT_METHODREF_TAG: + case Symbol.CONSTANT_INTERFACE_METHODREF_TAG: + case Symbol.CONSTANT_INTEGER_TAG: + case Symbol.CONSTANT_FLOAT_TAG: + case Symbol.CONSTANT_NAME_AND_TYPE_TAG: + cpInfoSize = 5; + break; + case Symbol.CONSTANT_DYNAMIC_TAG: + cpInfoSize = 5; + hasBootstrapMethods = true; + hasConstantDynamic = true; + break; + case Symbol.CONSTANT_INVOKE_DYNAMIC_TAG: + cpInfoSize = 5; + hasBootstrapMethods = true; + break; + case Symbol.CONSTANT_LONG_TAG: + case Symbol.CONSTANT_DOUBLE_TAG: + cpInfoSize = 9; + currentCpInfoIndex++; + break; + case Symbol.CONSTANT_UTF8_TAG: + cpInfoSize = 3 + readUnsignedShort(currentCpInfoOffset + 1); + if (cpInfoSize > currentMaxStringLength) { + // The size in bytes of this CONSTANT_Utf8 structure provides a conservative estimate + // of the length in characters of the corresponding string, and is much cheaper to + // compute than this exact length. + currentMaxStringLength = cpInfoSize; + } + break; + case Symbol.CONSTANT_METHOD_HANDLE_TAG: + cpInfoSize = 4; + break; + case Symbol.CONSTANT_CLASS_TAG: + case Symbol.CONSTANT_STRING_TAG: + case Symbol.CONSTANT_METHOD_TYPE_TAG: + case Symbol.CONSTANT_PACKAGE_TAG: + case Symbol.CONSTANT_MODULE_TAG: + cpInfoSize = 3; + break; + default: + throw new IllegalArgumentException(); + } + currentCpInfoOffset += cpInfoSize; + } + maxStringLength = currentMaxStringLength; + // The Classfile's access_flags field is just after the last constant pool entry. + header = currentCpInfoOffset; + + // Allocate the cache of ConstantDynamic values, if there is at least one. + constantDynamicValues = hasConstantDynamic ? new ConstantDynamic[constantPoolCount] : null; + + // Read the BootstrapMethods attribute, if any (only get the offset of each method). + bootstrapMethodOffsets = + hasBootstrapMethods ? readBootstrapMethodsAttribute(currentMaxStringLength) : null; + } + + /** + * Constructs a new {@link ClassReader} object. + * + * @param inputStream an input stream of the JVMS ClassFile structure to be read. This input + * stream must contain nothing more than the ClassFile structure itself. It is read from its + * current position to its end. + * @throws IOException if a problem occurs during reading. + */ + public ClassReader(final InputStream inputStream) throws IOException { + this(readStream(inputStream, false)); + } + + /** + * Constructs a new {@link ClassReader} object. + * + * @param className the fully qualified name of the class to be read. The ClassFile structure is + * retrieved with the current class loader's {@link ClassLoader#getSystemResourceAsStream}. + * @throws IOException if an exception occurs during reading. + */ + public ClassReader(final String className) throws IOException { + this( + readStream( + ClassLoader.getSystemResourceAsStream(className.replace('.', '/') + ".class"), true)); + } + + /** + * Reads the given input stream and returns its content as a byte array. + * + * @param inputStream an input stream. + * @param close true to close the input stream after reading. + * @return the content of the given input stream. + * @throws IOException if a problem occurs during reading. + */ + private static byte[] readStream(final InputStream inputStream, final boolean close) + throws IOException { + if (inputStream == null) { + throw new IOException("Class not found"); + } + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + byte[] data = new byte[INPUT_STREAM_DATA_CHUNK_SIZE]; + int bytesRead; + while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) { + outputStream.write(data, 0, bytesRead); + } + outputStream.flush(); + return outputStream.toByteArray(); + } finally { + if (close) { + inputStream.close(); + } + } + } + + // ----------------------------------------------------------------------------------------------- + // Accessors + // ----------------------------------------------------------------------------------------------- + + /** + * Returns the class's access flags (see {@link Opcodes}). This value may not reflect Deprecated + * and Synthetic flags when bytecode is before 1.5 and those flags are represented by attributes. + * + * @return the class access flags. + * @see ClassVisitor#visit(int, int, String, String, String, String[]) + */ + public int getAccess() { + return readUnsignedShort(header); + } + + /** + * Returns the internal name of the class (see {@link Type#getInternalName()}). + * + * @return the internal class name. + * @see ClassVisitor#visit(int, int, String, String, String, String[]) + */ + public String getClassName() { + // this_class is just after the access_flags field (using 2 bytes). + return readClass(header + 2, new char[maxStringLength]); + } + + /** + * Returns the internal of name of the super class (see {@link Type#getInternalName()}). For + * interfaces, the super class is {@link Object}. + * + * @return the internal name of the super class, or {@literal null} for {@link Object} class. + * @see ClassVisitor#visit(int, int, String, String, String, String[]) + */ + public String getSuperName() { + // super_class is after the access_flags and this_class fields (2 bytes each). + return readClass(header + 4, new char[maxStringLength]); + } + + /** + * Returns the internal names of the implemented interfaces (see {@link Type#getInternalName()}). + * + * @return the internal names of the directly implemented interfaces. Inherited implemented + * interfaces are not returned. + * @see ClassVisitor#visit(int, int, String, String, String, String[]) + */ + public String[] getInterfaces() { + // interfaces_count is after the access_flags, this_class and super_class fields (2 bytes each). + int currentOffset = header + 6; + int interfacesCount = readUnsignedShort(currentOffset); + String[] interfaces = new String[interfacesCount]; + if (interfacesCount > 0) { + char[] charBuffer = new char[maxStringLength]; + for (int i = 0; i < interfacesCount; ++i) { + currentOffset += 2; + interfaces[i] = readClass(currentOffset, charBuffer); + } + } + return interfaces; + } + + // ----------------------------------------------------------------------------------------------- + // Public methods + // ----------------------------------------------------------------------------------------------- + + /** + * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this + * {@link ClassReader}. + * + * @param classVisitor the visitor that must visit this class. + * @param parsingOptions the options to use to parse this class. One or more of {@link + * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}. + */ + public void accept(final ClassVisitor classVisitor, final int parsingOptions) { + accept(classVisitor, new Attribute[0], parsingOptions); + } + + /** + * Makes the given visitor visit the JVMS ClassFile structure passed to the constructor of this + * {@link ClassReader}. + * + * @param classVisitor the visitor that must visit this class. + * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of + * the class. Any attribute whose type is not equal to the type of one the prototypes will not + * be parsed: its byte array value will be passed unchanged to the ClassWriter. This may + * corrupt it if this value contains references to the constant pool, or has syntactic or + * semantic links with a class element that has been transformed by a class adapter between + * the reader and the writer. + * @param parsingOptions the options to use to parse this class. One or more of {@link + * #SKIP_CODE}, {@link #SKIP_DEBUG}, {@link #SKIP_FRAMES} or {@link #EXPAND_FRAMES}. + */ + public void accept( + final ClassVisitor classVisitor, + final Attribute[] attributePrototypes, + final int parsingOptions) { + Context context = new Context(); + context.attributePrototypes = attributePrototypes; + context.parsingOptions = parsingOptions; + context.charBuffer = new char[maxStringLength]; + + // Read the access_flags, this_class, super_class, interface_count and interfaces fields. + char[] charBuffer = context.charBuffer; + int currentOffset = header; + int accessFlags = readUnsignedShort(currentOffset); + String thisClass = readClass(currentOffset + 2, charBuffer); + String superClass = readClass(currentOffset + 4, charBuffer); + String[] interfaces = new String[readUnsignedShort(currentOffset + 6)]; + currentOffset += 8; + for (int i = 0; i < interfaces.length; ++i) { + interfaces[i] = readClass(currentOffset, charBuffer); + currentOffset += 2; + } + + // Read the class attributes (the variables are ordered as in Section 4.7 of the JVMS). + // Attribute offsets exclude the attribute_name_index and attribute_length fields. + // - The offset of the InnerClasses attribute, or 0. + int innerClassesOffset = 0; + // - The offset of the EnclosingMethod attribute, or 0. + int enclosingMethodOffset = 0; + // - The string corresponding to the Signature attribute, or null. + String signature = null; + // - The string corresponding to the SourceFile attribute, or null. + String sourceFile = null; + // - The string corresponding to the SourceDebugExtension attribute, or null. + String sourceDebugExtension = null; + // - The offset of the RuntimeVisibleAnnotations attribute, or 0. + int runtimeVisibleAnnotationsOffset = 0; + // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. + int runtimeInvisibleAnnotationsOffset = 0; + // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. + int runtimeVisibleTypeAnnotationsOffset = 0; + // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. + int runtimeInvisibleTypeAnnotationsOffset = 0; + // - The offset of the Module attribute, or 0. + int moduleOffset = 0; + // - The offset of the ModulePackages attribute, or 0. + int modulePackagesOffset = 0; + // - The string corresponding to the ModuleMainClass attribute, or null. + String moduleMainClass = null; + // - The string corresponding to the NestHost attribute, or null. + String nestHostClass = null; + // - The offset of the NestMembers attribute, or 0. + int nestMembersOffset = 0; + // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). + // This list in the reverse order or their order in the ClassFile structure. + Attribute attributes = null; + + int currentAttributeOffset = getFirstAttributeOffset(); + for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { + // Read the attribute_info's attribute_name and attribute_length fields. + String attributeName = readUTF8(currentAttributeOffset, charBuffer); + int attributeLength = readInt(currentAttributeOffset + 2); + currentAttributeOffset += 6; + // The tests are sorted in decreasing frequency order (based on frequencies observed on + // typical classes). + if (Constants.SOURCE_FILE.equals(attributeName)) { + sourceFile = readUTF8(currentAttributeOffset, charBuffer); + } else if (Constants.INNER_CLASSES.equals(attributeName)) { + innerClassesOffset = currentAttributeOffset; + } else if (Constants.ENCLOSING_METHOD.equals(attributeName)) { + enclosingMethodOffset = currentAttributeOffset; + } else if (Constants.NEST_HOST.equals(attributeName)) { + nestHostClass = readClass(currentAttributeOffset, charBuffer); + } else if (Constants.NEST_MEMBERS.equals(attributeName)) { + nestMembersOffset = currentAttributeOffset; + } else if (Constants.SIGNATURE.equals(attributeName)) { + signature = readUTF8(currentAttributeOffset, charBuffer); + } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { + runtimeVisibleAnnotationsOffset = currentAttributeOffset; + } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { + runtimeVisibleTypeAnnotationsOffset = currentAttributeOffset; + } else if (Constants.DEPRECATED.equals(attributeName)) { + accessFlags |= Opcodes.ACC_DEPRECATED; + } else if (Constants.SYNTHETIC.equals(attributeName)) { + accessFlags |= Opcodes.ACC_SYNTHETIC; + } else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) { + sourceDebugExtension = + readUtf(currentAttributeOffset, attributeLength, new char[attributeLength]); + } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { + runtimeInvisibleAnnotationsOffset = currentAttributeOffset; + } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { + runtimeInvisibleTypeAnnotationsOffset = currentAttributeOffset; + } else if (Constants.MODULE.equals(attributeName)) { + moduleOffset = currentAttributeOffset; + } else if (Constants.MODULE_MAIN_CLASS.equals(attributeName)) { + moduleMainClass = readClass(currentAttributeOffset, charBuffer); + } else if (Constants.MODULE_PACKAGES.equals(attributeName)) { + modulePackagesOffset = currentAttributeOffset; + } else if (!Constants.BOOTSTRAP_METHODS.equals(attributeName)) { + // The BootstrapMethods attribute is read in the constructor. + Attribute attribute = + readAttribute( + attributePrototypes, + attributeName, + currentAttributeOffset, + attributeLength, + charBuffer, + -1, + null); + attribute.nextAttribute = attributes; + attributes = attribute; + } + currentAttributeOffset += attributeLength; + } + + // Visit the class declaration. The minor_version and major_version fields start 6 bytes before + // the first constant pool entry, which itself starts at cpInfoOffsets[1] - 1 (by definition). + classVisitor.visit( + readInt(cpInfoOffsets[1] - 7), accessFlags, thisClass, signature, superClass, interfaces); + + // Visit the SourceFile and SourceDebugExtenstion attributes. + if ((parsingOptions & SKIP_DEBUG) == 0 + && (sourceFile != null || sourceDebugExtension != null)) { + classVisitor.visitSource(sourceFile, sourceDebugExtension); + } + + // Visit the Module, ModulePackages and ModuleMainClass attributes. + if (moduleOffset != 0) { + readModuleAttributes( + classVisitor, context, moduleOffset, modulePackagesOffset, moduleMainClass); + } + + // Visit the NestHost attribute. + if (nestHostClass != null) { + classVisitor.visitNestHost(nestHostClass); + } + + // Visit the EnclosingMethod attribute. + if (enclosingMethodOffset != 0) { + String className = readClass(enclosingMethodOffset, charBuffer); + int methodIndex = readUnsignedShort(enclosingMethodOffset + 2); + String name = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex], charBuffer); + String type = methodIndex == 0 ? null : readUTF8(cpInfoOffsets[methodIndex] + 2, charBuffer); + classVisitor.visitOuterClass(className, name, type); + } + + // Visit the RuntimeVisibleAnnotations attribute. + if (runtimeVisibleAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); + int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeInvisibleAnnotations attribute. + if (runtimeInvisibleAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); + int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + classVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeVisibleTypeAnnotations attribute. + if (runtimeVisibleTypeAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); + int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the target_type, target_info and target_path fields. + currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + classVisitor.visitTypeAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + annotationDescriptor, + /* visible = */ true), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeInvisibleTypeAnnotations attribute. + if (runtimeInvisibleTypeAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); + int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the target_type, target_info and target_path fields. + currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + classVisitor.visitTypeAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + annotationDescriptor, + /* visible = */ false), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the non standard attributes. + while (attributes != null) { + // Copy and reset the nextAttribute field so that it can also be used in ClassWriter. + Attribute nextAttribute = attributes.nextAttribute; + attributes.nextAttribute = null; + classVisitor.visitAttribute(attributes); + attributes = nextAttribute; + } + + // Visit the NestedMembers attribute. + if (nestMembersOffset != 0) { + int numberOfNestMembers = readUnsignedShort(nestMembersOffset); + int currentNestMemberOffset = nestMembersOffset + 2; + while (numberOfNestMembers-- > 0) { + classVisitor.visitNestMember(readClass(currentNestMemberOffset, charBuffer)); + currentNestMemberOffset += 2; + } + } + + // Visit the InnerClasses attribute. + if (innerClassesOffset != 0) { + int numberOfClasses = readUnsignedShort(innerClassesOffset); + int currentClassesOffset = innerClassesOffset + 2; + while (numberOfClasses-- > 0) { + classVisitor.visitInnerClass( + readClass(currentClassesOffset, charBuffer), + readClass(currentClassesOffset + 2, charBuffer), + readUTF8(currentClassesOffset + 4, charBuffer), + readUnsignedShort(currentClassesOffset + 6)); + currentClassesOffset += 8; + } + } + + // Visit the fields and methods. + int fieldsCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (fieldsCount-- > 0) { + currentOffset = readField(classVisitor, context, currentOffset); + } + int methodsCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (methodsCount-- > 0) { + currentOffset = readMethod(classVisitor, context, currentOffset); + } + + // Visit the end of the class. + classVisitor.visitEnd(); + } + + // ---------------------------------------------------------------------------------------------- + // Methods to parse modules, fields and methods + // ---------------------------------------------------------------------------------------------- + + /** + * Reads the Module, ModulePackages and ModuleMainClass attributes and visit them. + * + * @param classVisitor the current class visitor + * @param context information about the class being parsed. + * @param moduleOffset the offset of the Module attribute (excluding the attribute_info's + * attribute_name_index and attribute_length fields). + * @param modulePackagesOffset the offset of the ModulePackages attribute (excluding the + * attribute_info's attribute_name_index and attribute_length fields), or 0. + * @param moduleMainClass the string corresponding to the ModuleMainClass attribute, or null. + */ + private void readModuleAttributes( + final ClassVisitor classVisitor, + final Context context, + final int moduleOffset, + final int modulePackagesOffset, + final String moduleMainClass) { + char[] buffer = context.charBuffer; + + // Read the module_name_index, module_flags and module_version_index fields and visit them. + int currentOffset = moduleOffset; + String moduleName = readModule(currentOffset, buffer); + int moduleFlags = readUnsignedShort(currentOffset + 2); + String moduleVersion = readUTF8(currentOffset + 4, buffer); + currentOffset += 6; + ModuleVisitor moduleVisitor = classVisitor.visitModule(moduleName, moduleFlags, moduleVersion); + if (moduleVisitor == null) { + return; + } + + // Visit the ModuleMainClass attribute. + if (moduleMainClass != null) { + moduleVisitor.visitMainClass(moduleMainClass); + } + + // Visit the ModulePackages attribute. + if (modulePackagesOffset != 0) { + int packageCount = readUnsignedShort(modulePackagesOffset); + int currentPackageOffset = modulePackagesOffset + 2; + while (packageCount-- > 0) { + moduleVisitor.visitPackage(readPackage(currentPackageOffset, buffer)); + currentPackageOffset += 2; + } + } + + // Read the 'requires_count' and 'requires' fields. + int requiresCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (requiresCount-- > 0) { + // Read the requires_index, requires_flags and requires_version fields and visit them. + String requires = readModule(currentOffset, buffer); + int requiresFlags = readUnsignedShort(currentOffset + 2); + String requiresVersion = readUTF8(currentOffset + 4, buffer); + currentOffset += 6; + moduleVisitor.visitRequire(requires, requiresFlags, requiresVersion); + } + + // Read the 'exports_count' and 'exports' fields. + int exportsCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (exportsCount-- > 0) { + // Read the exports_index, exports_flags, exports_to_count and exports_to_index fields + // and visit them. + String exports = readPackage(currentOffset, buffer); + int exportsFlags = readUnsignedShort(currentOffset + 2); + int exportsToCount = readUnsignedShort(currentOffset + 4); + currentOffset += 6; + String[] exportsTo = null; + if (exportsToCount != 0) { + exportsTo = new String[exportsToCount]; + for (int i = 0; i < exportsToCount; ++i) { + exportsTo[i] = readModule(currentOffset, buffer); + currentOffset += 2; + } + } + moduleVisitor.visitExport(exports, exportsFlags, exportsTo); + } + + // Reads the 'opens_count' and 'opens' fields. + int opensCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (opensCount-- > 0) { + // Read the opens_index, opens_flags, opens_to_count and opens_to_index fields and visit them. + String opens = readPackage(currentOffset, buffer); + int opensFlags = readUnsignedShort(currentOffset + 2); + int opensToCount = readUnsignedShort(currentOffset + 4); + currentOffset += 6; + String[] opensTo = null; + if (opensToCount != 0) { + opensTo = new String[opensToCount]; + for (int i = 0; i < opensToCount; ++i) { + opensTo[i] = readModule(currentOffset, buffer); + currentOffset += 2; + } + } + moduleVisitor.visitOpen(opens, opensFlags, opensTo); + } + + // Read the 'uses_count' and 'uses' fields. + int usesCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (usesCount-- > 0) { + moduleVisitor.visitUse(readClass(currentOffset, buffer)); + currentOffset += 2; + } + + // Read the 'provides_count' and 'provides' fields. + int providesCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (providesCount-- > 0) { + // Read the provides_index, provides_with_count and provides_with_index fields and visit them. + String provides = readClass(currentOffset, buffer); + int providesWithCount = readUnsignedShort(currentOffset + 2); + currentOffset += 4; + String[] providesWith = new String[providesWithCount]; + for (int i = 0; i < providesWithCount; ++i) { + providesWith[i] = readClass(currentOffset, buffer); + currentOffset += 2; + } + moduleVisitor.visitProvide(provides, providesWith); + } + + // Visit the end of the module attributes. + moduleVisitor.visitEnd(); + } + + /** + * Reads a JVMS field_info structure and makes the given visitor visit it. + * + * @param classVisitor the visitor that must visit the field. + * @param context information about the class being parsed. + * @param fieldInfoOffset the start offset of the field_info structure. + * @return the offset of the first byte following the field_info structure. + */ + private int readField( + final ClassVisitor classVisitor, final Context context, final int fieldInfoOffset) { + char[] charBuffer = context.charBuffer; + + // Read the access_flags, name_index and descriptor_index fields. + int currentOffset = fieldInfoOffset; + int accessFlags = readUnsignedShort(currentOffset); + String name = readUTF8(currentOffset + 2, charBuffer); + String descriptor = readUTF8(currentOffset + 4, charBuffer); + currentOffset += 6; + + // Read the field attributes (the variables are ordered as in Section 4.7 of the JVMS). + // Attribute offsets exclude the attribute_name_index and attribute_length fields. + // - The value corresponding to the ConstantValue attribute, or null. + Object constantValue = null; + // - The string corresponding to the Signature attribute, or null. + String signature = null; + // - The offset of the RuntimeVisibleAnnotations attribute, or 0. + int runtimeVisibleAnnotationsOffset = 0; + // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. + int runtimeInvisibleAnnotationsOffset = 0; + // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. + int runtimeVisibleTypeAnnotationsOffset = 0; + // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. + int runtimeInvisibleTypeAnnotationsOffset = 0; + // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). + // This list in the reverse order or their order in the ClassFile structure. + Attribute attributes = null; + + int attributesCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (attributesCount-- > 0) { + // Read the attribute_info's attribute_name and attribute_length fields. + String attributeName = readUTF8(currentOffset, charBuffer); + int attributeLength = readInt(currentOffset + 2); + currentOffset += 6; + // The tests are sorted in decreasing frequency order (based on frequencies observed on + // typical classes). + if (Constants.CONSTANT_VALUE.equals(attributeName)) { + int constantvalueIndex = readUnsignedShort(currentOffset); + constantValue = constantvalueIndex == 0 ? null : readConst(constantvalueIndex, charBuffer); + } else if (Constants.SIGNATURE.equals(attributeName)) { + signature = readUTF8(currentOffset, charBuffer); + } else if (Constants.DEPRECATED.equals(attributeName)) { + accessFlags |= Opcodes.ACC_DEPRECATED; + } else if (Constants.SYNTHETIC.equals(attributeName)) { + accessFlags |= Opcodes.ACC_SYNTHETIC; + } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { + runtimeVisibleAnnotationsOffset = currentOffset; + } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { + runtimeVisibleTypeAnnotationsOffset = currentOffset; + } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { + runtimeInvisibleAnnotationsOffset = currentOffset; + } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { + runtimeInvisibleTypeAnnotationsOffset = currentOffset; + } else { + Attribute attribute = + readAttribute( + context.attributePrototypes, + attributeName, + currentOffset, + attributeLength, + charBuffer, + -1, + null); + attribute.nextAttribute = attributes; + attributes = attribute; + } + currentOffset += attributeLength; + } + + // Visit the field declaration. + FieldVisitor fieldVisitor = + classVisitor.visitField(accessFlags, name, descriptor, signature, constantValue); + if (fieldVisitor == null) { + return currentOffset; + } + + // Visit the RuntimeVisibleAnnotations attribute. + if (runtimeVisibleAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); + int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeInvisibleAnnotations attribute. + if (runtimeInvisibleAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); + int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + fieldVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeVisibleTypeAnnotations attribute. + if (runtimeVisibleTypeAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); + int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the target_type, target_info and target_path fields. + currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + fieldVisitor.visitTypeAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + annotationDescriptor, + /* visible = */ true), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeInvisibleTypeAnnotations attribute. + if (runtimeInvisibleTypeAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); + int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the target_type, target_info and target_path fields. + currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + fieldVisitor.visitTypeAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + annotationDescriptor, + /* visible = */ false), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the non standard attributes. + while (attributes != null) { + // Copy and reset the nextAttribute field so that it can also be used in FieldWriter. + Attribute nextAttribute = attributes.nextAttribute; + attributes.nextAttribute = null; + fieldVisitor.visitAttribute(attributes); + attributes = nextAttribute; + } + + // Visit the end of the field. + fieldVisitor.visitEnd(); + return currentOffset; + } + + /** + * Reads a JVMS method_info structure and makes the given visitor visit it. + * + * @param classVisitor the visitor that must visit the method. + * @param context information about the class being parsed. + * @param methodInfoOffset the start offset of the method_info structure. + * @return the offset of the first byte following the method_info structure. + */ + private int readMethod( + final ClassVisitor classVisitor, final Context context, final int methodInfoOffset) { + char[] charBuffer = context.charBuffer; + + // Read the access_flags, name_index and descriptor_index fields. + int currentOffset = methodInfoOffset; + context.currentMethodAccessFlags = readUnsignedShort(currentOffset); + context.currentMethodName = readUTF8(currentOffset + 2, charBuffer); + context.currentMethodDescriptor = readUTF8(currentOffset + 4, charBuffer); + currentOffset += 6; + + // Read the method attributes (the variables are ordered as in Section 4.7 of the JVMS). + // Attribute offsets exclude the attribute_name_index and attribute_length fields. + // - The offset of the Code attribute, or 0. + int codeOffset = 0; + // - The offset of the Exceptions attribute, or 0. + int exceptionsOffset = 0; + // - The strings corresponding to the Exceptions attribute, or null. + String[] exceptions = null; + // - Whether the method has a Synthetic attribute. + boolean synthetic = false; + // - The constant pool index contained in the Signature attribute, or 0. + int signatureIndex = 0; + // - The offset of the RuntimeVisibleAnnotations attribute, or 0. + int runtimeVisibleAnnotationsOffset = 0; + // - The offset of the RuntimeInvisibleAnnotations attribute, or 0. + int runtimeInvisibleAnnotationsOffset = 0; + // - The offset of the RuntimeVisibleParameterAnnotations attribute, or 0. + int runtimeVisibleParameterAnnotationsOffset = 0; + // - The offset of the RuntimeInvisibleParameterAnnotations attribute, or 0. + int runtimeInvisibleParameterAnnotationsOffset = 0; + // - The offset of the RuntimeVisibleTypeAnnotations attribute, or 0. + int runtimeVisibleTypeAnnotationsOffset = 0; + // - The offset of the RuntimeInvisibleTypeAnnotations attribute, or 0. + int runtimeInvisibleTypeAnnotationsOffset = 0; + // - The offset of the AnnotationDefault attribute, or 0. + int annotationDefaultOffset = 0; + // - The offset of the MethodParameters attribute, or 0. + int methodParametersOffset = 0; + // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). + // This list in the reverse order or their order in the ClassFile structure. + Attribute attributes = null; + + int attributesCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (attributesCount-- > 0) { + // Read the attribute_info's attribute_name and attribute_length fields. + String attributeName = readUTF8(currentOffset, charBuffer); + int attributeLength = readInt(currentOffset + 2); + currentOffset += 6; + // The tests are sorted in decreasing frequency order (based on frequencies observed on + // typical classes). + if (Constants.CODE.equals(attributeName)) { + if ((context.parsingOptions & SKIP_CODE) == 0) { + codeOffset = currentOffset; + } + } else if (Constants.EXCEPTIONS.equals(attributeName)) { + exceptionsOffset = currentOffset; + exceptions = new String[readUnsignedShort(exceptionsOffset)]; + int currentExceptionOffset = exceptionsOffset + 2; + for (int i = 0; i < exceptions.length; ++i) { + exceptions[i] = readClass(currentExceptionOffset, charBuffer); + currentExceptionOffset += 2; + } + } else if (Constants.SIGNATURE.equals(attributeName)) { + signatureIndex = readUnsignedShort(currentOffset); + } else if (Constants.DEPRECATED.equals(attributeName)) { + context.currentMethodAccessFlags |= Opcodes.ACC_DEPRECATED; + } else if (Constants.RUNTIME_VISIBLE_ANNOTATIONS.equals(attributeName)) { + runtimeVisibleAnnotationsOffset = currentOffset; + } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { + runtimeVisibleTypeAnnotationsOffset = currentOffset; + } else if (Constants.ANNOTATION_DEFAULT.equals(attributeName)) { + annotationDefaultOffset = currentOffset; + } else if (Constants.SYNTHETIC.equals(attributeName)) { + synthetic = true; + context.currentMethodAccessFlags |= Opcodes.ACC_SYNTHETIC; + } else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) { + runtimeInvisibleAnnotationsOffset = currentOffset; + } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { + runtimeInvisibleTypeAnnotationsOffset = currentOffset; + } else if (Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) { + runtimeVisibleParameterAnnotationsOffset = currentOffset; + } else if (Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS.equals(attributeName)) { + runtimeInvisibleParameterAnnotationsOffset = currentOffset; + } else if (Constants.METHOD_PARAMETERS.equals(attributeName)) { + methodParametersOffset = currentOffset; + } else { + Attribute attribute = + readAttribute( + context.attributePrototypes, + attributeName, + currentOffset, + attributeLength, + charBuffer, + -1, + null); + attribute.nextAttribute = attributes; + attributes = attribute; + } + currentOffset += attributeLength; + } + + // Visit the method declaration. + MethodVisitor methodVisitor = + classVisitor.visitMethod( + context.currentMethodAccessFlags, + context.currentMethodName, + context.currentMethodDescriptor, + signatureIndex == 0 ? null : readUtf(signatureIndex, charBuffer), + exceptions); + if (methodVisitor == null) { + return currentOffset; + } + + // If the returned MethodVisitor is in fact a MethodWriter, it means there is no method + // adapter between the reader and the writer. In this case, it might be possible to copy + // the method attributes directly into the writer. If so, return early without visiting + // the content of these attributes. + if (methodVisitor instanceof MethodWriter) { + MethodWriter methodWriter = (MethodWriter) methodVisitor; + if (methodWriter.canCopyMethodAttributes( + this, + synthetic, + (context.currentMethodAccessFlags & Opcodes.ACC_DEPRECATED) != 0, + readUnsignedShort(methodInfoOffset + 4), + signatureIndex, + exceptionsOffset)) { + methodWriter.setMethodAttributesSource(methodInfoOffset, currentOffset - methodInfoOffset); + return currentOffset; + } + } + + // Visit the MethodParameters attribute. + if (methodParametersOffset != 0) { + int parametersCount = readByte(methodParametersOffset); + int currentParameterOffset = methodParametersOffset + 1; + while (parametersCount-- > 0) { + // Read the name_index and access_flags fields and visit them. + methodVisitor.visitParameter( + readUTF8(currentParameterOffset, charBuffer), + readUnsignedShort(currentParameterOffset + 2)); + currentParameterOffset += 4; + } + } + + // Visit the AnnotationDefault attribute. + if (annotationDefaultOffset != 0) { + AnnotationVisitor annotationVisitor = methodVisitor.visitAnnotationDefault(); + readElementValue(annotationVisitor, annotationDefaultOffset, null, charBuffer); + if (annotationVisitor != null) { + annotationVisitor.visitEnd(); + } + } + + // Visit the RuntimeVisibleAnnotations attribute. + if (runtimeVisibleAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeVisibleAnnotationsOffset); + int currentAnnotationOffset = runtimeVisibleAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ true), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeInvisibleAnnotations attribute. + if (runtimeInvisibleAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeInvisibleAnnotationsOffset); + int currentAnnotationOffset = runtimeInvisibleAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + methodVisitor.visitAnnotation(annotationDescriptor, /* visible = */ false), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeVisibleTypeAnnotations attribute. + if (runtimeVisibleTypeAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeVisibleTypeAnnotationsOffset); + int currentAnnotationOffset = runtimeVisibleTypeAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the target_type, target_info and target_path fields. + currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + methodVisitor.visitTypeAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + annotationDescriptor, + /* visible = */ true), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeInvisibleTypeAnnotations attribute. + if (runtimeInvisibleTypeAnnotationsOffset != 0) { + int numAnnotations = readUnsignedShort(runtimeInvisibleTypeAnnotationsOffset); + int currentAnnotationOffset = runtimeInvisibleTypeAnnotationsOffset + 2; + while (numAnnotations-- > 0) { + // Parse the target_type, target_info and target_path fields. + currentAnnotationOffset = readTypeAnnotationTarget(context, currentAnnotationOffset); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentAnnotationOffset = + readElementValues( + methodVisitor.visitTypeAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + annotationDescriptor, + /* visible = */ false), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + } + + // Visit the RuntimeVisibleParameterAnnotations attribute. + if (runtimeVisibleParameterAnnotationsOffset != 0) { + readParameterAnnotations( + methodVisitor, context, runtimeVisibleParameterAnnotationsOffset, /* visible = */ true); + } + + // Visit the RuntimeInvisibleParameterAnnotations attribute. + if (runtimeInvisibleParameterAnnotationsOffset != 0) { + readParameterAnnotations( + methodVisitor, + context, + runtimeInvisibleParameterAnnotationsOffset, + /* visible = */ false); + } + + // Visit the non standard attributes. + while (attributes != null) { + // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. + Attribute nextAttribute = attributes.nextAttribute; + attributes.nextAttribute = null; + methodVisitor.visitAttribute(attributes); + attributes = nextAttribute; + } + + // Visit the Code attribute. + if (codeOffset != 0) { + methodVisitor.visitCode(); + readCode(methodVisitor, context, codeOffset); + } + + // Visit the end of the method. + methodVisitor.visitEnd(); + return currentOffset; + } + + // ---------------------------------------------------------------------------------------------- + // Methods to parse a Code attribute + // ---------------------------------------------------------------------------------------------- + + /** + * Reads a JVMS 'Code' attribute and makes the given visitor visit it. + * + * @param methodVisitor the visitor that must visit the Code attribute. + * @param context information about the class being parsed. + * @param codeOffset the start offset in {@link #classFileBuffer} of the Code attribute, excluding + * its attribute_name_index and attribute_length fields. + */ + private void readCode( + final MethodVisitor methodVisitor, final Context context, final int codeOffset) { + int currentOffset = codeOffset; + + // Read the max_stack, max_locals and code_length fields. + final byte[] classBuffer = classFileBuffer; + final char[] charBuffer = context.charBuffer; + final int majorVersion = readUnsignedShort(6); + final int minorVersion = readUnsignedShort(4); + + final int maxStack; + final int maxLocals; + final int codeLength; + + if (majorVersion == 45 && minorVersion <= 2) { + maxStack = readByte(currentOffset); + maxLocals = readByte(currentOffset + 1); + codeLength = readUnsignedShort(currentOffset + 2); + currentOffset += 4; + } else { + maxStack = readUnsignedShort(currentOffset); + maxLocals = readUnsignedShort(currentOffset + 2); + codeLength = readInt(currentOffset + 4); + currentOffset += 8; + } + + // Read the bytecode 'code' array to create a label for each referenced instruction. + final int bytecodeStartOffset = currentOffset; + final int bytecodeEndOffset = currentOffset + codeLength; + final Label[] labels = context.currentMethodLabels = new Label[codeLength + 1]; + while (currentOffset < bytecodeEndOffset) { + final int bytecodeOffset = currentOffset - bytecodeStartOffset; + final int opcode = classBuffer[currentOffset] & 0xFF; + switch (opcode) { + case Opcodes.NOP: + case Opcodes.ACONST_NULL: + case Opcodes.ICONST_M1: + case Opcodes.ICONST_0: + case Opcodes.ICONST_1: + case Opcodes.ICONST_2: + case Opcodes.ICONST_3: + case Opcodes.ICONST_4: + case Opcodes.ICONST_5: + case Opcodes.LCONST_0: + case Opcodes.LCONST_1: + case Opcodes.FCONST_0: + case Opcodes.FCONST_1: + case Opcodes.FCONST_2: + case Opcodes.DCONST_0: + case Opcodes.DCONST_1: + case Opcodes.IALOAD: + case Opcodes.LALOAD: + case Opcodes.FALOAD: + case Opcodes.DALOAD: + case Opcodes.AALOAD: + case Opcodes.BALOAD: + case Opcodes.CALOAD: + case Opcodes.SALOAD: + case Opcodes.IASTORE: + case Opcodes.LASTORE: + case Opcodes.FASTORE: + case Opcodes.DASTORE: + case Opcodes.AASTORE: + case Opcodes.BASTORE: + case Opcodes.CASTORE: + case Opcodes.SASTORE: + case Opcodes.POP: + case Opcodes.POP2: + case Opcodes.DUP: + case Opcodes.DUP_X1: + case Opcodes.DUP_X2: + case Opcodes.DUP2: + case Opcodes.DUP2_X1: + case Opcodes.DUP2_X2: + case Opcodes.SWAP: + case Opcodes.IADD: + case Opcodes.LADD: + case Opcodes.FADD: + case Opcodes.DADD: + case Opcodes.ISUB: + case Opcodes.LSUB: + case Opcodes.FSUB: + case Opcodes.DSUB: + case Opcodes.IMUL: + case Opcodes.LMUL: + case Opcodes.FMUL: + case Opcodes.DMUL: + case Opcodes.IDIV: + case Opcodes.LDIV: + case Opcodes.FDIV: + case Opcodes.DDIV: + case Opcodes.IREM: + case Opcodes.LREM: + case Opcodes.FREM: + case Opcodes.DREM: + case Opcodes.INEG: + case Opcodes.LNEG: + case Opcodes.FNEG: + case Opcodes.DNEG: + case Opcodes.ISHL: + case Opcodes.LSHL: + case Opcodes.ISHR: + case Opcodes.LSHR: + case Opcodes.IUSHR: + case Opcodes.LUSHR: + case Opcodes.IAND: + case Opcodes.LAND: + case Opcodes.IOR: + case Opcodes.LOR: + case Opcodes.IXOR: + case Opcodes.LXOR: + case Opcodes.I2L: + case Opcodes.I2F: + case Opcodes.I2D: + case Opcodes.L2I: + case Opcodes.L2F: + case Opcodes.L2D: + case Opcodes.F2I: + case Opcodes.F2L: + case Opcodes.F2D: + case Opcodes.D2I: + case Opcodes.D2L: + case Opcodes.D2F: + case Opcodes.I2B: + case Opcodes.I2C: + case Opcodes.I2S: + case Opcodes.LCMP: + case Opcodes.FCMPL: + case Opcodes.FCMPG: + case Opcodes.DCMPL: + case Opcodes.DCMPG: + case Opcodes.IRETURN: + case Opcodes.LRETURN: + case Opcodes.FRETURN: + case Opcodes.DRETURN: + case Opcodes.ARETURN: + case Opcodes.RETURN: + case Opcodes.ARRAYLENGTH: + case Opcodes.ATHROW: + case Opcodes.MONITORENTER: + case Opcodes.MONITOREXIT: + case Constants.ILOAD_0: + case Constants.ILOAD_1: + case Constants.ILOAD_2: + case Constants.ILOAD_3: + case Constants.LLOAD_0: + case Constants.LLOAD_1: + case Constants.LLOAD_2: + case Constants.LLOAD_3: + case Constants.FLOAD_0: + case Constants.FLOAD_1: + case Constants.FLOAD_2: + case Constants.FLOAD_3: + case Constants.DLOAD_0: + case Constants.DLOAD_1: + case Constants.DLOAD_2: + case Constants.DLOAD_3: + case Constants.ALOAD_0: + case Constants.ALOAD_1: + case Constants.ALOAD_2: + case Constants.ALOAD_3: + case Constants.ISTORE_0: + case Constants.ISTORE_1: + case Constants.ISTORE_2: + case Constants.ISTORE_3: + case Constants.LSTORE_0: + case Constants.LSTORE_1: + case Constants.LSTORE_2: + case Constants.LSTORE_3: + case Constants.FSTORE_0: + case Constants.FSTORE_1: + case Constants.FSTORE_2: + case Constants.FSTORE_3: + case Constants.DSTORE_0: + case Constants.DSTORE_1: + case Constants.DSTORE_2: + case Constants.DSTORE_3: + case Constants.ASTORE_0: + case Constants.ASTORE_1: + case Constants.ASTORE_2: + case Constants.ASTORE_3: + currentOffset += 1; + break; + case Opcodes.IFEQ: + case Opcodes.IFNE: + case Opcodes.IFLT: + case Opcodes.IFGE: + case Opcodes.IFGT: + case Opcodes.IFLE: + case Opcodes.IF_ICMPEQ: + case Opcodes.IF_ICMPNE: + case Opcodes.IF_ICMPLT: + case Opcodes.IF_ICMPGE: + case Opcodes.IF_ICMPGT: + case Opcodes.IF_ICMPLE: + case Opcodes.IF_ACMPEQ: + case Opcodes.IF_ACMPNE: + case Opcodes.GOTO: + case Opcodes.JSR: + case Opcodes.IFNULL: + case Opcodes.IFNONNULL: + createLabel(bytecodeOffset + readShort(currentOffset + 1), labels); + currentOffset += 3; + break; + case Constants.ASM_IFEQ: + case Constants.ASM_IFNE: + case Constants.ASM_IFLT: + case Constants.ASM_IFGE: + case Constants.ASM_IFGT: + case Constants.ASM_IFLE: + case Constants.ASM_IF_ICMPEQ: + case Constants.ASM_IF_ICMPNE: + case Constants.ASM_IF_ICMPLT: + case Constants.ASM_IF_ICMPGE: + case Constants.ASM_IF_ICMPGT: + case Constants.ASM_IF_ICMPLE: + case Constants.ASM_IF_ACMPEQ: + case Constants.ASM_IF_ACMPNE: + case Constants.ASM_GOTO: + case Constants.ASM_JSR: + case Constants.ASM_IFNULL: + case Constants.ASM_IFNONNULL: + createLabel(bytecodeOffset + readUnsignedShort(currentOffset + 1), labels); + currentOffset += 3; + break; + case Constants.GOTO_W: + case Constants.JSR_W: + case Constants.ASM_GOTO_W: + createLabel(bytecodeOffset + readInt(currentOffset + 1), labels); + currentOffset += 5; + break; + case Constants.WIDE: + switch (classBuffer[currentOffset + 1] & 0xFF) { + case Opcodes.ILOAD: + case Opcodes.FLOAD: + case Opcodes.ALOAD: + case Opcodes.LLOAD: + case Opcodes.DLOAD: + case Opcodes.ISTORE: + case Opcodes.FSTORE: + case Opcodes.ASTORE: + case Opcodes.LSTORE: + case Opcodes.DSTORE: + case Opcodes.RET: + currentOffset += 4; + break; + case Opcodes.IINC: + currentOffset += 6; + break; + default: + throw new IllegalArgumentException(); + } + break; + case Opcodes.TABLESWITCH: + // Skip 0 to 3 padding bytes. + currentOffset += 4 - (bytecodeOffset & 3); + // Read the default label and the number of table entries. + createLabel(bytecodeOffset + readInt(currentOffset), labels); + int numTableEntries = readInt(currentOffset + 8) - readInt(currentOffset + 4) + 1; + currentOffset += 12; + // Read the table labels. + while (numTableEntries-- > 0) { + createLabel(bytecodeOffset + readInt(currentOffset), labels); + currentOffset += 4; + } + break; + case Opcodes.LOOKUPSWITCH: + // Skip 0 to 3 padding bytes. + currentOffset += 4 - (bytecodeOffset & 3); + // Read the default label and the number of switch cases. + createLabel(bytecodeOffset + readInt(currentOffset), labels); + int numSwitchCases = readInt(currentOffset + 4); + currentOffset += 8; + // Read the switch labels. + while (numSwitchCases-- > 0) { + createLabel(bytecodeOffset + readInt(currentOffset + 4), labels); + currentOffset += 8; + } + break; + case Opcodes.ILOAD: + case Opcodes.LLOAD: + case Opcodes.FLOAD: + case Opcodes.DLOAD: + case Opcodes.ALOAD: + case Opcodes.ISTORE: + case Opcodes.LSTORE: + case Opcodes.FSTORE: + case Opcodes.DSTORE: + case Opcodes.ASTORE: + case Opcodes.RET: + case Opcodes.BIPUSH: + case Opcodes.NEWARRAY: + case Opcodes.LDC: + currentOffset += 2; + break; + case Opcodes.SIPUSH: + case Constants.LDC_W: + case Constants.LDC2_W: + case Opcodes.GETSTATIC: + case Opcodes.PUTSTATIC: + case Opcodes.GETFIELD: + case Opcodes.PUTFIELD: + case Opcodes.INVOKEVIRTUAL: + case Opcodes.INVOKESPECIAL: + case Opcodes.INVOKESTATIC: + case Opcodes.NEW: + case Opcodes.ANEWARRAY: + case Opcodes.CHECKCAST: + case Opcodes.INSTANCEOF: + case Opcodes.IINC: + currentOffset += 3; + break; + case Opcodes.INVOKEINTERFACE: + case Opcodes.INVOKEDYNAMIC: + currentOffset += 5; + break; + case Opcodes.MULTIANEWARRAY: + currentOffset += 4; + break; + default: + throw new IllegalArgumentException(); + } + } + + // Read the 'exception_table_length' and 'exception_table' field to create a label for each + // referenced instruction, and to make methodVisitor visit the corresponding try catch blocks. + int exceptionTableLength = readUnsignedShort(currentOffset); + currentOffset += 2; + while (exceptionTableLength-- > 0) { + Label start = createLabel(readUnsignedShort(currentOffset), labels); + Label end = createLabel(readUnsignedShort(currentOffset + 2), labels); + Label handler = createLabel(readUnsignedShort(currentOffset + 4), labels); + String catchType = readUTF8(cpInfoOffsets[readUnsignedShort(currentOffset + 6)], charBuffer); + currentOffset += 8; + methodVisitor.visitTryCatchBlock(start, end, handler, catchType); + } + + // Read the Code attributes to create a label for each referenced instruction (the variables + // are ordered as in Section 4.7 of the JVMS). Attribute offsets exclude the + // attribute_name_index and attribute_length fields. + // - The offset of the current 'stack_map_frame' in the StackMap[Table] attribute, or 0. + // Initially, this is the offset of the first 'stack_map_frame' entry. Then this offset is + // updated after each stack_map_frame is read. + int stackMapFrameOffset = 0; + // - The end offset of the StackMap[Table] attribute, or 0. + int stackMapTableEndOffset = 0; + // - Whether the stack map frames are compressed (i.e. in a StackMapTable) or not. + boolean compressedFrames = true; + // - The offset of the LocalVariableTable attribute, or 0. + int localVariableTableOffset = 0; + // - The offset of the LocalVariableTypeTable attribute, or 0. + int localVariableTypeTableOffset = 0; + // - The offset of each 'type_annotation' entry in the RuntimeVisibleTypeAnnotations + // attribute, or null. + int[] visibleTypeAnnotationOffsets = null; + // - The offset of each 'type_annotation' entry in the RuntimeInvisibleTypeAnnotations + // attribute, or null. + int[] invisibleTypeAnnotationOffsets = null; + // - The non standard attributes (linked with their {@link Attribute#nextAttribute} field). + // This list in the reverse order or their order in the ClassFile structure. + Attribute attributes = null; + + int attributesCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (attributesCount-- > 0) { + // Read the attribute_info's attribute_name and attribute_length fields. + String attributeName = readUTF8(currentOffset, charBuffer); + int attributeLength = readInt(currentOffset + 2); + currentOffset += 6; + if (Constants.LOCAL_VARIABLE_TABLE.equals(attributeName)) { + if ((context.parsingOptions & SKIP_DEBUG) == 0) { + localVariableTableOffset = currentOffset; + // Parse the attribute to find the corresponding (debug only) labels. + int currentLocalVariableTableOffset = currentOffset; + int localVariableTableLength = readUnsignedShort(currentLocalVariableTableOffset); + currentLocalVariableTableOffset += 2; + while (localVariableTableLength-- > 0) { + int startPc = readUnsignedShort(currentLocalVariableTableOffset); + createDebugLabel(startPc, labels); + int length = readUnsignedShort(currentLocalVariableTableOffset + 2); + createDebugLabel(startPc + length, labels); + // Skip the name_index, descriptor_index and index fields (2 bytes each). + currentLocalVariableTableOffset += 10; + } + } + } else if (Constants.LOCAL_VARIABLE_TYPE_TABLE.equals(attributeName)) { + localVariableTypeTableOffset = currentOffset; + // Here we do not extract the labels corresponding to the attribute content. We assume they + // are the same or a subset of those of the LocalVariableTable attribute. + } else if (Constants.LINE_NUMBER_TABLE.equals(attributeName)) { + if ((context.parsingOptions & SKIP_DEBUG) == 0) { + // Parse the attribute to find the corresponding (debug only) labels. + int currentLineNumberTableOffset = currentOffset; + int lineNumberTableLength = readUnsignedShort(currentLineNumberTableOffset); + currentLineNumberTableOffset += 2; + while (lineNumberTableLength-- > 0) { + int startPc = readUnsignedShort(currentLineNumberTableOffset); + int lineNumber = readUnsignedShort(currentLineNumberTableOffset + 2); + currentLineNumberTableOffset += 4; + createDebugLabel(startPc, labels); + labels[startPc].addLineNumber(lineNumber); + } + } + } else if (Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { + visibleTypeAnnotationOffsets = + readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ true); + // Here we do not extract the labels corresponding to the attribute content. This would + // require a full parsing of the attribute, which would need to be repeated when parsing + // the bytecode instructions (see below). Instead, the content of the attribute is read one + // type annotation at a time (i.e. after a type annotation has been visited, the next type + // annotation is read), and the labels it contains are also extracted one annotation at a + // time. This assumes that type annotations are ordered by increasing bytecode offset. + } else if (Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS.equals(attributeName)) { + invisibleTypeAnnotationOffsets = + readTypeAnnotations(methodVisitor, context, currentOffset, /* visible = */ false); + // Same comment as above for the RuntimeVisibleTypeAnnotations attribute. + } else if (Constants.STACK_MAP_TABLE.equals(attributeName)) { + if ((context.parsingOptions & SKIP_FRAMES) == 0) { + stackMapFrameOffset = currentOffset + 2; + stackMapTableEndOffset = currentOffset + attributeLength; + } + // Here we do not extract the labels corresponding to the attribute content. This would + // require a full parsing of the attribute, which would need to be repeated when parsing + // the bytecode instructions (see below). Instead, the content of the attribute is read one + // frame at a time (i.e. after a frame has been visited, the next frame is read), and the + // labels it contains are also extracted one frame at a time. Thanks to the ordering of + // frames, having only a "one frame lookahead" is not a problem, i.e. it is not possible to + // see an offset smaller than the offset of the current instruction and for which no Label + // exist. Except for UNINITIALIZED type offsets. We solve this by parsing the stack map + // table without a full decoding (see below). + } else if ("StackMap".equals(attributeName)) { + if ((context.parsingOptions & SKIP_FRAMES) == 0) { + stackMapFrameOffset = currentOffset + 2; + stackMapTableEndOffset = currentOffset + attributeLength; + compressedFrames = false; + } + // IMPORTANT! Here we assume that the frames are ordered, as in the StackMapTable attribute, + // although this is not guaranteed by the attribute format. This allows an incremental + // extraction of the labels corresponding to this attribute (see the comment above for the + // StackMapTable attribute). + } else { + Attribute attribute = + readAttribute( + context.attributePrototypes, + attributeName, + currentOffset, + attributeLength, + charBuffer, + codeOffset, + labels); + attribute.nextAttribute = attributes; + attributes = attribute; + } + currentOffset += attributeLength; + } + + // Initialize the context fields related to stack map frames, and generate the first + // (implicit) stack map frame, if needed. + final boolean expandFrames = (context.parsingOptions & EXPAND_FRAMES) != 0; + if (stackMapFrameOffset != 0) { + // The bytecode offset of the first explicit frame is not offset_delta + 1 but only + // offset_delta. Setting the implicit frame offset to -1 allows us to use of the + // "offset_delta + 1" rule in all cases. + context.currentFrameOffset = -1; + context.currentFrameType = 0; + context.currentFrameLocalCount = 0; + context.currentFrameLocalCountDelta = 0; + context.currentFrameLocalTypes = new Object[maxLocals]; + context.currentFrameStackCount = 0; + context.currentFrameStackTypes = new Object[maxStack]; + if (expandFrames) { + computeImplicitFrame(context); + } + // Find the labels for UNINITIALIZED frame types. Instead of decoding each element of the + // stack map table, we look for 3 consecutive bytes that "look like" an UNINITIALIZED type + // (tag ITEM_Uninitialized, offset within bytecode bounds, NEW instruction at this offset). + // We may find false positives (i.e. not real UNINITIALIZED types), but this should be rare, + // and the only consequence will be the creation of an unneeded label. This is better than + // creating a label for each NEW instruction, and faster than fully decoding the whole stack + // map table. + for (int offset = stackMapFrameOffset; offset < stackMapTableEndOffset - 2; ++offset) { + if (classBuffer[offset] == Frame.ITEM_UNINITIALIZED) { + int potentialBytecodeOffset = readUnsignedShort(offset + 1); + if (potentialBytecodeOffset >= 0 + && potentialBytecodeOffset < codeLength + && (classBuffer[bytecodeStartOffset + potentialBytecodeOffset] & 0xFF) + == Opcodes.NEW) { + createLabel(potentialBytecodeOffset, labels); + } + } + } + } + if (expandFrames && (context.parsingOptions & EXPAND_ASM_INSNS) != 0) { + // Expanding the ASM specific instructions can introduce F_INSERT frames, even if the method + // does not currently have any frame. These inserted frames must be computed by simulating the + // effect of the bytecode instructions, one by one, starting from the implicit first frame. + // For this, MethodWriter needs to know maxLocals before the first instruction is visited. To + // ensure this, we visit the implicit first frame here (passing only maxLocals - the rest is + // computed in MethodWriter). + methodVisitor.visitFrame(Opcodes.F_NEW, maxLocals, null, 0, null); + } + + // Visit the bytecode instructions. First, introduce state variables for the incremental parsing + // of the type annotations. + + // Index of the next runtime visible type annotation to read (in the + // visibleTypeAnnotationOffsets array). + int currentVisibleTypeAnnotationIndex = 0; + // The bytecode offset of the next runtime visible type annotation to read, or -1. + int currentVisibleTypeAnnotationBytecodeOffset = + getTypeAnnotationBytecodeOffset(visibleTypeAnnotationOffsets, 0); + // Index of the next runtime invisible type annotation to read (in the + // invisibleTypeAnnotationOffsets array). + int currentInvisibleTypeAnnotationIndex = 0; + // The bytecode offset of the next runtime invisible type annotation to read, or -1. + int currentInvisibleTypeAnnotationBytecodeOffset = + getTypeAnnotationBytecodeOffset(invisibleTypeAnnotationOffsets, 0); + + // Whether a F_INSERT stack map frame must be inserted before the current instruction. + boolean insertFrame = false; + + // The delta to subtract from a goto_w or jsr_w opcode to get the corresponding goto or jsr + // opcode, or 0 if goto_w and jsr_w must be left unchanged (i.e. when expanding ASM specific + // instructions). + final int wideJumpOpcodeDelta = + (context.parsingOptions & EXPAND_ASM_INSNS) == 0 ? Constants.WIDE_JUMP_OPCODE_DELTA : 0; + + currentOffset = bytecodeStartOffset; + while (currentOffset < bytecodeEndOffset) { + final int currentBytecodeOffset = currentOffset - bytecodeStartOffset; + + // Visit the label and the line number(s) for this bytecode offset, if any. + Label currentLabel = labels[currentBytecodeOffset]; + if (currentLabel != null) { + currentLabel.accept(methodVisitor, (context.parsingOptions & SKIP_DEBUG) == 0); + } + + // Visit the stack map frame for this bytecode offset, if any. + while (stackMapFrameOffset != 0 + && (context.currentFrameOffset == currentBytecodeOffset + || context.currentFrameOffset == -1)) { + // If there is a stack map frame for this offset, make methodVisitor visit it, and read the + // next stack map frame if there is one. + if (context.currentFrameOffset != -1) { + if (!compressedFrames || expandFrames) { + methodVisitor.visitFrame( + Opcodes.F_NEW, + context.currentFrameLocalCount, + context.currentFrameLocalTypes, + context.currentFrameStackCount, + context.currentFrameStackTypes); + } else { + methodVisitor.visitFrame( + context.currentFrameType, + context.currentFrameLocalCountDelta, + context.currentFrameLocalTypes, + context.currentFrameStackCount, + context.currentFrameStackTypes); + } + // Since there is already a stack map frame for this bytecode offset, there is no need to + // insert a new one. + insertFrame = false; + } + if (stackMapFrameOffset < stackMapTableEndOffset) { + stackMapFrameOffset = + readStackMapFrame(stackMapFrameOffset, compressedFrames, expandFrames, context); + } else { + stackMapFrameOffset = 0; + } + } + + // Insert a stack map frame for this bytecode offset, if requested by setting insertFrame to + // true during the previous iteration. The actual frame content is computed in MethodWriter. + if (insertFrame) { + if ((context.parsingOptions & EXPAND_FRAMES) != 0) { + methodVisitor.visitFrame(Constants.F_INSERT, 0, null, 0, null); + } + insertFrame = false; + } + + // Visit the instruction at this bytecode offset. + int opcode = classBuffer[currentOffset] & 0xFF; + switch (opcode) { + case Opcodes.NOP: + case Opcodes.ACONST_NULL: + case Opcodes.ICONST_M1: + case Opcodes.ICONST_0: + case Opcodes.ICONST_1: + case Opcodes.ICONST_2: + case Opcodes.ICONST_3: + case Opcodes.ICONST_4: + case Opcodes.ICONST_5: + case Opcodes.LCONST_0: + case Opcodes.LCONST_1: + case Opcodes.FCONST_0: + case Opcodes.FCONST_1: + case Opcodes.FCONST_2: + case Opcodes.DCONST_0: + case Opcodes.DCONST_1: + case Opcodes.IALOAD: + case Opcodes.LALOAD: + case Opcodes.FALOAD: + case Opcodes.DALOAD: + case Opcodes.AALOAD: + case Opcodes.BALOAD: + case Opcodes.CALOAD: + case Opcodes.SALOAD: + case Opcodes.IASTORE: + case Opcodes.LASTORE: + case Opcodes.FASTORE: + case Opcodes.DASTORE: + case Opcodes.AASTORE: + case Opcodes.BASTORE: + case Opcodes.CASTORE: + case Opcodes.SASTORE: + case Opcodes.POP: + case Opcodes.POP2: + case Opcodes.DUP: + case Opcodes.DUP_X1: + case Opcodes.DUP_X2: + case Opcodes.DUP2: + case Opcodes.DUP2_X1: + case Opcodes.DUP2_X2: + case Opcodes.SWAP: + case Opcodes.IADD: + case Opcodes.LADD: + case Opcodes.FADD: + case Opcodes.DADD: + case Opcodes.ISUB: + case Opcodes.LSUB: + case Opcodes.FSUB: + case Opcodes.DSUB: + case Opcodes.IMUL: + case Opcodes.LMUL: + case Opcodes.FMUL: + case Opcodes.DMUL: + case Opcodes.IDIV: + case Opcodes.LDIV: + case Opcodes.FDIV: + case Opcodes.DDIV: + case Opcodes.IREM: + case Opcodes.LREM: + case Opcodes.FREM: + case Opcodes.DREM: + case Opcodes.INEG: + case Opcodes.LNEG: + case Opcodes.FNEG: + case Opcodes.DNEG: + case Opcodes.ISHL: + case Opcodes.LSHL: + case Opcodes.ISHR: + case Opcodes.LSHR: + case Opcodes.IUSHR: + case Opcodes.LUSHR: + case Opcodes.IAND: + case Opcodes.LAND: + case Opcodes.IOR: + case Opcodes.LOR: + case Opcodes.IXOR: + case Opcodes.LXOR: + case Opcodes.I2L: + case Opcodes.I2F: + case Opcodes.I2D: + case Opcodes.L2I: + case Opcodes.L2F: + case Opcodes.L2D: + case Opcodes.F2I: + case Opcodes.F2L: + case Opcodes.F2D: + case Opcodes.D2I: + case Opcodes.D2L: + case Opcodes.D2F: + case Opcodes.I2B: + case Opcodes.I2C: + case Opcodes.I2S: + case Opcodes.LCMP: + case Opcodes.FCMPL: + case Opcodes.FCMPG: + case Opcodes.DCMPL: + case Opcodes.DCMPG: + case Opcodes.IRETURN: + case Opcodes.LRETURN: + case Opcodes.FRETURN: + case Opcodes.DRETURN: + case Opcodes.ARETURN: + case Opcodes.RETURN: + case Opcodes.ARRAYLENGTH: + case Opcodes.ATHROW: + case Opcodes.MONITORENTER: + case Opcodes.MONITOREXIT: + methodVisitor.visitInsn(opcode); + currentOffset += 1; + break; + case Constants.ILOAD_0: + case Constants.ILOAD_1: + case Constants.ILOAD_2: + case Constants.ILOAD_3: + case Constants.LLOAD_0: + case Constants.LLOAD_1: + case Constants.LLOAD_2: + case Constants.LLOAD_3: + case Constants.FLOAD_0: + case Constants.FLOAD_1: + case Constants.FLOAD_2: + case Constants.FLOAD_3: + case Constants.DLOAD_0: + case Constants.DLOAD_1: + case Constants.DLOAD_2: + case Constants.DLOAD_3: + case Constants.ALOAD_0: + case Constants.ALOAD_1: + case Constants.ALOAD_2: + case Constants.ALOAD_3: + opcode -= Constants.ILOAD_0; + methodVisitor.visitVarInsn(Opcodes.ILOAD + (opcode >> 2), opcode & 0x3); + currentOffset += 1; + break; + case Constants.ISTORE_0: + case Constants.ISTORE_1: + case Constants.ISTORE_2: + case Constants.ISTORE_3: + case Constants.LSTORE_0: + case Constants.LSTORE_1: + case Constants.LSTORE_2: + case Constants.LSTORE_3: + case Constants.FSTORE_0: + case Constants.FSTORE_1: + case Constants.FSTORE_2: + case Constants.FSTORE_3: + case Constants.DSTORE_0: + case Constants.DSTORE_1: + case Constants.DSTORE_2: + case Constants.DSTORE_3: + case Constants.ASTORE_0: + case Constants.ASTORE_1: + case Constants.ASTORE_2: + case Constants.ASTORE_3: + opcode -= Constants.ISTORE_0; + methodVisitor.visitVarInsn(Opcodes.ISTORE + (opcode >> 2), opcode & 0x3); + currentOffset += 1; + break; + case Opcodes.IFEQ: + case Opcodes.IFNE: + case Opcodes.IFLT: + case Opcodes.IFGE: + case Opcodes.IFGT: + case Opcodes.IFLE: + case Opcodes.IF_ICMPEQ: + case Opcodes.IF_ICMPNE: + case Opcodes.IF_ICMPLT: + case Opcodes.IF_ICMPGE: + case Opcodes.IF_ICMPGT: + case Opcodes.IF_ICMPLE: + case Opcodes.IF_ACMPEQ: + case Opcodes.IF_ACMPNE: + case Opcodes.GOTO: + case Opcodes.JSR: + case Opcodes.IFNULL: + case Opcodes.IFNONNULL: + methodVisitor.visitJumpInsn( + opcode, labels[currentBytecodeOffset + readShort(currentOffset + 1)]); + currentOffset += 3; + break; + case Constants.GOTO_W: + case Constants.JSR_W: + methodVisitor.visitJumpInsn( + opcode - wideJumpOpcodeDelta, + labels[currentBytecodeOffset + readInt(currentOffset + 1)]); + currentOffset += 5; + break; + case Constants.ASM_IFEQ: + case Constants.ASM_IFNE: + case Constants.ASM_IFLT: + case Constants.ASM_IFGE: + case Constants.ASM_IFGT: + case Constants.ASM_IFLE: + case Constants.ASM_IF_ICMPEQ: + case Constants.ASM_IF_ICMPNE: + case Constants.ASM_IF_ICMPLT: + case Constants.ASM_IF_ICMPGE: + case Constants.ASM_IF_ICMPGT: + case Constants.ASM_IF_ICMPLE: + case Constants.ASM_IF_ACMPEQ: + case Constants.ASM_IF_ACMPNE: + case Constants.ASM_GOTO: + case Constants.ASM_JSR: + case Constants.ASM_IFNULL: + case Constants.ASM_IFNONNULL: + { + // A forward jump with an offset > 32767. In this case we automatically replace ASM_GOTO + // with GOTO_W, ASM_JSR with JSR_W and ASM_IFxxx with IFNOTxxx GOTO_W L:..., + // where IFNOTxxx is the "opposite" opcode of ASMS_IFxxx (e.g. IFNE for ASM_IFEQ) and + // where designates the instruction just after the GOTO_W. + // First, change the ASM specific opcodes ASM_IFEQ ... ASM_JSR, ASM_IFNULL and + // ASM_IFNONNULL to IFEQ ... JSR, IFNULL and IFNONNULL. + opcode = + opcode < Constants.ASM_IFNULL + ? opcode - Constants.ASM_OPCODE_DELTA + : opcode - Constants.ASM_IFNULL_OPCODE_DELTA; + Label target = labels[currentBytecodeOffset + readUnsignedShort(currentOffset + 1)]; + if (opcode == Opcodes.GOTO || opcode == Opcodes.JSR) { + // Replace GOTO with GOTO_W and JSR with JSR_W. + methodVisitor.visitJumpInsn(opcode + Constants.WIDE_JUMP_OPCODE_DELTA, target); + } else { + // Compute the "opposite" of opcode. This can be done by flipping the least + // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ + // (with a pre and post offset by 1). + opcode = opcode < Opcodes.GOTO ? ((opcode + 1) ^ 1) - 1 : opcode ^ 1; + Label endif = createLabel(currentBytecodeOffset + 3, labels); + methodVisitor.visitJumpInsn(opcode, endif); + methodVisitor.visitJumpInsn(Constants.GOTO_W, target); + // endif designates the instruction just after GOTO_W, and is visited as part of the + // next instruction. Since it is a jump target, we need to insert a frame here. + insertFrame = true; + } + currentOffset += 3; + break; + } + case Constants.ASM_GOTO_W: + // Replace ASM_GOTO_W with GOTO_W. + methodVisitor.visitJumpInsn( + Constants.GOTO_W, labels[currentBytecodeOffset + readInt(currentOffset + 1)]); + // The instruction just after is a jump target (because ASM_GOTO_W is used in patterns + // IFNOTxxx ASM_GOTO_W L:..., see MethodWriter), so we need to insert a frame + // here. + insertFrame = true; + currentOffset += 5; + break; + case Constants.WIDE: + opcode = classBuffer[currentOffset + 1] & 0xFF; + if (opcode == Opcodes.IINC) { + methodVisitor.visitIincInsn( + readUnsignedShort(currentOffset + 2), readShort(currentOffset + 4)); + currentOffset += 6; + } else { + methodVisitor.visitVarInsn(opcode, readUnsignedShort(currentOffset + 2)); + currentOffset += 4; + } + break; + case Opcodes.TABLESWITCH: + { + // Skip 0 to 3 padding bytes. + currentOffset += 4 - (currentBytecodeOffset & 3); + // Read the instruction. + Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)]; + int low = readInt(currentOffset + 4); + int high = readInt(currentOffset + 8); + currentOffset += 12; + Label[] table = new Label[high - low + 1]; + for (int i = 0; i < table.length; ++i) { + table[i] = labels[currentBytecodeOffset + readInt(currentOffset)]; + currentOffset += 4; + } + methodVisitor.visitTableSwitchInsn(low, high, defaultLabel, table); + break; + } + case Opcodes.LOOKUPSWITCH: + { + // Skip 0 to 3 padding bytes. + currentOffset += 4 - (currentBytecodeOffset & 3); + // Read the instruction. + Label defaultLabel = labels[currentBytecodeOffset + readInt(currentOffset)]; + int numPairs = readInt(currentOffset + 4); + currentOffset += 8; + int[] keys = new int[numPairs]; + Label[] values = new Label[numPairs]; + for (int i = 0; i < numPairs; ++i) { + keys[i] = readInt(currentOffset); + values[i] = labels[currentBytecodeOffset + readInt(currentOffset + 4)]; + currentOffset += 8; + } + methodVisitor.visitLookupSwitchInsn(defaultLabel, keys, values); + break; + } + case Opcodes.ILOAD: + case Opcodes.LLOAD: + case Opcodes.FLOAD: + case Opcodes.DLOAD: + case Opcodes.ALOAD: + case Opcodes.ISTORE: + case Opcodes.LSTORE: + case Opcodes.FSTORE: + case Opcodes.DSTORE: + case Opcodes.ASTORE: + case Opcodes.RET: + methodVisitor.visitVarInsn(opcode, classBuffer[currentOffset + 1] & 0xFF); + currentOffset += 2; + break; + case Opcodes.BIPUSH: + case Opcodes.NEWARRAY: + methodVisitor.visitIntInsn(opcode, classBuffer[currentOffset + 1]); + currentOffset += 2; + break; + case Opcodes.SIPUSH: + methodVisitor.visitIntInsn(opcode, readShort(currentOffset + 1)); + currentOffset += 3; + break; + case Opcodes.LDC: + methodVisitor.visitLdcInsn(readConst(classBuffer[currentOffset + 1] & 0xFF, charBuffer)); + currentOffset += 2; + break; + case Constants.LDC_W: + case Constants.LDC2_W: + methodVisitor.visitLdcInsn(readConst(readUnsignedShort(currentOffset + 1), charBuffer)); + currentOffset += 3; + break; + case Opcodes.GETSTATIC: + case Opcodes.PUTSTATIC: + case Opcodes.GETFIELD: + case Opcodes.PUTFIELD: + case Opcodes.INVOKEVIRTUAL: + case Opcodes.INVOKESPECIAL: + case Opcodes.INVOKESTATIC: + case Opcodes.INVOKEINTERFACE: + { + int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)]; + int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; + String owner = readClass(cpInfoOffset, charBuffer); + String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); + String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); + if (opcode < Opcodes.INVOKEVIRTUAL) { + methodVisitor.visitFieldInsn(opcode, owner, name, descriptor); + } else { + boolean isInterface = + classBuffer[cpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG; + methodVisitor.visitMethodInsn(opcode, owner, name, descriptor, isInterface); + } + if (opcode == Opcodes.INVOKEINTERFACE) { + currentOffset += 5; + } else { + currentOffset += 3; + } + break; + } + case Opcodes.INVOKEDYNAMIC: + { + int cpInfoOffset = cpInfoOffsets[readUnsignedShort(currentOffset + 1)]; + int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; + String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); + String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); + int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)]; + Handle handle = + (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); + Object[] bootstrapMethodArguments = + new Object[readUnsignedShort(bootstrapMethodOffset + 2)]; + bootstrapMethodOffset += 4; + for (int i = 0; i < bootstrapMethodArguments.length; i++) { + bootstrapMethodArguments[i] = + readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); + bootstrapMethodOffset += 2; + } + methodVisitor.visitInvokeDynamicInsn( + name, descriptor, handle, bootstrapMethodArguments); + currentOffset += 5; + break; + } + case Opcodes.NEW: + case Opcodes.ANEWARRAY: + case Opcodes.CHECKCAST: + case Opcodes.INSTANCEOF: + methodVisitor.visitTypeInsn(opcode, readClass(currentOffset + 1, charBuffer)); + currentOffset += 3; + break; + case Opcodes.IINC: + methodVisitor.visitIincInsn( + classBuffer[currentOffset + 1] & 0xFF, classBuffer[currentOffset + 2]); + currentOffset += 3; + break; + case Opcodes.MULTIANEWARRAY: + methodVisitor.visitMultiANewArrayInsn( + readClass(currentOffset + 1, charBuffer), classBuffer[currentOffset + 3] & 0xFF); + currentOffset += 4; + break; + default: + throw new AssertionError(); + } + + // Visit the runtime visible instruction annotations, if any. + while (visibleTypeAnnotationOffsets != null + && currentVisibleTypeAnnotationIndex < visibleTypeAnnotationOffsets.length + && currentVisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) { + if (currentVisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) { + // Parse the target_type, target_info and target_path fields. + int currentAnnotationOffset = + readTypeAnnotationTarget( + context, visibleTypeAnnotationOffsets[currentVisibleTypeAnnotationIndex]); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + readElementValues( + methodVisitor.visitInsnAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + annotationDescriptor, + /* visible = */ true), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + currentVisibleTypeAnnotationBytecodeOffset = + getTypeAnnotationBytecodeOffset( + visibleTypeAnnotationOffsets, ++currentVisibleTypeAnnotationIndex); + } + + // Visit the runtime invisible instruction annotations, if any. + while (invisibleTypeAnnotationOffsets != null + && currentInvisibleTypeAnnotationIndex < invisibleTypeAnnotationOffsets.length + && currentInvisibleTypeAnnotationBytecodeOffset <= currentBytecodeOffset) { + if (currentInvisibleTypeAnnotationBytecodeOffset == currentBytecodeOffset) { + // Parse the target_type, target_info and target_path fields. + int currentAnnotationOffset = + readTypeAnnotationTarget( + context, invisibleTypeAnnotationOffsets[currentInvisibleTypeAnnotationIndex]); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentAnnotationOffset, charBuffer); + currentAnnotationOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + readElementValues( + methodVisitor.visitInsnAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + annotationDescriptor, + /* visible = */ false), + currentAnnotationOffset, + /* named = */ true, + charBuffer); + } + currentInvisibleTypeAnnotationBytecodeOffset = + getTypeAnnotationBytecodeOffset( + invisibleTypeAnnotationOffsets, ++currentInvisibleTypeAnnotationIndex); + } + } + if (labels[codeLength] != null) { + methodVisitor.visitLabel(labels[codeLength]); + } + + // Visit LocalVariableTable and LocalVariableTypeTable attributes. + if (localVariableTableOffset != 0 && (context.parsingOptions & SKIP_DEBUG) == 0) { + // The (start_pc, index, signature_index) fields of each entry of the LocalVariableTypeTable. + int[] typeTable = null; + if (localVariableTypeTableOffset != 0) { + typeTable = new int[readUnsignedShort(localVariableTypeTableOffset) * 3]; + currentOffset = localVariableTypeTableOffset + 2; + int typeTableIndex = typeTable.length; + while (typeTableIndex > 0) { + // Store the offset of 'signature_index', and the value of 'index' and 'start_pc'. + typeTable[--typeTableIndex] = currentOffset + 6; + typeTable[--typeTableIndex] = readUnsignedShort(currentOffset + 8); + typeTable[--typeTableIndex] = readUnsignedShort(currentOffset); + currentOffset += 10; + } + } + int localVariableTableLength = readUnsignedShort(localVariableTableOffset); + currentOffset = localVariableTableOffset + 2; + while (localVariableTableLength-- > 0) { + int startPc = readUnsignedShort(currentOffset); + int length = readUnsignedShort(currentOffset + 2); + String name = readUTF8(currentOffset + 4, charBuffer); + String descriptor = readUTF8(currentOffset + 6, charBuffer); + int index = readUnsignedShort(currentOffset + 8); + currentOffset += 10; + String signature = null; + if (typeTable != null) { + for (int i = 0; i < typeTable.length; i += 3) { + if (typeTable[i] == startPc && typeTable[i + 1] == index) { + signature = readUTF8(typeTable[i + 2], charBuffer); + break; + } + } + } + methodVisitor.visitLocalVariable( + name, descriptor, signature, labels[startPc], labels[startPc + length], index); + } + } + + // Visit the local variable type annotations of the RuntimeVisibleTypeAnnotations attribute. + if (visibleTypeAnnotationOffsets != null) { + for (int typeAnnotationOffset : visibleTypeAnnotationOffsets) { + int targetType = readByte(typeAnnotationOffset); + if (targetType == TypeReference.LOCAL_VARIABLE + || targetType == TypeReference.RESOURCE_VARIABLE) { + // Parse the target_type, target_info and target_path fields. + currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentOffset, charBuffer); + currentOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + readElementValues( + methodVisitor.visitLocalVariableAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + context.currentLocalVariableAnnotationRangeStarts, + context.currentLocalVariableAnnotationRangeEnds, + context.currentLocalVariableAnnotationRangeIndices, + annotationDescriptor, + /* visible = */ true), + currentOffset, + /* named = */ true, + charBuffer); + } + } + } + + // Visit the local variable type annotations of the RuntimeInvisibleTypeAnnotations attribute. + if (invisibleTypeAnnotationOffsets != null) { + for (int typeAnnotationOffset : invisibleTypeAnnotationOffsets) { + int targetType = readByte(typeAnnotationOffset); + if (targetType == TypeReference.LOCAL_VARIABLE + || targetType == TypeReference.RESOURCE_VARIABLE) { + // Parse the target_type, target_info and target_path fields. + currentOffset = readTypeAnnotationTarget(context, typeAnnotationOffset); + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentOffset, charBuffer); + currentOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + readElementValues( + methodVisitor.visitLocalVariableAnnotation( + context.currentTypeAnnotationTarget, + context.currentTypeAnnotationTargetPath, + context.currentLocalVariableAnnotationRangeStarts, + context.currentLocalVariableAnnotationRangeEnds, + context.currentLocalVariableAnnotationRangeIndices, + annotationDescriptor, + /* visible = */ false), + currentOffset, + /* named = */ true, + charBuffer); + } + } + } + + // Visit the non standard attributes. + while (attributes != null) { + // Copy and reset the nextAttribute field so that it can also be used in MethodWriter. + Attribute nextAttribute = attributes.nextAttribute; + attributes.nextAttribute = null; + methodVisitor.visitAttribute(attributes); + attributes = nextAttribute; + } + + // Visit the max stack and max locals values. + methodVisitor.visitMaxs(maxStack, maxLocals); + } + + /** + * Returns the label corresponding to the given bytecode offset. The default implementation of + * this method creates a label for the given offset if it has not been already created. + * + * @param bytecodeOffset a bytecode offset in a method. + * @param labels the already created labels, indexed by their offset. If a label already exists + * for bytecodeOffset this method must not create a new one. Otherwise it must store the new + * label in this array. + * @return a non null Label, which must be equal to labels[bytecodeOffset]. + */ + protected Label readLabel(final int bytecodeOffset, final Label[] labels) { + if (labels[bytecodeOffset] == null) { + labels[bytecodeOffset] = new Label(); + } + return labels[bytecodeOffset]; + } + + /** + * Creates a label without the {@link Label#FLAG_DEBUG_ONLY} flag set, for the given bytecode + * offset. The label is created with a call to {@link #readLabel} and its {@link + * Label#FLAG_DEBUG_ONLY} flag is cleared. + * + * @param bytecodeOffset a bytecode offset in a method. + * @param labels the already created labels, indexed by their offset. + * @return a Label without the {@link Label#FLAG_DEBUG_ONLY} flag set. + */ + private Label createLabel(final int bytecodeOffset, final Label[] labels) { + Label label = readLabel(bytecodeOffset, labels); + label.flags &= ~Label.FLAG_DEBUG_ONLY; + return label; + } + + /** + * Creates a label with the {@link Label#FLAG_DEBUG_ONLY} flag set, if there is no already + * existing label for the given bytecode offset (otherwise does nothing). The label is created + * with a call to {@link #readLabel}. + * + * @param bytecodeOffset a bytecode offset in a method. + * @param labels the already created labels, indexed by their offset. + */ + private void createDebugLabel(final int bytecodeOffset, final Label[] labels) { + if (labels[bytecodeOffset] == null) { + readLabel(bytecodeOffset, labels).flags |= Label.FLAG_DEBUG_ONLY; + } + } + + // ---------------------------------------------------------------------------------------------- + // Methods to parse annotations, type annotations and parameter annotations + // ---------------------------------------------------------------------------------------------- + + /** + * Parses a Runtime[In]VisibleTypeAnnotations attribute to find the offset of each type_annotation + * entry it contains, to find the corresponding labels, and to visit the try catch block + * annotations. + * + * @param methodVisitor the method visitor to be used to visit the try catch block annotations. + * @param context information about the class being parsed. + * @param runtimeTypeAnnotationsOffset the start offset of a Runtime[In]VisibleTypeAnnotations + * attribute, excluding the attribute_info's attribute_name_index and attribute_length fields. + * @param visible true if the attribute to parse is a RuntimeVisibleTypeAnnotations attribute, + * false it is a RuntimeInvisibleTypeAnnotations attribute. + * @return the start offset of each entry of the Runtime[In]VisibleTypeAnnotations_attribute's + * 'annotations' array field. + */ + private int[] readTypeAnnotations( + final MethodVisitor methodVisitor, + final Context context, + final int runtimeTypeAnnotationsOffset, + final boolean visible) { + char[] charBuffer = context.charBuffer; + int currentOffset = runtimeTypeAnnotationsOffset; + // Read the num_annotations field and create an array to store the type_annotation offsets. + int[] typeAnnotationsOffsets = new int[readUnsignedShort(currentOffset)]; + currentOffset += 2; + // Parse the 'annotations' array field. + for (int i = 0; i < typeAnnotationsOffsets.length; ++i) { + typeAnnotationsOffsets[i] = currentOffset; + // Parse the type_annotation's target_type and the target_info fields. The size of the + // target_info field depends on the value of target_type. + int targetType = readInt(currentOffset); + switch (targetType >>> 24) { + case TypeReference.LOCAL_VARIABLE: + case TypeReference.RESOURCE_VARIABLE: + // A localvar_target has a variable size, which depends on the value of their table_length + // field. It also references bytecode offsets, for which we need labels. + int tableLength = readUnsignedShort(currentOffset + 1); + currentOffset += 3; + while (tableLength-- > 0) { + int startPc = readUnsignedShort(currentOffset); + int length = readUnsignedShort(currentOffset + 2); + // Skip the index field (2 bytes). + currentOffset += 6; + createLabel(startPc, context.currentMethodLabels); + createLabel(startPc + length, context.currentMethodLabels); + } + break; + case TypeReference.CAST: + case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: + case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: + case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: + case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: + currentOffset += 4; + break; + case TypeReference.CLASS_EXTENDS: + case TypeReference.CLASS_TYPE_PARAMETER_BOUND: + case TypeReference.METHOD_TYPE_PARAMETER_BOUND: + case TypeReference.THROWS: + case TypeReference.EXCEPTION_PARAMETER: + case TypeReference.INSTANCEOF: + case TypeReference.NEW: + case TypeReference.CONSTRUCTOR_REFERENCE: + case TypeReference.METHOD_REFERENCE: + currentOffset += 3; + break; + case TypeReference.CLASS_TYPE_PARAMETER: + case TypeReference.METHOD_TYPE_PARAMETER: + case TypeReference.METHOD_FORMAL_PARAMETER: + case TypeReference.FIELD: + case TypeReference.METHOD_RETURN: + case TypeReference.METHOD_RECEIVER: + default: + // TypeReference type which can't be used in Code attribute, or which is unknown. + throw new IllegalArgumentException(); + } + // Parse the rest of the type_annotation structure, starting with the target_path structure + // (whose size depends on its path_length field). + int pathLength = readByte(currentOffset); + if ((targetType >>> 24) == TypeReference.EXCEPTION_PARAMETER) { + // Parse the target_path structure and create a corresponding TypePath. + TypePath path = pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset); + currentOffset += 1 + 2 * pathLength; + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentOffset, charBuffer); + currentOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentOffset = + readElementValues( + methodVisitor.visitTryCatchAnnotation( + targetType & 0xFFFFFF00, path, annotationDescriptor, visible), + currentOffset, + /* named = */ true, + charBuffer); + } else { + // We don't want to visit the other target_type annotations, so we just skip them (which + // requires some parsing because the element_value_pairs array has a variable size). First, + // skip the target_path structure: + currentOffset += 3 + 2 * pathLength; + // Then skip the num_element_value_pairs and element_value_pairs fields (by reading them + // with a null AnnotationVisitor). + currentOffset = + readElementValues( + /* annotationVisitor = */ null, currentOffset, /* named = */ true, charBuffer); + } + } + return typeAnnotationsOffsets; + } + + /** + * Returns the bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or + * -1 if there is no such type_annotation of if it does not have a bytecode offset. + * + * @param typeAnnotationOffsets the offset of each 'type_annotation' entry in a + * Runtime[In]VisibleTypeAnnotations attribute, or null. + * @param typeAnnotationIndex the index a 'type_annotation' entry in typeAnnotationOffsets. + * @return bytecode offset corresponding to the specified JVMS 'type_annotation' structure, or -1 + * if there is no such type_annotation of if it does not have a bytecode offset. + */ + private int getTypeAnnotationBytecodeOffset( + final int[] typeAnnotationOffsets, final int typeAnnotationIndex) { + if (typeAnnotationOffsets == null + || typeAnnotationIndex >= typeAnnotationOffsets.length + || readByte(typeAnnotationOffsets[typeAnnotationIndex]) < TypeReference.INSTANCEOF) { + return -1; + } + return readUnsignedShort(typeAnnotationOffsets[typeAnnotationIndex] + 1); + } + + /** + * Parses the header of a JVMS type_annotation structure to extract its target_type, target_info + * and target_path (the result is stored in the given context), and returns the start offset of + * the rest of the type_annotation structure. + * + * @param context information about the class being parsed. This is where the extracted + * target_type and target_path must be stored. + * @param typeAnnotationOffset the start offset of a type_annotation structure. + * @return the start offset of the rest of the type_annotation structure. + */ + private int readTypeAnnotationTarget(final Context context, final int typeAnnotationOffset) { + int currentOffset = typeAnnotationOffset; + // Parse and store the target_type structure. + int targetType = readInt(typeAnnotationOffset); + switch (targetType >>> 24) { + case TypeReference.CLASS_TYPE_PARAMETER: + case TypeReference.METHOD_TYPE_PARAMETER: + case TypeReference.METHOD_FORMAL_PARAMETER: + targetType &= 0xFFFF0000; + currentOffset += 2; + break; + case TypeReference.FIELD: + case TypeReference.METHOD_RETURN: + case TypeReference.METHOD_RECEIVER: + targetType &= 0xFF000000; + currentOffset += 1; + break; + case TypeReference.LOCAL_VARIABLE: + case TypeReference.RESOURCE_VARIABLE: + targetType &= 0xFF000000; + int tableLength = readUnsignedShort(currentOffset + 1); + currentOffset += 3; + context.currentLocalVariableAnnotationRangeStarts = new Label[tableLength]; + context.currentLocalVariableAnnotationRangeEnds = new Label[tableLength]; + context.currentLocalVariableAnnotationRangeIndices = new int[tableLength]; + for (int i = 0; i < tableLength; ++i) { + int startPc = readUnsignedShort(currentOffset); + int length = readUnsignedShort(currentOffset + 2); + int index = readUnsignedShort(currentOffset + 4); + currentOffset += 6; + context.currentLocalVariableAnnotationRangeStarts[i] = + createLabel(startPc, context.currentMethodLabels); + context.currentLocalVariableAnnotationRangeEnds[i] = + createLabel(startPc + length, context.currentMethodLabels); + context.currentLocalVariableAnnotationRangeIndices[i] = index; + } + break; + case TypeReference.CAST: + case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: + case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: + case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: + case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: + targetType &= 0xFF0000FF; + currentOffset += 4; + break; + case TypeReference.CLASS_EXTENDS: + case TypeReference.CLASS_TYPE_PARAMETER_BOUND: + case TypeReference.METHOD_TYPE_PARAMETER_BOUND: + case TypeReference.THROWS: + case TypeReference.EXCEPTION_PARAMETER: + targetType &= 0xFFFFFF00; + currentOffset += 3; + break; + case TypeReference.INSTANCEOF: + case TypeReference.NEW: + case TypeReference.CONSTRUCTOR_REFERENCE: + case TypeReference.METHOD_REFERENCE: + targetType &= 0xFF000000; + currentOffset += 3; + break; + default: + throw new IllegalArgumentException(); + } + context.currentTypeAnnotationTarget = targetType; + // Parse and store the target_path structure. + int pathLength = readByte(currentOffset); + context.currentTypeAnnotationTargetPath = + pathLength == 0 ? null : new TypePath(classFileBuffer, currentOffset); + // Return the start offset of the rest of the type_annotation structure. + return currentOffset + 1 + 2 * pathLength; + } + + /** + * Reads a Runtime[In]VisibleParameterAnnotations attribute and makes the given visitor visit it. + * + * @param methodVisitor the visitor that must visit the parameter annotations. + * @param context information about the class being parsed. + * @param runtimeParameterAnnotationsOffset the start offset of a + * Runtime[In]VisibleParameterAnnotations attribute, excluding the attribute_info's + * attribute_name_index and attribute_length fields. + * @param visible true if the attribute to parse is a RuntimeVisibleParameterAnnotations + * attribute, false it is a RuntimeInvisibleParameterAnnotations attribute. + */ + private void readParameterAnnotations( + final MethodVisitor methodVisitor, + final Context context, + final int runtimeParameterAnnotationsOffset, + final boolean visible) { + int currentOffset = runtimeParameterAnnotationsOffset; + int numParameters = classFileBuffer[currentOffset++] & 0xFF; + methodVisitor.visitAnnotableParameterCount(numParameters, visible); + char[] charBuffer = context.charBuffer; + for (int i = 0; i < numParameters; ++i) { + int numAnnotations = readUnsignedShort(currentOffset); + currentOffset += 2; + while (numAnnotations-- > 0) { + // Parse the type_index field. + String annotationDescriptor = readUTF8(currentOffset, charBuffer); + currentOffset += 2; + // Parse num_element_value_pairs and element_value_pairs and visit these values. + currentOffset = + readElementValues( + methodVisitor.visitParameterAnnotation(i, annotationDescriptor, visible), + currentOffset, + /* named = */ true, + charBuffer); + } + } + } + + /** + * Reads the element values of a JVMS 'annotation' structure and makes the given visitor visit + * them. This method can also be used to read the values of the JVMS 'array_value' field of an + * annotation's 'element_value'. + * + * @param annotationVisitor the visitor that must visit the values. + * @param annotationOffset the start offset of an 'annotation' structure (excluding its type_index + * field) or of an 'array_value' structure. + * @param named if the annotation values are named or not. This should be true to parse the values + * of a JVMS 'annotation' structure, and false to parse the JVMS 'array_value' of an + * annotation's element_value. + * @param charBuffer the buffer used to read strings in the constant pool. + * @return the end offset of the JVMS 'annotation' or 'array_value' structure. + */ + private int readElementValues( + final AnnotationVisitor annotationVisitor, + final int annotationOffset, + final boolean named, + final char[] charBuffer) { + int currentOffset = annotationOffset; + // Read the num_element_value_pairs field (or num_values field for an array_value). + int numElementValuePairs = readUnsignedShort(currentOffset); + currentOffset += 2; + if (named) { + // Parse the element_value_pairs array. + while (numElementValuePairs-- > 0) { + String elementName = readUTF8(currentOffset, charBuffer); + currentOffset = + readElementValue(annotationVisitor, currentOffset + 2, elementName, charBuffer); + } + } else { + // Parse the array_value array. + while (numElementValuePairs-- > 0) { + currentOffset = + readElementValue(annotationVisitor, currentOffset, /* named = */ null, charBuffer); + } + } + if (annotationVisitor != null) { + annotationVisitor.visitEnd(); + } + return currentOffset; + } + + /** + * Reads a JVMS 'element_value' structure and makes the given visitor visit it. + * + * @param annotationVisitor the visitor that must visit the element_value structure. + * @param elementValueOffset the start offset in {@link #classFileBuffer} of the element_value + * structure to be read. + * @param elementName the name of the element_value structure to be read, or {@literal null}. + * @param charBuffer the buffer used to read strings in the constant pool. + * @return the end offset of the JVMS 'element_value' structure. + */ + private int readElementValue( + final AnnotationVisitor annotationVisitor, + final int elementValueOffset, + final String elementName, + final char[] charBuffer) { + int currentOffset = elementValueOffset; + if (annotationVisitor == null) { + switch (classFileBuffer[currentOffset] & 0xFF) { + case 'e': // enum_const_value + return currentOffset + 5; + case '@': // annotation_value + return readElementValues(null, currentOffset + 3, /* named = */ true, charBuffer); + case '[': // array_value + return readElementValues(null, currentOffset + 1, /* named = */ false, charBuffer); + default: + return currentOffset + 3; + } + } + switch (classFileBuffer[currentOffset++] & 0xFF) { + case 'B': // const_value_index, CONSTANT_Integer + annotationVisitor.visit( + elementName, (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); + currentOffset += 2; + break; + case 'C': // const_value_index, CONSTANT_Integer + annotationVisitor.visit( + elementName, (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); + currentOffset += 2; + break; + case 'D': // const_value_index, CONSTANT_Double + case 'F': // const_value_index, CONSTANT_Float + case 'I': // const_value_index, CONSTANT_Integer + case 'J': // const_value_index, CONSTANT_Long + annotationVisitor.visit( + elementName, readConst(readUnsignedShort(currentOffset), charBuffer)); + currentOffset += 2; + break; + case 'S': // const_value_index, CONSTANT_Integer + annotationVisitor.visit( + elementName, (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset)])); + currentOffset += 2; + break; + + case 'Z': // const_value_index, CONSTANT_Integer + annotationVisitor.visit( + elementName, + readInt(cpInfoOffsets[readUnsignedShort(currentOffset)]) == 0 + ? Boolean.FALSE + : Boolean.TRUE); + currentOffset += 2; + break; + case 's': // const_value_index, CONSTANT_Utf8 + annotationVisitor.visit(elementName, readUTF8(currentOffset, charBuffer)); + currentOffset += 2; + break; + case 'e': // enum_const_value + annotationVisitor.visitEnum( + elementName, + readUTF8(currentOffset, charBuffer), + readUTF8(currentOffset + 2, charBuffer)); + currentOffset += 4; + break; + case 'c': // class_info + annotationVisitor.visit(elementName, Type.getType(readUTF8(currentOffset, charBuffer))); + currentOffset += 2; + break; + case '@': // annotation_value + currentOffset = + readElementValues( + annotationVisitor.visitAnnotation(elementName, readUTF8(currentOffset, charBuffer)), + currentOffset + 2, + true, + charBuffer); + break; + case '[': // array_value + int numValues = readUnsignedShort(currentOffset); + currentOffset += 2; + if (numValues == 0) { + return readElementValues( + annotationVisitor.visitArray(elementName), + currentOffset - 2, + /* named = */ false, + charBuffer); + } + switch (classFileBuffer[currentOffset] & 0xFF) { + case 'B': + byte[] byteValues = new byte[numValues]; + for (int i = 0; i < numValues; i++) { + byteValues[i] = (byte) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); + currentOffset += 3; + } + annotationVisitor.visit(elementName, byteValues); + break; + case 'Z': + boolean[] booleanValues = new boolean[numValues]; + for (int i = 0; i < numValues; i++) { + booleanValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]) != 0; + currentOffset += 3; + } + annotationVisitor.visit(elementName, booleanValues); + break; + case 'S': + short[] shortValues = new short[numValues]; + for (int i = 0; i < numValues; i++) { + shortValues[i] = (short) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); + currentOffset += 3; + } + annotationVisitor.visit(elementName, shortValues); + break; + case 'C': + char[] charValues = new char[numValues]; + for (int i = 0; i < numValues; i++) { + charValues[i] = (char) readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); + currentOffset += 3; + } + annotationVisitor.visit(elementName, charValues); + break; + case 'I': + int[] intValues = new int[numValues]; + for (int i = 0; i < numValues; i++) { + intValues[i] = readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); + currentOffset += 3; + } + annotationVisitor.visit(elementName, intValues); + break; + case 'J': + long[] longValues = new long[numValues]; + for (int i = 0; i < numValues; i++) { + longValues[i] = readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)]); + currentOffset += 3; + } + annotationVisitor.visit(elementName, longValues); + break; + case 'F': + float[] floatValues = new float[numValues]; + for (int i = 0; i < numValues; i++) { + floatValues[i] = + Float.intBitsToFloat( + readInt(cpInfoOffsets[readUnsignedShort(currentOffset + 1)])); + currentOffset += 3; + } + annotationVisitor.visit(elementName, floatValues); + break; + case 'D': + double[] doubleValues = new double[numValues]; + for (int i = 0; i < numValues; i++) { + doubleValues[i] = + Double.longBitsToDouble( + readLong(cpInfoOffsets[readUnsignedShort(currentOffset + 1)])); + currentOffset += 3; + } + annotationVisitor.visit(elementName, doubleValues); + break; + default: + currentOffset = + readElementValues( + annotationVisitor.visitArray(elementName), + currentOffset - 2, + /* named = */ false, + charBuffer); + break; + } + break; + default: + throw new IllegalArgumentException(); + } + return currentOffset; + } + + // ---------------------------------------------------------------------------------------------- + // Methods to parse stack map frames + // ---------------------------------------------------------------------------------------------- + + /** + * Computes the implicit frame of the method currently being parsed (as defined in the given + * {@link Context}) and stores it in the given context. + * + * @param context information about the class being parsed. + */ + private void computeImplicitFrame(final Context context) { + String methodDescriptor = context.currentMethodDescriptor; + Object[] locals = context.currentFrameLocalTypes; + int numLocal = 0; + if ((context.currentMethodAccessFlags & Opcodes.ACC_STATIC) == 0) { + if ("".equals(context.currentMethodName)) { + locals[numLocal++] = Opcodes.UNINITIALIZED_THIS; + } else { + locals[numLocal++] = readClass(header + 2, context.charBuffer); + } + } + // Parse the method descriptor, one argument type descriptor at each iteration. Start by + // skipping the first method descriptor character, which is always '('. + int currentMethodDescritorOffset = 1; + while (true) { + int currentArgumentDescriptorStartOffset = currentMethodDescritorOffset; + switch (methodDescriptor.charAt(currentMethodDescritorOffset++)) { + case 'Z': + case 'C': + case 'B': + case 'S': + case 'I': + locals[numLocal++] = Opcodes.INTEGER; + break; + case 'F': + locals[numLocal++] = Opcodes.FLOAT; + break; + case 'J': + locals[numLocal++] = Opcodes.LONG; + break; + case 'D': + locals[numLocal++] = Opcodes.DOUBLE; + break; + case '[': + while (methodDescriptor.charAt(currentMethodDescritorOffset) == '[') { + ++currentMethodDescritorOffset; + } + if (methodDescriptor.charAt(currentMethodDescritorOffset) == 'L') { + ++currentMethodDescritorOffset; + while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') { + ++currentMethodDescritorOffset; + } + } + locals[numLocal++] = + methodDescriptor.substring( + currentArgumentDescriptorStartOffset, ++currentMethodDescritorOffset); + break; + case 'L': + while (methodDescriptor.charAt(currentMethodDescritorOffset) != ';') { + ++currentMethodDescritorOffset; + } + locals[numLocal++] = + methodDescriptor.substring( + currentArgumentDescriptorStartOffset + 1, currentMethodDescritorOffset++); + break; + default: + context.currentFrameLocalCount = numLocal; + return; + } + } + } + + /** + * Reads a JVMS 'stack_map_frame' structure and stores the result in the given {@link Context} + * object. This method can also be used to read a full_frame structure, excluding its frame_type + * field (this is used to parse the legacy StackMap attributes). + * + * @param stackMapFrameOffset the start offset in {@link #classFileBuffer} of the + * stack_map_frame_value structure to be read, or the start offset of a full_frame structure + * (excluding its frame_type field). + * @param compressed true to read a 'stack_map_frame' structure, false to read a 'full_frame' + * structure without its frame_type field. + * @param expand if the stack map frame must be expanded. See {@link #EXPAND_FRAMES}. + * @param context where the parsed stack map frame must be stored. + * @return the end offset of the JVMS 'stack_map_frame' or 'full_frame' structure. + */ + private int readStackMapFrame( + final int stackMapFrameOffset, + final boolean compressed, + final boolean expand, + final Context context) { + int currentOffset = stackMapFrameOffset; + final char[] charBuffer = context.charBuffer; + final Label[] labels = context.currentMethodLabels; + int frameType; + if (compressed) { + // Read the frame_type field. + frameType = classFileBuffer[currentOffset++] & 0xFF; + } else { + frameType = Frame.FULL_FRAME; + context.currentFrameOffset = -1; + } + int offsetDelta; + context.currentFrameLocalCountDelta = 0; + if (frameType < Frame.SAME_LOCALS_1_STACK_ITEM_FRAME) { + offsetDelta = frameType; + context.currentFrameType = Opcodes.F_SAME; + context.currentFrameStackCount = 0; + } else if (frameType < Frame.RESERVED) { + offsetDelta = frameType - Frame.SAME_LOCALS_1_STACK_ITEM_FRAME; + currentOffset = + readVerificationTypeInfo( + currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels); + context.currentFrameType = Opcodes.F_SAME1; + context.currentFrameStackCount = 1; + } else if (frameType >= Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { + offsetDelta = readUnsignedShort(currentOffset); + currentOffset += 2; + if (frameType == Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) { + currentOffset = + readVerificationTypeInfo( + currentOffset, context.currentFrameStackTypes, 0, charBuffer, labels); + context.currentFrameType = Opcodes.F_SAME1; + context.currentFrameStackCount = 1; + } else if (frameType >= Frame.CHOP_FRAME && frameType < Frame.SAME_FRAME_EXTENDED) { + context.currentFrameType = Opcodes.F_CHOP; + context.currentFrameLocalCountDelta = Frame.SAME_FRAME_EXTENDED - frameType; + context.currentFrameLocalCount -= context.currentFrameLocalCountDelta; + context.currentFrameStackCount = 0; + } else if (frameType == Frame.SAME_FRAME_EXTENDED) { + context.currentFrameType = Opcodes.F_SAME; + context.currentFrameStackCount = 0; + } else if (frameType < Frame.FULL_FRAME) { + int local = expand ? context.currentFrameLocalCount : 0; + for (int k = frameType - Frame.SAME_FRAME_EXTENDED; k > 0; k--) { + currentOffset = + readVerificationTypeInfo( + currentOffset, context.currentFrameLocalTypes, local++, charBuffer, labels); + } + context.currentFrameType = Opcodes.F_APPEND; + context.currentFrameLocalCountDelta = frameType - Frame.SAME_FRAME_EXTENDED; + context.currentFrameLocalCount += context.currentFrameLocalCountDelta; + context.currentFrameStackCount = 0; + } else { + final int numberOfLocals = readUnsignedShort(currentOffset); + currentOffset += 2; + context.currentFrameType = Opcodes.F_FULL; + context.currentFrameLocalCountDelta = numberOfLocals; + context.currentFrameLocalCount = numberOfLocals; + for (int local = 0; local < numberOfLocals; ++local) { + currentOffset = + readVerificationTypeInfo( + currentOffset, context.currentFrameLocalTypes, local, charBuffer, labels); + } + final int numberOfStackItems = readUnsignedShort(currentOffset); + currentOffset += 2; + context.currentFrameStackCount = numberOfStackItems; + for (int stack = 0; stack < numberOfStackItems; ++stack) { + currentOffset = + readVerificationTypeInfo( + currentOffset, context.currentFrameStackTypes, stack, charBuffer, labels); + } + } + } else { + throw new IllegalArgumentException(); + } + context.currentFrameOffset += offsetDelta + 1; + createLabel(context.currentFrameOffset, labels); + return currentOffset; + } + + /** + * Reads a JVMS 'verification_type_info' structure and stores it at the given index in the given + * array. + * + * @param verificationTypeInfoOffset the start offset of the 'verification_type_info' structure to + * read. + * @param frame the array where the parsed type must be stored. + * @param index the index in 'frame' where the parsed type must be stored. + * @param charBuffer the buffer used to read strings in the constant pool. + * @param labels the labels of the method currently being parsed, indexed by their offset. If the + * parsed type is an ITEM_Uninitialized, a new label for the corresponding NEW instruction is + * stored in this array if it does not already exist. + * @return the end offset of the JVMS 'verification_type_info' structure. + */ + private int readVerificationTypeInfo( + final int verificationTypeInfoOffset, + final Object[] frame, + final int index, + final char[] charBuffer, + final Label[] labels) { + int currentOffset = verificationTypeInfoOffset; + int tag = classFileBuffer[currentOffset++] & 0xFF; + switch (tag) { + case Frame.ITEM_TOP: + frame[index] = Opcodes.TOP; + break; + case Frame.ITEM_INTEGER: + frame[index] = Opcodes.INTEGER; + break; + case Frame.ITEM_FLOAT: + frame[index] = Opcodes.FLOAT; + break; + case Frame.ITEM_DOUBLE: + frame[index] = Opcodes.DOUBLE; + break; + case Frame.ITEM_LONG: + frame[index] = Opcodes.LONG; + break; + case Frame.ITEM_NULL: + frame[index] = Opcodes.NULL; + break; + case Frame.ITEM_UNINITIALIZED_THIS: + frame[index] = Opcodes.UNINITIALIZED_THIS; + break; + case Frame.ITEM_OBJECT: + frame[index] = readClass(currentOffset, charBuffer); + currentOffset += 2; + break; + case Frame.ITEM_UNINITIALIZED: + frame[index] = createLabel(readUnsignedShort(currentOffset), labels); + currentOffset += 2; + break; + default: + throw new IllegalArgumentException(); + } + return currentOffset; + } + + // ---------------------------------------------------------------------------------------------- + // Methods to parse attributes + // ---------------------------------------------------------------------------------------------- + + /** + * Returns the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array + * field entry. + * + * @return the offset in {@link #classFileBuffer} of the first ClassFile's 'attributes' array + * field entry. + */ + final int getFirstAttributeOffset() { + // Skip the access_flags, this_class, super_class, and interfaces_count fields (using 2 bytes + // each), as well as the interfaces array field (2 bytes per interface). + int currentOffset = header + 8 + readUnsignedShort(header + 6) * 2; + + // Read the fields_count field. + int fieldsCount = readUnsignedShort(currentOffset); + currentOffset += 2; + // Skip the 'fields' array field. + while (fieldsCount-- > 0) { + // Invariant: currentOffset is the offset of a field_info structure. + // Skip the access_flags, name_index and descriptor_index fields (2 bytes each), and read the + // attributes_count field. + int attributesCount = readUnsignedShort(currentOffset + 6); + currentOffset += 8; + // Skip the 'attributes' array field. + while (attributesCount-- > 0) { + // Invariant: currentOffset is the offset of an attribute_info structure. + // Read the attribute_length field (2 bytes after the start of the attribute_info) and skip + // this many bytes, plus 6 for the attribute_name_index and attribute_length fields + // (yielding the total size of the attribute_info structure). + currentOffset += 6 + readInt(currentOffset + 2); + } + } + + // Skip the methods_count and 'methods' fields, using the same method as above. + int methodsCount = readUnsignedShort(currentOffset); + currentOffset += 2; + while (methodsCount-- > 0) { + int attributesCount = readUnsignedShort(currentOffset + 6); + currentOffset += 8; + while (attributesCount-- > 0) { + currentOffset += 6 + readInt(currentOffset + 2); + } + } + + // Skip the ClassFile's attributes_count field. + return currentOffset + 2; + } + + /** + * Reads the BootstrapMethods attribute to compute the offset of each bootstrap method. + * + * @param maxStringLength a conservative estimate of the maximum length of the strings contained + * in the constant pool of the class. + * @return the offsets of the bootstrap methods. + */ + private int[] readBootstrapMethodsAttribute(final int maxStringLength) { + char[] charBuffer = new char[maxStringLength]; + int currentAttributeOffset = getFirstAttributeOffset(); + int[] currentBootstrapMethodOffsets = null; + for (int i = readUnsignedShort(currentAttributeOffset - 2); i > 0; --i) { + // Read the attribute_info's attribute_name and attribute_length fields. + String attributeName = readUTF8(currentAttributeOffset, charBuffer); + int attributeLength = readInt(currentAttributeOffset + 2); + currentAttributeOffset += 6; + if (Constants.BOOTSTRAP_METHODS.equals(attributeName)) { + // Read the num_bootstrap_methods field and create an array of this size. + currentBootstrapMethodOffsets = new int[readUnsignedShort(currentAttributeOffset)]; + // Compute and store the offset of each 'bootstrap_methods' array field entry. + int currentBootstrapMethodOffset = currentAttributeOffset + 2; + for (int j = 0; j < currentBootstrapMethodOffsets.length; ++j) { + currentBootstrapMethodOffsets[j] = currentBootstrapMethodOffset; + // Skip the bootstrap_method_ref and num_bootstrap_arguments fields (2 bytes each), + // as well as the bootstrap_arguments array field (of size num_bootstrap_arguments * 2). + currentBootstrapMethodOffset += + 4 + readUnsignedShort(currentBootstrapMethodOffset + 2) * 2; + } + return currentBootstrapMethodOffsets; + } + currentAttributeOffset += attributeLength; + } + throw new IllegalArgumentException(); + } + + /** + * Reads a non standard JVMS 'attribute' structure in {@link #classFileBuffer}. + * + * @param attributePrototypes prototypes of the attributes that must be parsed during the visit of + * the class. Any attribute whose type is not equal to the type of one the prototypes will not + * be parsed: its byte array value will be passed unchanged to the ClassWriter. + * @param type the type of the attribute. + * @param offset the start offset of the JVMS 'attribute' structure in {@link #classFileBuffer}. + * The 6 attribute header bytes (attribute_name_index and attribute_length) are not taken into + * account here. + * @param length the length of the attribute's content (excluding the 6 attribute header bytes). + * @param charBuffer the buffer to be used to read strings in the constant pool. + * @param codeAttributeOffset the start offset of the enclosing Code attribute in {@link + * #classFileBuffer}, or -1 if the attribute to be read is not a code attribute. The 6 + * attribute header bytes (attribute_name_index and attribute_length) are not taken into + * account here. + * @param labels the labels of the method's code, or {@literal null} if the attribute to be read + * is not a code attribute. + * @return the attribute that has been read. + */ + private Attribute readAttribute( + final Attribute[] attributePrototypes, + final String type, + final int offset, + final int length, + final char[] charBuffer, + final int codeAttributeOffset, + final Label[] labels) { + for (Attribute attributePrototype : attributePrototypes) { + if (attributePrototype.type.equals(type)) { + return attributePrototype.read( + this, offset, length, charBuffer, codeAttributeOffset, labels); + } + } + return new Attribute(type).read(this, offset, length, null, -1, null); + } + + // ----------------------------------------------------------------------------------------------- + // Utility methods: low level parsing + // ----------------------------------------------------------------------------------------------- + + /** + * Returns the number of entries in the class's constant pool table. + * + * @return the number of entries in the class's constant pool table. + */ + public int getItemCount() { + return cpInfoOffsets.length; + } + + /** + * Returns the start offset in this {@link ClassReader} of a JVMS 'cp_info' structure (i.e. a + * constant pool entry), plus one. This method is intended for {@link Attribute} sub classes, + * and is normally not needed by class generators or adapters. + * + * @param constantPoolEntryIndex the index a constant pool entry in the class's constant pool + * table. + * @return the start offset in this {@link ClassReader} of the corresponding JVMS 'cp_info' + * structure, plus one. + */ + public int getItem(final int constantPoolEntryIndex) { + return cpInfoOffsets[constantPoolEntryIndex]; + } + + /** + * Returns a conservative estimate of the maximum length of the strings contained in the class's + * constant pool table. + * + * @return a conservative estimate of the maximum length of the strings contained in the class's + * constant pool table. + */ + public int getMaxStringLength() { + return maxStringLength; + } + + /** + * Reads a byte value in this {@link ClassReader}. This method is intended for {@link + * Attribute} sub classes, and is normally not needed by class generators or adapters. + * + * @param offset the start offset of the value to be read in this {@link ClassReader}. + * @return the read value. + */ + public int readByte(final int offset) { + return classFileBuffer[offset] & 0xFF; + } + + /** + * Reads an unsigned short value in this {@link ClassReader}. This method is intended for + * {@link Attribute} sub classes, and is normally not needed by class generators or adapters. + * + * @param offset the start index of the value to be read in this {@link ClassReader}. + * @return the read value. + */ + public int readUnsignedShort(final int offset) { + byte[] classBuffer = classFileBuffer; + return ((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF); + } + + /** + * Reads a signed short value in this {@link ClassReader}. This method is intended for {@link + * Attribute} sub classes, and is normally not needed by class generators or adapters. + * + * @param offset the start offset of the value to be read in this {@link ClassReader}. + * @return the read value. + */ + public short readShort(final int offset) { + byte[] classBuffer = classFileBuffer; + return (short) (((classBuffer[offset] & 0xFF) << 8) | (classBuffer[offset + 1] & 0xFF)); + } + + /** + * Reads a signed int value in this {@link ClassReader}. This method is intended for {@link + * Attribute} sub classes, and is normally not needed by class generators or adapters. + * + * @param offset the start offset of the value to be read in this {@link ClassReader}. + * @return the read value. + */ + public int readInt(final int offset) { + byte[] classBuffer = classFileBuffer; + return ((classBuffer[offset] & 0xFF) << 24) + | ((classBuffer[offset + 1] & 0xFF) << 16) + | ((classBuffer[offset + 2] & 0xFF) << 8) + | (classBuffer[offset + 3] & 0xFF); + } + + /** + * Reads a signed long value in this {@link ClassReader}. This method is intended for {@link + * Attribute} sub classes, and is normally not needed by class generators or adapters. + * + * @param offset the start offset of the value to be read in this {@link ClassReader}. + * @return the read value. + */ + public long readLong(final int offset) { + long l1 = readInt(offset); + long l0 = readInt(offset + 4) & 0xFFFFFFFFL; + return (l1 << 32) | l0; + } + + /** + * Reads a CONSTANT_Utf8 constant pool entry in this {@link ClassReader}. This method is + * intended for {@link Attribute} sub classes, and is normally not needed by class generators or + * adapters. + * + * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose + * value is the index of a CONSTANT_Utf8 entry in the class's constant pool table. + * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the String corresponding to the specified CONSTANT_Utf8 entry. + */ + // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). + public String readUTF8(final int offset, final char[] charBuffer) { + int constantPoolEntryIndex = readUnsignedShort(offset); + if (offset == 0 || constantPoolEntryIndex == 0) { + return null; + } + return readUtf(constantPoolEntryIndex, charBuffer); + } + + /** + * Reads a CONSTANT_Utf8 constant pool entry in {@link #classFileBuffer}. + * + * @param constantPoolEntryIndex the index of a CONSTANT_Utf8 entry in the class's constant pool + * table. + * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the String corresponding to the specified CONSTANT_Utf8 entry. + */ + final String readUtf(final int constantPoolEntryIndex, final char[] charBuffer) { + String value = constantUtf8Values[constantPoolEntryIndex]; + if (value != null) { + return value; + } + int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; + return constantUtf8Values[constantPoolEntryIndex] = + readUtf(cpInfoOffset + 2, readUnsignedShort(cpInfoOffset), charBuffer); + } + + /** + * Reads an UTF8 string in {@link #classFileBuffer}. + * + * @param utfOffset the start offset of the UTF8 string to be read. + * @param utfLength the length of the UTF8 string to be read. + * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the String corresponding to the specified UTF8 string. + */ + private String readUtf(final int utfOffset, final int utfLength, final char[] charBuffer) { + int currentOffset = utfOffset; + int endOffset = currentOffset + utfLength; + int strLength = 0; + byte[] classBuffer = classFileBuffer; + while (currentOffset < endOffset) { + int currentByte = classBuffer[currentOffset++]; + if ((currentByte & 0x80) == 0) { + charBuffer[strLength++] = (char) (currentByte & 0x7F); + } else if ((currentByte & 0xE0) == 0xC0) { + charBuffer[strLength++] = + (char) (((currentByte & 0x1F) << 6) + (classBuffer[currentOffset++] & 0x3F)); + } else { + charBuffer[strLength++] = + (char) + (((currentByte & 0xF) << 12) + + ((classBuffer[currentOffset++] & 0x3F) << 6) + + (classBuffer[currentOffset++] & 0x3F)); + } + } + return new String(charBuffer, 0, strLength); + } + + /** + * Reads a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, CONSTANT_Module or + * CONSTANT_Package constant pool entry in {@link #classFileBuffer}. This method is intended + * for {@link Attribute} sub classes, and is normally not needed by class generators or + * adapters. + * + * @param offset the start offset of an unsigned short value in {@link #classFileBuffer}, whose + * value is the index of a CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, + * CONSTANT_Module or CONSTANT_Package entry in class's constant pool table. + * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the String corresponding to the specified constant pool entry. + */ + private String readStringish(final int offset, final char[] charBuffer) { + // Get the start offset of the cp_info structure (plus one), and read the CONSTANT_Utf8 entry + // designated by the first two bytes of this cp_info. + return readUTF8(cpInfoOffsets[readUnsignedShort(offset)], charBuffer); + } + + /** + * Reads a CONSTANT_Class constant pool entry in this {@link ClassReader}. This method is + * intended for {@link Attribute} sub classes, and is normally not needed by class generators or + * adapters. + * + * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose + * value is the index of a CONSTANT_Class entry in class's constant pool table. + * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the String corresponding to the specified CONSTANT_Class entry. + */ + public String readClass(final int offset, final char[] charBuffer) { + return readStringish(offset, charBuffer); + } + + /** + * Reads a CONSTANT_Module constant pool entry in this {@link ClassReader}. This method is + * intended for {@link Attribute} sub classes, and is normally not needed by class generators or + * adapters. + * + * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose + * value is the index of a CONSTANT_Module entry in class's constant pool table. + * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the String corresponding to the specified CONSTANT_Module entry. + */ + public String readModule(final int offset, final char[] charBuffer) { + return readStringish(offset, charBuffer); + } + + /** + * Reads a CONSTANT_Package constant pool entry in this {@link ClassReader}. This method is + * intended for {@link Attribute} sub classes, and is normally not needed by class generators or + * adapters. + * + * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose + * value is the index of a CONSTANT_Package entry in class's constant pool table. + * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the String corresponding to the specified CONSTANT_Package entry. + */ + public String readPackage(final int offset, final char[] charBuffer) { + return readStringish(offset, charBuffer); + } + + /** + * Reads a CONSTANT_Dynamic constant pool entry in {@link #classFileBuffer}. + * + * @param constantPoolEntryIndex the index of a CONSTANT_Dynamic entry in the class's constant + * pool table. + * @param charBuffer the buffer to be used to read the string. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the ConstantDynamic corresponding to the specified CONSTANT_Dynamic entry. + */ + private ConstantDynamic readConstantDynamic( + final int constantPoolEntryIndex, final char[] charBuffer) { + ConstantDynamic constantDynamic = constantDynamicValues[constantPoolEntryIndex]; + if (constantDynamic != null) { + return constantDynamic; + } + int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; + int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 2)]; + String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); + String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); + int bootstrapMethodOffset = bootstrapMethodOffsets[readUnsignedShort(cpInfoOffset)]; + Handle handle = (Handle) readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); + Object[] bootstrapMethodArguments = new Object[readUnsignedShort(bootstrapMethodOffset + 2)]; + bootstrapMethodOffset += 4; + for (int i = 0; i < bootstrapMethodArguments.length; i++) { + bootstrapMethodArguments[i] = readConst(readUnsignedShort(bootstrapMethodOffset), charBuffer); + bootstrapMethodOffset += 2; + } + return constantDynamicValues[constantPoolEntryIndex] = + new ConstantDynamic(name, descriptor, handle, bootstrapMethodArguments); + } + + /** + * Reads a numeric or string constant pool entry in this {@link ClassReader}. This method is + * intended for {@link Attribute} sub classes, and is normally not needed by class generators or + * adapters. + * + * @param constantPoolEntryIndex the index of a CONSTANT_Integer, CONSTANT_Float, CONSTANT_Long, + * CONSTANT_Double, CONSTANT_Class, CONSTANT_String, CONSTANT_MethodType, + * CONSTANT_MethodHandle or CONSTANT_Dynamic entry in the class's constant pool. + * @param charBuffer the buffer to be used to read strings. This buffer must be sufficiently + * large. It is not automatically resized. + * @return the {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String}, + * {@link Type}, {@link Handle} or {@link ConstantDynamic} corresponding to the specified + * constant pool entry. + */ + public Object readConst(final int constantPoolEntryIndex, final char[] charBuffer) { + int cpInfoOffset = cpInfoOffsets[constantPoolEntryIndex]; + switch (classFileBuffer[cpInfoOffset - 1]) { + case Symbol.CONSTANT_INTEGER_TAG: + return readInt(cpInfoOffset); + case Symbol.CONSTANT_FLOAT_TAG: + return Float.intBitsToFloat(readInt(cpInfoOffset)); + case Symbol.CONSTANT_LONG_TAG: + return readLong(cpInfoOffset); + case Symbol.CONSTANT_DOUBLE_TAG: + return Double.longBitsToDouble(readLong(cpInfoOffset)); + case Symbol.CONSTANT_CLASS_TAG: + return Type.getObjectType(readUTF8(cpInfoOffset, charBuffer)); + case Symbol.CONSTANT_STRING_TAG: + return readUTF8(cpInfoOffset, charBuffer); + case Symbol.CONSTANT_METHOD_TYPE_TAG: + return Type.getMethodType(readUTF8(cpInfoOffset, charBuffer)); + case Symbol.CONSTANT_METHOD_HANDLE_TAG: + int referenceKind = readByte(cpInfoOffset); + int referenceCpInfoOffset = cpInfoOffsets[readUnsignedShort(cpInfoOffset + 1)]; + int nameAndTypeCpInfoOffset = cpInfoOffsets[readUnsignedShort(referenceCpInfoOffset + 2)]; + String owner = readClass(referenceCpInfoOffset, charBuffer); + String name = readUTF8(nameAndTypeCpInfoOffset, charBuffer); + String descriptor = readUTF8(nameAndTypeCpInfoOffset + 2, charBuffer); + boolean isInterface = + classFileBuffer[referenceCpInfoOffset - 1] == Symbol.CONSTANT_INTERFACE_METHODREF_TAG; + return new Handle(referenceKind, owner, name, descriptor, isInterface); + case Symbol.CONSTANT_DYNAMIC_TAG: + return readConstantDynamic(constantPoolEntryIndex, charBuffer); + default: + throw new IllegalArgumentException(); + } + } +} diff --git a/src/org/objectweb/asm/ClassWriter.java b/src/main/java/org/objectweb/asm/ClassWriter.java similarity index 97% rename from src/org/objectweb/asm/ClassWriter.java rename to src/main/java/org/objectweb/asm/ClassWriter.java index 7b1f4189..7bd6355c 100644 --- a/src/org/objectweb/asm/ClassWriter.java +++ b/src/main/java/org/objectweb/asm/ClassWriter.java @@ -1,972 +1,972 @@ -// ASM: a very small and fast Java bytecode manipulation framework -// Copyright (c) 2000-2011 INRIA, France Telecom -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. Neither the name of the copyright holders nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -// THE POSSIBILITY OF SUCH DAMAGE. -package org.objectweb.asm; - -/** - * A {@link ClassVisitor} that generates a corresponding ClassFile structure, as defined in the Java - * Virtual Machine Specification (JVMS). It can be used alone, to generate a Java class "from - * scratch", or with one or more {@link ClassReader} and adapter {@link ClassVisitor} to generate a - * modified class from one or more existing Java classes. - * - * @see JVMS 4 - * @author Eric Bruneton - */ -public class ClassWriter extends ClassVisitor { - - /** - * A flag to automatically compute the maximum stack size and the maximum number of local - * variables of methods. If this flag is set, then the arguments of the {@link - * MethodVisitor#visitMaxs} method of the {@link MethodVisitor} returned by the {@link - * #visitMethod} method will be ignored, and computed automatically from the signature and the - * bytecode of each method. - * - *

Note: for classes whose version is {@link Opcodes#V1_7} of more, this option requires - * valid stack map frames. The maximum stack size is then computed from these frames, and from the - * bytecode instructions in between. If stack map frames are not present or must be recomputed, - * used {@link #COMPUTE_FRAMES} instead. - * - * @see #ClassWriter(int) - */ - public static final int COMPUTE_MAXS = 1; - - /** - * A flag to automatically compute the stack map frames of methods from scratch. If this flag is - * set, then the calls to the {@link MethodVisitor#visitFrame} method are ignored, and the stack - * map frames are recomputed from the methods bytecode. The arguments of the {@link - * MethodVisitor#visitMaxs} method are also ignored and recomputed from the bytecode. In other - * words, {@link #COMPUTE_FRAMES} implies {@link #COMPUTE_MAXS}. - * - * @see #ClassWriter(int) - */ - public static final int COMPUTE_FRAMES = 2; - - // Note: fields are ordered as in the ClassFile structure, and those related to attributes are - // ordered as in Section 4.7 of the JVMS. - - /** - * The minor_version and major_version fields of the JVMS ClassFile structure. minor_version is - * stored in the 16 most significant bits, and major_version in the 16 least significant bits. - */ - private int version; - - /** The symbol table for this class (contains the constant_pool and the BootstrapMethods). */ - private final SymbolTable symbolTable; - - /** - * The access_flags field of the JVMS ClassFile structure. This field can contain ASM specific - * access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the - * ClassFile structure. - */ - private int accessFlags; - - /** The this_class field of the JVMS ClassFile structure. */ - private int thisClass; - - /** The super_class field of the JVMS ClassFile structure. */ - private int superClass; - - /** The interface_count field of the JVMS ClassFile structure. */ - private int interfaceCount; - - /** The 'interfaces' array of the JVMS ClassFile structure. */ - private int[] interfaces; - - /** - * The fields of this class, stored in a linked list of {@link FieldWriter} linked via their - * {@link FieldWriter#fv} field. This field stores the first element of this list. - */ - private FieldWriter firstField; - - /** - * The fields of this class, stored in a linked list of {@link FieldWriter} linked via their - * {@link FieldWriter#fv} field. This field stores the last element of this list. - */ - private FieldWriter lastField; - - /** - * The methods of this class, stored in a linked list of {@link MethodWriter} linked via their - * {@link MethodWriter#mv} field. This field stores the first element of this list. - */ - private MethodWriter firstMethod; - - /** - * The methods of this class, stored in a linked list of {@link MethodWriter} linked via their - * {@link MethodWriter#mv} field. This field stores the last element of this list. - */ - private MethodWriter lastMethod; - - /** The number_of_classes field of the InnerClasses attribute, or 0. */ - private int numberOfInnerClasses; - - /** The 'classes' array of the InnerClasses attribute, or {@literal null}. */ - private ByteVector innerClasses; - - /** The class_index field of the EnclosingMethod attribute, or 0. */ - private int enclosingClassIndex; - - /** The method_index field of the EnclosingMethod attribute. */ - private int enclosingMethodIndex; - - /** The signature_index field of the Signature attribute, or 0. */ - private int signatureIndex; - - /** The source_file_index field of the SourceFile attribute, or 0. */ - private int sourceFileIndex; - - /** The debug_extension field of the SourceDebugExtension attribute, or {@literal null}. */ - private ByteVector debugExtension; - - /** - * The last runtime visible annotation of this class. The previous ones can be accessed with the - * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeVisibleAnnotation; - - /** - * The last runtime invisible annotation of this class. The previous ones can be accessed with the - * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeInvisibleAnnotation; - - /** - * The last runtime visible type annotation of this class. The previous ones can be accessed with - * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeVisibleTypeAnnotation; - - /** - * The last runtime invisible type annotation of this class. The previous ones can be accessed - * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. - */ - private AnnotationWriter lastRuntimeInvisibleTypeAnnotation; - - /** The Module attribute of this class, or {@literal null}. */ - private ModuleWriter moduleWriter; - - /** The host_class_index field of the NestHost attribute, or 0. */ - private int nestHostClassIndex; - - /** The number_of_classes field of the NestMembers attribute, or 0. */ - private int numberOfNestMemberClasses; - - /** The 'classes' array of the NestMembers attribute, or {@literal null}. */ - private ByteVector nestMemberClasses; - - /** - * The first non standard attribute of this class. The next ones can be accessed with the {@link - * Attribute#nextAttribute} field. May be {@literal null}. - * - *

WARNING: this list stores the attributes in the reverse order of their visit. - * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link - * #toByteArray} method writes the attributes in the order defined by this list, i.e. in the - * reverse order specified by the user. - */ - private Attribute firstAttribute; - - /** - * Indicates what must be automatically computed in {@link MethodWriter}. Must be one of {@link - * MethodWriter#COMPUTE_NOTHING}, {@link MethodWriter#COMPUTE_MAX_STACK_AND_LOCAL}, {@link - * MethodWriter#COMPUTE_INSERTED_FRAMES}, or {@link MethodWriter#COMPUTE_ALL_FRAMES}. - */ - private int compute; - - // ----------------------------------------------------------------------------------------------- - // Constructor - // ----------------------------------------------------------------------------------------------- - - /** - * Constructs a new {@link ClassWriter} object. - * - * @param flags option flags that can be used to modify the default behavior of this class. Must - * be zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. - */ - public ClassWriter(final int flags) { - this(null, flags); - } - - /** - * Constructs a new {@link ClassWriter} object and enables optimizations for "mostly add" bytecode - * transformations. These optimizations are the following: - * - *

    - *
  • The constant pool and bootstrap methods from the original class are copied as is in the - * new class, which saves time. New constant pool entries and new bootstrap methods will be - * added at the end if necessary, but unused constant pool entries or bootstrap methods - * won't be removed. - *
  • Methods that are not transformed are copied as is in the new class, directly from the - * original class bytecode (i.e. without emitting visit events for all the method - * instructions), which saves a lot of time. Untransformed methods are detected by - * the fact that the {@link ClassReader} receives {@link MethodVisitor} objects that come - * from a {@link ClassWriter} (and not from any other {@link ClassVisitor} instance). - *
- * - * @param classReader the {@link ClassReader} used to read the original class. It will be used to - * copy the entire constant pool and bootstrap methods from the original class and also to - * copy other fragments of original bytecode where applicable. - * @param flags option flags that can be used to modify the default behavior of this class.Must be - * zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. These option flags do - * not affect methods that are copied as is in the new class. This means that neither the - * maximum stack size nor the stack frames will be computed for these methods. - */ - public ClassWriter(final ClassReader classReader, final int flags) { - super(Opcodes.ASM7); - symbolTable = classReader == null ? new SymbolTable(this) : new SymbolTable(this, classReader); - if ((flags & COMPUTE_FRAMES) != 0) { - this.compute = MethodWriter.COMPUTE_ALL_FRAMES; - } else if ((flags & COMPUTE_MAXS) != 0) { - this.compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL; - } else { - this.compute = MethodWriter.COMPUTE_NOTHING; - } - } - - // ----------------------------------------------------------------------------------------------- - // Implementation of the ClassVisitor abstract class - // ----------------------------------------------------------------------------------------------- - - @Override - public final void visit( - final int version, - final int access, - final String name, - final String signature, - final String superName, - final String[] interfaces) - { - this.version = version; - - //replace all pre jre minor versions to one that's outside of the old format - if((version & 0xFFFF) == 45 && (version >>> 16) <= 2) - { - this.version = (3 << 16) | 45; - } - this.accessFlags = access; - this.thisClass = symbolTable.setMajorVersionAndClassName(this.version & 0xFFFF, name); - if (signature != null) { - this.signatureIndex = symbolTable.addConstantUtf8(signature); - } - this.superClass = superName == null ? 0 : symbolTable.addConstantClass(superName).index; - if (interfaces != null && interfaces.length > 0) { - interfaceCount = interfaces.length; - this.interfaces = new int[interfaceCount]; - for (int i = 0; i < interfaceCount; ++i) { - this.interfaces[i] = symbolTable.addConstantClass(interfaces[i]).index; - } - } - if (compute == MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL && (this.version & 0xFFFF) >= Opcodes.V1_7) { - compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES; - } - } - - @Override - public final void visitSource(final String file, final String debug) { - if (file != null) { - sourceFileIndex = symbolTable.addConstantUtf8(file); - } - if (debug != null) { - debugExtension = new ByteVector().encodeUtf8(debug, 0, Integer.MAX_VALUE); - } - } - - @Override - public final ModuleVisitor visitModule( - final String name, final int access, final String version) { - return moduleWriter = - new ModuleWriter( - symbolTable, - symbolTable.addConstantModule(name).index, - access, - version == null ? 0 : symbolTable.addConstantUtf8(version)); - } - - @Override - public void visitNestHost(final String nestHost) { - nestHostClassIndex = symbolTable.addConstantClass(nestHost).index; - } - - @Override - public final void visitOuterClass( - final String owner, final String name, final String descriptor) { - enclosingClassIndex = symbolTable.addConstantClass(owner).index; - if (name != null && descriptor != null) { - enclosingMethodIndex = symbolTable.addConstantNameAndType(name, descriptor); - } - } - - @Override - public final AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { - if (visible) { - return lastRuntimeVisibleAnnotation = - AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation); - } else { - return lastRuntimeInvisibleAnnotation = - AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation); - } - } - - @Override - public final AnnotationVisitor visitTypeAnnotation( - final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { - if (visible) { - return lastRuntimeVisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation); - } else { - return lastRuntimeInvisibleTypeAnnotation = - AnnotationWriter.create( - symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation); - } - } - - @Override - public final void visitAttribute(final Attribute attribute) { - // Store the attributes in the reverse order of their visit by this method. - attribute.nextAttribute = firstAttribute; - firstAttribute = attribute; - } - - @Override - public void visitNestMember(final String nestMember) { - if (nestMemberClasses == null) { - nestMemberClasses = new ByteVector(); - } - ++numberOfNestMemberClasses; - nestMemberClasses.putShort(symbolTable.addConstantClass(nestMember).index); - } - - @Override - public final void visitInnerClass( - final String name, final String outerName, final String innerName, final int access) { - if (innerClasses == null) { - innerClasses = new ByteVector(); - } - // Section 4.7.6 of the JVMS states "Every CONSTANT_Class_info entry in the constant_pool table - // which represents a class or interface C that is not a package member must have exactly one - // corresponding entry in the classes array". To avoid duplicates we keep track in the info - // field of the Symbol of each CONSTANT_Class_info entry C whether an inner class entry has - // already been added for C. If so, we store the index of this inner class entry (plus one) in - // the info field. This trick allows duplicate detection in O(1) time. - Symbol nameSymbol = symbolTable.addConstantClass(name); - if (nameSymbol.info == 0) { - ++numberOfInnerClasses; - innerClasses.putShort(nameSymbol.index); - innerClasses.putShort(outerName == null ? 0 : symbolTable.addConstantClass(outerName).index); - innerClasses.putShort(innerName == null ? 0 : symbolTable.addConstantUtf8(innerName)); - innerClasses.putShort(access); - nameSymbol.info = numberOfInnerClasses; - } - // Else, compare the inner classes entry nameSymbol.info - 1 with the arguments of this method - // and throw an exception if there is a difference? - } - - @Override - public final FieldVisitor visitField( - final int access, - final String name, - final String descriptor, - final String signature, - final Object value) { - FieldWriter fieldWriter = - new FieldWriter(symbolTable, access, name, descriptor, signature, value); - if (firstField == null) { - firstField = fieldWriter; - } else { - lastField.fv = fieldWriter; - } - return lastField = fieldWriter; - } - - @Override - public final MethodVisitor visitMethod( - final int access, - final String name, - final String descriptor, - final String signature, - final String[] exceptions) { - MethodWriter methodWriter = - new MethodWriter(symbolTable, access, name, descriptor, signature, exceptions, compute); - if (firstMethod == null) { - firstMethod = methodWriter; - } else { - lastMethod.mv = methodWriter; - } - return lastMethod = methodWriter; - } - - @Override - public final void visitEnd() { - // Nothing to do. - } - - // ----------------------------------------------------------------------------------------------- - // Other public methods - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the content of the class file that was built by this ClassWriter. - * - * @return the binary content of the JVMS ClassFile structure that was built by this ClassWriter. - * @throws ClassTooLargeException if the constant pool of the class is too large. - * @throws MethodTooLargeException if the Code attribute of a method is too large. - */ - public byte[] toByteArray() { - // First step: compute the size in bytes of the ClassFile structure. - // The magic field uses 4 bytes, 10 mandatory fields (minor_version, major_version, - // constant_pool_count, access_flags, this_class, super_class, interfaces_count, fields_count, - // methods_count and attributes_count) use 2 bytes each, and each interface uses 2 bytes too. - int size = 24 + 2 * interfaceCount; - int fieldsCount = 0; - FieldWriter fieldWriter = firstField; - while (fieldWriter != null) { - ++fieldsCount; - size += fieldWriter.computeFieldInfoSize(); - fieldWriter = (FieldWriter) fieldWriter.fv; - } - int methodsCount = 0; - MethodWriter methodWriter = firstMethod; - while (methodWriter != null) { - ++methodsCount; - size += methodWriter.computeMethodInfoSize(); - methodWriter = (MethodWriter) methodWriter.mv; - } - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - int attributesCount = 0; - if (innerClasses != null) { - ++attributesCount; - size += 8 + innerClasses.length; - symbolTable.addConstantUtf8(Constants.INNER_CLASSES); - } - if (enclosingClassIndex != 0) { - ++attributesCount; - size += 10; - symbolTable.addConstantUtf8(Constants.ENCLOSING_METHOD); - } - if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && (version & 0xFFFF) < Opcodes.V1_5) { - ++attributesCount; - size += 6; - symbolTable.addConstantUtf8(Constants.SYNTHETIC); - } - if (signatureIndex != 0) { - ++attributesCount; - size += 8; - symbolTable.addConstantUtf8(Constants.SIGNATURE); - } - if (sourceFileIndex != 0) { - ++attributesCount; - size += 8; - symbolTable.addConstantUtf8(Constants.SOURCE_FILE); - } - if (debugExtension != null) { - ++attributesCount; - size += 6 + debugExtension.length; - symbolTable.addConstantUtf8(Constants.SOURCE_DEBUG_EXTENSION); - } - if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { - ++attributesCount; - size += 6; - symbolTable.addConstantUtf8(Constants.DEPRECATED); - } - if (lastRuntimeVisibleAnnotation != null) { - ++attributesCount; - size += - lastRuntimeVisibleAnnotation.computeAnnotationsSize( - Constants.RUNTIME_VISIBLE_ANNOTATIONS); - } - if (lastRuntimeInvisibleAnnotation != null) { - ++attributesCount; - size += - lastRuntimeInvisibleAnnotation.computeAnnotationsSize( - Constants.RUNTIME_INVISIBLE_ANNOTATIONS); - } - if (lastRuntimeVisibleTypeAnnotation != null) { - ++attributesCount; - size += - lastRuntimeVisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS); - } - if (lastRuntimeInvisibleTypeAnnotation != null) { - ++attributesCount; - size += - lastRuntimeInvisibleTypeAnnotation.computeAnnotationsSize( - Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); - } - if (symbolTable.computeBootstrapMethodsSize() > 0) { - ++attributesCount; - size += symbolTable.computeBootstrapMethodsSize(); - } - if (moduleWriter != null) { - attributesCount += moduleWriter.getAttributeCount(); - size += moduleWriter.computeAttributesSize(); - } - if (nestHostClassIndex != 0) { - ++attributesCount; - size += 8; - symbolTable.addConstantUtf8(Constants.NEST_HOST); - } - if (nestMemberClasses != null) { - ++attributesCount; - size += 8 + nestMemberClasses.length; - symbolTable.addConstantUtf8(Constants.NEST_MEMBERS); - } - if (firstAttribute != null) { - attributesCount += firstAttribute.getAttributeCount(); - size += firstAttribute.computeAttributesSize(symbolTable); - } - // IMPORTANT: this must be the last part of the ClassFile size computation, because the previous - // statements can add attribute names to the constant pool, thereby changing its size! - size += symbolTable.getConstantPoolLength(); - int constantPoolCount = symbolTable.getConstantPoolCount(); - if (constantPoolCount > 0xFFFF) { - throw new ClassTooLargeException(symbolTable.getClassName(), constantPoolCount); - } - - // Second step: allocate a ByteVector of the correct size (in order to avoid any array copy in - // dynamic resizes) and fill it with the ClassFile content. - ByteVector result = new ByteVector(size); - result.putInt(0xCAFEBABE).putInt(version); - symbolTable.putConstantPool(result); - int mask = (version & 0xFFFF) < Opcodes.V1_5 ? Opcodes.ACC_SYNTHETIC : 0; - result.putShort(accessFlags & ~mask).putShort(thisClass).putShort(superClass); - result.putShort(interfaceCount); - for (int i = 0; i < interfaceCount; ++i) { - result.putShort(interfaces[i]); - } - result.putShort(fieldsCount); - fieldWriter = firstField; - while (fieldWriter != null) { - fieldWriter.putFieldInfo(result); - fieldWriter = (FieldWriter) fieldWriter.fv; - } - result.putShort(methodsCount); - boolean hasFrames = false; - boolean hasAsmInstructions = false; - methodWriter = firstMethod; - while (methodWriter != null) { - hasFrames |= methodWriter.hasFrames(); - hasAsmInstructions |= methodWriter.hasAsmInstructions(); - methodWriter.putMethodInfo(result); - methodWriter = (MethodWriter) methodWriter.mv; - } - // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. - result.putShort(attributesCount); - if (innerClasses != null) { - result - .putShort(symbolTable.addConstantUtf8(Constants.INNER_CLASSES)) - .putInt(innerClasses.length + 2) - .putShort(numberOfInnerClasses) - .putByteArray(innerClasses.data, 0, innerClasses.length); - } - if (enclosingClassIndex != 0) { - result - .putShort(symbolTable.addConstantUtf8(Constants.ENCLOSING_METHOD)) - .putInt(4) - .putShort(enclosingClassIndex) - .putShort(enclosingMethodIndex); - } - if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && (version & 0xFFFF) < Opcodes.V1_5) { - result.putShort(symbolTable.addConstantUtf8(Constants.SYNTHETIC)).putInt(0); - } - if (signatureIndex != 0) { - result - .putShort(symbolTable.addConstantUtf8(Constants.SIGNATURE)) - .putInt(2) - .putShort(signatureIndex); - } - if (sourceFileIndex != 0) { - result - .putShort(symbolTable.addConstantUtf8(Constants.SOURCE_FILE)) - .putInt(2) - .putShort(sourceFileIndex); - } - if (debugExtension != null) { - int length = debugExtension.length; - result - .putShort(symbolTable.addConstantUtf8(Constants.SOURCE_DEBUG_EXTENSION)) - .putInt(length) - .putByteArray(debugExtension.data, 0, length); - } - if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { - result.putShort(symbolTable.addConstantUtf8(Constants.DEPRECATED)).putInt(0); - } - AnnotationWriter.putAnnotations( - symbolTable, - lastRuntimeVisibleAnnotation, - lastRuntimeInvisibleAnnotation, - lastRuntimeVisibleTypeAnnotation, - lastRuntimeInvisibleTypeAnnotation, - result); - symbolTable.putBootstrapMethods(result); - if (moduleWriter != null) { - moduleWriter.putAttributes(result); - } - if (nestHostClassIndex != 0) { - result - .putShort(symbolTable.addConstantUtf8(Constants.NEST_HOST)) - .putInt(2) - .putShort(nestHostClassIndex); - } - if (nestMemberClasses != null) { - result - .putShort(symbolTable.addConstantUtf8(Constants.NEST_MEMBERS)) - .putInt(nestMemberClasses.length + 2) - .putShort(numberOfNestMemberClasses) - .putByteArray(nestMemberClasses.data, 0, nestMemberClasses.length); - } - if (firstAttribute != null) { - firstAttribute.putAttributes(symbolTable, result); - } - - // Third step: replace the ASM specific instructions, if any. - if (hasAsmInstructions) { - return replaceAsmInstructions(result.data, hasFrames); - } else { - return result.data; - } - } - - /** - * Returns the equivalent of the given class file, with the ASM specific instructions replaced - * with standard ones. This is done with a ClassReader -> ClassWriter round trip. - * - * @param classFile a class file containing ASM specific instructions, generated by this - * ClassWriter. - * @param hasFrames whether there is at least one stack map frames in 'classFile'. - * @return an equivalent of 'classFile', with the ASM specific instructions replaced with standard - * ones. - */ - private byte[] replaceAsmInstructions(final byte[] classFile, final boolean hasFrames) { - final Attribute[] attributes = getAttributePrototypes(); - firstField = null; - lastField = null; - firstMethod = null; - lastMethod = null; - lastRuntimeVisibleAnnotation = null; - lastRuntimeInvisibleAnnotation = null; - lastRuntimeVisibleTypeAnnotation = null; - lastRuntimeInvisibleTypeAnnotation = null; - moduleWriter = null; - nestHostClassIndex = 0; - numberOfNestMemberClasses = 0; - nestMemberClasses = null; - firstAttribute = null; - compute = hasFrames ? MethodWriter.COMPUTE_INSERTED_FRAMES : MethodWriter.COMPUTE_NOTHING; - new ClassReader(classFile, 0, /* checkClassVersion = */ false) - .accept( - this, - attributes, - (hasFrames ? ClassReader.EXPAND_FRAMES : 0) | ClassReader.EXPAND_ASM_INSNS); - return toByteArray(); - } - - /** - * Returns the prototypes of the attributes used by this class, its fields and its methods. - * - * @return the prototypes of the attributes used by this class, its fields and its methods. - */ - private Attribute[] getAttributePrototypes() { - Attribute.Set attributePrototypes = new Attribute.Set(); - attributePrototypes.addAttributes(firstAttribute); - FieldWriter fieldWriter = firstField; - while (fieldWriter != null) { - fieldWriter.collectAttributePrototypes(attributePrototypes); - fieldWriter = (FieldWriter) fieldWriter.fv; - } - MethodWriter methodWriter = firstMethod; - while (methodWriter != null) { - methodWriter.collectAttributePrototypes(attributePrototypes); - methodWriter = (MethodWriter) methodWriter.mv; - } - return attributePrototypes.toArray(); - } - - // ----------------------------------------------------------------------------------------------- - // Utility methods: constant pool management for Attribute sub classes - // ----------------------------------------------------------------------------------------------- - - /** - * Adds a number or string constant to the constant pool of the class being build. Does nothing if - * the constant pool already contains a similar item. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param value the value of the constant to be added to the constant pool. This parameter must be - * an {@link Integer}, a {@link Float}, a {@link Long}, a {@link Double} or a {@link String}. - * @return the index of a new or already existing constant item with the given value. - */ - public int newConst(final Object value) { - return symbolTable.addConstant(value).index; - } - - /** - * Adds an UTF8 string to the constant pool of the class being build. Does nothing if the constant - * pool already contains a similar item. This method is intended for {@link Attribute} sub - * classes, and is normally not needed by class generators or adapters. - * - * @param value the String value. - * @return the index of a new or already existing UTF8 item. - */ - // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). - public int newUTF8(final String value) { - return symbolTable.addConstantUtf8(value); - } - - /** - * Adds a class reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param value the internal name of the class. - * @return the index of a new or already existing class reference item. - */ - public int newClass(final String value) { - return symbolTable.addConstantClass(value).index; - } - - /** - * Adds a method type reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param methodDescriptor method descriptor of the method type. - * @return the index of a new or already existing method type reference item. - */ - public int newMethodType(final String methodDescriptor) { - return symbolTable.addConstantMethodType(methodDescriptor).index; - } - - /** - * Adds a module reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param moduleName name of the module. - * @return the index of a new or already existing module reference item. - */ - public int newModule(final String moduleName) { - return symbolTable.addConstantModule(moduleName).index; - } - - /** - * Adds a package reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param packageName name of the package in its internal form. - * @return the index of a new or already existing module reference item. - */ - public int newPackage(final String packageName) { - return symbolTable.addConstantPackage(packageName).index; - } - - /** - * Adds a handle to the constant pool of the class being build. Does nothing if the constant pool - * already contains a similar item. This method is intended for {@link Attribute} sub classes, - * and is normally not needed by class generators or adapters. - * - * @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, {@link - * Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link - * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, - * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. - * @param owner the internal name of the field or method owner class. - * @param name the name of the field or method. - * @param descriptor the descriptor of the field or method. - * @return the index of a new or already existing method type reference item. - * @deprecated this method is superseded by {@link #newHandle(int, String, String, String, - * boolean)}. - */ - @Deprecated - public int newHandle( - final int tag, final String owner, final String name, final String descriptor) { - return newHandle(tag, owner, name, descriptor, tag == Opcodes.H_INVOKEINTERFACE); - } - - /** - * Adds a handle to the constant pool of the class being build. Does nothing if the constant pool - * already contains a similar item. This method is intended for {@link Attribute} sub classes, - * and is normally not needed by class generators or adapters. - * - * @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, {@link - * Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link - * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, - * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. - * @param owner the internal name of the field or method owner class. - * @param name the name of the field or method. - * @param descriptor the descriptor of the field or method. - * @param isInterface true if the owner is an interface. - * @return the index of a new or already existing method type reference item. - */ - public int newHandle( - final int tag, - final String owner, - final String name, - final String descriptor, - final boolean isInterface) { - return symbolTable.addConstantMethodHandle(tag, owner, name, descriptor, isInterface).index; - } - - /** - * Adds a dynamic constant reference to the constant pool of the class being build. Does nothing - * if the constant pool already contains a similar item. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param name name of the invoked method. - * @param descriptor field descriptor of the constant type. - * @param bootstrapMethodHandle the bootstrap method. - * @param bootstrapMethodArguments the bootstrap method constant arguments. - * @return the index of a new or already existing dynamic constant reference item. - */ - public int newConstantDynamic( - final String name, - final String descriptor, - final Handle bootstrapMethodHandle, - final Object... bootstrapMethodArguments) { - return symbolTable.addConstantDynamic( - name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments) - .index; - } - - /** - * Adds an invokedynamic reference to the constant pool of the class being build. Does nothing if - * the constant pool already contains a similar item. This method is intended for {@link - * Attribute} sub classes, and is normally not needed by class generators or adapters. - * - * @param name name of the invoked method. - * @param descriptor descriptor of the invoke method. - * @param bootstrapMethodHandle the bootstrap method. - * @param bootstrapMethodArguments the bootstrap method constant arguments. - * @return the index of a new or already existing invokedynamic reference item. - */ - public int newInvokeDynamic( - final String name, - final String descriptor, - final Handle bootstrapMethodHandle, - final Object... bootstrapMethodArguments) { - return symbolTable.addConstantInvokeDynamic( - name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments) - .index; - } - - /** - * Adds a field reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param owner the internal name of the field's owner class. - * @param name the field's name. - * @param descriptor the field's descriptor. - * @return the index of a new or already existing field reference item. - */ - public int newField(final String owner, final String name, final String descriptor) { - return symbolTable.addConstantFieldref(owner, name, descriptor).index; - } - - /** - * Adds a method reference to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param owner the internal name of the method's owner class. - * @param name the method's name. - * @param descriptor the method's descriptor. - * @param isInterface {@literal true} if {@code owner} is an interface. - * @return the index of a new or already existing method reference item. - */ - public int newMethod( - final String owner, final String name, final String descriptor, final boolean isInterface) { - return symbolTable.addConstantMethodref(owner, name, descriptor, isInterface).index; - } - - /** - * Adds a name and type to the constant pool of the class being build. Does nothing if the - * constant pool already contains a similar item. This method is intended for {@link Attribute} - * sub classes, and is normally not needed by class generators or adapters. - * - * @param name a name. - * @param descriptor a type descriptor. - * @return the index of a new or already existing name and type item. - */ - public int newNameType(final String name, final String descriptor) { - return symbolTable.addConstantNameAndType(name, descriptor); - } - - // ----------------------------------------------------------------------------------------------- - // Default method to compute common super classes when computing stack map frames - // ----------------------------------------------------------------------------------------------- - - /** - * Returns the common super type of the two given types. The default implementation of this method - * loads the two given classes and uses the java.lang.Class methods to find the common - * super class. It can be overridden to compute this common super type in other ways, in - * particular without actually loading any class, or to take into account the class that is - * currently being generated by this ClassWriter, which can of course not be loaded since it is - * under construction. - * - * @param type1 the internal name of a class. - * @param type2 the internal name of another class. - * @return the internal name of the common super class of the two given classes. - */ - protected String getCommonSuperClass(final String type1, final String type2) { - ClassLoader classLoader = getClassLoader(); - Class class1; - try { - class1 = Class.forName(type1.replace('/', '.'), false, classLoader); - } catch (ClassNotFoundException e) { - throw new TypeNotPresentException(type1, e); - } - Class class2; - try { - class2 = Class.forName(type2.replace('/', '.'), false, classLoader); - } catch (ClassNotFoundException e) { - throw new TypeNotPresentException(type2, e); - } - if (class1.isAssignableFrom(class2)) { - return type1; - } - if (class2.isAssignableFrom(class1)) { - return type2; - } - if (class1.isInterface() || class2.isInterface()) { - return "java/lang/Object"; - } else { - do { - class1 = class1.getSuperclass(); - } while (!class1.isAssignableFrom(class2)); - return class1.getName().replace('.', '/'); - } - } - - /** - * Returns the {@link ClassLoader} to be used by the default implementation of {@link - * #getCommonSuperClass(String, String)}, that of this {@link ClassWriter}'s runtime type by - * default. - * - * @return ClassLoader - */ - protected ClassLoader getClassLoader() { - return getClass().getClassLoader(); - } +// ASM: a very small and fast Java bytecode manipulation framework +// Copyright (c) 2000-2011 INRIA, France Telecom +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 3. Neither the name of the copyright holders nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +// THE POSSIBILITY OF SUCH DAMAGE. +package org.objectweb.asm; + +/** + * A {@link ClassVisitor} that generates a corresponding ClassFile structure, as defined in the Java + * Virtual Machine Specification (JVMS). It can be used alone, to generate a Java class "from + * scratch", or with one or more {@link ClassReader} and adapter {@link ClassVisitor} to generate a + * modified class from one or more existing Java classes. + * + * @see JVMS 4 + * @author Eric Bruneton + */ +public class ClassWriter extends ClassVisitor { + + /** + * A flag to automatically compute the maximum stack size and the maximum number of local + * variables of methods. If this flag is set, then the arguments of the {@link + * MethodVisitor#visitMaxs} method of the {@link MethodVisitor} returned by the {@link + * #visitMethod} method will be ignored, and computed automatically from the signature and the + * bytecode of each method. + * + *

Note: for classes whose version is {@link Opcodes#V1_7} of more, this option requires + * valid stack map frames. The maximum stack size is then computed from these frames, and from the + * bytecode instructions in between. If stack map frames are not present or must be recomputed, + * used {@link #COMPUTE_FRAMES} instead. + * + * @see #ClassWriter(int) + */ + public static final int COMPUTE_MAXS = 1; + + /** + * A flag to automatically compute the stack map frames of methods from scratch. If this flag is + * set, then the calls to the {@link MethodVisitor#visitFrame} method are ignored, and the stack + * map frames are recomputed from the methods bytecode. The arguments of the {@link + * MethodVisitor#visitMaxs} method are also ignored and recomputed from the bytecode. In other + * words, {@link #COMPUTE_FRAMES} implies {@link #COMPUTE_MAXS}. + * + * @see #ClassWriter(int) + */ + public static final int COMPUTE_FRAMES = 2; + + // Note: fields are ordered as in the ClassFile structure, and those related to attributes are + // ordered as in Section 4.7 of the JVMS. + + /** + * The minor_version and major_version fields of the JVMS ClassFile structure. minor_version is + * stored in the 16 most significant bits, and major_version in the 16 least significant bits. + */ + private int version; + + /** The symbol table for this class (contains the constant_pool and the BootstrapMethods). */ + private final SymbolTable symbolTable; + + /** + * The access_flags field of the JVMS ClassFile structure. This field can contain ASM specific + * access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the + * ClassFile structure. + */ + private int accessFlags; + + /** The this_class field of the JVMS ClassFile structure. */ + private int thisClass; + + /** The super_class field of the JVMS ClassFile structure. */ + private int superClass; + + /** The interface_count field of the JVMS ClassFile structure. */ + private int interfaceCount; + + /** The 'interfaces' array of the JVMS ClassFile structure. */ + private int[] interfaces; + + /** + * The fields of this class, stored in a linked list of {@link FieldWriter} linked via their + * {@link FieldWriter#fv} field. This field stores the first element of this list. + */ + private FieldWriter firstField; + + /** + * The fields of this class, stored in a linked list of {@link FieldWriter} linked via their + * {@link FieldWriter#fv} field. This field stores the last element of this list. + */ + private FieldWriter lastField; + + /** + * The methods of this class, stored in a linked list of {@link MethodWriter} linked via their + * {@link MethodWriter#mv} field. This field stores the first element of this list. + */ + private MethodWriter firstMethod; + + /** + * The methods of this class, stored in a linked list of {@link MethodWriter} linked via their + * {@link MethodWriter#mv} field. This field stores the last element of this list. + */ + private MethodWriter lastMethod; + + /** The number_of_classes field of the InnerClasses attribute, or 0. */ + private int numberOfInnerClasses; + + /** The 'classes' array of the InnerClasses attribute, or {@literal null}. */ + private ByteVector innerClasses; + + /** The class_index field of the EnclosingMethod attribute, or 0. */ + private int enclosingClassIndex; + + /** The method_index field of the EnclosingMethod attribute. */ + private int enclosingMethodIndex; + + /** The signature_index field of the Signature attribute, or 0. */ + private int signatureIndex; + + /** The source_file_index field of the SourceFile attribute, or 0. */ + private int sourceFileIndex; + + /** The debug_extension field of the SourceDebugExtension attribute, or {@literal null}. */ + private ByteVector debugExtension; + + /** + * The last runtime visible annotation of this class. The previous ones can be accessed with the + * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. + */ + private AnnotationWriter lastRuntimeVisibleAnnotation; + + /** + * The last runtime invisible annotation of this class. The previous ones can be accessed with the + * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. + */ + private AnnotationWriter lastRuntimeInvisibleAnnotation; + + /** + * The last runtime visible type annotation of this class. The previous ones can be accessed with + * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. + */ + private AnnotationWriter lastRuntimeVisibleTypeAnnotation; + + /** + * The last runtime invisible type annotation of this class. The previous ones can be accessed + * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. + */ + private AnnotationWriter lastRuntimeInvisibleTypeAnnotation; + + /** The Module attribute of this class, or {@literal null}. */ + private ModuleWriter moduleWriter; + + /** The host_class_index field of the NestHost attribute, or 0. */ + private int nestHostClassIndex; + + /** The number_of_classes field of the NestMembers attribute, or 0. */ + private int numberOfNestMemberClasses; + + /** The 'classes' array of the NestMembers attribute, or {@literal null}. */ + private ByteVector nestMemberClasses; + + /** + * The first non standard attribute of this class. The next ones can be accessed with the {@link + * Attribute#nextAttribute} field. May be {@literal null}. + * + *

WARNING: this list stores the attributes in the reverse order of their visit. + * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link + * #toByteArray} method writes the attributes in the order defined by this list, i.e. in the + * reverse order specified by the user. + */ + private Attribute firstAttribute; + + /** + * Indicates what must be automatically computed in {@link MethodWriter}. Must be one of {@link + * MethodWriter#COMPUTE_NOTHING}, {@link MethodWriter#COMPUTE_MAX_STACK_AND_LOCAL}, {@link + * MethodWriter#COMPUTE_INSERTED_FRAMES}, or {@link MethodWriter#COMPUTE_ALL_FRAMES}. + */ + private int compute; + + // ----------------------------------------------------------------------------------------------- + // Constructor + // ----------------------------------------------------------------------------------------------- + + /** + * Constructs a new {@link ClassWriter} object. + * + * @param flags option flags that can be used to modify the default behavior of this class. Must + * be zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. + */ + public ClassWriter(final int flags) { + this(null, flags); + } + + /** + * Constructs a new {@link ClassWriter} object and enables optimizations for "mostly add" bytecode + * transformations. These optimizations are the following: + * + *

    + *
  • The constant pool and bootstrap methods from the original class are copied as is in the + * new class, which saves time. New constant pool entries and new bootstrap methods will be + * added at the end if necessary, but unused constant pool entries or bootstrap methods + * won't be removed. + *
  • Methods that are not transformed are copied as is in the new class, directly from the + * original class bytecode (i.e. without emitting visit events for all the method + * instructions), which saves a lot of time. Untransformed methods are detected by + * the fact that the {@link ClassReader} receives {@link MethodVisitor} objects that come + * from a {@link ClassWriter} (and not from any other {@link ClassVisitor} instance). + *
+ * + * @param classReader the {@link ClassReader} used to read the original class. It will be used to + * copy the entire constant pool and bootstrap methods from the original class and also to + * copy other fragments of original bytecode where applicable. + * @param flags option flags that can be used to modify the default behavior of this class.Must be + * zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. These option flags do + * not affect methods that are copied as is in the new class. This means that neither the + * maximum stack size nor the stack frames will be computed for these methods. + */ + public ClassWriter(final ClassReader classReader, final int flags) { + super(Opcodes.ASM7); + symbolTable = classReader == null ? new SymbolTable(this) : new SymbolTable(this, classReader); + if ((flags & COMPUTE_FRAMES) != 0) { + this.compute = MethodWriter.COMPUTE_ALL_FRAMES; + } else if ((flags & COMPUTE_MAXS) != 0) { + this.compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL; + } else { + this.compute = MethodWriter.COMPUTE_NOTHING; + } + } + + // ----------------------------------------------------------------------------------------------- + // Implementation of the ClassVisitor abstract class + // ----------------------------------------------------------------------------------------------- + + @Override + public final void visit( + final int version, + final int access, + final String name, + final String signature, + final String superName, + final String[] interfaces) + { + this.version = version; + + //replace all pre jre minor versions to one that's outside of the old format + if((version & 0xFFFF) == 45 && (version >>> 16) <= 2) + { + this.version = (3 << 16) | 45; + } + this.accessFlags = access; + this.thisClass = symbolTable.setMajorVersionAndClassName(this.version & 0xFFFF, name); + if (signature != null) { + this.signatureIndex = symbolTable.addConstantUtf8(signature); + } + this.superClass = superName == null ? 0 : symbolTable.addConstantClass(superName).index; + if (interfaces != null && interfaces.length > 0) { + interfaceCount = interfaces.length; + this.interfaces = new int[interfaceCount]; + for (int i = 0; i < interfaceCount; ++i) { + this.interfaces[i] = symbolTable.addConstantClass(interfaces[i]).index; + } + } + if (compute == MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL && (this.version & 0xFFFF) >= Opcodes.V1_7) { + compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES; + } + } + + @Override + public final void visitSource(final String file, final String debug) { + if (file != null) { + sourceFileIndex = symbolTable.addConstantUtf8(file); + } + if (debug != null) { + debugExtension = new ByteVector().encodeUtf8(debug, 0, Integer.MAX_VALUE); + } + } + + @Override + public final ModuleVisitor visitModule( + final String name, final int access, final String version) { + return moduleWriter = + new ModuleWriter( + symbolTable, + symbolTable.addConstantModule(name).index, + access, + version == null ? 0 : symbolTable.addConstantUtf8(version)); + } + + @Override + public void visitNestHost(final String nestHost) { + nestHostClassIndex = symbolTable.addConstantClass(nestHost).index; + } + + @Override + public final void visitOuterClass( + final String owner, final String name, final String descriptor) { + enclosingClassIndex = symbolTable.addConstantClass(owner).index; + if (name != null && descriptor != null) { + enclosingMethodIndex = symbolTable.addConstantNameAndType(name, descriptor); + } + } + + @Override + public final AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { + if (visible) { + return lastRuntimeVisibleAnnotation = + AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation); + } else { + return lastRuntimeInvisibleAnnotation = + AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation); + } + } + + @Override + public final AnnotationVisitor visitTypeAnnotation( + final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { + if (visible) { + return lastRuntimeVisibleTypeAnnotation = + AnnotationWriter.create( + symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation); + } else { + return lastRuntimeInvisibleTypeAnnotation = + AnnotationWriter.create( + symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation); + } + } + + @Override + public final void visitAttribute(final Attribute attribute) { + // Store the attributes in the reverse order of their visit by this method. + attribute.nextAttribute = firstAttribute; + firstAttribute = attribute; + } + + @Override + public void visitNestMember(final String nestMember) { + if (nestMemberClasses == null) { + nestMemberClasses = new ByteVector(); + } + ++numberOfNestMemberClasses; + nestMemberClasses.putShort(symbolTable.addConstantClass(nestMember).index); + } + + @Override + public final void visitInnerClass( + final String name, final String outerName, final String innerName, final int access) { + if (innerClasses == null) { + innerClasses = new ByteVector(); + } + // Section 4.7.6 of the JVMS states "Every CONSTANT_Class_info entry in the constant_pool table + // which represents a class or interface C that is not a package member must have exactly one + // corresponding entry in the classes array". To avoid duplicates we keep track in the info + // field of the Symbol of each CONSTANT_Class_info entry C whether an inner class entry has + // already been added for C. If so, we store the index of this inner class entry (plus one) in + // the info field. This trick allows duplicate detection in O(1) time. + Symbol nameSymbol = symbolTable.addConstantClass(name); + if (nameSymbol.info == 0) { + ++numberOfInnerClasses; + innerClasses.putShort(nameSymbol.index); + innerClasses.putShort(outerName == null ? 0 : symbolTable.addConstantClass(outerName).index); + innerClasses.putShort(innerName == null ? 0 : symbolTable.addConstantUtf8(innerName)); + innerClasses.putShort(access); + nameSymbol.info = numberOfInnerClasses; + } + // Else, compare the inner classes entry nameSymbol.info - 1 with the arguments of this method + // and throw an exception if there is a difference? + } + + @Override + public final FieldVisitor visitField( + final int access, + final String name, + final String descriptor, + final String signature, + final Object value) { + FieldWriter fieldWriter = + new FieldWriter(symbolTable, access, name, descriptor, signature, value); + if (firstField == null) { + firstField = fieldWriter; + } else { + lastField.fv = fieldWriter; + } + return lastField = fieldWriter; + } + + @Override + public final MethodVisitor visitMethod( + final int access, + final String name, + final String descriptor, + final String signature, + final String[] exceptions) { + MethodWriter methodWriter = + new MethodWriter(symbolTable, access, name, descriptor, signature, exceptions, compute); + if (firstMethod == null) { + firstMethod = methodWriter; + } else { + lastMethod.mv = methodWriter; + } + return lastMethod = methodWriter; + } + + @Override + public final void visitEnd() { + // Nothing to do. + } + + // ----------------------------------------------------------------------------------------------- + // Other public methods + // ----------------------------------------------------------------------------------------------- + + /** + * Returns the content of the class file that was built by this ClassWriter. + * + * @return the binary content of the JVMS ClassFile structure that was built by this ClassWriter. + * @throws ClassTooLargeException if the constant pool of the class is too large. + * @throws MethodTooLargeException if the Code attribute of a method is too large. + */ + public byte[] toByteArray() { + // First step: compute the size in bytes of the ClassFile structure. + // The magic field uses 4 bytes, 10 mandatory fields (minor_version, major_version, + // constant_pool_count, access_flags, this_class, super_class, interfaces_count, fields_count, + // methods_count and attributes_count) use 2 bytes each, and each interface uses 2 bytes too. + int size = 24 + 2 * interfaceCount; + int fieldsCount = 0; + FieldWriter fieldWriter = firstField; + while (fieldWriter != null) { + ++fieldsCount; + size += fieldWriter.computeFieldInfoSize(); + fieldWriter = (FieldWriter) fieldWriter.fv; + } + int methodsCount = 0; + MethodWriter methodWriter = firstMethod; + while (methodWriter != null) { + ++methodsCount; + size += methodWriter.computeMethodInfoSize(); + methodWriter = (MethodWriter) methodWriter.mv; + } + // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. + int attributesCount = 0; + if (innerClasses != null) { + ++attributesCount; + size += 8 + innerClasses.length; + symbolTable.addConstantUtf8(Constants.INNER_CLASSES); + } + if (enclosingClassIndex != 0) { + ++attributesCount; + size += 10; + symbolTable.addConstantUtf8(Constants.ENCLOSING_METHOD); + } + if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && (version & 0xFFFF) < Opcodes.V1_5) { + ++attributesCount; + size += 6; + symbolTable.addConstantUtf8(Constants.SYNTHETIC); + } + if (signatureIndex != 0) { + ++attributesCount; + size += 8; + symbolTable.addConstantUtf8(Constants.SIGNATURE); + } + if (sourceFileIndex != 0) { + ++attributesCount; + size += 8; + symbolTable.addConstantUtf8(Constants.SOURCE_FILE); + } + if (debugExtension != null) { + ++attributesCount; + size += 6 + debugExtension.length; + symbolTable.addConstantUtf8(Constants.SOURCE_DEBUG_EXTENSION); + } + if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { + ++attributesCount; + size += 6; + symbolTable.addConstantUtf8(Constants.DEPRECATED); + } + if (lastRuntimeVisibleAnnotation != null) { + ++attributesCount; + size += + lastRuntimeVisibleAnnotation.computeAnnotationsSize( + Constants.RUNTIME_VISIBLE_ANNOTATIONS); + } + if (lastRuntimeInvisibleAnnotation != null) { + ++attributesCount; + size += + lastRuntimeInvisibleAnnotation.computeAnnotationsSize( + Constants.RUNTIME_INVISIBLE_ANNOTATIONS); + } + if (lastRuntimeVisibleTypeAnnotation != null) { + ++attributesCount; + size += + lastRuntimeVisibleTypeAnnotation.computeAnnotationsSize( + Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS); + } + if (lastRuntimeInvisibleTypeAnnotation != null) { + ++attributesCount; + size += + lastRuntimeInvisibleTypeAnnotation.computeAnnotationsSize( + Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); + } + if (symbolTable.computeBootstrapMethodsSize() > 0) { + ++attributesCount; + size += symbolTable.computeBootstrapMethodsSize(); + } + if (moduleWriter != null) { + attributesCount += moduleWriter.getAttributeCount(); + size += moduleWriter.computeAttributesSize(); + } + if (nestHostClassIndex != 0) { + ++attributesCount; + size += 8; + symbolTable.addConstantUtf8(Constants.NEST_HOST); + } + if (nestMemberClasses != null) { + ++attributesCount; + size += 8 + nestMemberClasses.length; + symbolTable.addConstantUtf8(Constants.NEST_MEMBERS); + } + if (firstAttribute != null) { + attributesCount += firstAttribute.getAttributeCount(); + size += firstAttribute.computeAttributesSize(symbolTable); + } + // IMPORTANT: this must be the last part of the ClassFile size computation, because the previous + // statements can add attribute names to the constant pool, thereby changing its size! + size += symbolTable.getConstantPoolLength(); + int constantPoolCount = symbolTable.getConstantPoolCount(); + if (constantPoolCount > 0xFFFF) { + throw new ClassTooLargeException(symbolTable.getClassName(), constantPoolCount); + } + + // Second step: allocate a ByteVector of the correct size (in order to avoid any array copy in + // dynamic resizes) and fill it with the ClassFile content. + ByteVector result = new ByteVector(size); + result.putInt(0xCAFEBABE).putInt(version); + symbolTable.putConstantPool(result); + int mask = (version & 0xFFFF) < Opcodes.V1_5 ? Opcodes.ACC_SYNTHETIC : 0; + result.putShort(accessFlags & ~mask).putShort(thisClass).putShort(superClass); + result.putShort(interfaceCount); + for (int i = 0; i < interfaceCount; ++i) { + result.putShort(interfaces[i]); + } + result.putShort(fieldsCount); + fieldWriter = firstField; + while (fieldWriter != null) { + fieldWriter.putFieldInfo(result); + fieldWriter = (FieldWriter) fieldWriter.fv; + } + result.putShort(methodsCount); + boolean hasFrames = false; + boolean hasAsmInstructions = false; + methodWriter = firstMethod; + while (methodWriter != null) { + hasFrames |= methodWriter.hasFrames(); + hasAsmInstructions |= methodWriter.hasAsmInstructions(); + methodWriter.putMethodInfo(result); + methodWriter = (MethodWriter) methodWriter.mv; + } + // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. + result.putShort(attributesCount); + if (innerClasses != null) { + result + .putShort(symbolTable.addConstantUtf8(Constants.INNER_CLASSES)) + .putInt(innerClasses.length + 2) + .putShort(numberOfInnerClasses) + .putByteArray(innerClasses.data, 0, innerClasses.length); + } + if (enclosingClassIndex != 0) { + result + .putShort(symbolTable.addConstantUtf8(Constants.ENCLOSING_METHOD)) + .putInt(4) + .putShort(enclosingClassIndex) + .putShort(enclosingMethodIndex); + } + if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && (version & 0xFFFF) < Opcodes.V1_5) { + result.putShort(symbolTable.addConstantUtf8(Constants.SYNTHETIC)).putInt(0); + } + if (signatureIndex != 0) { + result + .putShort(symbolTable.addConstantUtf8(Constants.SIGNATURE)) + .putInt(2) + .putShort(signatureIndex); + } + if (sourceFileIndex != 0) { + result + .putShort(symbolTable.addConstantUtf8(Constants.SOURCE_FILE)) + .putInt(2) + .putShort(sourceFileIndex); + } + if (debugExtension != null) { + int length = debugExtension.length; + result + .putShort(symbolTable.addConstantUtf8(Constants.SOURCE_DEBUG_EXTENSION)) + .putInt(length) + .putByteArray(debugExtension.data, 0, length); + } + if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { + result.putShort(symbolTable.addConstantUtf8(Constants.DEPRECATED)).putInt(0); + } + AnnotationWriter.putAnnotations( + symbolTable, + lastRuntimeVisibleAnnotation, + lastRuntimeInvisibleAnnotation, + lastRuntimeVisibleTypeAnnotation, + lastRuntimeInvisibleTypeAnnotation, + result); + symbolTable.putBootstrapMethods(result); + if (moduleWriter != null) { + moduleWriter.putAttributes(result); + } + if (nestHostClassIndex != 0) { + result + .putShort(symbolTable.addConstantUtf8(Constants.NEST_HOST)) + .putInt(2) + .putShort(nestHostClassIndex); + } + if (nestMemberClasses != null) { + result + .putShort(symbolTable.addConstantUtf8(Constants.NEST_MEMBERS)) + .putInt(nestMemberClasses.length + 2) + .putShort(numberOfNestMemberClasses) + .putByteArray(nestMemberClasses.data, 0, nestMemberClasses.length); + } + if (firstAttribute != null) { + firstAttribute.putAttributes(symbolTable, result); + } + + // Third step: replace the ASM specific instructions, if any. + if (hasAsmInstructions) { + return replaceAsmInstructions(result.data, hasFrames); + } else { + return result.data; + } + } + + /** + * Returns the equivalent of the given class file, with the ASM specific instructions replaced + * with standard ones. This is done with a ClassReader -> ClassWriter round trip. + * + * @param classFile a class file containing ASM specific instructions, generated by this + * ClassWriter. + * @param hasFrames whether there is at least one stack map frames in 'classFile'. + * @return an equivalent of 'classFile', with the ASM specific instructions replaced with standard + * ones. + */ + private byte[] replaceAsmInstructions(final byte[] classFile, final boolean hasFrames) { + final Attribute[] attributes = getAttributePrototypes(); + firstField = null; + lastField = null; + firstMethod = null; + lastMethod = null; + lastRuntimeVisibleAnnotation = null; + lastRuntimeInvisibleAnnotation = null; + lastRuntimeVisibleTypeAnnotation = null; + lastRuntimeInvisibleTypeAnnotation = null; + moduleWriter = null; + nestHostClassIndex = 0; + numberOfNestMemberClasses = 0; + nestMemberClasses = null; + firstAttribute = null; + compute = hasFrames ? MethodWriter.COMPUTE_INSERTED_FRAMES : MethodWriter.COMPUTE_NOTHING; + new ClassReader(classFile, 0, /* checkClassVersion = */ false) + .accept( + this, + attributes, + (hasFrames ? ClassReader.EXPAND_FRAMES : 0) | ClassReader.EXPAND_ASM_INSNS); + return toByteArray(); + } + + /** + * Returns the prototypes of the attributes used by this class, its fields and its methods. + * + * @return the prototypes of the attributes used by this class, its fields and its methods. + */ + private Attribute[] getAttributePrototypes() { + Attribute.Set attributePrototypes = new Attribute.Set(); + attributePrototypes.addAttributes(firstAttribute); + FieldWriter fieldWriter = firstField; + while (fieldWriter != null) { + fieldWriter.collectAttributePrototypes(attributePrototypes); + fieldWriter = (FieldWriter) fieldWriter.fv; + } + MethodWriter methodWriter = firstMethod; + while (methodWriter != null) { + methodWriter.collectAttributePrototypes(attributePrototypes); + methodWriter = (MethodWriter) methodWriter.mv; + } + return attributePrototypes.toArray(); + } + + // ----------------------------------------------------------------------------------------------- + // Utility methods: constant pool management for Attribute sub classes + // ----------------------------------------------------------------------------------------------- + + /** + * Adds a number or string constant to the constant pool of the class being build. Does nothing if + * the constant pool already contains a similar item. This method is intended for {@link + * Attribute} sub classes, and is normally not needed by class generators or adapters. + * + * @param value the value of the constant to be added to the constant pool. This parameter must be + * an {@link Integer}, a {@link Float}, a {@link Long}, a {@link Double} or a {@link String}. + * @return the index of a new or already existing constant item with the given value. + */ + public int newConst(final Object value) { + return symbolTable.addConstant(value).index; + } + + /** + * Adds an UTF8 string to the constant pool of the class being build. Does nothing if the constant + * pool already contains a similar item. This method is intended for {@link Attribute} sub + * classes, and is normally not needed by class generators or adapters. + * + * @param value the String value. + * @return the index of a new or already existing UTF8 item. + */ + // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). + public int newUTF8(final String value) { + return symbolTable.addConstantUtf8(value); + } + + /** + * Adds a class reference to the constant pool of the class being build. Does nothing if the + * constant pool already contains a similar item. This method is intended for {@link Attribute} + * sub classes, and is normally not needed by class generators or adapters. + * + * @param value the internal name of the class. + * @return the index of a new or already existing class reference item. + */ + public int newClass(final String value) { + return symbolTable.addConstantClass(value).index; + } + + /** + * Adds a method type reference to the constant pool of the class being build. Does nothing if the + * constant pool already contains a similar item. This method is intended for {@link Attribute} + * sub classes, and is normally not needed by class generators or adapters. + * + * @param methodDescriptor method descriptor of the method type. + * @return the index of a new or already existing method type reference item. + */ + public int newMethodType(final String methodDescriptor) { + return symbolTable.addConstantMethodType(methodDescriptor).index; + } + + /** + * Adds a module reference to the constant pool of the class being build. Does nothing if the + * constant pool already contains a similar item. This method is intended for {@link Attribute} + * sub classes, and is normally not needed by class generators or adapters. + * + * @param moduleName name of the module. + * @return the index of a new or already existing module reference item. + */ + public int newModule(final String moduleName) { + return symbolTable.addConstantModule(moduleName).index; + } + + /** + * Adds a package reference to the constant pool of the class being build. Does nothing if the + * constant pool already contains a similar item. This method is intended for {@link Attribute} + * sub classes, and is normally not needed by class generators or adapters. + * + * @param packageName name of the package in its internal form. + * @return the index of a new or already existing module reference item. + */ + public int newPackage(final String packageName) { + return symbolTable.addConstantPackage(packageName).index; + } + + /** + * Adds a handle to the constant pool of the class being build. Does nothing if the constant pool + * already contains a similar item. This method is intended for {@link Attribute} sub classes, + * and is normally not needed by class generators or adapters. + * + * @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, {@link + * Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link + * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, + * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. + * @param owner the internal name of the field or method owner class. + * @param name the name of the field or method. + * @param descriptor the descriptor of the field or method. + * @return the index of a new or already existing method type reference item. + * @deprecated this method is superseded by {@link #newHandle(int, String, String, String, + * boolean)}. + */ + @Deprecated + public int newHandle( + final int tag, final String owner, final String name, final String descriptor) { + return newHandle(tag, owner, name, descriptor, tag == Opcodes.H_INVOKEINTERFACE); + } + + /** + * Adds a handle to the constant pool of the class being build. Does nothing if the constant pool + * already contains a similar item. This method is intended for {@link Attribute} sub classes, + * and is normally not needed by class generators or adapters. + * + * @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, {@link + * Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link + * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, + * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. + * @param owner the internal name of the field or method owner class. + * @param name the name of the field or method. + * @param descriptor the descriptor of the field or method. + * @param isInterface true if the owner is an interface. + * @return the index of a new or already existing method type reference item. + */ + public int newHandle( + final int tag, + final String owner, + final String name, + final String descriptor, + final boolean isInterface) { + return symbolTable.addConstantMethodHandle(tag, owner, name, descriptor, isInterface).index; + } + + /** + * Adds a dynamic constant reference to the constant pool of the class being build. Does nothing + * if the constant pool already contains a similar item. This method is intended for {@link + * Attribute} sub classes, and is normally not needed by class generators or adapters. + * + * @param name name of the invoked method. + * @param descriptor field descriptor of the constant type. + * @param bootstrapMethodHandle the bootstrap method. + * @param bootstrapMethodArguments the bootstrap method constant arguments. + * @return the index of a new or already existing dynamic constant reference item. + */ + public int newConstantDynamic( + final String name, + final String descriptor, + final Handle bootstrapMethodHandle, + final Object... bootstrapMethodArguments) { + return symbolTable.addConstantDynamic( + name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments) + .index; + } + + /** + * Adds an invokedynamic reference to the constant pool of the class being build. Does nothing if + * the constant pool already contains a similar item. This method is intended for {@link + * Attribute} sub classes, and is normally not needed by class generators or adapters. + * + * @param name name of the invoked method. + * @param descriptor descriptor of the invoke method. + * @param bootstrapMethodHandle the bootstrap method. + * @param bootstrapMethodArguments the bootstrap method constant arguments. + * @return the index of a new or already existing invokedynamic reference item. + */ + public int newInvokeDynamic( + final String name, + final String descriptor, + final Handle bootstrapMethodHandle, + final Object... bootstrapMethodArguments) { + return symbolTable.addConstantInvokeDynamic( + name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments) + .index; + } + + /** + * Adds a field reference to the constant pool of the class being build. Does nothing if the + * constant pool already contains a similar item. This method is intended for {@link Attribute} + * sub classes, and is normally not needed by class generators or adapters. + * + * @param owner the internal name of the field's owner class. + * @param name the field's name. + * @param descriptor the field's descriptor. + * @return the index of a new or already existing field reference item. + */ + public int newField(final String owner, final String name, final String descriptor) { + return symbolTable.addConstantFieldref(owner, name, descriptor).index; + } + + /** + * Adds a method reference to the constant pool of the class being build. Does nothing if the + * constant pool already contains a similar item. This method is intended for {@link Attribute} + * sub classes, and is normally not needed by class generators or adapters. + * + * @param owner the internal name of the method's owner class. + * @param name the method's name. + * @param descriptor the method's descriptor. + * @param isInterface {@literal true} if {@code owner} is an interface. + * @return the index of a new or already existing method reference item. + */ + public int newMethod( + final String owner, final String name, final String descriptor, final boolean isInterface) { + return symbolTable.addConstantMethodref(owner, name, descriptor, isInterface).index; + } + + /** + * Adds a name and type to the constant pool of the class being build. Does nothing if the + * constant pool already contains a similar item. This method is intended for {@link Attribute} + * sub classes, and is normally not needed by class generators or adapters. + * + * @param name a name. + * @param descriptor a type descriptor. + * @return the index of a new or already existing name and type item. + */ + public int newNameType(final String name, final String descriptor) { + return symbolTable.addConstantNameAndType(name, descriptor); + } + + // ----------------------------------------------------------------------------------------------- + // Default method to compute common super classes when computing stack map frames + // ----------------------------------------------------------------------------------------------- + + /** + * Returns the common super type of the two given types. The default implementation of this method + * loads the two given classes and uses the java.lang.Class methods to find the common + * super class. It can be overridden to compute this common super type in other ways, in + * particular without actually loading any class, or to take into account the class that is + * currently being generated by this ClassWriter, which can of course not be loaded since it is + * under construction. + * + * @param type1 the internal name of a class. + * @param type2 the internal name of another class. + * @return the internal name of the common super class of the two given classes. + */ + protected String getCommonSuperClass(final String type1, final String type2) { + ClassLoader classLoader = getClassLoader(); + Class class1; + try { + class1 = Class.forName(type1.replace('/', '.'), false, classLoader); + } catch (ClassNotFoundException e) { + throw new TypeNotPresentException(type1, e); + } + Class class2; + try { + class2 = Class.forName(type2.replace('/', '.'), false, classLoader); + } catch (ClassNotFoundException e) { + throw new TypeNotPresentException(type2, e); + } + if (class1.isAssignableFrom(class2)) { + return type1; + } + if (class2.isAssignableFrom(class1)) { + return type2; + } + if (class1.isInterface() || class2.isInterface()) { + return "java/lang/Object"; + } else { + do { + class1 = class1.getSuperclass(); + } while (!class1.isAssignableFrom(class2)); + return class1.getName().replace('.', '/'); + } + } + + /** + * Returns the {@link ClassLoader} to be used by the default implementation of {@link + * #getCommonSuperClass(String, String)}, that of this {@link ClassWriter}'s runtime type by + * default. + * + * @return ClassLoader + */ + protected ClassLoader getClassLoader() { + return getClass().getClassLoader(); + } } \ No newline at end of file diff --git a/src/the/bytecode/club/bootloader/AbstractLoaderFactory.java b/src/main/java/the/bytecode/club/bootloader/AbstractLoaderFactory.java similarity index 100% rename from src/the/bytecode/club/bootloader/AbstractLoaderFactory.java rename to src/main/java/the/bytecode/club/bootloader/AbstractLoaderFactory.java diff --git a/src/the/bytecode/club/bootloader/Boot.java b/src/main/java/the/bytecode/club/bootloader/Boot.java similarity index 100% rename from src/the/bytecode/club/bootloader/Boot.java rename to src/main/java/the/bytecode/club/bootloader/Boot.java diff --git a/src/the/bytecode/club/bootloader/ClassPathLoader.java b/src/main/java/the/bytecode/club/bootloader/ClassPathLoader.java similarity index 100% rename from src/the/bytecode/club/bootloader/ClassPathLoader.java rename to src/main/java/the/bytecode/club/bootloader/ClassPathLoader.java diff --git a/src/the/bytecode/club/bootloader/ILoader.java b/src/main/java/the/bytecode/club/bootloader/ILoader.java similarity index 100% rename from src/the/bytecode/club/bootloader/ILoader.java rename to src/main/java/the/bytecode/club/bootloader/ILoader.java diff --git a/src/the/bytecode/club/bootloader/InitialBootScreen.java b/src/main/java/the/bytecode/club/bootloader/InitialBootScreen.java similarity index 100% rename from src/the/bytecode/club/bootloader/InitialBootScreen.java rename to src/main/java/the/bytecode/club/bootloader/InitialBootScreen.java diff --git a/src/the/bytecode/club/bootloader/LibraryClassLoader.java b/src/main/java/the/bytecode/club/bootloader/LibraryClassLoader.java similarity index 100% rename from src/the/bytecode/club/bootloader/LibraryClassLoader.java rename to src/main/java/the/bytecode/club/bootloader/LibraryClassLoader.java diff --git a/src/the/bytecode/club/bootloader/LoaderFactory.java b/src/main/java/the/bytecode/club/bootloader/LoaderFactory.java similarity index 100% rename from src/the/bytecode/club/bootloader/LoaderFactory.java rename to src/main/java/the/bytecode/club/bootloader/LoaderFactory.java diff --git a/src/the/bytecode/club/bootloader/resource/DataContainer.java b/src/main/java/the/bytecode/club/bootloader/resource/DataContainer.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/DataContainer.java rename to src/main/java/the/bytecode/club/bootloader/resource/DataContainer.java diff --git a/src/the/bytecode/club/bootloader/resource/EmptyExternalResource.java b/src/main/java/the/bytecode/club/bootloader/resource/EmptyExternalResource.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/EmptyExternalResource.java rename to src/main/java/the/bytecode/club/bootloader/resource/EmptyExternalResource.java diff --git a/src/the/bytecode/club/bootloader/resource/ExternalLibrary.java b/src/main/java/the/bytecode/club/bootloader/resource/ExternalLibrary.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/ExternalLibrary.java rename to src/main/java/the/bytecode/club/bootloader/resource/ExternalLibrary.java diff --git a/src/the/bytecode/club/bootloader/resource/ExternalResource.java b/src/main/java/the/bytecode/club/bootloader/resource/ExternalResource.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/ExternalResource.java rename to src/main/java/the/bytecode/club/bootloader/resource/ExternalResource.java diff --git a/src/the/bytecode/club/bootloader/resource/JarContents.java b/src/main/java/the/bytecode/club/bootloader/resource/JarContents.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/JarContents.java rename to src/main/java/the/bytecode/club/bootloader/resource/JarContents.java diff --git a/src/the/bytecode/club/bootloader/resource/JarInfo.java b/src/main/java/the/bytecode/club/bootloader/resource/JarInfo.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/JarInfo.java rename to src/main/java/the/bytecode/club/bootloader/resource/JarInfo.java diff --git a/src/the/bytecode/club/bootloader/resource/JarResource.java b/src/main/java/the/bytecode/club/bootloader/resource/JarResource.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/JarResource.java rename to src/main/java/the/bytecode/club/bootloader/resource/JarResource.java diff --git a/src/the/bytecode/club/bootloader/resource/JarType.java b/src/main/java/the/bytecode/club/bootloader/resource/JarType.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/JarType.java rename to src/main/java/the/bytecode/club/bootloader/resource/JarType.java diff --git a/src/the/bytecode/club/bootloader/resource/LocateableJarContents.java b/src/main/java/the/bytecode/club/bootloader/resource/LocateableJarContents.java similarity index 100% rename from src/the/bytecode/club/bootloader/resource/LocateableJarContents.java rename to src/main/java/the/bytecode/club/bootloader/resource/LocateableJarContents.java diff --git a/src/the/bytecode/club/bootloader/util/Base64.java b/src/main/java/the/bytecode/club/bootloader/util/Base64.java similarity index 97% rename from src/the/bytecode/club/bootloader/util/Base64.java rename to src/main/java/the/bytecode/club/bootloader/util/Base64.java index dac91b3f..23704c50 100644 --- a/src/the/bytecode/club/bootloader/util/Base64.java +++ b/src/main/java/the/bytecode/club/bootloader/util/Base64.java @@ -1,932 +1,932 @@ -package the.bytecode.club.bootloader.util; - -import java.io.FilterOutputStream; -import java.io.InputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.*; - -public class Base64 { - - private Base64() {} - - /** - * Returns a {@link Encoder} that encodes using the - * Basic type base64 encoding scheme. - * - * @return A Base64 encoder. - */ - public static Encoder getEncoder() { - return Encoder.RFC4648; - } - - /** - * Returns a {@link Encoder} that encodes using the - * URL and Filename safe type base64 - * encoding scheme. - * - * @return A Base64 encoder. - */ - public static Encoder getUrlEncoder() { - return Encoder.RFC4648_URLSAFE; - } - - /** - * Returns a {@link Encoder} that encodes using the - * MIME type base64 encoding scheme. - * - * @return A Base64 encoder. - */ - public static Encoder getMimeEncoder() { - return Encoder.RFC2045; - } - - /** - * Returns a {@link Encoder} that encodes using the - * MIME type base64 encoding scheme - * with specified line length and line separators. - * - * @param lineLength - * the length of each output line (rounded down to nearest multiple - * of 4). If {@code lineLength <= 0} the output will not be separated - * in lines - * @param lineSeparator - * the line separator for each output line - * - * @return A Base64 encoder. - * - * @throws IllegalArgumentException if {@code lineSeparator} includes any - * character of "The Base64 Alphabet" as specified in Table 1 of - * RFC 2045. - */ - public static Encoder getMimeEncoder(int lineLength, byte[] lineSeparator) { - Objects.requireNonNull(lineSeparator); - int[] base64 = Decoder.fromBase64; - for (byte b : lineSeparator) { - if (base64[b & 0xff] != -1) - throw new IllegalArgumentException( - "Illegal base64 line separator character 0x" + Integer.toString(b, 16)); - } - if (lineLength <= 0) { - return Encoder.RFC4648; - } - return new Encoder(false, lineSeparator, lineLength >> 2 << 2, true); - } - - /** - * Returns a {@link Decoder} that decodes using the - * Basic type base64 encoding scheme. - * - * @return A Base64 decoder. - */ - public static Decoder getDecoder() { - return Decoder.RFC4648; - } - - /** - * Returns a {@link Decoder} that decodes using the - * URL and Filename safe type base64 - * encoding scheme. - * - * @return A Base64 decoder. - */ - public static Decoder getUrlDecoder() { - return Decoder.RFC4648_URLSAFE; - } - - /** - * Returns a {@link Decoder} that decodes using the - * MIME type base64 decoding scheme. - * - * @return A Base64 decoder. - */ - public static Decoder getMimeDecoder() { - return Decoder.RFC2045; - } - - /** - * This class implements an encoder for encoding byte data using - * the Base64 encoding scheme as specified in RFC 4648 and RFC 2045. - * - *

Instances of {@link Encoder} class are safe for use by - * multiple concurrent threads. - * - *

Unless otherwise noted, passing a {@code null} argument to - * a method of this class will cause a - * {@link java.lang.NullPointerException NullPointerException} to - * be thrown. - * - * @see Decoder - * @since 1.8 - */ - public static class Encoder { - - private final byte[] newline; - private final int linemax; - private final boolean isURL; - private final boolean doPadding; - - private Encoder(boolean isURL, byte[] newline, int linemax, boolean doPadding) { - this.isURL = isURL; - this.newline = newline; - this.linemax = linemax; - this.doPadding = doPadding; - } - - /** - * This array is a lookup table that translates 6-bit positive integer - * index values into their "Base64 Alphabet" equivalents as specified - * in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648). - */ - private static final char[] toBase64 = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' - }; - - /** - * It's the lookup table for "URL and Filename safe Base64" as specified - * in Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and - * '_'. This table is used when BASE64_URL is specified. - */ - private static final char[] toBase64URL = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' - }; - - private static final int MIMELINEMAX = 76; - private static final byte[] CRLF = new byte[] {'\r', '\n'}; - - static final Encoder RFC4648 = new Encoder(false, null, -1, true); - static final Encoder RFC4648_URLSAFE = new Encoder(true, null, -1, true); - static final Encoder RFC2045 = new Encoder(false, CRLF, MIMELINEMAX, true); - - private final int outLength(int srclen) { - int len = 0; - if (doPadding) { - len = 4 * ((srclen + 2) / 3); - } else { - int n = srclen % 3; - len = 4 * (srclen / 3) + (n == 0 ? 0 : n + 1); - } - if (linemax > 0) // line separators - len += (len - 1) / linemax * newline.length; - return len; - } - - /** - * Encodes all bytes from the specified byte array into a newly-allocated - * byte array using the {@link Base64} encoding scheme. The returned byte - * array is of the length of the resulting bytes. - * - * @param src - * the byte array to encode - * @return A newly-allocated byte array containing the resulting - * encoded bytes. - */ - public byte[] encode(byte[] src) { - int len = outLength(src.length); // dst array size - byte[] dst = new byte[len]; - int ret = encode0(src, 0, src.length, dst); - if (ret != dst.length) - return Arrays.copyOf(dst, ret); - return dst; - } - - /** - * Encodes all bytes from the specified byte array using the - * {@link Base64} encoding scheme, writing the resulting bytes to the - * given output byte array, starting at offset 0. - * - *

It is the responsibility of the invoker of this method to make - * sure the output byte array {@code dst} has enough space for encoding - * all bytes from the input byte array. No bytes will be written to the - * output byte array if the output byte array is not big enough. - * - * @param src - * the byte array to encode - * @param dst - * the output byte array - * @return The number of bytes written to the output byte array - * - * @throws IllegalArgumentException if {@code dst} does not have enough - * space for encoding all input bytes. - */ - public int encode(byte[] src, byte[] dst) { - int len = outLength(src.length); // dst array size - if (dst.length < len) - throw new IllegalArgumentException( - "Output byte array is too small for encoding all input bytes"); - return encode0(src, 0, src.length, dst); - } - - /** - * Encodes the specified byte array into a String using the {@link Base64} - * encoding scheme. - * - *

This method first encodes all input bytes into a base64 encoded - * byte array and then constructs a new String by using the encoded byte - * array and the {@link java.nio.charset.StandardCharsets#ISO_8859_1 - * ISO-8859-1} charset. - * - *

In other words, an invocation of this method has exactly the same - * effect as invoking - * {@code new String(encode(src), StandardCharsets.ISO_8859_1)}. - * - * @param src - * the byte array to encode - * @return A String containing the resulting Base64 encoded characters - */ - @SuppressWarnings("deprecation") - public String encodeToString(byte[] src) { - byte[] encoded = encode(src); - return new String(encoded, 0, 0, encoded.length); - } - - /** - * Encodes all remaining bytes from the specified byte buffer into - * a newly-allocated ByteBuffer using the {@link Base64} encoding - * scheme. - * - * Upon return, the source buffer's position will be updated to - * its limit; its limit will not have been changed. The returned - * output buffer's position will be zero and its limit will be the - * number of resulting encoded bytes. - * - * @param buffer - * the source ByteBuffer to encode - * @return A newly-allocated byte buffer containing the encoded bytes. - */ - public ByteBuffer encode(ByteBuffer buffer) { - int len = outLength(buffer.remaining()); - byte[] dst = new byte[len]; - int ret = 0; - if (buffer.hasArray()) { - ret = encode0(buffer.array(), - buffer.arrayOffset() + buffer.position(), - buffer.arrayOffset() + buffer.limit(), - dst); - buffer.position(buffer.limit()); - } else { - byte[] src = new byte[buffer.remaining()]; - buffer.get(src); - ret = encode0(src, 0, src.length, dst); - } - if (ret != dst.length) - dst = Arrays.copyOf(dst, ret); - return ByteBuffer.wrap(dst); - } - - /** - * Wraps an output stream for encoding byte data using the {@link Base64} - * encoding scheme. - * - *

It is recommended to promptly close the returned output stream after - * use, during which it will flush all possible leftover bytes to the underlying - * output stream. Closing the returned output stream will close the underlying - * output stream. - * - * @param os - * the output stream. - * @return the output stream for encoding the byte data into the - * specified Base64 encoded format - */ - public OutputStream wrap(OutputStream os) { - Objects.requireNonNull(os); - return new EncOutputStream(os, isURL ? toBase64URL : toBase64, - newline, linemax, doPadding); - } - - /** - * Returns an encoder instance that encodes equivalently to this one, - * but without adding any padding character at the end of the encoded - * byte data. - * - *

The encoding scheme of this encoder instance is unaffected by - * this invocation. The returned encoder instance should be used for - * non-padding encoding operation. - * - * @return an equivalent encoder that encodes without adding any - * padding character at the end - */ - public Encoder withoutPadding() { - if (!doPadding) - return this; - return new Encoder(isURL, newline, linemax, false); - } - - private int encode0(byte[] src, int off, int end, byte[] dst) { - char[] base64 = isURL ? toBase64URL : toBase64; - int sp = off; - int slen = (end - off) / 3 * 3; - int sl = off + slen; - if (linemax > 0 && slen > linemax / 4 * 3) - slen = linemax / 4 * 3; - int dp = 0; - while (sp < sl) { - int sl0 = Math.min(sp + slen, sl); - for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { - int bits = (src[sp0++] & 0xff) << 16 | - (src[sp0++] & 0xff) << 8 | - (src[sp0++] & 0xff); - dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; - dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; - dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; - dst[dp0++] = (byte)base64[bits & 0x3f]; - } - int dlen = (sl0 - sp) / 3 * 4; - dp += dlen; - sp = sl0; - if (dlen == linemax && sp < end) { - for (byte b : newline){ - dst[dp++] = b; - } - } - } - if (sp < end) { // 1 or 2 leftover bytes - int b0 = src[sp++] & 0xff; - dst[dp++] = (byte)base64[b0 >> 2]; - if (sp == end) { - dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; - if (doPadding) { - dst[dp++] = '='; - dst[dp++] = '='; - } - } else { - int b1 = src[sp++] & 0xff; - dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; - dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; - if (doPadding) { - dst[dp++] = '='; - } - } - } - return dp; - } - } - - /** - * This class implements a decoder for decoding byte data using the - * Base64 encoding scheme as specified in RFC 4648 and RFC 2045. - * - *

The Base64 padding character {@code '='} is accepted and - * interpreted as the end of the encoded byte data, but is not - * required. So if the final unit of the encoded byte data only has - * two or three Base64 characters (without the corresponding padding - * character(s) padded), they are decoded as if followed by padding - * character(s). If there is a padding character present in the - * final unit, the correct number of padding character(s) must be - * present, otherwise {@code IllegalArgumentException} ( - * {@code IOException} when reading from a Base64 stream) is thrown - * during decoding. - * - *

Instances of {@link Decoder} class are safe for use by - * multiple concurrent threads. - * - *

Unless otherwise noted, passing a {@code null} argument to - * a method of this class will cause a - * {@link java.lang.NullPointerException NullPointerException} to - * be thrown. - * - * @see Encoder - * @since 1.8 - */ - public static class Decoder { - - private final boolean isURL; - private final boolean isMIME; - - private Decoder(boolean isURL, boolean isMIME) { - this.isURL = isURL; - this.isMIME = isMIME; - } - - /** - * Lookup table for decoding unicode characters drawn from the - * "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into - * their 6-bit positive integer equivalents. Characters that - * are not in the Base64 alphabet but fall within the bounds of - * the array are encoded to -1. - * - */ - private static final int[] fromBase64 = new int[256]; - static { - Arrays.fill(fromBase64, -1); - for (int i = 0; i < Encoder.toBase64.length; i++) - fromBase64[Encoder.toBase64[i]] = i; - fromBase64['='] = -2; - } - - /** - * Lookup table for decoding "URL and Filename safe Base64 Alphabet" - * as specified in Table2 of the RFC 4648. - */ - private static final int[] fromBase64URL = new int[256]; - - static { - Arrays.fill(fromBase64URL, -1); - for (int i = 0; i < Encoder.toBase64URL.length; i++) - fromBase64URL[Encoder.toBase64URL[i]] = i; - fromBase64URL['='] = -2; - } - - static final Decoder RFC4648 = new Decoder(false, false); - static final Decoder RFC4648_URLSAFE = new Decoder(true, false); - static final Decoder RFC2045 = new Decoder(false, true); - - /** - * Decodes all bytes from the input byte array using the {@link Base64} - * encoding scheme, writing the results into a newly-allocated output - * byte array. The returned byte array is of the length of the resulting - * bytes. - * - * @param src - * the byte array to decode - * - * @return A newly-allocated byte array containing the decoded bytes. - * - * @throws IllegalArgumentException - * if {@code src} is not in valid Base64 scheme - */ - public byte[] decode(byte[] src) { - byte[] dst = new byte[outLength(src, 0, src.length)]; - int ret = decode0(src, 0, src.length, dst); - if (ret != dst.length) { - dst = Arrays.copyOf(dst, ret); - } - return dst; - } - - /** - * Decodes a Base64 encoded String into a newly-allocated byte array - * using the {@link Base64} encoding scheme. - * - *

An invocation of this method has exactly the same effect as invoking - * {@code decode(src.getBytes(StandardCharsets.ISO_8859_1))} - * - * @param src - * the string to decode - * - * @return A newly-allocated byte array containing the decoded bytes. - * - * @throws IllegalArgumentException - * if {@code src} is not in valid Base64 scheme - */ - public byte[] decode(String src) { - return decode(src.getBytes(StandardCharsets.ISO_8859_1)); - } - - /** - * Decodes all bytes from the input byte array using the {@link Base64} - * encoding scheme, writing the results into the given output byte array, - * starting at offset 0. - * - *

It is the responsibility of the invoker of this method to make - * sure the output byte array {@code dst} has enough space for decoding - * all bytes from the input byte array. No bytes will be be written to - * the output byte array if the output byte array is not big enough. - * - *

If the input byte array is not in valid Base64 encoding scheme - * then some bytes may have been written to the output byte array before - * IllegalargumentException is thrown. - * - * @param src - * the byte array to decode - * @param dst - * the output byte array - * - * @return The number of bytes written to the output byte array - * - * @throws IllegalArgumentException - * if {@code src} is not in valid Base64 scheme, or {@code dst} - * does not have enough space for decoding all input bytes. - */ - public int decode(byte[] src, byte[] dst) { - int len = outLength(src, 0, src.length); - if (dst.length < len) - throw new IllegalArgumentException( - "Output byte array is too small for decoding all input bytes"); - return decode0(src, 0, src.length, dst); - } - - /** - * Decodes all bytes from the input byte buffer using the {@link Base64} - * encoding scheme, writing the results into a newly-allocated ByteBuffer. - * - *

Upon return, the source buffer's position will be updated to - * its limit; its limit will not have been changed. The returned - * output buffer's position will be zero and its limit will be the - * number of resulting decoded bytes - * - *

{@code IllegalArgumentException} is thrown if the input buffer - * is not in valid Base64 encoding scheme. The position of the input - * buffer will not be advanced in this case. - * - * @param buffer - * the ByteBuffer to decode - * - * @return A newly-allocated byte buffer containing the decoded bytes - * - * @throws IllegalArgumentException - * if {@code src} is not in valid Base64 scheme. - */ - public ByteBuffer decode(ByteBuffer buffer) { - int pos0 = buffer.position(); - try { - byte[] src; - int sp, sl; - if (buffer.hasArray()) { - src = buffer.array(); - sp = buffer.arrayOffset() + buffer.position(); - sl = buffer.arrayOffset() + buffer.limit(); - buffer.position(buffer.limit()); - } else { - src = new byte[buffer.remaining()]; - buffer.get(src); - sp = 0; - sl = src.length; - } - byte[] dst = new byte[outLength(src, sp, sl)]; - return ByteBuffer.wrap(dst, 0, decode0(src, sp, sl, dst)); - } catch (IllegalArgumentException iae) { - buffer.position(pos0); - throw iae; - } - } - - /** - * Returns an input stream for decoding {@link Base64} encoded byte stream. - * - *

The {@code read} methods of the returned {@code InputStream} will - * throw {@code IOException} when reading bytes that cannot be decoded. - * - *

Closing the returned input stream will close the underlying - * input stream. - * - * @param is - * the input stream - * - * @return the input stream for decoding the specified Base64 encoded - * byte stream - */ - public InputStream wrap(InputStream is) { - Objects.requireNonNull(is); - return new DecInputStream(is, isURL ? fromBase64URL : fromBase64, isMIME); - } - - private int outLength(byte[] src, int sp, int sl) { - int[] base64 = isURL ? fromBase64URL : fromBase64; - int paddings = 0; - int len = sl - sp; - if (len == 0) - return 0; - if (len < 2) { - if (isMIME && base64[0] == -1) - return 0; - throw new IllegalArgumentException( - "Input byte[] should at least have 2 bytes for base64 bytes"); - } - if (isMIME) { - // scan all bytes to fill out all non-alphabet. a performance - // trade-off of pre-scan or Arrays.copyOf - int n = 0; - while (sp < sl) { - int b = src[sp++] & 0xff; - if (b == '=') { - len -= (sl - sp + 1); - break; - } - if ((b = base64[b]) == -1) - n++; - } - len -= n; - } else { - if (src[sl - 1] == '=') { - paddings++; - if (src[sl - 2] == '=') - paddings++; - } - } - if (paddings == 0 && (len & 0x3) != 0) - paddings = 4 - (len & 0x3); - return 3 * ((len + 3) / 4) - paddings; - } - - private int decode0(byte[] src, int sp, int sl, byte[] dst) { - int[] base64 = isURL ? fromBase64URL : fromBase64; - int dp = 0; - int bits = 0; - int shiftto = 18; // pos of first byte of 4-byte atom - while (sp < sl) { - int b = src[sp++] & 0xff; - if ((b = base64[b]) < 0) { - if (b == -2) { // padding byte '=' - // = shiftto==18 unnecessary padding - // x= shiftto==12 a dangling single x - // x to be handled together with non-padding case - // xx= shiftto==6&&sp==sl missing last = - // xx=y shiftto==6 last is not = - if (shiftto == 6 && (sp == sl || src[sp++] != '=') || - shiftto == 18) { - throw new IllegalArgumentException( - "Input byte array has wrong 4-byte ending unit"); - } - break; - } - if (isMIME) // skip if for rfc2045 - continue; - else - throw new IllegalArgumentException( - "Illegal base64 character " + - Integer.toString(src[sp - 1], 16)); - } - bits |= (b << shiftto); - shiftto -= 6; - if (shiftto < 0) { - dst[dp++] = (byte)(bits >> 16); - dst[dp++] = (byte)(bits >> 8); - dst[dp++] = (byte)(bits); - shiftto = 18; - bits = 0; - } - } - // reached end of byte array or hit padding '=' characters. - if (shiftto == 6) { - dst[dp++] = (byte)(bits >> 16); - } else if (shiftto == 0) { - dst[dp++] = (byte)(bits >> 16); - dst[dp++] = (byte)(bits >> 8); - } else if (shiftto == 12) { - // dangling single "x", incorrectly encoded. - throw new IllegalArgumentException( - "Last unit does not have enough valid bits"); - } - // anything left is invalid, if is not MIME. - // if MIME, ignore all non-base64 character - while (sp < sl) { - if (isMIME && base64[src[sp++]] < 0) - continue; - throw new IllegalArgumentException( - "Input byte array has incorrect ending byte at " + sp); - } - return dp; - } - } - - /* - * An output stream for encoding bytes into the Base64. - */ - private static class EncOutputStream extends FilterOutputStream { - - private int leftover = 0; - private int b0, b1, b2; - private boolean closed = false; - - private final char[] base64; // byte->base64 mapping - private final byte[] newline; // line separator, if needed - private final int linemax; - private final boolean doPadding;// whether or not to pad - private int linepos = 0; - - EncOutputStream(OutputStream os, char[] base64, - byte[] newline, int linemax, boolean doPadding) { - super(os); - this.base64 = base64; - this.newline = newline; - this.linemax = linemax; - this.doPadding = doPadding; - } - - @Override - public void write(int b) throws IOException { - byte[] buf = new byte[1]; - buf[0] = (byte)(b & 0xff); - write(buf, 0, 1); - } - - private void checkNewline() throws IOException { - if (linepos == linemax) { - out.write(newline); - linepos = 0; - } - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - if (closed) - throw new IOException("Stream is closed"); - if (off < 0 || len < 0 || off + len > b.length) - throw new ArrayIndexOutOfBoundsException(); - if (len == 0) - return; - if (leftover != 0) { - if (leftover == 1) { - b1 = b[off++] & 0xff; - len--; - if (len == 0) { - leftover++; - return; - } - } - b2 = b[off++] & 0xff; - len--; - checkNewline(); - out.write(base64[b0 >> 2]); - out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]); - out.write(base64[(b1 << 2) & 0x3f | (b2 >> 6)]); - out.write(base64[b2 & 0x3f]); - linepos += 4; - } - int nBits24 = len / 3; - leftover = len - (nBits24 * 3); - while (nBits24-- > 0) { - checkNewline(); - int bits = (b[off++] & 0xff) << 16 | - (b[off++] & 0xff) << 8 | - (b[off++] & 0xff); - out.write(base64[(bits >>> 18) & 0x3f]); - out.write(base64[(bits >>> 12) & 0x3f]); - out.write(base64[(bits >>> 6) & 0x3f]); - out.write(base64[bits & 0x3f]); - linepos += 4; - } - if (leftover == 1) { - b0 = b[off++] & 0xff; - } else if (leftover == 2) { - b0 = b[off++] & 0xff; - b1 = b[off++] & 0xff; - } - } - - @Override - public void close() throws IOException { - if (!closed) { - closed = true; - if (leftover == 1) { - checkNewline(); - out.write(base64[b0 >> 2]); - out.write(base64[(b0 << 4) & 0x3f]); - if (doPadding) { - out.write('='); - out.write('='); - } - } else if (leftover == 2) { - checkNewline(); - out.write(base64[b0 >> 2]); - out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]); - out.write(base64[(b1 << 2) & 0x3f]); - if (doPadding) { - out.write('='); - } - } - leftover = 0; - out.close(); - } - } - } - - /* - * An input stream for decoding Base64 bytes - */ - private static class DecInputStream extends InputStream { - - private final InputStream is; - private final boolean isMIME; - private final int[] base64; // base64 -> byte mapping - private int bits = 0; // 24-bit buffer for decoding - private int nextin = 18; // next available "off" in "bits" for input; - // -> 18, 12, 6, 0 - private int nextout = -8; // next available "off" in "bits" for output; - // -> 8, 0, -8 (no byte for output) - private boolean eof = false; - private boolean closed = false; - - DecInputStream(InputStream is, int[] base64, boolean isMIME) { - this.is = is; - this.base64 = base64; - this.isMIME = isMIME; - } - - private byte[] sbBuf = new byte[1]; - - @Override - public int read() throws IOException { - return read(sbBuf, 0, 1) == -1 ? -1 : sbBuf[0] & 0xff; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (closed) - throw new IOException("Stream is closed"); - if (eof && nextout < 0) // eof and no leftover - return -1; - if (off < 0 || len < 0 || len > b.length - off) - throw new IndexOutOfBoundsException(); - int oldOff = off; - if (nextout >= 0) { // leftover output byte(s) in bits buf - do { - if (len == 0) - return off - oldOff; - b[off++] = (byte)(bits >> nextout); - len--; - nextout -= 8; - } while (nextout >= 0); - bits = 0; - } - while (len > 0) { - int v = is.read(); - if (v == -1) { - eof = true; - if (nextin != 18) { - if (nextin == 12) - throw new IOException("Base64 stream has one un-decoded dangling byte."); - // treat ending xx/xxx without padding character legal. - // same logic as v == '=' below - b[off++] = (byte)(bits >> (16)); - len--; - if (nextin == 0) { // only one padding byte - if (len == 0) { // no enough output space - bits >>= 8; // shift to lowest byte - nextout = 0; - } else { - b[off++] = (byte) (bits >> 8); - } - } - } - if (off == oldOff) - return -1; - else - return off - oldOff; - } - if (v == '=') { // padding byte(s) - // = shiftto==18 unnecessary padding - // x= shiftto==12 dangling x, invalid unit - // xx= shiftto==6 && missing last '=' - // xx=y or last is not '=' - if (nextin == 18 || nextin == 12 || - nextin == 6 && is.read() != '=') { - throw new IOException("Illegal base64 ending sequence:" + nextin); - } - b[off++] = (byte)(bits >> (16)); - len--; - if (nextin == 0) { // only one padding byte - if (len == 0) { // no enough output space - bits >>= 8; // shift to lowest byte - nextout = 0; - } else { - b[off++] = (byte) (bits >> 8); - } - } - eof = true; - break; - } - if ((v = base64[v]) == -1) { - if (isMIME) // skip if for rfc2045 - continue; - else - throw new IOException("Illegal base64 character " + - Integer.toString(v, 16)); - } - bits |= (v << nextin); - if (nextin == 0) { - nextin = 18; // clear for next - nextout = 16; - while (nextout >= 0) { - b[off++] = (byte)(bits >> nextout); - len--; - nextout -= 8; - if (len == 0 && nextout >= 0) { // don't clean "bits" - return off - oldOff; - } - } - bits = 0; - } else { - nextin -= 6; - } - } - return off - oldOff; - } - - @Override - public int available() throws IOException { - if (closed) - throw new IOException("Stream is closed"); - return is.available(); // TBD: - } - - @Override - public void close() throws IOException { - if (!closed) { - closed = true; - is.close(); - } - } - } +package the.bytecode.club.bootloader.util; + +import java.io.FilterOutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.*; + +public class Base64 { + + private Base64() {} + + /** + * Returns a {@link Encoder} that encodes using the + * Basic type base64 encoding scheme. + * + * @return A Base64 encoder. + */ + public static Encoder getEncoder() { + return Encoder.RFC4648; + } + + /** + * Returns a {@link Encoder} that encodes using the + * URL and Filename safe type base64 + * encoding scheme. + * + * @return A Base64 encoder. + */ + public static Encoder getUrlEncoder() { + return Encoder.RFC4648_URLSAFE; + } + + /** + * Returns a {@link Encoder} that encodes using the + * MIME type base64 encoding scheme. + * + * @return A Base64 encoder. + */ + public static Encoder getMimeEncoder() { + return Encoder.RFC2045; + } + + /** + * Returns a {@link Encoder} that encodes using the + * MIME type base64 encoding scheme + * with specified line length and line separators. + * + * @param lineLength + * the length of each output line (rounded down to nearest multiple + * of 4). If {@code lineLength <= 0} the output will not be separated + * in lines + * @param lineSeparator + * the line separator for each output line + * + * @return A Base64 encoder. + * + * @throws IllegalArgumentException if {@code lineSeparator} includes any + * character of "The Base64 Alphabet" as specified in Table 1 of + * RFC 2045. + */ + public static Encoder getMimeEncoder(int lineLength, byte[] lineSeparator) { + Objects.requireNonNull(lineSeparator); + int[] base64 = Decoder.fromBase64; + for (byte b : lineSeparator) { + if (base64[b & 0xff] != -1) + throw new IllegalArgumentException( + "Illegal base64 line separator character 0x" + Integer.toString(b, 16)); + } + if (lineLength <= 0) { + return Encoder.RFC4648; + } + return new Encoder(false, lineSeparator, lineLength >> 2 << 2, true); + } + + /** + * Returns a {@link Decoder} that decodes using the + * Basic type base64 encoding scheme. + * + * @return A Base64 decoder. + */ + public static Decoder getDecoder() { + return Decoder.RFC4648; + } + + /** + * Returns a {@link Decoder} that decodes using the + * URL and Filename safe type base64 + * encoding scheme. + * + * @return A Base64 decoder. + */ + public static Decoder getUrlDecoder() { + return Decoder.RFC4648_URLSAFE; + } + + /** + * Returns a {@link Decoder} that decodes using the + * MIME type base64 decoding scheme. + * + * @return A Base64 decoder. + */ + public static Decoder getMimeDecoder() { + return Decoder.RFC2045; + } + + /** + * This class implements an encoder for encoding byte data using + * the Base64 encoding scheme as specified in RFC 4648 and RFC 2045. + * + *

Instances of {@link Encoder} class are safe for use by + * multiple concurrent threads. + * + *

Unless otherwise noted, passing a {@code null} argument to + * a method of this class will cause a + * {@link java.lang.NullPointerException NullPointerException} to + * be thrown. + * + * @see Decoder + * @since 1.8 + */ + public static class Encoder { + + private final byte[] newline; + private final int linemax; + private final boolean isURL; + private final boolean doPadding; + + private Encoder(boolean isURL, byte[] newline, int linemax, boolean doPadding) { + this.isURL = isURL; + this.newline = newline; + this.linemax = linemax; + this.doPadding = doPadding; + } + + /** + * This array is a lookup table that translates 6-bit positive integer + * index values into their "Base64 Alphabet" equivalents as specified + * in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648). + */ + private static final char[] toBase64 = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' + }; + + /** + * It's the lookup table for "URL and Filename safe Base64" as specified + * in Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and + * '_'. This table is used when BASE64_URL is specified. + */ + private static final char[] toBase64URL = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' + }; + + private static final int MIMELINEMAX = 76; + private static final byte[] CRLF = new byte[] {'\r', '\n'}; + + static final Encoder RFC4648 = new Encoder(false, null, -1, true); + static final Encoder RFC4648_URLSAFE = new Encoder(true, null, -1, true); + static final Encoder RFC2045 = new Encoder(false, CRLF, MIMELINEMAX, true); + + private final int outLength(int srclen) { + int len = 0; + if (doPadding) { + len = 4 * ((srclen + 2) / 3); + } else { + int n = srclen % 3; + len = 4 * (srclen / 3) + (n == 0 ? 0 : n + 1); + } + if (linemax > 0) // line separators + len += (len - 1) / linemax * newline.length; + return len; + } + + /** + * Encodes all bytes from the specified byte array into a newly-allocated + * byte array using the {@link Base64} encoding scheme. The returned byte + * array is of the length of the resulting bytes. + * + * @param src + * the byte array to encode + * @return A newly-allocated byte array containing the resulting + * encoded bytes. + */ + public byte[] encode(byte[] src) { + int len = outLength(src.length); // dst array size + byte[] dst = new byte[len]; + int ret = encode0(src, 0, src.length, dst); + if (ret != dst.length) + return Arrays.copyOf(dst, ret); + return dst; + } + + /** + * Encodes all bytes from the specified byte array using the + * {@link Base64} encoding scheme, writing the resulting bytes to the + * given output byte array, starting at offset 0. + * + *

It is the responsibility of the invoker of this method to make + * sure the output byte array {@code dst} has enough space for encoding + * all bytes from the input byte array. No bytes will be written to the + * output byte array if the output byte array is not big enough. + * + * @param src + * the byte array to encode + * @param dst + * the output byte array + * @return The number of bytes written to the output byte array + * + * @throws IllegalArgumentException if {@code dst} does not have enough + * space for encoding all input bytes. + */ + public int encode(byte[] src, byte[] dst) { + int len = outLength(src.length); // dst array size + if (dst.length < len) + throw new IllegalArgumentException( + "Output byte array is too small for encoding all input bytes"); + return encode0(src, 0, src.length, dst); + } + + /** + * Encodes the specified byte array into a String using the {@link Base64} + * encoding scheme. + * + *

This method first encodes all input bytes into a base64 encoded + * byte array and then constructs a new String by using the encoded byte + * array and the {@link java.nio.charset.StandardCharsets#ISO_8859_1 + * ISO-8859-1} charset. + * + *

In other words, an invocation of this method has exactly the same + * effect as invoking + * {@code new String(encode(src), StandardCharsets.ISO_8859_1)}. + * + * @param src + * the byte array to encode + * @return A String containing the resulting Base64 encoded characters + */ + @SuppressWarnings("deprecation") + public String encodeToString(byte[] src) { + byte[] encoded = encode(src); + return new String(encoded, 0, 0, encoded.length); + } + + /** + * Encodes all remaining bytes from the specified byte buffer into + * a newly-allocated ByteBuffer using the {@link Base64} encoding + * scheme. + * + * Upon return, the source buffer's position will be updated to + * its limit; its limit will not have been changed. The returned + * output buffer's position will be zero and its limit will be the + * number of resulting encoded bytes. + * + * @param buffer + * the source ByteBuffer to encode + * @return A newly-allocated byte buffer containing the encoded bytes. + */ + public ByteBuffer encode(ByteBuffer buffer) { + int len = outLength(buffer.remaining()); + byte[] dst = new byte[len]; + int ret = 0; + if (buffer.hasArray()) { + ret = encode0(buffer.array(), + buffer.arrayOffset() + buffer.position(), + buffer.arrayOffset() + buffer.limit(), + dst); + buffer.position(buffer.limit()); + } else { + byte[] src = new byte[buffer.remaining()]; + buffer.get(src); + ret = encode0(src, 0, src.length, dst); + } + if (ret != dst.length) + dst = Arrays.copyOf(dst, ret); + return ByteBuffer.wrap(dst); + } + + /** + * Wraps an output stream for encoding byte data using the {@link Base64} + * encoding scheme. + * + *

It is recommended to promptly close the returned output stream after + * use, during which it will flush all possible leftover bytes to the underlying + * output stream. Closing the returned output stream will close the underlying + * output stream. + * + * @param os + * the output stream. + * @return the output stream for encoding the byte data into the + * specified Base64 encoded format + */ + public OutputStream wrap(OutputStream os) { + Objects.requireNonNull(os); + return new EncOutputStream(os, isURL ? toBase64URL : toBase64, + newline, linemax, doPadding); + } + + /** + * Returns an encoder instance that encodes equivalently to this one, + * but without adding any padding character at the end of the encoded + * byte data. + * + *

The encoding scheme of this encoder instance is unaffected by + * this invocation. The returned encoder instance should be used for + * non-padding encoding operation. + * + * @return an equivalent encoder that encodes without adding any + * padding character at the end + */ + public Encoder withoutPadding() { + if (!doPadding) + return this; + return new Encoder(isURL, newline, linemax, false); + } + + private int encode0(byte[] src, int off, int end, byte[] dst) { + char[] base64 = isURL ? toBase64URL : toBase64; + int sp = off; + int slen = (end - off) / 3 * 3; + int sl = off + slen; + if (linemax > 0 && slen > linemax / 4 * 3) + slen = linemax / 4 * 3; + int dp = 0; + while (sp < sl) { + int sl0 = Math.min(sp + slen, sl); + for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { + int bits = (src[sp0++] & 0xff) << 16 | + (src[sp0++] & 0xff) << 8 | + (src[sp0++] & 0xff); + dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; + dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; + dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; + dst[dp0++] = (byte)base64[bits & 0x3f]; + } + int dlen = (sl0 - sp) / 3 * 4; + dp += dlen; + sp = sl0; + if (dlen == linemax && sp < end) { + for (byte b : newline){ + dst[dp++] = b; + } + } + } + if (sp < end) { // 1 or 2 leftover bytes + int b0 = src[sp++] & 0xff; + dst[dp++] = (byte)base64[b0 >> 2]; + if (sp == end) { + dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; + if (doPadding) { + dst[dp++] = '='; + dst[dp++] = '='; + } + } else { + int b1 = src[sp++] & 0xff; + dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; + dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; + if (doPadding) { + dst[dp++] = '='; + } + } + } + return dp; + } + } + + /** + * This class implements a decoder for decoding byte data using the + * Base64 encoding scheme as specified in RFC 4648 and RFC 2045. + * + *

The Base64 padding character {@code '='} is accepted and + * interpreted as the end of the encoded byte data, but is not + * required. So if the final unit of the encoded byte data only has + * two or three Base64 characters (without the corresponding padding + * character(s) padded), they are decoded as if followed by padding + * character(s). If there is a padding character present in the + * final unit, the correct number of padding character(s) must be + * present, otherwise {@code IllegalArgumentException} ( + * {@code IOException} when reading from a Base64 stream) is thrown + * during decoding. + * + *

Instances of {@link Decoder} class are safe for use by + * multiple concurrent threads. + * + *

Unless otherwise noted, passing a {@code null} argument to + * a method of this class will cause a + * {@link java.lang.NullPointerException NullPointerException} to + * be thrown. + * + * @see Encoder + * @since 1.8 + */ + public static class Decoder { + + private final boolean isURL; + private final boolean isMIME; + + private Decoder(boolean isURL, boolean isMIME) { + this.isURL = isURL; + this.isMIME = isMIME; + } + + /** + * Lookup table for decoding unicode characters drawn from the + * "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into + * their 6-bit positive integer equivalents. Characters that + * are not in the Base64 alphabet but fall within the bounds of + * the array are encoded to -1. + * + */ + private static final int[] fromBase64 = new int[256]; + static { + Arrays.fill(fromBase64, -1); + for (int i = 0; i < Encoder.toBase64.length; i++) + fromBase64[Encoder.toBase64[i]] = i; + fromBase64['='] = -2; + } + + /** + * Lookup table for decoding "URL and Filename safe Base64 Alphabet" + * as specified in Table2 of the RFC 4648. + */ + private static final int[] fromBase64URL = new int[256]; + + static { + Arrays.fill(fromBase64URL, -1); + for (int i = 0; i < Encoder.toBase64URL.length; i++) + fromBase64URL[Encoder.toBase64URL[i]] = i; + fromBase64URL['='] = -2; + } + + static final Decoder RFC4648 = new Decoder(false, false); + static final Decoder RFC4648_URLSAFE = new Decoder(true, false); + static final Decoder RFC2045 = new Decoder(false, true); + + /** + * Decodes all bytes from the input byte array using the {@link Base64} + * encoding scheme, writing the results into a newly-allocated output + * byte array. The returned byte array is of the length of the resulting + * bytes. + * + * @param src + * the byte array to decode + * + * @return A newly-allocated byte array containing the decoded bytes. + * + * @throws IllegalArgumentException + * if {@code src} is not in valid Base64 scheme + */ + public byte[] decode(byte[] src) { + byte[] dst = new byte[outLength(src, 0, src.length)]; + int ret = decode0(src, 0, src.length, dst); + if (ret != dst.length) { + dst = Arrays.copyOf(dst, ret); + } + return dst; + } + + /** + * Decodes a Base64 encoded String into a newly-allocated byte array + * using the {@link Base64} encoding scheme. + * + *

An invocation of this method has exactly the same effect as invoking + * {@code decode(src.getBytes(StandardCharsets.ISO_8859_1))} + * + * @param src + * the string to decode + * + * @return A newly-allocated byte array containing the decoded bytes. + * + * @throws IllegalArgumentException + * if {@code src} is not in valid Base64 scheme + */ + public byte[] decode(String src) { + return decode(src.getBytes(StandardCharsets.ISO_8859_1)); + } + + /** + * Decodes all bytes from the input byte array using the {@link Base64} + * encoding scheme, writing the results into the given output byte array, + * starting at offset 0. + * + *

It is the responsibility of the invoker of this method to make + * sure the output byte array {@code dst} has enough space for decoding + * all bytes from the input byte array. No bytes will be be written to + * the output byte array if the output byte array is not big enough. + * + *

If the input byte array is not in valid Base64 encoding scheme + * then some bytes may have been written to the output byte array before + * IllegalargumentException is thrown. + * + * @param src + * the byte array to decode + * @param dst + * the output byte array + * + * @return The number of bytes written to the output byte array + * + * @throws IllegalArgumentException + * if {@code src} is not in valid Base64 scheme, or {@code dst} + * does not have enough space for decoding all input bytes. + */ + public int decode(byte[] src, byte[] dst) { + int len = outLength(src, 0, src.length); + if (dst.length < len) + throw new IllegalArgumentException( + "Output byte array is too small for decoding all input bytes"); + return decode0(src, 0, src.length, dst); + } + + /** + * Decodes all bytes from the input byte buffer using the {@link Base64} + * encoding scheme, writing the results into a newly-allocated ByteBuffer. + * + *

Upon return, the source buffer's position will be updated to + * its limit; its limit will not have been changed. The returned + * output buffer's position will be zero and its limit will be the + * number of resulting decoded bytes + * + *

{@code IllegalArgumentException} is thrown if the input buffer + * is not in valid Base64 encoding scheme. The position of the input + * buffer will not be advanced in this case. + * + * @param buffer + * the ByteBuffer to decode + * + * @return A newly-allocated byte buffer containing the decoded bytes + * + * @throws IllegalArgumentException + * if {@code src} is not in valid Base64 scheme. + */ + public ByteBuffer decode(ByteBuffer buffer) { + int pos0 = buffer.position(); + try { + byte[] src; + int sp, sl; + if (buffer.hasArray()) { + src = buffer.array(); + sp = buffer.arrayOffset() + buffer.position(); + sl = buffer.arrayOffset() + buffer.limit(); + buffer.position(buffer.limit()); + } else { + src = new byte[buffer.remaining()]; + buffer.get(src); + sp = 0; + sl = src.length; + } + byte[] dst = new byte[outLength(src, sp, sl)]; + return ByteBuffer.wrap(dst, 0, decode0(src, sp, sl, dst)); + } catch (IllegalArgumentException iae) { + buffer.position(pos0); + throw iae; + } + } + + /** + * Returns an input stream for decoding {@link Base64} encoded byte stream. + * + *

The {@code read} methods of the returned {@code InputStream} will + * throw {@code IOException} when reading bytes that cannot be decoded. + * + *

Closing the returned input stream will close the underlying + * input stream. + * + * @param is + * the input stream + * + * @return the input stream for decoding the specified Base64 encoded + * byte stream + */ + public InputStream wrap(InputStream is) { + Objects.requireNonNull(is); + return new DecInputStream(is, isURL ? fromBase64URL : fromBase64, isMIME); + } + + private int outLength(byte[] src, int sp, int sl) { + int[] base64 = isURL ? fromBase64URL : fromBase64; + int paddings = 0; + int len = sl - sp; + if (len == 0) + return 0; + if (len < 2) { + if (isMIME && base64[0] == -1) + return 0; + throw new IllegalArgumentException( + "Input byte[] should at least have 2 bytes for base64 bytes"); + } + if (isMIME) { + // scan all bytes to fill out all non-alphabet. a performance + // trade-off of pre-scan or Arrays.copyOf + int n = 0; + while (sp < sl) { + int b = src[sp++] & 0xff; + if (b == '=') { + len -= (sl - sp + 1); + break; + } + if ((b = base64[b]) == -1) + n++; + } + len -= n; + } else { + if (src[sl - 1] == '=') { + paddings++; + if (src[sl - 2] == '=') + paddings++; + } + } + if (paddings == 0 && (len & 0x3) != 0) + paddings = 4 - (len & 0x3); + return 3 * ((len + 3) / 4) - paddings; + } + + private int decode0(byte[] src, int sp, int sl, byte[] dst) { + int[] base64 = isURL ? fromBase64URL : fromBase64; + int dp = 0; + int bits = 0; + int shiftto = 18; // pos of first byte of 4-byte atom + while (sp < sl) { + int b = src[sp++] & 0xff; + if ((b = base64[b]) < 0) { + if (b == -2) { // padding byte '=' + // = shiftto==18 unnecessary padding + // x= shiftto==12 a dangling single x + // x to be handled together with non-padding case + // xx= shiftto==6&&sp==sl missing last = + // xx=y shiftto==6 last is not = + if (shiftto == 6 && (sp == sl || src[sp++] != '=') || + shiftto == 18) { + throw new IllegalArgumentException( + "Input byte array has wrong 4-byte ending unit"); + } + break; + } + if (isMIME) // skip if for rfc2045 + continue; + else + throw new IllegalArgumentException( + "Illegal base64 character " + + Integer.toString(src[sp - 1], 16)); + } + bits |= (b << shiftto); + shiftto -= 6; + if (shiftto < 0) { + dst[dp++] = (byte)(bits >> 16); + dst[dp++] = (byte)(bits >> 8); + dst[dp++] = (byte)(bits); + shiftto = 18; + bits = 0; + } + } + // reached end of byte array or hit padding '=' characters. + if (shiftto == 6) { + dst[dp++] = (byte)(bits >> 16); + } else if (shiftto == 0) { + dst[dp++] = (byte)(bits >> 16); + dst[dp++] = (byte)(bits >> 8); + } else if (shiftto == 12) { + // dangling single "x", incorrectly encoded. + throw new IllegalArgumentException( + "Last unit does not have enough valid bits"); + } + // anything left is invalid, if is not MIME. + // if MIME, ignore all non-base64 character + while (sp < sl) { + if (isMIME && base64[src[sp++]] < 0) + continue; + throw new IllegalArgumentException( + "Input byte array has incorrect ending byte at " + sp); + } + return dp; + } + } + + /* + * An output stream for encoding bytes into the Base64. + */ + private static class EncOutputStream extends FilterOutputStream { + + private int leftover = 0; + private int b0, b1, b2; + private boolean closed = false; + + private final char[] base64; // byte->base64 mapping + private final byte[] newline; // line separator, if needed + private final int linemax; + private final boolean doPadding;// whether or not to pad + private int linepos = 0; + + EncOutputStream(OutputStream os, char[] base64, + byte[] newline, int linemax, boolean doPadding) { + super(os); + this.base64 = base64; + this.newline = newline; + this.linemax = linemax; + this.doPadding = doPadding; + } + + @Override + public void write(int b) throws IOException { + byte[] buf = new byte[1]; + buf[0] = (byte)(b & 0xff); + write(buf, 0, 1); + } + + private void checkNewline() throws IOException { + if (linepos == linemax) { + out.write(newline); + linepos = 0; + } + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (closed) + throw new IOException("Stream is closed"); + if (off < 0 || len < 0 || off + len > b.length) + throw new ArrayIndexOutOfBoundsException(); + if (len == 0) + return; + if (leftover != 0) { + if (leftover == 1) { + b1 = b[off++] & 0xff; + len--; + if (len == 0) { + leftover++; + return; + } + } + b2 = b[off++] & 0xff; + len--; + checkNewline(); + out.write(base64[b0 >> 2]); + out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]); + out.write(base64[(b1 << 2) & 0x3f | (b2 >> 6)]); + out.write(base64[b2 & 0x3f]); + linepos += 4; + } + int nBits24 = len / 3; + leftover = len - (nBits24 * 3); + while (nBits24-- > 0) { + checkNewline(); + int bits = (b[off++] & 0xff) << 16 | + (b[off++] & 0xff) << 8 | + (b[off++] & 0xff); + out.write(base64[(bits >>> 18) & 0x3f]); + out.write(base64[(bits >>> 12) & 0x3f]); + out.write(base64[(bits >>> 6) & 0x3f]); + out.write(base64[bits & 0x3f]); + linepos += 4; + } + if (leftover == 1) { + b0 = b[off++] & 0xff; + } else if (leftover == 2) { + b0 = b[off++] & 0xff; + b1 = b[off++] & 0xff; + } + } + + @Override + public void close() throws IOException { + if (!closed) { + closed = true; + if (leftover == 1) { + checkNewline(); + out.write(base64[b0 >> 2]); + out.write(base64[(b0 << 4) & 0x3f]); + if (doPadding) { + out.write('='); + out.write('='); + } + } else if (leftover == 2) { + checkNewline(); + out.write(base64[b0 >> 2]); + out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]); + out.write(base64[(b1 << 2) & 0x3f]); + if (doPadding) { + out.write('='); + } + } + leftover = 0; + out.close(); + } + } + } + + /* + * An input stream for decoding Base64 bytes + */ + private static class DecInputStream extends InputStream { + + private final InputStream is; + private final boolean isMIME; + private final int[] base64; // base64 -> byte mapping + private int bits = 0; // 24-bit buffer for decoding + private int nextin = 18; // next available "off" in "bits" for input; + // -> 18, 12, 6, 0 + private int nextout = -8; // next available "off" in "bits" for output; + // -> 8, 0, -8 (no byte for output) + private boolean eof = false; + private boolean closed = false; + + DecInputStream(InputStream is, int[] base64, boolean isMIME) { + this.is = is; + this.base64 = base64; + this.isMIME = isMIME; + } + + private byte[] sbBuf = new byte[1]; + + @Override + public int read() throws IOException { + return read(sbBuf, 0, 1) == -1 ? -1 : sbBuf[0] & 0xff; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + if (closed) + throw new IOException("Stream is closed"); + if (eof && nextout < 0) // eof and no leftover + return -1; + if (off < 0 || len < 0 || len > b.length - off) + throw new IndexOutOfBoundsException(); + int oldOff = off; + if (nextout >= 0) { // leftover output byte(s) in bits buf + do { + if (len == 0) + return off - oldOff; + b[off++] = (byte)(bits >> nextout); + len--; + nextout -= 8; + } while (nextout >= 0); + bits = 0; + } + while (len > 0) { + int v = is.read(); + if (v == -1) { + eof = true; + if (nextin != 18) { + if (nextin == 12) + throw new IOException("Base64 stream has one un-decoded dangling byte."); + // treat ending xx/xxx without padding character legal. + // same logic as v == '=' below + b[off++] = (byte)(bits >> (16)); + len--; + if (nextin == 0) { // only one padding byte + if (len == 0) { // no enough output space + bits >>= 8; // shift to lowest byte + nextout = 0; + } else { + b[off++] = (byte) (bits >> 8); + } + } + } + if (off == oldOff) + return -1; + else + return off - oldOff; + } + if (v == '=') { // padding byte(s) + // = shiftto==18 unnecessary padding + // x= shiftto==12 dangling x, invalid unit + // xx= shiftto==6 && missing last '=' + // xx=y or last is not '=' + if (nextin == 18 || nextin == 12 || + nextin == 6 && is.read() != '=') { + throw new IOException("Illegal base64 ending sequence:" + nextin); + } + b[off++] = (byte)(bits >> (16)); + len--; + if (nextin == 0) { // only one padding byte + if (len == 0) { // no enough output space + bits >>= 8; // shift to lowest byte + nextout = 0; + } else { + b[off++] = (byte) (bits >> 8); + } + } + eof = true; + break; + } + if ((v = base64[v]) == -1) { + if (isMIME) // skip if for rfc2045 + continue; + else + throw new IOException("Illegal base64 character " + + Integer.toString(v, 16)); + } + bits |= (v << nextin); + if (nextin == 0) { + nextin = 18; // clear for next + nextout = 16; + while (nextout >= 0) { + b[off++] = (byte)(bits >> nextout); + len--; + nextout -= 8; + if (len == 0 && nextout >= 0) { // don't clean "bits" + return off - oldOff; + } + } + bits = 0; + } else { + nextin -= 6; + } + } + return off - oldOff; + } + + @Override + public int available() throws IOException { + if (closed) + throw new IOException("Stream is closed"); + return is.available(); // TBD: + } + + @Override + public void close() throws IOException { + if (!closed) { + closed = true; + is.close(); + } + } + } } \ No newline at end of file diff --git a/src/the/bytecode/club/bootloader/util/ClassHelper.java b/src/main/java/the/bytecode/club/bootloader/util/ClassHelper.java similarity index 100% rename from src/the/bytecode/club/bootloader/util/ClassHelper.java rename to src/main/java/the/bytecode/club/bootloader/util/ClassHelper.java diff --git a/src/the/bytecode/club/bootloader/util/ClassTree.java b/src/main/java/the/bytecode/club/bootloader/util/ClassTree.java similarity index 100% rename from src/the/bytecode/club/bootloader/util/ClassTree.java rename to src/main/java/the/bytecode/club/bootloader/util/ClassTree.java diff --git a/src/the/bytecode/club/bootloader/util/NullCreator.java b/src/main/java/the/bytecode/club/bootloader/util/NullCreator.java similarity index 100% rename from src/the/bytecode/club/bootloader/util/NullCreator.java rename to src/main/java/the/bytecode/club/bootloader/util/NullCreator.java diff --git a/src/the/bytecode/club/bootloader/util/NullPermeableHashMap.java b/src/main/java/the/bytecode/club/bootloader/util/NullPermeableHashMap.java similarity index 100% rename from src/the/bytecode/club/bootloader/util/NullPermeableHashMap.java rename to src/main/java/the/bytecode/club/bootloader/util/NullPermeableHashMap.java diff --git a/src/the/bytecode/club/bootloader/util/SetCreator.java b/src/main/java/the/bytecode/club/bootloader/util/SetCreator.java similarity index 100% rename from src/the/bytecode/club/bootloader/util/SetCreator.java rename to src/main/java/the/bytecode/club/bootloader/util/SetCreator.java diff --git a/src/the/bytecode/club/bootloader/util/ValueCreator.java b/src/main/java/the/bytecode/club/bootloader/util/ValueCreator.java similarity index 100% rename from src/the/bytecode/club/bootloader/util/ValueCreator.java rename to src/main/java/the/bytecode/club/bootloader/util/ValueCreator.java diff --git a/src/the/bytecode/club/bytecodeviewer/BytecodeViewer.java b/src/main/java/the/bytecode/club/bytecodeviewer/BytecodeViewer.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/BytecodeViewer.java rename to src/main/java/the/bytecode/club/bytecodeviewer/BytecodeViewer.java diff --git a/src/the/bytecode/club/bytecodeviewer/CommandLineInput.java b/src/main/java/the/bytecode/club/bytecodeviewer/CommandLineInput.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/CommandLineInput.java rename to src/main/java/the/bytecode/club/bytecodeviewer/CommandLineInput.java diff --git a/src/the/bytecode/club/bytecodeviewer/Resources.java b/src/main/java/the/bytecode/club/bytecodeviewer/Resources.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/Resources.java rename to src/main/java/the/bytecode/club/bytecodeviewer/Resources.java diff --git a/src/the/bytecode/club/bytecodeviewer/SecurityMan.java b/src/main/java/the/bytecode/club/bytecodeviewer/SecurityMan.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/SecurityMan.java rename to src/main/java/the/bytecode/club/bytecodeviewer/SecurityMan.java diff --git a/src/the/bytecode/club/bytecodeviewer/Settings.java b/src/main/java/the/bytecode/club/bytecodeviewer/Settings.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/Settings.java rename to src/main/java/the/bytecode/club/bytecodeviewer/Settings.java diff --git a/src/the/bytecode/club/bytecodeviewer/api/ASMUtil_OLD.java b/src/main/java/the/bytecode/club/bytecodeviewer/api/ASMUtil_OLD.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/api/ASMUtil_OLD.java rename to src/main/java/the/bytecode/club/bytecodeviewer/api/ASMUtil_OLD.java diff --git a/src/the/bytecode/club/bytecodeviewer/api/BytecodeHook.java b/src/main/java/the/bytecode/club/bytecodeviewer/api/BytecodeHook.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/api/BytecodeHook.java rename to src/main/java/the/bytecode/club/bytecodeviewer/api/BytecodeHook.java diff --git a/src/the/bytecode/club/bytecodeviewer/api/BytecodeViewer.java b/src/main/java/the/bytecode/club/bytecodeviewer/api/BytecodeViewer.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/api/BytecodeViewer.java rename to src/main/java/the/bytecode/club/bytecodeviewer/api/BytecodeViewer.java diff --git a/src/the/bytecode/club/bytecodeviewer/api/ClassNodeLoader.java b/src/main/java/the/bytecode/club/bytecodeviewer/api/ClassNodeLoader.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/api/ClassNodeLoader.java rename to src/main/java/the/bytecode/club/bytecodeviewer/api/ClassNodeLoader.java diff --git a/src/the/bytecode/club/bytecodeviewer/api/ExceptionUI.java b/src/main/java/the/bytecode/club/bytecodeviewer/api/ExceptionUI.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/api/ExceptionUI.java rename to src/main/java/the/bytecode/club/bytecodeviewer/api/ExceptionUI.java diff --git a/src/the/bytecode/club/bytecodeviewer/api/Plugin.java b/src/main/java/the/bytecode/club/bytecodeviewer/api/Plugin.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/api/Plugin.java rename to src/main/java/the/bytecode/club/bytecodeviewer/api/Plugin.java diff --git a/src/the/bytecode/club/bytecodeviewer/api/PluginConsole.java b/src/main/java/the/bytecode/club/bytecodeviewer/api/PluginConsole.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/api/PluginConsole.java rename to src/main/java/the/bytecode/club/bytecodeviewer/api/PluginConsole.java diff --git a/src/the/bytecode/club/bytecodeviewer/compilers/Compiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/Compiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/compilers/Compiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/compilers/Compiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/compilers/JavaCompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/JavaCompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/compilers/JavaCompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/compilers/JavaCompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/compilers/KrakatauAssembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/KrakatauAssembler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/compilers/KrakatauAssembler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/compilers/KrakatauAssembler.java diff --git a/src/the/bytecode/club/bytecodeviewer/compilers/SmaliAssembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/compilers/SmaliAssembler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/compilers/SmaliAssembler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/compilers/SmaliAssembler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/ASMTextifierDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/ASMTextifierDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/ASMTextifierDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/ASMTextifierDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/CFRDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/CFRDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/CFRDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/CFRDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/Decompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/Decompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/Decompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/Decompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/FernFlowerDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/FernFlowerDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/FernFlowerDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/FernFlowerDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/JADXDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/JADXDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/JADXDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/JADXDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/JDGUIDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/JDGUIDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/JDGUIDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/JDGUIDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/KrakatauDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/KrakatauDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/KrakatauDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/KrakatauDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/KrakatauDisassembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/KrakatauDisassembler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/KrakatauDisassembler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/KrakatauDisassembler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/ProcyonDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/ProcyonDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/ProcyonDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/ProcyonDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/SmaliDisassembler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/SmaliDisassembler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/SmaliDisassembler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/SmaliDisassembler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/ClassNodeDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/ClassNodeDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/ClassNodeDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/ClassNodeDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/FieldNodeDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/FieldNodeDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/FieldNodeDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/FieldNodeDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPattern.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPattern.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPattern.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPattern.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPrinter.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPrinter.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPrinter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionPrinter.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionSearcher.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionSearcher.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionSearcher.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/InstructionSearcher.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/MethodNodeDecompiler.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/MethodNodeDecompiler.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/MethodNodeDecompiler.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/MethodNodeDecompiler.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/PrefixedStringBuilder.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/PrefixedStringBuilder.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/PrefixedStringBuilder.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/PrefixedStringBuilder.java diff --git a/src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/TypeAndName.java b/src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/TypeAndName.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/decompilers/bytecode/TypeAndName.java rename to src/main/java/the/bytecode/club/bytecodeviewer/decompilers/bytecode/TypeAndName.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/AboutWindow.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/AboutWindow.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/AboutWindow.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/AboutWindow.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/ClassViewer.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/ClassViewer.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/ClassViewer.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/ClassViewer.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/DelayTabbedPaneThread.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/DelayTabbedPaneThread.java similarity index 95% rename from src/the/bytecode/club/bytecodeviewer/gui/DelayTabbedPaneThread.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/DelayTabbedPaneThread.java index 288fa7ca..8dbc2ba0 100644 --- a/src/the/bytecode/club/bytecodeviewer/gui/DelayTabbedPaneThread.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/gui/DelayTabbedPaneThread.java @@ -1,49 +1,49 @@ -package the.bytecode.club.bytecodeviewer.gui; - -import the.bytecode.club.bytecodeviewer.BytecodeViewer; - -import javax.swing.*; -import java.awt.*; - -/** - * @author Konloch - */ -public class DelayTabbedPaneThread extends Thread -{ - public boolean stopped = false; - private TabbedPane pane; - - public DelayTabbedPaneThread(TabbedPane pane) - { - this.pane = pane; - } - - @Override - public void run() - { - try - { - sleep(200); - } - catch (InterruptedException e) - { - e.printStackTrace(); - } - if(!stopped) - { - SwingUtilities.invokeLater(new Runnable() - { - @Override - public void run() - { - if(stopped) - return; - - pane.label.setOpaque(true); - pane.label.setBackground(Color.MAGENTA); - pane.label.updateUI(); - } - }); - } - } -} +package the.bytecode.club.bytecodeviewer.gui; + +import the.bytecode.club.bytecodeviewer.BytecodeViewer; + +import javax.swing.*; +import java.awt.*; + +/** + * @author Konloch + */ +public class DelayTabbedPaneThread extends Thread +{ + public boolean stopped = false; + private TabbedPane pane; + + public DelayTabbedPaneThread(TabbedPane pane) + { + this.pane = pane; + } + + @Override + public void run() + { + try + { + sleep(200); + } + catch (InterruptedException e) + { + e.printStackTrace(); + } + if(!stopped) + { + SwingUtilities.invokeLater(new Runnable() + { + @Override + public void run() + { + if(stopped) + return; + + pane.label.setOpaque(true); + pane.label.setBackground(Color.MAGENTA); + pane.label.updateUI(); + } + }); + } + } +} diff --git a/src/the/bytecode/club/bytecodeviewer/gui/ExportJar.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/ExportJar.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/ExportJar.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/ExportJar.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/FileNavigationPane.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/FileNavigationPane.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/FileNavigationPane.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/FileNavigationPane.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/FileViewer.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/FileViewer.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/FileViewer.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/FileViewer.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/GraphicialReflectionKit.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/GraphicialReflectionKit.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/GraphicialReflectionKit.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/GraphicialReflectionKit.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/MainViewerGUI.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/MainViewerGUI.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/MainViewerGUI.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/MainViewerGUI.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/MaliciousCodeScannerOptions.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/MaliciousCodeScannerOptions.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/MaliciousCodeScannerOptions.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/MaliciousCodeScannerOptions.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/PaneUpdaterThread.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/PaneUpdaterThread.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/PaneUpdaterThread.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/PaneUpdaterThread.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/ReplaceStringsOptions.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/ReplaceStringsOptions.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/ReplaceStringsOptions.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/ReplaceStringsOptions.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/RunOptions.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/RunOptions.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/RunOptions.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/RunOptions.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/SearchingPane.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/SearchingPane.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/SearchingPane.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/SearchingPane.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/SystemErrConsole.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/SystemErrConsole.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/SystemErrConsole.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/SystemErrConsole.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/TabbedPane.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/TabbedPane.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/TabbedPane.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/TabbedPane.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/Viewer.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/Viewer.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/Viewer.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/Viewer.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/VisibleComponent.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/VisibleComponent.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/VisibleComponent.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/VisibleComponent.java diff --git a/src/the/bytecode/club/bytecodeviewer/gui/WorkPane.java b/src/main/java/the/bytecode/club/bytecodeviewer/gui/WorkPane.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/gui/WorkPane.java rename to src/main/java/the/bytecode/club/bytecodeviewer/gui/WorkPane.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/JavaObfuscator.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/JavaObfuscator.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/JavaObfuscator.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/JavaObfuscator.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameClasses.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/RenameFields.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameFields.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/RenameFields.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameFields.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/RenameMethods.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameMethods.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/RenameMethods.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/RenameMethods.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/HookMap.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/HookMap.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/HookMap.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/HookMap.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RefactorMapper.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RefactorMapper.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RefactorMapper.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RefactorMapper.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Refactorer.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Refactorer.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Refactorer.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Refactorer.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Remapper.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Remapper.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Remapper.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/Remapper.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingAnnotationAdapter.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingAnnotationAdapter.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingAnnotationAdapter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingAnnotationAdapter.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingClassAdapter.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingClassAdapter.java similarity index 97% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingClassAdapter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingClassAdapter.java index 3aceb011..3cf60119 100644 --- a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingClassAdapter.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingClassAdapter.java @@ -1,136 +1,136 @@ -package the.bytecode.club.bytecodeviewer.obfuscators.mapping; - -/*** - * ASM: a very small and fast Java bytecode manipulation framework - * Copyright (c) 2000-2011 INRIA, France Telecom - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of the copyright holders nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - * THE POSSIBILITY OF SUCH DAMAGE. - */ - -import org.objectweb.asm.AnnotationVisitor; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.TypePath; - -/** - * A {@link ClassVisitor} for type remapping. - * - * @author Eugene Kuleshov - */ -public class RemappingClassAdapter extends ClassVisitor { - - protected final Remapper remapper; - - protected String className; - - public RemappingClassAdapter(final ClassVisitor cv, final Remapper remapper) { - this(Opcodes.ASM5, cv, remapper); - } - - protected RemappingClassAdapter(final int api, final ClassVisitor cv, - final Remapper remapper) { - super(api, cv); - this.remapper = remapper; - } - - @Override - public void visit(int version, int access, String name, String signature, - String superName, String[] interfaces) { - this.className = name; - super.visit(version, access, remapper.mapType(name), remapper - .mapSignature(signature, false), remapper.mapType(superName), - interfaces == null ? null : remapper.mapTypes(interfaces)); - } - - @Override - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - AnnotationVisitor av = super.visitAnnotation(remapper.mapDesc(desc), - visible); - return av == null ? null : createRemappingAnnotationAdapter(av); - } - - @Override - public AnnotationVisitor visitTypeAnnotation(int typeRef, - TypePath typePath, String desc, boolean visible) { - AnnotationVisitor av = super.visitTypeAnnotation(typeRef, typePath, - remapper.mapDesc(desc), visible); - return av == null ? null : createRemappingAnnotationAdapter(av); - } - - @Override - public FieldVisitor visitField(int access, String name, String desc, - String signature, Object value) { - FieldVisitor fv = super.visitField(access, - remapper.mapFieldName(className, name, desc), - remapper.mapDesc(desc), remapper.mapSignature(signature, true), - remapper.mapValue(value)); - return fv == null ? null : createRemappingFieldAdapter(fv); - } - - @Override - public MethodVisitor visitMethod(int access, String name, String desc, - String signature, String[] exceptions) { - String newDesc = remapper.mapMethodDesc(desc); - MethodVisitor mv = super.visitMethod(access, remapper.mapMethodName( - className, name, desc), newDesc, remapper.mapSignature( - signature, false), - exceptions == null ? null : remapper.mapTypes(exceptions)); - return mv == null ? null : createRemappingMethodAdapter(access, - newDesc, mv); - } - - @Override - public void visitInnerClass(String name, String outerName, - String innerName, int access) { - // TODO should innerName be changed? - super.visitInnerClass(remapper.mapType(name), outerName == null ? null - : remapper.mapType(outerName), innerName, access); - } - - @Override - public void visitOuterClass(String owner, String name, String desc) { - super.visitOuterClass(remapper.mapType(owner), name == null ? null - : remapper.mapMethodName(owner, name, desc), - desc == null ? null : remapper.mapMethodDesc(desc)); - } - - protected FieldVisitor createRemappingFieldAdapter(FieldVisitor fv) { - return new RemappingFieldAdapter(fv, remapper); - } - - protected MethodVisitor createRemappingMethodAdapter(int access, - String newDesc, MethodVisitor mv) { - return new RemappingMethodAdapter(access, newDesc, mv, remapper); - } - - protected AnnotationVisitor createRemappingAnnotationAdapter( - AnnotationVisitor av) { - return new RemappingAnnotationAdapter(av, remapper); - } -} - +package the.bytecode.club.bytecodeviewer.obfuscators.mapping; + +/*** + * ASM: a very small and fast Java bytecode manipulation framework + * Copyright (c) 2000-2011 INRIA, France Telecom + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.TypePath; + +/** + * A {@link ClassVisitor} for type remapping. + * + * @author Eugene Kuleshov + */ +public class RemappingClassAdapter extends ClassVisitor { + + protected final Remapper remapper; + + protected String className; + + public RemappingClassAdapter(final ClassVisitor cv, final Remapper remapper) { + this(Opcodes.ASM5, cv, remapper); + } + + protected RemappingClassAdapter(final int api, final ClassVisitor cv, + final Remapper remapper) { + super(api, cv); + this.remapper = remapper; + } + + @Override + public void visit(int version, int access, String name, String signature, + String superName, String[] interfaces) { + this.className = name; + super.visit(version, access, remapper.mapType(name), remapper + .mapSignature(signature, false), remapper.mapType(superName), + interfaces == null ? null : remapper.mapTypes(interfaces)); + } + + @Override + public AnnotationVisitor visitAnnotation(String desc, boolean visible) { + AnnotationVisitor av = super.visitAnnotation(remapper.mapDesc(desc), + visible); + return av == null ? null : createRemappingAnnotationAdapter(av); + } + + @Override + public AnnotationVisitor visitTypeAnnotation(int typeRef, + TypePath typePath, String desc, boolean visible) { + AnnotationVisitor av = super.visitTypeAnnotation(typeRef, typePath, + remapper.mapDesc(desc), visible); + return av == null ? null : createRemappingAnnotationAdapter(av); + } + + @Override + public FieldVisitor visitField(int access, String name, String desc, + String signature, Object value) { + FieldVisitor fv = super.visitField(access, + remapper.mapFieldName(className, name, desc), + remapper.mapDesc(desc), remapper.mapSignature(signature, true), + remapper.mapValue(value)); + return fv == null ? null : createRemappingFieldAdapter(fv); + } + + @Override + public MethodVisitor visitMethod(int access, String name, String desc, + String signature, String[] exceptions) { + String newDesc = remapper.mapMethodDesc(desc); + MethodVisitor mv = super.visitMethod(access, remapper.mapMethodName( + className, name, desc), newDesc, remapper.mapSignature( + signature, false), + exceptions == null ? null : remapper.mapTypes(exceptions)); + return mv == null ? null : createRemappingMethodAdapter(access, + newDesc, mv); + } + + @Override + public void visitInnerClass(String name, String outerName, + String innerName, int access) { + // TODO should innerName be changed? + super.visitInnerClass(remapper.mapType(name), outerName == null ? null + : remapper.mapType(outerName), innerName, access); + } + + @Override + public void visitOuterClass(String owner, String name, String desc) { + super.visitOuterClass(remapper.mapType(owner), name == null ? null + : remapper.mapMethodName(owner, name, desc), + desc == null ? null : remapper.mapMethodDesc(desc)); + } + + protected FieldVisitor createRemappingFieldAdapter(FieldVisitor fv) { + return new RemappingFieldAdapter(fv, remapper); + } + + protected MethodVisitor createRemappingMethodAdapter(int access, + String newDesc, MethodVisitor mv) { + return new RemappingMethodAdapter(access, newDesc, mv, remapper); + } + + protected AnnotationVisitor createRemappingAnnotationAdapter( + AnnotationVisitor av) { + return new RemappingAnnotationAdapter(av, remapper); + } +} + diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingFieldAdapter.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingFieldAdapter.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingFieldAdapter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingFieldAdapter.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingMethodAdapter.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingMethodAdapter.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingMethodAdapter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingMethodAdapter.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingSignatureAdapter.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingSignatureAdapter.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingSignatureAdapter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/RemappingSignatureAdapter.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/FieldMappingData.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/FieldMappingData.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/FieldMappingData.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/FieldMappingData.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MappingData.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MappingData.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MappingData.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MappingData.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MethodMappingData.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MethodMappingData.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MethodMappingData.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/mapping/data/MethodMappingData.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameClasses.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameClasses.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameClasses.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameClasses.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameFields.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameFields.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameFields.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameFields.java diff --git a/src/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameMethods.java b/src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameMethods.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameMethods.java rename to src/main/java/the/bytecode/club/bytecodeviewer/obfuscators/rename/RenameMethods.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/PluginLaunchStrategy.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/PluginLaunchStrategy.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/PluginLaunchStrategy.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/PluginLaunchStrategy.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/PluginManager.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/PluginManager.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/PluginManager.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/PluginManager.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/AllatoriStringDecrypter.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/AllatoriStringDecrypter.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/AllatoriStringDecrypter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/AllatoriStringDecrypter.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/CodeSequenceDiagram.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/CodeSequenceDiagram.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/CodeSequenceDiagram.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/CodeSequenceDiagram.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/EZInjection.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/EZInjection.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/EZInjection.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/EZInjection.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/MaliciousCodeScanner.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/MaliciousCodeScanner.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/MaliciousCodeScanner.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/MaliciousCodeScanner.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ReplaceStrings.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ReplaceStrings.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ReplaceStrings.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ReplaceStrings.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ShowAllStrings.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ShowAllStrings.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ShowAllStrings.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ShowAllStrings.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ShowMainMethods.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ShowMainMethods.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ShowMainMethods.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ShowMainMethods.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/StackFramesRemover.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/StackFramesRemover.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/StackFramesRemover.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/StackFramesRemover.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZKMStringDecrypter.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZKMStringDecrypter.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZKMStringDecrypter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZKMStringDecrypter.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZStringArrayDecrypter.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZStringArrayDecrypter.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZStringArrayDecrypter.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/preinstalled/ZStringArrayDecrypter.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/strategies/CompiledJavaPluginLaunchStrategy.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/CompiledJavaPluginLaunchStrategy.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/strategies/CompiledJavaPluginLaunchStrategy.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/CompiledJavaPluginLaunchStrategy.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/strategies/GroovyPluginLaunchStrategy.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/GroovyPluginLaunchStrategy.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/strategies/GroovyPluginLaunchStrategy.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/GroovyPluginLaunchStrategy.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/strategies/JavaPluginLaunchStrategy.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/JavaPluginLaunchStrategy.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/strategies/JavaPluginLaunchStrategy.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/JavaPluginLaunchStrategy.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/strategies/PythonPluginLaunchStrategy.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/PythonPluginLaunchStrategy.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/strategies/PythonPluginLaunchStrategy.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/PythonPluginLaunchStrategy.java diff --git a/src/the/bytecode/club/bytecodeviewer/plugin/strategies/RubyPluginLaunchStrategy.java b/src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/RubyPluginLaunchStrategy.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/plugin/strategies/RubyPluginLaunchStrategy.java rename to src/main/java/the/bytecode/club/bytecodeviewer/plugin/strategies/RubyPluginLaunchStrategy.java diff --git a/src/the/bytecode/club/bytecodeviewer/searching/BackgroundSearchThread.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/BackgroundSearchThread.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/searching/BackgroundSearchThread.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/BackgroundSearchThread.java diff --git a/src/the/bytecode/club/bytecodeviewer/searching/EnterKeyEvent.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/EnterKeyEvent.java similarity index 96% rename from src/the/bytecode/club/bytecodeviewer/searching/EnterKeyEvent.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/EnterKeyEvent.java index 4fa46436..5889f723 100644 --- a/src/the/bytecode/club/bytecodeviewer/searching/EnterKeyEvent.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/searching/EnterKeyEvent.java @@ -1,23 +1,23 @@ -package the.bytecode.club.bytecodeviewer.searching; - -import the.bytecode.club.bytecodeviewer.BytecodeViewer; - -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; - -public class EnterKeyEvent implements KeyListener -{ - public static final EnterKeyEvent SINGLETON = new EnterKeyEvent(); - - @Override public void keyTyped(KeyEvent e) { } - - @Override public void keyPressed(KeyEvent e) { - if(e.getKeyCode() == KeyEvent.VK_ENTER) - { - BytecodeViewer.viewer.s.search(); - } - } - - @Override public void keyReleased(KeyEvent e) { } - -} +package the.bytecode.club.bytecodeviewer.searching; + +import the.bytecode.club.bytecodeviewer.BytecodeViewer; + +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; + +public class EnterKeyEvent implements KeyListener +{ + public static final EnterKeyEvent SINGLETON = new EnterKeyEvent(); + + @Override public void keyTyped(KeyEvent e) { } + + @Override public void keyPressed(KeyEvent e) { + if(e.getKeyCode() == KeyEvent.VK_ENTER) + { + BytecodeViewer.viewer.s.search(); + } + } + + @Override public void keyReleased(KeyEvent e) { } + +} diff --git a/src/the/bytecode/club/bytecodeviewer/searching/FieldCallSearch.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/FieldCallSearch.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/searching/FieldCallSearch.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/FieldCallSearch.java diff --git a/src/the/bytecode/club/bytecodeviewer/searching/LDCSearch.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/LDCSearch.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/searching/LDCSearch.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/LDCSearch.java diff --git a/src/the/bytecode/club/bytecodeviewer/searching/MethodCallSearch.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/MethodCallSearch.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/searching/MethodCallSearch.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/MethodCallSearch.java diff --git a/src/the/bytecode/club/bytecodeviewer/searching/RegexInsnFinder.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/RegexInsnFinder.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/searching/RegexInsnFinder.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/RegexInsnFinder.java diff --git a/src/the/bytecode/club/bytecodeviewer/searching/RegexSearch.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/RegexSearch.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/searching/RegexSearch.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/RegexSearch.java diff --git a/src/the/bytecode/club/bytecodeviewer/searching/SearchResultNotifier.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/SearchResultNotifier.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/searching/SearchResultNotifier.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/SearchResultNotifier.java diff --git a/src/the/bytecode/club/bytecodeviewer/searching/SearchTypeDetails.java b/src/main/java/the/bytecode/club/bytecodeviewer/searching/SearchTypeDetails.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/searching/SearchTypeDetails.java rename to src/main/java/the/bytecode/club/bytecodeviewer/searching/SearchTypeDetails.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/APKTool.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/APKTool.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/APKTool.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/APKTool.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/Dex2Jar.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/Dex2Jar.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/Dex2Jar.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/Dex2Jar.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/EncodeUtils.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/EncodeUtils.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/EncodeUtils.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/EncodeUtils.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/Enjarify.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/Enjarify.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/Enjarify.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/Enjarify.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/FileChangeNotifier.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/FileChangeNotifier.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/FileChangeNotifier.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/FileChangeNotifier.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/FileContainer.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/FileContainer.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/FileContainer.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/FileContainer.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/FileDrop.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/FileDrop.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/FileDrop.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/FileDrop.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/JRTExtractor.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/JRTExtractor.java similarity index 96% rename from src/the/bytecode/club/bytecodeviewer/util/JRTExtractor.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/JRTExtractor.java index 62ddd6fd..a5e3d4bd 100644 --- a/src/the/bytecode/club/bytecodeviewer/util/JRTExtractor.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/util/JRTExtractor.java @@ -1,59 +1,59 @@ -package the.bytecode.club.bytecodeviewer.util; - -// Copyright 2017 Robert Grosse - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 - -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import java.net.*; -import java.nio.file.*; -import java.util.*; -import java.util.zip.*; - -public class JRTExtractor -{ - public static void extractRT(String path) throws Throwable - { - FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/")); - - try(ZipOutputStream zipStream = new ZipOutputStream(Files.newOutputStream(Paths.get(path)))) - { - Files.walk(fs.getPath("/")).forEach(p -> { - if (!Files.isRegularFile(p)) {return;} - - try - { - byte[] data = Files.readAllBytes(p); - - List list = new ArrayList<>(); - p.iterator().forEachRemaining(p2 -> list.add(p2.toString())); - assert list.remove(0).equals("modules"); - - if (!list.get(list.size()-1).equals("module-info.class")) - { - list.remove(0); - } - - list.remove(0); - String outPath = String.join("/", list); - - if(!outPath.endsWith("module-info.class")) - { - ZipEntry ze = new ZipEntry(outPath); - zipStream.putNextEntry(ze); - zipStream.write(data); - } - } catch (Throwable t) {throw new RuntimeException(t);} - }); - } - } +package the.bytecode.club.bytecodeviewer.util; + +// Copyright 2017 Robert Grosse + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 + +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import java.net.*; +import java.nio.file.*; +import java.util.*; +import java.util.zip.*; + +public class JRTExtractor +{ + public static void extractRT(String path) throws Throwable + { + FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/")); + + try(ZipOutputStream zipStream = new ZipOutputStream(Files.newOutputStream(Paths.get(path)))) + { + Files.walk(fs.getPath("/")).forEach(p -> { + if (!Files.isRegularFile(p)) {return;} + + try + { + byte[] data = Files.readAllBytes(p); + + List list = new ArrayList<>(); + p.iterator().forEachRemaining(p2 -> list.add(p2.toString())); + assert list.remove(0).equals("modules"); + + if (!list.get(list.size()-1).equals("module-info.class")) + { + list.remove(0); + } + + list.remove(0); + String outPath = String.join("/", list); + + if(!outPath.endsWith("module-info.class")) + { + ZipEntry ze = new ZipEntry(outPath); + zipStream.putNextEntry(ze); + zipStream.write(data); + } + } catch (Throwable t) {throw new RuntimeException(t);} + }); + } + } } \ No newline at end of file diff --git a/src/the/bytecode/club/bytecodeviewer/util/JarUtils.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/JarUtils.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/JarUtils.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/JarUtils.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/LazyNameUtil.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/LazyNameUtil.java similarity index 96% rename from src/the/bytecode/club/bytecodeviewer/util/LazyNameUtil.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/LazyNameUtil.java index ad1cdc0e..5e7e8c1a 100644 --- a/src/the/bytecode/club/bytecodeviewer/util/LazyNameUtil.java +++ b/src/main/java/the/bytecode/club/bytecodeviewer/util/LazyNameUtil.java @@ -1,129 +1,129 @@ -package the.bytecode.club.bytecodeviewer.util; - -/*************************************************************************** - * Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite * - * Copyright (C) 2014 Kalen 'Konloch' Kinloch - http://bytecodeviewer.com * - * * - * This program is free software: you can redistribute it and/or modify * - * it under the terms of the GNU General Public License as published by * - * the Free Software Foundation, either version 3 of the License, or * - * (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program. If not, see . * - ***************************************************************************/ - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang3.StringUtils; - -import java.util.HashMap; - -/** - * @author Konloch - */ -public class LazyNameUtil -{ - public static boolean SAME_NAME_JAR_WORKSPACE = false; - - private static final HashMap nameMap = new HashMap<>(); - - public static void reset() - { - nameMap.clear(); - } - - public static String applyNameChanges(String name) { - if (nameMap.containsKey(name)) { - if (!SAME_NAME_JAR_WORKSPACE) { - SAME_NAME_JAR_WORKSPACE = true; - } - - SeqAndCount seqAndCount = nameMap.get(name); - nameMap.put(name, seqAndCount.incrSeqAndCount()); - return FilenameUtils.removeExtension(name) + "#" + seqAndCount.getSeq() + "." + FilenameUtils.getExtension(name); - } else { - nameMap.put(name, SeqAndCount.init()); - } - - return name; - } - - public static void removeName(String name) { - if (StringUtils.isBlank(name)) { - return; - } - - if (name.contains("#")) { - name = name.substring(0, name.indexOf("#")) + name.substring(name.indexOf(".")); - } - - SeqAndCount seqAndCount = nameMap.get(name); - if (seqAndCount == null) { - return; - } - - // sequence remain the same and decrease the count - // still the count become 1 - if (seqAndCount.getCount() == 1) { - nameMap.remove(name); - } else { - nameMap.put(name, seqAndCount.decrCount()); - } - } - -} - - -class SeqAndCount { - Integer seq; - Integer count; - - public static SeqAndCount init() { - SeqAndCount seqAndCount = new SeqAndCount(); - seqAndCount.setSeq(1); - seqAndCount.setCount(1); - return seqAndCount; - } - - public SeqAndCount incrSeq() { - seq = seq + 1; - return this; - } - - public SeqAndCount incrCount() { - count = count + 1; - return this; - } - - public SeqAndCount decrCount() { - count = count - 1; - return this; - } - - public SeqAndCount incrSeqAndCount() { - seq = seq + 1; - count = count + 1; - return this; - } - - public Integer getSeq() { - return seq; - } - - public void setSeq(Integer seq) { - this.seq = seq; - } - - public Integer getCount() { - return count; - } - - public void setCount(Integer count) { - this.count = count; - } +package the.bytecode.club.bytecodeviewer.util; + +/*************************************************************************** + * Bytecode Viewer (BCV) - Java & Android Reverse Engineering Suite * + * Copyright (C) 2014 Kalen 'Konloch' Kinloch - http://bytecodeviewer.com * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program. If not, see . * + ***************************************************************************/ + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.StringUtils; + +import java.util.HashMap; + +/** + * @author Konloch + */ +public class LazyNameUtil +{ + public static boolean SAME_NAME_JAR_WORKSPACE = false; + + private static final HashMap nameMap = new HashMap<>(); + + public static void reset() + { + nameMap.clear(); + } + + public static String applyNameChanges(String name) { + if (nameMap.containsKey(name)) { + if (!SAME_NAME_JAR_WORKSPACE) { + SAME_NAME_JAR_WORKSPACE = true; + } + + SeqAndCount seqAndCount = nameMap.get(name); + nameMap.put(name, seqAndCount.incrSeqAndCount()); + return FilenameUtils.removeExtension(name) + "#" + seqAndCount.getSeq() + "." + FilenameUtils.getExtension(name); + } else { + nameMap.put(name, SeqAndCount.init()); + } + + return name; + } + + public static void removeName(String name) { + if (StringUtils.isBlank(name)) { + return; + } + + if (name.contains("#")) { + name = name.substring(0, name.indexOf("#")) + name.substring(name.indexOf(".")); + } + + SeqAndCount seqAndCount = nameMap.get(name); + if (seqAndCount == null) { + return; + } + + // sequence remain the same and decrease the count + // still the count become 1 + if (seqAndCount.getCount() == 1) { + nameMap.remove(name); + } else { + nameMap.put(name, seqAndCount.decrCount()); + } + } + +} + + +class SeqAndCount { + Integer seq; + Integer count; + + public static SeqAndCount init() { + SeqAndCount seqAndCount = new SeqAndCount(); + seqAndCount.setSeq(1); + seqAndCount.setCount(1); + return seqAndCount; + } + + public SeqAndCount incrSeq() { + seq = seq + 1; + return this; + } + + public SeqAndCount incrCount() { + count = count + 1; + return this; + } + + public SeqAndCount decrCount() { + count = count - 1; + return this; + } + + public SeqAndCount incrSeqAndCount() { + seq = seq + 1; + count = count + 1; + return this; + } + + public Integer getSeq() { + return seq; + } + + public void setSeq(Integer seq) { + this.seq = seq; + } + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } } \ No newline at end of file diff --git a/src/the/bytecode/club/bytecodeviewer/util/MethodParser.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/MethodParser.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/MethodParser.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/MethodParser.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/MiscUtils.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/MiscUtils.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/MiscUtils.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/MiscUtils.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/NewlineOutputStream.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/NewlineOutputStream.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/NewlineOutputStream.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/NewlineOutputStream.java diff --git a/src/the/bytecode/club/bytecodeviewer/util/ZipUtils.java b/src/main/java/the/bytecode/club/bytecodeviewer/util/ZipUtils.java similarity index 100% rename from src/the/bytecode/club/bytecodeviewer/util/ZipUtils.java rename to src/main/java/the/bytecode/club/bytecodeviewer/util/ZipUtils.java diff --git a/src/Krakatau-12.zip b/src/main/resources/Krakatau-12.zip similarity index 100% rename from src/Krakatau-12.zip rename to src/main/resources/Krakatau-12.zip diff --git a/src/enjarify-4.zip b/src/main/resources/enjarify-4.zip similarity index 100% rename from src/enjarify-4.zip rename to src/main/resources/enjarify-4.zip diff --git a/src/resources/1.gif b/src/main/resources/resources/1.gif similarity index 100% rename from src/resources/1.gif rename to src/main/resources/resources/1.gif diff --git a/src/resources/android.png b/src/main/resources/resources/android.png similarity index 100% rename from src/resources/android.png rename to src/main/resources/resources/android.png diff --git a/src/resources/bat.png b/src/main/resources/resources/bat.png similarity index 100% rename from src/resources/bat.png rename to src/main/resources/resources/bat.png diff --git a/src/resources/c#.png b/src/main/resources/resources/c#.png similarity index 100% rename from src/resources/c#.png rename to src/main/resources/resources/c#.png diff --git a/src/resources/c++.png b/src/main/resources/resources/c++.png similarity index 100% rename from src/resources/c++.png rename to src/main/resources/resources/c++.png diff --git a/src/resources/class.png b/src/main/resources/resources/class.png similarity index 100% rename from src/resources/class.png rename to src/main/resources/resources/class.png diff --git a/src/resources/config.png b/src/main/resources/resources/config.png similarity index 100% rename from src/resources/config.png rename to src/main/resources/resources/config.png diff --git a/src/resources/decoded.png b/src/main/resources/resources/decoded.png similarity index 100% rename from src/resources/decoded.png rename to src/main/resources/resources/decoded.png diff --git a/src/resources/file.png b/src/main/resources/resources/file.png similarity index 100% rename from src/resources/file.png rename to src/main/resources/resources/file.png diff --git a/src/resources/folder.png b/src/main/resources/resources/folder.png similarity index 100% rename from src/resources/folder.png rename to src/main/resources/resources/folder.png diff --git a/src/resources/image.png b/src/main/resources/resources/image.png similarity index 100% rename from src/resources/image.png rename to src/main/resources/resources/image.png diff --git a/src/resources/intro.html b/src/main/resources/resources/intro.html similarity index 100% rename from src/resources/intro.html rename to src/main/resources/resources/intro.html diff --git a/src/resources/jar.png b/src/main/resources/resources/jar.png similarity index 100% rename from src/resources/jar.png rename to src/main/resources/resources/jar.png diff --git a/src/resources/java.png b/src/main/resources/resources/java.png similarity index 100% rename from src/resources/java.png rename to src/main/resources/resources/java.png diff --git a/src/resources/package.png b/src/main/resources/resources/package.png similarity index 100% rename from src/resources/package.png rename to src/main/resources/resources/package.png diff --git a/src/resources/sh.png b/src/main/resources/resources/sh.png similarity index 100% rename from src/resources/sh.png rename to src/main/resources/resources/sh.png diff --git a/src/resources/text.png b/src/main/resources/resources/text.png similarity index 100% rename from src/resources/text.png rename to src/main/resources/resources/text.png diff --git a/src/resources/zip.png b/src/main/resources/resources/zip.png similarity index 100% rename from src/resources/zip.png rename to src/main/resources/resources/zip.png