Initial v2 assembler and diassembler

This commit is contained in:
Robert Grosse 2022-10-16 16:41:18 -07:00
parent b4fd92ddab
commit 3b4a96ac79
41 changed files with 8305 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
/target
/out
out.*
temp.*
Cargo.lock

20
Cargo.toml Normal file
View File

@ -0,0 +1,20 @@
[package]
name = "krakatau2"
version = "2.0.0-alpha"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "3.1.18", features = ["derive"] }
lazy_static = "1.4.0"
regex = "1.4.3"
zip = "0.6.2"
hexf-parse = "0.2.1"
typed-arena = "2.0.1"
[[bin]]
name = "krak2"
path = "src/main.rs"

674
LICENSE.TXT Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

2
rustfmt.toml Normal file
View File

@ -0,0 +1,2 @@
max_width = 125
fn_call_width = 90

49
src/ass_main.rs Normal file
View File

@ -0,0 +1,49 @@
use std::path::PathBuf;
use clap::Parser;
use crate::file_input_util;
use crate::file_output_util::Writer;
use crate::lib::assemble;
use crate::lib::AssemblerOptions;
#[derive(Parser)]
pub struct AssemblerCli {
input: PathBuf,
#[clap(short, long, parse(from_os_str))]
out: PathBuf,
}
pub fn assembler_main(cli: AssemblerCli) -> i32 {
let opts = AssemblerOptions {};
let mut writer = Writer::new(&cli.out);
let mut error_count = 0;
file_input_util::read_files(&cli.input, "j", |fname, data| {
let data = std::str::from_utf8(data).expect(".j files must be utf8-encoded");
// let classes = assemble(&data, opts)?;
let res = assemble(&data, opts);
let classes = match res {
Ok(classes) => classes,
Err(err) => {
err.display(fname, data);
error_count += 1;
return;
}
};
println!("got {} classes", classes.len());
for (name, out) in classes {
let name = name.map(|name| format!("{}.class", name));
writer.write(name.as_deref(), &out);
println!("Wrote {} bytes to {}", out.len(), name.as_deref().unwrap_or("file"));
}
});
// set exit code 1 if there were errors
if error_count > 0 {
1
} else {
0
}
}

55
src/dis_main.rs Normal file
View File

@ -0,0 +1,55 @@
use std::path::PathBuf;
use clap::Parser;
use crate::file_input_util;
use crate::file_output_util::Writer;
use crate::lib::disassemble;
use crate::lib::DisassemblerOptions;
use crate::lib::ParserOptions;
#[derive(Parser)]
pub struct DisassemblerCli {
input: PathBuf,
#[clap(short, long, parse(from_os_str))]
out: PathBuf,
#[clap(short, long)]
roundtrip: bool,
#[clap(long)]
no_short_code_attr: bool,
}
pub fn disassembler_main(cli: DisassemblerCli) -> i32 {
let opts = DisassemblerOptions {
roundtrip: cli.roundtrip,
};
let parse_opts = ParserOptions {
no_short_code_attr: cli.no_short_code_attr,
};
let mut writer = Writer::new(&cli.out);
let mut error_count = 0;
file_input_util::read_files(&cli.input, "class", |fname, data| {
println!("disassemble {}", fname);
let (name, out) = match disassemble(&data, parse_opts, opts) {
Ok(v) => v,
Err(err) => {
eprintln!("Parse error in {}: {}", fname, err.0);
error_count += 1;
return;
}
};
let name = name.map(|name| format!("{}.j", name));
writer.write(name.as_deref(), &out);
println!("Wrote {} bytes to {}", out.len(), name.as_deref().unwrap_or("file"));
});
// set exit code 1 if there were errors
if error_count > 0 {
1
} else {
0
}
}

42
src/file_input_util.rs Normal file
View File

@ -0,0 +1,42 @@
use std::fs;
use std::io::Read;
use std::path::Path;
// pub fn read_files<E>(p: &Path, ext: &str, mut cb: impl FnMut(&[u8]) -> Result<(), E>) -> Result<(), E> {
pub fn read_files(p: &Path, ext: &str, mut cb: impl FnMut(&str, &[u8])) {
let input_ext = p
.extension()
.and_then(|s| s.to_str())
.expect("Missing input filename extension");
let input_ext = input_ext.to_ascii_lowercase();
if input_ext == ext {
let data = fs::read(p).expect("Error reading input file");
cb(&p.to_string_lossy(), &data);
} else if input_ext == "jar" || input_ext == "zip" {
let mut inbuf = Vec::new();
let file = fs::File::open(p).expect("Error reading input file");
let mut zip = zip::ZipArchive::new(file).expect("Error parsing archive");
let ext = format!(".{}", ext); // temp hack
for i in 0..zip.len() {
let mut file = zip.by_index(i).expect("Error parsing archive");
// println!("found {} {:?} {} {}", i, file.name(), file.size(), file.compressed_size());
let name = file.name().to_owned();
if !name.ends_with(&ext) {
continue;
}
inbuf.clear();
inbuf.reserve(file.size() as usize);
file.read_to_end(&mut inbuf).unwrap();
// println!("read {} bytes", inbuf.len());
cb(&name, &inbuf);
}
} else {
panic!("Unsupported input extension {}", input_ext)
}
// Ok(())
}

75
src/file_output_util.rs Normal file
View File

@ -0,0 +1,75 @@
use std::fs;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
pub enum Writer {
Dir(PathBuf),
Jar(zip::ZipWriter<fs::File>),
Merged(fs::File),
Single(fs::File, bool),
}
impl Writer {
pub fn new(p: &Path) -> Self {
fs::create_dir_all(p.parent().unwrap()).unwrap();
if p.is_dir() {
return Self::Dir(p.into());
}
let f = fs::File::create(p).unwrap();
let ext = p.extension().and_then(|s| s.to_str());
if let Some(s) = ext {
match s.to_ascii_lowercase().as_str() {
"jar" | "zip" => Self::Jar(zip::ZipWriter::new(f)),
"j" => Self::Merged(f),
"class" => Self::Single(f, false),
_ => panic!("Unsupported output extension {}", s),
}
} else {
panic!("Unsupported output extension {:?}", ext)
}
}
pub fn write(&mut self, name: Option<&str>, data: &[u8]) {
use Writer::*;
match self {
Dir(dir) => {
let name =
name.expect("Class has missing or invalid name. Try specifying a single file output name explicitly.");
if name.contains("..") {
panic!("Invalid path {}. Try outputting to a zip file instead.", name)
} else {
let p = dir.join(name);
println!("Writing to {}", p.display());
fs::create_dir_all(p.parent().unwrap())
.expect("Unable to create directory. Try outputting to a zip file instead");
let mut f = fs::File::create(p).expect("Unable to create file. Try outputting to a zip file instead");
f.write_all(data).unwrap();
}
}
Jar(zw) => {
let name =
name.expect("Class has missing or invalid name. Try specifying a single file output name explicitly.");
let options = zip::write::FileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.last_modified_time(zip::DateTime::default());
zw.start_file(name, options).unwrap();
zw.write_all(data).unwrap();
}
Merged(f) => {
f.write_all(data).unwrap();
}
Single(f, used) => {
if *used {
panic!(
"Error: Attempting to write multiple classes to single file. Try outputting to a zip file instead."
)
}
f.write_all(data).unwrap();
*used = true;
}
}
}
}

View File

@ -0,0 +1,127 @@
use super::parse_literal;
use super::span::Error;
use super::span::ErrorMaker;
use super::span::Span;
use super::tokenize::Token;
use super::tokenize::TokenType;
type Iter<'a> = std::iter::Peekable<std::vec::IntoIter<Token<'a>>>;
macro_rules! define_int_parse {
($t:ident) => {
pub fn $t(&mut self) -> Result<$t, Error> {
let tok = self.int()?;
parse_literal::int(tok.1 .0).ok_or_else(|| {
self.error1(&format!("Value must be in range {} <= {} <= {}", $t::MIN, tok.1 .0, $t::MAX), tok.1)
})
}
};
}
pub struct BaseParser<'a> {
error_maker: ErrorMaker<'a>,
source: &'a str,
tokens: Iter<'a>,
}
impl<'a> BaseParser<'a> {
pub fn new(source: &'a str, tokens: Vec<Token<'a>>) -> Self {
Self {
error_maker: ErrorMaker::new(source),
source,
tokens: tokens.into_iter().peekable(),
}
}
pub fn has_tokens_left(&mut self) -> bool {
self.tokens.peek().is_some()
}
pub fn next(&mut self) -> Result<Token<'a>, Error> {
self.tokens.next().ok_or_else(|| {
let tok = Token(TokenType::Newlines, Span(&self.source[self.source.len()..]));
self.error1("Error: Unexpected end of file", tok.1)
})
}
pub fn peek(&mut self) -> Result<Token<'a>, Error> {
self.tokens.peek().copied().ok_or_else(|| {
let tok = Token(TokenType::Newlines, Span(&self.source[self.source.len()..]));
self.error1("Error: Unexpected end of file", tok.1)
})
}
pub fn fail<T>(&mut self) -> Result<T, Error> {
let tok = self.next()?;
self.err1("Error: Unexpected token", tok.1)
}
pub fn tryv(&mut self, v: &str) -> bool {
self.tokens.next_if(|tok| tok.1 .0 == v).is_some()
}
pub fn tryv2(&mut self, v: &str) -> Option<Span<'a>> {
self.tokens.next_if(|tok| tok.1 .0 == v).map(|tok| tok.1)
}
pub fn has_type(&mut self, ty: TokenType) -> bool {
if let Some(tok) = self.tokens.peek() {
tok.0 == ty
} else {
false
}
}
pub fn val(&mut self, v: &str) -> Result<(), Error> {
if self.tryv(v) {
Ok(())
} else {
let span = self.next()?.1;
self.err1str(format!("Expected {}", v), span)
}
}
pub fn assert_type(&mut self, ty: TokenType) -> Result<Span<'a>, Error> {
let tok = self.next()?;
if tok.0 == ty {
Ok(tok.1)
} else {
self.fail()
}
}
pub fn eol(&mut self) -> Result<(), Error> {
let tok = self.next()?;
if tok.0 == TokenType::Newlines {
Ok(())
} else {
self.err1("Error: Expected end of line", tok.1)
}
}
///////////////////////////////////////////////////////////////////////////
pub fn int(&mut self) -> Result<Token<'a>, Error> {
let tok = self.next()?;
if tok.0 != TokenType::IntLit {
self.err1("Expected integer", tok.1)
} else {
Ok(tok)
}
}
define_int_parse!(u8);
define_int_parse!(u16);
define_int_parse!(u32);
define_int_parse!(i8);
define_int_parse!(i16);
define_int_parse!(i32);
// define_int_parse!(i64);
///////////////////////////////////////////////////////////////////////////
}
impl<'a> std::ops::Deref for BaseParser<'a> {
type Target = ErrorMaker<'a>;
fn deref(&self) -> &Self::Target {
&self.error_maker
}
}

View File

@ -0,0 +1,370 @@
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt::Display;
use typed_arena::Arena;
use super::base_parser::BaseParser;
use super::cpool;
use super::cpool::types;
use super::cpool::InlineConst;
use super::cpool::Or;
use super::cpool::Pool;
use super::flags::FlagList;
use super::label::Pos;
use super::parse_literal;
use super::span::Error;
use super::span::Span;
use super::string;
use super::tokenize::Token;
use super::tokenize::TokenType;
use super::writer::Writer;
use crate::lib::assemble::span::Spanned;
use crate::lib::mhtags;
use crate::lib::util::BStr;
/// Shorthand function to convert spanned const ref to non-spanned version
pub fn ns<'a, T, U>(r: Or<T, Spanned<'a, U>>) -> Or<T, U> {
r.map_b(|c| c.v)
}
pub struct ClassParser<'a> {
pub parser: BaseParser<'a>,
arena: &'a Arena<Vec<u8>>,
pub version: (u16, u16),
pub pool: cpool::Pool<'a>,
// Temporary values only set during parsing of Code attributes
pub labels: HashMap<&'a str, Pos>,
pub stack_map_table: Option<(u16, Writer<'a>)>,
}
impl<'a> std::ops::Deref for ClassParser<'a> {
type Target = BaseParser<'a>;
fn deref(&self) -> &Self::Target {
&self.parser
}
}
impl<'a> std::ops::DerefMut for ClassParser<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.parser
}
}
impl<'a> ClassParser<'a> {
pub fn new(parser: BaseParser<'a>, arena: &'a Arena<Vec<u8>>) -> Self {
let pool = Pool::new(*parser);
Self {
parser,
arena,
version: (49, 0),
pool,
labels: HashMap::new(),
stack_map_table: None,
}
}
pub fn ref_type(&self, span: Span<'a>) -> Result<types::RefType<'a>, Error> {
lazy_static! {
static ref DIGITS_RE: Regex = Regex::new(r"\A[0-9]+\z").unwrap();
}
let s = span.0;
let mut s = &s[1..s.len() - 1];
if s.starts_with("bs:") {
s = &s[3..];
}
Ok(if DIGITS_RE.is_match(s) {
let ind = s.parse().map_err(|_| self.error1("Invalid numeric reference", span))?;
types::RefType::Raw(ind)
} else {
types::RefType::Sym(span.of(s))
})
}
pub fn ref_from<T>(&self, span: Span<'a>) -> Result<cpool::RefOr<'a, T>, Error> {
Ok(Or::A(self.ref_type(span)?))
}
pub fn make_utf_ref(&self, b: &'a [u8], span: Span<'a>) -> Result<types::SymSpanUtf8<'a>, Error> {
if b.len() > u16::MAX as usize {
self.err1("Constant strings must be at most 65535 bytes in MUTF8 encoding.", span)
} else {
Ok(Or::B(span.of(types::InlineUtf8(BStr(b)))))
}
}
pub fn utf_from(&self, tok: Token<'a>) -> Result<types::SymSpanUtf8<'a>, Error> {
use TokenType::*;
match tok.0 {
Word => self.make_utf_ref(tok.1 .0.as_bytes(), tok.1),
Ref => self.ref_from(tok.1),
StringLit => {
// let bs = string::unescape(tok.1 .0).ok_or_else(|| self.error1("Invalid string literal", tok.1))?;
let bs = string::unescape(tok.1 .0).map_err(|(msg, s)| self.error1(msg, Span(s)))?;
let bs = self.arena.alloc(bs);
self.make_utf_ref(bs, tok.1)
}
_ => self.err1("Expected identifier or constant pool ref", tok.1),
}
}
pub fn utf(&mut self) -> Result<types::SymSpanUtf8<'a>, Error> {
let tok = self.next()?;
self.utf_from(tok)
}
pub fn cls_from(&self, tok: Token<'a>) -> Result<types::SymSpanClass<'a>, Error> {
match tok.0 {
TokenType::Ref => self.ref_from(tok.1),
_ => Ok(Or::B(tok.1.of(types::InlineClass(ns(self.utf_from(tok)?))))),
}
}
pub fn cls(&mut self) -> Result<types::SymSpanClass<'a>, Error> {
let tok = self.next()?;
self.cls_from(tok)
}
pub fn single(
&mut self,
f: fn(types::SymUtf8Ref<'a>) -> types::SymConstInline<'a>,
) -> Result<types::SymSpanConst<'a>, Error> {
let tok = self.next()?;
match tok.0 {
TokenType::Ref => self.ref_from(tok.1),
_ => Ok(Or::B(tok.1.of(f(ns(self.utf_from(tok)?))))),
}
}
pub fn nat(&mut self) -> Result<types::SymSpanNat<'a>, Error> {
let tok = self.next()?;
if tok.0 == TokenType::Ref {
self.ref_from(tok.1)
} else {
let name = ns(self.utf_from(tok)?);
let desc = ns(self.utf()?);
Ok(Or::B(tok.1.of(types::InlineNat(name, desc))))
}
}
pub fn mhnotref(&mut self, tag_span: Span<'a>) -> Result<types::SymSpanConstInline<'a>, Error> {
let tag = mhtags::parse(tag_span.0).ok_or_else(|| self.error1("Invalid method handle tag", tag_span))?;
let body = Box::new(ns(self.ref_or_tagged_const()?));
Ok(tag_span.of(InlineConst::MethodHandle(tag, body)))
}
pub fn bs_args(&mut self, mh: types::SymSpanConst<'a>) -> Result<types::SymBsInline<'a>, Error> {
let mut bsargs = vec![mh];
while !self.tryv(":") {
if bsargs.len() >= 65536 {
// Can have up to 65536 elements because initial mh doesn't count towards length
// todo - add test
let next_span = self.peek()?.1;
return self.err1("Maximum number of arguments to bootstrap method (65535) exceeded", next_span);
}
bsargs.push(self.ref_or_tagged_const()?);
}
Ok(types::InlineBs(bsargs))
}
pub fn bsref(&mut self) -> Result<types::SymBsRef<'a>, Error> {
let tok = self.next()?;
match tok.0 {
TokenType::BsRef => self.ref_from(tok.1),
TokenType::Word => {
let mh = Or::B(self.mhnotref(tok.1)?);
Ok(Or::B(self.bs_args(mh)?))
}
_ => self.err1("Expected methodhandle tag or bootstrap ref", tok.1),
}
}
pub fn float_from(&mut self, span: Span<'a>) -> Result<types::SymConstInline<'a>, Error> {
let s = span.0.trim_end_matches('f');
Ok(InlineConst::Float(
parse_literal::float(s).ok_or_else(|| self.error1("Invalid float literal", span))?,
))
}
pub fn double_from(&mut self, span: Span<'a>) -> Result<types::SymConstInline<'a>, Error> {
Ok(InlineConst::Double(
parse_literal::double(span.0).ok_or_else(|| self.error1("Invalid double literal", span))?,
))
}
pub fn long_from(&mut self, span: Span<'a>) -> Result<types::SymConstInline<'a>, Error> {
let s = span.0.trim_end_matches('L');
let i = parse_literal::int::<i64>(s).ok_or_else(|| self.error1("Invalid long literal", span))?;
Ok(InlineConst::Long(i as u64))
}
pub fn int_from(&mut self, span: Span<'a>) -> Result<types::SymConstInline<'a>, Error> {
let i = parse_literal::int::<i32>(span.0).ok_or_else(|| self.error1("Invalid integer literal", span))?;
Ok(InlineConst::Int(i as u32))
}
pub fn tagged_const_from(&mut self, span: Span<'a>) -> Result<types::SymConstInline<'a>, Error> {
use InlineConst::*;
Ok(match span.0 {
"Utf8" => {
let tok = self.next()?;
Utf8(match self.utf_from(tok)? {
Or::A(_) => return self.err1("Expected identifier or string, not ref", span),
Or::B(b) => b.v.0,
})
}
"Int" => Int(self.i32()? as u32),
"Float" => {
let span = self.assert_type(TokenType::FloatLit)?;
self.float_from(span)?
}
"Long" => {
let span = self.assert_type(TokenType::LongLit)?;
self.long_from(span)?
}
"Double" => {
let span = self.assert_type(TokenType::DoubleLit)?;
self.double_from(span)?
}
"Class" => Class(ns(self.utf()?)),
"String" => Str(ns(self.utf()?)),
"MethodType" => MethodType(ns(self.utf()?)),
"Module" => Module(ns(self.utf()?)),
"Package" => Package(ns(self.utf()?)),
"Field" => Field(ns(self.cls()?), ns(self.nat()?)),
"Method" => Method(ns(self.cls()?), ns(self.nat()?)),
"InterfaceMethod" => InterfaceMethod(ns(self.cls()?), ns(self.nat()?)),
"NameAndType" => NameAndType(ns(self.utf()?), ns(self.utf()?)),
"MethodHandle" => {
let tag_span = self.assert_type(TokenType::Word)?;
self.mhnotref(tag_span)?.v
}
"Dynamic" => Dynamic(self.bsref()?, ns(self.nat()?)),
"InvokeDynamic" => InvokeDynamic(self.bsref()?, ns(self.nat()?)),
_ => return self.err1("Unrecognized constant tag", span),
})
}
pub fn ref_or_tagged_const(&mut self) -> Result<types::SymSpanConst<'a>, Error> {
use TokenType::*;
let tok = self.next()?;
match tok.0 {
Ref => self.ref_from(tok.1),
Word => Ok(Or::B(tok.1.of(self.tagged_const_from(tok.1)?))),
_ => self.err1("Expected constant pool tag (Utf8, Int, String, NameAndType, etc.) or reference", tok.1),
}
}
pub fn ref_or_tagged_bootstrap(&mut self) -> Result<types::SymSpanBs<'a>, Error> {
use TokenType::*;
let tok = self.next()?;
match tok.0 {
BsRef => self.ref_from(tok.1),
Word => {
let tag_span = tok.1;
if tag_span.0 != "Bootstrap" {
return self.err1("Expected 'Bootstrap' or bootstrap reference", tok.1);
}
let tok = self.next()?;
let mh = match tok.0 {
Ref => self.ref_from(tok.1)?,
Word => Or::B(self.mhnotref(tok.1)?),
_ => return self.err1("Expected methodhandle tag or ref", tok.1),
};
Ok(Or::B(tag_span.of(self.bs_args(mh)?)))
}
_ => self.err1("Expected 'Bootstrap' or bootstrap reference", tok.1),
}
}
pub fn ldc_rhs(&mut self) -> Result<types::SymSpanConst<'a>, Error> {
use TokenType::*;
let tok = self.next()?;
match tok.0 {
IntLit => Ok(Or::B(tok.1.of(self.int_from(tok.1)?))),
FloatLit => Ok(Or::B(tok.1.of(self.float_from(tok.1)?))),
LongLit => Ok(Or::B(tok.1.of(self.long_from(tok.1)?))),
DoubleLit => Ok(Or::B(tok.1.of(self.double_from(tok.1)?))),
StringLit => Ok(Or::B(tok.1.of(types::InlineConst::Str(ns(self.utf_from(tok)?))))),
Ref => self.ref_from(tok.1),
Word => Ok(Or::B(tok.1.of(self.tagged_const_from(tok.1)?))),
_ => self.err1("Expected constant pool tag (Utf8, Int, String, NameAndType, etc.) or reference", tok.1),
}
}
pub fn static_utf(name: &'static str, span: Span<'a>) -> types::SymSpanUtf8<'a> {
Or::B(span.of(types::InlineUtf8(BStr(name.as_bytes()))))
}
pub fn flags(&mut self) -> Result<u16, Error> {
let mut flags = FlagList::new();
while self.has_type(TokenType::Word) {
if flags.push(self.peek()?.1).is_ok() {
self.next()?;
} else {
break;
}
}
Ok(flags.flush())
}
/////////////////////////////////////////////////////////////////////////////////////
pub fn lbl(&mut self) -> Result<Span<'a>, Error> {
let tok = self.next()?;
if tok.0 != TokenType::Word || !tok.1 .0.starts_with('L') {
self.err1("Expected label", tok.1)
} else {
Ok(tok.1)
}
}
pub fn lbl_to_pos(&self, span: Span<'a>) -> Result<Spanned<'a, Pos>, Error> {
self.labels
.get(span.0)
.map(|p| span.of(*p))
.ok_or_else(|| self.error1("Undefined label", span))
}
pub fn lblpos(&mut self) -> Result<Spanned<'a, Pos>, Error> {
let span = self.lbl()?;
self.labels
.get(span.0)
.map(|p| span.of(*p))
.ok_or_else(|| self.error1("Undefined label", span))
}
fn convert_pos<T: TryFrom<i64> + Display>(&self, span: Span<'a>, v: i64, min: T, max: T) -> Result<T, Error> {
v.try_into()
.map_err(|_| self.error1str(format!("Bytecode offset must be {} <= x <= {}, found {}", min, max, v), span))
}
pub fn pos_to_u16(&self, pos: Spanned<'a, Pos>) -> Result<u16, Error> {
self.convert_pos(pos.span, pos.v.0 as i64, u16::MIN, u16::MAX)
}
pub fn pos_diff_to_u16(&self, base: Pos, pos: Spanned<'a, Pos>) -> Result<u16, Error> {
self.convert_pos(pos.span, pos.v.0 as i64 - base.0 as i64, u16::MIN, u16::MAX)
}
pub fn pos_diff_to_i16(&self, base: Pos, pos: Spanned<'a, Pos>) -> Result<i16, Error> {
self.convert_pos(pos.span, pos.v.0 as i64 - base.0 as i64, i16::MIN, i16::MAX)
}
pub fn pos_diff_to_i32(&self, base: Pos, pos: Spanned<'a, Pos>) -> Result<i32, Error> {
self.convert_pos(pos.span, pos.v.0 as i64 - base.0 as i64, i32::MIN, i32::MAX)
}
pub fn lbl16(&mut self) -> Result<u16, Error> {
let pos = self.lblpos()?;
self.pos_to_u16(pos)
}
}

View File

@ -0,0 +1,363 @@
use std::collections::HashMap;
use super::raw_const::RawBsMeth;
use super::raw_const::RawConst;
use super::types::*;
use crate::lib::assemble::span::Error;
use crate::lib::assemble::span::ErrorMaker;
use crate::lib::assemble::span::Span;
use crate::lib::assemble::span::Spanned;
use crate::lib::assemble::writer::BufWriter;
use crate::lib::util::BStr;
#[derive(Debug)]
struct Range {
first: u16,
last: u16,
}
impl Range {
fn len(&self) -> usize {
(1 + self.last as usize) - self.first as usize
}
}
struct ConstSlotAllocator {
ranges: Vec<Range>,
// indexes into the ranges array
odd_ptr: usize,
wide_ptr: usize,
ptr: usize,
}
impl ConstSlotAllocator {
fn new(ranges: Vec<Range>) -> Self {
Self {
ranges,
odd_ptr: 0,
wide_ptr: 0,
ptr: 0,
}
}
fn alloc(&mut self, is_ldc: bool) -> Option<u16> {
while let Some(r) = self.ranges.get_mut(self.odd_ptr) {
if r.len() % 2 == 0 {
self.odd_ptr += 1;
} else if is_ldc && r.first > 255 {
break;
} else {
self.odd_ptr += 1;
let chosen = r.first;
r.first += 1;
return Some(chosen);
}
}
while let Some(r) = self.ranges.get_mut(self.ptr) {
if is_ldc && r.first > 255 {
return None;
}
if r.len() >= 1 {
let chosen = r.first;
r.first += 1;
return Some(chosen);
} else {
self.ptr += 1;
}
}
None
}
fn alloc_wide(&mut self) -> Option<u16> {
while let Some(r) = self.ranges.get_mut(self.wide_ptr) {
if r.len() >= 2 {
let chosen = r.first;
r.first += 2;
return Some(chosen);
} else {
self.wide_ptr += 1;
}
}
None
}
}
pub enum BsAttrNameNeeded {
Always,
IfPresent,
Never,
}
#[derive(Debug)]
pub struct BsAttrInfo {
pub buf: Vec<u8>,
pub num_bs: u16,
pub name: Option<u16>,
}
impl BsAttrInfo {
pub fn data_len(&self) -> Option<u32> {
(2 + self.buf.len() as u64).try_into().ok()
}
}
pub struct PoolBuilder<'a> {
error_maker: ErrorMaker<'a>,
pending: Vec<(u16, Spanned<'a, RawConstInline<'a>>)>,
allocated: HashMap<RawConstInline<'a>, u16>,
allocator: ConstSlotAllocator,
raw_bs_defs: Vec<(u16, Spanned<'a, RawBsInline<'a>>)>,
}
impl<'a> PoolBuilder<'a> {
pub fn new(
error_maker: ErrorMaker<'a>,
mut raw_defs: Vec<(u16, Spanned<'a, RawConstInline<'a>>)>,
mut raw_bs_defs: Vec<(u16, Spanned<'a, RawBsInline<'a>>)>,
) -> Self {
raw_defs.sort_unstable_by_key(|p| p.0);
raw_bs_defs.sort_unstable_by_key(|p| !p.0); // use bitwise not to reverse sort order
let mut ranges = Vec::new();
let mut first = 1;
for &(ind, ref c) in &raw_defs {
if ind > first {
ranges.push(Range { first, last: ind - 1 });
}
first = ind + if c.v.is_long() { 2 } else { 1 };
}
if first <= 65534 {
ranges.push(Range { first, last: 65534 });
}
Self {
error_maker,
pending: raw_defs,
allocated: HashMap::new(),
allocator: ConstSlotAllocator::new(ranges),
raw_bs_defs,
}
}
pub fn allocate(&mut self, span: Span<'a>, c: RawConstInline<'a>, is_ldc: bool) -> Result<u16, Error> {
// println!("allocate {} {:?} {}", span.0, c, is_ldc);
self.allocated
.get(&c)
.copied()
.or_else(|| {
let slot = if c.is_long() {
self.allocator.alloc_wide()
} else {
self.allocator.alloc(is_ldc)
};
if let Some(ind) = slot {
self.allocated.insert(c.clone(), ind);
self.pending.push((ind, span.of(c)));
}
slot
})
.ok_or_else(|| {
self.error_maker
.error1("Exceeded maximum 65534 constants per class in constant pool", span)
})
}
fn fix(&mut self, span: Span<'a>, r: Or<u16, impl ToConst<'a, u16>>) -> Result<u16, Error> {
match r {
Or::A(ind) => Ok(ind),
Or::B(u) => self.allocate(span, u.to_const(), false),
}
}
fn fix2(&mut self, r: Or<u16, Spanned<'a, impl ToConst<'a, u16>>>) -> Result<u16, Error> {
match r {
Or::A(ind) => Ok(ind),
Or::B(u) => self.allocate(u.span, u.v.to_const(), false),
}
}
fn fix_bs(&mut self, span: Span<'a>, r: RawBsRef<'a>, bs_table: &mut BootstrapBuilder) -> Result<u16, Error> {
match r {
Or::A(ind) => Ok(ind),
Or::B(bs) => {
let bs = self.resolve_bs_sub_refs(span.of(bs))?;
bs_table.allocate(bs).ok_or_else(|| {
self.error_maker
.error1("Exceeded maximum 65535 bootstrap methods per class", span)
})
}
}
}
fn resolve_cp_sub_refs(
&mut self,
c: Spanned<'a, RawConstInline<'a>>,
bs_table: &mut BootstrapBuilder,
) -> Result<RawConst<'a>, Error> {
let span = c.span;
Ok(match c.v {
InlineConst::Utf8(v) => RawConst::Utf8(v.0),
InlineConst::Int(v) => RawConst::Int(v),
InlineConst::Float(v) => RawConst::Float(v),
InlineConst::Long(v) => RawConst::Long(v),
InlineConst::Double(v) => RawConst::Double(v),
InlineConst::Class(v) => RawConst::Class(self.fix(span, v)?),
InlineConst::Str(v) => RawConst::Str(self.fix(span, v)?),
InlineConst::Field(cls, nat) => RawConst::Field(self.fix(span, cls)?, self.fix(span, nat)?),
InlineConst::Method(cls, nat) => RawConst::Method(self.fix(span, cls)?, self.fix(span, nat)?),
InlineConst::InterfaceMethod(cls, nat) => RawConst::InterfaceMethod(self.fix(span, cls)?, self.fix(span, nat)?),
InlineConst::NameAndType(u1, u2) => RawConst::NameAndType(self.fix(span, u1)?, self.fix(span, u2)?),
InlineConst::MethodHandle(tag, val) => RawConst::MethodHandle(tag, self.fix(span, *val)?),
InlineConst::MethodType(v) => RawConst::MethodType(self.fix(span, v)?),
InlineConst::Dynamic(bs, nat) => RawConst::Dynamic(self.fix_bs(span, bs, bs_table)?, self.fix(span, nat)?),
InlineConst::InvokeDynamic(bs, nat) => {
RawConst::InvokeDynamic(self.fix_bs(span, bs, bs_table)?, self.fix(span, nat)?)
}
InlineConst::Module(v) => RawConst::Module(self.fix(span, v)?),
InlineConst::Package(v) => RawConst::Package(self.fix(span, v)?),
})
}
fn resolve_bs_sub_refs(&mut self, bs: Spanned<'a, RawBsInline<'a>>) -> Result<RawBsMeth, Error> {
let mut iter = bs.v.0.into_iter();
let mh = iter.next().unwrap();
let mhref = self.fix2(mh)?;
let args = iter.map(|c| self.fix2(c)).collect::<Result<_, _>>()?;
Ok(RawBsMeth { mhref, args })
}
pub fn build(
mut self,
cpwriter: &mut BufWriter,
bs_name_needed: BsAttrNameNeeded,
class_name_ind: u16,
) -> Result<(BsAttrInfo, Option<&'a [u8]>), Error> {
let raw_bs_defs = std::mem::take(&mut self.raw_bs_defs);
let resolved_bs_defs = raw_bs_defs
.into_iter()
.map(|(ind, bs)| Ok((ind, self.resolve_bs_sub_refs(bs)?)))
.collect::<Result<_, _>>()?;
let mut bs_table = BootstrapBuilder::new(resolved_bs_defs);
// Just choose a span arbitrarily to use for the case where we can't allocate
// a name for an implicit BootstrapMethods attribute later.
let bs_name_span = self.pending.last().map(|(_, c)| c.span);
let filler_const = RawConst::Utf8(b"");
let mut table = [Some(filler_const); 65535];
table[0] = None;
while let Some((ind, c)) = self.pending.pop() {
let is_long = c.v.is_long();
assert!(table[ind as usize] == Some(filler_const));
table[ind as usize] = Some(self.resolve_cp_sub_refs(c, &mut bs_table)?);
if is_long {
assert!(table[ind as usize + 1] == Some(filler_const));
table[ind as usize + 1] = None;
}
}
let (buf, num_bs) = bs_table.finish();
let name_needed = match bs_name_needed {
BsAttrNameNeeded::Always => true,
BsAttrNameNeeded::IfPresent => num_bs > 0,
BsAttrNameNeeded::Never => false,
};
let name = if name_needed {
let s = b"BootstrapMethods";
let c = InlineConst::Utf8(BStr(s));
let slot = self.allocate(bs_name_span.unwrap(), c, false)?;
table[slot as usize] = Some(RawConst::Utf8(s));
Some(slot)
} else {
None
};
let bs_info = BsAttrInfo { buf, num_bs, name };
let num_consts = if let Some(range) = self.allocator.ranges.last() {
// todo - test this
if range.last == 65534 {
range.first
} else {
65535
}
} else {
65535
};
let class_name = match table[class_name_ind as usize] {
Some(RawConst::Class(utf_ind)) => match table[utf_ind as usize] {
Some(RawConst::Utf8(s)) => Some(s),
_ => None,
},
_ => None,
};
let w = cpwriter;
w.u16(num_consts);
for c in &table[1..num_consts as usize] {
// for (i, c) in table[..num_consts as usize].into_iter().enumerate() {
// println!("[{}] {:?}", i, c);
if let Some(c) = c {
c.write(w);
}
}
Ok((bs_info, class_name))
}
}
struct BootstrapBuilder {
w: BufWriter,
pending_bs_defs: Vec<(u16, RawBsMeth)>,
next_bs_ind: u16,
allocated: HashMap<RawBsMeth, u16>,
}
impl BootstrapBuilder {
fn new(pending_bs_defs: Vec<(u16, RawBsMeth)>) -> Self {
Self {
w: BufWriter::default(),
pending_bs_defs,
next_bs_ind: 0,
allocated: HashMap::new(),
}
}
fn allocate(&mut self, bs: RawBsMeth) -> Option<u16> {
self.allocated.get(&bs).copied().or_else(|| {
while self.pending_bs_defs.last().map(|&(ind, _)| ind) == Some(self.next_bs_ind) {
let (_, bs) = self.pending_bs_defs.pop().unwrap();
bs.write(&mut self.w);
assert!(self.next_bs_ind < u16::MAX);
self.next_bs_ind += 1;
}
if self.next_bs_ind == u16::MAX {
return None;
}
let slot = self.next_bs_ind;
bs.write(&mut self.w);
self.next_bs_ind += 1;
self.allocated.insert(bs, slot);
Some(slot)
})
}
fn finish(mut self) -> (Vec<u8>, u16) {
while let Some((ind, bs)) = self.pending_bs_defs.pop() {
assert!(ind >= self.next_bs_ind);
while self.next_bs_ind <= ind {
bs.write(&mut self.w);
self.next_bs_ind += 1;
}
}
(self.w.into_buf(), self.next_bs_ind)
}
}

View File

@ -0,0 +1,143 @@
mod builder;
mod raw_const;
mod sym_ref_resolver;
pub mod types;
use std::collections::HashMap;
use crate::lib::assemble::span::Error;
use crate::lib::assemble::span::ErrorMaker;
use crate::lib::assemble::span::Span;
use crate::lib::assemble::span::Spanned;
pub use builder::BsAttrNameNeeded;
use builder::PoolBuilder;
use sym_ref_resolver::PoolSymDefs;
pub use types::*;
pub type RefOr<'a, T> = Or<RefType<'a>, T>;
pub struct Pool<'a> {
sym_defs: PoolSymDefs<'a>,
raw_defs: HashMap<u16, (Span<'a>, Option<SymSpanConstInline<'a>>)>,
bs_raw_defs: HashMap<u16, (Span<'a>, SymSpanBsInline<'a>)>,
}
// Real instance methods
impl<'a> Pool<'a> {
pub fn new(error_maker: ErrorMaker<'a>) -> Self {
Self {
sym_defs: PoolSymDefs::new(error_maker),
raw_defs: HashMap::new(),
bs_raw_defs: HashMap::new(),
}
}
pub fn add_sym_def(&mut self, name: Spanned<'a, &'a str>, r: SymConstRef<'a>) -> Result<(), Error> {
self.sym_defs.add_def(name, r)
}
pub fn add_bs_sym_def(&mut self, name: Spanned<'a, &'a str>, r: SymBsRef<'a>) -> Result<(), Error> {
self.sym_defs.add_bs_def(name, r)
}
pub fn add_raw_def(&mut self, ind: u16, new_span: Span<'a>, r: SymSpanConstInline<'a>) -> Result<(), Error> {
let is_long = r.v.is_long();
if ind == 0 || ind == 0xFFFF || (is_long && ind == 0xFFFE) {
return self.err1("Invalid constant pool index", new_span);
}
if is_long {
if let Some((old_span, _old)) = self.raw_defs.insert(ind + 1, (new_span, None)) {
return self.err2(
"Conflicting raw const definition",
old_span,
"Note: Conflicts with wide const definition here",
new_span,
);
}
}
if let Some((old_span, old)) = self.raw_defs.insert(ind, (new_span, Some(r))) {
if old.is_some() {
self.err2("Duplicate raw const definition", new_span, "Note: Previously defined here", old_span)
} else {
self.err2(
"Conflicting raw const definition",
new_span,
"Note: Conflicts with wide const definition here",
old_span,
)
}
} else {
Ok(())
}
}
pub fn add_bs_raw_def(&mut self, ind: u16, new_span: Span<'a>, r: SymSpanBsInline<'a>) -> Result<(), Error> {
if ind == 0xFFFF {
return self.err1("Bootstrap method index must be <= 65534.", new_span);
}
if let Some((old_span, _)) = self.bs_raw_defs.insert(ind, (new_span, r)) {
self.err2("Duplicate raw bootstrap definition", new_span, "Note: Previously defined here", old_span)
} else {
Ok(())
}
}
pub fn finish_defs(mut self) -> Result<PoolResolver<'a>, Error> {
let error_maker = *self;
let raw_defs = self
.raw_defs
.into_iter()
.filter_map(|(ind, (_span, slot))| slot.map(|c| Ok((ind, self.sym_defs.resolve_const2(c)?))))
.collect::<Result<_, _>>()?;
let bs_raw_defs = self
.bs_raw_defs
.into_iter()
.map(|(ind, (_span, bs))| Ok((ind, self.sym_defs.resolve_bsmeth2(bs)?)))
.collect::<Result<_, _>>()?;
Ok(PoolResolver {
sym_defs: self.sym_defs,
builder: PoolBuilder::new(error_maker, raw_defs, bs_raw_defs),
})
}
}
impl<'a> std::ops::Deref for Pool<'a> {
type Target = ErrorMaker<'a>;
fn deref(&self) -> &Self::Target {
&self.sym_defs
}
}
pub struct PoolResolver<'a> {
sym_defs: PoolSymDefs<'a>,
builder: PoolBuilder<'a>,
}
impl<'a> PoolResolver<'a> {
pub fn resolve(&mut self, c: SymSpanConst<'a>) -> Result<u16, Error> {
let c = self.sym_defs.resolve_ref2(c)?;
match c {
Or::A(ind) => Ok(ind),
Or::B(c) => self.builder.allocate(c.span, c.v, false),
}
}
pub fn resolve_ldc(&mut self, c: SymSpanConst<'a>, span: Span<'a>) -> Result<u8, Error> {
let c = self.sym_defs.resolve_ref2(c)?;
let ind = match c {
Or::A(ind) => Ok(ind),
Or::B(c) => self.builder.allocate(c.span, c.v, true),
}?;
ind.try_into().map_err(|_| {
self.sym_defs
.error1("ldc constant index must be <= 255. Try using ldc_w instead.", span)
})
}
pub fn end(self) -> PoolBuilder<'a> {
self.builder
}
}

View File

@ -0,0 +1,122 @@
use crate::lib::assemble::writer::BufWriter;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RawConst<'a> {
Utf8(&'a [u8]),
Int(u32),
Float(u32),
Long(u64),
Double(u64),
Class(u16),
Str(u16),
Field(u16, u16),
Method(u16, u16),
InterfaceMethod(u16, u16),
NameAndType(u16, u16),
MethodHandle(u8, u16),
MethodType(u16),
Dynamic(u16, u16),
InvokeDynamic(u16, u16),
Module(u16),
Package(u16),
}
impl RawConst<'_> {
pub(super) fn write(self, w: &mut BufWriter) {
use RawConst::*;
match self {
Utf8(s) => {
w.u8(1);
w.u16(s.len().try_into().unwrap());
w.write(s);
}
Int(v) => {
w.u8(3);
w.u32(v);
}
Float(v) => {
w.u8(4);
w.u32(v);
}
Long(v) => {
w.u8(5);
w.u64(v);
}
Double(v) => {
w.u8(6);
w.u64(v);
}
Class(v) => {
w.u8(7);
w.u16(v);
}
Str(v) => {
w.u8(8);
w.u16(v);
}
Field(cls, nat) => {
w.u8(9);
w.u16(cls);
w.u16(nat);
}
Method(cls, nat) => {
w.u8(10);
w.u16(cls);
w.u16(nat);
}
InterfaceMethod(cls, nat) => {
w.u8(11);
w.u16(cls);
w.u16(nat);
}
NameAndType(n, t) => {
w.u8(12);
w.u16(n);
w.u16(t);
}
MethodHandle(tag, val) => {
w.u8(15);
w.u8(tag);
w.u16(val);
}
MethodType(v) => {
w.u8(16);
w.u16(v);
}
Dynamic(bs, nat) => {
w.u8(17);
w.u16(bs);
w.u16(nat);
}
InvokeDynamic(bs, nat) => {
w.u8(18);
w.u16(bs);
w.u16(nat);
}
Module(v) => {
w.u8(19);
w.u16(v);
}
Package(v) => {
w.u8(20);
w.u16(v);
}
}
}
}
#[derive(Debug, Hash, PartialEq, Eq)]
pub(super) struct RawBsMeth {
pub(super) mhref: u16,
pub(super) args: Vec<u16>,
}
impl RawBsMeth {
pub(super) fn write(&self, w: &mut BufWriter) {
w.u16(self.mhref);
w.u16(self.args.len().try_into().unwrap());
for v in self.args.iter().copied() {
w.u16(v);
}
}
}

View File

@ -0,0 +1,202 @@
use std::collections::HashMap;
use super::types::*;
use crate::lib::assemble::span::Error;
use crate::lib::assemble::span::ErrorMaker;
use crate::lib::assemble::span::Span;
use crate::lib::assemble::span::Spanned;
enum ResolveState<Lazy, Resolved> {
Unresolved(Option<Lazy>),
Resolved(Resolved),
}
pub struct PoolSymDefs<'a> {
error_maker: ErrorMaker<'a>,
sym_defs: HashMap<&'a str, (Span<'a>, ResolveState<SymConstRef<'a>, RawConstRef<'a>>)>,
bs_sym_defs: HashMap<&'a str, (Span<'a>, ResolveState<SymBsRef<'a>, RawBsRef<'a>>)>,
}
impl<'a> PoolSymDefs<'a> {
pub fn new(error_maker: ErrorMaker<'a>) -> Self {
Self {
error_maker,
sym_defs: HashMap::new(),
bs_sym_defs: HashMap::new(),
}
}
fn add_def_generic<Before, After>(
&mut self,
name: Spanned<'a, &'a str>,
r: Before,
get_map: fn(&mut Self) -> &mut HashMap<&'a str, (Span<'a>, ResolveState<Before, After>)>,
) -> Result<(), Error> {
let new_val = (name.span, ResolveState::Unresolved(Some(r)));
if let Some((prev_span, _)) = get_map(self).insert(name.v, new_val) {
self.err2(
"Error: Duplicate definition of symbolic ref",
name.span,
"Note: Previous definition was here",
prev_span,
)
} else {
Ok(())
}
}
pub fn add_def(&mut self, name: Spanned<'a, &'a str>, r: SymConstRef<'a>) -> Result<(), Error> {
self.add_def_generic(name, r, |this| &mut this.sym_defs)
}
pub fn add_bs_def(&mut self, name: Spanned<'a, &'a str>, r: SymBsRef<'a>) -> Result<(), Error> {
self.add_def_generic(name, r, |this| &mut this.bs_sym_defs)
}
fn resolve_sym_generic<Before, After: Clone>(
&mut self,
name: Spanned<'_, &str>,
get_map: fn(&mut Self) -> &mut HashMap<&'a str, (Span<'a>, ResolveState<Before, After>)>,
resolve: fn(&mut Self, Before) -> Result<After, Error>,
) -> Result<After, Error> {
if let Some((_, v)) = get_map(self).get_mut(name.v) {
use ResolveState::*;
let to_resolve = match v {
Unresolved(r) => r.take(),
Resolved(r) => return Ok(r.clone()),
};
if let Some(r) = to_resolve {
let r = resolve(self, r)?;
get_map(self).get_mut(name.v).unwrap().1 = Resolved(r.clone());
Ok(r)
} else {
self.err1("Circular definition of symbolic reference", name.span)
}
} else {
self.err1("Undefined symbolic reference", name.span)
}
}
fn resolve_sym(&mut self, name: Spanned<'_, &str>) -> Result<RawConstRef<'a>, Error> {
self.resolve_sym_generic(name, |this| &mut this.sym_defs, Self::resolve_ref)
}
fn resolve_bs_sym(&mut self, name: Spanned<'_, &str>) -> Result<RawBsRef<'a>, Error> {
self.resolve_sym_generic(name, |this| &mut this.bs_sym_defs, Self::resolve_bs_ref)
}
fn resolve_utf8(&mut self, r: SymUtf8Ref<'a>) -> Result<RawUtf8Ref<'a>, Error> {
Ok(match r {
Or::A(RefType::Raw(r)) => Or::A(r),
Or::A(RefType::Sym(name)) => {
let resolved = self.resolve_sym(name)?;
match resolved {
Or::A(r) => Or::A(r),
Or::B(InlineConst::Utf8(sym)) => Or::B(InlineUtf8(sym)),
_ => self.err1("Reference must resolve to raw or Utf8 reference.", name.span)?,
}
}
Or::B(sym) => Or::B(sym),
})
}
fn resolve_class(&mut self, r: SymClassRef<'a>) -> Result<RawClassRef<'a>, Error> {
Ok(match r {
Or::A(RefType::Raw(r)) => Or::A(r),
Or::A(RefType::Sym(name)) => {
let resolved = self.resolve_sym(name)?;
match resolved {
Or::A(r) => Or::A(r),
Or::B(InlineConst::Class(r)) => Or::B(InlineClass(r)),
_ => self.err1("Reference must resolve to raw or Class reference.", name.span)?,
}
}
Or::B(InlineClass(u)) => Or::B(InlineClass(self.resolve_utf8(u)?)),
})
}
fn resolve_nat(&mut self, r: SymNatRef<'a>) -> Result<RawNatRef<'a>, Error> {
Ok(match r {
Or::A(RefType::Raw(r)) => Or::A(r),
Or::A(RefType::Sym(name)) => {
let resolved = self.resolve_sym(name)?;
match resolved {
Or::A(r) => Or::A(r),
Or::B(InlineConst::NameAndType(r1, r2)) => Or::B(InlineNat(r1, r2)),
_ => self.err1("Reference must resolve to raw or NameAndType reference.", name.span)?,
}
}
Or::B(InlineNat(r1, r2)) => Or::B(InlineNat(self.resolve_utf8(r1)?, self.resolve_utf8(r2)?)),
})
}
pub fn resolve_bsmeth(&mut self, bs: SymBsInline<'a>) -> Result<RawBsInline<'a>, Error> {
Ok(InlineBs(bs.0.into_iter().map(|r| self.resolve_ref2(r)).collect::<Result<_, _>>()?))
}
fn resolve_bs_ref(&mut self, r: SymBsRef<'a>) -> Result<RawBsRef<'a>, Error> {
Ok(match r {
Or::A(RefType::Raw(r)) => Or::A(r),
Or::A(RefType::Sym(name)) => self.resolve_bs_sym(name)?,
Or::B(bs) => Or::B(self.resolve_bsmeth(bs)?),
})
}
pub fn resolve_const(&mut self, c: SymConstInline<'a>) -> Result<RawConstInline<'a>, Error> {
use InlineConst::*;
Ok(match c {
Utf8(v) => Utf8(v),
Int(v) => Int(v),
Float(v) => Float(v),
Long(v) => Long(v),
Double(v) => Double(v),
Class(v) => Class(self.resolve_utf8(v)?),
Str(v) => Str(self.resolve_utf8(v)?),
Field(clsr, natr) => Field(self.resolve_class(clsr)?, self.resolve_nat(natr)?),
Method(clsr, natr) => Method(self.resolve_class(clsr)?, self.resolve_nat(natr)?),
InterfaceMethod(clsr, natr) => InterfaceMethod(self.resolve_class(clsr)?, self.resolve_nat(natr)?),
NameAndType(r1, r2) => NameAndType(self.resolve_utf8(r1)?, self.resolve_utf8(r2)?),
MethodHandle(tag, r) => MethodHandle(tag, Box::new(self.resolve_ref(*r)?)),
MethodType(v) => MethodType(self.resolve_utf8(v)?),
Dynamic(dynr, natr) => Dynamic(self.resolve_bs_ref(dynr)?, self.resolve_nat(natr)?),
InvokeDynamic(dynr, natr) => InvokeDynamic(self.resolve_bs_ref(dynr)?, self.resolve_nat(natr)?),
Module(v) => Module(self.resolve_utf8(v)?),
Package(v) => Package(self.resolve_utf8(v)?),
})
}
fn resolve_ref(&mut self, r: SymConstRef<'a>) -> Result<RawConstRef<'a>, Error> {
Ok(match r {
Or::A(RefType::Raw(r)) => Or::A(r),
Or::A(RefType::Sym(name)) => self.resolve_sym(name)?,
Or::B(c) => Or::B(self.resolve_const(c)?),
})
}
// temp hack
pub fn resolve_ref2(&mut self, r: SymSpanConst<'a>) -> Result<RawSpanConst<'a>, Error> {
Ok(match r {
Or::A(RefType::Raw(r)) => Or::A(r),
Or::A(RefType::Sym(name)) => self.resolve_sym(name)?.map_b(|c| name.span.of(c)),
Or::B(c) => Or::B(c.span.of(self.resolve_const(c.v)?)),
})
}
pub fn resolve_bsmeth2(&mut self, bs: SymSpanBsInline<'a>) -> Result<RawSpanBsInline<'a>, Error> {
Ok(bs.span.of(self.resolve_bsmeth(bs.v)?))
}
pub fn resolve_const2(&mut self, c: SymSpanConstInline<'a>) -> Result<RawSpanConstInline<'a>, Error> {
Ok(c.span.of(self.resolve_const(c.v)?))
}
}
impl<'a> std::ops::Deref for PoolSymDefs<'a> {
type Target = ErrorMaker<'a>;
fn deref(&self) -> &Self::Target {
&self.error_maker
}
}

View File

@ -0,0 +1,154 @@
use std::fmt::Debug;
use crate::lib::assemble::span::Spanned;
use crate::lib::util::BStr;
#[derive(Hash, PartialEq, Eq, Clone, Copy)]
pub enum Or<A, B> {
A(A),
B(B),
}
impl<A: Debug, B: Debug> Debug for Or<A, B> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Or::A(v) => v.fmt(f),
Or::B(v) => v.fmt(f),
}
}
}
impl<A, B> Or<A, B> {
pub fn map_b<B2>(self, f: impl FnOnce(B) -> B2) -> Or<A, B2> {
match self {
Or::A(v) => Or::A(v),
Or::B(v) => Or::B(f(v)),
}
}
// pub fn try_map_b<B2, E>(self, f: impl FnOnce(B) -> Result<B2, E>) -> Result<Or<A, B2>, E> {
// Ok(match self {
// Or::A(v) => Or::A(v),
// Or::B(v) => Or::B(f(v)?),
// })
// }
pub fn as_b(&self) -> Option<&B> {
if let Or::B(v) = self {
Some(v)
} else {
None
}
}
}
pub type Utf8<'a, Ref> = Or<Ref, InlineUtf8<'a>>;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct InlineUtf8<'a>(pub BStr<'a>);
pub type Class<'a, Ref> = Or<Ref, InlineClass<'a, Ref>>;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct InlineClass<'a, Ref>(pub Utf8<'a, Ref>);
pub type Nat<'a, Ref> = Or<Ref, InlineNat<'a, Ref>>;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct InlineNat<'a, Ref>(pub Utf8<'a, Ref>, pub Utf8<'a, Ref>);
pub type Bs<'a, Ref> = Or<Ref, InlineBs<'a, Ref>>;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct InlineBs<'a, Ref>(pub Vec<SpanConst<'a, Ref>>);
pub type Const<'a, Ref> = Or<Ref, InlineConst<'a, Ref>>;
pub type SpanConst<'a, Ref> = Or<Ref, Spanned<'a, InlineConst<'a, Ref>>>;
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum InlineConst<'a, Ref> {
Utf8(BStr<'a>),
Int(u32),
Float(u32),
Long(u64),
Double(u64),
Class(Utf8<'a, Ref>),
Str(Utf8<'a, Ref>),
Field(Class<'a, Ref>, Nat<'a, Ref>),
Method(Class<'a, Ref>, Nat<'a, Ref>),
InterfaceMethod(Class<'a, Ref>, Nat<'a, Ref>),
NameAndType(Utf8<'a, Ref>, Utf8<'a, Ref>),
MethodHandle(u8, Box<Const<'a, Ref>>),
MethodType(Utf8<'a, Ref>),
Dynamic(Bs<'a, Ref>, Nat<'a, Ref>),
InvokeDynamic(Bs<'a, Ref>, Nat<'a, Ref>),
Module(Utf8<'a, Ref>),
Package(Utf8<'a, Ref>),
}
impl<'a, Ref> InlineConst<'a, Ref> {
pub fn is_long(&self) -> bool {
match self {
InlineConst::Long(_) | InlineConst::Double(_) => true,
_ => false,
}
}
}
pub trait ToConst<'a, Ref> {
fn to_const(self) -> InlineConst<'a, Ref>;
}
impl<'a, Ref> ToConst<'a, Ref> for InlineUtf8<'a> {
fn to_const(self) -> InlineConst<'a, Ref> {
InlineConst::Utf8(self.0)
}
}
impl<'a, Ref> ToConst<'a, Ref> for InlineClass<'a, Ref> {
fn to_const(self) -> InlineConst<'a, Ref> {
InlineConst::Class(self.0)
}
}
impl<'a, Ref> ToConst<'a, Ref> for InlineNat<'a, Ref> {
fn to_const(self) -> InlineConst<'a, Ref> {
InlineConst::NameAndType(self.0, self.1)
}
}
impl<'a, Ref> ToConst<'a, Ref> for InlineConst<'a, Ref> {
fn to_const(self) -> InlineConst<'a, Ref> {
self
}
}
#[derive(Debug)]
pub enum RefType<'a> {
Raw(u16),
Sym(Spanned<'a, &'a str>),
}
pub type SymUtf8Ref<'a> = Utf8<'a, RefType<'a>>;
pub type SymSpanUtf8<'a> = Or<RefType<'a>, Spanned<'a, InlineUtf8<'a>>>;
pub type RawUtf8Ref<'a> = Utf8<'a, u16>;
pub type SymClassRef<'a> = Class<'a, RefType<'a>>;
pub type SymSpanClass<'a> = Or<RefType<'a>, Spanned<'a, InlineClass<'a, RefType<'a>>>>;
// pub type SymClassInline<'a> = InlineClass<'a, RefType<'a>>;
pub type RawClassRef<'a> = Class<'a, u16>;
// pub type RawClassInline<'a> = InlineClass<'a, u16>;
pub type SymNatRef<'a> = Nat<'a, RefType<'a>>;
pub type SymSpanNat<'a> = Or<RefType<'a>, Spanned<'a, InlineNat<'a, RefType<'a>>>>;
// pub type SymNatInline<'a> = InlineNat<'a, RefType<'a>>;
pub type RawNatRef<'a> = Nat<'a, u16>;
// pub type RawNatInline<'a> = InlineNat<'a, u16>;
pub type SymConstRef<'a> = Const<'a, RefType<'a>>;
pub type SymSpanConst<'a> = Or<RefType<'a>, Spanned<'a, InlineConst<'a, RefType<'a>>>>;
pub type SymConstInline<'a> = InlineConst<'a, RefType<'a>>;
pub type SymSpanConstInline<'a> = Spanned<'a, InlineConst<'a, RefType<'a>>>;
pub type RawConstRef<'a> = Const<'a, u16>;
pub type RawSpanConst<'a> = Or<u16, Spanned<'a, InlineConst<'a, u16>>>;
pub type RawConstInline<'a> = InlineConst<'a, u16>;
pub type RawSpanConstInline<'a> = Spanned<'a, InlineConst<'a, u16>>;
pub type SymBsRef<'a> = Bs<'a, RefType<'a>>;
pub type SymSpanBs<'a> = Or<RefType<'a>, Spanned<'a, InlineBs<'a, RefType<'a>>>>;
pub type SymBsInline<'a> = InlineBs<'a, RefType<'a>>;
pub type SymSpanBsInline<'a> = Spanned<'a, InlineBs<'a, RefType<'a>>>;
pub type RawBsRef<'a> = Bs<'a, u16>;
pub type RawBsInline<'a> = InlineBs<'a, u16>;
pub type RawSpanBsInline<'a> = Spanned<'a, InlineBs<'a, u16>>;

58
src/lib/assemble/flags.rs Normal file
View File

@ -0,0 +1,58 @@
// use std::collections::HashMap;
use super::span::Span;
const FLAG_PAIRS: [(&str, u16); 24] = [
("abstract", 0x0400),
("annotation", 0x2000),
("bridge", 0x0040),
("enum", 0x4000),
("final", 0x0010),
("interface", 0x0200),
("mandated", 0x8000),
("module", 0x8000),
("native", 0x0100),
("open", 0x0020),
("private", 0x0002),
("protected", 0x0004),
("public", 0x0001),
("static", 0x0008),
("static_phase", 0x0040),
("strict", 0x0800),
("strictfp", 0x0800),
("super", 0x0020),
("synchronized", 0x0020),
("synthetic", 0x1000),
("transient", 0x0080),
("transitive", 0x0020),
("varargs", 0x0080),
("volatile", 0x0040),
];
// fn parse_flag(s: &str) -> Option<u16> {
// lazy_static! {
// static ref FLAG_MAP: HashMap<&'static str, u16> = FLAG_PAIRS.iter().copied().collect();
// }
// FLAG_MAP.get(s).copied()
// }
/// Accumulate a bitset of flags while holding on to the last token in case it was meant to not be a flag
pub struct FlagList {
flags: u16,
}
impl FlagList {
pub fn new() -> Self {
Self { flags: 0 }
}
pub fn push<'a>(&mut self, span: Span<'a>) -> Result<(), ()> {
let ind = FLAG_PAIRS.binary_search_by_key(&span.0, |t| t.0).map_err(|_| ())?;
let flag = FLAG_PAIRS[ind].1;
self.flags |= flag;
Ok(())
}
pub fn flush(self) -> u16 {
self.flags
}
}

View File

@ -0,0 +1,2 @@
#[derive(Debug, Clone, Copy)]
pub struct Pos(pub u32);

50
src/lib/assemble/mod.rs Normal file
View File

@ -0,0 +1,50 @@
mod base_parser;
mod class_parser;
mod cpool;
mod flags;
mod label;
mod parse_attr;
mod parse_class;
mod parse_code;
mod parse_literal;
mod span;
mod string;
mod tokenize;
mod writer;
use typed_arena::Arena;
use crate::lib::disassemble::string::parse_utf8;
use base_parser::BaseParser;
use class_parser::ClassParser;
pub use span::Error;
use tokenize::tokenize;
#[derive(Debug, Clone, Copy)]
pub struct AssemblerOptions {}
pub fn assemble(source: &str, _opts: AssemblerOptions) -> Result<Vec<(Option<String>, Vec<u8>)>, Error> {
let tokens = tokenize(source)?;
// for tok in &tokens {
// println!("{:?}", tok);
// }
let arena = Arena::new();
let mut base_parser = BaseParser::new(source, tokens);
let mut results = Vec::new();
while base_parser.has_tokens_left() {
let parser = ClassParser::new(base_parser, &arena);
let (parser, (class_name, data)) = parser.parse()?;
// let class_name = class_name.and_then(|bs| std::str::from_utf8(bs).ok().map(str::to_owned));
let class_name = class_name.and_then(parse_utf8);
results.push((class_name, data));
base_parser = parser;
if writer::UNUSED_PH.load(std::sync::atomic::Ordering::Relaxed) {
panic!("Unused placeholder!");
}
}
Ok(results)
}

View File

@ -0,0 +1,514 @@
use super::class_parser::ClassParser;
use super::cpool::types;
use super::cpool::InlineConst;
use super::span::Error;
use super::span::Span;
use super::string;
use super::tokenize::TokenType;
use super::writer::Writer;
pub enum AttrResult<'a> {
Normal,
ImplicitBootstrap {
name: Option<types::SymSpanUtf8<'a>>,
len: Option<u32>,
span: Span<'a>,
},
}
type ParseFn<'a> = fn(&mut ClassParser<'a>, &mut Writer<'a>) -> Result<(), Error>;
enum ListKind {
Line,
DotEnd,
Greedy(&'static str),
}
impl ListKind {
fn at_end(&self, p: &mut ClassParser<'_>) -> bool {
use ListKind::*;
match self {
Line => p.has_type(TokenType::Newlines),
DotEnd => p.tryv(".end"),
Greedy(dir) => !p.tryv(dir),
}
}
}
macro_rules! line_list {
($p: ident, $w:ident, $( $s:expr );+) => {
|p, w| p.list(w, ListKind::Line, |$p, $w| {$( $s );+; Ok(())})
};
}
macro_rules! dotend_list {
($tag:expr, $p: ident, $w:ident, $( $s:expr );+) => {
|p, w| {p.eol()?; p.list(w, ListKind::DotEnd, |$p, $w| {$( $s );+; Ok(())})?; p.val($tag)}
};
}
macro_rules! dotend_list8 {
($tag:expr, $p: ident, $w:ident, $( $s:expr );+) => {
|p, w| {p.eol()?; p.list8(w, ListKind::DotEnd, |$p, $w| {$( $s );+; Ok(())})?; p.val($tag)}
};
}
impl<'a> ClassParser<'a> {
fn get_parse_attr_body_fn(&mut self, directive: Span<'a>) -> Result<(&'static str, ParseFn<'a>), Error> {
Ok(match directive.0 {
".annotationdefault" => ("AnnotationDefault", Self::element_value),
".code" => ("Code", Self::parse_code),
".constantvalue" => ("ConstantValue", |p, w| {
w.cp(p.ldc_rhs()?);
Ok(())
}),
".deprecated" => ("Deprecated", |_p, _w| Ok(())),
".enclosing" => ("EnclosingMethod", |p, w| {
p.val("method")?;
w.cp(p.cls()?);
w.cp(p.nat()?);
Ok(())
}),
".exceptions" => ("Exceptions", line_list! {p, w, w.cp(p.cls()?)}),
".innerclasses" => (
"InnerClasses",
dotend_list! {"innerclasses", p, w,
w.cp(p.cls()?); w.cp(p.cls()?); w.cp(p.utf()?); w.u16(p.flags()?); p.eol()?
},
),
".linenumbertable" => (
"LineNumberTable",
dotend_list! {"linenumbertable", p, w, w.u16(p.lbl16()?); w.u16(p.u16()?); p.eol()?},
),
".localvariabletable" => (
"LocalVariableTable",
dotend_list! {"localvariabletable", p, w, p.local_var_table_item(w)?},
),
".localvariabletypetable" => (
"LocalVariableTypeTable",
dotend_list! {"localvariabletypetable", p, w, p.local_var_table_item(w)?},
),
".methodparameters" => (
"MethodParameters",
dotend_list8! {"methodparameters", p, w, w.cp(p.utf()?); w.u16(p.flags()?); p.eol()?},
),
".module" => ("Module", Self::module),
".modulemainclass" => ("ModuleMainClass", |p, w| {
w.cp(p.cls()?);
Ok(())
}),
".modulepackages" => ("ModulePackages", line_list! {p, w, w.cp(p.single(InlineConst::Package)?)}),
".nesthost" => ("NestHost", |p, w| {
w.cp(p.cls()?);
Ok(())
}),
".nestmembers" => ("NestMembers", line_list! {p, w, w.cp(p.cls()?)}),
".permittedsubclasses" => ("PermittedSubclasses", line_list! {p, w, w.cp(p.cls()?)}),
".record" => ("Record", dotend_list! {"record", p, w, p.record_item(w)?}),
".runtime" => {
let tok = self.next()?;
let visible = match tok.1 .0 {
"visible" => true,
"invisible" => false,
_ => return self.err1("Expected visible or invisible", tok.1),
};
let tok = self.next()?;
match tok.1 .0 {
"annotations" => (
if visible {
"RuntimeVisibleAnnotations"
} else {
"RuntimeInvisibleAnnotations"
},
dotend_list! {"runtime", p, w, p.val(".annotation")?; p.annotation(w, false)?; p.eol()?},
),
"paramannotations" => (
if visible {
"RuntimeVisibleParameterAnnotations"
} else {
"RuntimeInvisibleParameterAnnotations"
},
dotend_list8! {"runtime", p, w,
p.val(".paramannotation")?;
p.eol()?;
p.list(w, ListKind::DotEnd, |p, w| {p.val(".annotation")?; p.annotation(w, false)?; p.eol()})?;
p.val("paramannotation")?;
p.eol()?
},
),
"typeannotations" => (
if visible {
"RuntimeVisibleTypeAnnotations"
} else {
"RuntimeInvisibleTypeAnnotations"
},
dotend_list! {"runtime", p, w, p.val(".typeannotation")?; p.ta_target_info(w)?; p.ta_target_path(w)?; p.annotation(w, true)?; p.eol()?},
),
_ => return self.err1("Expected annotations, paramannotations, or typeannotations", tok.1),
}
}
".signature" => ("Signature", |p, w| {
w.cp(p.utf()?);
Ok(())
}),
".sourcedebugextension" => ("SourceDebugExtension", |p, w| {
let span = p.assert_type(TokenType::StringLit)?;
let bs = string::unescape(span.0).map_err(|(msg, s)| p.error1(msg, Span(s)))?;
w.write(&bs);
Ok(())
}),
".sourcefile" => ("SourceFile", |p, w| {
w.cp(p.utf()?);
Ok(())
}),
".stackmaptable" => ("StackMapTable", |p, w| {
if let Some((count, buf)) = p.stack_map_table.take() {
w.u16(count);
w.extend_from_writer(buf);
Ok(())
} else {
let span = p.next()?.1;
p.err1(
"StackMapTable attribute may only be used inside Code attributes, and only once per method",
span,
)
}
}),
".synthetic" => ("Synthetic", |_p, _w| Ok(())),
_ => return self.err1("Unrecognized attribute directive", directive),
})
}
fn parse_attr_sub(&mut self, w: &mut Writer<'a>) -> Result<AttrResult<'a>, Error> {
let (name, len) = if self.tryv(".attribute") {
(Some(self.utf()?), if self.tryv("length") { Some(self.u32()?) } else { None })
} else {
(None, None)
};
if self.has_type(TokenType::StringLit) {
if let Some(name) = name {
let span = self.next()?.1;
let bs = string::unescape(span.0).map_err(|(msg, s)| self.error1(msg, Span(s)))?;
w.cp(name);
w.u32(len.unwrap_or(bs.len() as u32));
w.write(&bs);
return Ok(AttrResult::Normal);
}
}
let directive = self.next()?.1;
if directive.0 == ".bootstrapmethods" {
return Ok(AttrResult::ImplicitBootstrap {
name,
len,
span: directive,
});
}
let (name_str, body_cb) = self.get_parse_attr_body_fn(directive)?;
w.cp(name.unwrap_or(Self::static_utf(name_str, directive)));
let ph = w.ph32();
let start_buf_len = w.len();
body_cb(&mut *self, &mut *w)?;
let end_buf_len = w.len();
let len = len.unwrap_or(
(end_buf_len - start_buf_len)
.try_into()
.map_err(|_| self.error1("Exceeded maximum attribute length (2^32-1 bytes)", directive))?,
);
w.fill32(ph, len);
Ok(AttrResult::Normal)
}
pub fn parse_attr_allow_bsm(&mut self, w: &mut Writer<'a>, count: &mut u16) -> Result<AttrResult<'a>, Error> {
let span = self.peek()?.1;
let res = self.parse_attr_sub(w)?;
if *count == u16::MAX {
self.err1("Maximum number of attributes (65535) exceeded", span)
} else {
*count += 1;
Ok(res)
}
}
pub fn parse_attr(&mut self, w: &mut Writer<'a>, count: &mut u16) -> Result<(), Error> {
match self.parse_attr_allow_bsm(w, count)? {
AttrResult::Normal => Ok(()),
AttrResult::ImplicitBootstrap { span, .. } => {
self.err1("Implicit bootstrap method attributes can only be used at class level.", span)
}
}
}
///////////////////////////////////////////////////////////////////////////////
fn annotation(&mut self, w: &mut Writer<'a>, is_type: bool) -> Result<(), Error> {
w.cp(self.utf()?);
self.eol()?;
let ph = w.ph();
let mut count = 0;
while !self.tryv(".end") {
if count == u16::MAX {
let span = self.peek()?.1;
return self.err1("Maximum number of annotations elements (65535) exceeded", span);
}
count += 1;
w.cp(self.utf()?);
self.val("=")?;
self.element_value(w)?;
self.eol()?;
}
if is_type {
self.val("typeannotation")?;
} else {
self.val("annotation")?;
}
w.fill(ph, count);
Ok(())
}
fn element_value(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
let tok = self.next()?;
match tok.1 .0 {
"annotation" => {
w.u8(64);
self.annotation(w, false)?;
}
"array" => {
w.u8(91);
self.eol()?;
let ph = w.ph();
let mut count = 0;
while !self.tryv(".end") {
if count == u16::MAX {
let span = self.peek()?.1;
return self.err1("Maximum number of annotations in array element (65535) exceeded", span);
}
count += 1;
self.element_value(w)?;
self.eol()?;
}
self.val("array")?;
w.fill(ph, count);
}
"boolean" => {
w.u8(90);
w.cp(self.ldc_rhs()?);
}
"byte" => {
w.u8(66);
w.cp(self.ldc_rhs()?);
}
"char" => {
w.u8(67);
w.cp(self.ldc_rhs()?);
}
"class" => {
w.u8(99);
w.cp(self.utf()?);
}
"double" => {
w.u8(68);
w.cp(self.ldc_rhs()?);
}
"enum" => {
w.u8(101);
w.cp(self.utf()?);
w.cp(self.utf()?);
}
"float" => {
w.u8(70);
w.cp(self.ldc_rhs()?);
}
"int" => {
w.u8(73);
w.cp(self.ldc_rhs()?);
}
"long" => {
w.u8(74);
w.cp(self.ldc_rhs()?);
}
"short" => {
w.u8(83);
w.cp(self.ldc_rhs()?);
}
"string" => {
w.u8(115);
w.cp(self.utf()?);
}
_ => return self.err1("Unrecognized element value tag", tok.1),
};
Ok(())
}
fn local_var_table_item(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
let (ind, _, name, desc, _, start, _, end) = (
self.u16()?,
self.val("is")?,
self.utf()?,
self.utf()?,
self.val("from")?,
self.lblpos()?,
self.val("to")?,
self.lblpos()?,
);
w.u16(self.pos_to_u16(start)?);
w.u16(self.pos_diff_to_u16(start.v, end)?);
w.cp(name);
w.cp(desc);
w.u16(ind);
self.eol()
}
fn list(&mut self, w: &mut Writer<'a>, kind: ListKind, f: ParseFn<'a>) -> Result<(), Error> {
let ph = w.ph();
let mut count = 0;
while !kind.at_end(self) {
if count == u16::MAX {
let span = self.peek()?.1;
return self.err1("Maximum number of elements (65535) exceeded", span);
}
count += 1;
f(self, w)?;
}
w.fill(ph, count);
Ok(())
}
fn list8(&mut self, w: &mut Writer<'a>, kind: ListKind, f: ParseFn<'a>) -> Result<(), Error> {
let ph = w.ph8();
let mut count = 0;
while !kind.at_end(self) {
if count == u8::MAX {
let span = self.peek()?.1;
return self.err1("Maximum number of elements (255) exceeded", span);
}
count += 1;
f(self, w)?;
}
w.fill8(ph, count);
Ok(())
}
fn module(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
use ListKind::Greedy;
w.cp(self.utf()?);
w.u16(self.flags()?);
self.val("version")?;
w.cp(self.utf()?);
self.eol()?;
let exports_item = |p: &mut Self, w: &mut Writer<'a>| {
w.cp(p.single(InlineConst::Package)?);
w.u16(p.flags()?);
if p.tryv("to") {
p.list(w, ListKind::Line, |p, w| Ok(w.cp(p.single(InlineConst::Package)?)))?;
} else {
w.u16(0); // count of 0 targets
}
p.eol()
};
self.list(w, Greedy(".requires"), |p, w| {
w.cp(p.single(InlineConst::Module)?);
w.u16(p.flags()?);
p.val("version")?;
w.cp(p.utf()?);
p.eol()
})?;
self.list(w, Greedy(".exports"), exports_item)?;
self.list(w, Greedy(".opens"), exports_item)?;
self.list(w, Greedy(".uses"), |p, w| {
w.cp(p.cls()?);
p.eol()
})?;
self.list(w, Greedy(".provides"), |p, w| {
w.cp(p.cls()?);
p.val("with")?;
p.list(w, ListKind::Line, |p, w| Ok(w.cp(p.cls()?)))?;
p.eol()
})?;
self.val(".end")?;
self.val("module")
}
fn record_item(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
w.cp(self.utf()?);
w.cp(self.utf()?);
if self.tryv(".attributes") {
self.eol()?;
let ph = w.ph();
let mut attr_count = 0;
while !self.tryv(".end") {
self.parse_attr(w, &mut attr_count)?;
self.eol()?;
}
self.val("attributes")?;
w.fill(ph, attr_count);
} else {
w.u16(0);
}
self.eol()
}
fn ta_target_info(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
w.u8(self.u8()?);
let span = self.next()?.1;
match span.0 {
"typeparam" => w.u8(self.u8()?),
"super" => w.u16(self.u16()?),
"typeparambound" => {
w.u8(self.u8()?);
w.u8(self.u8()?)
}
"empty" => (),
"methodparam" => w.u8(self.u8()?),
"throws" => w.u16(self.u16()?),
"localvar" => {
self.eol()?;
self.list(w, ListKind::DotEnd, |p, w| {
if p.tryv("nowhere") {
w.u16(0xFFFF);
w.u16(0xFFFF);
} else {
let (_, start, _, end) = (p.val("from")?, p.lblpos()?, p.val("to")?, p.lblpos()?);
w.u16(p.pos_to_u16(start)?);
w.u16(p.pos_diff_to_u16(start.v, end)?);
}
w.u16(p.u16()?);
p.eol()
})?;
self.val("localvar")?;
}
"catch" => w.u16(self.u16()?),
"offset" => w.u16(self.lbl16()?),
"typearg" => {
w.u16(self.lbl16()?);
w.u8(self.u8()?)
}
_ => return self.err1("Expected type annotation target info type", span),
}
self.eol()
}
fn ta_target_path(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
self.val(".typepath")?;
self.eol()?;
self.list8(w, ListKind::DotEnd, |p, w| {
w.u8(p.u8()?);
w.u8(p.u8()?);
p.eol()
})?;
self.val("typepath")?;
self.eol()
}
}

View File

@ -0,0 +1,313 @@
use super::base_parser::BaseParser;
use super::class_parser::ns;
use super::class_parser::ClassParser;
use super::cpool::types;
use super::cpool::BsAttrNameNeeded;
use super::cpool::Or;
use super::parse_attr::AttrResult;
use super::span::Error;
use super::tokenize::TokenType;
use super::writer::BufWriter;
use super::writer::Writer;
impl<'a> ClassParser<'a> {
fn parse_const_def(&mut self) -> Result<(), Error> {
self.val(".const")?;
let lhs_span = self.assert_type(TokenType::Ref)?;
let lhs = self.ref_type(lhs_span)?;
self.val("=")?;
let rhs_span = self.peek()?.1;
let rhs = self.ref_or_tagged_const()?;
match lhs {
types::RefType::Raw(ind) => {
let rhs = match rhs {
Or::A(_) => return self.err1("Raw refs cannot be defined by another ref", rhs_span),
Or::B(b) => b,
};
self.pool.add_raw_def(ind, lhs_span, rhs)?
}
types::RefType::Sym(name) => self.pool.add_sym_def(name, ns(rhs))?,
};
self.eol()
}
fn parse_bootstrap_def(&mut self) -> Result<(), Error> {
self.val(".bootstrap")?;
let lhs_span = self.assert_type(TokenType::BsRef)?;
let lhs = self.ref_type(lhs_span)?;
self.val("=")?;
let rhs_span = self.peek()?.1;
let rhs = self.ref_or_tagged_bootstrap()?;
match lhs {
types::RefType::Raw(ind) => {
let rhs = match rhs {
Or::A(_) => return self.err1("Raw refs cannot be defined by another ref", rhs_span),
Or::B(b) => b,
};
self.pool.add_bs_raw_def(ind, lhs_span, rhs)?
}
types::RefType::Sym(name) => self.pool.add_bs_sym_def(name, ns(rhs))?,
};
self.eol()
}
///////////////////////////////////////////////////////////////////////////
fn parse_field_def(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
self.val(".field")?;
w.u16(self.flags()?);
w.cp(self.utf()?);
w.cp(self.utf()?);
let ph = w.ph();
let mut attr_count = 0;
if let Some(span) = self.tryv2("=") {
w.cp(Self::static_utf("ConstantValue", span));
w.u32(2);
w.cp(self.ldc_rhs()?);
attr_count += 1;
}
if self.tryv(".fieldattributes") {
self.eol()?;
while !self.tryv(".end") {
self.parse_attr(w, &mut attr_count)?;
self.eol()?;
}
self.val("fieldattributes")?;
}
w.fill(ph, attr_count);
self.eol()?;
Ok(())
}
fn parse_method_def(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
self.val(".method")?;
w.u16(self.flags()?);
w.cp(self.utf()?);
self.val(":")?;
w.cp(self.utf()?);
self.eol()?;
let ph = w.ph();
let mut attr_count = 0;
if self.peek()?.1 .0 == ".limit" {
self.parse_legacy_method_body(w)?;
attr_count = 1;
} else {
while !self.tryv(".end") {
self.parse_attr(w, &mut attr_count)?;
self.eol()?;
}
}
self.val("method")?;
self.eol()?;
w.fill(ph, attr_count);
Ok(())
}
///////////////////////////////////////////////////////////////////////////
pub fn parse(mut self) -> Result<(BaseParser<'a>, (Option<&'a [u8]>, Vec<u8>)), Error> {
if self.tryv(".version") {
self.version = (self.u16()?, self.u16()?);
self.eol()?;
};
// todo
let debug_span = self.peek()?.1;
let mut w = Writer::default();
self.val(".class")?;
w.u16(self.flags()?);
w.cp(self.cls()?);
self.eol()?;
self.val(".super")?;
w.cp(self.cls()?);
self.eol()?;
let ph = w.ph();
let mut interface_count = 0;
while let Some(span) = self.tryv2(".implements") {
if interface_count == u16::MAX {
return self.err1("Maximum number of interfaces (65535) exceeded", span);
}
interface_count += 1;
w.cp(self.cls()?);
self.eol()?;
}
w.fill(ph, interface_count);
let mut field_w = w;
let field_ph = field_w.ph();
let mut field_count = 0;
let mut method_w = Writer::default();
let mut method_count = 0;
// We won't know how the contents of the bootstrap attr, and thus how long it should be,
// until the constant pool has been fully resolved at the end. Therefore, we use two
// writers, one for attributes before the .bootstrapmethods attr (if any), including the
// name of the later, and second writer for any attributes that appear after the
// .bootstrapmethods attr if one is present. Once we put all the pieces of the classfile together
// at the end, we'll fill in the actual data for the bootstramp methods table in between.
let mut attr_w1 = Writer::default();
let mut bs_attr_placeholder_info = None;
let mut attr_w2 = Writer::default();
let mut attr_count = 0;
while let Ok(tok) = self.peek() {
match tok.1 .0 {
".bootstrap" => self.parse_bootstrap_def()?,
".const" => self.parse_const_def()?,
".field" => {
if field_count == u16::MAX {
return self.err1("Maximum number of fields (65535) exceeded", tok.1);
}
field_count += 1;
self.parse_field_def(&mut field_w)?;
}
".method" => {
if method_count == u16::MAX {
return self.err1("Maximum number of methods (65535) exceeded", tok.1);
}
method_count += 1;
self.parse_method_def(&mut method_w)?;
}
".end" => {
self.val(".end")?;
self.val("class")?;
self.eol()?;
break;
}
_ => {
if bs_attr_placeholder_info.is_none() {
match self.parse_attr_allow_bsm(&mut attr_w1, &mut attr_count)? {
AttrResult::Normal => (),
AttrResult::ImplicitBootstrap { name, len, span: _ } => {
let bs_name_ph = match name {
Some(name) => {
// attr has name explicitly provided, so just write it and don't store a placeholder
attr_w1.cp(name);
None
}
None => {
// attr has no explicit name, so store a placeholder
// to be filled in with the implicitly created name later
Some(attr_w1.ph())
}
};
bs_attr_placeholder_info = Some((bs_name_ph, len));
}
}
} else {
match self.parse_attr_allow_bsm(&mut attr_w2, &mut attr_count)? {
AttrResult::Normal => (),
AttrResult::ImplicitBootstrap { span, .. } => {
return self.err1("Duplicate .bootstrapmethods attribute", span);
}
}
}
self.eol()?;
// return self.err1("Expected .field, .method, .const, .bootstrap, .end class, or attribute directive", tok.1)
}
}
}
field_w.fill(field_ph, field_count);
let mut pool = self.pool.finish_defs()?;
// println!("data {:?}", field_w);
field_w.resolve_ldc_refs(|r, s| pool.resolve_ldc(r, s))?;
method_w.resolve_ldc_refs(|r, s| pool.resolve_ldc(r, s))?;
attr_w1.resolve_ldc_refs(|r, s| pool.resolve_ldc(r, s))?;
attr_w2.resolve_ldc_refs(|r, s| pool.resolve_ldc(r, s))?;
let field_w = field_w.resolve_refs(|r| pool.resolve(r))?;
let method_w = method_w.resolve_refs(|r| pool.resolve(r))?;
let mut attr_w1 = attr_w1.resolve_refs(|r| pool.resolve(r))?;
let attr_w2 = attr_w2.resolve_refs(|r| pool.resolve(r))?;
// println!("data {:?}", field_w);
let mut w = BufWriter::default();
w.u32(0xCAFEBABE);
w.u16(self.version.1);
w.u16(self.version.0);
let bs_attr_needed = match bs_attr_placeholder_info {
Some((Some(_), _)) => BsAttrNameNeeded::Always,
Some((None, _)) => BsAttrNameNeeded::Never,
None => BsAttrNameNeeded::IfPresent,
};
let class_name_ind = field_w.read_u16(2);
let (assembled_bs_attr_info, class_name) = pool.end().build(&mut w, bs_attr_needed, class_name_ind)?;
w.extend(&field_w);
w.u16(method_count);
w.extend(&method_w);
// println!("bsattr info {:?}", bs_attr_placeholder_info);
if let Some((name_ph, len)) = bs_attr_placeholder_info {
if let Some(ph) = name_ph {
attr_w1.fill(ph, assembled_bs_attr_info.name.unwrap());
}
w.u16(attr_count);
w.extend(&attr_w1);
let actual_length = assembled_bs_attr_info.data_len().ok_or_else(|| {
self.parser
.error1("BootstrapMethods table exceeds maximum attribute length", debug_span)
})?;
w.u32(len.unwrap_or(actual_length));
w.u16(assembled_bs_attr_info.num_bs);
w.write(&assembled_bs_attr_info.buf);
w.extend(&attr_w2);
} else {
// check if we need to add an implicit BootstrapMethods attribute at the end
if let Some(name) = assembled_bs_attr_info.name {
if attr_count == u16::MAX {
return self.parser.err1(
"Exceeded maximum class attribute count due to implicit BootstrapMethods attribute",
debug_span,
);
}
let actual_length = assembled_bs_attr_info.data_len().ok_or_else(|| {
self.parser
.error1("BootstrapMethods table exceeds maximum attribute length", debug_span)
})?;
w.u16(attr_count + 1);
w.extend(&attr_w1);
w.u16(name);
w.u32(actual_length);
w.u16(assembled_bs_attr_info.num_bs);
w.write(&assembled_bs_attr_info.buf);
} else {
w.u16(attr_count);
w.extend(&attr_w1);
}
}
// println!("finish bs stuff");
// println!("data {:?}", w);
Ok((self.parser, (class_name, w.into_buf())))
}
}

View File

@ -0,0 +1,875 @@
use super::class_parser::ns;
use super::class_parser::ClassParser;
use super::cpool::types;
use super::cpool::InlineConst;
use super::cpool::Or;
use super::label::Pos;
use super::span::Error;
use super::span::Span;
use super::tokenize::Token;
use super::tokenize::TokenType;
use super::writer::Placeholder;
use super::writer::Writer;
use std::collections::HashMap;
#[derive(Debug)]
struct ExceptionHandler<'a> {
cls: types::SymSpanClass<'a>,
start: Span<'a>,
end: Span<'a>,
target: Span<'a>,
}
struct LazyJump<'a, const N: usize> {
base: Pos,
target: Span<'a>,
ph: Placeholder<N>,
}
#[derive(Default)]
struct BytecodeState<'a> {
labels: HashMap<&'a str, Pos>,
short_jumps: Vec<LazyJump<'a, 2>>,
long_jumps: Vec<LazyJump<'a, 4>>,
exceptions: Vec<ExceptionHandler<'a>>,
stack_map_table: StackMapTable<'a>,
no_implicit_stackmap: bool,
}
#[derive(Default)]
struct StackMapTable<'a> {
w: Writer<'a>,
vtype_lbls: Vec<(Placeholder<2>, Span<'a>)>,
num_entries: u16,
last_pos: Option<Pos>,
// track first .stack span so we can use it as span for implicit attr if necessary
debug_span: Option<Span<'a>>,
}
impl<'a> ClassParser<'a> {
fn legacy_fmim(
&mut self,
f: fn(types::SymClassRef<'a>, types::SymNatRef<'a>) -> types::SymConstInline<'a>,
) -> Result<types::SymSpanConst<'a>, Error> {
// Hacks to support undocumented legacy syntax
let first = self.peek()?.1;
if self.has_type(TokenType::Ref) {
self.next()?; // consume first
// Legacy method syntax
if self.has_type(TokenType::Word) || self.has_type(TokenType::StringLit) {
let nat = self.nat()?;
return Ok(Or::B(first.of(f(self.ref_from(first)?, ns(nat)))));
}
return self.ref_from(first);
}
// Official syntax requires Field, Method, or InterfaceMethod tag (or ref, handled above)
match first.0 {
"Field" | "Method" | "InterfaceMethod" => return self.ref_or_tagged_const(),
_ => (),
}
let mut words = Vec::with_capacity(3);
while words.len() < 3 && (self.has_type(TokenType::Word) || self.has_type(TokenType::StringLit)) {
words.push(self.next()?);
}
if self.has_type(TokenType::Ref) {
if words.len() == 2 {
let cls = self.cls_from(words[0])?;
let name = self.utf_from(words[1])?;
let desc = self.utf()?;
let nat = types::InlineNat(ns(name), ns(desc));
return Ok(Or::B(first.of(f(ns(cls), Or::B(nat)))));
} else if words.len() == 1 {
let cls = self.cls_from(words[0])?;
let nat = self.nat()?;
return Ok(Or::B(first.of(f(ns(cls), ns(nat)))));
}
}
fn tok_from_substr<'a>(s: &'a str) -> Token<'a> {
Token(TokenType::Word, Span(s))
}
let (cls, name, desc) = match words.len() {
3 => (self.cls_from(words[0])?, self.utf_from(words[1])?, self.utf_from(words[2])?),
2 => {
let cnn = words[0].1 .0;
let (left, right) = cnn.rsplit_once('/').unwrap_or((cnn, cnn));
let cls = self.cls_from(tok_from_substr(left))?;
let name = self.utf_from(tok_from_substr(right))?;
let desc = self.utf_from(words[1])?;
(cls, name, desc)
}
1 => {
let cnnd = words[0].1 .0;
let (cnn, _) = cnnd.split_once('(').unwrap_or((cnnd, cnnd));
let (_, d) = cnnd.split_at(cnn.len()); // include the ( back into d
let (left, right) = cnn.rsplit_once('/').unwrap_or((cnn, cnn));
let cls = self.cls_from(tok_from_substr(left))?;
let name = self.utf_from(tok_from_substr(right))?;
let desc = self.utf_from(tok_from_substr(d))?;
(cls, name, desc)
}
_ => return self.err1("Expected Field, Method, InterfaceMethod, or ref", first),
};
let nat = types::InlineNat(ns(name), ns(desc));
Ok(Or::B(first.of(f(ns(cls), Or::B(nat)))))
}
fn parse_invokeinterface(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
let r = self.legacy_fmim(InlineConst::InterfaceMethod)?;
let args = if self.has_type(TokenType::Newlines) {
let debug_span = self.peek()?.1;
let desc = r
.as_b()
.and_then(|const_| match &const_.v {
InlineConst::InterfaceMethod(_, nat) => nat.as_b().and_then(|nat| nat.1.as_b().map(|utf| utf.0 .0)),
_ => None,
})
.ok_or_else(|| self.error1("Exceeded maximum bytecode length", debug_span))?;
let mut count = 1;
let mut off = 1;
while off < desc.len() {
match desc[off] {
// )
41 => {
break;
}
// [
91 => {}
// J, D
68 | 74 => {
count += 2;
}
// L
76 => {
count += 1;
while off < desc.len() && desc[off] != 59
/* ; */
{
off += 1;
}
}
_ => {
count += 1;
}
}
off += 1;
}
count
} else {
self.u8()?
};
w.cp(r);
w.u8(args);
w.u8(0);
Ok(())
}
fn short_jump_instr(&mut self, pos: Pos, state: &mut BytecodeState<'a>, w: &mut Writer<'a>) -> Result<(), Error> {
let target = self.lbl()?;
state.short_jumps.push(LazyJump {
base: pos,
target,
ph: w.ph(),
});
Ok(())
}
fn long_jump_instr(&mut self, pos: Pos, state: &mut BytecodeState<'a>, w: &mut Writer<'a>) -> Result<(), Error> {
let target = self.lbl()?;
state.long_jumps.push(LazyJump {
base: pos,
target,
ph: w.ph32(),
});
Ok(())
}
fn parse_tableswitch(&mut self, pos: Pos, state: &mut BytecodeState<'a>, w: &mut Writer<'a>) -> Result<(), Error> {
// 0 to 3 padding bytes
for _ in (pos.0 % 4)..3 {
w.u8(0);
}
let low = self.i32()?;
self.eol()?;
let base = pos;
let default_ph = w.ph32();
w.u32(low as u32);
let high_ph = w.ph32();
// First non-default jump
state.long_jumps.push(LazyJump {
base,
target: self.lbl()?,
ph: w.ph32(),
});
self.eol()?;
let mut high = low;
// Now do the rest of the jumps
while !self.tryv("default") {
if high == i32::MAX {
let span = self.peek()?.1;
return self.err1("Overflow in tableswitch index", span);
}
high += 1;
state.long_jumps.push(LazyJump {
base,
target: self.lbl()?,
ph: w.ph32(),
});
self.eol()?;
}
// default jump
self.val(":")?;
state.long_jumps.push(LazyJump {
base,
target: self.lbl()?,
ph: default_ph,
});
w.fill32(high_ph, high as u32);
Ok(())
}
fn parse_lookupswitch(&mut self, pos: Pos, state: &mut BytecodeState<'a>, w: &mut Writer<'a>) -> Result<(), Error> {
// 0 to 3 padding bytes
for _ in (pos.0 % 4)..3 {
w.u8(0);
}
self.eol()?;
let base = pos;
let mut jumps = HashMap::new();
while !self.tryv("default") {
let span = self.peek()?.1;
let key = self.i32()?;
self.val(":")?;
let target = self.lbl()?;
self.eol()?;
if jumps.insert(key, target).is_some() {
return self.err1("Duplicate lookupswitch key", span);
}
if jumps.len() > (i32::MAX as usize) {
return self.err1("Overflow in lookupswitch jump count", span);
}
}
// default jump
self.val(":")?;
state.long_jumps.push(LazyJump {
base,
target: self.lbl()?,
ph: w.ph32(),
});
w.u32(jumps.len().try_into().unwrap());
let mut pairs: Vec<_> = jumps.into_iter().collect();
pairs.sort_unstable_by_key(|t| t.0);
for (k, v) in pairs {
w.u32(k as u32);
state.long_jumps.push(LazyJump {
base,
target: v,
ph: w.ph32(),
});
}
Ok(())
}
fn parse_wide(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
let tok = self.next()?;
match tok.1 .0 {
"aload" => (w.u8(25), w.u16(self.u16()?)).0,
"astore" => (w.u8(58), w.u16(self.u16()?)).0,
"dload" => (w.u8(24), w.u16(self.u16()?)).0,
"dstore" => (w.u8(57), w.u16(self.u16()?)).0,
"fload" => (w.u8(23), w.u16(self.u16()?)).0,
"fstore" => (w.u8(56), w.u16(self.u16()?)).0,
"iinc" => (w.u8(132), w.u16(self.u16()?), w.u16(self.i16()? as u16)).0,
"iload" => (w.u8(21), w.u16(self.u16()?)).0,
"istore" => (w.u8(54), w.u16(self.u16()?)).0,
"lload" => (w.u8(22), w.u16(self.u16()?)).0,
"lstore" => (w.u8(55), w.u16(self.u16()?)).0,
"ret" => (w.u8(169), w.u16(self.u16()?)).0,
_ => return self.err1("Unrecognized wide bytecode opcode", tok.1),
};
Ok(())
}
fn newarray_code(&mut self) -> Result<u8, Error> {
let span = self.next()?.1;
match span.0 {
"boolean" => Ok(4),
"byte" => Ok(8),
"char" => Ok(5),
"double" => Ok(7),
"float" => Ok(6),
"int" => Ok(10),
"long" => Ok(11),
"short" => Ok(9),
_ => self.err1(
"Error, expected 'boolean', 'byte', 'char', 'double', 'float', 'int', 'long', or 'short'.",
span,
),
}
}
fn parse_stack_directive(&mut self, pos: Pos, state: &mut StackMapTable<'a>) -> Result<(), Error> {
let w = &mut state.w;
let vtype_lbls = &mut state.vtype_lbls;
let span = self.next()?.1;
let offset = if let Some(prev) = state.last_pos {
if pos.0 > prev.0 {
pos.0 - prev.0 - 1
} else {
return self.err1("Stack frame must have strictly greater bytecode offset than previous frame", span);
}
} else {
pos.0
};
let offset: u16 = offset
.try_into()
.map_err(|_| self.error1("Exceeded maximum bytecode offset", span))?;
match span.0 {
"same" => {
if offset <= 63 {
w.u8(offset as u8);
} else {
return self.err1("Exceeded maximum bytecode offset (try using same_extended instead).", span);
}
}
"stack_1" => {
if offset <= 63 {
w.u8(offset as u8 + 64);
self.parse_vtype(w, vtype_lbls)?;
} else {
return self.err1("Exceeded maximum bytecode offset (try using same_extended instead).", span);
}
}
"stack_1_extended" => {
w.u8(247);
w.u16(offset);
self.parse_vtype(w, vtype_lbls)?;
}
"chop" => {
let amt = self.u8()?;
if amt > 4 {
return self.err1("Chop amount must be at most 4. Use a full frame to remove more items.", span);
}
w.u8(251 - amt);
w.u16(offset);
}
"same_extended" => {
w.u8(251);
w.u16(offset);
}
"append" => {
let ph = w.ph8();
w.u16(offset);
let mut tag = 251;
while tag < 255 && self.has_type(TokenType::Word) {
self.parse_vtype(w, vtype_lbls)?;
tag += 1;
}
w.fill8(ph, tag);
}
"full" => {
w.u8(255);
w.u16(offset);
self.eol()?;
{
self.val("locals")?;
let ph = w.ph();
let mut count = 0;
while count < u16::MAX && self.has_type(TokenType::Word) {
self.parse_vtype(w, vtype_lbls)?;
count += 1;
}
w.fill(ph, count);
self.eol()?;
}
{
self.val("stack")?;
let ph = w.ph();
let mut count = 0;
while count < u16::MAX && self.has_type(TokenType::Word) {
self.parse_vtype(w, vtype_lbls)?;
count += 1;
}
w.fill(ph, count);
self.eol()?;
}
self.val(".end")?;
self.val("stack")?;
}
_ => return self.err1("Expected same, stack_1, stack_1_extended, chop, same_extended, append, or full", span),
}
if state.num_entries == u16::MAX {
return self.err1("Exceeded maximum number of stack map entries per method (65535).", span);
}
state.num_entries += 1;
state.last_pos = Some(pos);
Ok(())
}
fn parse_vtype(&mut self, w: &mut Writer<'a>, vtype_lbls: &mut Vec<(Placeholder<2>, Span<'a>)>) -> Result<(), Error> {
let span = self.next()?.1;
match span.0 {
"Double" => w.u8(3),
"Float" => w.u8(2),
"Integer" => w.u8(1),
"Long" => w.u8(4),
"Null" => w.u8(5),
"Object" => (w.u8(7), w.cp(self.cls()?)).0,
"Top" => w.u8(0),
"Uninitialized" => {
w.u8(8);
vtype_lbls.push((w.ph(), self.lbl()?));
}
"UninitializedThis" => w.u8(6),
_ => return self.err1("Expected 'Double', 'Float', 'Integer', 'Long', 'Null', 'Object', 'Top', 'Uninitialized', or 'UninitializedThis'", span),
}
Ok(())
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
fn parse_code_inner(&mut self, w: &mut Writer<'a>) -> Result<usize, Error> {
let start_buf_len = w.len();
let mut state = BytecodeState::default();
let debug_span = self.peek()?.1;
loop {
let tok = self.peek()?;
let pos = Pos((w.len() - start_buf_len)
.try_into()
.map_err(|_| self.error1("Exceeded maximum bytecode length", tok.1))?);
match tok.0 {
TokenType::LabelDef => {
let lbl = self.next()?.1 .0.trim_end_matches(':');
if state.labels.insert(lbl, pos).is_some() {
return self.err1("Duplicate label.", tok.1);
}
if self.has_type(TokenType::Word) {
self.parse_instr_line(pos, &mut state, w)?;
} else {
self.eol()?;
}
}
TokenType::Directive => {
if !self.parse_code_directive_line(pos, &mut state, w, tok.1)? {
break;
}
}
TokenType::Word => self.parse_instr_line(pos, &mut state, w)?,
_ => return self.err1("Expected bytecode instruction or directive.", tok.1),
}
}
let bytecode_len = w.len() - start_buf_len;
if !self.labels.is_empty() || !self.stack_map_table.is_none() {
return self.err1("Invalid nested Code attribute", debug_span);
}
self.labels = state.labels;
for jump in state.short_jumps {
let target = self.lbl_to_pos(jump.target)?;
let offset = self.pos_diff_to_i16(jump.base, target)?;
w.fill(jump.ph, offset as u16);
}
for jump in state.long_jumps {
let target = self.lbl_to_pos(jump.target)?;
let offset = self.pos_diff_to_i32(jump.base, target)?;
w.fill32(jump.ph, offset as u32);
}
for (ph, lbl) in state.stack_map_table.vtype_lbls {
let offset = self.pos_to_u16(self.lbl_to_pos(lbl)?)?;
state.stack_map_table.w.fill(ph, offset);
}
w.u16(state.exceptions.len().try_into().unwrap());
for except in state.exceptions {
w.u16(self.pos_to_u16(self.lbl_to_pos(except.start)?)?);
w.u16(self.pos_to_u16(self.lbl_to_pos(except.end)?)?);
w.u16(self.pos_to_u16(self.lbl_to_pos(except.target)?)?);
w.cp(except.cls);
}
self.stack_map_table = Some((state.stack_map_table.num_entries, state.stack_map_table.w));
// Only accept code attributes after all bytecode and code directives
let ph = w.ph();
let mut attr_count = 0;
while !self.tryv(".end") {
self.parse_attr(w, &mut attr_count)?;
self.eol()?;
}
// Implicit StackMapTable attribute
if let Some((count, buf)) = self.stack_map_table.take() {
if count > 0 && !state.no_implicit_stackmap {
let span = state.stack_map_table.debug_span.unwrap();
w.cp(Self::static_utf("StackMapTable", span));
w.u32(2 + buf.len() as u32);
w.u16(count);
w.extend_from_writer(buf);
attr_count += 1;
}
}
w.fill(ph, attr_count);
self.labels.clear();
Ok(bytecode_len)
}
pub fn parse_code(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
let is_short = self.version < (45, 3) && !self.tryv("long");
if is_short {
(self.val("stack")?, w.u8(self.u8()?), self.val("locals")?, w.u8(self.u8()?), self.eol()?);
let ph = w.ph();
let bytecode_len = self.parse_code_inner(w)?;
let debug_span = self.peek()?.1;
let len = bytecode_len
.try_into()
.map_err(|_| self.error1("Exceeded maximum bytecode length", debug_span))?;
w.fill(ph, len);
} else {
(
self.val("stack")?,
w.u16(self.u16()?),
self.val("locals")?,
w.u16(self.u16()?),
self.eol()?,
);
let ph = w.ph32();
let bytecode_len = self.parse_code_inner(w)?;
let debug_span = self.peek()?.1;
let len = bytecode_len
.try_into()
.map_err(|_| self.error1("Exceeded maximum bytecode length", debug_span))?;
w.fill32(ph, len);
}
self.val("code")
}
pub fn parse_legacy_method_body(&mut self, w: &mut Writer<'a>) -> Result<(), Error> {
let debug_span = self.peek()?.1;
w.cp(Self::static_utf("Code", debug_span));
let code_len_ph = w.ph32();
let start_buf_len = w.len();
/////////////////////////
let mut stack = u16::MAX;
let mut locals = u16::MAX;
while self.tryv(".limit") {
if self.tryv("stack") {
stack = self.u16()?;
} else {
self.val("locals")?;
locals = self.u16()?;
}
self.eol()?;
}
let is_short = self.version < (45, 3);
if is_short {
w.u8(stack as u8);
w.u8(locals as u8);
let ph = w.ph();
let bytecode_len = self.parse_code_inner(w)?;
w.fill(ph, bytecode_len as u16);
} else {
w.u16(stack);
w.u16(locals);
let ph = w.ph32();
let bytecode_len = self.parse_code_inner(w)?;
w.fill32(ph, bytecode_len as u32);
}
let code_attr_len = w.len() - start_buf_len;
w.fill32(code_len_ph, code_attr_len as u32);
Ok(())
}
fn parse_code_directive_line(
&mut self,
pos: Pos,
state: &mut BytecodeState<'a>,
_w: &mut Writer<'a>,
directive: Span<'a>,
) -> Result<bool, Error> {
match directive.0 {
".catch" => {
self.next()?;
let cls = self.cls()?;
self.val("from")?;
let start = self.lbl()?;
self.val("to")?;
let end = self.lbl()?;
self.val("using")?;
let target = self.lbl()?;
state.exceptions.push(ExceptionHandler { cls, start, end, target });
if state.exceptions.len() > u16::MAX as usize {
return self.err1("Maximum 65535 exception handlers per method", directive);
}
}
// Uncodumented directive for backwards compatibility with Krakatau v1
".noimplicitstackmap" => {
self.next()?;
state.no_implicit_stackmap = true;
}
".stack" => {
self.next()?;
state.stack_map_table.debug_span.get_or_insert(directive);
self.parse_stack_directive(pos, &mut state.stack_map_table)?;
}
_ => return Ok(false),
}
self.eol()?;
Ok(true)
}
fn parse_instr_line(&mut self, pos: Pos, state: &mut BytecodeState<'a>, w: &mut Writer<'a>) -> Result<(), Error> {
let instr = self.next()?.1;
match instr.0 {
"aaload" => (w.u8(50), ()).0,
"aastore" => (w.u8(83), ()).0,
"aconst_null" => (w.u8(1), ()).0,
"aload" => (w.u8(25), w.u8(self.u8()?)).0,
"aload_0" => (w.u8(42), ()).0,
"aload_1" => (w.u8(43), ()).0,
"aload_2" => (w.u8(44), ()).0,
"aload_3" => (w.u8(45), ()).0,
"anewarray" => (w.u8(189), w.cp(self.cls()?)).0,
"areturn" => (w.u8(176), ()).0,
"arraylength" => (w.u8(190), ()).0,
"astore" => (w.u8(58), w.u8(self.u8()?)).0,
"astore_0" => (w.u8(75), ()).0,
"astore_1" => (w.u8(76), ()).0,
"astore_2" => (w.u8(77), ()).0,
"astore_3" => (w.u8(78), ()).0,
"athrow" => (w.u8(191), ()).0,
"baload" => (w.u8(51), ()).0,
"bastore" => (w.u8(84), ()).0,
"bipush" => (w.u8(16), w.u8(self.i8()? as u8)).0,
"caload" => (w.u8(52), ()).0,
"castore" => (w.u8(85), ()).0,
"checkcast" => (w.u8(192), w.cp(self.cls()?)).0,
"d2f" => (w.u8(144), ()).0,
"d2i" => (w.u8(142), ()).0,
"d2l" => (w.u8(143), ()).0,
"dadd" => (w.u8(99), ()).0,
"daload" => (w.u8(49), ()).0,
"dastore" => (w.u8(82), ()).0,
"dcmpg" => (w.u8(152), ()).0,
"dcmpl" => (w.u8(151), ()).0,
"dconst_0" => (w.u8(14), ()).0,
"dconst_1" => (w.u8(15), ()).0,
"ddiv" => (w.u8(111), ()).0,
"dload" => (w.u8(24), w.u8(self.u8()?)).0,
"dload_0" => (w.u8(38), ()).0,
"dload_1" => (w.u8(39), ()).0,
"dload_2" => (w.u8(40), ()).0,
"dload_3" => (w.u8(41), ()).0,
"dmul" => (w.u8(107), ()).0,
"dneg" => (w.u8(119), ()).0,
"drem" => (w.u8(115), ()).0,
"dreturn" => (w.u8(175), ()).0,
"dstore" => (w.u8(57), w.u8(self.u8()?)).0,
"dstore_0" => (w.u8(71), ()).0,
"dstore_1" => (w.u8(72), ()).0,
"dstore_2" => (w.u8(73), ()).0,
"dstore_3" => (w.u8(74), ()).0,
"dsub" => (w.u8(103), ()).0,
"dup" => (w.u8(89), ()).0,
"dup2" => (w.u8(92), ()).0,
"dup2_x1" => (w.u8(93), ()).0,
"dup2_x2" => (w.u8(94), ()).0,
"dup_x1" => (w.u8(90), ()).0,
"dup_x2" => (w.u8(91), ()).0,
"f2d" => (w.u8(141), ()).0,
"f2i" => (w.u8(139), ()).0,
"f2l" => (w.u8(140), ()).0,
"fadd" => (w.u8(98), ()).0,
"faload" => (w.u8(48), ()).0,
"fastore" => (w.u8(81), ()).0,
"fcmpg" => (w.u8(150), ()).0,
"fcmpl" => (w.u8(149), ()).0,
"fconst_0" => (w.u8(11), ()).0,
"fconst_1" => (w.u8(12), ()).0,
"fconst_2" => (w.u8(13), ()).0,
"fdiv" => (w.u8(110), ()).0,
"fload" => (w.u8(23), w.u8(self.u8()?)).0,
"fload_0" => (w.u8(34), ()).0,
"fload_1" => (w.u8(35), ()).0,
"fload_2" => (w.u8(36), ()).0,
"fload_3" => (w.u8(37), ()).0,
"fmul" => (w.u8(106), ()).0,
"fneg" => (w.u8(118), ()).0,
"frem" => (w.u8(114), ()).0,
"freturn" => (w.u8(174), ()).0,
"fstore" => (w.u8(56), w.u8(self.u8()?)).0,
"fstore_0" => (w.u8(67), ()).0,
"fstore_1" => (w.u8(68), ()).0,
"fstore_2" => (w.u8(69), ()).0,
"fstore_3" => (w.u8(70), ()).0,
"fsub" => (w.u8(102), ()).0,
"getfield" => (w.u8(180), w.cp(self.legacy_fmim(InlineConst::Field)?)).0,
"getstatic" => (w.u8(178), w.cp(self.legacy_fmim(InlineConst::Field)?)).0,
"goto" => (w.u8(167), self.short_jump_instr(pos, state, w)?).0,
"goto_w" => (w.u8(200), self.long_jump_instr(pos, state, w)?).0,
"i2b" => (w.u8(145), ()).0,
"i2c" => (w.u8(146), ()).0,
"i2d" => (w.u8(135), ()).0,
"i2f" => (w.u8(134), ()).0,
"i2l" => (w.u8(133), ()).0,
"i2s" => (w.u8(147), ()).0,
"iadd" => (w.u8(96), ()).0,
"iaload" => (w.u8(46), ()).0,
"iand" => (w.u8(126), ()).0,
"iastore" => (w.u8(79), ()).0,
"iconst_0" => (w.u8(3), ()).0,
"iconst_1" => (w.u8(4), ()).0,
"iconst_2" => (w.u8(5), ()).0,
"iconst_3" => (w.u8(6), ()).0,
"iconst_4" => (w.u8(7), ()).0,
"iconst_5" => (w.u8(8), ()).0,
"iconst_m1" => (w.u8(2), ()).0,
"idiv" => (w.u8(108), ()).0,
"if_acmpeq" => (w.u8(165), self.short_jump_instr(pos, state, w)?).0,
"if_acmpne" => (w.u8(166), self.short_jump_instr(pos, state, w)?).0,
"if_icmpeq" => (w.u8(159), self.short_jump_instr(pos, state, w)?).0,
"if_icmpge" => (w.u8(162), self.short_jump_instr(pos, state, w)?).0,
"if_icmpgt" => (w.u8(163), self.short_jump_instr(pos, state, w)?).0,
"if_icmple" => (w.u8(164), self.short_jump_instr(pos, state, w)?).0,
"if_icmplt" => (w.u8(161), self.short_jump_instr(pos, state, w)?).0,
"if_icmpne" => (w.u8(160), self.short_jump_instr(pos, state, w)?).0,
"ifeq" => (w.u8(153), self.short_jump_instr(pos, state, w)?).0,
"ifge" => (w.u8(156), self.short_jump_instr(pos, state, w)?).0,
"ifgt" => (w.u8(157), self.short_jump_instr(pos, state, w)?).0,
"ifle" => (w.u8(158), self.short_jump_instr(pos, state, w)?).0,
"iflt" => (w.u8(155), self.short_jump_instr(pos, state, w)?).0,
"ifne" => (w.u8(154), self.short_jump_instr(pos, state, w)?).0,
"ifnonnull" => (w.u8(199), self.short_jump_instr(pos, state, w)?).0,
"ifnull" => (w.u8(198), self.short_jump_instr(pos, state, w)?).0,
"iinc" => (w.u8(132), w.u8(self.u8()?), w.u8(self.i8()? as u8)).0,
"iload" => (w.u8(21), w.u8(self.u8()?)).0,
"iload_0" => (w.u8(26), ()).0,
"iload_1" => (w.u8(27), ()).0,
"iload_2" => (w.u8(28), ()).0,
"iload_3" => (w.u8(29), ()).0,
"imul" => (w.u8(104), ()).0,
"ineg" => (w.u8(116), ()).0,
"instanceof" => (w.u8(193), w.cp(self.cls()?)).0,
"invokedynamic" => (w.u8(186), w.cp(self.ref_or_tagged_const()?), w.u16(0)).0,
"invokeinterface" => (w.u8(185), self.parse_invokeinterface(w)?).0,
"invokespecial" => (w.u8(183), w.cp(self.legacy_fmim(InlineConst::Method)?)).0,
"invokestatic" => (w.u8(184), w.cp(self.legacy_fmim(InlineConst::Method)?)).0,
"invokevirtual" => (w.u8(182), w.cp(self.legacy_fmim(InlineConst::Method)?)).0,
"ior" => (w.u8(128), ()).0,
"irem" => (w.u8(112), ()).0,
"ireturn" => (w.u8(172), ()).0,
"ishl" => (w.u8(120), ()).0,
"ishr" => (w.u8(122), ()).0,
"istore" => (w.u8(54), w.u8(self.u8()?)).0,
"istore_0" => (w.u8(59), ()).0,
"istore_1" => (w.u8(60), ()).0,
"istore_2" => (w.u8(61), ()).0,
"istore_3" => (w.u8(62), ()).0,
"isub" => (w.u8(100), ()).0,
"iushr" => (w.u8(124), ()).0,
"ixor" => (w.u8(130), ()).0,
"jsr" => (w.u8(168), self.short_jump_instr(pos, state, w)?).0,
"jsr_w" => (w.u8(201), self.long_jump_instr(pos, state, w)?).0,
"l2d" => (w.u8(138), ()).0,
"l2f" => (w.u8(137), ()).0,
"l2i" => (w.u8(136), ()).0,
"ladd" => (w.u8(97), ()).0,
"laload" => (w.u8(47), ()).0,
"land" => (w.u8(127), ()).0,
"lastore" => (w.u8(80), ()).0,
"lcmp" => (w.u8(148), ()).0,
"lconst_0" => (w.u8(9), ()).0,
"lconst_1" => (w.u8(10), ()).0,
"ldc" => (w.u8(18), w.cp_ldc(self.ldc_rhs()?, instr)).0,
"ldc2_w" => (w.u8(20), w.cp(self.ldc_rhs()?)).0,
"ldc_w" => (w.u8(19), w.cp(self.ldc_rhs()?)).0,
"ldiv" => (w.u8(109), ()).0,
"lload" => (w.u8(22), w.u8(self.u8()?)).0,
"lload_0" => (w.u8(30), ()).0,
"lload_1" => (w.u8(31), ()).0,
"lload_2" => (w.u8(32), ()).0,
"lload_3" => (w.u8(33), ()).0,
"lmul" => (w.u8(105), ()).0,
"lneg" => (w.u8(117), ()).0,
"lookupswitch" => (w.u8(171), self.parse_lookupswitch(pos, state, w)?).0,
"lor" => (w.u8(129), ()).0,
"lrem" => (w.u8(113), ()).0,
"lreturn" => (w.u8(173), ()).0,
"lshl" => (w.u8(121), ()).0,
"lshr" => (w.u8(123), ()).0,
"lstore" => (w.u8(55), w.u8(self.u8()?)).0,
"lstore_0" => (w.u8(63), ()).0,
"lstore_1" => (w.u8(64), ()).0,
"lstore_2" => (w.u8(65), ()).0,
"lstore_3" => (w.u8(66), ()).0,
"lsub" => (w.u8(101), ()).0,
"lushr" => (w.u8(125), ()).0,
"lxor" => (w.u8(131), ()).0,
"monitorenter" => (w.u8(194), ()).0,
"monitorexit" => (w.u8(195), ()).0,
"multianewarray" => (w.u8(197), w.cp(self.cls()?), w.u8(self.u8()?)).0,
"new" => (w.u8(187), w.cp(self.cls()?)).0,
"newarray" => (w.u8(188), w.u8(self.newarray_code()?)).0,
"nop" => (w.u8(0), ()).0,
"pop" => (w.u8(87), ()).0,
"pop2" => (w.u8(88), ()).0,
"putfield" => (w.u8(181), w.cp(self.legacy_fmim(InlineConst::Field)?)).0,
"putstatic" => (w.u8(179), w.cp(self.legacy_fmim(InlineConst::Field)?)).0,
"ret" => (w.u8(169), w.u8(self.u8()?)).0,
"return" => (w.u8(177), ()).0,
"saload" => (w.u8(53), ()).0,
"sastore" => (w.u8(86), ()).0,
"sipush" => (w.u8(17), w.u16(self.i16()? as u16)).0,
"swap" => (w.u8(95), ()).0,
"tableswitch" => (w.u8(170), self.parse_tableswitch(pos, state, w)?).0,
"wide" => (w.u8(196), self.parse_wide(w)?).0,
_ => return self.err1("Unrecognized bytecode opcode", instr),
}
self.eol()
}
}

View File

@ -0,0 +1,69 @@
use hexf_parse::parse_hexf32;
use hexf_parse::parse_hexf64;
pub fn int<T>(s: &str) -> Option<T>
where
T: std::str::FromStr,
T: TryFrom<i64>,
{
let s = s.trim_start_matches('+');
// Hack to support parsing '-0' as unsigned types
let s = if s == "-0" { "0" } else { s };
if s.starts_with("-0x") {
let m = u64::from_str_radix(&s[3..], 16).ok()?;
if m > 1 << 63 {
return None;
}
let m = (m as i64).wrapping_neg();
m.try_into().ok()
} else if s.starts_with("0x") {
let m = i64::from_str_radix(&s[2..], 16).ok()?;
m.try_into().ok()
} else {
s.parse().ok()
}
}
pub fn float(s: &str) -> Option<u32> {
let mut s = s.trim_start_matches('+');
if s.starts_with("-NaN") {
s = &s[1..];
}
if s.ends_with(">") {
// todo - test -NaN<...>
assert!(s.starts_with("NaN<0x"));
let hex_part = &s[6..s.len() - 1];
return u32::from_str_radix(hex_part, 16).ok();
}
let f = if s.starts_with("0x") || s.starts_with("-0x") {
parse_hexf32(s, false).ok()
} else {
s.parse().ok()
}?;
Some(f.to_bits())
}
pub fn double(s: &str) -> Option<u64> {
let mut s = s.trim_start_matches('+');
if s.starts_with("-NaN") {
s = &s[1..];
}
if s.ends_with(">") {
assert!(s.starts_with("NaN<0x"));
let hex_part = &s[6..s.len() - 1];
return u64::from_str_radix(hex_part, 16).ok();
}
let f = if s.starts_with("0x") || s.starts_with("-0x") {
parse_hexf64(s, false).ok()
} else {
s.parse().ok()
}?;
Some(f.to_bits())
}

204
src/lib/assemble/span.rs Normal file
View File

@ -0,0 +1,204 @@
use std::cmp::Eq;
use std::cmp::PartialEq;
use std::fmt::Debug;
use std::hash::Hash;
use std::hash::Hasher;
#[derive(Debug, Clone, Copy)]
pub struct Span<'a>(pub &'a str);
impl<'a> Span<'a> {
pub fn of<T>(self, val: T) -> Spanned<'a, T> {
Spanned { v: val, span: self }
}
}
#[derive(Clone, Copy)]
pub struct Spanned<'a, T> {
pub v: T,
pub span: Span<'a>,
}
impl<T: Hash> Hash for Spanned<'_, T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.v.hash(state);
}
}
impl<T: PartialEq> PartialEq for Spanned<'_, T> {
fn eq(&self, other: &Self) -> bool {
self.v == other.v
}
}
impl<T: Eq> Eq for Spanned<'_, T> {}
impl<T: Debug> Debug for Spanned<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.v.fmt(f)
}
}
#[derive(Debug, Clone, Copy)]
pub struct SpanBounds {
start: usize,
end: usize,
}
impl SpanBounds {
fn new(span: Span, source: &str) -> Self {
let start = span.0.as_ptr() as usize - source.as_ptr() as usize;
assert!(start <= source.len());
let end = start + span.0.len();
assert!(end <= source.len());
Self { start, end }
}
}
struct ErrorPrinter<'a> {
fname: &'a str,
lines: Vec<(Span<'a>, SpanBounds)>,
}
impl<'a> ErrorPrinter<'a> {
fn new(fname: &'a str, source: &'a str) -> Self {
// get line offsets
// let mut pos = 0;
let lines: Vec<_> = source
.lines()
.map(|line| {
// println!("{line:?}");
// let start = pos;
// pos += line.len();
// (start, pos)
let span = Span(line);
(span, SpanBounds::new(span, source))
})
.collect();
// offsets.push(pos);
// println!("offsets {:?}", lines);
// for sb in offsets {
// println!("{:?}", &source[sb.start..sb.end]);
// }
// dbg!(lines.partition_point(|sb| sb.start <= 0));
Self { fname, lines }
}
fn print(&self, is_first: bool, msg: &str, span: SpanBounds) {
// const MAXLINELEN: usize = 80; // todo
const TABWIDTH: usize = 8;
let line_no = self.lines.partition_point(|(_, bounds)| bounds.end < span.start);
let (Span(line), line_bounds) = self.lines[line_no];
// convert byte positions to character positions (within the line)
let mut start_ci = None;
let mut end_ci = None;
let mut ci = 0;
// println!("{span:?}");
for (byte_offset, c) in line.char_indices() {
let bpos = line_bounds.start + byte_offset;
// println!("{bpos} {ci} {c}");
if span.start == bpos {
start_ci = Some(ci);
}
if span.end == bpos {
end_ci = Some(ci);
}
ci += if c == '\t' { TABWIDTH } else { 1 };
}
let start_ci = start_ci.unwrap_or(ci);
let end_ci = end_ci.unwrap_or(ci);
let underline: String = (0..ci + 1)
.map(|i| {
if i == start_ci {
'^'
} else if i > start_ci && i < end_ci {
'~'
} else {
' '
}
})
.collect();
// if is_first {
// eprintln!("{}:{}:{} {}", self.fname, line_no + 1, start_ci + 1, msg);
// } else {
// eprintln!("{}:{}:{} {}", self.fname, line_no + 1, start_ci + 1, msg);
// }
// todo - better line limit
fn trim(s: &str) -> &str {
&s[0..std::cmp::min(115, s.len())]
}
eprintln!("{}:{}:{} {}", self.fname, line_no + 1, start_ci + 1, msg);
// eprintln!(
// "{}:{}:{} {} {}",
// self.fname,
// line_no + 1,
// start_ci + 1,
// msg,
// trim(&self.source[span.start..span.end])
// );
if is_first && line_no > 0 {
eprintln!("{}", trim(self.lines[line_no - 1].0 .0));
}
eprintln!("{}", trim(line));
eprintln!("{}", trim(&underline));
if is_first && line_no + 1 < self.lines.len() {
eprintln!("{}", trim(self.lines[line_no + 1].0 .0));
}
}
}
#[derive(Debug)]
pub struct Error(Vec<(String, SpanBounds)>);
impl Error {
pub fn new(source: &str, pairs: Vec<(&str, Span<'_>)>) -> Self {
Self(
pairs
.into_iter()
.map(|(msg, span)| (msg.to_owned(), SpanBounds::new(span, source)))
.collect(),
)
}
pub fn display(&self, fname: &str, source: &str) {
let printer = ErrorPrinter::new(fname, source);
let mut is_first = true;
for (msg, span) in self.0.iter() {
printer.print(is_first, msg, *span);
is_first = false;
}
}
}
#[derive(Clone, Copy)]
pub struct ErrorMaker<'a> {
source: &'a str,
}
impl<'a> ErrorMaker<'a> {
pub fn new(source: &'a str) -> Self {
Self { source }
}
pub fn error1(&self, msg: &str, span: Span<'_>) -> Error {
Error::new(self.source, vec![(msg, span)])
}
pub fn error2(&self, msg: &str, span: Span<'_>, msg2: &str, span2: Span<'_>) -> Error {
Error::new(self.source, vec![(msg, span), (msg2, span2)])
}
pub fn err1<T>(&self, msg: &str, span: Span<'_>) -> Result<T, Error> {
Err(self.error1(msg, span))
}
pub fn err2<T>(&self, msg: &str, span: Span<'_>, msg2: &str, span2: Span<'_>) -> Result<T, Error> {
Err(self.error2(msg, span, msg2, span2))
}
pub fn error1str(&self, msg: String, span: Span<'_>) -> Error {
Error(vec![(msg, SpanBounds::new(span, self.source))])
}
pub fn err1str<T>(&self, msg: String, span: Span<'_>) -> Result<T, Error> {
Err(self.error1str(msg, span))
}
}

View File

@ -0,0 +1,83 @@
fn mutf8_codepoint(out: &mut Vec<u8>, c: u16) {
match c {
1..=127 => out.push(c as u8),
0 | 0x80..=0x7FF => {
out.push(0xC0 ^ ((c >> 6) as u8));
out.push(0x80 ^ ((c & 63) as u8));
}
0x800..=0xFFFF => {
out.push(0xE0 ^ ((c >> 12) as u8));
out.push(0x80 ^ (((c >> 6) & 63) as u8));
out.push(0x80 ^ ((c & 63) as u8));
}
}
}
fn mutf8_char(out: &mut Vec<u8>, c: char) {
let c = c as u32;
if c >= 0x10000 {
let c = c - 0x10000;
let high = 0xD800 + ((c >> 10) as u16);
let low = 0xDC00 + ((c & 0x3FF) as u16);
mutf8_codepoint(out, high);
mutf8_codepoint(out, low);
} else {
mutf8_codepoint(out, c as u16);
}
}
pub fn unescape(s: &str) -> Result<Vec<u8>, (&'static str, &str)> {
let mut out = Vec::with_capacity(s.len() - 2);
let is_binary = s.starts_with('b');
let s = s.trim_start_matches('b');
let mut chars = s.chars();
let quote = chars.next().unwrap();
assert!(quote == '"' || quote == '\'');
while let Some(c) = chars.next() {
if c == quote {
break;
} else if c == '\\' {
let rest = chars.as_str();
match chars.next().ok_or(("Premature end of input", rest))? {
'\\' => out.push('\\' as u8),
'n' => out.push('\n' as u8),
'r' => out.push('\r' as u8),
't' => out.push('\t' as u8),
'"' => out.push('\"' as u8),
'\'' => out.push('\'' as u8),
'u' => {
let hex = chars.as_str().get(..4).ok_or(("Illegal unicode escape", rest))?;
let c = u16::from_str_radix(hex, 16).map_err(|_| ("Illegal unicode escape", hex))?;
mutf8_codepoint(&mut out, c);
chars = rest[5..].chars();
}
'U' => {
let hex = chars.as_str().get(..8).ok_or(("Illegal unicode escape", rest))?;
let c = u32::from_str_radix(hex, 16).map_err(|_| ("Illegal unicode escape", hex))?;
let c = c.try_into().map_err(|_| ("Illegal unicode code point value", hex))?;
mutf8_char(&mut out, c);
chars = rest[9..].chars();
}
'x' => {
let hex = chars.as_str().get(..2).ok_or(("Illegal hex escape", rest))?;
let c = u8::from_str_radix(hex, 16).map_err(|_| ("Illegal hex escape", hex))?;
if is_binary {
out.push(c);
} else {
// workaround for backwards compat with Krakatau 1
mutf8_codepoint(&mut out, c as u16);
}
chars = rest[3..].chars();
}
_ => return Err(("Illegal string escape", rest)),
}
} else {
mutf8_char(&mut out, c);
}
}
Ok(out)
}

View File

@ -0,0 +1,152 @@
use lazy_static::lazy_static;
use regex::Regex;
use regex::RegexSet;
use super::span::Error;
use super::span::Span;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenType {
Newlines,
Colon,
Equals,
Directive,
Word,
Ref,
BsRef,
LabelDef,
StringLit,
IntLit,
LongLit,
FloatLit,
DoubleLit,
}
#[derive(Debug, Clone, Copy)]
pub struct Token<'a>(pub TokenType, pub Span<'a>);
pub fn tokenize(source: &str) -> Result<Vec<Token>, Error> {
use TokenType::*;
static SET_PATTERNS: &[&str] = &[
r"\A(?:;.*)?\s+",
// COLON
r"\A:($|\s)",
// EQUALS
r"\A=($|\s)",
// DIRECTIVE
r"\A\.[a-z]+($|\s)",
// WORD
r"\A(?-u)(?:[a-zA-Z_$\(<]|\[[A-Z\[])[\w$;/\[\(\)<>*+-]*($|\s)",
// REF
r"\A\[[a-z0-9_]+\]($|\s)",
r"\A\[bs:[a-z0-9_]+\]($|\s)",
// LABEL_DEF
r"\AL\w+:($|\s)",
// STRING_LITERAL
r#"\Ab?"[^"\n\\]*(?:\\.[^"\n\\]*)*"($|\s)"#,
r#"\Ab?'[^'\n\\]*(?:\\.[^'\n\\]*)*'($|\s)"#,
// INT_LITERAL
r#"\A[+-]?(?:0x[0-9a-fA-F]+|[1-9][0-9]*|0)L?($|\s)"#,
// FLOAT_LITERAL
r#"\A[+-]Infinityf?($|\s)"#,
r#"\A[+-]NaN(?:<0x[0-9a-fA-F]+>)?f?($|\s)"#,
r#"\A(?-u)[+-]?\d+\.\d+(?:e[+-]?\d+)?f?($|\s)"#, // decimal float
r#"\A(?-u)[+-]?\d+(?:e[+-]?\d+)f?($|\s)"#, // decimal float without fraction (exponent mandatory)
r#"\A(?-u)[+-]?0x[0-9a-fA-F]+(?:\.[0-9a-fA-F]+)?(?:p[+-]?\d+)f?($|\s)"#, // hex float
];
lazy_static! {
static ref RE_SET: RegexSet = RegexSet::new(SET_PATTERNS).unwrap();
static ref RE_VEC: Vec<Regex> = SET_PATTERNS.iter().map(|pat| Regex::new(pat).unwrap()).collect();
}
let error1 = |msg, tok| Err(Error::new(source, vec![(msg, tok)]));
let error2 = |msg, tok, msg2, tok2| Err(Error::new(source, vec![(msg, tok), (msg2, tok2)]));
let mut tokens = Vec::new();
let mut s = source.trim_end();
let mut has_newline = true;
while s.len() > 0 {
let matches: Vec<_> = RE_SET.matches(s).iter().collect();
// Invalid token
if matches.len() == 0 {
const SUFFIX_LEN: usize = r"($|\s)".len();
let trimmed_res: Vec<_> = SET_PATTERNS[1..]
.iter()
.map(|p| Regex::new(&p[..p.len() - SUFFIX_LEN]).unwrap())
.collect();
let best = trimmed_res.into_iter().filter_map(|re| re.find(s)).max_by_key(|m| m.end());
if let Some(best) = best {
let size = best.end();
let tok = Span(&s[..size]);
let tok2 = Span(&s[size..size]);
return error2("Error: Invalid token", tok, "Hint: Try adding a space here.", tok2);
} else if s.starts_with('"') || s.starts_with("'") {
let tok = Span(&s[..1]);
return error1("Error: Unclosed string literal", tok);
} else {
let tok = Span(s.split_whitespace().next().unwrap());
return error1("Error: Invalid token", tok);
}
}
assert!(matches.len() == 1);
let m_i = matches[0];
let m = RE_VEC[m_i].find(s).unwrap();
assert!(m.start() == 0);
let (tok, rest) = s.split_at(m.end());
if m_i == 0 {
// whitespace
if !has_newline && tok.contains('\n') {
tokens.push(Token(Newlines, Span(tok)));
has_newline = true;
}
} else {
has_newline = tok.ends_with('\n');
let tok = tok.trim_end();
let ty = match m_i {
1 => Colon,
2 => Equals,
3 => Directive,
4 => Word,
5 => Ref,
6 => BsRef,
7 => LabelDef,
8..=9 => StringLit,
10 => {
if tok.ends_with('L') {
LongLit
} else {
IntLit
}
}
11..=15 => {
if tok.ends_with('f') {
FloatLit
} else {
DoubleLit
}
}
_ => panic!("Internal error, please report this"),
};
tokens.push(Token(ty, Span(tok)));
if has_newline {
tokens.push(Token(Newlines, Span(&s[tok.len()..tok.len() + 1])));
}
}
s = rest;
}
if !has_newline {
tokens.push(Token(Newlines, Span(s)));
}
Ok(tokens)
}

169
src/lib/assemble/writer.rs Normal file
View File

@ -0,0 +1,169 @@
use std::fmt::Debug;
use std::sync::atomic::AtomicBool;
use super::cpool::types;
use super::cpool::Or;
use crate::lib::assemble::span::Span;
use crate::lib::assemble::span::Spanned;
#[derive(Debug)]
pub struct Placeholder<const N: usize>(usize);
impl<const N: usize> Placeholder<N> {
fn new(off: usize) -> Self {
Self(off)
}
fn increment(mut self, off: usize) -> Self {
self.0 += off;
self
}
fn into_range(self) -> std::ops::Range<usize> {
let off = self.0;
std::mem::forget(self); // avoid drop check
off..(off + N)
}
}
// temporary debug check to make sure placeholders are all used
pub static UNUSED_PH: AtomicBool = AtomicBool::new(false);
impl<const N: usize> Drop for Placeholder<N> {
fn drop(&mut self) {
UNUSED_PH.store(true, std::sync::atomic::Ordering::Relaxed);
}
}
fn assert_zero(buf: &mut [u8]) -> &mut [u8] {
assert!(buf.into_iter().all(|b| *b == 0));
buf
}
#[derive(Default)]
pub struct BufWriter {
buf: Vec<u8>,
}
impl BufWriter {
pub fn into_buf(self) -> Vec<u8> {
self.buf
}
pub fn len(&self) -> usize {
self.buf.len()
}
// pub fn len(&self) -> usize {self.buf.len()}
pub fn extend(&mut self, v: &BufWriter) {
self.buf.extend_from_slice(&v.buf)
}
pub fn write(&mut self, v: &[u8]) {
self.buf.extend_from_slice(v)
}
pub fn u8(&mut self, v: u8) {
self.buf.push(v)
}
pub fn u16(&mut self, v: u16) {
self.write(&v.to_be_bytes())
}
pub fn u32(&mut self, v: u32) {
self.write(&v.to_be_bytes())
}
pub fn u64(&mut self, v: u64) {
self.write(&v.to_be_bytes())
}
///////////////////////////////////////////////////////////////////////////
pub fn ph(&mut self) -> Placeholder<2> {
let i = self.buf.len();
self.u16(0);
Placeholder::new(i)
}
pub fn ph8(&mut self) -> Placeholder<1> {
let i = self.buf.len();
self.u8(0);
Placeholder::new(i)
}
pub fn ph32(&mut self) -> Placeholder<4> {
let i = self.buf.len();
self.u32(0);
Placeholder::new(i)
}
pub fn fill(&mut self, ph: Placeholder<2>, v: u16) {
assert_zero(&mut self.buf[ph.into_range()]).copy_from_slice(&v.to_be_bytes());
}
pub fn fill8(&mut self, ph: Placeholder<1>, v: u8) {
assert_zero(&mut self.buf[ph.into_range()]).copy_from_slice(&v.to_be_bytes());
}
pub fn fill32(&mut self, ph: Placeholder<4>, v: u32) {
assert_zero(&mut self.buf[ph.into_range()]).copy_from_slice(&v.to_be_bytes());
}
///////////////////////////////////////////////////////////////////////////
pub fn read_u16(&self, ind: usize) -> u16 {
u16::from_be_bytes(self.buf[ind..ind + 2].try_into().unwrap())
}
}
impl Debug for BufWriter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// self.buf.fmt(f)
f.write_fmt(format_args!("{:02X?}", self.buf))
}
}
#[derive(Debug, Default)]
pub struct Writer<'a> {
w: BufWriter,
ldc_refs: Vec<(Placeholder<1>, types::SymSpanConst<'a>, Span<'a>)>,
refs: Vec<(Placeholder<2>, types::SymSpanConst<'a>)>,
}
impl<'a> Writer<'a> {
pub fn cp(&mut self, r: Or<types::RefType<'a>, Spanned<'a, impl types::ToConst<'a, types::RefType<'a>>>>) {
let ph = self.ph();
// self.refs.push((ph, r.map_b(types::ToConst::to_const)));
self.refs.push((ph, r.map_b(|c| c.span.of(c.v.to_const()))));
}
pub fn cp_ldc(&mut self, r: types::SymSpanConst<'a>, ldc_span: Span<'a>) {
let ph = self.ph8();
self.ldc_refs.push((ph, r, ldc_span));
}
pub fn resolve_ldc_refs<E>(
&mut self,
mut f: impl FnMut(types::SymSpanConst<'a>, Span<'a>) -> Result<u8, E>,
) -> Result<(), E> {
for (ph, r, ldc_span) in self.ldc_refs.drain(..) {
self.w.fill8(ph, f(r, ldc_span)?);
}
Ok(())
}
pub fn resolve_refs<E>(mut self, mut f: impl FnMut(types::SymSpanConst<'a>) -> Result<u16, E>) -> Result<BufWriter, E> {
assert!(self.ldc_refs.is_empty());
for (ph, r) in self.refs.drain(..) {
self.w.fill(ph, f(r)?);
}
Ok(self.w)
}
pub fn extend_from_writer(&mut self, w: Writer<'a>) {
let off = self.len();
self.buf.extend_from_slice(&w.buf);
self.ldc_refs
.extend(w.ldc_refs.into_iter().map(|(ph, cp, span)| (ph.increment(off), cp, span)));
self.refs.extend(w.refs.into_iter().map(|(ph, cp)| (ph.increment(off), cp)));
}
}
impl<'a> std::ops::Deref for Writer<'a> {
type Target = BufWriter;
fn deref(&self) -> &Self::Target {
&self.w
}
}
impl<'a> std::ops::DerefMut for Writer<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.w
}
}

466
src/lib/classfile/attrs.rs Normal file
View File

@ -0,0 +1,466 @@
use super::code;
use super::code::MaybePosSet;
use super::code::Pos;
use super::code::PosSet;
use super::cpool::ConstPool;
use super::reader::ParseError;
use super::reader::Reader;
use crate::lib::util::BStr;
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub struct BootstrapMethod {
pub bsref: u16,
pub args: Vec<u16>,
}
impl BootstrapMethod {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
Ok(Self {
bsref: r.u16()?,
args: r.parse_list(Reader::u16)?,
})
}
}
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub enum ElementValue {
Anno(Annotation),
Array(Vec<ElementValue>),
Enum(u16, u16),
Class(u16),
Str(u16),
Byte(u16),
Boolean(u16),
Char(u16),
Short(u16),
Int(u16),
Float(u16),
Long(u16),
Double(u16),
}
impl ElementValue {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
use ElementValue::*;
Ok(match r.u8()? {
64 => Anno(Annotation::new(r)?),
66 => Byte(r.u16()?),
67 => Char(r.u16()?),
68 => Double(r.u16()?),
70 => Float(r.u16()?),
73 => Int(r.u16()?),
74 => Long(r.u16()?),
83 => Short(r.u16()?),
90 => Boolean(r.u16()?),
91 => Array(r.parse_list(ElementValue::new)?),
99 => Class(r.u16()?),
101 => Enum(r.u16()?, r.u16()?),
115 => Str(r.u16()?),
_ => return ParseError::s("Invalid element value tag"),
})
}
}
#[derive(Debug)]
pub struct Annotation(pub u16, pub Vec<(u16, ElementValue)>);
impl Annotation {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
let desc = r.u16()?;
let vals = r.parse_list(|r| Ok((r.u16()?, ElementValue::new(r)?)))?;
Ok(Self(desc, vals))
}
}
#[derive(Debug, Clone, Copy)]
pub struct LocalVarTargetInfo {
pub range: Option<(Pos, Pos)>,
pub index: u16,
}
impl LocalVarTargetInfo {
fn new(r: &mut Reader, pset: Option<&PosSet>) -> Result<Self, ParseError> {
let (start, length, index) = (r.u16()?, r.u16()?, r.u16()?);
// WTF, Java?
let range = if start == 0xFFFF && length == 0xFFFF {
None
} else {
let start = pset.make(start)?;
let end = pset.make_off(start, length)?;
Some((start, end))
};
Ok(Self { range, index })
}
}
type TargetInfo = (u8, TargetInfoData);
#[derive(Debug)]
pub enum TargetInfoData {
TypeParam(u8),
Super(u16),
TypeParamBound(u8, u8),
Empty,
FormalParam(u8),
Throws(u16),
LocalVar(Vec<LocalVarTargetInfo>),
Catch(u16),
Offset(Pos),
TypeArgument(Pos, u8),
}
impl TargetInfoData {
fn new(r: &mut Reader, pset: Option<&PosSet>) -> Result<TargetInfo, ParseError> {
use TargetInfoData::*;
let tag = r.u8()?;
let body = match tag {
0x00 => TypeParam(r.u8()?),
0x01 => TypeParam(r.u8()?),
0x10 => Super(r.u16()?),
0x11 => TypeParamBound(r.u8()?, r.u8()?),
0x12 => TypeParamBound(r.u8()?, r.u8()?),
0x13 => Empty,
0x14 => Empty,
0x15 => Empty,
0x16 => FormalParam(r.u8()?),
0x17 => Throws(r.u16()?),
0x40 => LocalVar(r.parse_list(|r| LocalVarTargetInfo::new(r, pset))?),
0x41 => LocalVar(r.parse_list(|r| LocalVarTargetInfo::new(r, pset))?),
0x42 => Catch(r.u16()?),
0x43 => Offset(pset.make(r.u16()?)?),
0x44 => Offset(pset.make(r.u16()?)?),
0x45 => Offset(pset.make(r.u16()?)?),
0x46 => Offset(pset.make(r.u16()?)?),
0x47 => TypeArgument(pset.make(r.u16()?)?, r.u8()?),
0x48 => TypeArgument(pset.make(r.u16()?)?, r.u8()?),
0x49 => TypeArgument(pset.make(r.u16()?)?, r.u8()?),
0x4A => TypeArgument(pset.make(r.u16()?)?, r.u8()?),
0x4B => TypeArgument(pset.make(r.u16()?)?, r.u8()?),
_ => return ParseError::s("Invalid target info tag"),
};
Ok((tag, body))
}
}
#[derive(Debug)]
pub struct ParameterAnnotation(pub Vec<Annotation>);
impl ParameterAnnotation {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
Ok(Self(r.parse_list(Annotation::new)?))
}
}
#[derive(Debug)]
pub struct TypeAnnotation {
pub info: TargetInfo,
pub path: Vec<(u8, u8)>,
pub anno: Annotation,
}
impl TypeAnnotation {
fn new(r: &mut Reader, pset: Option<&PosSet>) -> Result<Self, ParseError> {
let info = TargetInfoData::new(r, pset)?;
let path = r.parse_list_bytelen(|r| Ok((r.u8()?, r.u8()?)))?;
let anno = Annotation::new(r)?;
Ok(Self { info, path, anno })
}
}
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub struct RecordComponent<'a> {
pub name: u16,
pub desc: u16,
pub attrs: Vec<Attribute<'a>>,
}
impl<'a> RecordComponent<'a> {
fn new(r: &mut Reader<'a>, cp: &ConstPool<'a>, pset: Option<&PosSet>) -> Result<Self, ParseError> {
let name = r.u16()?;
let desc = r.u16()?;
let attrs = Attribute::new_list(r, cp, pset, code::CodeOptions::default())?;
Ok(Self { name, desc, attrs })
}
}
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub struct Requires {
pub module: u16,
pub flags: u16,
pub version: u16,
}
impl Requires {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
Ok(Self {
module: r.u16()?,
flags: r.u16()?,
version: r.u16()?,
})
}
}
#[derive(Debug)]
pub struct ModPackage {
pub package: u16,
pub flags: u16,
pub modules: Vec<u16>,
}
impl ModPackage {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
Ok(Self {
package: r.u16()?,
flags: r.u16()?,
modules: r.parse_list(Reader::u16)?,
})
}
}
#[derive(Debug)]
pub struct Provides {
pub cls: u16,
pub provides_with: Vec<u16>,
}
impl Provides {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
Ok(Self {
cls: r.u16()?,
provides_with: r.parse_list(Reader::u16)?,
})
}
}
#[derive(Debug)]
pub struct ModuleAttr {
pub module: u16,
pub flags: u16,
pub version: u16,
pub requires: Vec<Requires>,
pub exports: Vec<ModPackage>,
pub opens: Vec<ModPackage>,
pub uses: Vec<u16>,
pub provides: Vec<Provides>,
}
impl ModuleAttr {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
Ok(Self {
module: r.u16()?,
flags: r.u16()?,
version: r.u16()?,
requires: r.parse_list(Requires::new)?,
exports: r.parse_list(ModPackage::new)?,
opens: r.parse_list(ModPackage::new)?,
uses: r.parse_list(Reader::u16)?,
provides: r.parse_list(Provides::new)?,
})
}
}
#[derive(Debug, Clone, Copy)]
pub struct LocalVarLine {
pub start: Pos,
pub end: Pos,
pub name: u16,
pub desc: u16,
pub ind: u16,
}
impl LocalVarLine {
fn new(r: &mut Reader, pset: Option<&PosSet>) -> Result<Self, ParseError> {
let start = pset.make(r.u16()?)?;
let length = r.u16()?;
let end = pset.make_off(start, length)?;
Ok(Self {
start,
end,
name: r.u16()?,
desc: r.u16()?,
ind: r.u16()?,
})
}
}
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug)]
pub enum AttrBody<'a> {
AnnotationDefault(Box<ElementValue>),
BootstrapMethods(Vec<BootstrapMethod>),
Code((Box<code::Code<'a>>, Option<Box<code::Code<'a>>>)),
ConstantValue(u16),
Deprecated,
EnclosingMethod(u16, u16),
Exceptions(Vec<u16>),
InnerClasses(Vec<(u16, u16, u16, u16)>),
LineNumberTable(Vec<(Pos, u16)>),
LocalVariableTable(Vec<LocalVarLine>),
LocalVariableTypeTable(Vec<LocalVarLine>),
MethodParameters(Vec<(u16, u16)>),
Module(Box<ModuleAttr>),
ModuleMainClass(u16),
ModulePackages(Vec<u16>),
NestHost(u16),
NestMembers(Vec<u16>),
PermittedSubclasses(Vec<u16>),
Record(Vec<RecordComponent<'a>>),
RuntimeInvisibleAnnotations(Vec<Annotation>),
RuntimeInvisibleParameterAnnotations(Vec<ParameterAnnotation>),
RuntimeInvisibleTypeAnnotations(Vec<TypeAnnotation>),
RuntimeVisibleAnnotations(Vec<Annotation>),
RuntimeVisibleParameterAnnotations(Vec<ParameterAnnotation>),
RuntimeVisibleTypeAnnotations(Vec<TypeAnnotation>),
Signature(u16),
SourceDebugExtention(&'a [u8]),
SourceFile(u16),
StackMapTable(code::StackMapTable),
Synthetic,
Raw(&'a [u8]),
}
impl<'a> AttrBody<'a> {
pub fn new(
name: &'a [u8],
data: &'a [u8],
cp: &ConstPool<'a>,
pset: Option<&PosSet>,
code_opts: code::CodeOptions,
) -> Self {
Self::try_parse(name, data, cp, pset, code_opts).unwrap_or(Self::Raw(data))
// Self::try_parse(name, data, cp).unwrap()
}
fn try_parse(
name: &'a [u8],
data: &'a [u8],
cp: &ConstPool<'a>,
pset: Option<&PosSet>,
code_opts: code::CodeOptions,
) -> Result<Self, ParseError> {
use AttrBody::*;
let mut r = Reader(data);
let r = &mut r;
let parsed = match name {
b"AnnotationDefault" => AnnotationDefault(Box::new(ElementValue::new(r)?)),
b"BootstrapMethods" => BootstrapMethods(r.parse_list(BootstrapMethod::new)?),
b"Code" => {
let c = Code(code::Code::parse(r.clone(), cp, code_opts)?);
r.0 = &[];
c
}
b"ConstantValue" => ConstantValue(r.u16()?),
b"Deprecated" => Deprecated,
b"EnclosingMethod" => EnclosingMethod(r.u16()?, r.u16()?),
b"Exceptions" => Exceptions(r.parse_list(|r| Ok(r.u16()?))?),
b"InnerClasses" => InnerClasses(r.parse_list(|r| Ok((r.u16()?, r.u16()?, r.u16()?, r.u16()?)))?),
b"LineNumberTable" => LineNumberTable(r.parse_list(|r| Ok((pset.make(r.u16()?)?, r.u16()?)))?),
b"LocalVariableTable" => LocalVariableTable(r.parse_list(|r| LocalVarLine::new(r, pset))?),
b"LocalVariableTypeTable" => LocalVariableTypeTable(r.parse_list(|r| LocalVarLine::new(r, pset))?),
b"MethodParameters" => MethodParameters(r.parse_list_bytelen(|r| Ok((r.u16()?, r.u16()?)))?),
b"Module" => Module(Box::new(ModuleAttr::new(r)?)),
b"ModuleMainClass" => ModuleMainClass(r.u16()?),
b"ModulePackages" => ModulePackages(r.parse_list(|r| Ok(r.u16()?))?),
b"NestHost" => NestHost(r.u16()?),
b"NestMembers" => NestMembers(r.parse_list(|r| Ok(r.u16()?))?),
b"PermittedSubclasses" => PermittedSubclasses(r.parse_list(|r| Ok(r.u16()?))?),
b"Record" => Record(r.parse_list(|r| RecordComponent::new(r, cp, pset))?),
b"RuntimeInvisibleAnnotations" => RuntimeInvisibleAnnotations(r.parse_list(Annotation::new)?),
b"RuntimeInvisibleParameterAnnotations" => {
RuntimeInvisibleParameterAnnotations(r.parse_list_bytelen(ParameterAnnotation::new)?)
}
b"RuntimeInvisibleTypeAnnotations" => {
RuntimeInvisibleTypeAnnotations(r.parse_list(|r| TypeAnnotation::new(r, pset))?)
}
b"RuntimeVisibleAnnotations" => RuntimeVisibleAnnotations(r.parse_list(Annotation::new)?),
b"RuntimeVisibleParameterAnnotations" => {
RuntimeVisibleParameterAnnotations(r.parse_list_bytelen(ParameterAnnotation::new)?)
}
b"RuntimeVisibleTypeAnnotations" => {
RuntimeVisibleTypeAnnotations(r.parse_list(|r| TypeAnnotation::new(r, pset))?)
}
b"Signature" => Signature(r.u16()?),
b"SourceDebugExtention" => SourceDebugExtention(data),
b"SourceFile" => SourceFile(r.u16()?),
b"StackMapTable" => StackMapTable(code::StackMapTable::new(r, pset)?),
b"Synthetic" => Synthetic,
_ => Raw(data),
};
// assert!(r.0.len() == 0);
Ok(if r.0.len() > 0 { Raw(data) } else { parsed })
// Ok(parsed)
}
pub fn is_raw(&self) -> bool {
matches!(self, AttrBody::Raw(_))
}
}
#[derive(Debug)]
pub struct Attribute<'a> {
pub name: u16,
pub length: u32,
pub actual_length: u32,
pub name_utf: BStr<'a>,
pub body: AttrBody<'a>,
}
impl<'a> Attribute<'a> {
pub(super) fn new(
r: &mut Reader<'a>,
cp: &ConstPool<'a>,
pset: Option<&PosSet>,
allow_stackmap: bool,
code_opts: code::CodeOptions,
) -> Result<Self, ParseError> {
let name_ind = r.u16()?;
let length = r.u32()?;
let name_utf = cp.utf8(name_ind).ok_or(ParseError("Attribute has invalid name index"))?;
let actual_length = if name_utf == b"InnerClasses" {
r.clone().u16()? as u32 * 8 + 2
} else {
length
};
let data = r.get(actual_length as usize)?;
let mut body = AttrBody::new(name_utf, data, cp, pset, code_opts);
if !allow_stackmap {
if let AttrBody::StackMapTable(..) = body {
body = AttrBody::Raw(data);
}
}
Ok(Self {
name: name_ind,
length,
actual_length,
name_utf: BStr(name_utf),
body,
})
}
pub(super) fn new_list(
r: &mut Reader<'a>,
cp: &ConstPool<'a>,
pset: Option<&PosSet>,
code_opts: code::CodeOptions,
) -> Result<Vec<Self>, ParseError> {
let mut allow_stackmap = true;
r.parse_list(|r| {
let attr = Attribute::new(r, cp, pset, allow_stackmap, code_opts)?;
if let AttrBody::StackMapTable(..) = attr.body {
allow_stackmap = false;
}
Ok(attr)
})
}
pub(super) fn has_ambiguous_short_code(&self) -> bool {
if let AttrBody::Code((_, Some(_))) = self.body {
true
} else {
false
}
}
}

885
src/lib/classfile/code.rs Normal file
View File

@ -0,0 +1,885 @@
use super::attrs::Attribute;
use super::cpool::ConstPool;
use super::reader::ParseError;
use super::reader::Reader;
use std::collections::HashSet;
use std::fmt;
use std::fmt::Display;
#[derive(Clone, Copy, Debug, Default)]
pub struct CodeOptions {
pub allow_short: bool,
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
pub struct Pos(u32);
impl Pos {
fn off_sub(self, off: i32) -> Result<Self, ParseError> {
match (self.0 as i64)
.checked_add(off as i64)
.map(u32::try_from)
.and_then(|r| r.ok())
{
Some(v) => Ok(Self(v)),
None => ParseError::s("Bytecode offset overflow"),
}
}
fn off(self, off: impl Into<i32>) -> Result<Self, ParseError> {
self.off_sub(off.into())
}
pub fn is_start(self) -> bool {
self.0 == 0
}
}
impl Display for Pos {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "L{}", self.0)
}
}
pub struct PosSet([u64; 1 << 10], HashSet<u32>);
impl PosSet {
fn new() -> Self {
Self([0; 1 << 10], HashSet::new())
}
fn add(&mut self, v: Pos) {
if v.0 <= 0xFFFF {
self.0[(v.0 >> 6) as usize] |= 1 << (v.0 % 64);
} else {
self.1.insert(v.0);
}
}
fn contains(&self, v: Pos) -> bool {
if v.0 <= 0xFFFF {
self.0[(v.0 >> 6) as usize] & (1 << (v.0 % 64)) != 0
} else {
self.1.contains(&v.0)
}
}
}
pub trait MaybePosSet {
fn check(&self, v: Pos) -> Result<Pos, ParseError>;
fn validate(&self, v: Pos) -> Result<(), ParseError> {
self.check(v).map(|_| ())
}
fn make(&self, v: u16) -> Result<Pos, ParseError> {
self.check(Pos(v as u32))
}
fn make_off(&self, v: Pos, off: u16) -> Result<Pos, ParseError> {
self.check(v.off(off)?)
}
}
impl MaybePosSet for PosSet {
fn check(&self, v: Pos) -> Result<Pos, ParseError> {
if self.contains(v) {
Ok(v)
} else {
ParseError::s("Invalid bytecode offset")
}
}
}
impl MaybePosSet for Option<&'_ PosSet> {
fn check(&self, v: Pos) -> Result<Pos, ParseError> {
if let Some(set) = self {
set.check(v)
} else {
ParseError::s("Invalid bytecode offset outside of Code attribute")
}
}
}
#[derive(Debug)]
pub struct SwitchTable {
pub default: Pos,
pub low: i32,
pub table: Vec<Pos>,
}
impl SwitchTable {
fn new(r: &mut Reader, pos: Pos) -> Result<Self, ParseError> {
let padding = 3 - (pos.0 as usize % 4);
// JVM requires padding bytes to be 0, so we don't have to preserve them even in roundtrip mode
r.get(padding)?;
let default = pos.off(r.i32()?)?;
let low = r.i32()?;
let high = r.i32()?;
let count = (high - low + 1) as usize;
let mut table = Vec::with_capacity(count);
for _ in 0..count {
table.push(pos.off(r.i32()?)?);
}
Ok(Self { default, low, table })
}
}
#[derive(Debug)]
pub struct SwitchMap {
pub default: Pos,
pub table: Vec<(i32, Pos)>,
}
impl SwitchMap {
fn new(r: &mut Reader, pos: Pos) -> Result<Self, ParseError> {
let padding = 3 - (pos.0 as usize % 4);
// JVM requires padding bytes to be 0, so we don't have to preserve them even in roundtrip mode
r.get(padding)?;
let default = pos.off(r.i32()?)?;
let count = r.i32()? as usize;
let mut table = Vec::with_capacity(count);
for _ in 0..count {
table.push((r.i32()?, pos.off(r.i32()?)?));
}
Ok(Self { default, table })
}
}
#[derive(Clone, Copy, Debug)]
pub enum NewArrayTag {
Boolean,
Char,
Float,
Double,
Byte,
Short,
Int,
Long,
}
impl NewArrayTag {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
use NewArrayTag::*;
Ok(match r.u8()? {
4 => Boolean,
5 => Char,
6 => Float,
7 => Double,
8 => Byte,
9 => Short,
10 => Int,
11 => Long,
_ => return ParseError::s("Invalid newarray tag"),
})
}
}
impl Display for NewArrayTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use NewArrayTag::*;
let s = match self {
Boolean => "boolean",
Char => "char",
Float => "float",
Double => "double",
Byte => "byte",
Short => "short",
Int => "int",
Long => "long",
};
write!(f, "{}", s)
}
}
#[derive(Debug)]
pub enum WideInstr {
Iload(u16),
Lload(u16),
Fload(u16),
Dload(u16),
Aload(u16),
Istore(u16),
Lstore(u16),
Fstore(u16),
Dstore(u16),
Astore(u16),
Iinc(u16, i16),
Ret(u16),
}
impl WideInstr {
fn new(r: &mut Reader) -> Result<Self, ParseError> {
use WideInstr::*;
Ok(match r.u8()? {
0x15 => Iload(r.u16()?),
0x16 => Lload(r.u16()?),
0x17 => Fload(r.u16()?),
0x18 => Dload(r.u16()?),
0x19 => Aload(r.u16()?),
0x36 => Istore(r.u16()?),
0x37 => Lstore(r.u16()?),
0x38 => Fstore(r.u16()?),
0x39 => Dstore(r.u16()?),
0x3A => Astore(r.u16()?),
0x84 => Iinc(r.u16()?, r.i16()?),
0xA9 => Ret(r.u16()?),
_ => return ParseError::s("Invalid wide instr opcode"),
})
}
}
#[derive(Debug)]
pub enum Instr {
Nop,
AconstNull,
IconstM1,
Iconst0,
Iconst1,
Iconst2,
Iconst3,
Iconst4,
Iconst5,
Lconst0,
Lconst1,
Fconst0,
Fconst1,
Fconst2,
Dconst0,
Dconst1,
Bipush(i8),
Sipush(i16),
Ldc(u8),
LdcW(u16),
Ldc2W(u16),
Iload(u8),
Lload(u8),
Fload(u8),
Dload(u8),
Aload(u8),
Iload0,
Iload1,
Iload2,
Iload3,
Lload0,
Lload1,
Lload2,
Lload3,
Fload0,
Fload1,
Fload2,
Fload3,
Dload0,
Dload1,
Dload2,
Dload3,
Aload0,
Aload1,
Aload2,
Aload3,
Iaload,
Laload,
Faload,
Daload,
Aaload,
Baload,
Caload,
Saload,
Istore(u8),
Lstore(u8),
Fstore(u8),
Dstore(u8),
Astore(u8),
Istore0,
Istore1,
Istore2,
Istore3,
Lstore0,
Lstore1,
Lstore2,
Lstore3,
Fstore0,
Fstore1,
Fstore2,
Fstore3,
Dstore0,
Dstore1,
Dstore2,
Dstore3,
Astore0,
Astore1,
Astore2,
Astore3,
Iastore,
Lastore,
Fastore,
Dastore,
Aastore,
Bastore,
Castore,
Sastore,
Pop,
Pop2,
Dup,
DupX1,
DupX2,
Dup2,
Dup2X1,
Dup2X2,
Swap,
Iadd,
Ladd,
Fadd,
Dadd,
Isub,
Lsub,
Fsub,
Dsub,
Imul,
Lmul,
Fmul,
Dmul,
Idiv,
Ldiv,
Fdiv,
Ddiv,
Irem,
Lrem,
Frem,
Drem,
Ineg,
Lneg,
Fneg,
Dneg,
Ishl,
Lshl,
Ishr,
Lshr,
Iushr,
Lushr,
Iand,
Land,
Ior,
Lor,
Ixor,
Lxor,
Iinc(u8, i8),
I2l,
I2f,
I2d,
L2i,
L2f,
L2d,
F2i,
F2l,
F2d,
D2i,
D2l,
D2f,
I2b,
I2c,
I2s,
Lcmp,
Fcmpl,
Fcmpg,
Dcmpl,
Dcmpg,
Ifeq(Pos),
Ifne(Pos),
Iflt(Pos),
Ifge(Pos),
Ifgt(Pos),
Ifle(Pos),
IfIcmpeq(Pos),
IfIcmpne(Pos),
IfIcmplt(Pos),
IfIcmpge(Pos),
IfIcmpgt(Pos),
IfIcmple(Pos),
IfAcmpeq(Pos),
IfAcmpne(Pos),
Goto(Pos),
Jsr(Pos),
Ret(u8),
Tableswitch(SwitchTable),
Lookupswitch(SwitchMap),
Ireturn,
Lreturn,
Freturn,
Dreturn,
Areturn,
Return,
Getstatic(u16),
Putstatic(u16),
Getfield(u16),
Putfield(u16),
Invokevirtual(u16),
Invokespecial(u16),
Invokestatic(u16),
Invokeinterface(u16, u8),
Invokedynamic(u16),
New(u16),
Newarray(NewArrayTag),
Anewarray(u16),
Arraylength,
Athrow,
Checkcast(u16),
Instanceof(u16),
Monitorenter,
Monitorexit,
Wide(WideInstr),
Multianewarray(u16, u8),
Ifnull(Pos),
Ifnonnull(Pos),
GotoW(Pos),
JsrW(Pos),
}
impl Instr {
fn new(r: &mut Reader, pos: Pos) -> Result<Self, ParseError> {
use Instr::*;
Ok(match r.u8()? {
0x00 => Nop,
0x01 => AconstNull,
0x02 => IconstM1,
0x03 => Iconst0,
0x04 => Iconst1,
0x05 => Iconst2,
0x06 => Iconst3,
0x07 => Iconst4,
0x08 => Iconst5,
0x09 => Lconst0,
0x0A => Lconst1,
0x0B => Fconst0,
0x0C => Fconst1,
0x0D => Fconst2,
0x0E => Dconst0,
0x0F => Dconst1,
0x10 => Bipush(r.i8()?),
0x11 => Sipush(r.i16()?),
0x12 => Ldc(r.u8()?),
0x13 => LdcW(r.u16()?),
0x14 => Ldc2W(r.u16()?),
0x15 => Iload(r.u8()?),
0x16 => Lload(r.u8()?),
0x17 => Fload(r.u8()?),
0x18 => Dload(r.u8()?),
0x19 => Aload(r.u8()?),
0x1A => Iload0,
0x1B => Iload1,
0x1C => Iload2,
0x1D => Iload3,
0x1E => Lload0,
0x1F => Lload1,
0x20 => Lload2,
0x21 => Lload3,
0x22 => Fload0,
0x23 => Fload1,
0x24 => Fload2,
0x25 => Fload3,
0x26 => Dload0,
0x27 => Dload1,
0x28 => Dload2,
0x29 => Dload3,
0x2A => Aload0,
0x2B => Aload1,
0x2C => Aload2,
0x2D => Aload3,
0x2E => Iaload,
0x2F => Laload,
0x30 => Faload,
0x31 => Daload,
0x32 => Aaload,
0x33 => Baload,
0x34 => Caload,
0x35 => Saload,
0x36 => Istore(r.u8()?),
0x37 => Lstore(r.u8()?),
0x38 => Fstore(r.u8()?),
0x39 => Dstore(r.u8()?),
0x3A => Astore(r.u8()?),
0x3B => Istore0,
0x3C => Istore1,
0x3D => Istore2,
0x3E => Istore3,
0x3F => Lstore0,
0x40 => Lstore1,
0x41 => Lstore2,
0x42 => Lstore3,
0x43 => Fstore0,
0x44 => Fstore1,
0x45 => Fstore2,
0x46 => Fstore3,
0x47 => Dstore0,
0x48 => Dstore1,
0x49 => Dstore2,
0x4A => Dstore3,
0x4B => Astore0,
0x4C => Astore1,
0x4D => Astore2,
0x4E => Astore3,
0x4F => Iastore,
0x50 => Lastore,
0x51 => Fastore,
0x52 => Dastore,
0x53 => Aastore,
0x54 => Bastore,
0x55 => Castore,
0x56 => Sastore,
0x57 => Pop,
0x58 => Pop2,
0x59 => Dup,
0x5A => DupX1,
0x5B => DupX2,
0x5C => Dup2,
0x5D => Dup2X1,
0x5E => Dup2X2,
0x5F => Swap,
0x60 => Iadd,
0x61 => Ladd,
0x62 => Fadd,
0x63 => Dadd,
0x64 => Isub,
0x65 => Lsub,
0x66 => Fsub,
0x67 => Dsub,
0x68 => Imul,
0x69 => Lmul,
0x6A => Fmul,
0x6B => Dmul,
0x6C => Idiv,
0x6D => Ldiv,
0x6E => Fdiv,
0x6F => Ddiv,
0x70 => Irem,
0x71 => Lrem,
0x72 => Frem,
0x73 => Drem,
0x74 => Ineg,
0x75 => Lneg,
0x76 => Fneg,
0x77 => Dneg,
0x78 => Ishl,
0x79 => Lshl,
0x7A => Ishr,
0x7B => Lshr,
0x7C => Iushr,
0x7D => Lushr,
0x7E => Iand,
0x7F => Land,
0x80 => Ior,
0x81 => Lor,
0x82 => Ixor,
0x83 => Lxor,
0x84 => Iinc(r.u8()?, r.i8()?),
0x85 => I2l,
0x86 => I2f,
0x87 => I2d,
0x88 => L2i,
0x89 => L2f,
0x8A => L2d,
0x8B => F2i,
0x8C => F2l,
0x8D => F2d,
0x8E => D2i,
0x8F => D2l,
0x90 => D2f,
0x91 => I2b,
0x92 => I2c,
0x93 => I2s,
0x94 => Lcmp,
0x95 => Fcmpl,
0x96 => Fcmpg,
0x97 => Dcmpl,
0x98 => Dcmpg,
0x99 => Ifeq(pos.off(r.i16()?)?),
0x9A => Ifne(pos.off(r.i16()?)?),
0x9B => Iflt(pos.off(r.i16()?)?),
0x9C => Ifge(pos.off(r.i16()?)?),
0x9D => Ifgt(pos.off(r.i16()?)?),
0x9E => Ifle(pos.off(r.i16()?)?),
0x9F => IfIcmpeq(pos.off(r.i16()?)?),
0xA0 => IfIcmpne(pos.off(r.i16()?)?),
0xA1 => IfIcmplt(pos.off(r.i16()?)?),
0xA2 => IfIcmpge(pos.off(r.i16()?)?),
0xA3 => IfIcmpgt(pos.off(r.i16()?)?),
0xA4 => IfIcmple(pos.off(r.i16()?)?),
0xA5 => IfAcmpeq(pos.off(r.i16()?)?),
0xA6 => IfAcmpne(pos.off(r.i16()?)?),
0xA7 => Goto(pos.off(r.i16()?)?),
0xA8 => Jsr(pos.off(r.i16()?)?),
0xA9 => Ret(r.u8()?),
0xAA => Tableswitch(SwitchTable::new(r, pos)?),
0xAB => Lookupswitch(SwitchMap::new(r, pos)?),
0xAC => Ireturn,
0xAD => Lreturn,
0xAE => Freturn,
0xAF => Dreturn,
0xB0 => Areturn,
0xB1 => Return,
0xB2 => Getstatic(r.u16()?),
0xB3 => Putstatic(r.u16()?),
0xB4 => Getfield(r.u16()?),
0xB5 => Putfield(r.u16()?),
0xB6 => Invokevirtual(r.u16()?),
0xB7 => Invokespecial(r.u16()?),
0xB8 => Invokestatic(r.u16()?),
0xB9 => (Invokeinterface(r.u16()?, r.u8()?), r.u8()?).0,
0xBA => (Invokedynamic(r.u16()?), r.u16()?).0,
0xBB => New(r.u16()?),
0xBC => Newarray(NewArrayTag::new(r)?),
0xBD => Anewarray(r.u16()?),
0xBE => Arraylength,
0xBF => Athrow,
0xC0 => Checkcast(r.u16()?),
0xC1 => Instanceof(r.u16()?),
0xC2 => Monitorenter,
0xC3 => Monitorexit,
0xC4 => Wide(WideInstr::new(r)?),
0xC5 => Multianewarray(r.u16()?, r.u8()?),
0xC6 => Ifnull(pos.off(r.i16()?)?),
0xC7 => Ifnonnull(pos.off(r.i16()?)?),
0xC8 => GotoW(pos.off(r.i32()?)?),
0xC9 => JsrW(pos.off(r.i32()?)?),
_ => return ParseError::s("Invalid opcode"),
})
}
fn validate(&self, pset: &PosSet) -> Result<(), ParseError> {
use Instr::*;
match self {
Ifeq(p) => pset.validate(*p)?,
Ifne(p) => pset.validate(*p)?,
Iflt(p) => pset.validate(*p)?,
Ifge(p) => pset.validate(*p)?,
Ifgt(p) => pset.validate(*p)?,
Ifle(p) => pset.validate(*p)?,
IfIcmpeq(p) => pset.validate(*p)?,
IfIcmpne(p) => pset.validate(*p)?,
IfIcmplt(p) => pset.validate(*p)?,
IfIcmpge(p) => pset.validate(*p)?,
IfIcmpgt(p) => pset.validate(*p)?,
IfIcmple(p) => pset.validate(*p)?,
IfAcmpeq(p) => pset.validate(*p)?,
IfAcmpne(p) => pset.validate(*p)?,
Goto(p) => pset.validate(*p)?,
Jsr(p) => pset.validate(*p)?,
Tableswitch(table) => {
for p in table.table.iter() {
pset.validate(*p)?;
}
pset.validate(table.default)?
}
Lookupswitch(table) => {
for (_, p) in table.table.iter() {
pset.validate(*p)?;
}
pset.validate(table.default)?
}
Ifnull(p) => pset.validate(*p)?,
Ifnonnull(p) => pset.validate(*p)?,
GotoW(p) => pset.validate(*p)?,
JsrW(p) => pset.validate(*p)?,
_ => {}
};
Ok(())
}
}
#[derive(Debug)]
pub struct Bytecode(pub Vec<(Pos, Instr)>, pub Pos);
impl Bytecode {
fn new(r: &mut Reader) -> Result<(Self, PosSet), ParseError> {
let len = r.0.len();
if len > 0xFFFFFFFF {
return ParseError::s("Bytecode length > 0xFFFFFFFF bytes");
}
let mut instrs = Vec::new();
while r.0.len() > 0 {
let pos = Pos((len - r.0.len()) as u32);
instrs.push((pos, Instr::new(r, pos)?));
}
let endpos = Pos(len as u32);
// Now that all bytecode is parsed, create set of offsets and check them
let mut pset = PosSet::new();
for (p, _) in &instrs {
pset.add(*p);
}
pset.add(endpos);
for (_, instr) in &instrs {
instr.validate(&pset)?;
}
Ok((Self(instrs, endpos), pset))
}
}
#[derive(Debug, Clone, Copy)]
pub struct Except {
pub start: Pos,
pub end: Pos,
pub handler: Pos,
pub ctype: u16,
}
impl Except {
fn new(r: &mut Reader, pset: &PosSet) -> Result<Self, ParseError> {
Ok(Self {
start: pset.make(r.u16()?)?,
end: pset.make(r.u16()?)?,
handler: pset.make(r.u16()?)?,
ctype: r.u16()?,
})
}
}
#[derive(Debug)]
pub struct Code<'a> {
pub is_short: bool,
pub stack: u16,
pub locals: u16,
pub bytecode: Bytecode,
pub exceptions: Vec<Except>,
pub attrs: Vec<Attribute<'a>>,
}
impl<'a> Code<'a> {
fn new(r: &mut Reader<'a>, cp: &ConstPool<'a>, opts: CodeOptions) -> Result<Self, ParseError> {
let is_short = opts.allow_short;
let stack = if is_short { r.u8()? as u16 } else { r.u16()? };
let locals = if is_short { r.u8()? as u16 } else { r.u16()? };
let bclen = if is_short { r.u16()? as usize } else { r.u32()? as usize };
let (bytecode, pset) = Bytecode::new(&mut Reader(r.get(bclen)?))?;
let exceptions = r.parse_list(|r| Except::new(r, &pset))?;
let attrs = Attribute::new_list(r, cp, Some(&pset), opts)?;
if r.0.len() > 0 {
return ParseError::s("Extra data at end of Code attribute");
}
Ok(Self {
is_short,
stack,
locals,
bytecode,
exceptions,
attrs,
})
}
pub(super) fn parse(
mut r: Reader<'a>,
cp: &ConstPool<'a>,
opts: CodeOptions,
) -> Result<(Box<Self>, Option<Box<Self>>), ParseError> {
if opts.allow_short {
let short = Self::new(&mut r.clone(), cp, opts);
let long = Self::new(&mut r, cp, CodeOptions { allow_short: false });
if let Ok(short) = short {
if let Ok(long) = long {
Ok((Box::new(short), Some(Box::new(long))))
} else {
Ok((Box::new(short), None))
}
} else {
Ok((Box::new(long?), None))
}
} else {
let long = Self::new(&mut r, cp, opts);
Ok((Box::new(long?), None))
}
}
}
///////////////////////////////////////////////////////////////////////////////
#[derive(Debug, Clone, Copy)]
pub enum VType {
Top,
Int,
Float,
Long,
Double,
Null,
UninitThis,
Object(u16),
UninitObj(Pos),
}
impl VType {
fn new(r: &mut Reader, pset: &PosSet) -> Result<Self, ParseError> {
use VType::*;
Ok(match r.u8()? {
0 => Top,
1 => Int,
2 => Float,
3 => Double,
4 => Long,
5 => Null,
6 => UninitThis,
7 => Object(r.u16()?),
8 => UninitObj(pset.make(r.u16()?)?),
_ => return ParseError::s("Invalid verification type"),
})
}
}
#[derive(Debug)]
pub enum Frame {
Same,
Stack1(VType),
Stack1Ex(VType),
Chop(u8),
SameEx,
Append(Vec<VType>),
Full(Vec<VType>, Vec<VType>),
}
impl Frame {
fn new(r: &mut Reader, pset: &PosSet) -> Result<(Self, u16), ParseError> {
use Frame::*;
let tag = r.u8()?;
let delta = if tag <= 127 { tag as u16 % 64 } else { r.u16()? };
Ok((
match tag {
0..=63 => Same,
64..=127 => Stack1(VType::new(r, pset)?),
128..=246 => return ParseError::s("Invalid frame tag"),
247 => Stack1Ex(VType::new(r, pset)?),
248..=250 => Chop(251 - tag),
251 => SameEx,
252..=254 => {
let count = (tag - 251) as usize;
let mut vals = Vec::with_capacity(count);
for _ in 0..count {
vals.push(VType::new(r, pset)?);
}
Append(vals)
}
255 => Full(r.parse_list(|r| VType::new(r, pset))?, r.parse_list(|r| VType::new(r, pset))?),
},
delta,
))
}
}
#[derive(Debug)]
pub struct StackMapTable(pub Vec<(Pos, Frame)>);
impl StackMapTable {
pub(super) fn new(r: &mut Reader, pset: Option<&PosSet>) -> Result<Self, ParseError> {
let pset = pset.ok_or(ParseError("StackMapTable outside Code attribute"))?;
let mut pos = Pos(0);
let mut first = true;
Ok(Self(r.parse_list(|r| {
let (frame, delta) = Frame::new(r, pset)?;
pos = pos.off(delta)?;
if first {
first = false;
} else {
pos = pos.off(1)?;
}
Ok((pset.check(pos)?, frame))
})?))
}
}

View File

@ -0,0 +1,95 @@
use super::reader::ParseError;
use super::reader::Reader;
use crate::lib::util::BStr;
#[derive(Debug)]
pub enum Const<'a> {
Null, // 0 unused
Utf8(BStr<'a>),
// 2 unused
Int(u32),
Float(u32),
Long(u64),
Double(u64),
Class(u16),
Str(u16),
Field(u16, u16),
Method(u16, u16),
InterfaceMethod(u16, u16),
NameAndType(u16, u16),
// 13 unused
// 14 unused
MethodHandle(u8, u16),
MethodType(u16),
Dynamic(u16, u16),
InvokeDynamic(u16, u16),
Module(u16),
Package(u16),
}
impl<'a> Const<'a> {
fn read(r: &mut Reader<'a>) -> Result<(Self, bool), ParseError> {
use Const::*;
let tag = r.u8()?;
Ok((
match tag {
1 => {
let count = r.u16()?;
Utf8(BStr(r.get(count as usize)?))
}
3 => Int(r.u32()?),
4 => Float(r.u32()?),
5 => Long(r.u64()?),
6 => Double(r.u64()?),
7 => Class(r.u16()?),
8 => Str(r.u16()?),
9 => Field(r.u16()?, r.u16()?),
10 => Method(r.u16()?, r.u16()?),
11 => InterfaceMethod(r.u16()?, r.u16()?),
12 => NameAndType(r.u16()?, r.u16()?),
15 => MethodHandle(r.u8()?, r.u16()?),
16 => MethodType(r.u16()?),
17 => Dynamic(r.u16()?, r.u16()?),
18 => InvokeDynamic(r.u16()?, r.u16()?),
19 => Module(r.u16()?),
20 => Package(r.u16()?),
_ => return ParseError::s("Unrecognized constant pool tag"),
},
tag == 5 || tag == 6,
))
}
}
#[derive(Debug)]
pub struct ConstPool<'a>(pub Vec<Const<'a>>);
impl<'a> ConstPool<'a> {
pub(super) fn new(r: &mut Reader<'a>) -> Result<Self, ParseError> {
let count = r.u16()? as usize;
let mut cp = Vec::with_capacity(count);
cp.push(Const::Null);
while cp.len() < count {
let (entry, extra) = Const::read(r)?;
// println!("const[{}] = {:?}", cp.len(), entry);
cp.push(entry);
if extra {
cp.push(Const::Null)
}
}
Ok(Self(cp))
}
pub fn utf8(&self, i: u16) -> Option<&'a [u8]> {
self.0
.get(i as usize)
.and_then(|c| if let Const::Utf8(s) = c { Some(s.0) } else { None })
}
pub fn clsutf(&self, i: u16) -> Option<&'a [u8]> {
self.0.get(i as usize).and_then(|c| {
if let Const::Class(utf_ind) = c {
self.utf8(*utf_ind)
} else {
None
}
})
}
}

9
src/lib/classfile/mod.rs Normal file
View File

@ -0,0 +1,9 @@
pub mod attrs;
pub mod code;
pub mod cpool;
pub mod parse;
pub mod reader;
pub use parse::parse;
pub use parse::ParserOptions;
pub use reader::ParseError;

103
src/lib/classfile/parse.rs Normal file
View File

@ -0,0 +1,103 @@
use super::attrs::Attribute;
use super::code::CodeOptions;
use super::cpool::ConstPool;
use super::reader::ParseError;
use super::reader::Reader;
#[derive(Debug, Clone, Copy)]
pub struct ParserOptions {
pub no_short_code_attr: bool,
}
#[derive(Debug)]
pub struct Field<'a> {
pub access: u16,
pub name: u16,
pub desc: u16,
pub attrs: Vec<Attribute<'a>>,
}
impl<'a> Field<'a> {
fn new(r: &mut Reader<'a>, cp: &ConstPool<'a>, code_opts: CodeOptions) -> Result<Self, ParseError> {
let access = r.u16()?;
let name = r.u16()?;
let desc = r.u16()?;
let attrs = Attribute::new_list(r, cp, None, code_opts)?;
Ok(Self {
access,
name,
desc,
attrs,
})
}
}
#[derive(Debug)]
pub struct Class<'a> {
pub version: (u16, u16),
pub cp: ConstPool<'a>,
pub access: u16,
pub this: u16,
pub super_: u16,
pub interfaces: Vec<u16>,
pub fields: Vec<Field<'a>>,
pub methods: Vec<Field<'a>>,
pub attrs: Vec<Attribute<'a>>,
pub has_ambiguous_short_code: bool,
}
impl<'a> Class<'a> {
fn new(r: &mut Reader<'a>, opts: ParserOptions) -> Result<Self, ParseError> {
if r.u32()? != 0xCAFEBABE {
return ParseError::s("Classfile does not start with magic bytes. Are you sure you passed in a classfile?");
}
let minor = r.u16()?;
let major = r.u16()?;
let version = (major, minor);
let code_opts = CodeOptions {
allow_short: version <= (45, 2) && !opts.no_short_code_attr,
};
let cp = ConstPool::new(r)?;
let access = r.u16()?;
let this = r.u16()?;
let super_ = r.u16()?;
let interfaces = r.parse_list(|r| r.u16())?;
let fields = r.parse_list(|r| Field::new(r, &cp, code_opts))?;
let methods = r.parse_list(|r| Field::new(r, &cp, code_opts))?;
let attrs = Attribute::new_list(r, &cp, None, code_opts)?;
let has_ambiguous_short_code = code_opts.allow_short
&& methods.len() > 0
&& methods
.iter()
.all(|m| m.attrs.iter().all(Attribute::has_ambiguous_short_code));
if r.0.len() > 0 {
return ParseError::s("Extra data at end of classfile");
}
Ok(Class {
version,
cp,
access,
this,
super_,
interfaces,
fields,
methods,
attrs,
has_ambiguous_short_code,
})
}
}
pub fn parse(data: &[u8], opts: ParserOptions) -> Result<Class, ParseError> {
let mut r = Reader(data);
Class::new(&mut r, opts)
}

View File

@ -0,0 +1,67 @@
#[derive(Debug)]
pub struct ParseError(pub &'static str);
impl ParseError {
pub fn s<T>(s: &'static str) -> Result<T, ParseError> {
Err(ParseError(s))
}
}
#[derive(Debug, Clone)]
pub(super) struct Reader<'a>(pub(super) &'a [u8]);
impl<'a> Reader<'a> {
pub(super) fn get(&mut self, n: usize) -> Result<&'a [u8], ParseError> {
if n > self.0.len() {
return ParseError::s("end of data");
}
let (first, rest) = self.0.split_at(n);
self.0 = rest;
Ok(first)
}
pub(super) fn u8(&mut self) -> Result<u8, ParseError> {
Ok(self.get(1)?[0])
}
pub(super) fn u16(&mut self) -> Result<u16, ParseError> {
Ok(u16::from_be_bytes(self.get(2)?.try_into().unwrap()))
}
pub(super) fn u32(&mut self) -> Result<u32, ParseError> {
Ok(u32::from_be_bytes(self.get(4)?.try_into().unwrap()))
}
pub(super) fn u64(&mut self) -> Result<u64, ParseError> {
Ok(u64::from_be_bytes(self.get(8)?.try_into().unwrap()))
}
pub(super) fn i8(&mut self) -> Result<i8, ParseError> {
Ok(self.u8()? as i8)
}
pub(super) fn i16(&mut self) -> Result<i16, ParseError> {
Ok(self.u16()? as i16)
}
pub(super) fn i32(&mut self) -> Result<i32, ParseError> {
Ok(self.u32()? as i32)
}
pub(super) fn parse_list<T>(
&mut self,
mut cb: impl FnMut(&mut Self) -> Result<T, ParseError>,
) -> Result<Vec<T>, ParseError> {
let count = self.u16()? as usize;
let mut vals = Vec::with_capacity(count);
for _ in 0..count {
vals.push(cb(self)?);
}
Ok(vals)
}
pub(super) fn parse_list_bytelen<T>(
&mut self,
mut cb: impl FnMut(&mut Self) -> Result<T, ParseError>,
) -> Result<Vec<T>, ParseError> {
let count = self.u8()? as usize;
let mut vals = Vec::with_capacity(count);
for _ in 0..count {
vals.push(cb(self)?);
}
Ok(vals)
}
}

View File

@ -0,0 +1,918 @@
use super::flags::Flags;
use super::refprinter::RefPrinter;
use super::refprinter::SingleTag;
use super::string::escape_byte_string;
use crate::lib::classfile::attrs;
use crate::lib::classfile::attrs::AttrBody;
use crate::lib::classfile::attrs::Attribute;
use crate::lib::classfile::code;
use crate::lib::classfile::parse::Class;
use crate::lib::classfile::parse::Field;
use std::io::Result;
use std::io::Write;
static INDENT_BUF: &str = " ";
const ERROR: &str = "Internal error: Please report this!";
static SHORT_CODE_WARNING: [&str; 6] = [
"Warning! This classfile has been specially crafted so that it will parse",
"differently (and thus be interpreted as having different bytecode) in JVMs",
"for Java versions <= 13 and 14+. By default, Krakatau will show the code as",
"interpreted in Java <= 13. If you are sure that this class actually targets",
"Java 14+, pass the --no-short-code-attr option to see the alternate version",
"of the code instead.",
];
#[derive(Debug, Clone, Copy)]
pub struct DisassemblerOptions {
pub roundtrip: bool,
}
struct Disassembler<'a, W: Write> {
w: W,
rp: &'a RefPrinter<'a>,
roundtrip: bool,
cf_version: (u16, u16),
indentlevel: usize,
sol: &'static str,
}
impl<'a, W: Write> Disassembler<'a, W> {
fn new(w: W, rp: &'a RefPrinter<'a>, roundtrip: bool, cf_version: (u16, u16)) -> Self {
Self {
w,
rp,
roundtrip,
cf_version,
indentlevel: 0,
sol: "",
}
}
fn enter_block(&mut self) {
self.indentlevel += 1;
self.sol = &INDENT_BUF[0..std::cmp::min(self.indentlevel * 4, INDENT_BUF.len())];
}
fn exit_block(&mut self) {
if self.indentlevel == 0 {
panic!("Internal error: Please report this!");
}
self.indentlevel -= 1;
self.sol = &INDENT_BUF[0..std::cmp::min(self.indentlevel * 4, INDENT_BUF.len())];
}
fn field(&mut self, f: &Field<'a>) -> Result<()> {
let rp = self.rp;
let mut constant_value = None;
let mut skip = std::ptr::null();
if !self.roundtrip {
for attr in &f.attrs {
use AttrBody::*;
match &attr.body {
ConstantValue(v) => {
constant_value = Some(*v);
skip = attr; // store pointer so we can skip it later
}
_ => {}
}
}
}
write!(self.w, ".field {} {} {}", Flags::field(f.access), rp.utf(f.name), rp.utf(f.desc))?;
if let Some(cv) = constant_value {
write!(self.w, " = {}", rp.ldc(cv))?;
} else {
write!(self.w, "")?;
}
let used_count = if constant_value.is_some() { 1 } else { 0 };
if f.attrs.len() > used_count {
writeln!(self.w, " .fieldattributes")?;
self.enter_block();
for a in &f.attrs {
if std::ptr::eq(a, skip) {
continue;
}
self.attr(a)?;
}
self.exit_block();
writeln!(self.w, ".end fieldattributes")?;
} else {
writeln!(self.w, "")?;
}
Ok(())
}
fn method(&mut self, m: &Field<'a>) -> Result<()> {
let rp = self.rp;
writeln!(self.w, "\n.method {} {} : {}", Flags::method(m.access), rp.utf(m.name), rp.utf(m.desc))?;
self.enter_block();
for a in &m.attrs {
self.attr(a)?;
}
self.exit_block();
writeln!(self.w, ".end method")?;
Ok(())
}
fn attr(&mut self, a: &Attribute<'a>) -> Result<()> {
let rp = self.rp;
write!(self.w, "{}", self.sol)?;
if a.length != a.actual_length {
write!(self.w, ".attribute {} length {} ", rp.utf(a.name), a.length)?;
} else if self.roundtrip || a.body.is_raw() {
write!(self.w, ".attribute {} ", rp.utf(a.name))?;
}
use AttrBody::*;
match &a.body {
AnnotationDefault(ev) => {
write!(self.w, ".annotationdefault ")?;
self.element_value(ev)?;
}
BootstrapMethods(..) => write!(self.w, ".bootstrapmethods")?,
Code((code, _code2)) => self.code(code)?,
ConstantValue(r) => write!(self.w, ".constantvalue {}", rp.ldc(*r))?,
Deprecated => write!(self.w, ".deprecated")?,
EnclosingMethod(r, r2) => write!(self.w, ".enclosing method {} {}", rp.cls(*r), rp.nat(*r2))?,
Exceptions(vals) => {
write!(self.w, ".exceptions")?;
for ex in vals.iter().copied() {
write!(self.w, " {}", rp.cls(ex))?;
}
}
InnerClasses(lines) => {
writeln!(self.w, ".innerclasses")?;
self.enter_block();
for val in lines.iter().copied() {
writeln!(
self.w,
"{}{} {} {} {}",
self.sol,
rp.cls(val.0),
rp.cls(val.1),
rp.utf(val.2),
Flags::class(val.3)
)?;
}
self.exit_block();
write!(self.w, "{}.end innerclasses", self.sol)?;
}
LineNumberTable(lines) => {
writeln!(self.w, ".linenumbertable")?;
self.enter_block();
for val in lines.iter().copied() {
writeln!(self.w, "{}{} {}", self.sol, val.0, val.1)?;
}
self.exit_block();
write!(self.w, "{}.end linenumbertable", self.sol)?;
}
LocalVariableTable(lines) => {
writeln!(self.w, ".localvariabletable")?;
self.local_var_table(lines)?;
write!(self.w, "{}.end localvariabletable", self.sol)?;
}
LocalVariableTypeTable(lines) => {
writeln!(self.w, ".localvariabletypetable")?;
self.local_var_table(lines)?;
write!(self.w, "{}.end localvariabletypetable", self.sol)?;
}
MethodParameters(lines) => {
writeln!(self.w, ".methodparameters")?;
self.enter_block();
for val in lines.iter().copied() {
writeln!(self.w, "{}{} {}", self.sol, rp.utf(val.0), Flags::mod_other(val.1))?;
}
self.exit_block();
write!(self.w, "{}.end methodparameters", self.sol)?;
}
Module(modattr) => {
self.module_attr(&modattr)?;
}
ModuleMainClass(r) => write!(self.w, ".modulemainclass {}", rp.cls(*r))?,
ModulePackages(vals) => {
write!(self.w, ".modulepackages")?;
for ex in vals.iter().copied() {
write!(self.w, " {}", rp.single(ex, SingleTag::Package))?;
}
}
NestHost(r) => write!(self.w, ".nesthost {}", rp.cls(*r))?,
NestMembers(vals) => {
write!(self.w, ".nestmembers")?;
for ex in vals.iter().copied() {
write!(self.w, " {}", rp.cls(ex))?;
}
}
PermittedSubclasses(vals) => {
write!(self.w, ".permittedsubclasses")?;
for ex in vals.iter().copied() {
write!(self.w, " {}", rp.cls(ex))?;
}
}
Record(lines) => {
writeln!(self.w, ".record")?;
self.enter_block();
for val in lines {
self.record_component(val)?;
}
self.exit_block();
write!(self.w, "{}.end record", self.sol)?;
}
RuntimeInvisibleAnnotations(lines) => self.runtime_annotations("invisible", lines)?,
RuntimeInvisibleParameterAnnotations(lines) => self.runtime_param_annotations("invisible", lines)?,
RuntimeInvisibleTypeAnnotations(lines) => self.runtime_type_annotations("invisible", lines)?,
RuntimeVisibleAnnotations(lines) => self.runtime_annotations("visible", lines)?,
RuntimeVisibleParameterAnnotations(lines) => self.runtime_param_annotations("visible", lines)?,
RuntimeVisibleTypeAnnotations(lines) => self.runtime_type_annotations("visible", lines)?,
Signature(r) => write!(self.w, ".signature {}", rp.utf(*r))?,
SourceDebugExtention(s) => write!(self.w, ".sourcedebugextension b'{}'", escape_byte_string(s))?,
SourceFile(r) => write!(self.w, ".sourcefile {}", rp.utf(*r))?,
StackMapTable(_) => write!(self.w, ".stackmaptable")?,
Synthetic => write!(self.w, ".synthetic")?,
Raw(s) => write!(self.w, "b'{}'", escape_byte_string(s))?,
};
writeln!(self.w, "")?;
Ok(())
}
fn local_var_table(&mut self, lines: &[attrs::LocalVarLine]) -> Result<()> {
let rp = self.rp;
self.enter_block();
for lvl in lines.iter().copied() {
writeln!(
self.w,
"{}{} is {} {} from {} to {}",
self.sol,
lvl.ind,
rp.utf(lvl.name),
rp.utf(lvl.desc),
lvl.start,
lvl.end,
)?;
}
self.exit_block();
Ok(())
}
fn vtype(&mut self, vt: code::VType) -> Result<()> {
let rp = self.rp;
use code::VType::*;
match vt {
Top => write!(self.w, " Top"),
Int => write!(self.w, " Integer"),
Float => write!(self.w, " Float"),
Long => write!(self.w, " Long"),
Double => write!(self.w, " Double"),
Null => write!(self.w, " Null"),
UninitThis => write!(self.w, " UninitializedThis"),
Object(r) => write!(self.w, " Object {}", rp.cls(r)),
UninitObj(r) => write!(self.w, " Uninitialized {}", r),
}
}
fn begin_bytecode_line<'i>(
&mut self,
pos: code::Pos,
excepts: &mut std::iter::Peekable<impl Iterator<Item = code::Except>>,
frames: &mut std::iter::Peekable<impl Iterator<Item = &'i (code::Pos, code::Frame)>>,
) -> Result<()> {
let rp = self.rp;
while excepts.peek().map(|e| e.start <= pos).unwrap_or(false) {
let e = excepts.next().expect(ERROR);
writeln!(
self.w,
"{}.catch {} from {} to {} using {}",
self.sol,
rp.cls(e.ctype),
e.start,
e.end,
e.handler,
)?;
}
if frames.peek().map(|e| e.0 <= pos).unwrap_or(false) {
let f = frames.next().expect(ERROR);
// Add blank line before stackmap frames for readability, except at start of code
if !f.0.is_start() {
writeln!(self.w, "")?;
}
write!(self.w, "{}.stack ", self.sol)?;
use code::Frame::*;
match &f.1 {
Same => writeln!(self.w, "same")?,
Stack1(vt) => {
write!(self.w, "stack_1")?;
self.vtype(*vt)?;
writeln!(self.w, "")?
}
Stack1Ex(vt) => {
write!(self.w, "stack_1_extended")?;
self.vtype(*vt)?;
writeln!(self.w, "")?
}
Chop(cnt) => writeln!(self.w, "chop {}", *cnt)?,
SameEx => writeln!(self.w, "same_extended")?,
Append(vts) => {
write!(self.w, "append")?;
for vt in vts.iter().copied() {
self.vtype(vt)?;
}
writeln!(self.w, "")?;
}
Full(locals, stack) => {
writeln!(self.w, "full")?;
self.enter_block();
write!(self.w, "{}locals", self.sol)?;
for vt in locals.iter().copied() {
self.vtype(vt)?;
}
writeln!(self.w, "")?;
write!(self.w, "{}stack", self.sol)?;
for vt in stack.iter().copied() {
self.vtype(vt)?;
}
writeln!(self.w, "")?;
self.exit_block();
writeln!(self.w, "{}.end stack", self.sol)?;
}
}
}
let lhs = format!("{}:", pos);
let indent = self.sol.len();
write!(self.w, "{:indent$}", lhs)
}
fn instr(&mut self, ins: &code::Instr) -> Result<()> {
let rp = self.rp;
use code::Instr::*;
match ins {
Nop => writeln!(self.w, "nop")?,
AconstNull => writeln!(self.w, "aconst_null")?,
IconstM1 => writeln!(self.w, "iconst_m1")?,
Iconst0 => writeln!(self.w, "iconst_0")?,
Iconst1 => writeln!(self.w, "iconst_1")?,
Iconst2 => writeln!(self.w, "iconst_2")?,
Iconst3 => writeln!(self.w, "iconst_3")?,
Iconst4 => writeln!(self.w, "iconst_4")?,
Iconst5 => writeln!(self.w, "iconst_5")?,
Lconst0 => writeln!(self.w, "lconst_0")?,
Lconst1 => writeln!(self.w, "lconst_1")?,
Fconst0 => writeln!(self.w, "fconst_0")?,
Fconst1 => writeln!(self.w, "fconst_1")?,
Fconst2 => writeln!(self.w, "fconst_2")?,
Dconst0 => writeln!(self.w, "dconst_0")?,
Dconst1 => writeln!(self.w, "dconst_1")?,
Bipush(v0) => writeln!(self.w, "bipush {}", *v0)?,
Sipush(v0) => writeln!(self.w, "sipush {}", *v0)?,
Ldc(v0) => writeln!(self.w, "ldc {}", rp.ldc(*v0 as u16))?,
LdcW(v0) => writeln!(self.w, "ldc_w {}", rp.ldc(*v0))?,
Ldc2W(v0) => writeln!(self.w, "ldc2_w {}", rp.ldc(*v0))?,
Iload(v0) => writeln!(self.w, "iload {}", *v0)?,
Lload(v0) => writeln!(self.w, "lload {}", *v0)?,
Fload(v0) => writeln!(self.w, "fload {}", *v0)?,
Dload(v0) => writeln!(self.w, "dload {}", *v0)?,
Aload(v0) => writeln!(self.w, "aload {}", *v0)?,
Iload0 => writeln!(self.w, "iload_0")?,
Iload1 => writeln!(self.w, "iload_1")?,
Iload2 => writeln!(self.w, "iload_2")?,
Iload3 => writeln!(self.w, "iload_3")?,
Lload0 => writeln!(self.w, "lload_0")?,
Lload1 => writeln!(self.w, "lload_1")?,
Lload2 => writeln!(self.w, "lload_2")?,
Lload3 => writeln!(self.w, "lload_3")?,
Fload0 => writeln!(self.w, "fload_0")?,
Fload1 => writeln!(self.w, "fload_1")?,
Fload2 => writeln!(self.w, "fload_2")?,
Fload3 => writeln!(self.w, "fload_3")?,
Dload0 => writeln!(self.w, "dload_0")?,
Dload1 => writeln!(self.w, "dload_1")?,
Dload2 => writeln!(self.w, "dload_2")?,
Dload3 => writeln!(self.w, "dload_3")?,
Aload0 => writeln!(self.w, "aload_0")?,
Aload1 => writeln!(self.w, "aload_1")?,
Aload2 => writeln!(self.w, "aload_2")?,
Aload3 => writeln!(self.w, "aload_3")?,
Iaload => writeln!(self.w, "iaload")?,
Laload => writeln!(self.w, "laload")?,
Faload => writeln!(self.w, "faload")?,
Daload => writeln!(self.w, "daload")?,
Aaload => writeln!(self.w, "aaload")?,
Baload => writeln!(self.w, "baload")?,
Caload => writeln!(self.w, "caload")?,
Saload => writeln!(self.w, "saload")?,
Istore(v0) => writeln!(self.w, "istore {}", *v0)?,
Lstore(v0) => writeln!(self.w, "lstore {}", *v0)?,
Fstore(v0) => writeln!(self.w, "fstore {}", *v0)?,
Dstore(v0) => writeln!(self.w, "dstore {}", *v0)?,
Astore(v0) => writeln!(self.w, "astore {}", *v0)?,
Istore0 => writeln!(self.w, "istore_0")?,
Istore1 => writeln!(self.w, "istore_1")?,
Istore2 => writeln!(self.w, "istore_2")?,
Istore3 => writeln!(self.w, "istore_3")?,
Lstore0 => writeln!(self.w, "lstore_0")?,
Lstore1 => writeln!(self.w, "lstore_1")?,
Lstore2 => writeln!(self.w, "lstore_2")?,
Lstore3 => writeln!(self.w, "lstore_3")?,
Fstore0 => writeln!(self.w, "fstore_0")?,
Fstore1 => writeln!(self.w, "fstore_1")?,
Fstore2 => writeln!(self.w, "fstore_2")?,
Fstore3 => writeln!(self.w, "fstore_3")?,
Dstore0 => writeln!(self.w, "dstore_0")?,
Dstore1 => writeln!(self.w, "dstore_1")?,
Dstore2 => writeln!(self.w, "dstore_2")?,
Dstore3 => writeln!(self.w, "dstore_3")?,
Astore0 => writeln!(self.w, "astore_0")?,
Astore1 => writeln!(self.w, "astore_1")?,
Astore2 => writeln!(self.w, "astore_2")?,
Astore3 => writeln!(self.w, "astore_3")?,
Iastore => writeln!(self.w, "iastore")?,
Lastore => writeln!(self.w, "lastore")?,
Fastore => writeln!(self.w, "fastore")?,
Dastore => writeln!(self.w, "dastore")?,
Aastore => writeln!(self.w, "aastore")?,
Bastore => writeln!(self.w, "bastore")?,
Castore => writeln!(self.w, "castore")?,
Sastore => writeln!(self.w, "sastore")?,
Pop => writeln!(self.w, "pop")?,
Pop2 => writeln!(self.w, "pop2")?,
Dup => writeln!(self.w, "dup")?,
DupX1 => writeln!(self.w, "dup_x1")?,
DupX2 => writeln!(self.w, "dup_x2")?,
Dup2 => writeln!(self.w, "dup2")?,
Dup2X1 => writeln!(self.w, "dup2_x1")?,
Dup2X2 => writeln!(self.w, "dup2_x2")?,
Swap => writeln!(self.w, "swap")?,
Iadd => writeln!(self.w, "iadd")?,
Ladd => writeln!(self.w, "ladd")?,
Fadd => writeln!(self.w, "fadd")?,
Dadd => writeln!(self.w, "dadd")?,
Isub => writeln!(self.w, "isub")?,
Lsub => writeln!(self.w, "lsub")?,
Fsub => writeln!(self.w, "fsub")?,
Dsub => writeln!(self.w, "dsub")?,
Imul => writeln!(self.w, "imul")?,
Lmul => writeln!(self.w, "lmul")?,
Fmul => writeln!(self.w, "fmul")?,
Dmul => writeln!(self.w, "dmul")?,
Idiv => writeln!(self.w, "idiv")?,
Ldiv => writeln!(self.w, "ldiv")?,
Fdiv => writeln!(self.w, "fdiv")?,
Ddiv => writeln!(self.w, "ddiv")?,
Irem => writeln!(self.w, "irem")?,
Lrem => writeln!(self.w, "lrem")?,
Frem => writeln!(self.w, "frem")?,
Drem => writeln!(self.w, "drem")?,
Ineg => writeln!(self.w, "ineg")?,
Lneg => writeln!(self.w, "lneg")?,
Fneg => writeln!(self.w, "fneg")?,
Dneg => writeln!(self.w, "dneg")?,
Ishl => writeln!(self.w, "ishl")?,
Lshl => writeln!(self.w, "lshl")?,
Ishr => writeln!(self.w, "ishr")?,
Lshr => writeln!(self.w, "lshr")?,
Iushr => writeln!(self.w, "iushr")?,
Lushr => writeln!(self.w, "lushr")?,
Iand => writeln!(self.w, "iand")?,
Land => writeln!(self.w, "land")?,
Ior => writeln!(self.w, "ior")?,
Lor => writeln!(self.w, "lor")?,
Ixor => writeln!(self.w, "ixor")?,
Lxor => writeln!(self.w, "lxor")?,
Iinc(v0, v1) => writeln!(self.w, "iinc {} {}", *v0, *v1)?,
I2l => writeln!(self.w, "i2l")?,
I2f => writeln!(self.w, "i2f")?,
I2d => writeln!(self.w, "i2d")?,
L2i => writeln!(self.w, "l2i")?,
L2f => writeln!(self.w, "l2f")?,
L2d => writeln!(self.w, "l2d")?,
F2i => writeln!(self.w, "f2i")?,
F2l => writeln!(self.w, "f2l")?,
F2d => writeln!(self.w, "f2d")?,
D2i => writeln!(self.w, "d2i")?,
D2l => writeln!(self.w, "d2l")?,
D2f => writeln!(self.w, "d2f")?,
I2b => writeln!(self.w, "i2b")?,
I2c => writeln!(self.w, "i2c")?,
I2s => writeln!(self.w, "i2s")?,
Lcmp => writeln!(self.w, "lcmp")?,
Fcmpl => writeln!(self.w, "fcmpl")?,
Fcmpg => writeln!(self.w, "fcmpg")?,
Dcmpl => writeln!(self.w, "dcmpl")?,
Dcmpg => writeln!(self.w, "dcmpg")?,
Ifeq(v0) => writeln!(self.w, "ifeq {}", *v0)?,
Ifne(v0) => writeln!(self.w, "ifne {}", *v0)?,
Iflt(v0) => writeln!(self.w, "iflt {}", *v0)?,
Ifge(v0) => writeln!(self.w, "ifge {}", *v0)?,
Ifgt(v0) => writeln!(self.w, "ifgt {}", *v0)?,
Ifle(v0) => writeln!(self.w, "ifle {}", *v0)?,
IfIcmpeq(v0) => writeln!(self.w, "if_icmpeq {}", *v0)?,
IfIcmpne(v0) => writeln!(self.w, "if_icmpne {}", *v0)?,
IfIcmplt(v0) => writeln!(self.w, "if_icmplt {}", *v0)?,
IfIcmpge(v0) => writeln!(self.w, "if_icmpge {}", *v0)?,
IfIcmpgt(v0) => writeln!(self.w, "if_icmpgt {}", *v0)?,
IfIcmple(v0) => writeln!(self.w, "if_icmple {}", *v0)?,
IfAcmpeq(v0) => writeln!(self.w, "if_acmpeq {}", *v0)?,
IfAcmpne(v0) => writeln!(self.w, "if_acmpne {}", *v0)?,
Goto(v0) => writeln!(self.w, "goto {}", *v0)?,
Jsr(v0) => writeln!(self.w, "jsr {}", *v0)?,
Ret(v0) => writeln!(self.w, "ret {}", *v0)?,
Tableswitch(jumps) => {
writeln!(self.w, "tableswitch {}", jumps.low)?;
self.enter_block();
for target in jumps.table.iter().copied() {
writeln!(self.w, "{}{}", self.sol, target)?;
}
writeln!(self.w, "{}default : {}", self.sol, jumps.default)?;
self.exit_block();
}
Lookupswitch(jumps) => {
writeln!(self.w, "lookupswitch")?;
self.enter_block();
for (val, target) in jumps.table.iter().copied() {
writeln!(self.w, "{}{} : {}", self.sol, val, target)?;
}
writeln!(self.w, "{}default : {}", self.sol, jumps.default)?;
self.exit_block();
}
Ireturn => writeln!(self.w, "ireturn")?,
Lreturn => writeln!(self.w, "lreturn")?,
Freturn => writeln!(self.w, "freturn")?,
Dreturn => writeln!(self.w, "dreturn")?,
Areturn => writeln!(self.w, "areturn")?,
Return => writeln!(self.w, "return")?,
Getstatic(v0) => writeln!(self.w, "getstatic {}", rp.tagged_fmim(*v0))?,
Putstatic(v0) => writeln!(self.w, "putstatic {}", rp.tagged_fmim(*v0))?,
Getfield(v0) => writeln!(self.w, "getfield {}", rp.tagged_fmim(*v0))?,
Putfield(v0) => writeln!(self.w, "putfield {}", rp.tagged_fmim(*v0))?,
Invokevirtual(v0) => writeln!(self.w, "invokevirtual {}", rp.tagged_fmim(*v0))?,
Invokespecial(v0) => writeln!(self.w, "invokespecial {}", rp.tagged_fmim(*v0))?,
Invokestatic(v0) => writeln!(self.w, "invokestatic {}", rp.tagged_fmim(*v0))?,
Invokeinterface(v0, v1) => writeln!(self.w, "invokeinterface {} {}", rp.tagged_fmim(*v0), *v1)?,
Invokedynamic(v0) => writeln!(self.w, "invokedynamic {}", rp.cpref(*v0))?,
New(v0) => writeln!(self.w, "new {}", rp.cls(*v0))?,
Newarray(c) => writeln!(self.w, "newarray {}", *c)?,
Anewarray(v0) => writeln!(self.w, "anewarray {}", rp.cls(*v0))?,
Arraylength => writeln!(self.w, "arraylength")?,
Athrow => writeln!(self.w, "athrow")?,
Checkcast(v0) => writeln!(self.w, "checkcast {}", rp.cls(*v0))?,
Instanceof(v0) => writeln!(self.w, "instanceof {}", rp.cls(*v0))?,
Monitorenter => writeln!(self.w, "monitorenter")?,
Monitorexit => writeln!(self.w, "monitorexit")?,
Wide(w) => {
use code::WideInstr::*;
match w {
Iload(v0) => writeln!(self.w, "wide iload {}", *v0)?,
Lload(v0) => writeln!(self.w, "wide lload {}", *v0)?,
Fload(v0) => writeln!(self.w, "wide fload {}", *v0)?,
Dload(v0) => writeln!(self.w, "wide dload {}", *v0)?,
Aload(v0) => writeln!(self.w, "wide aload {}", *v0)?,
Istore(v0) => writeln!(self.w, "wide istore {}", *v0)?,
Lstore(v0) => writeln!(self.w, "wide lstore {}", *v0)?,
Fstore(v0) => writeln!(self.w, "wide fstore {}", *v0)?,
Dstore(v0) => writeln!(self.w, "wide dstore {}", *v0)?,
Astore(v0) => writeln!(self.w, "wide astore {}", *v0)?,
Iinc(v0, v1) => writeln!(self.w, "wide iinc {} {}", *v0, *v1)?,
Ret(v0) => writeln!(self.w, "wide ret {}", *v0)?,
}
}
Multianewarray(v0, v1) => writeln!(self.w, "multianewarray {} {}", rp.cls(*v0), *v1)?,
Ifnull(v0) => writeln!(self.w, "ifnull {}", *v0)?,
Ifnonnull(v0) => writeln!(self.w, "ifnonnull {}", *v0)?,
GotoW(v0) => writeln!(self.w, "goto_w {}", *v0)?,
JsrW(v0) => writeln!(self.w, "jsr_w {}", *v0)?,
}
Ok(())
}
fn code(&mut self, c: &code::Code<'a>) -> Result<()> {
let mut stack_map_table = None;
let mut skip = std::ptr::null();
for attr in &c.attrs {
use AttrBody::*;
match &attr.body {
StackMapTable(v) => {
stack_map_table = Some(v);
if !self.roundtrip {
skip = attr; // store pointer so we can skip it later
}
}
_ => {}
}
}
let stack_map_table = stack_map_table.map(|smt| &smt.0[..]).unwrap_or(&[]);
if self.cf_version <= (45, 2) && !c.is_short {
writeln!(self.w, ".code long stack {} locals {}", c.stack, c.locals)?;
} else {
writeln!(self.w, ".code stack {} locals {}", c.stack, c.locals)?;
}
self.enter_block();
let mut excepts = c.exceptions.iter().copied().peekable();
let mut frames = stack_map_table.iter().peekable();
for &(addr, ref instr) in c.bytecode.0.iter() {
self.begin_bytecode_line(addr, &mut excepts, &mut frames)?;
self.instr(instr)?;
}
self.begin_bytecode_line(c.bytecode.1, &mut excepts, &mut frames)?;
writeln!(self.w, "")?;
for a in &c.attrs {
if a as *const _ == skip {
continue;
}
self.attr(a)?;
}
self.exit_block();
write!(self.w, "{}.end code", self.sol)?;
Ok(())
}
fn runtime_annotations(&mut self, kind: &'static str, lines: &[attrs::Annotation]) -> Result<()> {
writeln!(self.w, ".runtime {} annotations", kind)?;
self.enter_block();
for line in lines {
write!(self.w, "{}.annotation ", self.sol)?;
self.annotation_contents(line)?;
writeln!(self.w, "{}.end annotation", self.sol)?;
}
self.exit_block();
write!(self.w, "{}.end runtime", self.sol)?;
Ok(())
}
fn runtime_param_annotations(&mut self, kind: &'static str, lines: &[attrs::ParameterAnnotation]) -> Result<()> {
writeln!(self.w, ".runtime {} paramannotations", kind)?;
self.enter_block();
for line in lines {
writeln!(self.w, "{}.paramannotation", self.sol)?;
self.enter_block();
for anno in &line.0 {
write!(self.w, "{}.annotation ", self.sol)?;
self.annotation_contents(anno)?;
writeln!(self.w, "{}.end annotation", self.sol)?;
}
self.exit_block();
writeln!(self.w, "{}.end paramannotation", self.sol)?;
}
self.exit_block();
write!(self.w, "{}.end runtime", self.sol)?;
Ok(())
}
fn runtime_type_annotations(&mut self, kind: &'static str, lines: &[attrs::TypeAnnotation]) -> Result<()> {
writeln!(self.w, ".runtime {} typeannotations", kind)?;
self.enter_block();
for line in lines {
write!(self.w, "{}.typeannotation {} ", self.sol, line.info.0)?;
self.enter_block();
use attrs::TargetInfoData::*;
match &line.info.1 {
TypeParam(v) => writeln!(self.w, "typeparam {}", *v)?,
Super(v) => writeln!(self.w, "super {}", *v)?,
TypeParamBound(v, v2) => writeln!(self.w, "typeparambound {} {}", *v, *v2)?,
Empty => writeln!(self.w, "empty")?,
FormalParam(v) => writeln!(self.w, "methodparam {}", *v)?,
Throws(v) => writeln!(self.w, "throws {}", *v)?,
LocalVar(vals) => {
writeln!(self.w, "localvar")?;
// writeln!(self.w, "{}.localvar", self.sol)?;
self.enter_block();
for v in vals.iter().copied() {
if let Some((start, end)) = v.range {
writeln!(self.w, "{}from {} to {} {}", self.sol, start, end, v.index)?;
} else {
// WTF, Java?
writeln!(self.w, "{}nowhere {}", self.sol, v.index)?;
}
}
self.exit_block();
writeln!(self.w, "{}.end localvar", self.sol)?;
}
Catch(v) => writeln!(self.w, "catch {}", *v)?,
Offset(v) => writeln!(self.w, "offset {}", *v)?,
TypeArgument(v, v2) => writeln!(self.w, "typearg {} {}", *v, *v2)?,
}
writeln!(self.w, "{}.typepath", self.sol)?;
self.enter_block();
for (v1, v2) in line.path.iter().copied() {
writeln!(self.w, "{}{} {}", self.sol, v1, v2)?;
}
self.exit_block();
writeln!(self.w, "{}.end typepath", self.sol)?;
write!(self.w, "{}", self.sol)?;
self.annotation_contents(&line.anno)?;
self.exit_block();
writeln!(self.w, "{}.end typeannotation", self.sol)?;
}
self.exit_block();
write!(self.w, "{}.end runtime", self.sol)?;
Ok(())
}
fn record_component(&mut self, r: &attrs::RecordComponent<'a>) -> Result<()> {
let rp = self.rp;
write!(self.w, "{}{} {}", self.sol, rp.utf(r.name), rp.utf(r.desc))?;
if r.attrs.len() > 0 {
writeln!(self.w, "{} .attributes", self.sol)?;
self.enter_block();
for a in &r.attrs {
self.attr(a)?;
}
self.exit_block();
writeln!(self.w, "{}.end attributes", self.sol)?;
} else {
writeln!(self.w, "")?;
}
Ok(())
}
fn module_attr(&mut self, m: &attrs::ModuleAttr) -> Result<()> {
let rp = self.rp;
writeln!(
self.w,
".module {} {} version {}",
rp.single(m.module, SingleTag::Module),
Flags::mod_other(m.flags),
rp.utf(m.version)
)?;
self.enter_block();
for req in &m.requires {
writeln!(
self.w,
"{}.requires {} {} version {}",
self.sol,
rp.single(req.module, SingleTag::Module),
Flags::mod_requires(req.flags),
rp.utf(req.version)
)?;
}
for p in &m.exports {
write!(
self.w,
"{}.exports {} {} to",
self.sol,
rp.single(p.package, SingleTag::Package),
Flags::mod_other(p.flags)
)?;
for submod in p.modules.iter().copied() {
write!(self.w, " {}", rp.single(submod, SingleTag::Module))?;
}
writeln!(self.w, "")?;
}
for p in &m.opens {
write!(
self.w,
"{}.opens {} {} to",
self.sol,
rp.single(p.package, SingleTag::Package),
Flags::mod_other(p.flags)
)?;
for submod in p.modules.iter().copied() {
write!(self.w, " {}", rp.single(submod, SingleTag::Module))?;
}
writeln!(self.w, "")?;
}
for u in m.uses.iter().copied() {
writeln!(self.w, "{}.uses {}", self.sol, rp.cls(u))?;
}
for p in &m.provides {
write!(self.w, "{}.provides {} with", self.sol, rp.cls(p.cls))?;
for c in p.provides_with.iter().copied() {
write!(self.w, " {}", rp.cls(c))?;
}
writeln!(self.w, "")?;
}
self.exit_block();
writeln!(self.w, "{}.end module", self.sol)?;
Ok(())
}
fn element_value(&mut self, ev: &attrs::ElementValue) -> Result<()> {
let rp = self.rp;
use attrs::ElementValue::*;
match ev {
Anno(anno) => {
write!(self.w, "annotation ")?;
self.annotation_contents(anno)?;
writeln!(self.w, "{}.end annotation", self.sol)?;
}
Array(vals) => {
writeln!(self.w, "array")?;
self.enter_block();
for val in vals {
write!(self.w, "{}", self.sol)?;
self.element_value(val)?;
writeln!(self.w, "")?;
}
self.exit_block();
writeln!(self.w, "{}.end array", self.sol)?;
}
Enum(r1, r2) => write!(self.w, "enum {} {}", rp.utf(*r1), rp.utf(*r2))?,
Class(r) => write!(self.w, "class {}", rp.utf(*r))?,
Str(r) => write!(self.w, "string {}", rp.utf(*r))?,
Byte(r) => write!(self.w, "byte {}", rp.ldc(*r))?,
Boolean(r) => write!(self.w, "boolean {}", rp.ldc(*r))?,
Char(r) => write!(self.w, "char {}", rp.ldc(*r))?,
Short(r) => write!(self.w, "short {}", rp.ldc(*r))?,
Int(r) => write!(self.w, "int {}", rp.ldc(*r))?,
Float(r) => write!(self.w, "float {}", rp.ldc(*r))?,
Long(r) => write!(self.w, "long {}", rp.ldc(*r))?,
Double(r) => write!(self.w, "double {}", rp.ldc(*r))?,
}
Ok(())
}
fn annotation_contents(&mut self, anno: &attrs::Annotation) -> Result<()> {
let rp = self.rp;
writeln!(self.w, "{}", rp.utf(anno.0))?;
self.enter_block();
for val in &anno.1 {
write!(self.w, "{}{} = ", self.sol, rp.utf(val.0))?;
self.element_value(&val.1)?;
writeln!(self.w, "")?;
}
self.exit_block();
Ok(())
}
}
pub fn disassemble(mut w: impl Write, c: &Class, opts: DisassemblerOptions) -> Result<()> {
let mut bstable = None;
let mut inner_classes = None;
for attr in &c.attrs {
use AttrBody::*;
match &attr.body {
BootstrapMethods(v) => bstable = Some(v.as_ref()),
InnerClasses(v) => inner_classes = Some(v.as_ref()),
_ => {}
}
}
let rp = RefPrinter::new(opts.roundtrip, &c.cp, bstable, inner_classes);
// d.v(".version")?.v(c.version.0)?.v(c.version.1)?.eol()?;
if c.has_ambiguous_short_code {
for line in SHORT_CODE_WARNING {
writeln!(w, "; {}", line)?;
}
}
writeln!(w, ".version {} {}", c.version.0, c.version.1)?;
writeln!(w, ".class {} {}", Flags::class(c.access), rp.cls(c.this))?;
writeln!(w, ".super {}", rp.cls(c.super_))?;
for ind in c.interfaces.iter().copied() {
writeln!(w, ".implements {}", rp.cls(ind))?;
}
let mut d = Disassembler::new(w, &rp, opts.roundtrip, c.version);
for field in c.fields.iter() {
d.field(field)?;
}
for method in c.methods.iter() {
d.method(method)?;
}
for attr in c.attrs.iter() {
d.attr(attr)?;
}
let mut w = d.w;
rp.print_const_defs(&mut w)?;
writeln!(w, ".end class")
}

View File

@ -0,0 +1,152 @@
use std::fmt;
static CLASS: [&str; 16] = [
"public",
"private",
"protected",
"static",
"final",
"super",
"volatile",
"transient",
"native",
"interface",
"abstract",
"strict",
"synthetic",
"annotation",
"enum",
"module",
];
static FIELD: [&str; 16] = [
"public",
"private",
"protected",
"static",
"final",
"super",
"volatile",
"transient",
"native",
"interface",
"abstract",
"strict",
"synthetic",
"annotation",
"enum",
"module",
];
static METHOD: [&str; 16] = [
"public",
"private",
"protected",
"static",
"final",
"synchronized",
"bridge",
"varargs",
"native",
"interface",
"abstract",
"strict",
"synthetic",
"annotation",
"enum",
"module",
];
static MOD_REQUIRES: [&str; 16] = [
"public",
"private",
"protected",
"static",
"final",
"transitive",
"static_phase",
"transient",
"native",
"interface",
"abstract",
"strict",
"synthetic",
"annotation",
"enum",
"mandated",
];
static MOD_OTHER: [&str; 16] = [
"public",
"private",
"protected",
"static",
"final",
"open",
"volatile",
"transient",
"native",
"interface",
"abstract",
"strict",
"synthetic",
"annotation",
"enum",
"mandated",
];
pub static ALL_FLAGS: [&str; 24] = [
"abstract",
"annotation",
"bridge",
"enum",
"final",
"interface",
"mandated",
"module",
"native",
"open",
"private",
"protected",
"public",
"static",
"static_phase",
"strict",
"strictfp",
"super",
"synchronized",
"synthetic",
"transient",
"transitive",
"varargs",
"volatile",
];
pub(super) struct Flags(&'static [&'static str; 16], u16);
impl fmt::Display for Flags {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
for i in 0..16 {
if self.1 & (1 << i) != 0 {
if first {
first = false;
} else {
f.write_str(" ")?;
}
f.write_str(self.0[i])?;
}
}
Ok(())
}
}
impl Flags {
pub(super) fn class(v: u16) -> Flags {
Flags(&CLASS, v)
}
pub(super) fn field(v: u16) -> Flags {
Flags(&FIELD, v)
}
pub(super) fn method(v: u16) -> Flags {
Flags(&METHOD, v)
}
pub(super) fn mod_requires(v: u16) -> Flags {
Flags(&MOD_REQUIRES, v)
}
pub(super) fn mod_other(v: u16) -> Flags {
Flags(&MOD_OTHER, v)
}
}

View File

@ -0,0 +1,7 @@
mod disassembler;
mod flags;
mod refprinter;
pub mod string;
pub use disassembler::disassemble;
pub use disassembler::DisassemblerOptions;

View File

@ -0,0 +1,474 @@
use std::borrow::Cow;
use std::cell::Cell;
use std::fmt;
use std::fmt::Display;
use super::string::escape;
use super::string::StrLitType;
use crate::lib::classfile::attrs::BootstrapMethod;
use crate::lib::classfile::cpool::Const;
use crate::lib::classfile::cpool::ConstPool;
use crate::lib::mhtags::MHTAGS;
struct UtfData<'a> {
stype: StrLitType,
s: Cow<'a, str>,
use_count: Cell<u8>,
}
impl<'a> UtfData<'a> {
fn to_lit(&'a self) -> StringLit<'a> {
let s = self.s.as_ref();
StringLit { stype: self.stype, s }
}
fn ident(&'a self) -> Option<StringLit<'a>> {
let s = self.s.as_ref();
if s.len() < 50 {
Some(self.to_lit())
} else if s.len() < 300 && self.use_count.get() < 10 {
self.use_count.set(self.use_count.get() + 1);
Some(self.to_lit())
} else {
None
}
}
}
pub(super) struct StringLit<'a> {
stype: StrLitType,
s: &'a str,
}
impl Display for StringLit<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use StrLitType::*;
match self.stype {
Unquoted => f.write_str(self.s),
Regular => write!(f, "\"{}\"", self.s),
Binary => write!(f, "b\"{}\"", self.s),
}
}
}
pub(super) enum RefOrString<'a> {
Raw(u16),
Sym(u16),
RawBs(u16),
Str(StringLit<'a>),
}
use RefOrString::*;
impl Display for RefOrString<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use RefOrString::*;
match self {
Raw(ind) => write!(f, "[{}]", ind),
Sym(ind) => write!(f, "[_{}]", ind),
RawBs(ind) => write!(f, "[bs:{}]", ind),
Str(sl) => sl.fmt(f),
}
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum SingleTag {
Class,
String,
MethodType,
Module,
Package,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
enum PrimTag {
Int,
Long,
Float,
Double,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
enum FmimTag {
Field,
Method,
InterfaceMethod,
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
enum DynTag {
Dynamic,
InvokeDynamic,
}
enum ConstData<'a> {
Invalid,
Utf8(UtfData<'a>),
Prim(PrimTag, String),
Single(SingleTag, u16),
Fmim(FmimTag, u16, u16),
Nat(u16, u16),
MethodHandle(u8, u16),
Dyn(DynTag, u16, u16),
}
impl<'a> ConstData<'a> {
fn new(roundtrip: bool, c: &Const<'a>) -> Self {
use Const::*;
match c {
Null => ConstData::Invalid,
Utf8(s) => {
let (stype, s) = escape(s.0);
ConstData::Utf8(UtfData {
stype,
s,
use_count: Cell::new(0),
})
}
Int(v) => ConstData::Prim(PrimTag::Int, format!("{}", *v as i32)),
Long(v) => ConstData::Prim(PrimTag::Long, format!("{}L", *v as i64)),
Float(v) => ConstData::Prim(PrimTag::Float, {
let f = f32::from_bits(*v);
if f.is_nan() {
if roundtrip {
format!("+NaN<0x{:08X}>f", *v)
} else {
format!("+NaNf")
}
} else if f.is_infinite() {
if f > 0.0 { "+Infinityf" } else { "-Infinityf" }.to_string()
} else {
format!("{:e}f", f)
}
}),
Double(v) => ConstData::Prim(PrimTag::Double, {
let f = f64::from_bits(*v);
if f.is_nan() {
if roundtrip {
format!("+NaN<0x{:016X}>", *v)
} else {
format!("+NaN")
}
} else if f.is_infinite() {
if f > 0.0 { "+Infinity" } else { "-Infinity" }.to_string()
} else {
format!("{:e}", f)
}
}),
Class(v) => ConstData::Single(SingleTag::Class, *v),
Str(v) => ConstData::Single(SingleTag::String, *v),
MethodType(v) => ConstData::Single(SingleTag::MethodType, *v),
Module(v) => ConstData::Single(SingleTag::Module, *v),
Package(v) => ConstData::Single(SingleTag::Package, *v),
Field(c, nat) => ConstData::Fmim(FmimTag::Field, *c, *nat),
Method(c, nat) => ConstData::Fmim(FmimTag::Method, *c, *nat),
InterfaceMethod(c, nat) => ConstData::Fmim(FmimTag::InterfaceMethod, *c, *nat),
NameAndType(n, t) => ConstData::Nat(*n, *t),
MethodHandle(tag, t) => ConstData::MethodHandle(*tag, *t),
Dynamic(r1, r2) => ConstData::Dyn(DynTag::Dynamic, *r1, *r2),
InvokeDynamic(r1, r2) => ConstData::Dyn(DynTag::InvokeDynamic, *r1, *r2),
}
}
}
struct ConstLine<'a> {
data: ConstData<'a>,
force_raw: bool,
is_defined: Cell<bool>, // used during printing at the end
sym_used: Cell<bool>,
}
impl<'a> ConstLine<'a> {
fn new(roundtrip: bool, c: &Const<'a>) -> Self {
Self {
data: ConstData::new(roundtrip, c),
force_raw: roundtrip,
is_defined: Cell::new(false),
sym_used: Cell::new(false),
}
}
}
pub(super) struct RefPrinter<'a> {
roundtrip: bool,
cpool: Vec<ConstLine<'a>>,
bs: &'a [BootstrapMethod],
}
impl<'a> RefPrinter<'a> {
pub(super) fn new(
roundtrip: bool,
cp: &ConstPool<'a>,
bs: Option<&'a [BootstrapMethod]>,
inner_classes: Option<&'a [(u16, u16, u16, u16)]>,
) -> Self {
let mut new = Self {
roundtrip,
cpool: cp.0.iter().map(|c| ConstLine::new(roundtrip, c)).collect(),
bs: bs.unwrap_or(&[]),
};
// There is one case where exact references are significant due to a bug in old versions of the JVM. In the InnerClasses attribute, specifying the same index for inner and outer class will fail verification, but specifying different indexes which point to identical class entries will pass (at least in old versions of Java). In this case, we force references to those indexes to be raw, so they don't get merged and potentially break the class.
for (inner, outer, _, _) in inner_classes.unwrap_or(&[]).iter().copied() {
if inner == outer {
continue;
}
if let Some(s1) = cp.clsutf(inner) {
if let Some(s2) = cp.clsutf(outer) {
if s1 == s2 {
new.cpool[inner as usize].force_raw = true;
new.cpool[outer as usize].force_raw = true;
}
}
}
}
new
}
fn get(&self, ind: u16) -> Option<&ConstData<'a>> {
if let Some(ConstLine {
data, force_raw: false, ..
}) = self.cpool.get(ind as usize)
{
Some(data)
} else {
None
}
}
fn ident(&self, ind: u16) -> Option<StringLit> {
if let Some(ConstData::Utf8(d)) = self.get(ind) {
d.ident()
} else {
None
}
}
fn symref(&self, ind: u16) -> RefOrString {
self.cpool[ind as usize].sym_used.set(true);
Sym(ind)
}
pub(super) fn cpref(&self, ind: u16) -> RefOrString {
if let Some(_) = self.get(ind) {
self.symref(ind)
} else {
Raw(ind)
}
}
pub(super) fn utf(&self, ind: u16) -> RefOrString {
if let Some(ConstData::Utf8(d)) = self.get(ind) {
if let Some(sl) = d.ident() {
Str(sl)
} else {
self.symref(ind)
}
} else {
Raw(ind)
}
}
pub(super) fn single(&self, ind: u16, expected: SingleTag) -> RefOrString {
if let Some(ConstData::Single(tag, v)) = self.get(ind) {
if *tag != expected {
return Raw(ind);
}
if let Some(sl) = self.ident(*v) {
Str(sl)
} else {
self.symref(ind)
}
} else {
Raw(ind)
}
}
pub(super) fn cls(&self, ind: u16) -> RefOrString {
self.single(ind, SingleTag::Class)
}
pub(super) fn nat(&self, ind: u16) -> impl Display + '_ {
LazyPrint(move |f: &mut fmt::Formatter| {
if let Some(ConstData::Nat(n, t)) = self.get(ind) {
if let Some(sl) = self.ident(*n) {
write!(f, "{} {}", sl, self.utf(*t))
} else {
self.symref(ind).fmt(f)
}
} else {
Raw(ind).fmt(f)
}
})
}
pub(super) fn tagged_fmim(&self, ind: u16) -> impl Display + '_ {
LazyPrint(move |f: &mut fmt::Formatter| {
if let Some(ConstData::Fmim(tag, c, nat)) = self.get(ind) {
write!(f, "{:?} {} {}", *tag, self.cls(*c), self.nat(*nat))
} else {
Raw(ind).fmt(f)
}
})
}
fn tagged_const_nomhdyn(&self, f: &mut fmt::Formatter, ind: u16) -> fmt::Result {
// Like regular tagged_const except that MethodHandle and Dynamic/InvokeDynamic
// are replaced with symrefs to prevent recursion or indefinite expansion
if let Some(c) = self.get(ind) {
use ConstData::*;
match c {
MethodHandle(..) | Dyn(..) => self.symref(ind).fmt(f),
_ => self.tagged_const_sub(f, c),
}
} else {
Raw(ind).fmt(f)
}
}
fn mhnotref(&self, f: &mut fmt::Formatter, mhtag: u8, r: u16) -> fmt::Result {
let tag_str = MHTAGS.get(mhtag as usize).copied().unwrap_or("INVALID");
// todo - inline tagged ref consts
write!(f, "{} ", tag_str)?;
self.tagged_const_nomhdyn(f, r)
}
fn bsnotref(&self, f: &mut fmt::Formatter, bsm: &BootstrapMethod, tagged: bool) -> fmt::Result {
if tagged {
write!(f, "Bootstrap {}", Raw(bsm.bsref))?;
} else if let Some(ConstData::MethodHandle(mhtag, r)) = self.get(bsm.bsref) {
self.mhnotref(f, *mhtag, *r)?;
} else {
Raw(bsm.bsref).fmt(f)?;
}
for bsarg in &bsm.args {
write!(f, " ")?;
self.tagged_const_nomhdyn(f, *bsarg)?;
}
write!(f, " :")
}
fn bs(&self, bsind: u16) -> impl Display + '_ {
LazyPrint(move |f: &mut fmt::Formatter| {
if !self.roundtrip {
if let Some(bsm) = self.bs.get(bsind as usize) {
return self.bsnotref(f, bsm, false);
}
}
RawBs(bsind).fmt(f)
})
}
fn tagged_const_sub(&self, f: &mut fmt::Formatter, c: &ConstData) -> fmt::Result {
use ConstData::*;
match c {
Invalid => panic!("Internal error: Please report this!"),
Utf8(ud) => write!(f, "Utf8 {}", ud.to_lit()),
Prim(tag, s) => write!(f, "{:?} {}", tag, s),
Single(tag, r) => write!(f, "{:?} {}", tag, self.utf(*r)),
Fmim(tag, r1, r2) => write!(f, "{:?} {} {}", tag, self.cls(*r1), self.nat(*r2)),
Nat(r1, r2) => write!(f, "NameAndType {} {}", self.utf(*r1), self.utf(*r2)),
MethodHandle(mhtag, r) => {
f.write_str("MethodHandle ")?;
self.mhnotref(f, *mhtag, *r)
}
Dyn(tag, bs, nat) => write!(f, "{:?} {} {}", tag, self.bs(*bs), self.nat(*nat)),
}
}
#[allow(unused)]
pub(super) fn tagged_const(&self, ind: u16) -> impl Display + '_ {
LazyPrint(move |f: &mut fmt::Formatter| {
if let Some(c) = self.get(ind) {
self.tagged_const_sub(f, c)
} else {
Raw(ind).fmt(f)
}
})
}
fn ldcrhs_sub(&self, f: &mut fmt::Formatter, ind: u16, c: &ConstData) -> fmt::Result {
use ConstData::*;
match c {
Prim(_tag, s) => write!(f, "{}", s),
Single(SingleTag::String, r) => {
if let Some(mut sl) = self.ident(*r) {
if sl.stype == StrLitType::Unquoted {
sl.stype = StrLitType::Regular;
}
write!(f, "{}", sl)
} else {
write!(f, "{}", self.symref(ind))
}
}
Single(tag, r) => write!(f, "{:?} {}", tag, self.utf(*r)),
MethodHandle(..) | Dyn(..) => self.tagged_const_sub(f, c),
Invalid | Utf8(..) | Fmim(..) | Nat(..) => write!(f, "{}", Raw(ind)),
}
}
pub(super) fn ldc(&self, ind: u16) -> impl Display + '_ {
LazyPrint(move |f: &mut fmt::Formatter| {
if let Some(c) = self.get(ind) {
self.ldcrhs_sub(f, ind, c)
} else {
Raw(ind).fmt(f)
}
})
}
fn cp_def_rhs(&'a self, c: &'a ConstData) -> impl Display + 'a {
LazyPrint(move |f: &mut fmt::Formatter| self.tagged_const_sub(f, c))
}
fn bs_def_rhs(&'a self, bsm: &'a BootstrapMethod) -> impl Display + 'a {
LazyPrint(move |f: &mut fmt::Formatter| self.bsnotref(f, bsm, true))
}
pub(super) fn print_const_defs(self, mut w: impl std::io::Write) -> std::io::Result<()> {
loop {
let mut done = true;
for (ind, line) in self.cpool.iter().enumerate() {
let ind = ind as u16;
if let ConstData::Invalid = line.data {
continue;
}
if !line.is_defined.get() && (line.force_raw || line.sym_used.get()) {
let lhs = if line.force_raw { Raw(ind) } else { Sym(ind) };
writeln!(w, ".const {} = {}", lhs, self.cp_def_rhs(&line.data))?;
line.is_defined.set(true);
done = false;
}
}
// In non-roundtrip mode, printing symref defs may result in other
// constant pool entries being referenced for the first time, so we
// have to repeat the loop until no more entries are printed
if done || self.roundtrip {
break;
}
}
// We never create symbolic bs refs in non-roundtrip mode (printing them inline instead)
// which makes things easy - print the whole table raw in roundtrip mode, do nothing otherwise
if self.roundtrip {
for (ind, bsm) in self.bs.iter().enumerate() {
let ind = ind as u16;
writeln!(w, ".bootstrap {} = {}", RawBs(ind), self.bs_def_rhs(bsm))?;
}
}
Ok(())
}
}
struct LazyPrint<F>(F);
impl<F: Fn(&mut fmt::Formatter) -> fmt::Result> Display for LazyPrint<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0(f)
}
}

View File

@ -0,0 +1,144 @@
use super::flags::ALL_FLAGS;
use lazy_static::lazy_static;
use regex::Regex;
use std::borrow::Cow;
use std::fmt::Write;
use std::str;
lazy_static! {
static ref WORD_RE: Regex = Regex::new(r"\A(?:[a-zA-Z_$\(<]|\[[A-Z\[])[a-zA-Z0-9_$;/\[\(\)<>*+-]*\z").unwrap();
}
fn decode(mut iter: impl Iterator<Item = u8>, mut cb: impl FnMut(u16)) -> bool {
while let Some(b) = iter.next() {
match b {
0b00000001..=0b01111111 => cb(b as u16),
0b11000000..=0b11011111 => {
let val = (b as u16) & 31;
if let Some(b) = iter.next() {
let val = (val << 6) ^ (b as u16) & 63;
cb(val);
}
}
0b11100000..=0b11101111 => {
let val = (b as u16) & 15;
if let Some(b) = iter.next() {
let val = (val << 6) ^ (b as u16) & 63;
if let Some(b) = iter.next() {
let val = (val << 6) ^ (b as u16) & 63;
cb(val);
}
}
}
_ => return false, // return false to indicate invalid MUTF8
}
}
true
}
fn escape_sub(s: &[u8]) -> (StrLitType, String) {
let mut out = String::with_capacity(s.len());
if decode(s.iter().copied(), |c| {
match c {
// 0..=7 => write!(&mut out, "\\{}", c),
34 => write!(&mut out, "\\\""),
92 => write!(&mut out, "\\\\"),
32..=126 => write!(&mut out, "{}", char::from_u32(c.into()).unwrap()),
_ => write!(&mut out, "\\u{:04X}", c),
}
.unwrap();
}) {
(StrLitType::Regular, out)
} else {
(StrLitType::Binary, escape_byte_string(s))
}
}
fn is_word(s: &str) -> bool {
WORD_RE.is_match(s) && !ALL_FLAGS.contains(&s)
}
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum StrLitType {
Unquoted,
Regular,
Binary,
}
pub(super) fn escape(s: &[u8]) -> (StrLitType, Cow<str>) {
if let Ok(s) = str::from_utf8(s) {
if is_word(s) {
return (StrLitType::Unquoted, Cow::from(s));
}
}
let (ty, s) = escape_sub(s);
(ty, Cow::from(s))
}
pub(super) fn escape_byte_string(s: &[u8]) -> String {
let mut buf = String::with_capacity(s.len() * 4);
for b in s {
write!(buf, "\\x{:02X}", b).unwrap();
}
buf
}
pub fn parse_utf8(s: &[u8]) -> Option<String> {
if let Ok(s) = str::from_utf8(s) {
return Some(s.to_owned());
}
let mut u16s = Vec::with_capacity(s.len());
if !decode(s.iter().copied(), |c16| {
u16s.push(c16);
}) {
return None;
}
std::char::decode_utf16(u16s.into_iter()).collect::<Result<String, _>>().ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_word() {
assert!(is_word("hello"));
assert!(is_word("[Lhello/world;"));
assert!(is_word("[[[Z"));
assert!(is_word("<main>"));
assert!(is_word("(ZZ)[LFoo;"));
assert!(is_word("foo2"));
assert!(!is_word(""));
assert!(!is_word("[42]"));
assert!(!is_word("0"));
assert!(!is_word("\n"));
assert!(!is_word("hello\n"));
assert!(!is_word("a b"));
assert!(!is_word("a.b"));
}
#[test]
fn test_escape() {
assert_eq!(escape(b"hello").1.as_ref(), "hello");
assert_eq!(escape(b"[42]").1.as_ref(), "[42]");
assert_eq!(escape(b"s = \"42\";").1.as_ref(), r#"s = \"42\";"#);
assert_eq!(escape(b"\xC0\x80").1.as_ref(), r#"\u0000"#);
assert_eq!(escape(b"\xdf\xbf\xef\xbf\xbf").1.as_ref(), r#"\u07FF\uFFFF"#);
assert_eq!(
escape(b"\xed\xaf\xbf\xed\xbf\xbf\xed\xaf\x80\xed\xb0\x81").1.as_ref(),
r#"\uDBFF\uDFFF\uDBC0\uDC01"#
);
assert_eq!(
escape(b"\x3B\x0C\x3D\x06\x34\x01\x25\x04\x34\x16").1.as_ref(),
r#";\u000C=\u00064\u0001%\u00044\u0016"#
);
}
#[test]
fn test_escape_byte_string() {
assert_eq!(escape_byte_string(b"\x00\xAB"), r"\x00\xAB");
}
}

16
src/lib/mhtags.rs Normal file
View File

@ -0,0 +1,16 @@
pub static MHTAGS: [&str; 10] = [
"INVALID",
"getField",
"getStatic",
"putField",
"putStatic",
"invokeVirtual",
"invokeStatic",
"invokeSpecial",
"newInvokeSpecial",
"invokeInterface",
];
pub fn parse(s: &str) -> Option<u8> {
MHTAGS.into_iter().position(|v| v == s).map(|i| i as u8)
}

26
src/lib/mod.rs Normal file
View File

@ -0,0 +1,26 @@
mod assemble;
mod classfile;
mod disassemble;
mod mhtags;
mod util;
pub use assemble::assemble;
pub use assemble::AssemblerOptions;
pub use assemble::Error as AssembleError;
pub use classfile::ParserOptions;
pub use disassemble::string::parse_utf8;
pub use disassemble::DisassemblerOptions;
pub fn disassemble(
data: &[u8],
parse_opts: ParserOptions,
opts: DisassemblerOptions,
) -> Result<(Option<String>, Vec<u8>), classfile::ParseError> {
let parsed = classfile::parse(data, parse_opts)?;
let name = parsed.cp.clsutf(parsed.this).and_then(parse_utf8);
let mut out = Vec::with_capacity(1000 + data.len() * 4);
disassemble::disassemble(&mut out, &parsed, opts).expect("Internal error - please report this!");
Ok((name, out))
}

7
src/lib/util.rs Normal file
View File

@ -0,0 +1,7 @@
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct BStr<'a>(pub &'a [u8]);
impl<'a> std::fmt::Debug for BStr<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
String::from_utf8_lossy(self.0).fmt(f)
}
}

44
src/main.rs Normal file
View File

@ -0,0 +1,44 @@
// #![allow(unused)]
mod ass_main;
mod dis_main;
mod file_input_util;
mod file_output_util;
mod lib;
use std::str;
use std::thread;
use clap::{Parser, Subcommand};
use ass_main::assembler_main;
use ass_main::AssemblerCli;
use dis_main::disassembler_main;
use dis_main::DisassemblerCli;
#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
struct Cli {
#[clap(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Asm(AssemblerCli),
Dis(DisassemblerCli),
}
fn real_main() -> i32 {
let cli = Cli::parse();
match cli.command {
Command::Asm(cli) => assembler_main(cli),
Command::Dis(cli) => disassembler_main(cli),
}
}
fn main() {
// Workaround for limited stack size in Rust: Spawn a thread with 256mb stack and run everything there.
let child = thread::Builder::new().stack_size(256 * 1024 * 1024).spawn(real_main).unwrap();
std::process::exit(child.join().unwrap());
// std::process::exit(real_main());
}