Repository: Nugine/bfjit Branch: main Commit: f82b2b6a7d22 Files: 28 Total size: 89.4 KB Directory structure: gitextract_smcnmwh3/ ├── .gitattributes ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ ├── ci.yml │ └── deploy.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── bf/ │ ├── cgbfi2.bf │ ├── hello.bf │ └── mendelbrot.bf ├── book/ │ ├── book.toml │ └── src/ │ ├── 1.md │ ├── 2.md │ ├── 3.md │ ├── 4.md │ ├── 5.md │ ├── 6.md │ ├── 7.md │ ├── 8.md │ ├── SUMMARY.md │ ├── conclusion.md │ └── introduction.md ├── justfile └── src/ ├── bfir.rs ├── bfjit.rs ├── error.rs └── main.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ docs/* linguist-vendored bf/* linguist-vendored ================================================ FILE: .github/dependabot.yml ================================================ # To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "cargo" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "monthly" groups: dependencies: patterns: - "*" ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: push: branches: - main - 'feat/**' pull_request: branches: - main - 'feat/**' schedule: - cron: '0 0 * * 0' # at midnight of each sunday workflow_dispatch: jobs: develop: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@just - uses: dtolnay/rust-toolchain@nightly with: components: rustfmt, clippy, miri, rust-src - uses: Swatinem/rust-cache@v2 - run: just ci msrv: runs-on: ubuntu-latest strategy: fail-fast: false matrix: toolchain: - 1.78.0 # MSRV - stable steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@just - uses: dtolnay/rust-toolchain@master with: toolchain: ${{ matrix.toolchain }} - uses: Swatinem/rust-cache@v2 - run: just test audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@cargo-audit - run: cargo audit -D warnings ================================================ FILE: .github/workflows/deploy.yml ================================================ name: Deploy on: push: branches: ["main"] workflow_dispatch: permissions: contents: read pages: write id-token: write concurrency: group: "pages" cancel-in-progress: false jobs: deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/install-action@mdbook - run: cd book && mdbook build - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: path: ./dist - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 ================================================ FILE: .gitignore ================================================ /target **/*.rs.bk .vscode /dist ================================================ FILE: Cargo.toml ================================================ [package] name = "bfjit" version = "0.1.4" authors = ["Nugine "] edition = "2021" license = "AGPL-3.0" repository = "https://github.com/Nugine/bfjit" description = "Brainfuck JIT VM tutorial" keywords = ["brainfuck", "jit", "tutorial"] categories = ["compilers", "command-line-utilities"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] thiserror = "2.0.18" dynasm = "5.0.0" dynasmrt = "5.0.0" clap = { version = "4.5.60", features = ["derive"] } [profile.release] debug = "full" ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. 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. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. 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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. 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 AGPL, see . ================================================ FILE: README.md ================================================ # Brainfuck JIT 虚拟机教程 当我们谈到 JIT 时,通常会想到 V8、JVM 之类的庞然大物,然后望而生畏,觉得 JIT 是一种极其高深复杂的技术。 但 JIT 也可以变得非常简单,我们不需要做完善的优化和分析,只要输入源码,输出机器指令,再执行,这和普通的文本处理程序没什么区别。 在本教程中,我们将用 Rust 语言实现一个简单的 Brainfuck JIT 虚拟机,逐步理解 JIT 技术。 教程地址: 如果本教程对您有帮助,请[赞助我的开源工作](https://github.com/Nugine#sponsor)。 ================================================ FILE: bf/cgbfi2.bf ================================================ Brainfuck Self Interpreter: by Clive Gifford Version 1: 01 December 2006 (one trip between code and data per op) Version 2: 16 December 2006 (virtual codes for various combinations) Credits A large section of code to load the input to the interpreter is copied from the the 423 byte dbfi interpreter as described in the November 2003 paper "A Very Small Interpeter" by Oleg Mazonka and Daniel B Cristofani Goals The goal for this interpreter was to be efficient rather than small and particularly to allow as many copies of itself as possible to be "stacked" up with something else on top / In other words to achieve a low "eigenratio" (See http eigenratios dot blogspot dot com for more information) The main idea of the first version was to only make one round trip between the emulated code and emulated data for each instruction executed instead of multiple round trips which is what Daniel and Oleg's version does The second version does more pre processing of the guest program in order to map several common sequences to virtual codes thus reducing the memory footprint and also further reducing the number of round trips between the emulated code and data Other info: The input must consist of valid brainfuck code (to be interpreted) which must always be followed by an exclamation mark and then any associated data Input can also include "comments" (if desired) except for exclamation mark If you are stacking multiple copies of this interpreter then each additional level also has to appear in the input with a trailing exclamation mark and then we finally have the input for the very top level to finish things off The underlying brainfuck machine determines the possible range of values in the data cell values and what happens if an attempt is made to go outside the supported range but this interpreter does not more than 8 bit data itself Loops in the emulated code can be nested up to the maximum cell value in the underlying machine and this interpreter requires that at least 17 levels of nesting is supported Behaviour on end of input is also inherited from the next level down >>>> leave a little extra space before the program code + start in left hand cell of first program code pair [ ->>> clear flag and move to the starting position ++>+>+++++++ setup differences and read char as per dbfi [<++++>>++<-]++>>+>+> (by Daniel B Cristofani) +++++[>++>++++++<<-] +>>>,<++ [ [>[->>]<[>>]<<-] see section 3 of dbfi paper <[<]<+>>[>]> [ see section 4 of dbfi paper <+>- [[<+>-]>] see section 5 of dbfi paper < see section 6 of dbfi paper [ [[-]<] scan left and zero the differences ++<- see section 7 of dbfi paper [ <+++++++++>[<->-]>> ] >> ] ] << ] a three way switch to handle possibilities and adjust positioning >[-]+<< set "done" flag and position to value [ -- 2 means last decode was for a valid instruction [ so if we still have something left now it was a 9 [-] originally (meaning input should be ignored) >>- <<<+> so all we do is set the "more input" flag ] >> [ - <<<<[>+<-] for valid input move everything right one start of processing to find and recode certain combinations of codes +<<+ set flags to indicate we want to process the last two instructions in the loop below [ -> clear flag and move to instruction [<+>>>>>>+<<<<<-] double copy instruction and then <[>+<-]>>>>>> restore original before moving to copy map relevant codes to values giving unique pairwise sums and also set a flag if we see the end of a loop >+< [ -[ -[ -[ -[ -[ -[ -[ -[ [-] >-< ]>[-<<+++++++>>] < ] ] ]>[-]< ]>[-<<+++>>]< ]>[-<<+>>]< ]>[-]< ]>[-<<<<<<<+>>>>>>>]< set flag if it is end of loop ]>[-]< <<<< goto next instruction flag ] add values from above together to get unique sum >>>[<<+>>-] <+< setup a switch to figure out what it means [ -[ -[ -[ -[ -[ -[ -[ -[ -[ -[ [-] >-<<<[-]<<+>> change code 8 (add 1) to 9 (add 2) ] ] ] ]>[-]< ]>[-<<<[-]<<+++++++>>>]< change code 4 (left) to 11 (left 2) ] ] ]>[-]< ]>[-<<<[-]<<+++++++>>>]< change code 3 (right) to 10 (right 2) ] ]>[-]< clear flag set if second to last was end of loop and go to similar flag for last instruction <<<<<[-]>> [ - <<<[>+>>+<<<-]>[<+>-]>> copy third to last instruction if it is the start of a loop then we can (in some cases) collapse the last three instructions to single virtual code [ -[ -[ [-] >> ] > [ Now we are ready to check what code is in the loop (must be at least 1) <<[<+>>+<-]>[<+>-]+<< - [ -[ -[ -[ -[ -[ -[ -[ -[ -[ - <+> fall through & code as 16 (double skip left) ]<+++++++++++++>>[-]>->-<< code as 15 (double skip right) ] ] ]>>[->>>>>]<< ]>>[-<<<++++++++++++>>[-]>>-]<< code as 14 (zero) ]>>[->>>>>]<< ]>>[-<<<+++++++++++>>[-]>>-]<< code as 13 (skip left) ]>>[-<<<++++++++++>>[-]>>-]<< code as 12 (skip right) ] ]>>[->>>>>]<< ] < ] ]>[>>]< << ] >>+>>> ] << ] >> [->+>] << end of input so clear "done" and set data mark and finally position to a zero cell ready for next phase < move to "more input" flag ] <<[<<]>> go to the first instruction ******** MAIN INTERPRETER LOOPS STARTS HERE ******** [ start on current instruction code setup a big switch statement to decode instructions [<+>>+<-] move/copy instruction code and set "done" flag to +<- start with '(i less 1) (1) (i) for i = instruction [ -[ -[ -[ -[ -[ -[ -[ -[ -[ -[ -[ -[ -[ -[ - can't be anything but 1 so bracketing not needed >->> [>>] >> [>>]< [<-<<-<] <[<<] << [<<]< double skip left (code 16) ] >[->> [>>] >> [>>]< [>+>>+>] <[<<] << [<<]]< double skip right (code 15) ] >[->> [>>] >> [>>] <[-]< [<<] << [<<]]< zero (code 14) ] >[->> [>>] >> [>>]< [<-<] <[<<] << [<<]]< skip left (code 13) ] >[->> [>>] >> [>>]< [>+>] <[<<] << [<<]]< skip right (code 12) ] >[->> [>>] >> [>>]< <-<<-< <[<<] << [<<]]< double move left (code 11) ] >[->> [>>] >> [>>] +>>+ [<<] << [<<]]< double move right (code 10) ] >[->> [>>] >> [>>]< ++ <[<<] << [<<]]< add 2 (code 9) ] >[->> [>>] >> [>>]< + <[<<] << [<<]]< increment ] >[->> [>>] >> [>>]< , <[<<] << [<<]]< input ] >[->> [>>] >> [>>]< - <[<<] << [<<]]< decrement ] >[->> [>>] >> [>>]< . <[<<] << [<<]]< output ] >[->> [>>] >> [>>] <<-<< [<<] << [<<]]< move left ] >[->> [>>] >> [>>] + [<<] << [<<]]< move right ] > [- left hand bracket >> [>>] >> [>>]< move to data cell [>+>>+<<<-]> make double copy and move to first [<+>-] restore original data cell value >>[<<+>>[-]]+ This and the following achieves <<[>>-<<-] x = not x >> go to flag cell (0 or 1) Some tricky stuff here: set up (not flag) also so we can later choose appropriate instruction sequence to get back to code area in one pass In one case we set flags at the other end (data greater than 0) but for the other we just go back without setting any flags (data equals 0) [<<+>>>>+<<-] make two copies of flag >>[<<+>>-] <<[>>+<<-]+ This and the following achieves >>[<<->>-]<< x = not x << so we now have (data) '(flag) (?) (not flag) [ if flag set then -<< [<<] << [<<]< clear and return to code section where we save << << ++ a 2 meaning we need (later) to match left bracket >> stop in zero cell for now ] >> if we executed code above then now at switch flag else it will put us ready to return from data area [-<<<<<<[<<]<<[<<]<] move back to switch flag without setting anything > ] < ] > [- right hand bracket >> [>>] >> [>>]< move to data cell [>+>>+<<<-]> make double copy and move to first [[<+>-]>>[-]+<<] restore data from one then zero second and set flag >> go to flag cell (0 or 1) Some tricky stuff here: set up (not flag) also so we can later choose appropriate instruction sequence to get back to code area in one pass In one case we set flags at the other end (data greater than 0) but for the other we just go back without setting any flags (data equals 0) [<<+>>>>+<<-] make two copes of flag >>[<<+>>-] <<[>>+<<-]+ This and the following achieves >>[<<->>-]<< x = not x << so we now have (data) '(flag) (?) (not flag) [ if flag set then -<< [<<] << [<<]< clear and return to code section where we save << << + a 1 meaning we need (later) to match right bracket >> stop in zero cell for now ] >> if we executed code above then now at switch flag else it will put us ready to return from data area [-<<<<<<[<<]<<[<<]<] move back to switch flag without setting anything > ] >[<+>-] restore original instruction code *** We are positioned in the cell immediately to the right of the *** *** instruction that has just been "executed" in the switch above *** *** The following code is to handle finding matching brackets *** *** because code above has only set a cell value to 1 or 2 to show *** *** what kind of loop scanning is required (1=scan left 2=right) *** << << << position to cell showing if matching required [ if non zero we need to find a matching bracket >> + set up "done" flag for switch and << - decrement switch value so now is 0 or 1 [ if 1 we are looking for matching right bracket - >> - >> + clear switch value & "done" & set level to 1 [ while level is more than 0 >>>[-<+>>+<] make double copy of instruction code +<- set flag and prepare for switch [ -[ [-] clear whatever is left of code > - < do nothing except clear flag ] > [- <<< + >>>] < increment level ] > [- <<< - >>>] decrement level >[-<+>]<< restore instruction code << go to level [>>+<<-] if level then move right one instruction >> ] << << << go back to switch value cell ] >> go to switch done flag and if still set then [ we must be looking for a matching left bracket - << + clear switch value & "done" & set level to 1 [ repeat while level is more than 0 >>>[-<+>>+<] make double copy of instruction code +<- set flag and prepare for switch [ -[ [-] clear whatever is left of code > - < do nothing except clear flag ] > [- <<< - >>>] < decrement level ] > [- <<< + >>>] increment level >[-<+>]<< restore instruction code << go to level [<<+>>-] if level then move left one instruction << ] ] ] >> >> >> > move forward to next instruction ] ================================================ FILE: bf/hello.bf ================================================ [ This program prints "Hello World" and a newline to the screen, its length is 106 active command characters. [It is not the shortest.] This loop is an "initial comment loop", a simple way of adding a comment to a BF program such that you don't have to worry about any command characters. Any ".", ",", "+", "-", "<" and ">" characters are simply ignored, the "[" and "]" characters just have to be balanced. This loop and the commands it contains are ignored because the current cell defaults to a value of 0; the 0 value causes this loop to be skipped. ] ++++++++ Set Cell #0 to 8 [ >++++ Add 4 to Cell #1; this will always set Cell #1 to 4 [ as the cell will be cleared by the loop >++ Add 2 to Cell #2 >+++ Add 3 to Cell #3 >+++ Add 3 to Cell #4 >+ Add 1 to Cell #5 <<<<- Decrement the loop counter in Cell #1 ] Loop till Cell #1 is zero; number of iterations is 4 >+ Add 1 to Cell #2 >+ Add 1 to Cell #3 >- Subtract 1 from Cell #4 >>+ Add 1 to Cell #6 [<] Move back to the first zero cell you find; this will be Cell #1 which was cleared by the previous loop <- Decrement the loop Counter in Cell #0 ] Loop till Cell #0 is zero; number of iterations is 8 The result of this is: Cell No : 0 1 2 3 4 5 6 Contents: 0 0 72 104 88 32 8 Pointer : ^ >>. Cell #2 has value 72 which is 'H' >---. Subtract 3 from Cell #3 to get 101 which is 'e' +++++++..+++. Likewise for 'llo' from Cell #3 >>. Cell #5 is 32 for the space <-. Subtract 1 from Cell #4 for 87 to give a 'W' <. Cell #3 was set to 'o' from the end of 'Hello' +++.------.--------. Cell #3 for 'rl' and 'd' >>+. Add 1 to Cell #5 gives us an exclamation point >++. And finally a newline from Cell #6 ================================================ FILE: bf/mendelbrot.bf ================================================ [A mandelbrot set fractal viewer in brainf*** written by Erik Bosman] +++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[ >>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+ <<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>> >+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[-]>>]<<<<<<<<<[<<<<<<<<<]>> >>>>>[-]+<<<<<<++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<+++++++[-[->>> >>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[[-]>>>>>>[>>>>> >>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>> [>>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<< <<]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]>>>>>>>>>+++++++++++++++[[ >>>>>>>>>]+>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+[ >+>>>>>>>>]<<<<<<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+[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<< <<<<<]]>>>] ================================================ FILE: book/book.toml ================================================ [book] authors = ["Nugine"] language = "zh-CN" multilingual = false src = "src" title = "Brainfuck JIT 虚拟机教程" [build] build-dir = "../dist" ================================================ FILE: book/src/1.md ================================================ # 1. 背景知识 ## Brainfuck 简介 Brainfuck 仅包含八个指令,却是图灵完备的,理论上它可以做到任何用图灵机能做到的事情。 机器模型:一个字节数组,一个数据指针,一个指令指针,输入流,输出流。 数组初始化为全零,数据指针初始时指向数组的第一个字节,指令指针指向第一条指令。 字符 '>':将数据指针加一。 字符 '<':将数据指针减一。 字符 '+':将数据指针所指的单元加一。 字符 '-':将数据指针所指的单元减一。 字符 ',':从输入流中读取一个字节,存入数据指针所指单元。 字符 '.':输出数据指针所指单元的字节。 字符 '[':如果当前单元是 0,那么跳转到对应的 ']' 的下一条指令,否则继续执行。 字符 ']':如果当前单元不是 0,那么跳转到对应的 '[' 的下一条指令,否则继续执行。 Brainfuck 可以直接对应到 C 代码,仅用几十行就能写个从 bf 到 c 的编译器。 初始化 ```c char array[30000] = {0}; char *ptr=array; ``` | 指令 | C 代码 | | ---- | --------------- | | > | ++ptr; | | < | --ptr; | | + | ++*ptr; | | - | --*ptr; | | . | putchar(*ptr); | | , | *ptr=getchar(); | | [ | while (*ptr) { | | ] | } | Brainfuck 可视化 ## Rust 资源 Rust 官网 Rust 一键安装 Rust 并不是一个能立即上手的语言,如果您是一位 Rust 新手,最好先全面了解 Rust 语言特性。 Rust 官网入门教程 中文书《Rust编程之道》 ================================================ FILE: book/src/2.md ================================================ # 2. 启动项目 初始化项目 ```bash cargo new bfjit cd bfjit cargo run ``` 空白项目默认为 Hello world ``` Finished dev [unoptimized + debuginfo] target(s) in 0.06s Running `target/debug/bfjit` Hello, world! ``` 一切就绪。 ================================================ FILE: book/src/3.md ================================================ # 3. 中间表示 为了方便后期处理,我们先将 Brainfuck 代码转换为一种中间表示 (IR). 在 src 目录下添加文件 bfir.rs 此时目录结构 ``` . ├── Cargo.lock ├── Cargo.toml └── src ├── bfir.rs └── main.rs ``` main.rs ```rust ,noplaypen mod bfir; fn main() { println!("Hello, world!"); } ``` 本节以下代码都将写入 bfir.rs ## IR 定义 AddVal, SubVal 表示将当前单元加减某一数值。 AddPtr, SubPtr 表示将数据指针加减某一数值。 Jz,Jnz 表示跳转指令,带有跳转地址。 ```rust ,noplaypen {{#include ../../src/bfir.rs:3:13}} ``` ## 错误处理 我们使用 thiserror 库,用来轻松定义错误类型。 导入第三方库时: 若 Rust 版本 >= 1.62,可直接 [cargo add](https://doc.rust-lang.org/cargo/commands/cargo-add.html) 。 若 Rust 版本 < 1.62,推荐用 cargo-edit 插件。安装 cargo-edit 插件后,可以用命令导入第三方库。 也可手动编辑 Cargo.toml。 ```bash cargo install cargo-edit ``` ```bash cargo add thiserror ``` 错误定义 ```rust ,noplaypen {{#include ../../src/bfir.rs:15:28}} ``` 为 CompileError 实现 Display 和 Error,Display 用于对人友好的信息,Error 表明它是一个错误类型。 ```rust ,noplaypen {{#include ../../src/bfir.rs:23:34}} ``` ## 编译为 IR ```rust ,noplaypen {{#include ../../src/bfir.rs:38:44}} ``` compile 函数接收一个字符串,返回 IR 序列。 code 存储已解析的 IR,stk 作为栈,存储左括号的IR位置、源代码行位置、源代码列位置,line 和 col 分别记录行号和列号。 主循环结构 ```rust ,noplaypen for ch in src.chars() { col += 1; match ch { ... } } ``` 处理换行 ```rust ,noplaypen '\n' => { line += 1; col = 0; } ``` 处理普通指令 ```rust ,noplaypen '+' => code.push(BfIR::AddVal(1)), '-' => code.push(BfIR::SubVal(1)), '>' => code.push(BfIR::AddPtr(1)), '<' => code.push(BfIR::SubPtr(1)), ',' => code.push(BfIR::GetByte), '.' => code.push(BfIR::PutByte), ``` 处理左括号,将左括号位置入栈。 ```rust ,noplaypen '[' => { let pos = code.len() as u32; stk.push((pos, line, col)); code.push(BfIR::Jz) } ``` 处理右括号,从栈中弹出左括号位置,如果栈为空,说明没有匹配的左括号,生成一个编译错误并返回。如果有匹配的左括号,则正常生成 IR。 ```rust ,noplaypen ']' => { stk.pop().ok_or(CompileError { line, col, kind: CompileErrorKind::UnexpectedRightBracket, })?; code.push(BfIR::Jnz) } ``` 忽略其他字符 ```rust ,noplaypen _ => {} ``` 循环结束后,如果栈不为空,说明有左括号没有匹配到右括号,弹出左括号位置,生成编译错误。最后返回生成的IR. ```rust ,noplaypen if let Some((_, line, col)) = stk.pop() { return Err(CompileError { line, col, kind: CompileErrorKind::UnclosedLeftBracket, }); } Ok(code) ``` 完整代码 ```rust,noplaypen {{#include ../../src/bfir.rs:38:84}} ``` ## 简单优化 brainfuck 代码中经常有连续的算术加减和指针移动,这些操作完全可以折叠起来。 优化函数直接操作 IR 序列,用一次遍历完成折叠,原地操作。时间复杂度 O(n),空间复杂度 O(1)。 这里定义两个宏来避免复制粘贴大量同样的代码。 ```rust,noplaypen {{#include ../../src/bfir.rs:88:132}} ``` ## 简单测试 Rust 内置一套单元测试框架,在模块内随手写个函数,标上 `#[test]`,然后运行命令 `cargo test`。cargo 会收集所有测试,逐个运行,并报告结果。 ```rust,noplaypen {{#include ../../src/bfir.rs:134:161}} ``` ================================================ FILE: book/src/4.md ================================================ # 4. Hello, JIT 通常来说,Just In Time (JIT) 编译器 是指在某段高阶代码即将运行时将其编译到机器码再执行的程序。下文中,我们把这样的程序叫做 "JIT"。 一个最简单的 JIT 工作方式是这样的: 1. 将源代码编译为机器码。 2. 申请一段可写可执行内存,写入机器码。 3. 跳转到这段内存,执行机器码。 4. 执行完毕,稍作清理,退出。 以下代码引用自 [Hello, JIT World: The Joy of Simple JITs](http://blog.reverberate.org/2012/12/hello-jit-world-joy-of-simple-jits.html) ```c #include #include #include #include int main(int argc, char *argv[]) { // 机器码: // mov eax, 0 // ret unsigned char code[] = {0xb8, 0x00, 0x00, 0x00, 0x00, 0xc3}; if (argc < 2) { fprintf(stderr, "Usage: jit1 \n"); return 1; } // 把用户给出的数值写入机器码,覆盖立即数 "0" // mov eax, // ret int num = atoi(argv[1]); memcpy(&code[1], &num, 4); // 分配可写可执行内存 // 注意:真实的程序不应该映射同时可写可执行的内存, // 这里有安全风险。 void *mem = mmap(NULL, sizeof(code), PROT_WRITE | PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0); memcpy(mem, code, sizeof(code)); // 定义一个函数指针指向机器码内存,再执行函数 int (*func)() = mem; return func(); } ``` 编写 JIT 的一大难点是如何生成机器码,这里通常有跨平台问题、可读性消失问题。 最笨的方法:写一段汇编,用汇编器生成机器码,再复制到高级代码里。但这样不具有通用性,开发效率非常低。 ## dynasm [DynAsm](http://luajit.org/dynasm.html) 是 LuaJIT 的一部分,它用预处理器把混合汇编的 C 文件转换成 纯 C 文件,还包含一个微型运行时,用来执行运行时工作。 [dynasm-rs](https://crates.io/crates/dynasm) 是对应的 Rust 实现,用过程宏在编译期解析汇编语法,也包含微型运行时。 Rust 过程宏作为编译器插件几乎是万能的,不光是汇编,html、shell、cpp 等语言都能嵌入,转换成对应的 Rust 结构,给人一种相当纯粹的感觉。过程宏还有很多用途,感兴趣的可以自行研究。 ```bash cargo add dynasm dynasmrt ``` 修改 main.rs,导入 dynasm. ```rust ,noplaypen mod bfir; use dynasm::dynasm; use dynasmrt::{DynasmApi, DynasmLabelApi}; use std::io::{stdout, Write}; ``` 编写 print 函数,使用 "sysv64" ABI。 x86-64 Linux 系统上默认为 System V ABI. [相关文档](https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI) ```rust ,noplaypen unsafe extern "sysv64" fn print(buf: *const u8, len: u64) -> u8 { let buf = std::slice::from_raw_parts(buf, len as usize); stdout().write_all(buf).is_err() as u8 } ``` 首先初始化汇编器,指定架构为 x64,全局标签 hello 指向字符串。 ```rust ,noplaypen fn main() { let mut ops = dynasmrt::x64::Assembler::new().unwrap(); let string = b"Hello, JIT!\n"; dynasm!(ops ; .arch x64 ; ->hello: ; .bytes string ); ``` dynasm 使用 nasm 的方言,左操作数为目标,右操作数为源。 sysv64 调用约定规定 rdi, rsi, rdx, rcx 存放前四个整数参数,rax 存放返回值。 ```rust ,noplaypen let hello = ops.offset(); dynasm!(ops ; lea rdi, [->hello] // 将 hello 字符串地址放入 rdi ; mov rsi, QWORD string.len() as _ // 将 字符串长度放入 rsi ; mov rax, QWORD print as _ // 将 print 函数地址放入 rax ; call rax // 调用函数 ; ret // 返回 ); ``` 完成汇编,取得可执行缓冲区。根据偏移拿到函数地址,强制转换为函数指针。最后调用机器码,得到结果。 ```rust ,noplaypen let buf = ops.finalize().unwrap(); let hello_fn: unsafe extern "sysv64" fn() -> u8 = unsafe { std::mem::transmute(buf.ptr(hello)) }; let ret = unsafe { hello_fn() }; assert_eq!(ret, 0); } ``` 运行结果 ```bash $ cargo run Finished dev [unoptimized + debuginfo] target(s) in 1.30s Running `target/debug/bfjit` Hello, JIT! ``` 完整代码 ```rust ,noplaypen mod bfir; use dynasm::dynasm; use dynasmrt::{DynasmApi, DynasmLabelApi}; use std::io::{stdout, Write}; unsafe extern "sysv64" fn print(buf: *const u8, len: u64) -> u8 { let buf = std::slice::from_raw_parts(buf, len as usize); stdout().write_all(buf).is_err() as u8 } fn main() { let mut ops = dynasmrt::x64::Assembler::new().unwrap(); let string = b"Hello, JIT!\n"; dynasm!(ops ; .arch x64 ; ->hello: ; .bytes string ); let hello = ops.offset(); dynasm!(ops ; lea rdi, [->hello] ; mov rsi, QWORD string.len() as _ ; mov rax, QWORD print as _ ; call rax ; ret ); let buf = ops.finalize().unwrap(); let hello_fn: unsafe extern "sysv64" fn() -> u8 = unsafe { std::mem::transmute(buf.ptr(hello)) }; let ret = unsafe { hello_fn() }; assert_eq!(ret, 0); } ``` ## 如何处理 panic 跨越 Rust 边界的 panic 是未定义行为,我们很难让汇编去匹配 unwind ABI。 暴露给外部调用的 Rust 函数最好捕获 panic,用其他方式去处理。 例如这样 ```rust unsafe extern "sysv64" fn print(buf: *const u8, len: u64) -> u8 { let ret = std::panic::catch_unwind(|| { let buf = std::slice::from_raw_parts(buf, len as usize); stdout().write_all(buf).is_err() }); match ret { Ok(false) => 0, Ok(true) => 1, Err(_) => 2, } } ``` ================================================ FILE: book/src/5.md ================================================ # 5. 来点错误 添加一个错误模块 src/main.rs ```rust ,noplaypen mod error; ``` src/error.rs ```rust ,noplaypen {{#include ../../src/error.rs}} ``` 虚拟机运行时可能出现两种错误,IO 错误和指针溢出。 虚拟机首先需要读取源代码,可能出现IO错误,然后将源代码编译为 IR,可能发生编译错误,最后运行程序,可能有运行时错误。 ================================================ FILE: book/src/6.md ================================================ # 6. 实现虚拟机 添加模块 src/bfjit.rs 导入必要的类型 ```rust,noplaypen {{#include ../../src/bfjit.rs:1:9}} ``` 虚拟机定义与 Brainfuck 机器模型一致。 机器码缓冲区,起始偏移,字节数组,输入输出流。 字节数组大小至少为 30000,这里设置为 4 MiB. ```rust,noplaypen {{#include ../../src/bfjit.rs:13:19}} ``` 准备汇编可调用的函数,brainfuck 通过 unsafe 函数与虚拟机交互。 为了传出可能的错误,把错误移动到堆上,返回裸指针。您也可以选择其他方式来传出错误。 在 FFI 时完善地处理 panic 和 backtrace 是一个复杂的问题。为了不增加过多处理代码,这里选择忽略 unsafe 函数中的 panic 问题。在代码正确的情况下,panic 应该不会发生。 请注意:跨语言的栈展开 (stack unwind) 是未定义行为,有可能引发段错误,您需要仔细研究 ABI 才能解决它。 ```rust,noplaypen {{#include ../../src/bfjit.rs:21:52}} ``` 用输入流、输出流、源文件路径初始化虚拟机,优化选项也由外部提供。 compile 方法暂时留空。 ```rust ,noplaypen impl BfVM<'_> { fn compile(code: &[BfIR]) -> Result<(dynasmrt::ExecutableBuffer, dynasmrt::AssemblyOffset)> { todo!() } ``` ```rust,noplaypen {{#include ../../src/bfjit.rs:54:79}} ``` 即时编译出的裸函数接收虚拟机指针和字节数组的边界指针,返回错误指针。 执行函数后检查错误指针,如果非空,就把错误从堆上移动到栈上再返回。 ```rust,noplaypen {{#include ../../src/bfjit.rs:81:102}} ``` ================================================ FILE: book/src/7.md ================================================ # 7. 生成机器码 完成上一节留空的 compile 方法。 整个 brainfuck 程序将被编译为一个大函数,在上一节的 run 方法中我们已经指定了该函数的签名。 ```rust,noplaypen type RawFn = unsafe extern "sysv64" fn( this: *mut BfVM<'_>, memory_start: *mut u8, memory_end: *const u8, ) -> *mut VMError; ``` 在 compile 方法中,首先初始化汇编器,函数起始地址就是最开始的偏移。 loops 作为栈,用来存放动态标签,指引跳转。 ```rust,noplaypen {{#include ../../src/bfjit.rs:104:110}} ``` sysv64 调用约定规定 rdi, rsi, rdx, rcx 存放前四个整数参数,rax 存放返回值,这些属于易失性寄存器,在调用子函数时其内容可能丢失。 rbp, rbx, r12 ~ r15 是非易失性寄存器,在调用子函数时不会丢失。如果函数中会占用这些寄存器,也要在开头和结尾相应地保存和恢复它们的内容。 我们在注释里记录函数会用到的所有寄存器。rdi, rsi, rdx 对应函数的三个参数,我们将其保存到 r12, r13, r14 寄存器。函数中需要一个 ptr 变量记录 brainfuck 程序的当前指针,我们使用 r15 寄存器。 ```rust,noplaypen {{#include ../../src/bfjit.rs:112:115}} ``` 汇编函数开始,首先把 rax 压栈。x86-64-psABI 规定参数区域的结尾按16字节对齐。函数开始时返回地址压栈,此时 栈指针+8 是 16 的倍数,因此再把 rax 压栈,使栈指针对齐,以便之后的函数调用,rax 的内容没有意义。 由于函数中用到 r12 ~ r15 非易失性寄存器,将其压栈保存。注意这里压入 4 个 8 字节寄存器,栈指针仍然对齐。 ```rust,noplaypen {{#include ../../src/bfjit.rs:117:127}} ``` 每个 IR 依次映射到汇编。 指针移动,需要检查算术溢出和数组边界溢出,出错即跳转到全局标签所指的错误处理区域。 ```rust,noplaypen {{#include ../../src/bfjit.rs:129:143}} ``` 单个字节的算术加减,允许溢出。 ```rust,noplaypen {{#include ../../src/bfjit.rs:144:149}} ``` IO 操作。首先保存当前数据指针寄存器,将虚拟机函数所需的各参数和函数地址放入寄存器,调用函数。 如果函数返回的不是空指针,说明出错,应该跳转到IO错误处理区域。 最后恢复数据指针寄存器。 ```rust,noplaypen {{#include ../../src/bfjit.rs:150:165}} ``` 跳转指令。利用 dynasm 提供的 api, 创建两个动态标签,分别生成跳转汇编。由于编译到 IR 时已经验证过跳转指令的对应关系,这里的栈可以直接弹出。 ```rust,noplaypen {{#include ../../src/bfjit.rs:166:186}} ``` 正常退出函数时应该返回空指针,表示没有错误。 溢出时生成一个溢出错误,IO错误时错误指针已经存入 rax,无需处理。 最后退栈,与函数开始时的压栈对应,维持栈平衡。注意退栈时不能破坏 rax 中的返回值。 ```rust,noplaypen {{#include ../../src/bfjit.rs:188:203}} ``` 完成汇编,取出可执行缓冲区,返回。 ```rust,noplaypen {{#include ../../src/bfjit.rs:205:210}} ``` ================================================ FILE: book/src/8.md ================================================ # 8. 命令行界面 虚拟机已经完成,剩下的就是把它包装成命令行界面 (CLI) 了。 我们使用 clap 库,用结构体定义命令行参数解析。 ```bash cargo add clap --features derive ``` 这就是 main.rs 的全部代码。 ```rust,noplaypen {{#include ../../src/main.rs}} ``` 把写好的命令行应用安装到系统。 ```bash $ cargo install --path . $ bfjit --help Usage: bfjit [OPTIONS] Arguments: Options: -o, --optimize Optimize code -h, --help Print help -V, --version Print version ``` 从 github 上找一些 brainfuck 程序运行,观察 JIT 与解释器的效率差别。 ```bash $ bfjit bf/hello.bf Hello World! ``` 观察折叠操作对速度的影响。 ```bash $ time bfjit bf/mendelbrot.bf > m.txt real 0m5.858s user 0m5.840s sys 0m0.012s $ time bfjit bf/mendelbrot.bf -o > m.txt real 0m1.921s user 0m1.903s sys 0m0.010s ``` 甚至可以运行一层 brainfuck 自解释器。 注意:多层自解释器的效率会严重下降,短时间内无法得出结果。 ================================================ FILE: book/src/SUMMARY.md ================================================ # Summary [介绍](introduction.md) - [背景知识](./1.md) - [启动项目](./2.md) - [中间表示](./3.md) - [Hello, JIT](./4.md) - [来点错误](./5.md) - [实现虚拟机](./6.md) - [生成机器码](./7.md) - [命令行界面](./8.md) [结语](./conclusion.md) ================================================ FILE: book/src/conclusion.md ================================================ # 结语 本教程基于 dynasm 实现了一个 Brainfuck JIT 虚拟机,主要功能有 Brainfuck 解析编译、简单优化、动态生成机器码,并提供了友好的命令行界面。 希望本项目对有兴趣深入研究 JIT 技术的人有所帮助。 欢迎 PR 来进一步改进本项目。 第三方依赖: ================================================ FILE: book/src/introduction.md ================================================ # Brainfuck JIT 虚拟机教程 当我们谈到 JIT 时,通常会想到 V8、JVM 之类的庞然大物,然后望而生畏,觉得 JIT 是一种极其高深复杂的技术。 但 JIT 也可以变得非常简单,我们不需要做完善的优化和分析,只要输入源码,输出机器指令,再执行,这和普通的文本处理程序没什么区别。 在本教程中,我们将用 Rust 语言实现一个简单的 Brainfuck JIT 虚拟机,逐步理解 JIT 技术。 ================================================ FILE: justfile ================================================ build: cd book && mdbook build serve: cd book && mdbook serve --open dev: just fmt just lint just test fmt *ARGS: cargo fmt --all {{ARGS}} lint *ARGS: cargo clippy --all-features --tests --benches {{ARGS}} test *ARGS: cargo test --all-features {{ARGS}} cargo run --release -- bf/hello.bf cargo run --release -- bf/hello.bf -o cargo run --release -- bf/mendelbrot.bf cargo run --release -- bf/mendelbrot.bf -o ci: just fmt --check just lint -- -D warnings just test ================================================ FILE: src/bfir.rs ================================================ use std::fmt; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BfIR { AddVal(u8), // + SubVal(u8), // - AddPtr(u32), // > SubPtr(u32), // < GetByte, // , PutByte, // . Jz, // [ Jnz, // ] } #[derive(Debug, thiserror::Error)] pub enum CompileErrorKind { #[error("Unclosed left bracket")] UnclosedLeftBracket, #[error("Unexpected right bracket")] UnexpectedRightBracket, } #[derive(Debug)] pub struct CompileError { line: u32, col: u32, kind: CompileErrorKind, } impl fmt::Display for CompileError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} at line {}:{}", self.kind, self.line, self.col) } } impl std::error::Error for CompileError {} pub fn compile(src: &str) -> Result, CompileError> { let mut code: Vec = vec![]; let mut stk: Vec<(u32, u32, u32)> = vec![]; let mut line: u32 = 1; let mut col: u32 = 0; for ch in src.chars() { col += 1; match ch { '\n' => { line += 1; col = 0; } '+' => code.push(BfIR::AddVal(1)), '-' => code.push(BfIR::SubVal(1)), '>' => code.push(BfIR::AddPtr(1)), '<' => code.push(BfIR::SubPtr(1)), ',' => code.push(BfIR::GetByte), '.' => code.push(BfIR::PutByte), '[' => { let pos = code.len() as u32; stk.push((pos, line, col)); code.push(BfIR::Jz) } ']' => { stk.pop().ok_or(CompileError { line, col, kind: CompileErrorKind::UnexpectedRightBracket, })?; code.push(BfIR::Jnz) } _ => {} } } if let Some((_, line, col)) = stk.pop() { return Err(CompileError { line, col, kind: CompileErrorKind::UnclosedLeftBracket, }); } Ok(code) } pub fn optimize(code: &mut Vec) { let len = code.len(); let mut i = 0; let mut pc = 0; macro_rules! _fold_ir { ($variant:ident, $x:ident) => {{ let mut j = i + 1; while j < len { if let $variant(d) = code[j] { $x = $x.wrapping_add(d); } else { break; } j += 1; } i = j; code[pc] = $variant($x); pc += 1; }}; } macro_rules! _normal_ir { () => {{ code[pc] = code[i]; pc += 1; i += 1; }}; } use BfIR::*; while i < len { match code[i] { AddPtr(mut x) => _fold_ir!(AddPtr, x), SubPtr(mut x) => _fold_ir!(SubPtr, x), AddVal(mut x) => _fold_ir!(AddVal, x), SubVal(mut x) => _fold_ir!(SubVal, x), GetByte => _normal_ir!(), PutByte => _normal_ir!(), Jz => _normal_ir!(), Jnz => _normal_ir!(), } } code.truncate(pc); code.shrink_to_fit(); } #[test] fn test_compile() { assert_eq!( compile("+[,.]").unwrap(), vec![ BfIR::AddVal(1), BfIR::Jz, BfIR::GetByte, BfIR::PutByte, BfIR::Jnz, ] ); match compile("[").unwrap_err().kind { CompileErrorKind::UnclosedLeftBracket => {} _ => panic!(), }; match compile("]").unwrap_err().kind { CompileErrorKind::UnexpectedRightBracket => {} _ => panic!(), }; let mut code = compile("[+++++]").unwrap(); optimize(&mut code); assert_eq!(code, vec![BfIR::Jz, BfIR::AddVal(5), BfIR::Jnz]); } ================================================ FILE: src/bfjit.rs ================================================ use crate::bfir::{self, BfIR}; use crate::error::{Result, RuntimeError, VMError}; use std::io::{Read, Write}; use std::path::Path; use std::ptr; use dynasm::dynasm; use dynasmrt::{DynasmApi, DynasmLabelApi}; const MEMORY_SIZE: usize = 4 * 1024 * 1024; pub struct BfVM<'io> { code: dynasmrt::ExecutableBuffer, start: dynasmrt::AssemblyOffset, memory: Box<[u8]>, input: Box, output: Box, } #[inline(always)] fn vm_error(re: RuntimeError) -> *mut VMError { let e = Box::new(VMError::from(re)); Box::into_raw(e) } impl BfVM<'_> { unsafe extern "sysv64" fn getbyte(this: *mut Self, ptr: *mut u8) -> *mut VMError { let mut buf = [0_u8]; let this = &mut *this; match this.input.read(&mut buf) { Ok(0) => {} Ok(1) => *ptr = buf[0], Err(e) => return vm_error(RuntimeError::IO(e)), _ => unreachable!(), } ptr::null_mut() } unsafe extern "sysv64" fn putbyte(this: *mut Self, ptr: *const u8) -> *mut VMError { let buf = std::slice::from_ref(&*ptr); let this = &mut *this; match this.output.write_all(buf) { Ok(()) => ptr::null_mut(), Err(e) => vm_error(RuntimeError::IO(e)), } } unsafe extern "sysv64" fn overflow_error() -> *mut VMError { vm_error(RuntimeError::PointerOverflow) } } impl<'io> BfVM<'io> { pub fn new( file_path: &Path, input: Box, output: Box, optimize: bool, ) -> Result { let src = std::fs::read_to_string(file_path)?; let mut ir = bfir::compile(&src)?; drop(src); if optimize { bfir::optimize(&mut ir); } let (code, start) = Self::compile(&ir)?; drop(ir); let memory = vec![0; MEMORY_SIZE].into_boxed_slice(); Ok(Self { code, start, memory, input, output, }) } pub fn run(&mut self) -> Result<()> { type RawFn = unsafe extern "sysv64" fn( this: *mut BfVM<'_>, memory_start: *mut u8, memory_end: *const u8, ) -> *mut VMError; let raw_fn: RawFn = unsafe { std::mem::transmute(self.code.ptr(self.start)) }; let this: *mut Self = self; let memory_start = self.memory.as_mut_ptr(); let memory_end = unsafe { memory_start.add(MEMORY_SIZE) }; let ret: *mut VMError = unsafe { raw_fn(this, memory_start, memory_end) }; if ret.is_null() { Ok(()) } else { Err(*unsafe { Box::from_raw(ret) }) } } } impl BfVM<'_> { #[allow(clippy::fn_to_numeric_cast)] fn compile(code: &[BfIR]) -> Result<(dynasmrt::ExecutableBuffer, dynasmrt::AssemblyOffset)> { let mut ops = dynasmrt::x64::Assembler::new()?; let start = ops.offset(); let mut loops = vec![]; // this: rdi r12 // memory_start: rsi r13 // memory_end: rdx r14 // ptr: r15 dynasm!(ops ; push rax ; push r12 ; push r13 ; push r14 ; push r15 ; mov r12, rdi // save this ; mov r13, rsi // save memory_start ; mov r14, rdx // save memory_end ; mov r15, rsi // ptr = memory_start ); use BfIR::*; for &ir in code { match ir { AddPtr(x) => dynasm!(ops ; add r15, x as i32 // ptr += x ; jc ->overflow // jmp if overflow ; cmp r15, r14 // ptr - memory_end ; jnb ->overflow // jmp if ptr >= memory_end ), SubPtr(x) => dynasm!(ops ; sub r15, x as i32 // ptr -= x ; jc ->overflow // jmp if overflow ; cmp r15, r13 // ptr - memory_start ; jb ->overflow // jmp if ptr < memory_start ), AddVal(x) => dynasm!(ops ; add BYTE [r15], x as i8 // *ptr += x ), SubVal(x) => dynasm!(ops ; sub BYTE [r15], x as i8 // *ptr -= x ), GetByte => dynasm!(ops ; mov rdi, r12 // arg0: this ; mov rsi, r15 // arg1: ptr ; mov rax, QWORD BfVM::getbyte as *const () as _ ; call rax // getbyte(this, ptr) ; test rax, rax ; jnz ->io_error // jmp if rax != 0 ), PutByte => dynasm!(ops ; mov rdi, r12 // arg0: this ; mov rsi, r15 // arg1: ptr ; mov rax, QWORD BfVM::putbyte as *const () as _ ; call rax // putbyte(this, ptr) ; test rax, rax ; jnz ->io_error // jmp if rax != 0 ), Jz => { let left = ops.new_dynamic_label(); let right = ops.new_dynamic_label(); loops.push((left, right)); dynasm!(ops ; cmp BYTE [r15], 0 ; jz => right // jmp if *ptr == 0 ; => left ) } Jnz => { let (left, right) = loops.pop().unwrap(); dynasm!(ops ; cmp BYTE [r15], 0 ; jnz => left // jmp if *ptr != 0 ; => right ) } } } dynasm!(ops ; xor rax, rax ; jmp >exit ; -> overflow: ; mov rax, QWORD BfVM::overflow_error as *const () as _ ; call rax ; jmp >exit ; -> io_error: ; exit: ; pop r15 ; pop r14 ; pop r13 ; pop r12 ; pop rdx ; ret ); let code = ops.finalize().unwrap(); Ok((code, start)) } } ================================================ FILE: src/error.rs ================================================ #[derive(Debug, thiserror::Error)] pub enum RuntimeError { #[error("IO: {0}")] IO(#[from] std::io::Error), #[error("Pointer overflow")] PointerOverflow, } #[derive(Debug, thiserror::Error)] pub enum VMError { #[error("IO: {0}")] IO(#[from] std::io::Error), #[error("Compile: {0}")] Compile(#[from] crate::bfir::CompileError), #[error("Runtime: {0}")] Runtime(#[from] RuntimeError), } pub type Result = std::result::Result; ================================================ FILE: src/main.rs ================================================ mod bfir; mod bfjit; mod error; use crate::bfjit::BfVM; use std::io::{stdin, stdout}; use std::path::PathBuf; use clap::Parser; #[derive(Debug, clap::Parser)] #[clap(version)] struct Opt { #[clap(name = "FILE")] file_path: PathBuf, #[clap(short = 'o', long = "optimize", help = "Optimize code")] optimize: bool, } fn main() { let opt = Opt::parse(); let stdin = stdin(); let stdout = stdout(); let ret = BfVM::new( &opt.file_path, Box::new(stdin.lock()), Box::new(stdout.lock()), opt.optimize, ) .and_then(|mut vm| vm.run()); if let Err(e) = &ret { eprintln!("bfjit: {e}"); } std::process::exit(ret.is_err() as i32) }