[
  {
    "path": ".gitattributes",
    "content": "###############################################################################\n# Set default behavior to automatically normalize line endings.\n###############################################################################\n* text=auto\n\n###############################################################################\n# Set default behavior for command prompt diff.\n#\n# This is need for earlier builds of msysgit that does not have it on by\n# default for csharp files.\n# Note: This is only used by command line\n###############################################################################\n#*.cs     diff=csharp\n\n###############################################################################\n# Set the merge driver for project and solution files\n#\n# Merging from the command prompt will add diff markers to the files if there\n# are conflicts (Merging from VS is not affected by the settings below, in VS\n# the diff markers are never inserted). Diff markers may cause the following \n# file extensions to fail to load in VS. An alternative would be to treat\n# these files as binary and thus will always conflict and require user\n# intervention with every merge. To do so, just uncomment the entries below\n###############################################################################\n#*.sln       merge=binary\n#*.csproj    merge=binary\n#*.vbproj    merge=binary\n#*.vcxproj   merge=binary\n#*.vcproj    merge=binary\n#*.dbproj    merge=binary\n#*.fsproj    merge=binary\n#*.lsproj    merge=binary\n#*.wixproj   merge=binary\n#*.modelproj merge=binary\n#*.sqlproj   merge=binary\n#*.wwaproj   merge=binary\n\n###############################################################################\n# behavior for image files\n#\n# image files are treated as binary by default.\n###############################################################################\n#*.jpg   binary\n#*.png   binary\n#*.gif   binary\n\n###############################################################################\n# diff behavior for common document formats\n# \n# Convert binary document formats to text before diffing them. This feature\n# is only available from the command line. Turn it on by uncommenting the \n# entries below.\n###############################################################################\n#*.doc   diff=astextplain\n#*.DOC   diff=astextplain\n#*.docx  diff=astextplain\n#*.DOCX  diff=astextplain\n#*.dot   diff=astextplain\n#*.DOT   diff=astextplain\n#*.pdf   diff=astextplain\n#*.PDF   diff=astextplain\n#*.rtf   diff=astextplain\n#*.RTF   diff=astextplain\n"
  },
  {
    "path": ".gitignore",
    "content": "# Visual Studio Files\n.vs/\n*.opensdf\n*.sdf\n*.suo\n*.sln\n*.user\nx64/\nRelease\nDebug"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# gftrace\n\nA command line Windows API tracing tool for Golang binaries.\n\n**Note:** This tool is a PoC and a work-in-progress prototype so please treat it as such. Feedbacks are always welcome!\n\n## **How it works?**\n\nAlthough Golang programs contains a lot of nuances regarding the way they are built and their behavior in runtime they still need to interact with the OS layer and that means at some point they do need to call functions from the Windows API.\n\nThe Go runtime package contains a function called [asmstdcall](https://github.com/golang/go/blob/master/src/runtime/sys_windows_amd64.s#L20) and this function is a kind of \"gateway\" used to interact with the Windows API. Since it's expected this function to call the Windows API functions we can assume it needs to have access to information such as the address of the function and it's parameters, and this is where things start to get more interesting.\n\nAsmstdcall receives a single parameter which is pointer to something similar to the following structure:\n\n```\nstruct LIBCALL {\n\tDWORD_PTR Addr;\n\tDWORD Argc;\n\tDWORD_PTR Argv;\n\tDWORD_PTR ReturnValue;\n\t\n\t[...]\n}\n```\n\nSome of these fields are filled after the API function is called, like the return value, others are received by asmstdcall, like the function address, the number of arguments and the list of arguments. Regardless when those are set it's clear that the asmstdcall function manipulates a lot of interesting information regarding the execution of programs compiled in Golang.\n\nThe gftrace leverages asmstdcall and the way it works to monitor specific fields of the mentioned struct and log it to the user. The tool is capable of log the function name, it's parameters and also the return value of each Windows function called by a Golang application. All of it with no need to hook a single API function or have a signature for it.\n\nThe tool also tries to ignore all the noise from the Go runtime initialization and only log functions called after it (i.e. functions from the main package).\n\nIf you want to know more about this project and research check the [blogpost](https://leandrofroes.github.io/posts/An-in-depth-look-at-Golang-Windows-calls/).\n\n## **Installation**\n\nDownload the latest [release](https://github.com/leandrofroes/gftrace/releases).\n\n## **Usage**\n\n1. Make sure gftrace.exe, gftrace.dll and gftrace.cfg are in the same directory.\n2. Specify which API functions you want to trace in the gftrace.cfg file (the tool does not work without API filters applied).\n3. Run gftrace.exe passing the target Golang program path as a parameter.\n\n```\ngftrace.exe <filepath> <params>\n```\n\n## **Configuration**\n\nAll you need to do is specify which functions you want to trace in the gftrace.cfg file, separating it by comma with no spaces:\n\n```\nCreateFileW,ReadFile,CreateProcessW\n```\n\nThe exact Windows API functions a Golang method X of a package Y would call in a specific scenario can only be determined either by analysis of the method itself or trying to guess it. There's some interesting characteristics that can be used to determine it, for example, Golang applications seems to always prefer to call functions from the \"Wide\" and \"Ex\" set (e.g. CreateFileW, CreateProcessW, GetComputerNameExW, etc) so you can consider it during your analysis.\n\nThe default config file contains multiple functions in which I tested already (at least most part of them) and can say for sure they can be called by a Golang application at some point. I'll try to update it eventually.\n\n## **Examples**\n\nTracing CreateFileW() and ReadFile() in a simple Golang file that calls \"os.ReadFile\" twice:\n\n```\n- CreateFileW(\"C:\\Users\\user\\Desktop\\doc.txt\", 0x80000000, 0x3, 0x0, 0x3, 0x1, 0x0) = 0x168 (360)\n- ReadFile(0x168, 0xc000108000, 0x200, 0xc000075d64, 0x0) = 0x1 (1)\n- CreateFileW(\"C:\\Users\\user\\Desktop\\doc2.txt\", 0x80000000, 0x3, 0x0, 0x3, 0x1, 0x0) = 0x168 (360)\n- ReadFile(0x168, 0xc000108200, 0x200, 0xc000075d64, 0x0) = 0x1 (1)\n```\n\nTracing CreateProcessW() in the TunnelFish malware:\n\n```\n- CreateProcessW(\"C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\", \"powershell /c \"Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Recipient | Select Name -ExpandProperty EmailAddresses -first 1 | Select SmtpAddress |  ft -hidetableheaders\"\", 0x0, 0x0, 0x1, 0x80400, \"=C:=C:\\Users\\user\\Desktop\", 0x0, 0xc0000ace98, 0xc0000acd68) = 0x1 (1)\n- CreateProcessW(\"C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\", \"powershell /c \"Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Recipient | Select Name -ExpandProperty EmailAddresses -first 1 | Select SmtpAddress |  ft -hidetableheaders\"\", 0x0, 0x0, 0x1, 0x80400, \"=C:=C:\\Users\\user\\Desktop\", 0x0, 0xc0000c4ec8, 0xc0000c4d98) = 0x1 (1)\n- CreateProcessW(\"C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\", \"powershell /c \"Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Recipient | Select Name -ExpandProperty EmailAddresses -first 1 | Select SmtpAddress |  ft -hidetableheaders\"\", 0x0, 0x0, 0x1, 0x80400, \"=C:=C:\\Users\\user\\Desktop\", 0x0, 0xc00005eec8, 0xc00005ed98) = 0x1 (1)\n- CreateProcessW(\"C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\", \"powershell /c \"Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Recipient | Select Name -ExpandProperty EmailAddresses -first 1 | Select SmtpAddress |  ft -hidetableheaders\"\", 0x0, 0x0, 0x1, 0x80400, \"=C:=C:\\Users\\user\\Desktop\", 0x0, 0xc0000bce98, 0xc0000bcd68) = 0x1 (1)\n- CreateProcessW(\"C:\\WINDOWS\\system32\\cmd.exe\", \"cmd /c \"wmic computersystem get domain\"\", 0x0, 0x0, 0x1, 0x80400, \"=C:=C:\\Users\\user\\Desktop\", 0x0, 0xc0000c4ef0, 0xc0000c4dc0) = 0x1 (1)\n- CreateProcessW(\"C:\\WINDOWS\\system32\\cmd.exe\", \"cmd /c \"wmic computersystem get domain\"\", 0x0, 0x0, 0x1, 0x80400, \"=C:=C:\\Users\\user\\Desktop\", 0x0, 0xc0000acec0, 0xc0000acd90) = 0x1 (1)\n- CreateProcessW(\"C:\\WINDOWS\\system32\\cmd.exe\", \"cmd /c \"wmic computersystem get domain\"\", 0x0, 0x0, 0x1, 0x80400, \"=C:=C:\\Users\\user\\Desktop\", 0x0, 0xc0000bcec0, 0xc0000bcd90) = 0x1 (1)\n\n[...]\n```\n\nTracing multiple functions in the Sunshuttle malware:\n\n```\n- CreateFileW(\"config.dat.tmp\", 0x80000000, 0x3, 0x0, 0x3, 0x1, 0x0) = 0xffffffffffffffff (-1)\n- CreateFileW(\"config.dat.tmp\", 0xc0000000, 0x3, 0x0, 0x2, 0x80, 0x0) = 0x198 (408)\n- CreateFileW(\"config.dat.tmp\", 0xc0000000, 0x3, 0x0, 0x3, 0x80, 0x0) = 0x1a4 (420)\n- WriteFile(0x1a4, 0xc000112780, 0xeb, 0xc0000c79d4, 0x0) = 0x1 (1)\n- GetAddrInfoW(\"reyweb.com\", 0x0, 0xc000031f18, 0xc000031e88) = 0x0 (0)\n- WSASocketW(0x2, 0x1, 0x0, 0x0, 0x0, 0x81) = 0x1f0 (496)\n- WSASend(0x1f0, 0xc00004f038, 0x1, 0xc00004f020, 0x0, 0xc00004eff0, 0x0) = 0x0 (0)\n- WSARecv(0x1f0, 0xc00004ef60, 0x1, 0xc00004ef48, 0xc00004efd0, 0xc00004ef18, 0x0) = 0xffffffff (-1)\n- GetAddrInfoW(\"reyweb.com\", 0x0, 0xc000031f18, 0xc000031e88) = 0x0 (0)\n- WSASocketW(0x2, 0x1, 0x0, 0x0, 0x0, 0x81) = 0x200 (512)\n- WSASend(0x200, 0xc00004f2b8, 0x1, 0xc00004f2a0, 0x0, 0xc00004f270, 0x0) = 0x0 (0)\n- WSARecv(0x200, 0xc00004f1e0, 0x1, 0xc00004f1c8, 0xc00004f250, 0xc00004f198, 0x0) = 0xffffffff (-1)\n\n[...]\n```\n\nTracing multiple functions in the DeimosC2 framework agent:\n\n```\n- WSASocketW(0x2, 0x1, 0x0, 0x0, 0x0, 0x81) = 0x130 (304)\n- setsockopt(0x130, 0xffff, 0x20, 0xc0000b7838, 0x4) = 0xffffffff (-1)\n- socket(0x2, 0x1, 0x6) = 0x138 (312)\n- WSAIoctl(0x138, 0xc8000006, 0xaf0870, 0x10, 0xb38730, 0x8, 0xc0000b746c, 0x0, 0x0) = 0x0 (0)\n- GetModuleFileNameW(0x0, \"C:\\Users\\user\\Desktop\\samples\\deimos.exe\", 0x400) = 0x2f (47)\n- GetUserProfileDirectoryW(0x140, \"C:\\Users\\user\", 0xc0000b7a08) = 0x1 (1)\n- LookupAccountSidw(0x0, 0xc00000e250, \"user\", 0xc0000b796c, \"DESKTOP-TEST\", 0xc0000b7970, 0xc0000b79f0) = 0x1 (1)\n- NetUserGetInfo(\"DESKTOP-TEST\", \"user\", 0xa, 0xc0000b7930) = 0x0 (0)\n- GetComputerNameExW(0x5, \"DESKTOP-TEST\", 0xc0000b7b78) = 0x1 (1)\n- GetAdaptersAddresses(0x0, 0x10, 0x0, 0xc000120000, 0xc0000b79d0) = 0x0 (0)\n- CreateToolhelp32Snapshot(0x2, 0x0) = 0x1b8 (440)\n- GetCurrentProcessId() = 0x2584 (9604)\n- GetCurrentDirectoryW(0x12c, \"C:\\Users\\user\\AppData\\Local\\Programs\\retoolkit\\bin\") = 0x39 (57)\n\n[...]\n```\n\n## **Future features:**\n\n- [x] Support inspection of 32 bits files.\n- [x] Add support to files calling functions via the \"IAT jmp table\" instead of the API call directly in asmstdcall.\n- [x] Add support to cmdline parameters for the target process\n- [ ] Send the tracing log output to a file by default to make it better to filter. Currently there's no separation between the target file and gftrace output. An alternative is redirect gftrace output to a file using the command line.\n\n## :warning: **Warning**\n\n* The tool inspects the target binary dynamically and it means the file being traced is executed. If you're inspecting a malware or an unknown software please make sure you do it in a controlled environment.\n* Golang programs can be very noisy depending the file and/or function being traced (e.g. VirtualAlloc is always called multiple times by the runtime package, CreateFileW is called multiple times before a call to CreateProcessW, etc). The tool ignores the Golang runtime initialization noise but after that it's up to the user to decide what functions are better to filter in each scenario.\n\n## **License**\n\nThe gftrace is published under the GPL v3 License. Please refer to the file named LICENSE for more information.\n"
  },
  {
    "path": "injector/injector.c",
    "content": "#include <stdio.h>\n#include <windows.h>\n\nint main(int argc, char** argv)\n{\n    if (argc < 2)\n    {\n        printf(\"Usage: gftrace.exe <file> <params>\\n\");\n        return 1;\n    }\n\n    LPSTR CmdLine = GetCommandLineA();\n    LPSTR ProcCmdLine = strchr(CmdLine, 0x20);\n\n    //\n    // Ignore all the spaces next to argv[0]\n    //\n    while (*++ProcCmdLine == 0x20);\n\n    PROCESS_INFORMATION ProcessInformation;\n    STARTUPINFOA StartupInfo;\n\n    StartupInfo.cb = sizeof(STARTUPINFO);\n    ZeroMemory(&StartupInfo, sizeof(STARTUPINFO));\n    ZeroMemory(&ProcessInformation, sizeof(PROCESS_INFORMATION));\n\n    //\n    // Create the target process in suspended state.\n    //\n    if (!CreateProcessA(NULL, ProcCmdLine, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &StartupInfo, &ProcessInformation))\n    {\n        printf(\"[!] Failed to create the target process.\\n[!] Error code: %u\\n\", GetLastError());\n        return 1;\n    }\n\n    HANDLE hProcess = ProcessInformation.hProcess;\n    HANDLE hThread = ProcessInformation.hThread;\n\n    //\n    // Check if the target process is a Wow64 process and if so, terminate it cause we don't support it for now.\n    //\n#ifdef _WIN64\n    BOOL IsWow64Proc = FALSE;\n\n    if (!IsWow64Process(hProcess, &IsWow64Proc))\n    {\n        printf(\"[!] Failed to check if the target process is WoW64.\\n[!] Error code: %u\\n\", GetLastError());\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n\n    if (IsWow64Proc)\n    {\n        printf(\"[!] The target file needs to be a x64 file.\\n\");\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n#endif\n\n    char LibFullPath[MAX_PATH] = {0};\n    char CurrentModuleFilepath[MAX_PATH] = {0};\n\n    DWORD Len = GetModuleFileNameA(GetModuleHandleA(NULL), CurrentModuleFilepath, MAX_PATH);\n\n    if (!Len)\n    {\n        printf(\"[!] Failed to get the current module filepath.\\n[!] Error code: %u\\n\", GetLastError());\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n\n    for (SIZE_T i = Len - 1; i > 0; i--)\n    {\n        if (CurrentModuleFilepath[i] == 0x5c || CurrentModuleFilepath[i] == 0x2f)\n        {\n            CurrentModuleFilepath[i + 1] = '\\0';\n            break;\n        }\n    }\n\n    SIZE_T i = 0;\n\n    do\n    {\n        LibFullPath[i] = CurrentModuleFilepath[i];\n        i++;\n    } while (CurrentModuleFilepath[i] != '\\0');\n\n#ifdef _WIN64\n    const char* LibName = \"\\\\gftrace.dll\";\n#else\n    const char* LibName = \"\\\\gftrace32.dll\";\n#endif\n\n    SIZE_T Size = strlen(LibFullPath) + strlen(LibName) + 1;\n\n    //\n    // Build the gftrace.dll full path to be used in the injection step.\n    //\n    strncat_s(LibFullPath, Size, LibName, _TRUNCATE);\n\n    //\n    // Check if the gftrace.dll file exists in the gftrace.exe directory.\n    //\n    if (GetFileAttributesA((LPCSTR)LibFullPath) == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND)\n    {\n        printf(\"[!] Failed to find the gftrace DLL file in the gftrace.exe directory.\\n\");\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n\n    //\n    // Get kernel32.dll module base address.\n    //\n    HMODULE ModuleBase = GetModuleHandleW(L\"kernel32.dll\");\n\n    if (ModuleBase == NULL)\n    {\n        printf(\"[!] Failed to get kernel32 base address.\\n[!] Error code: %u\\n\", GetLastError());\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n\n    //\n    // Get the address of LoadLibraryA() to be used to inject gftrace DLL into the target process.\n    //\n    FARPROC pLoadLibraryA = GetProcAddress(ModuleBase, \"LoadLibraryA\");\n\n    if (pLoadLibraryA == NULL)\n    {\n        printf(\"[!] Failed to resolve LoadLibraryA address.\\n[!] Error code: %u\\n\", GetLastError());\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n\n    //\n    // Allocate memory for gftrace DLL full path in the target process.\n    //\n    LPVOID LibFullPathRemoteAddr = VirtualAllocEx(hProcess, NULL, Size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);\n\n    if (LibFullPathRemoteAddr == NULL)\n    {\n        printf(\"[!] Failed to allocate virtual memory in the target process.\\n[!] Error code: %u\\n\", GetLastError());\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n\n    //\n    // Write gftrace DLL full path into the target process.\n    //\n    if (!WriteProcessMemory(hProcess, LibFullPathRemoteAddr, (LPCVOID)LibFullPath, Size, NULL))\n    {\n        printf(\"[!] Failed to write to the target process memory.\\n[!] Error code: %u\\n\", GetLastError());\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n\n    DWORD ThreadId;\n\n    //\n    // Create a thread in the target process pointing to LoadLibraryA() to load the gftrace DLL into the target process address space.\n    //\n    HANDLE hInjectionThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pLoadLibraryA, (LPVOID)LibFullPathRemoteAddr, 0, &ThreadId);\n\n    if (hInjectionThread == NULL)\n    {\n        printf(\"[!] Failed to create a remote thread in the target process.\\n[!] Error code: %u\\n\", GetLastError());\n        TerminateProcess(hProcess, 0);\n        return 1;\n    }\n\n    //\n    // Wait for the injection thread to finish.\n    //\n    WaitForSingleObject(hInjectionThread, INFINITE);\n\n    //\n    // Resume the target process main thread.\n    //\n    ResumeThread(hThread);\n\n    WaitForSingleObject(hProcess, INFINITE);\n\n    VirtualFreeEx(hProcess, LibFullPathRemoteAddr, 0, MEM_RELEASE);\n    CloseHandle(hInjectionThread);\n    CloseHandle(hThread);\n\n    return 0;\n}"
  },
  {
    "path": "injector/injector.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug|Win32\">\n      <Configuration>Debug</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|Win32\">\n      <Configuration>Release</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug|x64\">\n      <Configuration>Debug</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|x64\">\n      <Configuration>Release</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <VCProjectVersion>16.0</VCProjectVersion>\n    <Keyword>Win32Proj</Keyword>\n    <ProjectGuid>{adacdd4b-f686-4706-bc39-ec3896af2d86}</ProjectGuid>\n    <RootNamespace>injector</RootNamespace>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\n    <ConfigurationType>Application</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n  </ImportGroup>\n  <ImportGroup Label=\"Shared\">\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n    <TargetName>gftrace32</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n    <TargetName>gftrace</TargetName>\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n      <Optimization>Disabled</Optimization>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>false</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n      <Optimization>Disabled</Optimization>\n    </ClCompile>\n    <Link>\n      <SubSystem>Console</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>false</GenerateDebugInformation>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"injector.c\" />\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n  </ImportGroup>\n</Project>"
  },
  {
    "path": "injector/injector.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <Filter Include=\"Source Files\">\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\n      <Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n    </Filter>\n    <Filter Include=\"Header Files\">\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\n      <Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>\n    </Filter>\n    <Filter Include=\"Resource Files\">\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n    </Filter>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"injector.c\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n  </ItemGroup>\n</Project>"
  },
  {
    "path": "tracer/dllmain.c",
    "content": "#include \"utils.h\"\n#include \"hooks.h\"\n\nVOID\nInit()\n{\n    //\n    // Get kernel32.dll module base address.\n    //\n    HMODULE ModuleBase = GetModuleHandleW(L\"kernel32.dll\");\n\n    if (ModuleBase == NULL)\n    {\n        PrintWinError(\"Failed to get kernel32.dll base address\", GetLastError());\n    }\n\n    //\n    // Get the address of GetCommandLineW() and save it for further usage.\n    //\n    pGetCommandLineW = GetProcAddress(ModuleBase, (LPCSTR)\"GetCommandLineW\");\n\n    if (pGetCommandLineW == NULL)\n    {\n        PrintWinError(\"Failed to resolve GetCommandLineW() address\", GetLastError());\n    }\n\n    //\n    // Get the address of GetProcAddress() and save it for further usage.\n    //\n    pGetProcAddress = GetProcAddress(ModuleBase, (LPCSTR)\"GetProcAddress\");\n\n    if (pGetProcAddress == NULL)\n    {\n        PrintWinError(\"Failed to resolve GetProcAddress() address\", GetLastError());\n    }\n\n    //\n    // Initialize a critical section object.\n    //\n    InitializeCriticalSection(&CriticalSection);\n\n    //\n    // Parse the user-defined API function list and initialize our global target list.\n    //\n    InitTargetFuncList();\n\n    //\n    // Initialize our IAT deny list.\n    //\n    InitIATDenyList();\n\n    //\n    // Perform the asmstdcall hook.\n    //\n    HookAsmstdcall();\n}\n\nBOOL WINAPI DllMain(\n    HINSTANCE hModule,\n    DWORD Reason,\n    LPVOID Reserved\n)\n{\n    switch (Reason)\n    {\n        case DLL_PROCESS_ATTACH:\n            //\n            // Disable the DLL_THREAD_ATTACH and DLL_THREAD_DETACH notifications in our DLL.\n            //\n            DisableThreadLibraryCalls(hModule);\n\n            Init();\n\n            break;\n\n        case DLL_THREAD_ATTACH:\n            break;\n\n        case DLL_THREAD_DETACH:\n            break;\n\n        case DLL_PROCESS_DETACH:\n            while (!GetAsyncKeyState(VK_RETURN))\n            {\n                Sleep(1000);\n            }\n\n            printf(\"\\n\\n[+] Trace finished! Press \\\"Enter\\\" to close...\\n\");\n\n            break;\n    }\n\n    return TRUE;\n}"
  },
  {
    "path": "tracer/gftrace.cfg",
    "content": "CreateFileW,ReadFile,WriteFile,MoveFileW,DeleteFileW,SetFilePointerEx,CopyFileW,FindFirstFileW,SetFileAttributesW,GetCurrentDirectoryW,GetUserProfileDirectoryW,SetCurrentDirectoryW,GetTempPathW,GetModuleFileNameW,RemoveDirectoryW,GetSystemDirectoryW,GetFullPathNameW,WSASocketW,socket,setsockopt,gethostbyname,WSARecvFrom,WSASendTo,DnsQuery_W,WSAIoctl,WSASend,WSASendTo,WSARecv,GetAddrInfoW,WinHttpAddRequestHeaders,WinHttpOpen,WinHttpConnect,WinHttpOpenRequest,WinHttpSendRequest,WinHttpReceiveResponse,WinHttpReadData,WinHttpSetOption,WinHttpSetTimeouts,WinHttpGetIEProxyConfigForCurrentUser,WinHttpGetProxyForUrl,WinHttpGetDefaultProxyConfiguration,OpenProcess,CreateProcessW,CreateProcessAsUserW,TerminateProcess,GetCurrentProcessId,ReadProcessMemory,WriteProcessMemory,ConvertSidToStringSidW,CreateMutexW,CreateToolhelp32Snapshot,QueryFullProcessImageNameW,OpenProcessToken,GetTokenInformation,CheckTokenMembership,AdjustTokenPrivileges,LookupAccountSidW,CreateNamedPipeW,ShellExecuteW,WTSGetActiveConsoleSessionId,WTSQuerySessionInformationW,GetLogicalDrives,GetDriveTypeW,GetLogicalDriveStringsW,GetVolumeInformationW,RegCreateKeyExW,RegOpenKeyExW,RegQueryValueExW,RegSetValueExW,RegDeleteKeyW,GetComputerNameExW,LookupAccountNameW,NetUserGetInfo,GetAdaptersAddresses,GetTimeZoneInformation,GetMonitorInfoW,EnumDisplaySettingsW,GetSystemMetrics,GetDC,CreateCompatibleDC,CreateCompatibleBitmap,BitBlt,GetDIBits,SelectObject,GetSystemTimes,RegisterServiceCtrlHandlerExW\n"
  },
  {
    "path": "tracer/hooks.c",
    "content": "#include \"hooks.h\"\n#include \"utils.h\"\n#include \"pe.h\"\n\nbIsReadyToLog = FALSE;\n\nLPVOID\nPerformHook(\n\t_In_ ULONG_PTR Src,\n\t_In_ ULONG_PTR Dest,\n\t_In_ SIZE_T Len\n)\n{\n\tCHAR HookBytes[] = {\n\t\t0x49, 0xbb, 0xd, 0xe, 0xa, 0xd, 0xb, 0xe, 0xe, 0xf, // mov r11, <target_addr>\n\t\t0x41, 0xff, 0xe3,                                   // jmp r11\n\t};\n\n\tDWORD HookBytesLen = 13;\n\tDWORD OldProtection;\n\n\t//\n\t// Change the memory permission of the region we want to modify the bytes.\n\t//\n\tif (!VirtualProtect((LPVOID)Src, Len, PAGE_EXECUTE_READWRITE, &OldProtection))\n\t{\n\t\tPrintWinError(\"Failed setting the hook memory region protection\", GetLastError());\n\t}\n\n\t//\n\t// Write the HookBytes array with the correct dest address into the target address.\n\t//\n\t*(ULONG_PTR*)(HookBytes + 2) = Dest;\n\tRtlCopyMemory((LPVOID)Src, (LPCVOID)HookBytes, sizeof(HookBytes));\n\n\t//\n\t// NOP the remaining hook bytes to make sure the instructions will be properly aligned.\n\t//\n\tfor (SIZE_T i = HookBytesLen; i < Len; i++)\n\t{\n\t\t*((BYTE*)Src + i) = 0x90;\n\t}\n\n\t//\n\t// Restore the hook memory region permissions.\n\t//\n\tif (!VirtualProtect((LPVOID)Src, Len, OldProtection, &OldProtection))\n\t{\n\t\tPrintWinError(\"Failed setting the old memory protection\", GetLastError());\n\t}\n\n\t//\n\t// Return the jump back address (i.e. the address to return after our hook is executed). \n\t//\n\treturn (LPVOID)(Src + Len);\n}\n\nLPVOID\nPerformHook32(\n\t_In_ ULONG_PTR Src,\n\t_In_ ULONG_PTR Dest,\n\t_In_ SIZE_T Len\n)\n{\n\tDWORD HookBytesLen = 5;\n\tDWORD OldProtection;\n\n\t//\n\t// Change the memory permission of the region we want to modify the bytes.\n\t//\n\tif (!VirtualProtect((LPVOID)Src, Len, PAGE_READWRITE, &OldProtection))\n\t{\n\t\tPrintWinError(\"Failed setting the hook memory region protection\", GetLastError());\n\t}\n\n\tULONG_PTR RelativeAddr = (Dest - Src) - 5;\n\n\t//\n\t// Write the \"jmp <address>\" bytes into the target address.\n\t//\n\t*(BYTE*)Src = 0xE9; // JMP\n\t*(ULONG_PTR*)(Src + 1) = RelativeAddr;\n\n\t//\n\t// NOP the remaining hook bytes to make sure the instructions will be properly aligned.\n\t//\n\tfor (SIZE_T i = HookBytesLen; i < Len; i++)\n\t{\n\t\t*((BYTE*)Src + i) = 0x90;\n\t}\n\n\t//\n\t// Restore the hook memory region permissions.\n\t//\n\tif (!VirtualProtect((LPVOID)Src, Len, OldProtection, &OldProtection))\n\t{\n\t\tPrintWinError(\"Failed setting the old memory protection\", GetLastError());\n\t}\n\n\t//\n\t// Return the jump back address (i.e. the address to return after our hook is executed). \n\t//\n\treturn (LPVOID)(Src + Len);\n}\n\nVOID\nHookAsmstdcall()\n{\n\t//\n\t// Get the base address of the Golang module the gftrace DLL is injected into.\n\t//\n\tHMODULE GolangModuleBase = GetModuleHandleW(NULL);\n\n\tif (GolangModuleBase == NULL)\n\t{\n\t\tPrintWinError(\"Failed to get the Golang module base address\", GetLastError());\n\t}\n\n\t//\n\t// Get the .text section header of the Golang module.\n\t//\n\tPIMAGE_SECTION_HEADER SectionHeader = GetSectionHeader((ULONG_PTR)GolangModuleBase, (BYTE*)\".text\");\n\n\tif (SectionHeader == NULL)\n\t{\n\t\tPrintError(\"Failed to get a pointer to the Golang module .text section\");\n\t}\n\n\t//\n\t// Get the size of the .text section of the Golang module.\n\t//\n\tSIZE_T SectionSize = (SIZE_T)SectionHeader->Misc.VirtualSize;\n\n\tif (!SectionSize)\n\t{\n\t\tPrintError(\"Golang module .text section size is zero\");\n\t}\n\n#ifdef _WIN64\n\t//\n\t// https://github.com/golang/go/blob/master/src/runtime/sys_windows_amd64.s#L20\n\t// \n\tCHAR TargetAddrPattern[] = {\n\t\t0x65, 0x48, 0x8B, 0x3C, 0x25, 0x30, 0x00, 0x00, 0x00, \t// mov rdi, qword ptr gs:[0x30]\n\t\t0x8B, 0x47, 0x68,                                     \t// mov eax, dword ptr ds:[rdi+0x68]\n\t\t0x48, 0x89, 0x41, 0x28\t\t\t\t\t// mov qword ptr ds:[rcx+0x28], rax\n\t};\n\n\tLPCSTR Mask = \"xxxxxxxxxxxxxxxx\";\n\tSIZE_T NumberOfBytesToHook = 0x10;\n#else\n\t//\n\t// https://github.com/golang/go/blob/master/src/runtime/sys_windows_386.s#L17\n\t// \n\tCHAR TargetAddrPattern[] = {\n\t\t0x64, 0x8B, 0x05, 0x34, 0x00, 0x00, 0x00,\t// mov eax, dword ptr fs:[0x34]\n\t\t0x89, 0x43, 0x14,\t\t\t\t// mov dword ptr ds:[ebx+0x14], eax\n\t\t0xC3\t\t\t\t\t\t// ret\n\t};\n\n\tLPCSTR Mask = \"xxxxxxxxxxx\";\n\tSIZE_T NumberOfBytesToHook = 0x7;\n#endif\n\n\t//\n\t// Attempt to find the target address we want to hook inside Asmstdcall function.\n\t//\n\tULONG_PTR HookAddr = FindPattern((ULONG_PTR)GolangModuleBase, SectionSize, (LPCSTR)TargetAddrPattern, Mask);\n\n\tif (!HookAddr)\n\t{\n\t\tPrintError(\"Failed to find Asmstdcall code pattern\");\n\t}\n\n\t//\n\t// Perform a mid function hook and set the address to jump back when the hooking function execution is done.\n\t//\n#ifdef _WIN64\n\tJmpBackAddr = PerformHook((ULONG_PTR)HookAddr, (ULONG_PTR)AsmstdcallStub, NumberOfBytesToHook);\n#else\n\tJmpBackAddr = PerformHook32((ULONG_PTR)HookAddr, (ULONG_PTR)AsmstdcallStub, NumberOfBytesToHook);\n#endif\n}\n\nVOID\nhk_Asmstdcall(\n\t_In_ PLIBCALL Frame\n)\n{\n\t//\n\t// Request the ownership of the critical section.\n\t//\n\tEnterCriticalSection(&CriticalSection);\n\n\t//\n\t// Get the address of the current Windows API function to be called by asmstdcall.\n\t//\n\tULONG_PTR FuncAddr = Frame->FuncAddr;\n\n\t//\n\t// Make sure we avoid the IAT entries not set by the user.\n\t//\n\tfor (SIZE_T i = 0; i < NumberOfIATEntries; i++)\n\t{\n\t\tif (FuncAddr == IatInfo[i].Addr && !IatInfo[i].IsAllowedToLog)\n\t\t{\n\t\t\tgoto Exit;\n\t\t}\n\t}\n\n\t//\n\t// Check if we are ready to start to log the API calls to the user.\n\t//\n\tif (bIsReadyToLog)\n\t{\n\t\tULONG_PTR Params = Frame->Argv;\n\t\tULONG_PTR ReturnValue = Frame->ReturnValue;\n\n\t\t//\n\t\t// Make sure we also trace API functions resolved after the Go runtime initialization.\n\t\t//\n\t\tif (FuncAddr == (ULONG_PTR)pGetProcAddress)\n\t\t{\n\t\t\t//\n\t\t\t// Get the second parameter passed to GetProcAddress() function (i.e. lpProcName).\n\t\t\t//\n\t\t\tLPCSTR FuncName = (LPCSTR)(Params + 1);\n\n\t\t\t//\n\t\t\t// Go through our target function list and check if the function address resolved by GetProcAddress \n\t\t\t// is in our list and if not, add it.\n\t\t\t//\n\t\t\tfor (SIZE_T i = 0; i < NumberOfTargetFuncs; i++)\n\t\t\t{\n\t\t\t\tif (!strncmp(TargetFuncsInfo[i].Name, FuncName, strlen(FuncName) + 1) && TargetFuncsInfo[i].Addr == NULL)\n\t\t\t\t{\n\t\t\t\t\tTargetFuncsInfo[i].Addr = (FARPROC)ReturnValue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//\n\t\t// Check if the instructions in the received address is a JMP. If that's the case probably we are in a jump table.\n\t\t// Programs compiled with cgo/gcc usually would have this table containing a JMP to the real IAT entry so we need to handle these cases.\n\t\t// \n\t\t// The JMP could be the IAT address address directly (x86) or an offset based on the current address (x64) hence we need to check our arch.\n\t\t//\n\t\tif (*(BYTE*)FuncAddr == 0xFF && *((BYTE*)FuncAddr + 1) == 0x25)\n\t\t{\n\n#ifdef _WIN64\n\t\t\tDWORD offset = *(DWORD*)(FuncAddr + 2);\n\t\t\tFARPROC RealFuncEntry = *(FARPROC)(FuncAddr + offset + 6);\n#else\n\t\t\tFARPROC RealFuncEntry = *(FARPROC)(FuncAddr + 2);\n#endif\n\t\t\tif (RealFuncEntry)\n\t\t\t{\n\t\t\t\tBOOL bFuncFound = FALSE;\n\n\t\t\t\t//\n\t\t\t\t// Check if the function address is present in the IAT to make sure we get the correct address.\n\t\t\t\t//\n\t\t\t\tif (HasImport(RealFuncEntry))\n\t\t\t\t{\n\t\t\t\t\t//\n\t\t\t\t\t// Get the name of the imported function using it's IAT address.\n\t\t\t\t\t//\n\t\t\t\t\tLPCSTR FuncName = GetImportName(RealFuncEntry);\n\n\t\t\t\t\tif (FuncName != NULL)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (SIZE_T i = 0; i < NumberOfTargetFuncs; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!strncmp(TargetFuncsInfo[i].Name, FuncName, strlen(FuncName) + 1))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tTargetFuncsInfo[i].Addr = (FARPROC)FuncAddr;\n\t\t\t\t\t\t\t\tbFuncFound = TRUE;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (SIZE_T i = 0; i < NumberOfIATEntries; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!IatInfo[i].Addr)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (bFuncFound)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tIatInfo[i].IsAllowedToLog = TRUE;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tIatInfo[i].Addr = FuncAddr;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//\n\t\t// Go through our target function list and check if the function called by Asmstdcall is wanted and if so, log it to the user.\n\t\t//\n\t\tfor (SIZE_T i = 0; i < NumberOfTargetFuncs; i++)\n\t\t{\n\t\t\tFARPROC WantedFuncAddr = TargetFuncsInfo[i].Addr;\n\n\t\t\tif (WantedFuncAddr)\n\t\t\t{\n\t\t\t\tif (FuncAddr == (ULONG_PTR)WantedFuncAddr)\n\t\t\t\t{\n\t\t\t\t\tif (!strcmp(TargetFuncsInfo[i].Name, \"GetProcAddress\"))\n\t\t\t\t\t{\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// Since this is a special case we have a function to print it.\n\t\t\t\t\t\t//\n\t\t\t\t\t\tLogGetProcAddressCall(Params, (FARPROC)ReturnValue);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tDWORD Argc = Frame->Argc;\n\t\t\t\t\t\tLogAPICall(TargetFuncsInfo[i].Name, Argc, Params, (DWORD)ReturnValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//\n\t// Check if we should start to log the API calls by checking if the function called by Asmstdcall is GetCommandLineW().\n\t// This function is part of the \"os\" package initialization and is called before the main package so we use it as a sentinel. \n\t// \n\t//\n\tif (FuncAddr == (ULONG_PTR)pGetCommandLineW && !bIsReadyToLog)\n\t{\n\t\tbIsReadyToLog = TRUE;\n\n\t\t//\n\t\t// Resolve the address of the user-defined functions to trace and fills our TargetFuncInfo global list.\n\t\t//\n\t\tResolveTargetFuncListAddresses();\n\n\t\t//\n\t\t// Attempt to create a console in case we are injected into a GUI application.\n\t\t//\n\t\tif (AllocConsole())\n\t\t{\n\t\t\tFILE* fp = NULL;\n\t\t\tfreopen_s(&fp, \"CONOUT$\", \"w\", stdout);\n\t\t\tSetConsoleTitle(TEXT(\"gftrace\"));\n\t\t}\n\n\t\t//\n\t\t// Just some new line chars to make the output cleaner.\n\t\t//\n\t\tprintf(\"\\n\\n\");\n\t}\n\nExit:\n\n\t//\n\t// Release ownership of the critical section.\n\t//\n\tLeaveCriticalSection(&CriticalSection);\n}\n"
  },
  {
    "path": "tracer/hooks.h",
    "content": "#pragma once\n\n#include <windows.h>\n\ntypedef struct LIBCALL\n{\n\tULONG_PTR FuncAddr;\n\tDWORD Argc;\n\tULONG_PTR Argv;\n\tULONG_PTR ReturnValue;\n} LIBCALL, * PLIBCALL;\n\nextern VOID AsmstdcallStub(VOID);\n\nLPVOID JmpBackAddr;\n\nLPVOID PerformHook(_In_ ULONG_PTR Src, _In_ ULONG_PTR Dest, _In_ SIZE_T Size);\nLPVOID PerformHook32(_In_ ULONG_PTR Src, _In_ ULONG_PTR Dest, _In_ SIZE_T Size);\nVOID HookAsmstdcall();\nVOID hk_Asmstdcall(_In_ PLIBCALL Frame);"
  },
  {
    "path": "tracer/pe.c",
    "content": "#include \"pe.h\"\n#include \"utils.h\"\n\nPIMAGE_NT_HEADERS64\nGetNtHeader(\n\t_In_ ULONG_PTR ModuleBase\n)\n{\n\tIMAGE_DOS_HEADER* DosHeader = (IMAGE_DOS_HEADER*)ModuleBase;\n\n\tif (DosHeader->e_magic != IMAGE_DOS_SIGNATURE)\n\t{\n\t\tPrintError(\"The target process has an invalid DOS Signare\");\n\t}\n\n\tPIMAGE_NT_HEADERS64 NtHeader = (IMAGE_NT_HEADERS64*)(ModuleBase + DosHeader->e_lfanew);\n\n\tif (NtHeader->Signature != IMAGE_NT_SIGNATURE)\n\t{\n\t\tPrintError(\"The target process has an invalid PE Signare\");\n\t}\n\n\treturn NtHeader;\n}\n\nPIMAGE_NT_HEADERS32\nGetNtHeader32(\n\t_In_ ULONG_PTR ModuleBase\n)\n{\n\tIMAGE_DOS_HEADER* DosHeader = (IMAGE_DOS_HEADER*)ModuleBase;\n\n\tif (DosHeader->e_magic != IMAGE_DOS_SIGNATURE)\n\t{\n\t\tPrintError(\"The target process has an invalid DOS Signare\");\n\t}\n\n\tPIMAGE_NT_HEADERS32 NtHeader = (IMAGE_NT_HEADERS32*)(ModuleBase + DosHeader->e_lfanew);\n\n\tif (NtHeader->Signature != IMAGE_NT_SIGNATURE)\n\t{\n\t\tPrintError(\"The target process has an invalid PE Signare\");\n\t}\n\n\treturn NtHeader;\n}\n\nPIMAGE_EXPORT_DIRECTORY\nGetExportDirectory(\n\t_In_ ULONG_PTR ModuleBase\n)\n{\n#ifdef _WIN64\n\tPIMAGE_NT_HEADERS64 NtHeader = GetNtHeader(ModuleBase);\n\tIMAGE_OPTIONAL_HEADER64 OptHeader = NtHeader->OptionalHeader;\n#else\n\tPIMAGE_NT_HEADERS32 NtHeader = GetNtHeader32(ModuleBase);\n\tIMAGE_OPTIONAL_HEADER32 OptHeader = NtHeader->OptionalHeader;\n#endif\n\n\tIMAGE_DATA_DIRECTORY ExportDataDir = OptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];\n\tDWORD ExportDirRva = ExportDataDir.VirtualAddress;\n\n\tif (!ExportDirRva)\n\t{\n\t\treturn NULL;\n\t}\n\n\treturn (PIMAGE_EXPORT_DIRECTORY)(ModuleBase + ExportDirRva);\n}\n\nPIMAGE_IMPORT_DESCRIPTOR\nGetImportDesc(\n\t_In_ ULONG_PTR ModuleBase\n)\n{\n#ifdef _WIN64\n\tPIMAGE_NT_HEADERS64 NtHeader = GetNtHeader(ModuleBase);\n\tIMAGE_OPTIONAL_HEADER64 OptHeader = NtHeader->OptionalHeader;\n#else\n\tPIMAGE_NT_HEADERS32 NtHeader = GetNtHeader32(ModuleBase);\n\tIMAGE_OPTIONAL_HEADER32 OptHeader = NtHeader->OptionalHeader;\n#endif\n\n\tIMAGE_DATA_DIRECTORY ImportDataDir = OptHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];\n\tDWORD ImportDirRva = ImportDataDir.VirtualAddress;\n\n\tif (!ImportDirRva)\n\t{\n\t\treturn NULL;\n\t}\n\n\treturn (PIMAGE_IMPORT_DESCRIPTOR)(ModuleBase + ImportDirRva);\n}\n\nPIMAGE_SECTION_HEADER\nGetSectionHeader(\n\t_In_ ULONG_PTR ModuleBase,\n\t_In_ BYTE* SectionName\n)\n{\n#ifdef _WIN64\n\tPIMAGE_NT_HEADERS64 NtHeader = GetNtHeader(ModuleBase);\n#else\n\tPIMAGE_NT_HEADERS32 NtHeader = GetNtHeader32(ModuleBase);\n#endif\n\n\tPIMAGE_SECTION_HEADER pSection = IMAGE_FIRST_SECTION(NtHeader);\n\tDWORD NumberOfSections = NtHeader->FileHeader.NumberOfSections;\n\n\tif (NumberOfSections == 0)\n\t{\n\t\tPrintError(\"The number of sections of the target process is zero\");\n\t}\n\n\tfor (SIZE_T i = 0; i < NumberOfSections; i++)\n\t{\n\t\tif (IsSameStr((BYTE*)pSection->Name, SectionName))\n\t\t{\n\t\t\treturn pSection;\n\t\t}\n\n\t\tpSection++;\n\t}\n\n\treturn NULL;\n}\n\nFARPROC\nGetExportAddr(\n\t_In_ LPCSTR ExportName\n)\n{\n#ifdef _WIN64\n\tPPEB Peb = (PPEB)__readgsqword(0x60);\n#else\n\tPPEB Peb = (PPEB)__readfsdword(0x30);\n#endif\n\n\tPLDR_DATA_TABLE_ENTRY CurrentModule = NULL;\n\tPLIST_ENTRY CurrentEntry = Peb->Ldr->InLoadOrderModuleList.Flink;\n\tFARPROC ExportAddr;\n\n\t//\n\t// Go through each loaded module and try to find the target export address using the given export name.\n\t//\n\twhile (CurrentEntry != &Peb->Ldr->InLoadOrderModuleList && CurrentEntry != NULL)\n\t{\n\t\tCurrentModule = CONTAINING_RECORD(CurrentEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);\n\t\tExportAddr = ResolveExportAddr((ULONG_PTR)CurrentModule->DllBase, ExportName);\n\n\t\tif (ExportAddr != NULL)\n\t\t{\n\t\t\treturn ExportAddr;\n\t\t}\n\n\t\tCurrentEntry = CurrentEntry->Flink;\n\t}\n\n\treturn NULL;\n}\n\nFARPROC\nResolveExportAddr(\n\t_In_ ULONG_PTR ModuleBase,\n\t_In_ LPCSTR ExportName\n)\n{\n\tPIMAGE_EXPORT_DIRECTORY ExportDir = GetExportDirectory(ModuleBase);\n\n\tif (ExportDir == NULL)\n\t{\n\t\treturn NULL;\n\t}\n\n\tDWORD AddressOfNameRva = ExportDir->AddressOfNames;\n\tDWORD NumberOfNames = ExportDir->NumberOfNames;\n\tDWORD AddressOfNameOrdinals = ExportDir->AddressOfNameOrdinals;\n\tDWORD AddressOfFunctions = ExportDir->AddressOfFunctions;\n\n\tfor (SIZE_T i = 0; i < NumberOfNames; i++)\n\t{\n\t\tDWORD NameRva = *(DWORD*)(ModuleBase + AddressOfNameRva + i * sizeof(DWORD));\n\t\tWORD OrdinalRva = *(WORD*)(ModuleBase + AddressOfNameOrdinals + i * sizeof(WORD));\n\t\tLPCSTR Name = (LPCSTR)(ModuleBase + NameRva);\n\n\t\tif (IsSameStr((BYTE*)ExportName, (BYTE*)Name))\n\t\t{\n\t\t\tDWORD ExportRva = *(DWORD*)(ModuleBase + AddressOfFunctions + OrdinalRva * sizeof(DWORD));\n\n\t\t\treturn (FARPROC)(ModuleBase + ExportRva);\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nLPCSTR\nGetImportName(\n\t_In_ FARPROC ImportAddr\n)\n{\n\tHMODULE ModuleBase = GetModuleHandle(NULL);\n\tPIMAGE_IMPORT_DESCRIPTOR ImportDesc = GetImportDesc((ULONG_PTR)ModuleBase);\n\n\tif (ImportDesc == NULL)\n\t{\n\t\treturn NULL;\n\t}\n\n\tPIMAGE_THUNK_DATA OriginalFirstThunk = (PIMAGE_THUNK_DATA)((ULONG_PTR)ModuleBase + ImportDesc->OriginalFirstThunk);\n\tPIMAGE_THUNK_DATA FirstThunk = (PIMAGE_THUNK_DATA)((ULONG_PTR)ModuleBase + ImportDesc->FirstThunk);\n\n\tSIZE_T i = 0;\n\n\twhile (ImportDesc[i++].OriginalFirstThunk)\n\t{\n\t\twhile (OriginalFirstThunk->u1.Function)\n\t\t{\n\t\t\tif (!memcmp(&FirstThunk->u1.Function, ImportAddr, sizeof(FARPROC)))\n\t\t\t{\n\t\t\t\tPIMAGE_IMPORT_BY_NAME ImportName = (PIMAGE_IMPORT_BY_NAME)((ULONG_PTR)ModuleBase + OriginalFirstThunk->u1.AddressOfData);\n\t\t\t\treturn (LPCSTR)ImportName->Name;\n\t\t\t}\n\t\t\tOriginalFirstThunk++;\n\t\t\tFirstThunk++;\n\t\t}\n\t}\n\n\treturn NULL;\n}\n\nBOOL\nHasImport(\n\t_In_ FARPROC ImportAddr\n)\n{\n\tHMODULE ModuleBase = GetModuleHandleW(NULL);\n\tPIMAGE_IMPORT_DESCRIPTOR ImportDesc = GetImportDesc((ULONG_PTR)ModuleBase);\n\n\tif (ImportDesc == NULL)\n\t{\n\t\treturn FALSE;\n\t}\n\n\tPIMAGE_THUNK_DATA FirstThunk = (PIMAGE_THUNK_DATA)((ULONG_PTR)ModuleBase + ImportDesc->FirstThunk);\n\n\tSIZE_T i = 0;\n\n\twhile (ImportDesc[i++].FirstThunk)\n\t{\n\t\twhile (FirstThunk->u1.Function)\n\t\t{\n\t\t\tif (!memcmp(&FirstThunk->u1.Function, ImportAddr, sizeof(FARPROC)))\n\t\t\t{\n\t\t\t\treturn TRUE;\n\t\t\t}\n\t\t\tFirstThunk++;\n\t\t}\n\t}\n\n\treturn FALSE;\n}"
  },
  {
    "path": "tracer/pe.h",
    "content": "#pragma once\n\n#include <windows.h>\n\n//\n// Since we only need some fields of these structs there's no need to define all of them.\n//\ntypedef struct _LDR_DATA_TABLE_ENTRY\n{\n    LIST_ENTRY InLoadOrderLinks;\n    LIST_ENTRY InMemoryOrderLinks;\n    union\n    {\n        LIST_ENTRY InInitializationOrderLinks;\n        LIST_ENTRY InProgressLinks;\n    };\n    PVOID DllBase;\n}LDR_DATA_TABLE_ENTRY, * PLDR_DATA_TABLE_ENTRY;\n\ntypedef struct _PEB_LDR_DATA\n{\n    ULONG Length;\n    BOOLEAN Initialized;\n    HANDLE SsHandle;\n    LIST_ENTRY InLoadOrderModuleList;\n    LIST_ENTRY InMemoryOrderModuleList;\n    LIST_ENTRY InInitializationOrderModuleList;\n} PEB_LDR_DATA, * PPEB_LDR_DATA;\n\ntypedef struct _PEB\n{\n    BOOLEAN InheritedAddressSpace;\n    BOOLEAN ReadImageFileExecOptions;\n    BOOLEAN BeingDebugged;\n    union\n    {\n        BOOLEAN BitField;\n        struct\n        {\n            BOOLEAN ImageUsesLargePages : 1;\n            BOOLEAN IsProtectedProcess : 1;\n            BOOLEAN IsImageDynamicallyRelocated : 1;\n            BOOLEAN SkipPatchingUser32Forwarders : 1;\n            BOOLEAN IsPackagedProcess : 1;\n            BOOLEAN IsAppContainer : 1;\n            BOOLEAN IsProtectedProcessLight : 1;\n            BOOLEAN IsLongPathAwareProcess : 1;\n        } s1;\n    } u1;\n\n    HANDLE Mutant;\n\n    PVOID ImageBaseAddress;\n    PPEB_LDR_DATA Ldr;\n} PEB, * PPEB;\n\nPIMAGE_NT_HEADERS64 GetNtHeader(_In_ ULONG_PTR ModuleBase);\nPIMAGE_NT_HEADERS32 GetNtHeader32(_In_ ULONG_PTR ModuleBase);\nPIMAGE_SECTION_HEADER GetSectionHeader(_In_ ULONG_PTR ModuleBase, _In_ BYTE* SectionName);\nPIMAGE_EXPORT_DIRECTORY GetExportDirectory(_In_ ULONG_PTR ModuleBase);\nFARPROC GetExportAddr(_In_ LPCSTR ExportName);\nFARPROC ResolveExportAddr(_In_ ULONG_PTR ModuleBase, _In_ LPCSTR ExportName);\nPIMAGE_IMPORT_DESCRIPTOR GetImportDesc(_In_ ULONG_PTR ModuleBase);\nBOOL HasImport(_In_ FARPROC ImportAddr);\nLPCSTR GetImportName(_In_ FARPROC ImportAddr);"
  },
  {
    "path": "tracer/stub.asm",
    "content": "EXTERN JmpBackAddr: QWORD\nEXTERN hk_Asmstdcall: PROC\n\n.code\nAsmstdcallStub PROC PUBLIC\n\n    ; Execute the patched Asmstdcall instructions.\n    mov rdi, qword ptr gs:[30h]\n    mov eax, dword ptr [rdi+68h]\n    mov qword ptr [rcx+28h], rax\n\n    ; Save RCX value.\n    push rcx\n\n    ; Call the Asmstdcall hook.\n    call hk_Asmstdcall\n\n    ; Restore RCX value.\n    pop rcx\n\n    ; Jump back to the original Asmstdcall function after the hooking point.\n    jmp [JmpBackAddr]\n\nAsmstdcallStub ENDP\n\nEND"
  },
  {
    "path": "tracer/stub32.asm",
    "content": ".MODEL flat, C\n\nEXTERN JmpBackAddr: DWORD\nEXTERN hk_Asmstdcall: PROC\n\nASSUME FS:NOTHING\n\n.code\nAsmstdcallStub PROC PUBLIC\n\n    ; Execute the patched Asmstdcall instructions.\n    mov eax, dword ptr fs:[34h]\n\n    ; Save EAX and EBX values.\n    push eax\n    push ebx\n\n    ; Call the Asmstdcall hook.\n    call hk_Asmstdcall\n\n    ; Restore EBX and EAX values.\n    pop ebx\n    pop eax\n\n    ; Jump back to the original Asmstdcall function after the hooking point.\n    jmp [JmpBackAddr]\n\nAsmstdcallStub ENDP\n\nEND"
  },
  {
    "path": "tracer/tracer.vcxproj",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug|Win32\">\n      <Configuration>Debug</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|Win32\">\n      <Configuration>Release</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Debug|x64\">\n      <Configuration>Debug</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|x64\">\n      <Configuration>Release</Configuration>\n      <Platform>x64</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"dllmain.c\" />\n    <ClCompile Include=\"hooks.c\" />\n    <ClCompile Include=\"pe.c\" />\n    <ClCompile Include=\"utils.c\" />\n  </ItemGroup>\n  <ItemGroup>\n    <MASM Include=\"stub.asm\">\n      <FileType>Document</FileType>\n      <ExcludedFromBuild Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">true</ExcludedFromBuild>\n    </MASM>\n    <MASM Include=\"stub32.asm\">\n      <ExcludedFromBuild Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">true</ExcludedFromBuild>\n    </MASM>\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"hooks.h\" />\n    <ClInclude Include=\"pe.h\" />\n    <ClInclude Include=\"utils.h\" />\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <VCProjectVersion>16.0</VCProjectVersion>\n    <Keyword>Win32Proj</Keyword>\n    <ProjectGuid>{bdd5a131-45ee-4b2c-a6ec-f0b08a4e8982}</ProjectGuid>\n    <RootNamespace>tracer</RootNamespace>\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>true</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseDebugLibraries>false</UseDebugLibraries>\n    <PlatformToolset>v143</PlatformToolset>\n    <WholeProgramOptimization>true</WholeProgramOptimization>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n    <Import Project=\"$(VCTargetsPath)\\BuildCustomizations\\masm.props\" />\n  </ImportGroup>\n  <ImportGroup Label=\"Shared\">\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <LinkIncremental>true</LinkIncremental>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <LinkIncremental>false</LinkIncremental>\n    <TargetName>gftrace32</TargetName>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <LinkIncremental>true</LinkIncremental>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <LinkIncremental>false</LinkIncremental>\n    <TargetName>gftrace</TargetName>\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;_DEBUG;TRACER_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n      <PrecompiledHeader>Use</PrecompiledHeader>\n      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableUAC>false</EnableUAC>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>WIN32;NDEBUG;TRACER_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n      <PrecompiledHeader>NotUsing</PrecompiledHeader>\n      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>\n      <Optimization>Disabled</Optimization>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>false</GenerateDebugInformation>\n      <EnableUAC>false</EnableUAC>\n      <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>\n    </Link>\n    <PostBuildEvent>\n      <Command>copy $(ProjectDir)\\gftrace.cfg $(TargetDir)</Command>\n    </PostBuildEvent>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>_DEBUG;TRACER_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n      <PrecompiledHeader>Use</PrecompiledHeader>\n      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <EnableUAC>false</EnableUAC>\n    </Link>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\n    <ClCompile>\n      <WarningLevel>Level3</WarningLevel>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <IntrinsicFunctions>true</IntrinsicFunctions>\n      <SDLCheck>true</SDLCheck>\n      <PreprocessorDefinitions>NDEBUG;TRACER_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <ConformanceMode>true</ConformanceMode>\n      <PrecompiledHeader>NotUsing</PrecompiledHeader>\n      <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>\n      <Optimization>Disabled</Optimization>\n    </ClCompile>\n    <Link>\n      <SubSystem>Windows</SubSystem>\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\n      <OptimizeReferences>true</OptimizeReferences>\n      <GenerateDebugInformation>false</GenerateDebugInformation>\n      <EnableUAC>false</EnableUAC>\n    </Link>\n    <PostBuildEvent>\n      <Command>copy $(ProjectDir)\\gftrace.cfg $(TargetDir)</Command>\n    </PostBuildEvent>\n  </ItemDefinitionGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n    <Import Project=\"$(VCTargetsPath)\\BuildCustomizations\\masm.targets\" />\n  </ImportGroup>\n</Project>"
  },
  {
    "path": "tracer/tracer.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup>\n    <Filter Include=\"Source Files\">\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\n      <Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\n    </Filter>\n    <Filter Include=\"Header Files\">\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\n      <Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>\n    </Filter>\n    <Filter Include=\"Resource Files\">\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>\n    </Filter>\n  </ItemGroup>\n  <ItemGroup>\n    <ClCompile Include=\"dllmain.c\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"hooks.c\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"pe.c\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n    <ClCompile Include=\"utils.c\">\n      <Filter>Source Files</Filter>\n    </ClCompile>\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"hooks.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"pe.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n    <ClInclude Include=\"utils.h\">\n      <Filter>Header Files</Filter>\n    </ClInclude>\n  </ItemGroup>\n  <ItemGroup>\n    <MASM Include=\"stub.asm\">\n      <Filter>Source Files</Filter>\n    </MASM>\n    <MASM Include=\"stub32.asm\">\n      <Filter>Source Files</Filter>\n    </MASM>\n  </ItemGroup>\n</Project>"
  },
  {
    "path": "tracer/utils.c",
    "content": "#include \"utils.h\"\n#include \"pe.h\"\n\nVOID\nPrintError(\n\t_In_ LPCSTR Msg\n)\n{\n\tprintf(\"\\n[!] Error: %s!\\n\", Msg);\n\tExitProcess(0);\n}\n\nVOID\nPrintWinError(\n\t_In_ LPCSTR Msg,\n\t_In_ DWORD ErrorCode\n)\n{\n\tprintf(\"\\n[!] Error: %s!\\n[!] Error code: %u\\n\", Msg, ErrorCode);\n\tExitProcess(0);\n}\n\nULONG_PTR\nFindPattern(\n\t_In_ ULONG_PTR BaseAddr,\n\t_In_ SIZE_T Size,\n\t_In_ LPCSTR BytePattern,\n\t_In_ LPCSTR Mask\n)\n{\n\tSIZE_T PatternSize = strlen(Mask);\n\tBOOL bFound;\n\n\tfor (SIZE_T i = 0; i < Size - PatternSize; i++)\n\t{\n\t\tbFound = TRUE;\n\n\t\tfor (SIZE_T j = 0; j < PatternSize; j++)\n\t\t{\n\t\t\tbFound &= Mask[j] == '?' || BytePattern[j] == *((LPCSTR)BaseAddr + i + j);\n\t\t}\n\n\t\tif (bFound)\n\t\t{\n\t\t\treturn (ULONG_PTR)(BaseAddr + i);\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nVOID\nLogAPICall(\n\t_In_ LPCSTR FuncName,\n\t_In_ DWORD Argc,\n\t_In_ ULONG_PTR Params,\n\t_In_ DWORD ReturnValue\n)\n{\n\tchar* TempBuffer = calloc(MAX_STR_SIZE, 1);\n\tchar FinalString[MAX_STR_SIZE] = {0};\n\tSIZE_T Size = MAX_STR_SIZE;\n\n\tsnprintf(TempBuffer, Size, \"- %s(\", FuncName);\n\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\n\t//\n\t// Build the log entry string using the provided info (i.e. FuncName, Argc, Params, ReturnValue).\n\t//\n\tfor (SIZE_T i = 0; i < Argc; i++)\n\t{\n\t\tULONG_PTR Argv = *((ULONG_PTR*)Params + i);\n\n\t\t//\n\t\t// Try to guess if the argument is a string, an address or simply a number and print it properly.\n\t\t//\n\t\tif (IsWideStr((BYTE*)Argv))\n\t\t{\n\t\t\tLPCWSTR StrArg = (LPCWSTR)Argv;\n\t\t\tif (wcslen((LPCWSTR)Argv) > 2048)\n\t\t\t{\n\t\t\t\tStrArg = L\"[string is too large]\";\n\t\t\t}\n\n\t\t\tsnprintf(TempBuffer, Size, \"\\\"%ws\\\"\", StrArg);\n\t\t\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsnprintf(TempBuffer, Size, \"0x%llx\", Argv);\n\t\t\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\t\t}\n\n\t\tif (Argc > i + 1)\n\t\t{\n\t\t\tsnprintf(TempBuffer, Size, \", \");\n\t\t\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\t\t}\n\t}\n\n\tsnprintf(TempBuffer, Size, \") = 0x%lx (%d)\", ReturnValue, (INT)ReturnValue);\n\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\n\t//\n\t// Print the final log entry string.\n\t//\n\tputs(FinalString);\n\n\tfree(TempBuffer);\n}\n\nVOID\nLogGetProcAddressCall(\n\t_In_ ULONG_PTR Params,\n\t_In_ FARPROC ReturnValue\n)\n{\n\tchar* TempBuffer = calloc(MAX_STR_SIZE, 1);\n\tchar FinalString[MAX_STR_SIZE] = {0};\n\tSIZE_T Size = MAX_STR_SIZE;\n\n\tsnprintf(TempBuffer, Size, \"- GetProcAddress(\");\n\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\n\tHMODULE ModuleBase = (HMODULE) * ((ULONG_PTR*)Params + 0);\n\n\tsnprintf(TempBuffer, Size, \"0x%llx, \", ModuleBase);\n\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\n\tLPCSTR ExportName = (LPCSTR) * ((ULONG_PTR*)Params + 1);\n\n\tsnprintf(TempBuffer, Size, \"\\\"%s\\\"\", ExportName);\n\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\tsnprintf(TempBuffer, Size, \") = 0x%llx\", ReturnValue);\n\tstrncat_s(FinalString, Size, TempBuffer, _TRUNCATE);\n\n\t//\n\t// Print the final log entry string.\n\t//\n\tputs(FinalString);\n\n\tfree(TempBuffer);\n}\n\n/*\n* Since we are not using API signatures to know what is the type of each parameter we need to try to guess what it is.\n* That's not good in general and handle these scenarios can be a pain. The implementation bellow is very bad but at\n* least it works \"ok\" guessing if the provided address is a wide string or not.\n*\n* TODO: improve the function bellow.\n*/\nBOOL\nIsWideStr(\n\t_In_ BYTE* Addr\n)\n{\n\tif (!IsValidStrMem((LPCVOID)Addr))\n\t{\n\t\treturn FALSE;\n\t}\n\n\tWORD RequiredLen = 6;\n\n\tfor (SIZE_T i = 0; i < RequiredLen; i += 2)\n\t{\n\t\tif (Addr[i] > 0x7e || Addr[i] < 0x20 || Addr[i + 1] != '\\0')\n\t\t{\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\treturn TRUE;\n}\n\nBOOL\nIsValidStrMem(\n\t_In_ LPCVOID Addr\n)\n{\n\tif (!Addr)\n\t{\n\t\treturn FALSE;\n\t}\n\n\tHANDLE hProcess = GetCurrentProcess();\n\tMEMORY_BASIC_INFORMATION Mbi = {0};\n\n\tif (!VirtualQueryEx(hProcess, Addr, &Mbi, sizeof(Mbi)) && GetLastError() != ERROR_INVALID_PARAMETER)\n\t{\n\t\tPrintWinError(\"Failed to query virtual memory\", GetLastError());\n\t}\n\n\treturn Mbi.Protect == PAGE_READWRITE;\n}\n\nBOOL\nIsSameStr(\n\t_In_ BYTE* Str1,\n\t_In_ BYTE* Str2\n)\n{\n\tif (!Str1 || !Str2)\n\t{\n\t\treturn FALSE;\n\t}\n\n\tSIZE_T StrLen1 = strlen(Str1);\n\tSIZE_T StrLen2 = strlen(Str2);\n\n\tif (StrLen1 != StrLen2)\n\t{\n\t\treturn FALSE;\n\t}\n\n\tfor (SIZE_T i = 0; i < StrLen1; i++)\n\t{\n\t\tchar c1 = Str1[i];\n\t\tchar c2 = Str2[i];\n\n\t\tc1 = tolower(c1);\n\t\tc2 = tolower(c2);\n\n\t\tif (c1 != c2)\n\t\t{\n\t\t\treturn FALSE;\n\t\t}\n\t}\n\n\treturn TRUE;\n}\n\nVOID\nInitTargetFuncList()\n{\n\tchar ConfigFileFullPath[MAX_PATH] = {0};\n\tchar CurrentModuleFilepath[MAX_PATH] = {0};\n\n#ifdef _WIN64\n\tLPCSTR ModuleName = \"gftrace.dll\";\n#else\n\tLPCSTR ModuleName = \"gftrace32.dll\";\n#endif\n\n\tDWORD Len = GetModuleFileNameA(GetModuleHandleA(ModuleName), CurrentModuleFilepath, MAX_PATH);\n\n\tif (!Len)\n\t{\n\t\tPrintWinError(\"Failed to get the gftrace.dll module filepath\", GetLastError());\n\t}\n\n\tfor (SIZE_T i = Len - 1; i > 0; i--)\n\t{\n\t\tif (CurrentModuleFilepath[i] == 0x5c || CurrentModuleFilepath[i] == 0x2f)\n\t\t{\n\t\t\tCurrentModuleFilepath[i + 1] = '\\0';\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tSIZE_T i = 0;\n\n\tdo\n\t{\n\t\tConfigFileFullPath[i] = CurrentModuleFilepath[i];\n\t\ti++;\n\t} while (CurrentModuleFilepath[i] != '\\0');\n\n\tLPCSTR ConfigFilename = \"\\\\gftrace.cfg\";\n\n\tSIZE_T ConfigFullPathSize = strlen(ConfigFileFullPath) + strlen(ConfigFilename) + 1;\n\n\t//\n\t// Build the gftrace.cfg full path.\n\t//\n\tstrncat_s(ConfigFileFullPath, ConfigFullPathSize, ConfigFilename, _TRUNCATE);\n\n\t//\n\t// Check if the gftrace.cfg file exists in the expected directory.\n\t//\n\tif (GetFileAttributesA((LPCSTR)ConfigFileFullPath) == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND)\n\t{\n\t\tPrintError(\"Failed to find the gftrace.cfg file in the current directory\");\n\t}\n\n\tHANDLE hFile = CreateFileA(ConfigFileFullPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\n\tif (hFile == INVALID_HANDLE_VALUE)\n\t{\n\t\tPrintWinError(\"Failed to open the config file\", GetLastError());\n\t}\n\n\tDWORD FileSizeHigh = 0;\n\n\tDWORD FileSize = GetFileSize(hFile, &FileSizeHigh);\n\n\tif (FileSize == INVALID_FILE_SIZE)\n\t{\n\t\tCloseHandle(hFile);\n\t\tPrintWinError(\"Failed to get config file size\", GetLastError());\n\t}\n\n\tBYTE* FileContent = calloc(FileSize, 1);\n\n\tDWORD NumberOfBytesRead;\n\n\tif (!ReadFile(hFile, (LPVOID)FileContent, FileSize, &NumberOfBytesRead, NULL))\n\t{\n\t\tCloseHandle(hFile);\n\t\tPrintWinError(\"Failed to read the config file content\", GetLastError());\n\t}\n\n\tNumberOfTargetFuncs = 0;\n\n\t//\n\t// Calculate the provided user list length.\n\t// \n\t// TODO: improve the code bellow.\n\t//\n\tfor (SIZE_T i = 0; i <= FileSize; i++)\n\t{\n\t\tif (FileContent[i] == ',' || i == FileSize)\n\t\t{\n\t\t\tNumberOfTargetFuncs++;\n\t\t}\n\t}\n\n\tSIZE_T ListSize = NumberOfTargetFuncs * sizeof(FUNCINFO);\n\n\tHANDLE hHeap = GetProcessHeap();\n\n\tif (hHeap == NULL)\n\t{\n\t\tCloseHandle(hFile);\n\t\tPrintWinError(\"Failed to get process heap\", GetLastError());\n\t}\n\n\t//\n\t// Allocate memory for our global target function list.\n\t//\n\tTargetFuncsInfo = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, ListSize);\n\n\tif (TargetFuncsInfo == NULL)\n\t{\n\t\tCloseHandle(hFile);\n\t\tPrintWinError(\"Failed to allocate memory for the target function list\", GetLastError());\n\t}\n\n\tLPCSTR TmpFuncName;\n\tSIZE_T j = 0;\n\n\t//\n\t// Go through the user-defined list and set each function name into our global function list.\n\t// \n\t// TODO: improve the code bellow.\n\t//\n\tfor (SIZE_T i = 0, x = 0; i <= FileSize; i++)\n\t{\n\t\tif (FileContent[i] == ',')\n\t\t{\n\t\t\tFileContent[i] = '\\0';\n\t\t\tTmpFuncName = _strdup((LPCSTR)&FileContent[j]);\n\n\t\t\tif (TmpFuncName == NULL)\n\t\t\t{\n\t\t\t\tCloseHandle(hFile);\n\t\t\t\tPrintError(\"Failed to strdup API function name\");\n\t\t\t}\n\n\t\t\tTargetFuncsInfo[x].Name = TmpFuncName;\n\n\t\t\tx++;\n\t\t\tj = i + 1;\n\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (i == FileSize)\n\t\t{\n\t\t\tFileContent[i] = '\\0';\n\t\t\tTmpFuncName = _strdup((LPCSTR)&FileContent[j]);\n\n\t\t\tif (TmpFuncName == NULL)\n\t\t\t{\n\t\t\t\tCloseHandle(hFile);\n\t\t\t\tPrintError(\"Failed to strdup the API function name\");\n\t\t\t}\n\n\t\t\tTargetFuncsInfo[x].Name = TmpFuncName;\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tCloseHandle(hFile);\n}\n\nVOID\nResolveTargetFuncListAddresses()\n{\n\t//\n\t// Go through each function name in our global list, resolve it's export address and add it to the list.\n\t//\n\tfor (SIZE_T i = 0; i < NumberOfTargetFuncs; i++)\n\t{\n\t\tFARPROC ExportAddr = GetExportAddr(TargetFuncsInfo[i].Name);\n\t\tTargetFuncsInfo[i].Addr = ExportAddr;\n\t}\n}\n\nVOID\nInitIATDenyList()\n{\n\tHMODULE ModuleBase = GetModuleHandleW(NULL);\n\tPIMAGE_IMPORT_DESCRIPTOR ImportDesc = GetImportDesc((ULONG_PTR)ModuleBase);\n\n\tif (ImportDesc == NULL)\n\t{\n\t\tPrintError(\"Import Descriptor is NULL\");\n\t}\n\n\tPIMAGE_THUNK_DATA FirstThunk = (PIMAGE_THUNK_DATA)((ULONG_PTR)ModuleBase + ImportDesc->FirstThunk);\n\n\tif (!FirstThunk)\n\t{\n\t\tPrintError(\"First Thunk is 0\");\n\t}\n\n\tNumberOfIATEntries = 0;\n\tSIZE_T i = 0;\n\n\twhile (ImportDesc[i++].FirstThunk)\n\t{\n\t\twhile (FirstThunk->u1.Function)\n\t\t{\n\t\t\tNumberOfIATEntries++;\n\t\t\tFirstThunk++;\n\t\t}\n\t}\n\n\tHANDLE hHeap = GetProcessHeap();\n\n\tif (hHeap == NULL)\n\t{\n\t\tPrintWinError(\"Failed to get process heap\", GetLastError());\n\t}\n\n\tSIZE_T ListSize = NumberOfIATEntries * sizeof(IATINFO);\n\n\tIatInfo = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, ListSize);\n\n\tif (IatInfo == NULL)\n\t{\n\t\tPrintWinError(\"Failed to allocate memory for the deny function list\", GetLastError());\n\t}\n\n\tfor (SIZE_T i = 0; i < NumberOfIATEntries; i++)\n\t{\n\t\tIatInfo[i].Addr = 0;\n\t\tIatInfo[i].IsAllowedToLog = FALSE;\n\t}\n}"
  },
  {
    "path": "tracer/utils.h",
    "content": "#pragma once\n\n#include <windows.h>\n#include <stdio.h>\n#include <string.h>\n\n#define MAX_STR_SIZE 8192\n\ntypedef struct FUNCINFO\n{\n\tLPCSTR Name;\n\tFARPROC Addr;\n} FUNCINFO;\n\nstruct FUNCINFO* TargetFuncsInfo;\n\ntypedef struct IATINFO\n{\n\tULONG_PTR Addr;\n\tBOOL IsAllowedToLog;\n} IATINFO;\n\nstruct IATINFO* IatInfo;\n\nCRITICAL_SECTION CriticalSection;\nDWORD NumberOfTargetFuncs;\nDWORD NumberOfIATEntries;\nFARPROC pGetCommandLineW;\nFARPROC pGetProcAddress;\nBOOL bIsReadyToLog;\n\nVOID PrintError(_In_ LPCSTR Msg);\nVOID PrintWinError(_In_ LPCSTR Msg, _In_ DWORD ErrorCode);\n\nULONG_PTR FindPattern(_In_ ULONG_PTR BaseAddr, _In_ SIZE_T Size, _In_ LPCSTR BytePattern, _In_ LPCSTR Mask);\n\nVOID LogAPICall(_In_ LPCSTR FuncName, _In_ DWORD Argc, _In_ ULONG_PTR Params, _In_ DWORD ReturnValue);\nVOID LogGetProcAddressCall(_In_ ULONG_PTR Params, _In_ FARPROC ReturnValue);\n\nBOOL IsWideStr(_In_ BYTE* Addr);\nBOOL IsSameStr(_In_ BYTE* TargetName, _In_ BYTE* Str);\nBOOL IsValidStrMem(_In_ LPCVOID Addr);\n\nVOID InitTargetFuncList();\nVOID ResolveTargetFuncListAddresses();\nVOID InitIATDenyList();"
  }
]