From 7ebe14b3275fba00662e0c0ceeabe96343d04c5a Mon Sep 17 00:00:00 2001 From: andromeda Date: Mon, 19 Oct 2026 01:41:59 -0400 Subject: init --- .gitignore | 4 + LICENSE | 674 +++++++++++++++++++++++++ lib/uefi.c3l/LICENSE | 21 + lib/uefi.c3l/README.md | 77 +++ lib/uefi.c3l/manifest.json | 22 + lib/uefi.c3l/src/def.c3i | 240 +++++++++ lib/uefi.c3l/src/err.c3 | 129 +++++ lib/uefi.c3l/src/exports.c3 | 207 ++++++++ lib/uefi.c3l/src/guid.c3 | 82 +++ lib/uefi.c3l/src/lib/console.c3 | 132 +++++ lib/uefi.c3l/src/lib/init.c3 | 92 ++++ lib/uefi.c3l/src/lib/input.c3 | 36 ++ lib/uefi.c3l/src/lib/private/print.c3 | 159 ++++++ lib/uefi.c3l/src/lib/string.c3 | 145 ++++++ lib/uefi.c3l/src/lib/system.c3 | 268 ++++++++++ lib/uefi.c3l/src/lib/util.c3 | 19 + lib/uefi.c3l/src/protocol/console.c3 | 225 +++++++++ lib/uefi.c3l/src/protocol/evt_timer_task.c3 | 103 ++++ lib/uefi.c3l/src/protocol/handler.c3 | 86 ++++ lib/uefi.c3l/src/protocol/image.c3 | 27 + lib/uefi.c3l/src/protocol/mem.c3 | 105 ++++ lib/uefi.c3l/src/protocol/misc_boot_svcs.c3 | 25 + lib/uefi.c3l/src/protocol/misc_runtime_svcs.c3 | 124 +++++ lib/uefi.c3l/src/protocol/time.c3 | 23 + lib/uefi.c3l/src/protocol/variable.c3 | 68 +++ project.json | 45 ++ src/main.c3 | 8 + 27 files changed, 3146 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 lib/uefi.c3l/LICENSE create mode 100644 lib/uefi.c3l/README.md create mode 100644 lib/uefi.c3l/manifest.json create mode 100644 lib/uefi.c3l/src/def.c3i create mode 100644 lib/uefi.c3l/src/err.c3 create mode 100644 lib/uefi.c3l/src/exports.c3 create mode 100644 lib/uefi.c3l/src/guid.c3 create mode 100644 lib/uefi.c3l/src/lib/console.c3 create mode 100644 lib/uefi.c3l/src/lib/init.c3 create mode 100644 lib/uefi.c3l/src/lib/input.c3 create mode 100644 lib/uefi.c3l/src/lib/private/print.c3 create mode 100644 lib/uefi.c3l/src/lib/string.c3 create mode 100644 lib/uefi.c3l/src/lib/system.c3 create mode 100644 lib/uefi.c3l/src/lib/util.c3 create mode 100644 lib/uefi.c3l/src/protocol/console.c3 create mode 100644 lib/uefi.c3l/src/protocol/evt_timer_task.c3 create mode 100644 lib/uefi.c3l/src/protocol/handler.c3 create mode 100644 lib/uefi.c3l/src/protocol/image.c3 create mode 100644 lib/uefi.c3l/src/protocol/mem.c3 create mode 100644 lib/uefi.c3l/src/protocol/misc_boot_svcs.c3 create mode 100644 lib/uefi.c3l/src/protocol/misc_runtime_svcs.c3 create mode 100644 lib/uefi.c3l/src/protocol/time.c3 create mode 100644 lib/uefi.c3l/src/protocol/variable.c3 create mode 100644 project.json create mode 100644 src/main.c3 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b04841 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build/ +out/ +build/ +out/ 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/lib/uefi.c3l/LICENSE b/lib/uefi.c3l/LICENSE new file mode 100644 index 0000000..e3cd020 --- /dev/null +++ b/lib/uefi.c3l/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Zack Puhl + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/lib/uefi.c3l/README.md b/lib/uefi.c3l/README.md new file mode 100644 index 0000000..f9cb4e3 --- /dev/null +++ b/lib/uefi.c3l/README.md @@ -0,0 +1,77 @@ +# uefi.c3l - UEFI Definitions & Library for C3 +A gnu-efi-like library enabling UEFI bootloader development in C3. + + +## Installation +The library is incredibly easy to pull and use right away. + +1. Change to your project's `lib` directory. +2. Clone this repository: `git clone https://github.com/NotsoanoNimus/uefi.c3l.git`. +3. Start developing with `import uefi;` where needed. + +Most c3c projects will automatically source modules from their `lib` folders. If this is not the case, you can use the following `c3c` parameters to source the library: `--lib uefi --libdir lib/` + +This will certainly be improved as the project becomes more mature. + + +## Compiling EFI Binaries +I need to revisit this, but I have been successfully compiling my EFI test binaries with the following: +``` +~$ c3c compile-only src/*.c3 --link-libc=no --no-entry \ + --target windows-x64 --lib uefi --libdir ./lib + +~$ clang -target x86_64-unknown-windows -nostdlib -fno-stack-protector -mno-red-zone \ + -ffreestanding -fPIC -Wl,-entry:efi_main -Wl,-subsystem:efi_application \ + -fuse-ld=lld-link -mno-stack-arg-probe -v -o test.efi ./obj/windows-x64/*.obj +``` + +I'm pretty sure I'm switching up my compilation and linker arguments for this right now. :shrug: Again, to be improved as the project matures. + +This snippet explicitly uses `clang` and `lld-link` in order to generate the EFI application. For me, it's a must; however, others may be more comfortable linking with another tool like `gcc`. It's all the same after `c3c` generates its objects. + + +## Example Usage +The following example shows what a "Hello World" style EFI application might look like in C3. When it starts, it sets a baseline console color, clears the window, and attempts to enable the Graphics Output Protocol and draw a simple rectangle. + +Some of these methods currently don't exist; this is more of a "finished product" presentation. + + +```cpp +module hello_uefi; + +import uefi; + + +fn EfiStatus efi_main(EfiHandle image_handle, SystemTable* system_table) @export("efi_main") +{ + pre_load::init(image_handle, system_table)!!; + + console::clear_to({YELLOW, RED}); + + io::cprintn(@wstring("Enabling GOP mode..."), {GREEN, BLACK})!!; + + if (catch excuse = sys::enable_gop()) { + io::cprintn(@wstring("ERROR: Failed to initialize Graphics Output Protocol."), {RED, BLACK})!!; + } else { + gop::draw_rect( + {0, 0, 100, 200}, + {{0xff, 0x12, 0x34, 0x56}, {.a = 0xff, .r = 0xdd}} /* {r,g,b,a} */ + ); + } + + sys::@stall(s2us(3)); /* s2us == sec-to-microsec */ + sys::@reset(SHUTDOWN); +} + +``` + + +## TODOs +In no particular order... +- [ ] Finish C3 standard library integration, to provide helpful constructs like String formatting and such. +- [ ] Implement all macro exports for System, Console, etc. +- [ ] Organize library imports such that `uefi` isn't just bulk-imported everywhere. +- [ ] Unit/Integration testing. + - Not sure if this will require a mock UEFI environment, or if it will need to be on a function-by-function basis. We'll see. +- [ ] Graphics library support and support functions . + - [ ] e.g. an optional BLT-based framebuffer lib. diff --git a/lib/uefi.c3l/manifest.json b/lib/uefi.c3l/manifest.json new file mode 100644 index 0000000..40fe81e --- /dev/null +++ b/lib/uefi.c3l/manifest.json @@ -0,0 +1,22 @@ +{ + "provides" : "uefi", + "sources" : [ "src/**" ], + "targets" : { + "windows-aarch64" : { + // Extra flags to the linker for this target: + "link-args" : [], + // C3 libraries this target depends on: + "dependencies" : [], + // The external libraries to link for this target: + "linked-libraries" : [] + }, + "windows-x64" : { + // Extra flags to the linker for this target: + "link-args" : [ "-nostdlib", "-ffreestanding" ], + // C3 libraries this target depends on: + "dependencies" : [], + // The external libraries to link for this target: + "linked-libraries" : [] + }, + } +} diff --git a/lib/uefi.c3l/src/def.c3i b/lib/uefi.c3l/src/def.c3i new file mode 100644 index 0000000..f595caa --- /dev/null +++ b/lib/uefi.c3l/src/def.c3i @@ -0,0 +1,240 @@ +module uefi; + + +/* + * EFI_HANDLE alias (sec x.x.x of the UEFI 2.11 specification). + */ +typedef EfiHandle = void*; + +/* + * All UEFI strings are wchar_t strings (Wide-Char types). + */ +alias EfiString = ushort[]; +alias EfiStringRaw = ushort*; + +/* + * ... But ASCII strings can also be used and dynamically converted to wide ones. + */ +alias AsciiString = char[]; +alias AsciiStringRaw = char*; + +/* + * EFI_EVENT alias (sec 7.1.1 of the UEFI 2.11 specification). + */ +typedef EfiEvent = void*; + + +/* + * EFI_TABLE_HEADER structure (sec 4.2.1 of the UEFI 2.11 specification). + * The same section contains the following constant expressions + * as well as the EFI_SYSTEM_TABLE structure. + */ +struct EfiTableHeader @packed +{ + ulong signature; + uint revision; + uint header_size; + uint crc32; + uint _reserved; +} + +const ulong EFI_SYSTEM_TABLE_SIGNATURE = 0x5453595320494249; +const uint EFI_2_100_SYSTEM_TABLE_REVISION = ((2<<16) | (100)); +const uint EFI_2_90_SYSTEM_TABLE_REVISION = ((2<<16) | (90)); +const uint EFI_2_80_SYSTEM_TABLE_REVISION = ((2<<16) | (80)); +const uint EFI_2_70_SYSTEM_TABLE_REVISION = ((2<<16) | (70)); +const uint EFI_2_60_SYSTEM_TABLE_REVISION = ((2<<16) | (60)); +const uint EFI_2_50_SYSTEM_TABLE_REVISION = ((2<<16) | (50)); +const uint EFI_2_40_SYSTEM_TABLE_REVISION = ((2<<16) | (40)); +const uint EFI_2_31_SYSTEM_TABLE_REVISION = ((2<<16) | (31)); +const uint EFI_2_30_SYSTEM_TABLE_REVISION = ((2<<16) | (30)); +const uint EFI_2_20_SYSTEM_TABLE_REVISION = ((2<<16) | (20)); +const uint EFI_2_10_SYSTEM_TABLE_REVISION = ((2<<16) | (10)); +const uint EFI_2_00_SYSTEM_TABLE_REVISION = ((2<<16) | (00)); +const uint EFI_1_10_SYSTEM_TABLE_REVISION = ((1<<16) | (10)); +const uint EFI_1_02_SYSTEM_TABLE_REVISION = ((1<<16) | (02)); +const uint EFI_SYSTEM_TABLE_REVISION = EFI_2_100_SYSTEM_TABLE_REVISION; +const uint EFI_SPECIFICATION_VERSION = EFI_SYSTEM_TABLE_REVISION; + +/* NOTE: Do NOT pack this struct: firmware_revision being 32-bit causes misalignment */ +struct SystemTable +{ + EfiTableHeader header; + EfiStringRaw firmware_vendor; + uint firmware_revision; + EfiHandle conin_handle; + SimpleTextInputProtocol *conin; + EfiHandle conout_handle; + SimpleTextOutputProtocol *conout; + EfiHandle conerr_handle; + SimpleTextOutputProtocol *conerr; + RuntimeServices *runtime_services; + BootServices *boot_services; + usz num_entries; + ConfigurationTable *configuration_table; +} + + +/* + * EFI_CONFIGURATION_TABLE structure (sec 4.6.1 of the UEFI 2.11 specification). + */ +struct ConfigurationTable @packed +{ + EfiGuid vendor_guid; + void *vendor_table; +} + + +/* EFI_BOOT_SERVICES structure (4.4.1) */ +const ulong EFI_BOOT_SERVICES_SIGNATURE = 0x56524553544f4f42; //'BOOTSERV' <- EightCC +const uint EFI_BOOT_SERVICES_REVISION = EFI_SPECIFICATION_VERSION; + +struct BootServices @packed +{ + EfiTableHeader header; + + /* Task priority services (uefi::proto::evt) */ + FnRaiseTpl raise_tpl; + FnRestoreTpl restore_tpl; + + /* Memory services (uefi::proto::mem) */ + FnAllocatePages allocate_pages; + FnFreePages free_pages; + FnGetMemoryMap get_memory_map; + FnAllocatePool allocate_pool; + FnFreePool free_pool; + + /* Event and Timer services (uefi::proto::evt) */ + FnCreateEvent create_event; + FnSetTimer set_timer; + FnWaitForEvent wait_for_event; + FnSignalEvent signal_event; + FnCloseEvent close_event; + FnCheckEvent check_event; + + /* Protocol Handler services (uefi::proto::handler) */ + FnInstallProtocolInterface install_protocol_interface; + FnReinstallProtocolInterface reinstall_protocol_interface; + FnUninstallProtocolInterface uninstall_protocol_interface; + FnHandleProtocol handle_protocol; + void *_reserved; /* alright then */ + FnRegisterProtocolNotify register_protocol_notify; + FnLocateHandle locate_handle; + FnLocateDevicePath locate_device_path; + FnInstallConfigurationTable install_configuration_table; + + /* Image services (uefi::proto::image) */ + FnLoadImage load_image; + FnStartImage start_image; + FnExitImage exit_image; + FnUnloadImage unload_image; + FnExitBootServices exit_boot_services; + + /* Misc services (uefi::proto::misc_bs) */ + FnGetNextMonotonicCount get_next_monotonic_count; + FnStall stall; + FnSetWatchdogTimer set_watchdog_timer; + + /* Driver Support services (uefi::proto::handler) */ + FnConnectController connect_controller; + FnDisconnectController disconnect_controller; + + /* Open/Close Protocol services (uefi::proto::handler) */ + FnOpenProtocol open_protocol; + FnCloseProtocol close_protocol; + FnOpenProtocolInformation open_protocol_information; + + /* Library services (uefi::proto::handler) */ + FnProtocolsPerHandle protocols_per_handle; + FnLocateHandleBuffer locate_handle_buffer; + FnLocateProtocol locate_protocol; + FnInstallMultipleProtocolInterfaces install_multiple_protocol_interfaces; + FnUninstallMultipleProtocolInterfaces uninstall_multiple_protocol_interfaces; + + /* 32-bit CRC services (uefi::proto::misc_bs) */ + FnCalculateCrc32 calculate_crc32; + + /* More misc/trailing services */ + FnCopyMem copy_mem; + FnSetMem set_mem; + FnCreateEventEx create_event_ex; +} + + +struct RuntimeServices @packed +{ + EfiTableHeader header; + + /* Time services (uefi::proto::time) */ + FnGetTime get_time; + FnSetTime set_time; + FnGetWakeupTime get_wakeup_time; + FnSetWakeupTime set_wakeup_time; + + /* Virtual Memory services (uefi::proto::mem) */ + FnSetVirtualAddressMap set_virtual_address_map; + FnConvertPointer convert_pointer; + + /* Variable services (uefi::proto::variable) */ + FnGetVariable get_variable; + FnGetNextVariableName get_next_variable_name; + FnSetVariable set_variable; + + /* Miscellaneous and Capsule services (uefi::proto::misc_rt) */ + FnGetNextHighMonotonicCount get_next_high_monotonic_count; + FnResetSystem reset_system; + FnUpdateCapsule update_capsule; + FnQueryCapsuleCapabilities query_capsule_capabilities; + FnQueryVariableInfo query_variable_info; +} + + + +/* + * EFI_GUID structure (sec x.x.x of the UEFI 2.11 specification). + */ +struct EfiGuid @packed +{ + uint data1; + ushort data2; + ushort data3; + char[8] data4; +} + + +/* + * EFI_TIME structure (sec 8.3.1 of the UEFI 2.11 specification). + */ +struct EfiTime @packed +{ + ushort year; + char month; + char day; + char hour; + char minute; + char second; + char _pad1; + uint nanosecond; + short timezone; + EfiDaylightFlags daylight; + char _pad2; +} + +bitstruct EfiDaylightFlags : char +{ + bool adjust : 0; + bool in_daylight : 1; + char reserved : 2..7; +} + +const short EFI_UNSPECIFIED_TIMEZONE = 0x07FF; + +/* + * EFI_TIME_CAPABILITIES (sec 8.3.1 of the UEFI 2.11 specification). + */ +struct EfiTimeCapabilities @packed +{ + uint resolution; + uint accuracy; + bool sets_to_zero; +} diff --git a/lib/uefi.c3l/src/err.c3 b/lib/uefi.c3l/src/err.c3 new file mode 100644 index 0000000..d21729b --- /dev/null +++ b/lib/uefi.c3l/src/err.c3 @@ -0,0 +1,129 @@ +/* EFI errors can actually be faults: they should raise exceptions + in the handling of a program, if the user so chooses to. */ +module uefi::efi_error; +faultdef + NO_FAULT, + LOAD_ERROR, + INVALID_PARAMETER, + UNSUPPORTED, + BAD_BUFFER_SIZE, + BUFFER_TOO_SMALL, + NOT_READY, + DEVICE_ERROR, + WRITE_PROTECTED, + OUT_OF_RESOURCES, + VOLUME_CORRUPTED, + VOLUME_FULL, + NO_MEDIA, + MEDIA_CHANGED, + NOT_FOUND, + ACCESS_DENIED, + NO_RESPONSE, + NO_MAPPING, + TIMEOUT, + NOT_STARTED, + ALREADY_STARTED, + ABORTED, + ICMP_ERROR, + TFTP_ERROR, + PROTOCOL_ERROR, + INCOMPATIBLE_VERSION, + SECURITY_VIOLATION, + CRC_ERROR, + END_OF_MEDIA, + UNKNOWN_29, // NOTE: UEFI spec is missing this definition. + UNKNOWN_30, // NOTE: UEFI spec is missing this definition. + END_OF_FILE, + INVALID_LANGUAGE, + COMPROMISED_DATA, + IP_ADDRESS_CONFLICT, + HTTP_ERROR, + EFILIB_UNINITIALIZED, // Used for efilib calls when init() hasn't been called. + UNKNOWN_STATUS; /* Fallback for an unknown status code. */ + +module uefi::efi_warning; +faultdef + UNKNOWN_GLYPH, DELETE_FAILURE, WRITE_FAILURE, BUFFER_TOO_SMALL, STALE_DATA, FILE_SYSTEM, RESET_REQUIRED; + + +module uefi; + +import uefi::efi_error; +import uefi::efi_warning; + +/** EFI_STATUS enum (apx D of the UEFI 2.11 specification). */ +macro @efi_err($x) @private => (usz)((1l << ((usz::size * 8) - 1)) | $x); +macro @efi_warn($x) @private => (usz)$x; + +enum EfiStatus : usz (usz raw, fault fault_type) +{ + SUCCESS { 0, efi_error::NO_FAULT }, + + LOAD_ERROR { @efi_err(1), efi_error::LOAD_ERROR }, + INVALID_PARAMETER { @efi_err(2), efi_error::INVALID_PARAMETER }, + UNSUPPORTED { @efi_err(3), efi_error::UNSUPPORTED }, + BAD_BUFFER_SIZE { @efi_err(4), efi_error::BAD_BUFFER_SIZE }, + BUFFER_TOO_SMALL { @efi_err(5), efi_error::BUFFER_TOO_SMALL }, + NOT_READY { @efi_err(6), efi_error::NOT_READY }, + DEVICE_ERROR { @efi_err(7), efi_error::DEVICE_ERROR }, + WRITE_PROTECTED { @efi_err(8), efi_error::WRITE_PROTECTED }, + OUT_OF_RESOURCES { @efi_err(9), efi_error::OUT_OF_RESOURCES }, + VOLUME_CORRUPTED { @efi_err(10), efi_error::VOLUME_CORRUPTED }, + VOLUME_FULL { @efi_err(11), efi_error::VOLUME_FULL }, + NO_MEDIA { @efi_err(12), efi_error::NO_MEDIA }, + MEDIA_CHANGED { @efi_err(13), efi_error::MEDIA_CHANGED }, + NOT_FOUND { @efi_err(14), efi_error::NOT_FOUND }, + ACCESS_DENIED { @efi_err(15), efi_error::ACCESS_DENIED }, + NO_RESPONSE { @efi_err(16), efi_error::NO_RESPONSE }, + NO_MAPPING { @efi_err(17), efi_error::NO_MAPPING }, + TIMEOUT { @efi_err(18), efi_error::TIMEOUT }, + NOT_STARTED { @efi_err(19), efi_error::NOT_STARTED }, + ALREADY_STARTED { @efi_err(20), efi_error::ALREADY_STARTED }, + ABORTED { @efi_err(21), efi_error::ABORTED }, + ICMP_ERROR { @efi_err(22), efi_error::ICMP_ERROR }, + TFTP_ERROR { @efi_err(23), efi_error::TFTP_ERROR }, + PROTOCOL_ERROR { @efi_err(24), efi_error::PROTOCOL_ERROR }, + INCOMPATIBLE_VERSION { @efi_err(25), efi_error::INCOMPATIBLE_VERSION }, + SECURITY_VIOLATION { @efi_err(26), efi_error::SECURITY_VIOLATION }, + CRC_ERROR { @efi_err(27), efi_error::CRC_ERROR }, + END_OF_MEDIA { @efi_err(28), efi_error::END_OF_MEDIA }, + UNKNOWN_29 { @efi_err(29), efi_error::UNKNOWN_29 }, /* NOTE: UEFI spec is missing this definition. */ + UNKNOWN_30 { @efi_err(30), efi_error::UNKNOWN_30 }, /* NOTE: UEFI spec is missing this definition. */ + END_OF_FILE { @efi_err(31), efi_error::END_OF_FILE }, + INVALID_LANGUAGE { @efi_err(32), efi_error::INVALID_LANGUAGE }, + COMPROMISED_DATA { @efi_err(33), efi_error::COMPROMISED_DATA }, + IP_ADDRESS_CONFLICT { @efi_err(34), efi_error::IP_ADDRESS_CONFLICT }, + HTTP_ERROR { @efi_err(35), efi_error::HTTP_ERROR }, + + WARN_UNKNOWN_GLYPH { @efi_warn(1), efi_warning::UNKNOWN_GLYPH }, + WARN_DELETE_FAILURE { @efi_warn(2), efi_warning::DELETE_FAILURE }, + WARN_WRITE_FAILURE { @efi_warn(3), efi_warning::WRITE_FAILURE }, + WARN_BUFFER_TOO_SMALL { @efi_warn(4), efi_warning::BUFFER_TOO_SMALL }, + WARN_STALE_DATA { @efi_warn(5), efi_warning::STALE_DATA }, + WARN_FILE_SYSTEM { @efi_warn(6), efi_warning::FILE_SYSTEM }, + WARN_RESET_REQUIRED { @efi_warn(7), efi_warning::RESET_REQUIRED }, +} + + +// ////////////////////////////////////////////////////////////////////// +<* + Handle EFI errors when they occur. + @param status : `The EfiStatus code to check` + @param throw_on_warnings : `Return a ``true`` value on EFI_WARN_... codes` + @return ```false`` on success. ``true`` when ``throw_on_warnings`` is false and ``status`` is a warning. Returns a fault otherwise.` +*> +fn bool? efi_error(EfiStatus status, bool throw_on_warnings = true) @export("efi_error") @builtin +{ + switch + { + case status == SUCCESS: return false; + + case status >= EfiStatus.WARN_UNKNOWN_GLYPH && status <= EfiStatus.WARN_RESET_REQUIRED: + return throw_on_warnings ? status.fault_type~ : true; + + case status >= EfiStatus.LOAD_ERROR && status <= EfiStatus.HTTP_ERROR: + return status.fault_type~; + } + + return efi_error::UNKNOWN_STATUS~; +} \ No newline at end of file diff --git a/lib/uefi.c3l/src/exports.c3 b/lib/uefi.c3l/src/exports.c3 new file mode 100644 index 0000000..3b337e3 --- /dev/null +++ b/lib/uefi.c3l/src/exports.c3 @@ -0,0 +1,207 @@ +// ------------------------------------------------------------------ +module uefi; +import uefi::efi_system @public; + + +extern fn void initialize_lib(EfiHandle, SystemTable*); + +PanicFn panic_func = (PanicFn)&uefi::efilib::pre_load::default_panic; + + +// ------------------------------------------------------------------ +module uefi::io; +import uefi; +import uefi::efi_system @public; + + +// interface LibcFile +// { +// // +// } +// typedef OutStream (LibcFile) = uptr; +// const OutStream STDERR @export("stderr") = (OutStream)efi_system::efi_sys.console.stderr; + +macro EfiStatus? memdump( + void* ptr, + usz len, + usz $align = 16 +) @maydiscard => efi_system::efi_sys.console.printn(a2w(efi_system::efi_sys.create_memdump(ptr, len, $align))); +macro EfiStatus? cmemdump( + ConsoleColor color, + void* ptr, + usz len, + usz $align = 16 +) @maydiscard => efi_system::efi_sys.console.cprintn(color, a2w(efi_system::efi_sys.create_memdump(ptr, len, $align))); + +macro EfiStatus? wprint(EfiString str) @maydiscard => efi_system::efi_sys.console.print(str); +macro EfiStatus? wprintn(EfiString str) @maydiscard => efi_system::efi_sys.console.printn(str); +macro EfiStatus? wfprint( + SimpleTextOutputProtocol* stream, + EfiString str +) @maydiscard => efi_system::efi_sys.console.print(str, stream); +macro EfiStatus? wfprintn( + SimpleTextOutputProtocol* stream, + EfiString str +) @maydiscard => efi_system::efi_sys.console.printn(str, stream); +macro EfiStatus? wprinte(EfiString str, args...) @maydiscard => efi_system::efi_sys.console.printe(str, ...args); +macro EfiStatus? wfprinte( + SimpleTextOutputProtocol* stream, + EfiString str, + args... +) @maydiscard => efi_system::efi_sys.console.fprinte(stream, str, ...args); + +macro EfiStatus? print(AsciiString str) @maydiscard => efi_system::efi_sys.console.print(a2w(str)); +macro EfiStatus? printn(AsciiString str) @maydiscard => efi_system::efi_sys.console.printn(a2w(str)); +macro EfiStatus? fprint( + SimpleTextOutputProtocol* stream, + AsciiString str +) @maydiscard => efi_system::efi_sys.console.print(a2w(str), stream); +macro EfiStatus? fprintn( + SimpleTextOutputProtocol* stream, + AsciiString str +) @maydiscard => efi_system::efi_sys.console.printn(a2w(str), stream); +macro EfiStatus? printe(AsciiString str, args...) @maydiscard => efi_system::efi_sys.console.printn(a2w(str), ...args); +macro EfiStatus? fprinte( + SimpleTextOutputProtocol* stream, + AsciiString str, + args... +) @maydiscard => efi_system::efi_sys.console.printn(stream, a2w(str), ...args); + +macro EfiStatus? wcprint( + ConsoleColor color, + EfiString str +) @maydiscard => efi_system::efi_sys.console.cprint(color, str); +macro EfiStatus? wcprintn( + ConsoleColor color, + EfiString str +) @maydiscard => efi_system::efi_sys.console.cprintn(color, str); +macro EfiStatus? wcprinte( + ConsoleColor color, + EfiString str, + args... +) @maydiscard => efi_system::efi_sys.console.cprinte(color, str, ...args); +macro EfiStatus? cprint( + ConsoleColor color, + AsciiString str +) @maydiscard => efi_system::efi_sys.console.cprint(color, a2w(str)); +macro EfiStatus? cprintn( + ConsoleColor color, + AsciiString str +) @maydiscard => efi_system::efi_sys.console.cprintn(color, a2w(str)); +macro EfiStatus? cprinte( + ConsoleColor color, + AsciiString str, + args... +) @maydiscard => efi_system::efi_sys.console.cprinte(color, a2w(str), ...args); + + +// ------------------------------------------------------------------ +module uefi::str; +import uefi; +import uefi::efi_system @public; + + +// + + +// ------------------------------------------------------------------ +module uefi::console; +import uefi; +import uefi::efi_system @public; + + +macro void? clear_to( + ConsoleColor color, + bool preserve = false, + bool reset_cursor = true +) @maydiscard => efi_system::efi_sys.console.clear(color, preserve, reset_cursor); +macro void? clear() @maydiscard => (void)(efi_error( + efi_system::efi_sys.console.stdout.clear_screen(efi_system::efi_sys.console.stdout) +)!); + + +// ------------------------------------------------------------------ +module uefi::sys; +import uefi; +import uefi::efi_system @public; + + +macro BootServices* bs() => efi_system::efi_sys.boot_services; +macro RuntimeServices* rs() => efi_system::efi_sys.runtime_services; +macro SystemTable* st() => efi_system::efi_sys.system_table; +macro EfiHandle image() => efi_system::efi_sys.image_handle; + +macro SimpleTextOutputProtocol* stdout() => efi_system::efi_sys.console.stdout; +macro SimpleTextOutputProtocol* stderr() => efi_system::efi_sys.console.stderr; +macro any stdin() => !sys::stdin_extended() ? efi_system::efi_sys.console.stdin : efi_system::efi_sys.console.stdin_ex; +macro bool stdin_extended() => null != efi_system::efi_sys.console.stdin_ex; + +macro void @stall(usz $duration) @builtin => efi_system::efi_sys.stall($duration); + +macro void @reset( + ResetType $type, + EfiStatus code = SUCCESS, + char[] buffer = { } +) @noreturn @builtin => efi_system::efi_sys.reset($type, code, buffer); + +macro void hang() @noreturn +{ + sys::@disable_watchdog(); + while (true) sys::@stall(500_000); +} +macro void halt() @noreturn => sys::hang(); +fn void lock() @noreturn +{ + while (true);} + +macro void @panic( + $message +) @builtin => efi_system::efi_sys.panic( + "[" +++ $$FILE +++ ":" +++ $$FUNC +++ ":" +++ $$LINE +++ "] PANIC! " +++ $message +); + +macro bool? @set_watchdog(usz $seconds) @maydiscard => efi_system::efi_sys.set_watchdog_timer($seconds); +macro bool? @disable_watchdog() @maydiscard => efi_system::efi_sys.set_watchdog_timer(0); +macro bool? set_watchdog_full( + usz seconds, + ulong code = -1, + usz data_size = 0, + EfiStringRaw data = null +) @maydiscard => efi_system::efi_sys.set_watchdog_timer(seconds, code, data_size, data); + +macro ulong? get_next_monotonic_count() @maydiscard => efi_system::efi_sys.get_next_monotonic_count(); + +macro uint? get_crc32(void* data @noalias, usz data_size) => efi_system::efi_sys.calculate_crc32(data, data_size); + +macro SystemMemoryMap*? get_memory_map() => efi_system::efi_sys.get_memory_map(); + + +// ------------------------------------------------------------------ +module uefi::mem; +import uefi; +import uefi::efi_system @public; + + +fn void* memcpy(void* into, void* from, usz length) @export("memcpy") @nostrip +{ + efi_system::efi_sys.memcpy(into, from, length); + return into; +} + +fn void memset( + void* at, + char value, + usz length +) @export("memset") @nostrip => efi_system::efi_sys.memset(at, value, length); + +fn void* malloc(usz size) @export("malloc") @nostrip => efi_system::efi_sys.malloc(size)!!; +fn void* calloc(usz num, usz size) @export("calloc") @nostrip => efi_system::efi_sys.calloc(num, size)!!; + +fn void* realloc( + void* pool, + usz prev_len, + usz new_len +) @export("realloc") @nostrip => efi_system::efi_sys.realloc(pool, prev_len, new_len)!!; + +fn void free(void* pool) @export("free") @nostrip => efi_system::efi_sys.free(pool); +fn void? free_safe(void* pool) @export("free_safe") @nostrip => efi_system::efi_sys.free_safe(pool); \ No newline at end of file diff --git a/lib/uefi.c3l/src/guid.c3 b/lib/uefi.c3l/src/guid.c3 new file mode 100644 index 0000000..25d1c7b --- /dev/null +++ b/lib/uefi.c3l/src/guid.c3 @@ -0,0 +1,82 @@ +module uefi::guid; +import uefi; + + +/* SYSTEM TABLE GUIDS: + Sections 4.6.1.x, 4.6.2 - .5 show industry-standard + configuration table identifiers (guids). */ +const EfiGuid ACPI_20_TABLE = { 0x8868e871, 0xe4f1, 0x11d3, { 0xbc, 0x22, 0x00, 0x80, 0xc7, 0x3c, 0x88, 0x81 } }; + +/* It's reasonable to assume most machines nowadays default to ACPI 2.0+. + However, ACPI_10_TABLE below is still defined in case there's no match + on ACPI_TABLE here. */ +const EfiGuid ACPI_TABLE = ACPI_20_TABLE; + +const EfiGuid ACPI_10_TABLE = { 0xeb9d2d30, 0x2d88, 0x11d3, { 0x9a, 0x16, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } }; + +const EfiGuid SAL_SYSTEM_TABLE = { 0xeb9d2d32, 0x2d88, 0x11d3, { 0x9a, 0x16, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } }; +const EfiGuid SMBIOS_TABLE = { 0xeb9d2d31, 0x2d88, 0x11d3, { 0x9a, 0x16, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } }; +const EfiGuid SMBIOS3_TABLE = { 0xf2fd1544, 0x9794, 0x4a2, { 0x99, 0x2e, 0xe5, 0xbb, 0xcf, 0x20, 0xe3, 0x94 } }; +const EfiGuid MPS_TABLE = { 0xeb9d2d2f, 0x2d88, 0x11d3, { 0x9a, 0x16, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } }; + +const EfiGuid JSON_CONFIG_DATA_TABLE = { + 0x87367f87, + 0x1119, + 0x41ce, + { 0xaa, 0xec, 0x8b, 0xe0, 0x11, 0x1f, 0x55, 0x8a } +}; +const EfiGuid JSON_CAPSULE_DATA_TABLE = { + 0x35e7a725, + 0x8dd2, + 0x4cac, + { 0x80, 0x11, 0x33, 0xcd, 0xa8, 0x10, 0x90, 0x56 } +}; +const EfiGuid JSON_CAPSULE_RESULT_TABLE = { + 0xdbc461c3, + 0xb3de, + 0x422a, + { 0xb9, 0xb4, 0x98, 0x86, 0xfd, 0x49, 0xa1, 0xe5 } +}; + +const EfiGuid DTB_TABLE = { + 0xb1b621d5, + 0xf19c, + 0x41a5, + { 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0 } +}; +const EfiGuid MEMORY_ATTRIBUTES_TABLE = { + 0xdcfa911d, + 0x26eb, + 0x469f, + { 0xa2, 0x20, 0x38, 0xb7, 0xdc, 0x46, 0x12, 0x20 } +}; +const EfiGuid CONFORMANCE_PROFILES_TABLE = { + 0x36122546, + 0xf7e7, + 0x4c8f, + { 0xbd, 0x9b, 0xeb, 0x85, 0x25, 0xb5, 0x0c, 0x0b } +}; +const EfiGuid CONFORMANCE_PROFILES_UEFI_SPEC = { + 0x523c91af, + 0xa195, + 0x4382, + { 0x81, 0x8d, 0x29, 0x5f, 0xe4, 0x00, 0x64, 0x65 } +}; +const EfiGuid MEMORY_RANGE_CAPSULE = { + 0xde9f0ec, + 0x88b6, + 0x428f, + { 0x97, 0x7a, 0x25, 0x8f, 0x1d, 0x0e, 0x5e, 0x72 } +}; +const EfiGuid DEBUG_IMAGE_INFO_TABLE = { + 0x49152e77, + 0x1ada, + 0x4764, + { 0xb7, 0xa2, 0x7a, 0xfe, 0xfe, 0xd9, 0x5e, 0x8b } +}; +const EfiGuid SYSTEM_RESOURCE_TABLE = { + 0xb122a263, + 0x3661, + 0x4f68, + { 0x99, 0x29, 0x78, 0xf8, 0xb0, 0xd6, 0x21, 0x80 } +}; \ No newline at end of file diff --git a/lib/uefi.c3l/src/lib/console.c3 b/lib/uefi.c3l/src/lib/console.c3 new file mode 100644 index 0000000..43c4116 --- /dev/null +++ b/lib/uefi.c3l/src/lib/console.c3 @@ -0,0 +1,132 @@ +module uefi::efilib; +import uefi; + + +struct Console +{ + SimpleTextOutputProtocol* stdout; + SimpleTextOutputProtocol* stderr; + SimpleTextInputProtocol* stdin; + SimpleTextInputExProtocol* stdin_ex; +} + + +// --------------------------------------------------- +module uefi::efilib::efi_console @private; +import uefi; +import uefi::efilib::pre_load @public; + + +fn Console*? new(EfiHandle image, SystemTable* st) +{ + if (!pre_load::initialized) return efi_error::EFILIB_UNINITIALIZED~; + + Console* new_console; + efi_error(st.boot_services.allocate_pool(LOADER_DATA, Console::size, &new_console))!; + + new_console.stdout = st.conout; + new_console.stderr = st.conerr; + new_console.stdin = st.conin; + + // Attempt to initialize the extended input protocol. To do this, its handle must be pulled off of + // instances pre-loaded by the system's UEFI firmware. + if (catch efi_error( + st.boot_services.locate_protocol(&&guid::SIMPLE_TEXT_INPUT_EX_PROTOCOL, null, &new_console.stdin_ex) + )) new_console.stdin_ex = null; + + return new_console; +} + + +// --------------------------------------------------- +module uefi::efilib; +import uefi; + +fn EfiStatus? Console.print(&self, EfiString text, SimpleTextOutputProtocol* stream = null) +{ + if (null == (void*)stream) stream = self.stdout; + efi_error(stream.output_string(stream, text))!; + + return SUCCESS; +} + + +fn EfiStatus? Console.printn(&self, EfiString text, SimpleTextOutputProtocol* stream = null) +{ + self.print(text, stream)!; + + ushort[3] nl = { '\r', '\n', 0 }; + return self.print((EfiString)&nl, stream)!; +} + + +fn EfiStatus? Console.cprint(&self, EfiString text, ConsoleColor color, SimpleTextOutputProtocol* stream = null) +{ + if (null == (void*)stream) stream = self.stdout; + + usz previous_attr = (usz)stream.mode.current_attribute; + defer stream.set_attribute(stream, previous_attr); + + stream.set_attribute(stream, (usz)(char)color); + return self.print(text, stream); +} + + +fn EfiStatus? Console.cprintn(&self, ConsoleColor color, EfiString text, SimpleTextOutputProtocol* stream = null) +{ + self.cprint(text, color, stream)!; + + ushort[3] nl = { '\r', '\n', 0x00 }; + return self.print((EfiString)&nl); +} + + +fn EfiStatus? Console.printe(&self, EfiString text, args...) +{ + EfiString formatted_text = _expandf(text, ...args)!; + defer mem::free(formatted_text); + + return self.print(formatted_text); +} + + +fn EfiStatus? Console.fprinte(&self, SimpleTextOutputProtocol* stream, EfiString text, args...) +{ + EfiString formatted_text = _expandf(text, ...args)!; + defer mem::free(formatted_text); + + return self.print(formatted_text, stream); +} + + +fn EfiStatus? Console.cprinte(&self, ConsoleColor color, EfiString text, args...) +{ + EfiString formatted_text = _expandf(text, ...args)!; + defer mem::free(formatted_text); + + return self.cprint(formatted_text, color); +} + + +fn EfiStatus? Console.cfprinte(&self, ConsoleColor color, SimpleTextOutputProtocol* stream, EfiString text, args...) +{ + EfiString formatted_text = _expandf(text, ...args)!; + defer mem::free(formatted_text); + + return self.cprint(formatted_text, color, stream); +} + + +fn void? Console.clear(&self, ConsoleColor color, bool preserve_attr = false, bool reset_cursor = true) +{ + char previous_attr = (char)(self.stdout.mode.current_attribute & 0xFF); + + efi_error(self.stdout.set_attribute(self.stdout, (usz)(char)color))!; + self.stdout.clear_screen(self.stdout); + + /* Reinstate the old attribute if specified. */ + if (preserve_attr) efi_error(self.stdout.set_attribute(self.stdout, (usz)previous_attr))!; + + /* Reset the cursor position if specified. */ + if (reset_cursor) efi_error(self.stdout.set_cursor_position(self.stdout, 0, 0))!; +} diff --git a/lib/uefi.c3l/src/lib/init.c3 b/lib/uefi.c3l/src/lib/init.c3 new file mode 100644 index 0000000..23dc781 --- /dev/null +++ b/lib/uefi.c3l/src/lib/init.c3 @@ -0,0 +1,92 @@ +module uefi::efilib::pre_load; +import uefi; +import uefi::efi_system @public; + + +/* Global variables/structures to be optionally used with all EFI programs. */ +bool initialized @private = false; + +SystemTable* gST @export("gST") @builtin @deprecated("Legacy symbol. Use `sys::st()` instead.") = null; + +BootServices* gBS @export("gBS") @builtin @deprecated("Legacy symbol. Use `sys::bs()` instead.") = null; +RuntimeServices* gRS @export("gRS") @builtin @deprecated("Legacy symbol. Use `sys::rs()` instead.") = null; + +EfiHandle gImageHandle @export("gImageHandle") @builtin @deprecated("Legacy symbol. Use `sys::image()` instead.") = (EfiHandle)null; + +bool in_panic @local = false; +bool panic_in_panic @local = false; + +fn void default_panic( + String message, + String file, + String function, + uint line +) @public @allow_deprecated @export("panic") @noreturn +{ + if (!initialized) sys::lock(); // spin forever, can't do anything... + + if (in_panic) + { + if (panic_in_panic) sys::lock(); // prevent infinite panic recursion + panic_in_panic = true; + + gST.conout.output_string(gST.conout, @wstring("PANIC raised within panicfn! Locking system...")); + sys::lock(); + } + + in_panic = true; + + // Create a wide string on the stack from the passed information. + ushort[1024] _w_msg; + usz _w_msg_start, x; + + foreach (i, c : file) _w_msg[i % _w_msg.len] = (ushort)c; + _w_msg_start = file.len; + + _w_msg[_w_msg_start++] = (ushort)':'; + foreach (i, c : function) _w_msg[((ulong)i + _w_msg_start) % _w_msg.len] = (ushort)c; + _w_msg_start += function.len; + + _w_msg[_w_msg_start++] = (ushort)':'; + ushort[7] _i_to_str; + for (x = 0; line && x < _i_to_str.len; line /= 10, ++x) _i_to_str[x] = (ushort)(0x30 + (line % 10)); + for (usz w = 1; w <= x; ++w) _w_msg[_w_msg_start++] = _i_to_str[x - w]; + + _w_msg[_w_msg_start++] = (ushort)':'; + foreach (i, c : message) _w_msg[((ulong)i + _w_msg_start) % _w_msg.len] = (ushort)c; + + _w_msg[1023] = 0; // explicit null-terminator + + gST.conout.output_string(gST.conout, @wstring("PANIC! ")); + gST.conout.output_string(gST.conout, &_w_msg); + + sys::lock(); +} + + +<* + Initialize the UEFI C3 library. This call should be made immediately upon EFI entry. + @param [&in] image : "The input EFI_IMAGE handle to the EFI application" + @param [&in] st : "A reference to the system table provided to the EFI application" + @return "Whether the library was successfully initialized." +*> +fn bool? init(EfiHandle image, SystemTable* st) @public @allow_deprecated +{ + builtin::panic = (PanicFn)&default_panic; // in case the user did not compile with '--panicfn' + + if (null == (void*)image || null == (void*)st) return efi_error::LOAD_ERROR~; + + // Though these are deprecated, they should hang around for the purpose of interfacing with old code. + gST = st; + gBS = st.boot_services; + gRS = st.runtime_services; + gImageHandle = image; + + /* The library is _technically_ initialized once the above pointers are populated. */ + initialized = true; + + efi_system::efi_sys = efi_system::new(image, st)!; + initialized = initialized && (null != (void*)efi_system::efi_sys); + + return initialized; +} diff --git a/lib/uefi.c3l/src/lib/input.c3 b/lib/uefi.c3l/src/lib/input.c3 new file mode 100644 index 0000000..8c896d4 --- /dev/null +++ b/lib/uefi.c3l/src/lib/input.c3 @@ -0,0 +1,36 @@ +module uefi::efilib; +import uefi; + + +fn EfiKeyData? read_key(usz timeout_ms) +{ + EfiEvent[2] events; + usz fired_event_index = 0; + + // if (timeout_ms) { + // // + // } + + while OUTER: (true) + { + // events[0] = sys::bs().wait_for_event(timeout_ms ? 2 : 1, &events, &fired_event_index); + + // any _stdin = sys::stdin(); + + // switch (_stdin.type) { + // case SimpleTextInputProtocol.typeid: + // SimpleTextInputProtocol* stdin = _stdin; + // stdin.reset(stdin, false); + + + // case SimpleTextInputExProtocol.typeId: + // SimpleTextInputExProtocol* stdin = _stdin; + // stdin.reset(stdin, false); + + // default: return efi_error::NO_MAPPING?; + // } + } +} + + +// fn bool? confirm(EfiString prompt) => {} \ No newline at end of file diff --git a/lib/uefi.c3l/src/lib/private/print.c3 b/lib/uefi.c3l/src/lib/private/print.c3 new file mode 100644 index 0000000..cb5185c --- /dev/null +++ b/lib/uefi.c3l/src/lib/private/print.c3 @@ -0,0 +1,159 @@ +module uefi::efilib @private; + +import uefi; + + +macro EfiString? @expand_param($Type, any value, #assign_to) +{ + $switch $Type: + $case EfiString: + $nextcase; + $weweoifj; + $case ushort*: + #assign_to = wstrdup((EfiStringRaw)value); + $endswitch +} + + +fn EfiString? _expandf(EfiString input, args...) +{ + if (null == (void*)input.ptr) return efi_error::INVALID_PARAMETER~; + if (0 == args.len) return wide_strdup(input); + + usz scroll = 0; + usz pool_idx = 1; + usz vararg_idx = 0; + EfiString[32] strpool; + strpool[0] = wstrdup(input)!; + EfiString dup = strpool[0]; + + while (scroll < dup.len && 0 != dup[scroll]) + { + if ((ushort)'<' != dup[scroll]) + { + ++scroll; + continue; + } + + // if (scroll == (dup.len - 1)) break; // Do NOT read past the end. + + if ((ushort)'<' == dup[scroll + 1]) + { + dup[scroll + 1] = 0; + + // if ((scroll + 2) == (dup.len - 1)) break; + + if (pool_idx >= 64) return efi_error::OUT_OF_RESOURCES~; + strpool[pool_idx] = dup[(scroll + 2):wstrlen(&dup[scroll + 2])!]; + dup = strpool[pool_idx]; + ++pool_idx; + + scroll = 0; + continue; + } + else if ((ushort)'>' == dup[scroll + 1]) + { + if (vararg_idx >= args.len) return efi_error::NO_MAPPING~; + + dup[scroll] = 0; + + if (pool_idx >= 64 - 1) return efi_error::OUT_OF_RESOURCES~; + strpool[pool_idx] = _expand_arg(args[vararg_idx])!; + ++vararg_idx; + ++pool_idx; + + strpool[pool_idx] = dup[(scroll + 2):wstrlen(&dup[scroll + 2])!]; + dup = strpool[pool_idx]; + ++pool_idx; + + scroll = 0; + continue; + } + else + { + return efi_error::INVALID_LANGUAGE~; + } + } + + usz required_buffer_size = 0; + EfiStringRaw buff = null; + scroll = 0; + + foreach (item : strpool[:pool_idx]) + { + if (!item[0]) continue; + io::wprintn(item)!; + required_buffer_size += item.bytes(); + } + + buff = mem::malloc(required_buffer_size + ushort::size); + + foreach (item : strpool[:pool_idx]) + { + if (!item[0]) continue; + + mem::memcpy(&buff[scroll], item.ptr, item.bytes()); + scroll += (item.len - 1); + + // mem::free(item.ptr); + } + + buff[wstrlen(buff)!] = 0; + io::memdump(buff, wstrlen(buff) + 2)!; + + return wslice_from_raw(buff, required_buffer_size / ushort::size); +} + + +fn EfiString? _expand_arg(any value) +{ + EfiString expansion = { }; + + switch (value.type) + { + case EfiString: nextcase; + case EfiStringRaw: + io::wprintn($$wstr16("efi_string"))!; + expansion = wide_strdup(wslice_from_raw(value, wstrlen((EfiStringRaw)value) + 1))!; + case AsciiString: + io::wprintn($$wstr16("ascii_string"))!; + expansion = a2w(slice_from_raw(value, strlen((AsciiStringRaw)value) + 1))!; + case bool: + expansion = _bool_to_str(((bool)(value.ptr)))!; + case EfiGuid: + expansion = _guid_to_str((EfiGuid*)value.ptr)!; + // case EfiDevicePath: expansion = _device_path_to_str((EfiDevicePath *)value); + case float: nextcase; + case double: + expansion = a2w("fract")!; // _fractional_to_str(value); + case int128: nextcase; + case uint128: nextcase; + case long: nextcase; + case ulong: nextcase; + case int: nextcase; + case uint: nextcase; + case short: nextcase; + case ushort: nextcase; + case ichar: nextcase; + case char: + expansion = a2w("number")!; // _number_to_str(value); + case void: + expansion = a2w("pointer")!; // _pointer_to_str(value); + default: + expansion = a2w("umm")!; // efi_error::INVALID_PARAMETER?; + } + // io::print(a2w("EXPAND: '"))!;io::print(expansion)!;io::printn(a2w("'"))!; + // io::printn(a2w(memdump(&&expansion.len, usz.sizeof)))!; + + if (null == (void*)expansion.ptr || 0 == expansion.len) return efi_error::INVALID_PARAMETER~; + + return expansion; +} + + +fn EfiString? _bool_to_str(bool b) => b ? a2w("TRUE") : a2w("FALSE"); + +fn EfiString? _guid_to_str(EfiGuid* guid) +{ + return a2w("SOMEGUID"); +} diff --git a/lib/uefi.c3l/src/lib/string.c3 b/lib/uefi.c3l/src/lib/string.c3 new file mode 100644 index 0000000..a03981e --- /dev/null +++ b/lib/uefi.c3l/src/lib/string.c3 @@ -0,0 +1,145 @@ +module uefi::efilib; +import uefi; + + +fn usz? wide_strlen(ushort* rawptr) @export("wstrlen") +{ + if (null == rawptr) return efi_error::INVALID_PARAMETER~; + + usz len = 0; + while (rawptr[len]) ++len; + + return len; +} + + +fn usz? ascii_strlen(char* rawptr) @export("strlen") +{ + if (null == rawptr) return efi_error::INVALID_PARAMETER~; + + usz len = 0; + while (rawptr[len]) ++len; + + return len; +} + + +fn EfiString? ascii_to_wide(AsciiString str) @export("a2w") +{ + if (null == (void*)str.ptr || 0 == str[0]) return efi_error::INVALID_PARAMETER~; + + EfiString ret = wslice_from_raw(mem::calloc(str.len + 1, ushort::size), str.len + 1); + + for (int i = 0; i < str.len; ++i) ret[i] = (ushort)str[i]; + ret[^1] = 0; + + return ret; +} + + +fn AsciiString? wide_to_ascii(EfiString str) @export("w2a") +{ + if (null == (void*)str.ptr || 0 == str[0]) return efi_error::INVALID_PARAMETER~; + + AsciiString ret = slice_from_raw(mem::calloc(str.len + 1, char::size), str.len + 1); + + for (int i = 0; i < str.len; ++i) ret[i] = (char)str[i]; /* lossy */ + ret[^1] = 0; + + return ret; +} + + +fn EfiString? wide_strdup(EfiString str) @export("wstrdup") +{ + if (null == (void*)str.ptr) return efi_error::INVALID_PARAMETER~; + if (0 == str.len) return a2w({ 0 }); + + usz str_len = wide_strlen(str.ptr)!; + EfiString ret = wslice_from_raw(mem::calloc(str_len + 1, ushort::size), str_len + 1); + + mem::memcpy(ret, str, str_len * ushort::size); + ret[^1] = 0; + + return ret; +} + + +fn AsciiString? ascii_strdup(AsciiString str) @export("strdup") +{ + if (null == (void*)str.ptr) return efi_error::INVALID_PARAMETER~; + if (0 == str.len) return mem::calloc(1, 1)[:1]; + + AsciiString ret = slice_from_raw(mem::malloc(str.len + 1), str.len + 1); + mem::memcpy(ret, str, str.len); + ret[^1] = 0; + + return ret; +} + + +fn EfiString? wide_strcat(EfiString str, EfiString addl) @export("wstrcat") +{ + if (null == (void*)str.ptr || null == (void*)addl.ptr) return efi_error::INVALID_PARAMETER~; + + usz str_size = wide_strlen(str.ptr)! * ushort::size; + usz addl_size = wide_strlen(addl.ptr)! * ushort::size; + usz new_size = str_size + addl_size + ushort::size; + + void* buff = mem::malloc(new_size); + wstrcpy(buff, str)!; + mem::memcpy((void*)((uptr)buff + str_size), addl.ptr, addl_size); + + EfiString reinterp = wslice_from_raw(buff, new_size / ushort::size); + reinterp[^1] = 0; + + return reinterp; +} + + +fn AsciiString? ascii_strcat(AsciiString str, AsciiString addl) @export("strcat") +{ + if (null == (void*)str || null == (void*)addl) return efi_error::INVALID_PARAMETER~; + + mem::memcpy((void*)((uptr)str.ptr + str.len), addl, addl.len); + + return str; +} + + +fn void? wide_strcpy(void* to, EfiString from) @export("wstrcpy") +{ + if (null == (void*)from.ptr || null == to) return efi_error::INVALID_PARAMETER~; + + mem::memcpy(to, from.ptr, from.bytes()); + ((EfiStringRaw)to)[from.len - 1] = 0; +} + + +fn void? ascii_strcpy(void* to, AsciiString from) @export("strcpy") +{ + if (null == (void*)from.ptr || null == to) return efi_error::INVALID_PARAMETER~; + + mem::memcpy(to, from.ptr, from.bytes()); + ((AsciiStringRaw)to)[from.len - 1] = 0; +} + + +fn usz EfiString.bytes(&self) => (self.len - 1) * ushort::size; +fn usz AsciiString.bytes(&self) => (self.len - 1) * char::size; + + +macro usz? wstrlen(EfiStringRaw rawptr) @builtin => wide_strlen(rawptr); +macro EfiString? wstrdup(EfiString str) @builtin => wide_strdup(str); +macro EfiString? wstrcat(EfiString str, EfiString addl) @builtin => wide_strcat(str, addl); +macro void? wstrcpy(void* into, EfiString from) @builtin => wide_strcpy(into, from); +macro AsciiString? w2a(EfiString c) @builtin => wide_to_ascii(c); + +macro usz? strlen(AsciiStringRaw rawptr) @builtin => ascii_strlen(rawptr); +macro AsciiString? strdup(AsciiString str) @builtin => ascii_strdup(str); +macro AsciiString? strcat(AsciiString str, AsciiString addl) @builtin => ascii_strcat(str, addl); +macro void? strcpy(void* into, AsciiString from) @builtin => ascii_strcpy(into, from); +macro EfiString? a2w(AsciiString c) @builtin => ascii_to_wide(c); + +macro EfiString wslice_from_raw(void* rawptr, usz length) @builtin => ((EfiStringRaw)rawptr)[:length]; +macro AsciiString slice_from_raw(void* rawptr, usz length) @builtin => ((AsciiStringRaw)rawptr)[:length]; diff --git a/lib/uefi.c3l/src/lib/system.c3 b/lib/uefi.c3l/src/lib/system.c3 new file mode 100644 index 0000000..0f68294 --- /dev/null +++ b/lib/uefi.c3l/src/lib/system.c3 @@ -0,0 +1,268 @@ +module uefi::efilib; +import uefi; + + +struct System +{ + EfiHandle image_handle; + + SystemTable* system_table; + + BootServices* boot_services; + RuntimeServices* runtime_services; + + Console* console; + + bool gop_initialized; + + // TODO: What's going on here? + // LoadedImageProtocol image_info; + MemoryType image_data_type; +} + + +// --------------------------------------------------- +module uefi::efi_system @private; +import uefi; +import uefi::efilib::efi_console @public; +import uefi::efilib::pre_load @public; + + +System* efi_sys @private = null; + + +fn System*? new(EfiHandle image, SystemTable* st) +{ + if (!pre_load::initialized) return efi_error::EFILIB_UNINITIALIZED~; + + System* new_system = null; + efi_error(st.boot_services.allocate_pool(LOADER_CODE, System::size, &new_system))!; + + if (null == new_system) return efi_error::OUT_OF_RESOURCES~; + + new_system.system_table = st; + + new_system.boot_services = st.boot_services; + new_system.runtime_services = st.runtime_services; + + new_system.image_handle = image; + + new_system.gop_initialized = false; + + new_system.console = efi_console::new(image, st)!; + + return new_system; +} + + +// --------------------------------------------------- +module uefi::efilib; +import uefi; + + +fn void System.reset( + &self, + ResetType type, + EfiStatus code = SUCCESS, + char[] buffer = { } +) @noreturn => self.runtime_services.reset_system(type, code, buffer.len, buffer.ptr); + + +fn void System.stall(&self, usz duration) => self.boot_services.stall(duration); + + +fn void System.panic(&self, AsciiString message) @noreturn @allow_deprecated +{ + if (!self.gop_initialized) + { + ushort[1024] _w_msg; + foreach (i, c : message) _w_msg[i % _w_msg.len] = (ushort)c; + gST.conout.set_attribute(gST.conout, (usz)(char)(ConsoleColor) { RED, BLACK }); + gST.conout.output_string(gST.conout, &_w_msg); + } + + sys::halt(); +} + + +fn bool? System.set_watchdog_timer( + &self, + usz timer_seconds, + ulong code = -1, + usz data_size = 0, + EfiStringRaw data = null +) => efi_error(self.boot_services.set_watchdog_timer(timer_seconds, code, data_size, data)); + + +fn ulong? System.get_next_monotonic_count(&self) +{ + ulong count_value = 0; + + efi_error(self.boot_services.get_next_monotonic_count(&count_value))!; + + return count_value; +} + +fn uint? System.calculate_crc32(&self, void* data @noalias, usz data_size) +{ + uint result = 0; + + efi_error(self.boot_services.calculate_crc32(data, data_size, &result))!; + + return result; +} + + +fn void System.free(&self, void* pool) +{ + if (null != pool) self.boot_services.free_pool(pool); +} + + +fn void? System.free_safe(&self, void* pool) +{ + if (null != pool) efi_error(self.boot_services.free_pool(pool))!; +} + + +fn void*? System.malloc(&self, usz size, MemoryType type = LIMIT) +{ + if (MemoryType.LIMIT == type) type = self.image_data_type; + + void* res; + efi_error(self.boot_services.allocate_pool(type, size, &res))!; + + return res; +} + + +fn void*? System.calloc(&self, usz size, usz length, MemoryType type = LIMIT) +{ + if (MemoryType.LIMIT == type) type = self.image_data_type; + + void* p = self.malloc(size * length, type)!; + self.memset(p, 0x00, size * length); + + return p; +} + + +fn void*? System.realloc(&self, void* pool, usz prev_len, usz new_len) +{ + if (0 == new_len) + { + self.free(pool); + return null; + } + + void* new_pool = self.calloc(1, new_len)!; + + if (null != pool) + { + self.memcpy(new_pool, pool, @min(prev_len, new_len)); + self.free(pool); + } + + return new_pool; +} + + +fn void System.memset(&self, void* at, char value, usz length) +{ + if (null == at || 0 == length) return; + + self.boot_services.set_mem(at, length, value); +} + + +fn void System.memcpy(&self, void* to, void* from, usz length) +{ + if (null == to || null == from || 0 == length) return; + + self.boot_services.copy_mem(to, from, length); +} + + +fn AsciiString? System.create_memdump(&self, void* at, usz len, usz align = 16) +{ + if (null == at || 0 == len) return efi_error::INVALID_PARAMETER~; + + AsciiString ret = slice_from_raw(self.calloc(char::size, (len * 3) + 1)!, (len * 3) + 1); + + for (usz i = 0; i < len; ++i) + { + char c = *((char*)((usz)at + i)); + char high_nibble = (c & 0xF0) >> 4; + char low_nibble = c & 0x0F; + + ret[(i * 3) + 0] = high_nibble + (high_nibble >= 10 ? ('A' - 10) : '0'); + ret[(i * 3) + 1] = low_nibble + (low_nibble >= 10 ? ('A' - 10) : '0'); + ret[(i * 3) + 2] = ((i + 1) % align) ? ' ' : '\n'; + } + + ret[len * 3] = '\0'; // paranoia + return ret; +} + + +fn SystemMemoryMap*? System.get_memory_map(&self) +{ + SystemMemoryMap* result = self.calloc(1, SystemMemoryMap::size)!; + + // The first query should return a "BUFFER_TOO_SMALL" efi error, which sets 'buffer_size' to the right value. + EfiStatus? status = self.boot_services.get_memory_map( + &result.buffer_size, + result.descriptors, + &result.map_key, + &result.descriptor_size, + &result.descriptor_version + ); + + if (catch status_as_fault = status) + { + if (efi_error::BUFFER_TOO_SMALL != status_as_fault) + { + self.free(result); + return status_as_fault~; + } + } + + if (0 == result.buffer_size || 0 == result.descriptor_size) + { + self.free(result); + return efi_error::NOT_FOUND~; + } + + // Account for the possible fragmentation/expansion of the memory map based on the below allocation. + /* NOTE: The size is 2x because a new AllocatePool range inserted into the middle of an existing entry will result + in 2 new entries: the allocation as well as the trailing region/fragment of free space. */ + result.buffer_size += (2 * result.descriptor_size); + + // Allocate the resultant buffer. + result.descriptors = self.calloc(1, result.buffer_size)!; + + status = self.boot_services.get_memory_map( + &result.buffer_size, + result.descriptors, + &result.map_key, + &result.descriptor_size, + &result.descriptor_version + ); + if (catch status_as_fault = status) + { + self.free(result.descriptors); + self.free(result); + return status_as_fault~; + } + + if (0 == result.buffer_size || 0 == result.descriptor_size) + { + self.free(result.descriptors); + self.free(result); + return efi_error::NOT_FOUND~; + } + + result.descriptors_count = result.buffer_size / result.descriptor_size; + + return result; +} diff --git a/lib/uefi.c3l/src/lib/util.c3 b/lib/uefi.c3l/src/lib/util.c3 new file mode 100644 index 0000000..d276393 --- /dev/null +++ b/lib/uefi.c3l/src/lib/util.c3 @@ -0,0 +1,19 @@ +module uefi::core_util; + + +/* Conversion macros: s2ms, s2us, ms2us (sec to millisec, sec to microsec, millisec to microsec) */ +macro usz @s2ms(usz $x) @public @builtin => $x * 1_000; +macro usz @s2us(usz $x) @public @builtin => $x * 1_000_000; +macro usz @ms2us(usz $x) @public @builtin => $x * 1_000; + +/* min/max macros for le global use */ +macro @min(#x, #y) @public @builtin => ((#x) < (#y) ? (#x) : (#y)); +macro @max(#x, #y) @public @builtin => ((#x) > (#y) ? (#x) : (#y)); + +macro @foreach(rawptr, len; @body(index, value)) @builtin +{ + for (usz i = 0; i < len; ++i) + { + @body(i, rawptr[i]); + } +} \ No newline at end of file diff --git a/lib/uefi.c3l/src/protocol/console.c3 b/lib/uefi.c3l/src/protocol/console.c3 new file mode 100644 index 0000000..1e30f30 --- /dev/null +++ b/lib/uefi.c3l/src/protocol/console.c3 @@ -0,0 +1,225 @@ +module uefi::proto::console; +import uefi; + + +/***/ +bitstruct ConsoleColor : char @bigendian +{ + TextColor background : 0..3; + TextColor foreground : 4..7; /* NOTE: bit '7' is technically not used per spec */ +} + + +/* 12.1.) Console I/O Protocol (Scan Codes - see Appendix B, Table B.1) */ +enum ScanCode : ushort (ushort raw) +{ + NULL { 0x0000 }, + UP_ARROW { 0x0001 }, + DOWN_ARROW { 0x0002 }, + RIGHT_ARROW { 0x0003 }, + LEFT_ARROW { 0x0004 }, + HOME { 0x0005 }, + END { 0x0006 }, + INSERT { 0x0007 }, + DELETE { 0x0008 }, + PAGE_UP { 0x0009 }, + PAGE_DOWN { 0x000A }, + F1 { 0x000B }, + F2 { 0x000C }, + F3 { 0x000D }, + F4 { 0x000E }, + F5 { 0x000F }, + F6 { 0x0010 }, + F7 { 0x0011 }, + F8 { 0x0012 }, + F9 { 0x0013 }, + F10 { 0x0014 }, + F11 { 0x0015 }, + F12 { 0x0016 }, + ESCAPE { 0x0017 }, + PAUSE { 0x0048 }, + F13 { 0x0068 }, + F14 { 0x0069 }, + F15 { 0x006A }, + F16 { 0x006B }, + F17 { 0x006C }, + F18 { 0x006D }, + F19 { 0x006E }, + F20 { 0x006F }, + F21 { 0x0070 }, + F22 { 0x0071 }, + F23 { 0x0072 }, + F24 { 0x0073 }, + MUTE { 0x007F }, + VOLUME_UP { 0x0080 }, + VOLUME_DOWN { 0x0081 }, + BRIGHTNESS_UP { 0x0100 }, + BRIGHTNESS_DOWN { 0x0101 }, + SUSPEND { 0x0102 }, + HIBERNATE { 0x0103 }, + TOGGLE_DISPLAY { 0x0104 }, + RECOVERY { 0x0105 }, + EJECT { 0x0106 }, +} + + +/* 12.3.) Simple Text Input Protocol */ +module uefi::guid; +const EfiGuid SIMPLE_TEXT_INPUT_PROTOCOL = { + 0x387477c1, + 0x69c7, + 0x11d2, + { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } +}; +const EfiGuid SIMPLE_TEXT_INPUT_EX_PROTOCOL = { + 0xdd9e7534, + 0x7762, + 0x4698, + { 0x8c, 0x14, 0xf5, 0x85, 0x17, 0xa6, 0x25, 0xaa } +}; + +module uefi::proto::console; +struct SimpleTextInputProtocol +{ + FnInputReset reset; + FnInputReadKey read_key; + EfiEvent event_wait_for_key; +} + +struct EfiInputKey +{ + ushort scan_code; + ushort unicode_char; +} + +alias FnInputReset = fn EfiStatus(SimpleTextInputProtocol*, bool); +alias FnInputReadKey = fn EfiStatus(SimpleTextInputProtocol*, EfiInputKey*); + + +/* 12.2.) Simple Text Input Ex Protocol */ +struct SimpleTextInputExProtocol +{ + FnInputResetEx reset; + FnInputReadKeyEx read_key; + EfiEvent event_wait_for_key; + FnInputSetState set_state; + FnInputRegisterKeystrokeNotify register_keystroke_notify; + FnInputUnregisterKeystrokeNotify unregister_keystroke_notify; +} + +enum KeyShiftState : uint (uint raw) +{ + SHIFT_STATE_VALID { 0x8000_0000 }, + RIGHT_SHIFT_PRESSED { 0x0000_0001 }, + LEFT_SHIFT_PRESSED { 0x0000_0002 }, + RIGHT_CONTROL_PRESSED { 0x0000_0004 }, + LEFT_CONTROL_PRESSED { 0x0000_0008 }, + RIGHT_ALT_PRESSED { 0x0000_0010 }, + LEFT_ALT_PRESSED { 0x0000_0020 }, + RIGHT_LOGO_PRESSED { 0x0000_0040 }, + LEFT_LOGO_PRESSED { 0x0000_0080 }, + MENU_KEY_PRESSED { 0x0000_0100 }, + SYS_REQ_PRESSED { 0x0000_0200 }, +} + +enum KeyToggleState : char (char raw) +{ + TOGGLE_STATE_VALID { 0x80 }, + KEY_STATE_EXPOSED { 0x40 }, + SCROLL_LOCK_ACTIVE { 0x01 }, + NUM_LOCK_ACTIVE { 0x02 }, + CAPS_LOCK_ACTIVE { 0x04 }, +} + +struct EfiKeyState +{ + KeyShiftState key_shift_state; + KeyToggleState key_toggle_state; +} + +struct EfiKeyData +{ + EfiInputKey key; + EfiKeyState key_state; +} + +alias FnInputResetEx = fn EfiStatus(SimpleTextInputExProtocol*, bool); +alias FnInputReadKeyEx = fn EfiStatus(SimpleTextInputExProtocol*, EfiKeyData*); +alias FnInputSetState = fn EfiStatus(SimpleTextInputExProtocol*, KeyToggleState*); +alias FnInputRegisterKeystrokeNotify = fn EfiStatus( + SimpleTextInputExProtocol*, + EfiKeyData*, + FnKeyNotificationFunction, + void** +); +alias FnInputUnregisterKeystrokeNotify = fn EfiStatus(EfiKeyData*); + +alias FnKeyNotificationFunction = fn EfiStatus(EfiKeyData*); + + +/* 12.4.) Simple Text Output Protocol */ +module uefi::guid; +const EfiGuid SIMPLE_TEXT_OUTPUT_PROTOCOL = { + 0x387477c2, + 0x69c7, + 0x11d2, + { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } +}; + +module uefi::proto::console; +struct SimpleTextOutputProtocol +{ + FnOutputReset reset; + FnOutputString output_string; + FnOutputTestString test_string; + FnOutputQueryMode query_mode; + FnOutputSetMode set_mode; + FnOutputSetAttribute set_attribute; + FnOutputClearScreen clear_screen; + FnOutputSetCursorPosition set_cursor_position; + FnOutputEnableCursor enable_cursor; + TextMode* mode; +} + +struct TextMode +{ + int max_mode; + int current_mode; + int current_attribute; + int current_cursor_column; + int current_cursor_row; + bool is_cursor_visible; +} + +alias FnOutputReset = fn EfiStatus(SimpleTextOutputProtocol*, bool); +alias FnOutputString = fn EfiStatus(SimpleTextOutputProtocol*, EfiStringRaw); +alias FnOutputTestString = fn EfiStatus(SimpleTextOutputProtocol*, EfiStringRaw); +alias FnOutputQueryMode = fn EfiStatus(SimpleTextOutputProtocol*, usz, usz*, usz*); +alias FnOutputSetMode = fn EfiStatus(SimpleTextOutputProtocol*, usz); +alias FnOutputSetAttribute = fn EfiStatus(SimpleTextOutputProtocol*, usz); +alias FnOutputClearScreen = fn EfiStatus(SimpleTextOutputProtocol*); +alias FnOutputSetCursorPosition = fn EfiStatus(SimpleTextOutputProtocol*, usz, usz); +alias FnOutputEnableCursor = fn EfiStatus(SimpleTextOutputProtocol*, bool); + +/* Standard terminal color constants. */ +enum TextColor : char (char raw) +{ + BLACK { 0x00 }, + BLUE { 0x01 }, + GREEN { 0x02 }, + CYAN { 0x03 }, + RED { 0x04 }, + MAGENTA { 0x05 }, + BROWN { 0x06 }, + LIGHT_GRAY { 0x07 }, + DARK_GRAY { 0x08 }, /* BRIGHT, or (BLACK|BRIGHT) */ + LIGHT_BLUE { 0x09 }, + LIGHT_GREEN { 0x0A }, + LIGHT_CYAN { 0x0B }, + LIGHT_RED { 0x0C }, + LIGHT_MAGENTA { 0x0D }, + YELLOW { 0x0E }, + WHITE { 0x0F }, +} + +macro char @efi_color($fg, $bg) @builtin @public => ($fg | ((0x07 & $bg) << 4)); \ No newline at end of file diff --git a/lib/uefi.c3l/src/protocol/evt_timer_task.c3 b/lib/uefi.c3l/src/protocol/evt_timer_task.c3 new file mode 100644 index 0000000..3d2929b --- /dev/null +++ b/lib/uefi.c3l/src/protocol/evt_timer_task.c3 @@ -0,0 +1,103 @@ +module uefi::proto::evt; +import uefi; + + +/* 7.1.) Event, Timer, and Task Priority Services */ +/* NOTE: EfiEvent is defined in ../def.c3, as it's more globally used. */ +enum EventType : uint (uint raw) +{ + TIMER { 0x8000_0000 }, + RUNTIME { 0x4000_0000 }, + NOTIFY_WAIT { 0x0000_0100 }, + NOTIFY_SIGNAL { 0x0000_0200 }, + SIGNAL_EXIT_BOOT_SERVICES { 0x0000_0201 }, + SIGNAL_VIRTUAL_ADDRESS_CHANGE { 0x6000_0202 }, +} + + +/* EFI_EVENT_NOTIFY (7.1.1) */ +alias FnEventNotify = fn void(EfiEvent, void*); + +/* EFI_CREATE_EVENT (7.1.1) */ +alias FnCreateEvent = fn EfiStatus(EventType, EventTpl, FnEventNotify, void*, EfiEvent*); + +/* EFI_CREATE_EVENT_EX (7.1.2) */ +alias FnCreateEventEx = fn EfiStatus(EventType, EventTpl, FnEventNotify, void*, EfiGuid*, EfiEvent*); + +/* EFI event group GUIDs (7.1.2) */ +const EfiGuid EVENT_GROUP_EXIT_BOOT_SERVICES = { + 0x27abf055, + 0xb1b8, + 0x4c26, + { 0x80, 0x48, 0x74, 0x8f, 0x37, 0xba, 0xa2, 0xdf } +}; +const EfiGuid EVENT_GROUP_BEFORE_EXIT_BOOT_SERVICES = { + 0x8be0e274, + 0x3970, + 0x4b44, + { 0x80, 0xc5, 0x1a, 0xb9, 0x50, 0x2f, 0x3b, 0xfc } +}; +const EfiGuid EVENT_GROUP_VIRTUAL_ADDRESS_CHANGE = { + 0x13fa7698, + 0xc831, + 0x49c7, + { 0x87, 0xea, 0x8f, 0x43, 0xfc, 0xc2, 0x51, 0x96 } +}; +const EfiGuid EVENT_GROUP_MEMORY_MAP_CHANGE = { + 0x78bee926, + 0x692f, + 0x48fd, + { 0x9e, 0xdb, 0x01, 0x42, 0x2e, 0xf0, 0xd7, 0xab } +}; +const EfiGuid EVENT_GROUP_READY_TO_BOOT = { + 0x7ce88fb3, + 0x4bd7, + 0x4679, + { 0x87, 0xa8, 0xa8, 0xd8, 0xde, 0xe5, 0x0d, 0x2b } +}; +const EfiGuid EVENT_GROUP_AFTER_READY_TO_BOOT = { + 0x3a2a00ad, + 0x98b9, + 0x4cdf, + { 0xa4, 0x78, 0x70, 0x27, 0x77, 0xf1, 0xc1, 0x0b } +}; +const EfiGuid EVENT_GROUP_RESET_SYSTEM = { + 0x62da6a56, + 0x13fb, + 0x485a, + { 0xa8, 0xda, 0xa3, 0xdd, 0x79, 0x12, 0xcb, 0x6b } +}; + +/* EFI_CLOSE_EVENT (7.1.3) */ +alias FnCloseEvent = fn EfiStatus(EfiEvent); + +/* EFI_SIGNAL_EVENT (7.1.4) */ +alias FnSignalEvent = fn EfiStatus(EfiEvent); + +/* EFI_WAIT_FOR_EVENT (7.1.5) */ +alias FnWaitForEvent = fn EfiStatus(usz, EfiEvent*, usz*); + +/* EFI_CHECK_EVENT (7.1.6) */ +alias FnCheckEvent = fn EfiStatus(EfiEvent); + +/* EFI_SET_TIMER (7.1.7) and EFI_TIMER_DELAY */ +alias FnSetTimer = fn EfiStatus(EfiEvent, TimerDelay, ulong); + +enum TimerDelay +{ + TIMER_CANCEL, + TIMER_PERIODIC, + TIMER_RELATIVE, +} + +/* EFI_RAISE_TPL (7.1.8) and TPL */ +alias FnRaiseTpl = fn EventTpl(EventTpl); + +typedef EventTpl = usz; +const EventTpl TPL_APPLICATION = (EventTpl)4; +const EventTpl TPL_CALLBACK = (EventTpl)8; +const EventTpl TPL_NOTIFY = (EventTpl)16; +const EventTpl TPL_HIGH_LEVEL = (EventTpl)31; + +/* EFI_RESTORE_TPL (7.1.9) */ +alias FnRestoreTpl = fn void(EventTpl); diff --git a/lib/uefi.c3l/src/protocol/handler.c3 b/lib/uefi.c3l/src/protocol/handler.c3 new file mode 100644 index 0000000..5bc9e86 --- /dev/null +++ b/lib/uefi.c3l/src/protocol/handler.c3 @@ -0,0 +1,86 @@ +module uefi::proto::handle; +import uefi; + + +/* 7.3) Protocol Handler Services */ +/* EFI_INSTALL_PROTOCOL_INTERFACE (7.3.2) and related definitions */ +alias FnInstallProtocolInterface = fn EfiStatus(EfiHandle*, EfiGuid*, InterfaceType, void*); + +/* NOTE: EFI_HANDLE and EFI_GUID are defined in the def.c3 globals file. */ +enum InterfaceType +{ + NATIVE_INTERFACE, +} + +/* EFI_UNINSTALL_PROTOCOL_INTERFACE (7.3.3) */ +alias FnUninstallProtocolInterface = fn EfiStatus(EfiHandle*, EfiGuid*, void*); + +/* EFI_REINSTALL_PROTOCOL_INTERFACE (7.3.4) */ +alias FnReinstallProtocolInterface = fn EfiStatus(EfiHandle*, EfiGuid*, void*, void*); + +/* EFI_REGISTER_PROTOCOL_NOTIFY (7.3.5) */ +alias FnRegisterProtocolNotify = fn EfiStatus(EfiGuid*, EfiEvent, void**); + +/* EFI_LOCATE_HANDLE (7.3.6) and related */ +alias FnLocateHandle = fn EfiStatus(HandleSearchType, EfiGuid*, void*, usz*, EfiHandle*); + +enum HandleSearchType +{ + ALL_HANDLES, + BY_REGISTER_NOTIFY, + BY_PROTOCOL, +} + +/* EFI_HANDLE_PROTOCOL (7.3.7) */ +alias FnHandleProtocol = fn EfiStatus(EfiHandle, EfiGuid*, void**); + +/* EFI_LOCATE_DEVICE_PATH (7.3.8) */ +// alias FnLocateDevicePath = fn EfiStatus(EfiGuid*, device::DevicePathProtocol**, EfiHandle*); +alias FnLocateDevicePath = fn EfiStatus(EfiGuid*, void**, EfiHandle*); + +/* EFI_OPEN_PROTOCOL (7.3.9) and related */ +alias FnOpenProtocol = fn EfiStatus(EfiHandle, EfiGuid*, void**, EfiHandle, EfiHandle, OpenProtocolAttribute); + +alias OpenProtocolAttribute = uint; +const OpenProtocolAttribute BY_HANDLE_PROTOCOL = 0x0000_0001; +const OpenProtocolAttribute GET_PROTOCOL = 0x0000_0002; +const OpenProtocolAttribute TEST_PROTOCOL = 0x0000_0004; +const OpenProtocolAttribute BY_CHILD_CONTROLLER = 0x0000_0008; +const OpenProtocolAttribute BY_DRIVER = 0x0000_0010; +const OpenProtocolAttribute EXCLUSIVE = 0x0000_0020; + +/* EFI_CLOSE_PROTOCOL (7.3.10) */ +alias FnCloseProtocol = fn EfiStatus(EfiHandle, EfiGuid*, EfiHandle, EfiHandle); + +/* EFI_OPEN_PROTOCOL_INFORMATION (7.3.11) and related */ +alias FnOpenProtocolInformation = fn EfiStatus(EfiHandle, EfiGuid*, OpenProtocolInformationEntry**, usz*); + +struct OpenProtocolInformationEntry +{ + EfiHandle agent_handle; + EfiHandle controller_handle; + OpenProtocolAttribute attributes; + uint open_count; +} + +/* EFI_CONNECT_CONTROLLER (7.3.12) */ +// alias FnConnectController = fn EfiStatus(EfiHandle, EfiHandle*, device::DevicePathProtocol*, bool); +alias FnConnectController = fn EfiStatus(EfiHandle, EfiHandle*, void*, bool); + +/* EFI_DISCONNECT_CONTROLLER (7.3.13) */ +alias FnDisconnectController = fn EfiStatus(EfiHandle, EfiHandle, EfiHandle); + +/* EFI_PROTOCOLS_PER_HANDLE (7.3.14) */ +alias FnProtocolsPerHandle = fn EfiStatus(EfiHandle, EfiGuid***, usz*); + +/* EFI_LOCATE_HANDLE_BUFFER (7.3.15) */ +alias FnLocateHandleBuffer = fn EfiStatus(HandleSearchType, EfiGuid*, void*, usz*, EfiHandle**); + +/* EFI_LOCATE_PROTOCOL (7.3.16) */ +alias FnLocateProtocol = fn EfiStatus(EfiGuid*, void*, void**); + +/* EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES (7.3.17) */ +alias FnInstallMultipleProtocolInterfaces = fn EfiStatus(EfiHandle*, ...); + +/* EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES (7.3.18) */ +alias FnUninstallMultipleProtocolInterfaces = fn EfiStatus(EfiHandle, ...); \ No newline at end of file diff --git a/lib/uefi.c3l/src/protocol/image.c3 b/lib/uefi.c3l/src/protocol/image.c3 new file mode 100644 index 0000000..eb1a4b1 --- /dev/null +++ b/lib/uefi.c3l/src/protocol/image.c3 @@ -0,0 +1,27 @@ +module uefi::proto::image; +import uefi; + + +/* 7.4) Image Services */ +/* EFI_IMAGE_LOAD (7.4.1) */ +// alias FnLoadImage = fn EfiStatus(bool, EfiHandle, device::DevicePathProtocol*, void*, usz, EfiHandle*); +alias FnLoadImage = fn EfiStatus(bool, EfiHandle, void*, void*, usz, EfiHandle*); + +/* const EfiGuid HII_PACKAGE_LIST_PROTOCOL = + { 0x6a1ee763, 0xd47a, 0x43b4, {0xaa,0xbe,0xef,0x1d,0xe2,0xab,0x56,0xfc} }; +alias HiiPackageListHeader = hii::PackageListProtocol; */ + +/* EFI_IMAGE_START (7.4.2) */ +alias FnStartImage = fn EfiStatus(EfiHandle, usz*, EfiStringRaw*); + +/* EFI_IMAGE_UNLOAD (7.4.3) */ +alias FnUnloadImage = fn EfiStatus(EfiHandle); + +/* EFI_IMAGE_ENTRY_POINT (7.4.4) */ +alias FnImageEntryPoint = fn EfiStatus(EfiHandle, SystemTable*); + +/* EFI_EXIT (7.4.5) */ +alias FnExitImage = fn EfiStatus(EfiHandle, EfiStatus, usz, EfiStringRaw); + +/* EFI_EXIT_BOOT_SERVICES (7.4.6) */ +alias FnExitBootServices = fn EfiStatus(EfiHandle, usz); \ No newline at end of file diff --git a/lib/uefi.c3l/src/protocol/mem.c3 b/lib/uefi.c3l/src/protocol/mem.c3 new file mode 100644 index 0000000..8bb2cbb --- /dev/null +++ b/lib/uefi.c3l/src/protocol/mem.c3 @@ -0,0 +1,105 @@ +module uefi::proto::memory; +import uefi; + + +/* 7.2.) Memory Allocation Services */ + +/* EFI_ALLOCATE_PAGES (7.2.1) and Allocation definitions */ +alias FnAllocatePages = fn EfiStatus(AllocateType, MemoryType, usz, PhysicalAddress*); + +alias PhysicalAddress = ulong; +alias VirtualAddress = ulong; +enum AllocateType +{ + ANY_PAGES, + MAX_ADDRESS, + ADDRESS, + LIMIT +} +enum MemoryType : uint +{ + RESERVED, + LOADER_CODE, + LOADER_DATA, + BOOT_SERVICES_CODE, + BOOT_SERVICES_DATA, + RUNTIME_SERVICES_CODE, + RUNTIME_SERVICES_DATA, + CONVENTIONAL, + UNUSABLE, + ACPI_RECLAIM, + ACPI_NVS, + MMIO, + MMIO_PORT_SPACE, + PAL_CODE, + PERSISTENT, + UNACCEPTED, + LIMIT +} + +/* EFI_FREE_PAGES (7.2.2) */ +alias FnFreePages = fn EfiStatus(PhysicalAddress, usz); + +/* EFI_GET_MEMORY_MAP (7.2.3) and related definitions */ +alias FnGetMemoryMap = fn EfiStatus(usz*, void*, usz*, usz*, uint*); + +const uint MEMORY_DESCRIPTOR_VERSION = 1; +struct MemoryDescriptor +{ + MemoryType type; + PhysicalAddress physical_start; + VirtualAddress virtual_start; + ulong num_pages; + MemoryAttribute attribute; +} + +struct SystemMemoryMap +{ + usz map_key; + usz buffer_size; + usz descriptor_size; + uint descriptor_version; + void* descriptors; + usz descriptors_count; +} + +typedef MemoryAttribute = ulong; +const MemoryAttribute MEMORY_UC = (MemoryAttribute)0x0000_0000_0000_0001; +const MemoryAttribute MEMORY_WC = (MemoryAttribute)0x0000_0000_0000_0002; +const MemoryAttribute MEMORY_WT = (MemoryAttribute)0x0000_0000_0000_0004; +const MemoryAttribute MEMORY_WB = (MemoryAttribute)0x0000_0000_0000_0008; +const MemoryAttribute MEMORY_UCE = (MemoryAttribute)0x0000_0000_0000_0010; +const MemoryAttribute MEMORY_WP = (MemoryAttribute)0x0000_0000_0000_1000; +const MemoryAttribute MEMORY_RP = (MemoryAttribute)0x0000_0000_0000_2000; +const MemoryAttribute MEMORY_XP = (MemoryAttribute)0x0000_0000_0000_4000; +const MemoryAttribute MEMORY_NV = (MemoryAttribute)0x0000_0000_0000_8000; +const MemoryAttribute MEMORY_MORE_RELIABLE = (MemoryAttribute)0x0000_0000_0001_0000; +const MemoryAttribute MEMORY_RO = (MemoryAttribute)0x0000_0000_0002_0000; +const MemoryAttribute MEMORY_SP = (MemoryAttribute)0x0000_0000_0004_0000; +const MemoryAttribute MEMORY_CPU_CRYPTO = (MemoryAttribute)0x0000_0000_0008_0000; +const MemoryAttribute MEMORY_HOT_PLUGGABLE = (MemoryAttribute)0x0000_0000_0010_0000; +const MemoryAttribute MEMORY_RUNTIME = (MemoryAttribute)0x8000_0000_0000_0000; +const MemoryAttribute MEMORY_ISA_VALID = (MemoryAttribute)0x4000_0000_0000_0000; +const MemoryAttribute MEMORY_ISA_MASK = (MemoryAttribute)0x0FFF_F000_0000_0000; + +/* EFI_ALLOCATE_POOL (7.2.4) */ +alias FnAllocatePool = fn EfiStatus(MemoryType, usz, void**); + +/* EFI_FREE_POOL (7.2.5) */ +alias FnFreePool = fn EfiStatus(void*); + + +/* 8.4.) Virtual Memory services */ +/* 8.4.1.) SetVirtualAddressMap() */ +alias FnSetVirtualAddressMap = fn EfiStatus(usz, usz, uint, MemoryDescriptor*); + +/* 8.4.2.) ConvertPointer() */ +alias FnConvertPointer = fn EfiStatus(usz, void**); +const usz EFI_OPTIONAL_PTR = 0x1; + +/* 8.5.3.3.) Items related to capsules */ +struct MemoryRange +{ + PhysicalAddress address; + ulong length; +} diff --git a/lib/uefi.c3l/src/protocol/misc_boot_svcs.c3 b/lib/uefi.c3l/src/protocol/misc_boot_svcs.c3 new file mode 100644 index 0000000..8fc17af --- /dev/null +++ b/lib/uefi.c3l/src/protocol/misc_boot_svcs.c3 @@ -0,0 +1,25 @@ +module uefi::proto::misc_bs; +import uefi; + + +/* 7.5) Miscellaneous Boot Services */ +/* EFI_SET_WATCHDOG_TIMER (7.5.1) */ +alias FnSetWatchdogTimer = fn EfiStatus(usz, ulong, usz, EfiStringRaw); + +/* EFI_STALL (7.5.2) */ +alias FnStall = fn EfiStatus(usz); + +/* EFI_COPY_MEM (7.5.3) */ +alias FnCopyMem = fn void(void*, void*, usz); + +/* EFI_SET_MEM (7.5.4) */ +alias FnSetMem = fn void(void*, usz, char); + +/* EFI_GET_NEXT_MONOTONIC_COUNT (7.5.5) */ +alias FnGetNextMonotonicCount = fn EfiStatus(ulong*); + +/* EFI_INSTALL_CONFIGURATION_TABLE (7.5.6) */ +alias FnInstallConfigurationTable = fn EfiStatus(EfiGuid*, void*); + +/* EFI_CALCULATE_CRC32 (7.5.7) */ +alias FnCalculateCrc32 = fn EfiStatus(void*, usz, uint*); \ No newline at end of file diff --git a/lib/uefi.c3l/src/protocol/misc_runtime_svcs.c3 b/lib/uefi.c3l/src/protocol/misc_runtime_svcs.c3 new file mode 100644 index 0000000..0ec0aba --- /dev/null +++ b/lib/uefi.c3l/src/protocol/misc_runtime_svcs.c3 @@ -0,0 +1,124 @@ +module uefi::proto::misc_rt; +import uefi; + + +/* 8.5.) Miscellaneous Runtime services */ +/* 8.5.1.1.) ResetSystem() */ +alias FnResetSystem = fn void(ResetType, EfiStatus, usz, void*); + +enum ResetType : uint +{ + COLD, + WARM, + SHUTDOWN, + PLATFORM_SPECIFIC, +} + +/* 8.5.2.1.) GetNextHighMonotonicCount() */ +alias FnGetNextHighMonotonicCount = fn EfiStatus(uint*); + +/* 8.5.3.1.) UpdateCapsule() and related */ +alias FnUpdateCapsule = fn EfiStatus(CapsuleHeader**, usz, PhysicalAddress); + +struct CapsuleHeader +{ + EfiGuid capsule_guid; + uint header_size; + uint flags; + uint capsule_image_size; +} + +enum CapsuleFlags : uint (uint raw) +{ + PERSIST_ACROSS_RESET { 0x0001_0000 }, + POPULATE_SYSTEM_TABLE { 0x0002_0000 }, + INITIATE_RESET { 0x0004_0000 }, +} + +struct CapsuleBlockDescriptor +{ + ulong length; + union + { + PhysicalAddress data_block; + PhysicalAddress continuation_pointer; + } +} + +struct CapsuleTable +{ + uint capsule_array_number; + void* capsule_ptr; +} + +const EfiGuid EFI_MEMORY_RANGE_CAPSULE_GUID = { + 0xde9f0ec, + 0x88b6, + 0x428f, + { 0x97, 0x7a, 0x25, 0x8f, 0x1d, 0xe, 0x5e, 0x72 } +}; + +struct MemoryRangeCapsule +{ + CapsuleHeader header; + uint requested_memory_type; + ulong num_memory_ranges; + MemoryRange* memory_ranges; +} + +struct MemoryRangeCapsuleResult +{ + ulong firmware_memory_requirement; + ulong num_memory_ranges; +} + +/* 8.5.3.4.) QueryCapsuleCapabilities() */ +alias FnQueryCapsuleCapabilities = fn EfiStatus(CapsuleHeader**, usz, ulong*, ResetType*); + +/* OS Indications from a nearby section */ +enum OsIndications : ulong (ulong raw) // TODO: Change to inline ulong once supported +{ + BOOT_TO_FW_UI { 0x1 }, + TIMESTAMP_REVOCATION { 0x2 }, + FILE_CAPSULE_DELIVERY_SUPPORTED { 0x4 }, + FMP_CAPSULE_SUPPORTED { 0x8 }, + CAPSULE_RESULT_VAR_SUPPORTED { 0x10 }, + START_OS_RECOVERY { 0x20 }, + START_PLATFORM_RECOVERY { 0x40 }, + JSON_CONFIG_DATA_REFRESH { 0x80 }, +} + +/* 8.5.6.1.) -- */ +const EfiGuid EFI_CAPSULE_REPORT_GUID = { + 0x39b68c46, + 0xf7fb, + 0x441b, + { 0xb6, 0xec, 0x16, 0xb0, 0xf6, 0x98, 0x21, 0xf3 } +}; + +struct CapsuleResultVariableHeader +{ + uint variable_total_size; + uint reserved; /* spec says 'alignment' */ + EfiGuid capsule_guid; + EfiTime capsule_processed_at; + EfiStatus capsule_status; +} + +struct CapsuleResultVariableFMP +{ + ushort version; + char payload_index; + char update_image_index; + EfiGuid update_image_type_id; + /* implied: EfiStringRaw capsule_file_name */ + /* implied: EfiStringRaw capsule_target */ +} + +struct CapsuleResultVariableJson +{ + uint version; + uint capsule_id; + uint response_length; + char* response_data; +} \ No newline at end of file diff --git a/lib/uefi.c3l/src/protocol/time.c3 b/lib/uefi.c3l/src/protocol/time.c3 new file mode 100644 index 0000000..261e4b1 --- /dev/null +++ b/lib/uefi.c3l/src/protocol/time.c3 @@ -0,0 +1,23 @@ +module uefi::proto::time; +import uefi; + + +/* 8.3.) Time services */ +/* 8.3.1.) GetTime() */ +alias FnGetTime = fn EfiStatus(EfiTime*, EfiTimeCapabilities*); + +struct TimeCapabilities +{ + uint resolution; + uint accuracy; + bool sets_to_zero; +} + +/* 8.3.2.) SetTime() */ +alias FnSetTime = fn EfiStatus(EfiTime*); + +/* 8.3.3.) GetWakeupTime() */ +alias FnGetWakeupTime = fn EfiStatus(bool*, bool*, EfiTime*); + +/* 8.3.4.) SetWakeupTime() */ +alias FnSetWakeupTime = fn EfiStatus(bool, EfiTime*); \ No newline at end of file diff --git a/lib/uefi.c3l/src/protocol/variable.c3 b/lib/uefi.c3l/src/protocol/variable.c3 new file mode 100644 index 0000000..bf5175b --- /dev/null +++ b/lib/uefi.c3l/src/protocol/variable.c3 @@ -0,0 +1,68 @@ +module uefi::proto::variable; +import uefi; + + +/* 8.2.) Variable services */ +/* 8.2.1.) GetVariable() */ +alias FnGetVariable = fn EfiStatus(EfiStringRaw, EfiGuid*, uint*, usz*, void*); + +/* Variable Attributes */ +enum EfiVarAttr : uint (uint raw) // TODO: Add `inline` inside parens when supported +{ + NON_VOLATILE { 0x0000_0001 }, + BOOTSERVICE_ACCESS { 0x0000_0002 }, + RUNTIME_ACCESS { 0x0000_0004 }, + HARDWARE_ERROR_RECORD { 0x0000_0008 }, + HR { 0x0000_0008 }, /* spec notes aliasing of this to above */ + RESERVED { 0x0000_0010 }, + TIME_BASED_AUTHENTICATED_WRITE_ACCESS { 0x0000_0020 }, + APPEND_WRITE { 0x0000_0040 }, + ENHANCED_AUTHENTICATED_ACCESS { 0x0000_0080 }, +} + +struct VariableAuthentication3CertId +{ + char type; + uint id_size; + /* implied to follow: char id[id_size]; */ +} + +/* 8.2.2.) GetNextVariableName() */ +alias FnGetNextVariableName = fn EfiStatus(usz*, EfiStringRaw, EfiGuid*); + +/* 8.2.3.) SetVariable() */ +alias FnSetVariable = fn EfiStatus(EfiStringRaw, EfiGuid*, uint, usz, void*); + +/* TODO: Too much extra complexity to use right now. Add later. */ +/* struct VariableAuthentication2 +{ + EfiTime timestamp; + WinCertificateUefiGuid auth_info; +} */ + +const char EFI_VARIABLE_AUTHENTICATION_3_TIMESTAMP_TYPE = 1; +const char EFI_VARIABLE_AUTHENTICATION_3_NONCE_TYPE = 2; +struct VariableAuthentication3 +{ + char version; + char type; + uint metadata_size; + uint flags; +} + +struct VariableAuthentication3Nonce +{ + uint nonce_size; + /* implied to follow: char nonce[nonce_size]; */ +} + +/* 8.2.4.) QueryVariableInfo() */ +alias FnQueryVariableInfo = fn EfiStatus(uint, ulong*, ulong*, ulong*); + +/* 8.2.7.2.) Hardware Error Record Variables */ +const EfiGuid EFI_HARDWARE_ERROR_VARIABLE = { + 0x414e6bdd, + 0xe47b, + 0x47cc, + { 0xb2, 0x44, 0xbb, 0x61, 0x02, 0x0c, 0xf5, 0x16 } +}; \ No newline at end of file diff --git a/project.json b/project.json new file mode 100644 index 0000000..8c76722 --- /dev/null +++ b/project.json @@ -0,0 +1,45 @@ +{ + // Language version of C3. + "langrev": "1", + // Warnings used for all targets. + "warnings": [ "no-unused" ], + // Directories where C3 library files may be found. + "dependency-search-paths": [ "lib" ], + // Libraries to use for all targets. + "dependencies": [ ], + // Authors, optionally with email. + "authors": [ "John Doe " ], + // Version using semantic versioning. + "version": "0.1.0", + // Sources compiled for all targets. + "sources": [ "src/**" ], + // Test sources compiled for all targets. + "test-sources": [ "test/**" ], + // C sources if the project also compiles C sources + // relative to the project file. + // "c-sources": [ "csource/**" ], + // Include directories for C sources relative to the project file. + // "c-include-dirs": [ "csource/include" ], + // Build location, relative to project file. + "build-dir": "build", + // Output location, relative to project file. + "output": "build", + // Architecture and OS target. + // You can use 'c3c --list-targets' to list all valid targets. + // "target": "windows-x64", + // Targets. + "targets": { + "c3os": { + // Executable or library. + "type": "executable", + // Additional libraries, sources + // and overrides of global settings here. + }, + }, + // Global settings. + // CPU name, used for optimizations in the LLVM backend. + "cpu": "generic", + // Optimization: "O0", "O1", "O2", "O3", "O4", "O5", "Os", "Oz". + "opt": "O0" + // See resources/examples/project_all_settings.json and 'c3c --list-project-properties' to see more properties. +} \ No newline at end of file diff --git a/src/main.c3 b/src/main.c3 new file mode 100644 index 0000000..c857210 --- /dev/null +++ b/src/main.c3 @@ -0,0 +1,8 @@ +module c3os; +import std::io; + +fn int main(String[] args) +{ + io::printn("Hello, World!"); + return 0; +} -- cgit v1.3.1