From 2ed275821676a0d5baea6c7fd843d71c72c2342c Mon Sep 17 00:00:00 2001 From: Freya Murphy Date: Mon, 9 Sep 2024 12:41:49 -0400 Subject: [PATCH] initial mips32 (r2000ish mips32r6) assembler --- .gitignore | 1 + LICENSE | 674 +++++++++++++++++++++++++++++++++++ README.md | 5 + compile_flags.txt | 7 + config.mk | 24 ++ include/merror.h | 37 ++ include/mips.h | 16 + include/mips32.h | 496 ++++++++++++++++++++++++++ include/mlimits.h | 21 ++ lib/error.c | 53 +++ makefile.mk | 32 ++ masm/: | 363 +++++++++++++++++++ masm/Makefile | 7 + masm/asm.h | 33 ++ masm/asm_mips32.c | 365 +++++++++++++++++++ masm/lex.c | 343 ++++++++++++++++++ masm/lex.h | 55 +++ masm/main.c | 9 + masm/parse.c | 198 +++++++++++ masm/parse.h | 156 ++++++++ masm/parse_mips32.c | 847 ++++++++++++++++++++++++++++++++++++++++++++ masm/parse_mips32.h | 14 + masm/reftbl.c | 47 +++ masm/sectbl.c | 103 ++++++ masm/strtbl.c | 49 +++ masm/symtbl.c | 57 +++ masm/test.asm | 22 ++ 27 files changed, 4034 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 compile_flags.txt create mode 100644 config.mk create mode 100644 include/merror.h create mode 100644 include/mips.h create mode 100644 include/mips32.h create mode 100644 include/mlimits.h create mode 100644 lib/error.c create mode 100644 makefile.mk create mode 100644 masm/: create mode 100644 masm/Makefile create mode 100644 masm/asm.h create mode 100644 masm/asm_mips32.c create mode 100644 masm/lex.c create mode 100644 masm/lex.h create mode 100644 masm/main.c create mode 100644 masm/parse.c create mode 100644 masm/parse.h create mode 100644 masm/parse_mips32.c create mode 100644 masm/parse_mips32.h create mode 100644 masm/reftbl.c create mode 100644 masm/sectbl.c create mode 100644 masm/strtbl.c create mode 100644 masm/symtbl.c create mode 100644 masm/test.asm diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ba077a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +bin diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + 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 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..74a0a26 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +### mips toolchain + +lots to do still + +do not use the diff --git a/compile_flags.txt b/compile_flags.txt new file mode 100644 index 0000000..545b1ad --- /dev/null +++ b/compile_flags.txt @@ -0,0 +1,7 @@ +-c +-std=c2x +-Wall +-Wextra +-pedantic +-Wno-gnu-binary-literal +-Iinclude diff --git a/config.mk b/config.mk new file mode 100644 index 0000000..682002b --- /dev/null +++ b/config.mk @@ -0,0 +1,24 @@ +# ======================= COMPILE OPTIONS == + +CC=cc +LD=cc + +CFLAGS += -pipe +CFLAGS += -Wall -Wextra -pedantic +CFLAGS += -O3 -g + +# ======================== CONFIG OPTIONS == +# +# MAX LEX LENGTH +# Specifies how long a ident, register, +# instruction name, or any type of variable +# length text can be inside the lexer +# +# CFLAGS+= -DMAX_LEX_LENGTH=24 +# +# +# MAX_ARG_LENGTH +# Specifies how many max arguments a given +# directive can hold +# +# CFLAGS+= -DMAX_ARG_LENGTH=12 diff --git a/include/merror.h b/include/merror.h new file mode 100644 index 0000000..727111d --- /dev/null +++ b/include/merror.h @@ -0,0 +1,37 @@ +/* Copyright (c) 2024 Freya Murphy */ +#ifndef __MERROR_H__ +#define __MERROR_H__ + +/* Error codes + */ +#define M_SUCCESS 0 +#define M_EOF 1 +#define M_ERROR -1 + +#define __DEBUG 1 +#define __WARNING 2 +#define __ERROR 3 + +__attribute__((format(printf, 4, 5))) +void __log_impl_pos(int line, int column, int type, const char *format, ...); +void __log_impl(int type, const char *format, ...); + +#define DEBUG(format, ...) \ + __log_impl(__DEBUG, format, ##__VA_ARGS__) + +#define WARNING(format, ...) \ + __log_impl(__WARNING, format, ##__VA_ARGS__) + +#define ERROR(format, ...) \ + __log_impl(__ERROR, format, ##__VA_ARGS__) + +#define DEBUG_POS(pos, format, ...) \ + __log_impl_pos(pos.y, pos.x, __DEBUG, format, ##__VA_ARGS__) + +#define WARNING_POS(pos, format, ...) \ + __log_impl_pos(pos.y, pos.x, __WARNING, format, ##__VA_ARGS__) + +#define ERROR_POS(pos, format, ...) \ + __log_impl_pos(pos.y, pos.x, __ERROR, format, ##__VA_ARGS__) + +#endif /* __MERROR_H__ */ diff --git a/include/mips.h b/include/mips.h new file mode 100644 index 0000000..79b516b --- /dev/null +++ b/include/mips.h @@ -0,0 +1,16 @@ +/* Copyright (c) 2024 Freya Murphy */ + +#ifndef __MIPS_H__ +#define __MIPS_H__ + +#include + +union mips_instruction { + struct mips32_instruction mips32; +}; + +union mips_directive { + struct mips32_directive mips32; +}; + +#endif /* __MIPS_H */ diff --git a/include/mips32.h b/include/mips32.h new file mode 100644 index 0000000..ce0e997 --- /dev/null +++ b/include/mips32.h @@ -0,0 +1,496 @@ +/* Copyright (c) 2024 Freya Murphy */ + +#ifndef __MIPS32_H__ +#define __MIPS32_H__ + +#include +#include + +/* all mips registers $0-$31 */ +enum mips32_register { + MIPS32_REG_ZERO = 0, + MIPS32_REG_AT = 1, + MIPS32_REG_V0 = 2, + MIPS32_REG_V1 = 3, + MIPS32_REG_A0 = 4, + MIPS32_REG_A1 = 5, + MIPS32_REG_A2 = 6, + MIPS32_REG_A3 = 7, + MIPS32_REG_T0 = 8, + MIPS32_REG_T1 = 9, + MIPS32_REG_T2 = 10, + MIPS32_REG_T3 = 11, + MIPS32_REG_T4 = 12, + MIPS32_REG_T5 = 13, + MIPS32_REG_T6 = 14, + MIPS32_REG_T7 = 15, + MIPS32_REG_S0 = 16, + MIPS32_REG_S1 = 17, + MIPS32_REG_S2 = 18, + MIPS32_REG_S3 = 19, + MIPS32_REG_S4 = 20, + MIPS32_REG_S5 = 21, + MIPS32_REG_S6 = 22, + MIPS32_REG_S7 = 23, + MIPS32_REG_T8 = 24, + MIPS32_REG_T9 = 25, + MIPS32_REG_K0 = 26, + MIPS32_REG_K1 = 27, + MIPS32_REG_GP = 28, + MIPS32_REG_SP = 29, + MIPS32_REG_FP = 30, + MIPS32_REG_RA = 31, +}; + +/* mips instruction format */ +enum mips32_instruction_format { + MIPS32_FORMAT_R, + MIPS32_FORMAT_I, + MIPS32_FORMAT_J, + MIPS32_FORMAT_B, +}; + +/* mips instructions */ +enum mips32_instruction_type { + MIPS32_INS_ADD, + MIPS32_INS_ADDI, + MIPS32_INS_ADDIU, + MIPS32_INS_ADDU, + MIPS32_INS_AND, + MIPS32_INS_ANDI, + MIPS32_INS_BAL, + MIPS32_INS_BALC, + MIPS32_INS_BC, + MIPS32_INS_BEQ, + MIPS32_INS_BEQL, + MIPS32_INS_BGEZ, + MIPS32_INS_BGEZAL, + MIPS32_INS_BGEZALL, + MIPS32_INS_BGEZL, + MIPS32_INS_BGTZ, + MIPS32_INS_BGTZL, + MIPS32_INS_BLEZ, + MIPS32_INS_BLEZL, + MIPS32_INS_BLTZ, + MIPS32_INS_BLTZAL, + MIPS32_INS_BLTZALL, + MIPS32_INS_BLTZL, + MIPS32_INS_BNE, + MIPS32_INS_BNEL, + MIPS32_INS_DDIV, + MIPS32_INS_DDIVU, + MIPS32_INS_DIV, + MIPS32_INS_DIVU, + MIPS32_INS_J, + MIPS32_INS_JAL, + MIPS32_INS_JALR, + MIPS32_INS_JALX, + MIPS32_INS_JR, + MIPS32_INS_LB, + MIPS32_INS_LBU, + MIPS32_INS_LH, + MIPS32_INS_LHU, + MIPS32_INS_LUI, + MIPS32_INS_LW, + MIPS32_INS_LWL, + MIPS32_INS_LWR, + MIPS32_INS_MFHI, + MIPS32_INS_MFLO, + MIPS32_INS_MTHI, + MIPS32_INS_MTLO, + MIPS32_INS_MULT, + MIPS32_INS_MULTU, + MIPS32_INS_SB, + MIPS32_INS_SH, + MIPS32_INS_SW, + MIPS32_INS_SWL, + MIPS32_INS_SWR, + MIPS32_INS_SLL, + MIPS32_INS_SLLV, + MIPS32_INS_SLT, + MIPS32_INS_SLTI, + MIPS32_INS_SLTIU, + MIPS32_INS_SLTU, + MIPS32_INS_SRA, + MIPS32_INS_SRAV, + MIPS32_INS_SRL, + MIPS32_INS_SRLV, + MIPS32_INS_SUB, + MIPS32_INS_SUBU, + MIPS32_INS_OR, + MIPS32_INS_ORI, + MIPS32_INS_NOR, + MIPS32_INS_XOR, + MIPS32_INS_XORI, + // gets the size of the enum + __MIPS32_INS_LEN, +}; + +/* mips instruction R TYPE */ +struct mips32_instruction_r_data { + uint32_t funct : 6; + uint32_t shamt : 5; + uint32_t rd : 5; + uint32_t rt : 5; + uint32_t rs : 5; + uint32_t op : 6; +} __attribute__((packed)); + +/* mips instruction I TYPE */ +struct mips32_instruction_i_data { + uint32_t immd : 16; + uint32_t rt : 5; + uint32_t rs : 5; + uint32_t op : 6; +} __attribute__((packed)); + +/* mips instruction J TYPE */ +struct mips32_instruction_j_data { + uint32_t target : 26; + uint32_t op : 6; +} __attribute__((packed)); + +/* mips instruction BRANCH TYPE */ +struct mips32_instruction_branch_data { + int32_t offset : 16; + uint32_t funct : 5; + uint32_t rs : 5; + uint32_t op : 6; +} __attribute__((packed)); + +/* mips instruction information */ +struct mips32_instruction { + // metadata + enum mips32_instruction_type type; + enum mips32_instruction_format format; + const char *name; + + // data + union { + uint32_t data; + struct mips32_instruction_r_data R_data; + struct mips32_instruction_i_data I_data; + struct mips32_instruction_j_data J_data; + struct mips32_instruction_branch_data B_data; + } __attribute__((packed)); +}; + + +#define MIPS32_INS(ins, format, ...) \ + [MIPS32_INS_ ##ins] = { \ + MIPS32_INS_ ##ins, \ + MIPS32_FORMAT_ ##format, \ + #ins, \ + .format##_data = { __VA_ARGS__ } \ + }, \ + +static const struct mips32_instruction mips32_instructions[] = { +/* ADD - add */ +#define MIPS32_OP_SPECIAL 0b000000 +#define MIPS32_FUNCT_ADD 0b100000 +MIPS32_INS(ADD, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_ADD) + +/* ADDI - add immediate */ +#define MIPS32_OP_ADDI 0b001000 +MIPS32_INS(ADDI, I, .op = MIPS32_OP_ADDI) + +/* ADDIU - add immediate unsigned */ +#define MIPS32_OP_ADDIU 0b001001 +MIPS32_INS(ADDIU, I, .op = MIPS32_OP_ADDIU) + +/* ADDU - add unsigned */ +#define MIPS32_FUNCT_ADDU 0b100001 +MIPS32_INS(ADDU, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_ADDU) + +/* AND - and */ +#define MIPS32_FUNCT_AND 0b100100 +MIPS32_INS(AND, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_AND) + +/* ANDI - and immediate */ +#define MIPS32_OP_ANDI 0b001100 +MIPS32_INS(ANDI, I, .op = MIPS32_OP_ANDI) + +/* BAL - branch and link */ +#define MIPS32_OP_REGIMM 0b000001 +#define MIPS32_FUNCT_BAL 0b10001 +MIPS32_INS(BAL, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BAL) + +/* BALC - branch and link, compact */ +#define MIPS32_OP_BALC 0b111010 +MIPS32_INS(BALC, J, .op = MIPS32_OP_BALC) + +/* BC - branch, compact */ +#define MIPS32_OP_BC 0b110010 +MIPS32_INS(BC, J, .op = MIPS32_OP_BC) + +/* BEQ - branch on equal */ +#define MIPS32_OP_BEQ 0b000100 +MIPS32_INS(BEQ, I, .op = MIPS32_OP_BEQ) + +/* BEQL - branch on equal likely */ +#define MIPS32_OP_BEQL 0b010100 +MIPS32_INS(BEQL, I, .op = MIPS32_OP_BEQL) + +/* BGEZ - branch on greater than or equal to zero */ +#define MIPS32_FUNCT_BGEZ 0b00001 +MIPS32_INS(BGEZ, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BGEZ) + +/* BGEZAL - branch on greater than or equal to zero and link */ +#define MIPS32_FUNCT_BGEZAL 0b10001 +MIPS32_INS(BGEZAL, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BGEZAL) + +/* BGEZAL - branch on greater than or equal to zero and link likely */ +#define MIPS32_FUNCT_BGEZALL 0b10011 +MIPS32_INS(BGEZALL, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BGEZALL) + +/* BGEZL - branch on greater than or equal to zero likely */ +#define MIPS32_FUNCT_BGEZL 0b00011 +MIPS32_INS(BGEZL, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BGEZL) + +/* BGTZ - branch on greater than zero */ +#define MIPS32_OP_BGTZ 0b000111 +MIPS32_INS(BGTZ, I, .op = MIPS32_OP_BGTZ) + +/* BGTZL - branch on greater than zero likely */ +#define MIPS32_OP_BGTZL 0b010111 +MIPS32_INS(BGTZL, I, .op = MIPS32_OP_BGTZL) + +/* BLEZ - branch on less than or equal to zero */ +#define MIPS32_OP_BLEZ 0b000110 +MIPS32_INS(BLEZ, I, .op = MIPS32_OP_BLEZ) + +/* BLEZL - branch on less than or equal to zero likely */ +#define MIPS32_OP_BLEZL 0b010110 +MIPS32_INS(BLEZL, I, .op = MIPS32_OP_BLEZL) + +/* BLTZ - branch on less than zero */ +#define MIPS32_FUNCT_BLTZ 0b00000 +MIPS32_INS(BLTZ, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BLTZ) + +/* BLTZAL - branch on less than zero and link */ +#define MIPS32_FUNCT_BLTZAL 0b10000 +MIPS32_INS(BLTZAL, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BLTZAL) + +/* BLTZALL - branch on less than zero and link likely */ +#define MIPS32_FUNCT_BLTZALL 0b10010 +MIPS32_INS(BLTZALL, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BLTZALL) + +/* BLTZL - branch on less than zero likely */ +#define MIPS32_FUNCT_BLTZL 0b00010 +MIPS32_INS(BLTZL, B, .op = MIPS32_OP_REGIMM, .funct = MIPS32_FUNCT_BLTZL) + +/* BNE - branch on not equal */ +#define MIPS32_OP_BNE 0b000101 +MIPS32_INS(BNE, I, .op = MIPS32_OP_BNE) + +/* BNEL - branch on not equal likely */ +#define MIPS32_OP_BNEL 0b010101 +MIPS32_INS(BNEL, I, .op = MIPS32_OP_BNEL) + +/* DDIV - doubleword divide */ +#define MIPS32_FUNCT_DDIV 0b011110 +MIPS32_INS(DDIV, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_DDIV) + +/* DDIVU - doubleword divide unsigned */ +#define MIPS32_FUNCT_DDIVU 0b011111 +MIPS32_INS(DDIVU, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_DDIVU) + +/* DIV - divide */ +#define MIPS32_FUNCT_DIV 0b011010 +MIPS32_INS(DIV, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_DIV) + +/* DIVU - divide unsigned */ +#define MIPS32_FUNCT_DIVU 0b011011 +MIPS32_INS(DIVU, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_DIVU) + +/* J - jump */ +#define MIPS32_OP_J 0b000010 +MIPS32_INS(J, J, .op = MIPS32_OP_J) + +/* JAL - jump and link */ +#define MIPS32_OP_JAL 0b000011 +MIPS32_INS(JAL, J, .op = MIPS32_OP_JAL) + +/* JALR - jump and link register */ +#define MIPS32_FUNCT_JALR 0b001001 +MIPS32_INS(JALR, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_JALR) + +/* JALX - jump and link exchange */ +#define MIPS32_OP_JALX 0b011101 +MIPS32_INS(JALX, J, .op = MIPS32_OP_JALX) + +/* JR - jump register */ +#define MIPS32_FUNCT_JR 0b001000 +MIPS32_INS(JR, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_JR) + +/* LB - load byte */ +#define MIPS32_OP_LB 0b100000 +MIPS32_INS(LB, I, .op = MIPS32_OP_LB) + +/* LBU - load byte unsigned */ +#define MIPS32_OP_LBU 0b100100 +MIPS32_INS(LBU, I, .op = MIPS32_OP_LBU) + +/* LH - load half */ +#define MIPS32_OP_LH 0b100001 +MIPS32_INS(LH, I, .op = MIPS32_OP_LH) + +/* LHU - load half unsigned */ +#define MIPS32_OP_LHU 0b100101 +MIPS32_INS(LHU, I, .op = MIPS32_OP_LHU) + +/* LUI - load upper immediate */ +#define MIPS32_OP_LUI 0b001111 +MIPS32_INS(LUI, I, .op = MIPS32_OP_LUI) + +/* LW - load word */ +#define MIPS32_OP_LW 0b100011 +MIPS32_INS(LW, I, .op = MIPS32_OP_LW) + +/* LWL - load word left */ +#define MIPS32_OP_LWL 0b100010 +MIPS32_INS(LWL, I, .op = MIPS32_OP_LWL) + +/* LWR - load word right */ +#define MIPS32_OP_LWR 0b100110 +MIPS32_INS(LWR, I, .op = MIPS32_OP_LWR) + +/* MFHI - move from hi */ +#define MIPS32_FUNCT_MFHI 0b010000 +MIPS32_INS(MFHI, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_MFHI) + +/* MFLO - move from hi */ +#define MIPS32_FUNCT_MFLO 0b010010 +MIPS32_INS(MFLO, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_MFLO) + +/* MTHI - move from hi */ +#define MIPS32_FUNCT_MTHI 0b010001 +MIPS32_INS(MTHI, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_MTHI) + +/* MTLO - move from hi */ +#define MIPS32_FUNCT_MTLO 0b010011 +MIPS32_INS(MTLO, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_MTLO) + +/* MULT - multiply */ +#define MIPS32_FUNCT_MULT 0b011000 +MIPS32_INS(MULT, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_MULT) + +/* MULTU - multiply unsigned */ +#define MIPS32_FUNCT_MULTU 0b011001 +MIPS32_INS(MULTU, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_MULTU) + +/* SB - store byte */ +#define MIPS32_OP_SB 0b101000 +MIPS32_INS(SB, I, .op = MIPS32_OP_SB) + +/* SH - store half */ +#define MIPS32_OP_SH 0b101001 +MIPS32_INS(SH, I, .op = MIPS32_OP_SH) + +/* SW - store word */ +#define MIPS32_OP_SW 0b101011 +MIPS32_INS(SW, I, .op = MIPS32_OP_SW) + +/* SWL - store word left */ +#define MIPS32_OP_SWL 0b101010 +MIPS32_INS(SWL, I, .op = MIPS32_OP_SWL) + +/* SWR - store word right */ +#define MIPS32_OP_SWR 0b101110 +MIPS32_INS(SWR, I, .op = MIPS32_OP_SWR) + +/* SLL - shift left logical */ +#define MIPS32_FUNCT_SLL 0b000000 +MIPS32_INS(SLL, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SLL) + +/* SLLV - shift left logical variable */ +#define MIPS32_FUNCT_SLLV 0b000100 +MIPS32_INS(SLLV, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SLLV) + +/* SLT - set less then */ +#define MIPS32_FUNCT_SLT 0b101010 +MIPS32_INS(SLT, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SLT) + +/* SLTI - set less then immediate */ +#define MIPS32_OP_SLTI 0b001010 +MIPS32_INS(SLTI, I, .op = MIPS32_OP_SLTI) + +/* SLTIU - set less then imemdiate unsigned */ +#define MIPS32_OP_SLTIU 0b001011 +MIPS32_INS(SLTIU, I, .op = MIPS32_OP_SLTIU) + +/* SLTU - set less than unsigned */ +#define MIPS32_FUNCT_SLTU 0b101011 +MIPS32_INS(SLTU, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SLTU) + +/* SRA - shift right arithmetic */ +#define MIPS32_FUNCT_SRA 0b000011 +MIPS32_INS(SRA, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SRA) + +/* SRAV - shift right arithmetic variable */ +#define MIPS32_FUNCT_SRAV 0b000111 +MIPS32_INS(SRAV, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SRAV) + +/* SRL - shift right logical */ +#define MIPS32_FUNCT_SRL 0b000010 +MIPS32_INS(SRL, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SRL) + +/* SRLV - shift right logical variable */ +#define MIPS32_FUNCT_SRLV 0b000110 +MIPS32_INS(SRLV, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SRLV) + +/* SUB - subtract */ +#define MIPS32_FUNCT_SUB 0b100010 +MIPS32_INS(SUB, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SUB) + +/* SUBU - subtract unsigned */ +#define MIPS32_FUNCT_SUBU 0b100011 +MIPS32_INS(SUBU, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_SUBU) + +/* OR - or */ +#define MIPS32_FUNCT_OR 0b100101 +MIPS32_INS(OR, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_OR) + +/* ORI - or imemdiate */ +#define MIPS32_OP_ORI 0b001101 +MIPS32_INS(ORI, I, .op = MIPS32_OP_ORI) + +/* NOR - not or */ +#define MIPS32_FUNCT_NOR 0b100111 +MIPS32_INS(NOR, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_NOR) + +/* XOR - exclusive or */ +#define MIPS32_FUNCT_XOR 0b100110 +MIPS32_INS(XOR, R, .op = MIPS32_OP_SPECIAL, .funct = MIPS32_FUNCT_XOR) + +/* XORI - exclusive or immediate */ +#define MIPS32_OP_XORI 0b001110 +MIPS32_INS(XORI, I, .op = MIPS32_OP_XORI) +}; + +#undef MIPS32_INS + +/* mips32 directive types */ +enum mips32_directive_type { + MIPS32_DIRECTIVE_ALIGN, + MIPS32_DIRECTIVE_SPACE, + MIPS32_DIRECTIVE_WORD, + MIPS32_DIRECTIVE_HALF, + MIPS32_DIRECTIVE_BYTE, + MIPS32_DIRECTIVE_SECTION, +}; + +/* mip32 directive */ +struct mips32_directive { + enum mips32_directive_type type; + union { + uint16_t align; + uint16_t space; + uint32_t words[MAX_ARG_LENGTH]; + uint16_t halfs[MAX_ARG_LENGTH]; + uint8_t bytes[MAX_ARG_LENGTH]; + char name[MAX_ARG_LENGTH]; + }; +}; + +#endif /* __MIPS32_H__ */ diff --git a/include/mlimits.h b/include/mlimits.h new file mode 100644 index 0000000..12318be --- /dev/null +++ b/include/mlimits.h @@ -0,0 +1,21 @@ +/* Copyright (c) 2024 Freya Murphy */ + +#ifndef __MLIMITS_H__ +#define __MLIMITS_H__ + +/* Specifies how long a ident, register, + * instruction name, or any type of variable + * length text can be inside the lexer. + */ +#ifndef MAX_LEX_LENGTH +#define MAX_LEX_LENGTH 24 +#endif + +/* Specifices how many max arguments a + * given directive can hold + */ +#ifndef MAX_ARG_LENGTH +#define MAX_ARG_LENGTH 12 +#endif + +#endif /* __MLIMITS_H__ */ diff --git a/lib/error.c b/lib/error.c new file mode 100644 index 0000000..78f75ef --- /dev/null +++ b/lib/error.c @@ -0,0 +1,53 @@ +#include +#include +#include + +char *current_file = "file.asm"; + +__attribute__((format(printf, 4, 5))) +void __log_impl_pos(int line, int column, int type, const char *format, ...) +{ + va_list list; + va_start(list, format); + + char *t = NULL; + switch (type) { + case __DEBUG: + t = "\033[34mdebug:\033[0m"; + break; + case __WARNING: + t = "\033[35mwarning:\033[0m"; + break; + case __ERROR: + t = "\033[31merror:\033[0m"; + break; + } + + printf("%s:%d:%d: %s ", current_file, line, column, t); + vprintf(format, list); + putchar('\n'); +} + +__attribute__((format(printf, 2, 3))) +void __log_impl(int type, const char *format, ...) +{ + va_list list; + va_start(list, format); + + char *t = NULL; + switch (type) { + case __DEBUG: + t = "\033[34mdebug:\033[0m"; + break; + case __WARNING: + t = "\033[35mwarning:\033[0m"; + break; + case __ERROR: + t = "\033[31merror:\033[0m"; + break; + } + + printf("%s ", t); + vprintf(format, list); + putchar('\n'); +} diff --git a/makefile.mk b/makefile.mk new file mode 100644 index 0000000..afcfda7 --- /dev/null +++ b/makefile.mk @@ -0,0 +1,32 @@ + +# needed cflags +CFLAGS += -std=c2x + +# add include directory +CFLAGS += -isystem ../include +INCLUDE += ../include + +# add lib directory +SRC += ../lib + +H_SRC = $(shell find $(SRC) $(INCLUDE) -type f -name "*.h") +C_SRC = $(shell find $(SRC) -type f -name "*.c") +C_OBJ = $(patsubst %.c,$(BIN)/%.o,$(C_SRC)) + +.PHONY: clean build run + +build: $(BIN)/$(OUT) + +clean: + rm -fr $(BIN) + +run: build + $(BIN)/$(OUT) + +$(C_OBJ): $(BIN)/%.o : %.c + @mkdir -p $(@D) + $(CC) -c $(CFLAGS) -o $@ $< + +$(BIN)/$(OUT): $(C_OBJ) $(H_SRC) + @mkdir -p $(@D) + $(LD) $(LDFLAGS) -o $(BIN)/$(OUT) $(C_OBJ) diff --git a/masm/: b/masm/: new file mode 100644 index 0000000..96d212f --- /dev/null +++ b/masm/: @@ -0,0 +1,363 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "asm.h" +#include "mlimits.h" +#include "parse.h" +#include "parse_mips32.h" + +extern char *current_file; + +#define SHDR_STRTBL 0 +#define SHDR_SYMTBL 1 +#define SHDR_SECTIONS 2 + +static int parse_file(struct parser *parser) +{ + while (1) { + struct expr expr; + if (parser_next(parser, &expr)) { + break; + } + + if (expr.type == EXPR_INS) + if (sectbl_push(&parser->sec_tbl, + parser->sec_tbl.current, expr.ins)) + return M_ERROR; + } + + for (uint32_t i = 0; i < parser->ref_tbl.count; i++) { + struct reference *ref = &parser->ref_tbl.references[i]; + struct symbol *sym; + struct mips32_instruction *ins; + + if (symtbl_find(&parser->sym_tbl, &sym, ref->name)) { + ERROR("undefined symbol '%s'", ref->name); + return M_ERROR; + } + + ins = &ref->section->ins[ref->index].mips32; + + switch (ref->type) { + case REF_OFFESET: + ins->B_data.offset += sym->position - + (ref->section->start + ref->index); + break; + case REF_TARGET: + ins->J_data.target += sym->position; + break; + } + }; + + return M_SUCCESS; +} + +static int assemble_phdr(struct assembler *asm, Elf32_Phdr **res, + uint32_t *res2) +{ + struct parser *parser = asm->parser; + Elf32_Phdr *phdr = malloc(sizeof(Elf32_Phdr) * + parser->sec_tbl.count); + size_t ins_sz = sizeof(struct mips32_instruction); + + if (phdr == NULL) { + ERROR("cannot alloc"); + return M_ERROR;; + } + + for (uint32_t i = 0; i < parser->sec_tbl.count; i++) { + Elf32_Phdr *hdr = &phdr[i]; + struct section *sec = &parser->sec_tbl.sections[i]; + + hdr->p_type = PT_LOAD; + hdr->p_flags = PF_X | PF_W | PF_R; // FIXME: this is bad + hdr->p_offset = sec->start * ins_sz; + hdr->p_vaddr = sec->start * ins_sz; + hdr->p_paddr = 0x00; + hdr->p_filesz = sec->count * ins_sz; + hdr->p_memsz = sec->count * ins_sz; + hdr->p_align = sec->alignment; + } + + *res = phdr; + *res2 = parser->sec_tbl.count; + return M_SUCCESS; +} + +static int assemble_symtbl(struct assembler *asm, Elf32_Sym **res, + uint32_t *res2) +{ + Elf32_Sym *stbl = malloc(sizeof(Elf32_Sym) * asm->parser->sym_tbl + .count); + + if (stbl == NULL) + return M_ERROR; + + for (uint32_t i = 0; i < asm->parser->sym_tbl.count; i++) { + struct symbol *sym = &asm->parser->sym_tbl.symbols[i]; + size_t str_off; + + if (strtbl_write_str(&asm->str_tbl, sym->name, &str_off)) { + free(stbl); + return M_ERROR; + } + + int viz = STB_LOCAL; + switch (sym->flag) { + case SYM_LOCAL: + viz = STB_LOCAL; + break; + case SYM_GLOBAL: + case SYM_EXTERNAL: + viz = STB_GLOBAL; + break; + } + + stbl[i] = (Elf32_Sym) { + .st_name = str_off, + .st_value = sym->position, + .st_size = 0, + .st_info = (unsigned char) + ELF32_ST_INFO(SYMINFO_BT_SELF, + SYMINFO_FLG_DIRECT), + .st_other = (unsigned char) + ELF32_ST_VISIBILITY(viz), + .st_shndx = 0, // FIXME: specify section + }; + }; + + *res = stbl; + *res2 = asm->parser->sym_tbl.count; + + return M_SUCCESS; +} + +static int assemble_shdr(struct assembler *asm, Elf32_Shdr **res, + uint32_t *res2) +{ + uint32_t entries = 2; // str table and sym tabel + entries += asm->parser->sec_tbl.count; // sections + + Elf32_Shdr *shdr = malloc(sizeof(Elf32_Shdr) * entries); + + size_t str_off; + if (strtbl_write_str(&asm->str_tbl, ".shstrtab", &str_off)) { + free(shdr); + return M_ERROR; + } + + // string table + shdr[SHDR_STRTBL] = (Elf32_Shdr) { + .sh_name = str_off, + .sh_type = SHT_STRTAB, + .sh_flags = SHF_STRINGS, + .sh_addr = 0, + .sh_offset = 0, + .sh_size = 0, + .sh_link = 0, + .sh_info = 0, + .sh_addralign = 1, + .sh_entsize = 0, + }; + + if (strtbl_write_str(&asm->str_tbl, ".shsymtab", &str_off)) { + free(shdr); + return M_ERROR; + } + + // symbol table + shdr[SHDR_SYMTBL] = (Elf32_Shdr) { + .sh_name = str_off, + .sh_type = SHT_SYMTAB, + .sh_flags = 0, + .sh_addr = 0, + .sh_offset = 0, + .sh_size = 0, + .sh_link = 0, + .sh_info = 0, + .sh_addralign = 1, + .sh_entsize = sizeof(Elf32_Sym), + }; + + // for each section + for (uint32_t i = 0; i < asm->parser->sec_tbl.count; i++) { + struct section *sec = &asm->parser->sec_tbl.sections[i]; + char name[MAX_LEX_LENGTH+1] = "."; + strcat(name, sec->name); + if (strtbl_write_str(&asm->str_tbl, name, &str_off)) { + free(shdr); + return M_ERROR; + } + shdr[i+SHDR_SECTIONS] = (Elf32_Shdr) { + .sh_name = str_off, + .sh_type = SHT_PROGBITS, + .sh_flags = SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR, + .sh_addr = 0, + .sh_offset = 0, + .sh_size = 0, + .sh_link = 0, + .sh_info = 0, + .sh_addralign = sec->alignment, + .sh_entsize = sizeof(struct mips32_instruction), + }; + } + + *res = shdr; + *res2 = entries; + + return M_SUCCESS; +} + +static int assemble_file(struct assembler *asm) +{ + Elf32_Phdr *phdr; + Elf32_Shdr *shdr; + Elf32_Sym *symtbl; + uint32_t phdr_len; + uint32_t shdr_len; + uint32_t symtbl_len; + + if (assemble_symtbl(asm, &symtbl, &symtbl_len)) + return M_ERROR; + + if (assemble_phdr(asm, &phdr, &phdr_len)) { + free(symtbl); + return M_ERROR; + } + + if (assemble_shdr(asm, &shdr, &shdr_len)) { + free(symtbl); + free(phdr); + return M_ERROR; + }; + + Elf32_Ehdr ehdr = { + .e_ident = { + [EI_MAG0] = ELFMAG0, + [EI_MAG1] = ELFMAG1, + [EI_MAG2] = ELFMAG2, + [EI_MAG3] = ELFMAG3, + [EI_CLASS] = ELFCLASS32, + [EI_DATA] = ELFDATA2LSB, + [EI_VERSION] = EV_CURRENT, + [EI_OSABI] = ELFOSABI_STANDALONE, + [EI_ABIVERSION] = 0x00, + [EI_PAD] = 0x00, + }, + .e_type = ET_REL, + .e_machine = EM_MIPS, + .e_version = EV_CURRENT, + .e_entry = 0x00, + .e_phoff = 0x00, + .e_shoff = 0x00, + .e_flags = EF_MIPS_ARCH_32R6, + .e_ehsize = sizeof(Elf32_Ehdr), + .e_phentsize = 0x20, + .e_phnum = phdr_len, + .e_shentsize = 0x28, + .e_shnum = shdr_len, + .e_shstrndx = 0x00, // str table is always inx 0 + }; + + uint32_t ptr = 0; + + // we must now correct offets and sizes inside the ehdr, phdr, + // and shdr + + ptr += sizeof(Elf32_Ehdr); + + // phdr + ehdr.e_phoff = ptr; + ptr += phdr_len * sizeof(Elf32_Phdr); + + // sections + for (uint32_t i = 0; i < asm->parser->sec_tbl.count; i++) { + phdr[i].p_offset = ptr; + phdr[i].p_vaddr = ptr; + shdr[i+SHDR_SECTIONS].sh_offset = ptr; + shdr[i+SHDR_SECTIONS].sh_size = phdr[i].p_filesz; + ptr += phdr[i].p_filesz; + } + + // strtbl + shdr[SHDR_STRTBL].sh_offset = ptr; + shdr[SHDR_STRTBL].sh_size = asm->str_tbl.size; + ptr += asm->str_tbl.size; + + // symtbl + ehdr.e_shoff = ptr; + shdr[SHDR_SYMTBL].sh_offset = ptr; + shdr[SHDR_SYMTBL].sh_size = symtbl_len * sizeof(Elf32_Sym); + ptr += symtbl_len * sizeof(Elf32_Sym); + + FILE *out = fopen("/home/freya/out.o", "w"); + + // ehdr + fwrite(&ehdr, sizeof(Elf32_Ehdr), 1, out); + + // phdr + fwrite(phdr, sizeof(Elf32_Phdr), phdr_len, out); + + // sections + for (uint32_t i = 0; i < asm->parser->sec_tbl.count; i++) { + struct section *sec = &asm->parser->sec_tbl.sections[i]; + for (uint32_t j = 0; j < sec->count; j++) { + struct mips32_instruction *ins = &sec->ins[j].mips32; + fwrite(ins, sizeof(struct mips32_instruction), + 1, out); + } + } + + // str tbl + fwrite(asm->str_tbl.ptr, asm->str_tbl.size, 1, out); + + // sym tbl + fwrite(symtbl, sizeof(Elf32_Sym), symtbl_len, out); + + // shdr + fwrite(shdr, sizeof(Elf32_Shdr), shdr_len, out); + + fclose(out); + + free(shdr); + free(phdr); + free(symtbl); + + return M_SUCCESS; +} + +int assemble_file_mips32(char *path) +{ + struct lexer lexer; + struct parser parser; + current_file = path; + int res = M_SUCCESS; + + if (lexer_init(current_file, &lexer)) + return M_ERROR; + + if (mips32_parser_init(&lexer, &parser)) + return M_ERROR; + + if (res == M_SUCCESS) + res = parse_file(&parser); + + struct assembler assembler; + assembler.parser = &parser; + strtbl_init(&assembler.str_tbl); + + if (res == M_SUCCESS) + res = assemble_file(&assembler); + + strtbl_free(&assembler.str_tbl); + lexer_free(&lexer); + parser_free(&parser); + + return res; +} diff --git a/masm/Makefile b/masm/Makefile new file mode 100644 index 0000000..cd1dae3 --- /dev/null +++ b/masm/Makefile @@ -0,0 +1,7 @@ +include ../config.mk + +SRC=. +BIN=../bin/masm +OUT=masm + +include ../makefile.mk diff --git a/masm/asm.h b/masm/asm.h new file mode 100644 index 0000000..1bc7cf5 --- /dev/null +++ b/masm/asm.h @@ -0,0 +1,33 @@ +/* Copyright (c) 2024 Freya Murphy */ + +#ifndef __ASM_H__ +#define __ASM_H__ + +#include + +struct str_table { + char *ptr; + size_t size; +}; + +/* initalize a string table */ +void strtbl_init(struct str_table *str_tbl); + +/* free a string table */ +void strtbl_free(struct str_table *str_tbl); + +/* get a string form the string table */ +int strtbl_get_str(struct str_table *str_tbl, const char *str, size_t *res); + +/* get or append a string into the string table */ +int strtbl_write_str(struct str_table *str_tbl, const char *str, size_t *res); + +struct assembler { + struct parser *parser; + struct str_table str_tbl; +}; + +/* assemble a mips32 file*/ +int assemble_file_mips32(char *path); + +#endif /* __ASM_H__ */ diff --git a/masm/asm_mips32.c b/masm/asm_mips32.c new file mode 100644 index 0000000..dcb81e5 --- /dev/null +++ b/masm/asm_mips32.c @@ -0,0 +1,365 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "asm.h" +#include "mlimits.h" +#include "parse.h" +#include "parse_mips32.h" + +extern char *current_file; + +#define SHDR_SYMTBL 0 +#define SHDR_STRTBL 1 +#define SHDR_SECTIONS 2 + +static int parse_file(struct parser *parser) +{ + while (1) { + struct expr expr; + if (parser_next(parser, &expr)) { + break; + } + + if (expr.type == EXPR_INS) + if (sectbl_push(&parser->sec_tbl, + parser->sec_tbl.current, expr.ins)) + return M_ERROR; + } + + for (uint32_t i = 0; i < parser->ref_tbl.count; i++) { + struct reference *ref = &parser->ref_tbl.references[i]; + struct symbol *sym; + struct mips32_instruction *ins; + + if (symtbl_find(&parser->sym_tbl, &sym, ref->name)) { + ERROR("undefined symbol '%s'", ref->name); + return M_ERROR; + } + + ins = &ref->section->ins[ref->index].mips32; + + switch (ref->type) { + case REF_OFFESET: + ins->B_data.offset += sym->position - + (ref->section->start + ref->index); + break; + case REF_TARGET: + ins->J_data.target += sym->position; + break; + } + }; + + return M_SUCCESS; +} + +static int assemble_phdr(struct assembler *asm, Elf32_Phdr **res, + uint32_t *res2) +{ + struct parser *parser = asm->parser; + Elf32_Phdr *phdr = malloc(sizeof(Elf32_Phdr) * + parser->sec_tbl.count); + size_t ins_sz = sizeof(struct mips32_instruction); + + if (phdr == NULL) { + ERROR("cannot alloc"); + return M_ERROR;; + } + + for (uint32_t i = 0; i < parser->sec_tbl.count; i++) { + Elf32_Phdr *hdr = &phdr[i]; + struct section *sec = &parser->sec_tbl.sections[i]; + + hdr->p_type = PT_LOAD; + hdr->p_flags = PF_X | PF_W | PF_R; // FIXME: this is bad + hdr->p_offset = sec->start * ins_sz; + hdr->p_vaddr = sec->start * ins_sz; + hdr->p_paddr = 0x00; + hdr->p_filesz = sec->count * ins_sz; + hdr->p_memsz = sec->count * ins_sz; + hdr->p_align = sec->alignment; + } + + *res = phdr; + *res2 = parser->sec_tbl.count; + return M_SUCCESS; +} + +static int assemble_symtbl(struct assembler *asm, Elf32_Sym **res, + uint32_t *res2) +{ + Elf32_Sym *stbl = malloc(sizeof(Elf32_Sym) * asm->parser->sym_tbl + .count); + + if (stbl == NULL) + return M_ERROR; + + for (uint32_t i = 0; i < asm->parser->sym_tbl.count; i++) { + struct symbol *sym = &asm->parser->sym_tbl.symbols[i]; + size_t str_off; + + if (strtbl_write_str(&asm->str_tbl, sym->name, &str_off)) { + free(stbl); + return M_ERROR; + } + + int viz = STB_LOCAL; + switch (sym->flag) { + case SYM_LOCAL: + viz = STB_LOCAL; + break; + case SYM_GLOBAL: + case SYM_EXTERNAL: + viz = STB_GLOBAL; + break; + } + + stbl[i] = (Elf32_Sym) { + .st_name = str_off, + .st_value = sym->position, + .st_size = 0, + .st_info = (unsigned char) + ELF32_ST_INFO(SYMINFO_BT_SELF, + SYMINFO_FLG_DIRECT), + .st_other = (unsigned char) + ELF32_ST_VISIBILITY(viz), + .st_shndx = 0, // FIXME: specify section + }; + }; + + *res = stbl; + *res2 = asm->parser->sym_tbl.count; + + return M_SUCCESS; +} + +static int assemble_shdr(struct assembler *asm, Elf32_Shdr **res, + uint32_t *res2) +{ + uint32_t entries = 2; // str table and sym tabel + entries += asm->parser->sec_tbl.count; // sections + + Elf32_Shdr *shdr = malloc(sizeof(Elf32_Shdr) * entries); + + size_t str_off; + if (strtbl_write_str(&asm->str_tbl, ".shsymtab", &str_off)) { + free(shdr); + return M_ERROR; + } + + // symbol table + shdr[SHDR_SYMTBL] = (Elf32_Shdr) { + .sh_name = str_off, + .sh_type = SHT_SYMTAB, + .sh_flags = 0, + .sh_addr = 0, + .sh_offset = 0, + .sh_size = 0, + .sh_link = 1, + .sh_info = 0, + .sh_addralign = 1, + .sh_entsize = sizeof(Elf32_Sym), + }; + + if (strtbl_write_str(&asm->str_tbl, ".shstrtab", &str_off)) { + free(shdr); + return M_ERROR; + } + + // string table + shdr[SHDR_STRTBL] = (Elf32_Shdr) { + .sh_name = str_off, + .sh_type = SHT_STRTAB, + .sh_flags = SHF_STRINGS, + .sh_addr = 0, + .sh_offset = 0, + .sh_size = 0, + .sh_link = 0, + .sh_info = 0, + .sh_addralign = 1, + .sh_entsize = 0, + }; + + // for each section + for (uint32_t i = 0; i < asm->parser->sec_tbl.count; i++) { + struct section *sec = &asm->parser->sec_tbl.sections[i]; + char name[MAX_LEX_LENGTH+1] = "."; + strcat(name, sec->name); + if (strtbl_write_str(&asm->str_tbl, name, &str_off)) { + free(shdr); + return M_ERROR; + } + shdr[i+SHDR_SECTIONS] = (Elf32_Shdr) { + .sh_name = str_off, + .sh_type = SHT_PROGBITS, + .sh_flags = SHF_WRITE | SHF_ALLOC | SHF_EXECINSTR, + .sh_addr = 0, + .sh_offset = 0, + .sh_size = 0, + .sh_link = 0, + .sh_info = 0, + .sh_addralign = sec->alignment, + .sh_entsize = sizeof(struct mips32_instruction), + }; + } + + *res = shdr; + *res2 = entries; + + return M_SUCCESS; +} + +static int assemble_file(struct assembler *asm) +{ + Elf32_Phdr *phdr; + Elf32_Shdr *shdr; + Elf32_Sym *symtbl; + uint32_t phdr_len; + uint32_t shdr_len; + uint32_t symtbl_len; + + if (assemble_symtbl(asm, &symtbl, &symtbl_len)) + return M_ERROR; + + if (assemble_phdr(asm, &phdr, &phdr_len)) { + free(symtbl); + return M_ERROR; + } + + if (assemble_shdr(asm, &shdr, &shdr_len)) { + free(symtbl); + free(phdr); + return M_ERROR; + }; + + Elf32_Ehdr ehdr = { + .e_ident = { + [EI_MAG0] = ELFMAG0, + [EI_MAG1] = ELFMAG1, + [EI_MAG2] = ELFMAG2, + [EI_MAG3] = ELFMAG3, + [EI_CLASS] = ELFCLASS32, + [EI_DATA] = ELFDATA2LSB, + [EI_VERSION] = EV_CURRENT, + [EI_OSABI] = ELFOSABI_NONE, + [EI_ABIVERSION] = 0x00, + [EI_PAD] = 0x00, + }, + .e_type = ET_REL, + .e_machine = EM_MIPS, + .e_version = EV_CURRENT, + .e_entry = 0x00, + .e_phoff = 0x00, + .e_shoff = 0x00, + .e_flags = EF_MIPS_ARCH_32R6, + .e_ehsize = sizeof(Elf32_Ehdr), + .e_phentsize = sizeof(Elf32_Phdr), + .e_phnum = phdr_len, + .e_shentsize = sizeof(Elf32_Shdr), + .e_shnum = shdr_len, + .e_shstrndx = SHDR_STRTBL, + }; + + uint32_t ptr = 0; + + // we must now correct offets and sizes inside the ehdr, phdr, + // and shdr + + ptr += sizeof(Elf32_Ehdr); + + // phdr + ehdr.e_phoff = ptr; + ptr += phdr_len * sizeof(Elf32_Phdr); + + // sections + for (uint32_t i = 0; i < asm->parser->sec_tbl.count; i++) { + phdr[i].p_offset = ptr; + phdr[i].p_vaddr = ptr; + shdr[i+SHDR_SECTIONS].sh_offset = ptr; + shdr[i+SHDR_SECTIONS].sh_size = phdr[i].p_filesz; + ptr += phdr[i].p_filesz; + } + + // symtbl + shdr[SHDR_SYMTBL].sh_offset = ptr; + shdr[SHDR_SYMTBL].sh_size = symtbl_len * sizeof(Elf32_Sym); + ptr += symtbl_len * sizeof(Elf32_Sym); + + // strtbl + shdr[SHDR_STRTBL].sh_offset = ptr; + shdr[SHDR_STRTBL].sh_size = asm->str_tbl.size; + ptr += asm->str_tbl.size; + + // shdr + ehdr.e_shoff = ptr; + + FILE *out = fopen("out.o", "w"); + + // ehdr + fwrite(&ehdr, sizeof(Elf32_Ehdr), 1, out); + + // phdr + fwrite(phdr, sizeof(Elf32_Phdr), phdr_len, out); + + // sections + for (uint32_t i = 0; i < asm->parser->sec_tbl.count; i++) { + struct section *sec = &asm->parser->sec_tbl.sections[i]; + for (uint32_t j = 0; j < sec->count; j++) { + struct mips32_instruction *ins = &sec->ins[j].mips32; + fwrite(ins, sizeof(struct mips32_instruction), + 1, out); + } + } + + // sym tbl + fwrite(symtbl, sizeof(Elf32_Sym), symtbl_len, out); + + // str tbl + fwrite(asm->str_tbl.ptr, asm->str_tbl.size, 1, out); + + // shdr + fwrite(shdr, sizeof(Elf32_Shdr), shdr_len, out); + + fclose(out); + + free(shdr); + free(phdr); + free(symtbl); + + return M_SUCCESS; +} + +int assemble_file_mips32(char *path) +{ + struct lexer lexer; + struct parser parser; + current_file = path; + int res = M_SUCCESS; + + if (lexer_init(current_file, &lexer)) + return M_ERROR; + + if (mips32_parser_init(&lexer, &parser)) + return M_ERROR; + + if (res == M_SUCCESS) + res = parse_file(&parser); + + struct assembler assembler; + assembler.parser = &parser; + strtbl_init(&assembler.str_tbl); + + if (res == M_SUCCESS) + res = assemble_file(&assembler); + + strtbl_free(&assembler.str_tbl); + lexer_free(&lexer); + parser_free(&parser); + + return res; +} diff --git a/masm/lex.c b/masm/lex.c new file mode 100644 index 0000000..06c7114 --- /dev/null +++ b/masm/lex.c @@ -0,0 +1,343 @@ +#include "lex.h" + +#include +#include + +static struct { + int x; + int y; +} pos; + +/* get next char in lexer */ +static int lex_next(struct lexer *lexer) +{ + if (lexer->peek != EOF) { + int c = lexer->peek; + lexer->peek = EOF; + return c; + } + + int c = getc(lexer->file); + if (c == '\n') { + lexer->x = 0; + lexer->y++; + } else { + lexer->x++; + } + return c; +} + +/* peek next char in lexer */ +static int lex_peek(struct lexer *lexer) +{ + if (lexer->peek == EOF) + lexer->peek = lex_next(lexer); + return lexer->peek; +} + +/* skip all characters until EOF or newline */ +static void skip_comment(struct lexer *lexer) +{ + int c; + while (1) { + c = lex_next(lexer); + if (c == EOF || c == '\n') + break; + } +} + +/* lexes text until whitespace + * returns error on zero length or too long */ +static int lex_ident(struct lexer *lexer, char text[MAX_LEX_LENGTH]) +{ + int len = 0; + char *ptr = text; + int c; + + while (1) { + c = lex_peek(lexer); + if (!( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + (c == '_') + )) { + break; + } + + // pop char out of lexer + lex_next(lexer); + + if (len + 1 == MAX_LEX_LENGTH) { + ERROR_POS(pos, "ident has max length of %d", + MAX_LEX_LENGTH); + return M_ERROR; + } + + *ptr++ = c; + len++; + } + + if (len == 0) { + ERROR_POS(pos, "attempted to lex empty ident %d", + MAX_LEX_LENGTH); + return M_ERROR; + } + + *ptr = '\0'; + return M_SUCCESS; +} + +/* lexes a string until closing quote + * returns error if string is too long or hit newline */ +static int lex_string(struct lexer *lexer,char text[MAX_LEX_LENGTH]) +{ + int len = 0; + char *ptr = text; + int c; + + while (1) { + c = lex_next(lexer); + if (c == '"') + break; + + // match escape character + if (c == '\\') { + switch (lex_peek(lexer)) { + case 'n': + c = '\n'; + lex_next(lexer); + break; + case 't': + c = '\t'; + lex_next(lexer); + break; + case '\\': + c = '\\'; + lex_next(lexer); + break; + case '"': + c = '"'; + lex_next(lexer); + break; + } + } + + // strings cannot span multiple lines + if (c == '\n') { + ERROR_POS(pos, "reached newline before end of string"); + return M_ERROR; + } + + if (len + 1 == MAX_LEX_LENGTH) { + ERROR_POS(pos, "string has max length of %d", + MAX_LEX_LENGTH); + return M_ERROR; + } + + *ptr++ = c; + len++; + } + + *ptr = '\0'; + return M_SUCCESS; +} + +/* lexes a integer number in base 2,8,10, or 16, + * uses base 10 by default but chan be changed by 0b, 0o, and 0x */ +static int lex_number(struct lexer *lexer, int64_t *n) +{ + int64_t number = 0; + int base = 10; + + // skip all leading zeros, they dont do anything. + // this also allows us to directly check for 0b, 0o, and 0x + // right away! + while (1) { + if (lex_peek(lexer) == '0') + lex_next(lexer); + else + break; + } + + // match change of base + switch (lex_peek(lexer)) { + case 'b': + base = 2; + lex_next(lexer); + break; + case 'o': + base = 8; + lex_next(lexer); + break; + case 'x': + base = 16; + lex_next(lexer); + break; + } + + while (1) { + char c = lex_peek(lexer); + int n = 0; + if (c >= '0' && c <= '9') { + n = c - '0'; + } else if (c >= 'a' && c <= 'z') { // match A-Z so we can + n = c - 'a' + 10; // catch the errors + } else if (c >= 'A' && c <= 'Z') { // here instead of later + n = c - 'A' + 10; + } else { + break; // no longer a number + } + // if number provided is bigger than my base, + // error ! + if (n >= base) { + ERROR_POS(pos, "character '%c' is bigger than number base" + "'%d'", c, base); + return M_ERROR; + } + lex_next(lexer); + number *= base; + number += n; + } + + *n = number; + return M_SUCCESS; +} + +/* lex the next token on the file */ +int lexer_next(struct lexer *lexer, struct token *token) +{ +again: // use label to avoid whitespace recursion + token->x = lexer->x; + token->y = lexer->y; + pos.x = lexer->x; + pos.y = lexer->y; + token->type = TOK_EOF; + + int c = lex_peek(lexer); + int res = M_SUCCESS; + + switch (c) { + + case EOF: + case '\0': + token->type = TOK_EOF; + break; + case ';': + case '#': + skip_comment(lexer); + goto again; + case ' ': + case '\t': + // skip white space + lex_next(lexer); + goto again; + case '\n': + lex_next(lexer); + token->type = TOK_NL; + break; + case ',': + lex_next(lexer); + token->type = TOK_COMMA; + break; + case '=': + lex_next(lexer); + token->type = TOK_EQUAL; + break; + case '(': + lex_next(lexer); + token->type = TOK_LPAREN; + break; + case ')': + token->type = TOK_RPAREN; + lex_next(lexer); + break; + case '$': + token->type = TOK_REG; + lex_next(lexer); + res = lex_ident(lexer, token->text); + break; + case '.': + token->type = TOK_DIRECTIVE; + lex_next(lexer); + res = lex_ident(lexer, token->text); + break; + case '"': + token->type = TOK_STRING; + lex_next(lexer); + res = lex_string(lexer, token->text); + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + token->type = TOK_NUMBER; + res = lex_number(lexer, &token->number); + break; + default: + token->type = TOK_IDENT; + res = lex_ident(lexer, token->text); + if (lex_peek(lexer) == ':') { + lex_next(lexer); + token->type = TOK_LABEL; + } + break; + } + return res; +} + +int lexer_init(const char *path, struct lexer *lexer) +{ + FILE *file = fopen(path, "r"); + if (file == NULL) { + ERROR_POS(pos, "cannot file '%s'", path); + return M_ERROR; + } + lexer->file = file; + lexer->peek = EOF; + lexer->x = 0; + lexer->y = 0; + return M_SUCCESS; +} + +int lexer_free(struct lexer *lexer) +{ + return fclose(lexer->file); +} + +char *token_str(enum token_type type) +{ + switch (type) { + case TOK_IDENT: + return "ident"; + case TOK_REG: + return "register"; + case TOK_LABEL: + return "label"; + case TOK_STRING: + return "string"; + case TOK_COMMA: + return "comma"; + case TOK_EQUAL: + return "equal"; + case TOK_LPAREN: + return "left parentheses"; + case TOK_RPAREN: + return "right parentheses"; + case TOK_NUMBER: + return "number"; + case TOK_EOF: + return "end of file"; + case TOK_NL: + return "new line"; + case TOK_DIRECTIVE: + return "directive"; + } + return "unknown"; +} diff --git a/masm/lex.h b/masm/lex.h new file mode 100644 index 0000000..f1c482a --- /dev/null +++ b/masm/lex.h @@ -0,0 +1,55 @@ +/* Copyright (c) 2024 Freya Murphy */ + +#ifndef __LEX_H__ +#define __LEX_H__ + +#include +#include +#include + +struct lexer { + FILE *file; + int peek; + int x; + int y; +}; + +enum token_type { + TOK_IDENT, + TOK_REG, + TOK_LABEL, + TOK_STRING, + TOK_COMMA, + TOK_EQUAL, + TOK_LPAREN, + TOK_RPAREN, + TOK_NUMBER, + TOK_EOF, + TOK_NL, + TOK_DIRECTIVE, +}; + +struct token { + enum token_type type; + union { + int64_t number; + char text[MAX_LEX_LENGTH]; + }; + int x; + int y; +}; + +/* initalize a lexer */ +int lexer_init(const char *file, struct lexer *lexer); + +/* free the lxer */ +int lexer_free(struct lexer *lexer); + +/* lexes the next token, returns M_ERROR on error, + * and TOK_EOF on EOF */ +int lexer_next(struct lexer *lexer, struct token *token); + +/* token type to string */ +char *token_str(enum token_type); + +#endif /* __LEX_H__ */ diff --git a/masm/main.c b/masm/main.c new file mode 100644 index 0000000..957b34c --- /dev/null +++ b/masm/main.c @@ -0,0 +1,9 @@ +#include "asm.h" + +int main(int argc, char **argv) { + + if (argc != 2) + return 0; + + return assemble_file_mips32(argv[1]); +} diff --git a/masm/parse.c b/masm/parse.c new file mode 100644 index 0000000..9876311 --- /dev/null +++ b/masm/parse.c @@ -0,0 +1,198 @@ +#include +#include +#include +#include + +#include "parse.h" +#include "lex.h" + +int next_token(struct parser *parser, struct token *tok) +{ + if (parser->peek.type != TOK_EOF) { + if (tok != NULL) + *tok = parser->peek; + parser->peek.type = TOK_EOF; + return M_SUCCESS; + } + struct token token; + if (lexer_next(parser->lexer, &token)) + return M_ERROR; + if (tok != NULL) + *tok = token; + return M_SUCCESS; +} + + +int peek_token(struct parser *parser, struct token *tok) +{ + if (parser->peek.type == TOK_EOF) { + if (next_token(parser, &parser->peek)) + return M_ERROR; + } + if (tok != NULL) + *tok = parser->peek; + return M_SUCCESS; +} + + +int assert_token(struct parser *parser, enum token_type type, + struct token *tok) +{ + struct token token; + if (next_token(parser, &token)) + return M_ERROR; + if (token.type != type) { + ERROR_POS(token, "expected a token of type '%s', got '%s'", + token_str(type), token_str(token.type)); + return M_ERROR; + } + if (tok != NULL) + *tok = token; + return M_SUCCESS; +} + +int assert_eol(struct parser *parser) +{ + struct token token; + if (next_token(parser, &token)) + return M_ERROR; + if (token.type != TOK_NL && token.type != TOK_EOF) { + ERROR_POS(token, "expected a new line or end of file"); + return M_ERROR; + } + return M_SUCCESS; +} + +static int parse_constant(struct parser *parser, struct const_expr *expr, + struct token ident) +{ + struct token number; + + if (assert_token(parser, TOK_EQUAL, NULL)) + return M_ERROR; + + if (assert_token(parser, TOK_NUMBER, &number)) + return M_ERROR; + + strcpy(expr->name,ident.text); + expr->value = number.number; + + return M_SUCCESS; +} + +static int parser_handle_ident(struct parser *parser, struct expr *expr) +{ + struct token ident; + struct token peek; + + if (assert_token(parser, TOK_IDENT, &ident)) + return M_ERROR; + + if (peek_token(parser, &peek)) + return M_ERROR; + + if (peek.type == TOK_EQUAL) { + expr->type = EXPR_CONSTANT; + return parse_constant(parser, &expr->constant, ident); + } else { + expr->type = EXPR_INS; + return parser->parse_instruction(parser, &expr->ins, ident); + } +} + + +static int parse_label(struct parser *parser, + struct expr *expr) +{ + struct token token; + struct symbol symbol; + uint32_t index; + + if (assert_token(parser, TOK_LABEL, &token)) + return M_ERROR; + strcpy(expr->text, token.text); + + if (symtbl_find(&parser->sym_tbl, NULL, token.text) == M_SUCCESS) { + ERROR_POS(token, "redefined symbol '%s'", token.text); + return M_ERROR; + } + + index = parser->sec_tbl.current->start + + parser->sec_tbl.current->count; + symbol = (struct symbol) { + .name = "", + .position = index, + .flag = SYM_LOCAL, + }; + strcpy(symbol.name, token.text); + + if (symtbl_push(&parser->sym_tbl, symbol)) + return M_ERROR; + + return M_SUCCESS; +} + + +int parser_next(struct parser *parser, struct expr *expr) +{ + struct token token; + int res = M_SUCCESS; + +again: + if (peek_token(parser, &token)) + return M_ERROR; + + switch (token.type) { + case TOK_NL: + next_token(parser, NULL); + goto again; + + case TOK_EOF: + res = M_EOF; + break; + + case TOK_LABEL: + expr->type = EXPR_LABEL; + res = parse_label(parser, expr); + break; + + case TOK_DIRECTIVE: + expr->type = EXPR_DIRECTIVE; + res = parser->parse_directive(parser, + &expr->directive); + break; + + case TOK_IDENT: + res = parser_handle_ident(parser, expr); + break; + + default: + ERROR_POS(token, "unexpected token '%s'", + token_str(token.type)); + return M_ERROR; + + } + + return res; +} + +int parser_init(struct lexer *lexer, struct parser *parser) +{ + parser->lexer = lexer; + parser->peek.type = TOK_EOF; + if (symtbl_init(&parser->sym_tbl)) + return M_ERROR; + if (sectbl_init(&parser->sec_tbl)) + return M_ERROR; + if (reftbl_init(&parser->ref_tbl)) + return M_ERROR; + return M_SUCCESS; +} + + +void parser_free(struct parser *parser) +{ + symtbl_free(&parser->sym_tbl); + sectbl_free(&parser->sec_tbl); + reftbl_free(&parser->ref_tbl); +} diff --git a/masm/parse.h b/masm/parse.h new file mode 100644 index 0000000..2aea0be --- /dev/null +++ b/masm/parse.h @@ -0,0 +1,156 @@ +/* Copyright (c) 2024 Freya Murphy */ + +#ifndef __PARSE_H__ +#define __PARSE_H__ + +#include "lex.h" + +#include +#include +#include + +struct const_expr { + char name[MAX_LEX_LENGTH]; + uint32_t value; +}; + +enum expr_type { + EXPR_INS, + EXPR_DIRECTIVE, + EXPR_CONSTANT, + EXPR_SEGMENT, + EXPR_LABEL, +}; + +struct expr { + enum expr_type type; + union { + // instruction + union mips_instruction ins; + // directive + union mips_directive directive; + // constant + struct const_expr constant; + // segment or label + char text[MAX_LEX_LENGTH]; + }; +}; + +enum symbol_flag { + SYM_LOCAL, + SYM_GLOBAL, + SYM_EXTERNAL, +}; + +struct symbol { + char name[MAX_LEX_LENGTH]; + uint32_t position; + enum symbol_flag flag; + +}; + +struct symbol_table { + uint32_t count; + uint32_t len; + struct symbol *symbols; +}; + +int symtbl_init(struct symbol_table *sym_tbl); +void symtbl_free(struct symbol_table *sym_tbl); + +int symtbl_push(struct symbol_table *sym_tbl, struct symbol sym); +int symtbl_find(struct symbol_table *sym_tbl, struct symbol **sym, + const char name[MAX_LEX_LENGTH]); + +struct section { + uint32_t count; + uint32_t len; + uint32_t start; + uint32_t alignment; + union mips_instruction *ins; + char name[MAX_LEX_LENGTH]; +}; + +struct section_table { + uint32_t count; + uint32_t len; + struct section *sections; + struct section *current; + char name[MAX_LEX_LENGTH]; + uint32_t total_ins; +}; + +int sectbl_init(struct section_table *sec_tbl); +void sectbl_free(struct section_table *sec_tbl); + +int sectbl_alloc(struct section_table *sec_tbl, struct section **sec, + const char name[MAX_LEX_LENGTH]); +int sectbl_push(struct section_table *sec_tbl, struct section *section, + union mips_instruction ins); +int sectbl_get(struct section_table *sec_tbl, struct section **sec, + const char name[MAX_LEX_LENGTH]); + +enum reference_type { + REF_OFFESET, + REF_TARGET, +}; + +struct reference { + enum reference_type type; + struct section *section; + uint32_t index; + char name[MAX_LEX_LENGTH]; +}; + +struct reference_table { + uint32_t count; + uint32_t len; + struct reference *references; +}; + +int reftbl_init(struct reference_table *ref_tbl); +void reftbl_free(struct reference_table *ref_tbl); +int reftbl_push(struct reference_table *ref_tbl, struct reference reference); + +struct parser { + struct lexer *lexer; + struct token peek; + + // sections + struct section_table sec_tbl; + + // symbols + struct symbol_table sym_tbl; + + // references + struct reference_table ref_tbl; + + int (*parse_instruction)(struct parser *, union mips_instruction *, + struct token); + int (*parse_directive)(struct parser *, union mips_directive *); + int (*is_instruction)(const char *ident); +}; + +/* get the next token in the parser */ +int next_token(struct parser *parser, struct token *tok); + +/* peek the next token in the parser */ +int peek_token(struct parser *parser, struct token *tok); + +/* assert the next token is a specific type */ +int assert_token(struct parser *parser, enum token_type type, + struct token *tok); + +/* assert the next token is EOF or NL */ +int assert_eol(struct parser *parser); + +/* get the next expression in the parser */ +int parser_next(struct parser *parser, struct expr *expr); + +/* initalize the base parser */ +int parser_init(struct lexer *lexer, struct parser *parser); + +/* free the base parser */ +void parser_free(struct parser *parser); + +#endif /* __PARSE_H__ */ diff --git a/masm/parse_mips32.c b/masm/parse_mips32.c new file mode 100644 index 0000000..bd07ce0 --- /dev/null +++ b/masm/parse_mips32.c @@ -0,0 +1,847 @@ +#include +#include +#include +#include +#include +#include + +#include "parse_mips32.h" +#include "parse.h" +#include "mlimits.h" +#include "parse.h" +#include "lex.h" + +/* each instruction has a given parse format + * internal to the parser */ +enum mips32_parse_format { + // register type: rs, rt, td + MIPS32_PARSE_R, + // register type: rs, rt + MIPS32_PARSE_R2, + // register type: rd + MIPS32_PARSE_RD, + // register type: rs + MIPS32_PARSE_RS, + // imeediate type: rs, rt, immd + MIPS32_PARSE_I, + // jump type: offset + MIPS32_PARSE_J, + // jump type: register + MIPS32_PARSE_JR, + // offset 16b type: offset + MIPS32_PARSE_O16, + // offset 26b type: offset + MIPS32_PARSE_O26, + // breanch equal type: rs, rt, offset + MIPS32_PARSE_BE, + // branch zero type: rs, offset + MIPS32_PARSE_BZ, + // store and load: rt, offset(base) + MIPS32_PARSE_SL, + // store and load immediate: rt, immediate + MIPS32_PARSE_SLI, + // shift: rd, rt, sa + MIPS32_PARSE_S, + // shift variable: rd, rt, rs + MIPS32_PARSE_SV, +}; + +#define FORMAT(ins, format) \ + [MIPS32_INS_##ins] = MIPS32_PARSE_##format, \ + +const enum mips32_parse_format mips32_parse_formats[] = { + FORMAT(ADD, R) + FORMAT(ADDI, I) + FORMAT(ADDIU, I) + FORMAT(ADDU, R) + FORMAT(AND, R) + FORMAT(ANDI, I) + FORMAT(BAL, O16) + FORMAT(BALC, O26) + FORMAT(BC, O26) + FORMAT(BEQ, BE) + FORMAT(BEQL, BE) + FORMAT(BGEZ, BZ) + FORMAT(BGEZAL, BZ) + FORMAT(BGEZALL, BZ) + FORMAT(BGEZL, BZ) + FORMAT(BGTZ, BZ) + FORMAT(BGTZL, BZ) + FORMAT(BLEZ, BZ) + FORMAT(BLEZL, BZ) + FORMAT(BLTZ, BZ) + FORMAT(BLTZAL, BZ) + FORMAT(BLTZALL, BZ) + FORMAT(BLTZL, BZ) + FORMAT(BNE, BE) + FORMAT(BNEL, BE) + FORMAT(DDIV, R2) + FORMAT(DDIVU, R2) + FORMAT(DIV, R2) + FORMAT(DIVU, R2) + FORMAT(J, J) + FORMAT(JAL, J) + FORMAT(JALR, JR) // TODO: handle rd + FORMAT(JALX, J) + FORMAT(JR, JR) + FORMAT(LB, SL) + FORMAT(LBU, SL) + FORMAT(LH, SL) + FORMAT(LHU, SL) + FORMAT(LUI, SLI) + FORMAT(LW, SL) + FORMAT(LWL, SL) + FORMAT(LWR, SL) + FORMAT(MFHI, RD) + FORMAT(MFLO, RD) + FORMAT(MTHI, RS) + FORMAT(MTLO, RS) + FORMAT(MULT, R2) + FORMAT(MULTU, R2) + FORMAT(SB, SL) + FORMAT(SH, SL) + FORMAT(SW, SL) + FORMAT(SWL, SL) + FORMAT(SLL, S) + FORMAT(SLLV, SV) + FORMAT(SLT, R) + FORMAT(SLTI, I) + FORMAT(SLTIU, I) + FORMAT(SLTU, R) + FORMAT(SRA, S) + FORMAT(SRAV, SV) + FORMAT(SRL, S) + FORMAT(SRLV, SV) + FORMAT(OR, R) + FORMAT(ORI, I) + FORMAT(NOR, R) + FORMAT(SUB, R) + FORMAT(SUBU, R) + FORMAT(XOR, R) + FORMAT(XORI, I) +}; + +#undef FORMAT + +#define MAX5 32 +#define MAX16 65536 +#define MAX26 67108864 + +static int get_reference(struct parser *parser, uint32_t *offset, + enum reference_type type) +{ + struct token token; + + if (next_token(parser, &token)) + return M_ERROR; + + if (token.type == TOK_NUMBER) { + *offset = token.number; + return M_SUCCESS; + } + + if (token.type != TOK_IDENT) { + ERROR_POS(token, "unexpected token of type '%s'", + token_str(token.type)); + return M_ERROR; + } + + struct reference reference = { + .section = parser->sec_tbl.current, + .index = parser->sec_tbl.current->count, + .type = type, + }; + strcpy(reference.name, token.text); + + if (reftbl_push(&parser->ref_tbl, reference)) + return M_ERROR; + + *offset = 0; + + return M_SUCCESS; +} + +static int get_offset(struct parser *parser, uint32_t *offset) +{ + return get_reference(parser, offset, REF_OFFESET); +} + +static int get_target(struct parser *parser, uint32_t *offset) +{ + return get_reference(parser, offset, REF_TARGET); +} + +static int get_instruction(const char *ident, struct mips32_instruction *res) +{ + for (int i = 0; i < __MIPS32_INS_LEN; i++) { + struct mips32_instruction ins = + mips32_instructions[i]; + if (strcasecmp(ident, ins.name) == 0) { + if (res != NULL) + *res = ins; + return M_SUCCESS; + } + } + return M_ERROR; +} + +static int is_instruction(const char *ident) +{ + return get_instruction(ident, NULL); +} + +static int parse_register(struct parser *parser, enum mips32_register *reg) +{ + struct token token; + if (assert_token(parser, TOK_REG, &token)) + return M_ERROR; + + int len = strlen(token.text); + int c0 = len > 0 ? token.text[0] : '\0', + c1 = len > 1 ? token.text[1] : '\0', + c2 = len > 2 ? token.text[2] : '\0', + c3 = len > 3 ? token.text[3] : '\0'; + + // $zero + if (c0 == 'z') { + if (c1 == 'e' && c2 == 'r' && c3 == 'o') { + *reg = MIPS32_REG_ZERO; + return M_SUCCESS; + } + } + + // $a0-a3 $at + else if (c0 == 'a') { + if (c1 == 't') { + *reg = MIPS32_REG_AT; + return M_SUCCESS; + } + if (c1 >= '0' && c1 <= '3') { + *reg = MIPS32_REG_A0; + *reg += c1 - '0'; + return M_SUCCESS; + } + } + + // $v0-v1 + else if (c0 == 'v') { + if (c1 >= '0' && c1 <= '1') { + *reg = MIPS32_REG_V0; + *reg += c1 - '0'; + return M_SUCCESS; + } + } + + // $t0-t9 + else if (c0 == 't') { + if (c1 >= '0' && c1 <= '7') { + *reg = MIPS32_REG_T0; + *reg += c1 - '0'; + return M_SUCCESS; + } + // reg T8-T9 are not in order with T0-T7 + if (c1 >= '8' && c1 <= '9') { + *reg = MIPS32_REG_T8; + *reg += c1 - '8'; + return M_SUCCESS; + } + } + + // $s0-s7 $sp + else if (c0 == 's') { + if (c1 >= '0' && c1 <= '7') { + *reg = MIPS32_REG_S0; + *reg += c1 - '0'; + return M_SUCCESS; + } + if (c1 == 'p') { + *reg = MIPS32_REG_SP; + return M_SUCCESS; + } + } + + // $k0-k1 + else if (c0 == 'k') { + if (c1 >= '0' && c1 <= '1') { + *reg = MIPS32_REG_K0; + *reg += c1 - '0'; + return M_SUCCESS; + } + } + + // $gp + else if (c0 == 'g') { + if (c1 == 'p') { + *reg = MIPS32_REG_GP; + return M_SUCCESS; + } + } + + // $fp + else if (c0 == 'f') { + if (c1 == 'p') { + *reg = MIPS32_REG_FP; + return M_SUCCESS; + } + } + + // $rp + else if (c0 == 'r') { + if (c1 == 'p') { + *reg = MIPS32_REG_RA; + return M_SUCCESS; + } + } + + // $0-31 (non aliased register names) + else if (c0 >= '0' && c0 <= '9') { + int i = c0 - '0'; + if (c1 >= '0' && c1 <= '9') { + i *= 10; + i += c1 - '0'; + } + if (i <= 31) { + *reg = i; + return M_SUCCESS; + } + } + + ERROR_POS(token, "unknown register $%s", token.text); + return M_ERROR; +} + +static int parse_instruction_r(struct parser *parser, + struct mips32_instruction *ins) +{ + // format: rs, rt, rd + enum mips32_register reg; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rd = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rs = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rt = reg; + + return M_SUCCESS; +} + +static int parse_instruction_r2(struct parser *parser, + struct mips32_instruction *ins) +{ + // format: rs, rt + enum mips32_register reg; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rs = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rt = reg; + + return M_SUCCESS; +} + +static int parse_instruction_rs(struct parser *parser, + struct mips32_instruction *ins) +{ + // format: rs + enum mips32_register reg; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rs = reg; + + return M_SUCCESS; +} + +static int parse_instruction_rd(struct parser *parser, + struct mips32_instruction *ins) +{ + // format: rd + enum mips32_register reg; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rd = reg; + + return M_SUCCESS; +} + +static int parse_instruction_i(struct parser *parser, + struct mips32_instruction *ins) +{ + // format: rs, rt, immd + enum mips32_register reg; + struct token token; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->I_data.rt = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->I_data.rs = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (assert_token(parser, TOK_NUMBER, &token)) + return M_ERROR; + + if (token.number >= MAX16) + return M_ERROR; + ins->I_data.immd = token.number; + + return M_SUCCESS; +} + +static int parse_instruction_offset(struct parser *parser, + uint32_t max, + struct mips32_instruction *ins) +{ + uint32_t n; + if (get_offset(parser, &n) || n > max) + return M_ERROR; + + switch (max) { + case MAX26: + ins->J_data.target = n; + break; + case MAX16: + ins->B_data.offset = n; + break; + } + + return M_SUCCESS; +} + +static int parse_instruction_j(struct parser *parser, + struct mips32_instruction *ins) +{ + uint32_t n; + if (get_target(parser, &n) || n > MAX26) + return M_ERROR; + ins->J_data.target = n; + + return M_SUCCESS; +} + +static int parse_instruction_jr(struct parser *parser, + struct mips32_instruction *ins) +{ + uint32_t n; + if (get_target(parser, &n) || n > MAX26) + return M_ERROR; + ins->J_data.target = n; + + return M_SUCCESS; +} + +static int parse_instruction_branch_equal(struct parser *parser, + struct mips32_instruction *ins) +{ + enum mips32_register reg; + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rs = reg; + + return M_SUCCESS; +} + +static int parse_instruction_branch(struct parser *parser, + struct mips32_instruction *ins) +{ + enum mips32_register reg; + uint32_t n; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->B_data.rs = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (get_offset(parser, &n) || n > MAX16) + return M_ERROR; + ins->B_data.offset = n; + + return M_SUCCESS; +} + +static int parse_instruction_sl(struct parser *parser, + struct mips32_instruction *ins) +{ + enum mips32_register reg; + uint32_t offset = 0; + struct token token; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->I_data.rt = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (peek_token(parser, &token)) + return M_ERROR; + + if (token.type != TOK_LPAREN) + if (get_offset(parser, &offset)) + return M_ERROR; + ins->I_data.immd = offset; + + if (peek_token(parser, &token)) + return M_ERROR; + + if (token.type == TOK_NL) { + ins->I_data.rs = MIPS32_REG_ZERO; + return M_SUCCESS; + } + + if (assert_token(parser, TOK_LPAREN, NULL)) + return M_ERROR; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->I_data.rs = reg; + + if (assert_token(parser, TOK_RPAREN, NULL)) + return M_ERROR; + + return M_SUCCESS; +} + +static int parse_instruction_sli(struct parser *parser, + struct mips32_instruction *ins) +{ + enum mips32_register reg; + struct token token; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->I_data.rt = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (assert_token(parser, TOK_NUMBER, &token) || token.number > MAX16) + return M_ERROR; + ins->I_data.immd = token.number; + + return M_SUCCESS; +} + +static int parse_instruction_s(struct parser *parser, + struct mips32_instruction *ins) +{ + enum mips32_register reg; + struct token token; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rd = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rt = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (assert_token(parser, TOK_NUMBER, &token) || token.number > MAX5) + return M_ERROR; + ins->R_data.shamt = token.number; + + return M_SUCCESS; +} + +static int parse_instruction_sv(struct parser *parser, + struct mips32_instruction *ins) +{ + enum mips32_register reg; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rd = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rt = reg; + + if (assert_token(parser, TOK_COMMA, NULL)) + return M_ERROR; + + if (parse_register(parser, ®)) + return M_ERROR; + ins->R_data.rs = reg; + + return M_SUCCESS; +} + +static int parse_instruction(struct parser *parser, + union mips_instruction *ins, + struct token ident) +{ + struct mips32_instruction instruction; + enum mips32_parse_format format; + int res = M_SUCCESS; + + if (get_instruction(ident.text, &instruction)) { + ERROR_POS(ident, "unknown instruction '%s'", ident.text); + return M_ERROR; + } + + ins->mips32 = instruction; + format = mips32_parse_formats[instruction.type]; + + switch (format) { + case MIPS32_PARSE_R: + res = parse_instruction_r(parser, &ins->mips32); + break; + case MIPS32_PARSE_R2: + res = parse_instruction_r2(parser, &ins->mips32); + break; + case MIPS32_PARSE_RS: + res = parse_instruction_rs(parser, &ins->mips32); + break; + case MIPS32_PARSE_RD: + res = parse_instruction_rd(parser, &ins->mips32); + break; + case MIPS32_PARSE_I: + res = parse_instruction_i(parser, &ins->mips32); + break; + case MIPS32_PARSE_J: + res = parse_instruction_j(parser, &ins->mips32); + break; + case MIPS32_PARSE_JR: + res = parse_instruction_jr(parser, &ins->mips32); + break; + case MIPS32_PARSE_O16: + res = parse_instruction_offset(parser, MAX16, &ins->mips32); + break; + case MIPS32_PARSE_O26: + res = parse_instruction_offset(parser, MAX26, &ins->mips32); + break; + case MIPS32_PARSE_BE: + res = parse_instruction_branch_equal(parser, &ins->mips32); + break; + case MIPS32_PARSE_BZ: + res = parse_instruction_branch(parser, &ins->mips32); + break; + case MIPS32_PARSE_SL: + res = parse_instruction_sl(parser, &ins->mips32); + break; + case MIPS32_PARSE_SLI: + res = parse_instruction_sli(parser, &ins->mips32); + break; + case MIPS32_PARSE_S: + res = parse_instruction_s(parser, &ins->mips32); + break; + case MIPS32_PARSE_SV: + res = parse_instruction_sv(parser, &ins->mips32); + break; + } + + if (res == M_SUCCESS && assert_eol(parser)) + return M_ERROR; + + return res; +} + + +static int parse_directive_align(struct parser *parser, + struct mips32_directive *directive) +{ + struct token token; + if (assert_token(parser, TOK_NUMBER, &token)) + return M_ERROR; + + if (token.number < 0) { + ERROR_POS(token, "cannot align negative"); + return M_ERROR; + } + + if (token.number > MAX16) { + ERROR_POS(token, "cannot align more than 65kb"); + return M_ERROR; + } + + directive->type = MIPS32_DIRECTIVE_ALIGN; + directive->align = token.number; + + return M_SUCCESS; +} + +static int parse_directive_space(struct parser *parser, + struct mips32_directive *directive) +{ + struct token token; + if (assert_token(parser, TOK_NUMBER, &token)) + return M_ERROR; + + if (token.number < 0) { + ERROR_POS(token, "cannot reserve negative"); + return M_ERROR; + } + + if (token.number > MAX16) { + ERROR_POS(token, "cannot reserve more than 65kb"); + return M_ERROR; + } + + directive->type = MIPS32_DIRECTIVE_SPACE; + directive->space = token.number; + + return M_SUCCESS; +} + +static int parse_directive_whb(struct parser *parser, + struct mips32_directive *directive, + enum mips32_directive_type type) +{ + struct token token; + uint32_t size = 0; + uint32_t len = 0; + + switch (type) { + case MIPS32_DIRECTIVE_WORD: + size = UINT32_MAX; + break; + case MIPS32_DIRECTIVE_HALF: + size = UINT16_MAX; + break; + case MIPS32_DIRECTIVE_BYTE: + size = UINT8_MAX; + break; + default: + } + + directive->type = type; + + while (1) { + if (assert_token(parser, TOK_NUMBER, &token)) + return M_ERROR; + + if (len >= MAX_ARG_LENGTH) { + ERROR_POS(token, "directives cannot be longer than " + "%d arguments", MAX_ARG_LENGTH); + return M_ERROR; + } + + if (token.number > size) { + ERROR_POS(token, "number cannot execede max size of: " + "%d", size); + return M_ERROR; + } + + switch (type) { + case MIPS32_DIRECTIVE_WORD: + directive->words[len++] = token.number; + break; + case MIPS32_DIRECTIVE_HALF: + directive->halfs[len++] = token.number; + break; + case MIPS32_DIRECTIVE_BYTE: + directive->bytes[len++] = token.number; + break; + default: + } + + if (peek_token(parser, &token)) + return M_ERROR; + + if (token.type == TOK_COMMA) { + next_token(parser, NULL); + continue; + } + + break; + } + + return M_SUCCESS; +} + +static int parse_section(struct parser *parser, + struct mips32_directive *directive, + char name[MAX_LEX_LENGTH]) +{ + directive->type = MIPS32_DIRECTIVE_SECTION; + strcpy(directive->name, name); + + struct section *sec; + if (sectbl_get(&parser->sec_tbl, &sec, name) == M_SUCCESS) { + parser->sec_tbl.current = sec; + return M_SUCCESS; + } + + if (sectbl_alloc(&parser->sec_tbl, &sec, name)) + return M_ERROR; + + parser->sec_tbl.current = sec; + return M_SUCCESS; +} + +static int parse_directive(struct parser *parser, + union mips_directive *directive) +{ + struct token token; + if (assert_token(parser, TOK_DIRECTIVE, &token)) + return M_ERROR; + + // .align n + if (strcmp(token.text, "align") == 0) + return parse_directive_align(parser, &directive->mips32); + else if (strcmp(token.text, "space") == 0) + return parse_directive_space(parser, &directive->mips32); + else if (strcmp(token.text, "word") == 0) + return parse_directive_whb(parser, &directive->mips32, + MIPS32_DIRECTIVE_WORD); + else if (strcmp(token.text, "half") == 0) + return parse_directive_whb(parser, &directive->mips32, + MIPS32_DIRECTIVE_HALF); + else if (strcmp(token.text, "byte") == 0) + return parse_directive_whb(parser, &directive->mips32, + MIPS32_DIRECTIVE_BYTE); + else + return parse_section(parser, &directive->mips32, token.text); +} + +int mips32_parser_init(struct lexer *lexer, struct parser *parser) +{ + if (parser_init(lexer, parser)) + return M_ERROR; + parser->parse_instruction = parse_instruction; + parser->is_instruction = is_instruction; + parser->parse_directive = parse_directive; + return M_SUCCESS; +} + +void mips32_parser_free(struct parser *parser) +{ + parser_free(parser); +} diff --git a/masm/parse_mips32.h b/masm/parse_mips32.h new file mode 100644 index 0000000..6de154f --- /dev/null +++ b/masm/parse_mips32.h @@ -0,0 +1,14 @@ +/* Copyright (c) 2024 Freya Murphy */ + +#ifndef __PARSE_MIPS32_H__ +#define __PARSE_MIPS32_H__ + +#include "parse.h" + +/* initzlize a mips32 parser*/ +int mips32_parser_init(struct lexer *lexer, struct parser *parser); + +/* free the mips32 parser */ +void mips32_parser_free(struct parser *parser); + +#endif /* __PARSE_MIPS32_H__ */ diff --git a/masm/reftbl.c b/masm/reftbl.c new file mode 100644 index 0000000..bdd1f07 --- /dev/null +++ b/masm/reftbl.c @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include + +#include "parse.h" + +#define RELTBL_INIT_LEN 8 + +int reftbl_init(struct reference_table *ref_tbl) +{ + ref_tbl->len = RELTBL_INIT_LEN; + ref_tbl->count = 0; + ref_tbl->references = malloc(sizeof(struct reference) * + RELTBL_INIT_LEN); + + if (ref_tbl->references == NULL) { + ERROR("cannot alloc"); + return M_ERROR; + } + + return M_SUCCESS; +} + +void reftbl_free(struct reference_table *ref_tbl) +{ + free(ref_tbl->references); +} + +int reftbl_push(struct reference_table *ref_tbl, struct reference reference) +{ + if (ref_tbl->count >= ref_tbl->len) { + ref_tbl->len *= 2; + ref_tbl->references = realloc(ref_tbl->references, + sizeof(struct reference) * ref_tbl->len); + + if (ref_tbl->references == NULL) { + ERROR("cannot realloc"); + return M_ERROR; + } + } + + ref_tbl->references[ref_tbl->count++] = reference; + + return M_SUCCESS; +} diff --git a/masm/sectbl.c b/masm/sectbl.c new file mode 100644 index 0000000..f568a6f --- /dev/null +++ b/masm/sectbl.c @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include + +#include "parse.h" + +#define SECTBL_INIT_LEN 8 +static const char inital_section[MAX_LEX_LENGTH] = "data"; + +int sectbl_init(struct section_table *sec_tbl) +{ + sec_tbl->len = SECTBL_INIT_LEN; + sec_tbl->count = 0; + sec_tbl->total_ins = 0; + sec_tbl->sections = malloc(sizeof(struct section) * SECTBL_INIT_LEN); + + if (sec_tbl->sections == NULL) { + ERROR("cannot alloc"); + return M_ERROR; + } + + if (sectbl_alloc(sec_tbl, &sec_tbl->current, inital_section)) + return M_ERROR; + + return M_SUCCESS; +} + +void sectbl_free(struct section_table *sec_tbl) +{ + for (uint32_t i = 0; i < sec_tbl->count; i++) { + free(sec_tbl->sections[i].ins); + } + free(sec_tbl->sections); +} + +int sectbl_alloc(struct section_table *sec_tbl, struct section **sec, + const char name[MAX_LEX_LENGTH]) +{ + if (sec_tbl->count >= sec_tbl->len) { + sec_tbl->len *= 2; + sec_tbl->sections = realloc(sec_tbl->sections, + sizeof(struct section) * sec_tbl->len); + + if (sec_tbl->sections == NULL) { + ERROR("cannot realloc"); + return M_ERROR; + } + } + + struct section *temp; + temp = &sec_tbl->sections[sec_tbl->count++]; + strcpy(temp->name,name); + temp->count = 0; + temp->len = SECTBL_INIT_LEN; + temp->start = sec_tbl->total_ins; + temp->alignment = 1; + temp->ins = malloc(sizeof(union mips_instruction) * SECTBL_INIT_LEN); + + if (temp->ins == NULL) { + ERROR("cannot alloc"); + return M_ERROR; + } + + *sec = temp; + return M_SUCCESS; +} + +int sectbl_push(struct section_table *sec_tbl, struct section *section, + union mips_instruction ins) +{ + if (section->count >= section->len) { + section->len *= 2; + section->ins = realloc(section->ins, + sizeof(union mips_instruction) * section->len); + + if (section->ins == NULL) { + ERROR("cannot realloc"); + return M_ERROR; + } + } + + section->ins[section->count++] = ins; + sec_tbl->total_ins++; + + return M_SUCCESS; +} + +int sectbl_get(struct section_table *sec_tbl, struct section **sec, + const char name[MAX_LEX_LENGTH]) +{ + for (uint32_t i = 0; i < sec_tbl->count; i++) { + struct section *temp = &sec_tbl->sections[i]; + if (strcmp(name, temp->name) == 0) { + if (sec != NULL) + *sec = temp; + return M_SUCCESS; + } + } + + return M_ERROR; +} diff --git a/masm/strtbl.c b/masm/strtbl.c new file mode 100644 index 0000000..b01bb92 --- /dev/null +++ b/masm/strtbl.c @@ -0,0 +1,49 @@ +#include +#include +#include + +#include "asm.h" + +int strtbl_get_str(struct str_table *str_tbl, const char *str, size_t *res) +{ + for (size_t i = 0; i < str_tbl->size; i ++) { + if (strcmp(str_tbl->ptr + i, str) == 0) { + if (res != NULL) + *res = i; + return M_SUCCESS; + } + } + + return M_ERROR; +} + +int strtbl_write_str(struct str_table *str_tbl, const char *str, size_t *res) +{ + if (strtbl_get_str(str_tbl, str, res) == M_SUCCESS) + return M_SUCCESS; + + size_t len = strlen(str); + char *new = realloc(str_tbl->ptr, str_tbl->size + len + 1); + if (new == NULL) + return M_ERROR; + str_tbl->ptr = new; + memcpy(str_tbl->ptr + str_tbl->size, str, len + 1); + + if (res != NULL) + *res = str_tbl->size; + + str_tbl->size += len + 1; + return M_SUCCESS; +} + +void strtbl_init(struct str_table *str_tbl) +{ + str_tbl->size = 1; + str_tbl->ptr = malloc(1); + *str_tbl->ptr = '\0'; +} + +void strtbl_free(struct str_table *str_tbl) +{ + free(str_tbl->ptr); +} diff --git a/masm/symtbl.c b/masm/symtbl.c new file mode 100644 index 0000000..b75c752 --- /dev/null +++ b/masm/symtbl.c @@ -0,0 +1,57 @@ +#include +#include +#include +#include + +#include "parse.h" + +#define SYMTBL_INIT_LEN 24 + +int symtbl_init(struct symbol_table *sym_tbl) +{ + sym_tbl->len = SYMTBL_INIT_LEN; + sym_tbl->count = 0; + sym_tbl->symbols = malloc(sizeof(struct symbol) * SYMTBL_INIT_LEN); + + if (sym_tbl->symbols == NULL) { + ERROR("cannot alloc"); + return M_ERROR; + } + + return M_SUCCESS; +} + +void symtbl_free(struct symbol_table *sym_tbl) +{ + free(sym_tbl->symbols); +} + +int symtbl_push(struct symbol_table *sym_tbl, struct symbol sym) +{ + if (sym_tbl->count >= sym_tbl->len) { + sym_tbl->len *= 2; + sym_tbl->symbols = realloc(sym_tbl->symbols, + sizeof(struct symbol) * sym_tbl->len); + if (sym_tbl->symbols == NULL) { + ERROR("cannot relloc"); + return M_ERROR; + } + } + + sym_tbl->symbols[sym_tbl->count++] = sym; + return M_SUCCESS; +} + +int symtbl_find(struct symbol_table *sym_tbl, struct symbol **ptr, + const char name[MAX_LEX_LENGTH]) +{ + for (uint32_t i = 0; i < sym_tbl->count; i++) { + struct symbol *sym = &sym_tbl->symbols[i]; + if (strcmp(sym->name, name) == 0) { + if (ptr != NULL) + *ptr = sym; + return M_SUCCESS; + } + } + return M_ERROR; +} diff --git a/masm/test.asm b/masm/test.asm new file mode 100644 index 0000000..c3b61fb --- /dev/null +++ b/masm/test.asm @@ -0,0 +1,22 @@ +.text +.align 2 + +main: + add $zero,$t7,$t7 + xori $a0, $v1, 69 + addi $a0, $v1, 69 + nor $s0, $s1, $s2 + + bltzall $s7, 0x50 + + lui $t7, 0x55 + lw $t0, 18($t7) + + sll $t0, $s0, 17 +test: + mult $a0, $s6 + + mfhi $s0 + mtlo $s7 + + j test