[
  {
    "path": ".gitmodules",
    "content": "[submodule \"ext/libfuse\"]\n\tpath = ext/libfuse\n\turl = https://github.com/billziss-gh/libfuse.git\n[submodule \"ext/winfsp\"]\n\tpath = ext/winfsp\n\turl = https://github.com/billziss-gh/winfsp.git\n[submodule \"ext/lxdk\"]\n\tpath = ext/lxdk\n\turl = https://github.com/billziss-gh/lxdk.git\n"
  },
  {
    "path": "Contributors.asciidoc",
    "content": "CONTRIBUTORS\n============\n\nThis document contains a list of all contributors to this project. Contributors that submit changes to this project MUST also change this document to identify themselves by adding their name and email address to the CONTRIBUTOR LIST. The CONTRIBUTOR LIST is maintained in alphabetical order.\n\nA contributor who adds themselves to this list indicates their acceptance of the terms of the CONTRIBUTOR AGREEMENT below. There are NO EXCEPTIONS to this rule. If you do not wish to accept the CONTRIBUTOR AGREEMENT, please do not submit any changes.\n\nThis CONTRIBUTOR AGREEMENT is based on the Oracle Contributor Agreement and is used under the Creative Commons Attribution-Share Alike 3.0 Unported License. The original agreement and an FAQ can be found at this location: http://www.oracle.com/technetwork/community/oca-486395.html\n\nThis document uses the asciidoc format: http://asciidoc.org.\n\n\nCONTRIBUTOR AGREEMENT\n---------------------\n\nThis CONTRIBUTOR AGREEMENT applies to any contribution that you make to the WinFuse project (the \"project\"), and sets out the intellectual property rights you grant to us in the contributed materials. The term “us” shall mean the original author of this project: Bill Zissimopoulos <billziss at navimatics.com>. The term “you” shall mean the persons or entities identified below. If you agree to be bound by these terms, add your name and email address to the CONTRIBUTOR LIST below; this action will constitute signing this CONTRIBUTOR AGREEMENT. These terms and conditions constitute a binding legal agreement.\n\n1. The term 'contribution' or ‘contributed materials’ means any source code, object code, patch, tool, sample, graphic, specification, manual, documentation, or any other material posted or submitted by you to the project.\n\n2. With respect to any worldwide copyrights, or copyright applications and registrations, in your contribution:\n* you hereby assign to us joint ownership, and to the extent that such assignment is or becomes invalid, ineffective or unenforceable, you hereby grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, royalty-free, unrestricted license to exercise all rights under those copyrights. This includes, at our option, the right to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements;\n* you agree that each of us can do all things in relation to your contribution as if each of us were the sole owners, and if one of us makes a derivative work of your contribution, the one who makes the derivative work (or has it made) will be the sole owner of that derivative work;\n* you agree that you will not assert any moral rights in your contribution against us, our licensees or transferees;\n* you agree that we may register a copyright in your contribution and exercise all ownership rights associated with it; and\n* you agree that neither of us has any duty to consult with, obtain the consent of, pay or render an accounting to the other for any use or distribution of your contribution.\n\n3. With respect to any patents you own, or that you can license without payment to any third party, you hereby grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, royalty-free license to:\n* make, have made, use, sell, offer to sell, import, and otherwise transfer your contribution in whole or in part, alone or in combination with or included in any product, work or materials arising out of the project to which your contribution was submitted, and\n* at our option, to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements.\n\n4. Except as set out above, you keep all right, title, and interest in your contribution. The rights that you grant to us under these terms are effective on the date you first submitted a contribution to us, even if your submission took place before the date you sign these terms. Any contribution we make available under any license will also be made available under a suitable FSF (Free Software Foundation) or OSI (Open Source Initiative) approved license.\n\n5. You covenant, represent, warrant and agree that:\n* each contribution that you submit is and shall be an original work of authorship and you can legally grant the rights set out in this CONTRIBUTOR AGREEMENT;\n* to the best of your knowledge, each contribution will not violate any third party's copyrights, trademarks, patents, or other intellectual property rights; and\n* each contribution shall be in compliance with U.S. export control laws and other applicable export and import laws.\n* You agree to notify us if you become aware of any circumstance which would make any of the foregoing representations inaccurate in any respect.\n\n6. This CONTRIBUTOR AGREEMENT is governed by the laws of the State of Washington and applicable U.S. Federal law. Any choice of law rules will not apply.\n\n7. Please add your name and email address in the CONTRIBUTOR LIST below:\n* Either \"I am signing on behalf of myself as an individual and no other person or entity, including my employer, has or will have rights with respect my contributions\". In this case add your name using the following format:\n+\n----\n|First Last                             |name at example.com\n----\n* Or \"I am signing on behalf of my employer or a legal entity and I have the actual authority to contractually bind that entity\". In this case add your name using the following format:\n+\n----\n|First Last (Company and/or URL)        |name at example.com\n----\n\n\nCONTRIBUTOR LIST\n----------------\n|===\n|Bill Zissimopoulos                                             |billziss at navimatics.com\n|===\n"
  },
  {
    "path": "License.txt",
    "content": "The WinFuse project is Copyright (C) Bill Zissimopoulos. It is licensed\nunder the terms of the AGPLv3.\n\nAs a special exception to AGPLv3, Bill Zissimopoulos grants additional\npermissions to Free/Libre and Open Source Software (\"FLOSS\") without requiring\nthat such software is covered by the AGPLv3.\n\n    1. Permission to use the WinFuse DeviceIoControl interface, which allows\n    programs running on native Windows to interact with WinFuse using the FUSE\n    protocol.\n\n    2. Permission to use the WinFuse /dev/fuse interface, which allows\n    programs running on the Windows Subsystem for Linux to interact with\n    WinFuse using the FUSE protocol.\n\n    These permissions (and no other) are granted provided that the software:\n\n    1. Is distributed under a license that satisfies the Free Software\n    Definition Version 1.141 (https://www.gnu.org/philosophy/free-sw.en.html)\n    or the Open Source Definition Version 1.9 (https://opensource.org/osd).\n\n    2. Includes the copyright notice \"WinFuse - FUSE for Windows,\n    Copyright (C) Bill Zissimopoulos\" and a link to the WinFuse repository in\n    its user-interface and any user-facing documentation.\n\n    3. Is not linked or distributed with proprietary (non-FLOSS) software.\n    [You cannot mix FLOSS and proprietary software while using WinFuse under\n    this special exception.]\n\nCommercial licensing options are also available: Please contact\nBill Zissimopoulos <billziss at navimatics.com>.\n\nThe full text of the AGPLv3 license follows below.\n\n-----------------------------------------------------------------------\n\n                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 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 Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\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,\nour General Public Licenses are 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.\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  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\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 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 work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\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 AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\">\n    WinFuse &middot; FUSE for the Windows kernel\n</h1>\n\n<p align=\"center\">\n    <b>Download</b><br>\n    <a href=\"https://github.com/billziss-gh/winfuse/releases\">\n        <img src=\"https://img.shields.io/github/release/billziss-gh/winfuse/all.svg?label=latest&colorB=e52e4b&style=for-the-badge\"/>\n    </a>\n    <br/>\n    <br/>\n    <a href=\"https://ci.appveyor.com/project/billziss-gh/winfuse\">\n        <img src=\"https://img.shields.io/appveyor/ci/billziss-gh/winfuse.svg\"/>\n    </a>\n</p>\n\n<p align=\"center\">\n    WinFuse is a suite of software components that allows FUSE file systems to run on Windows. Both Windows and Linux (WSL1) FUSE file systems are supported. Windows FUSE file systems are supported via a kernel driver that exposes the FUSE protocol via <code>DeviceIoControl</code> and a port of the libfuse library compiled as a Windows DLL. Linux FUSE file systems are expected to run in the WSL1 environment and are supported via a kernel driver that exposes <code>/dev/fuse</code>.\n    <br/>\n    <br/>\n    <img src=\"doc/wslcap.gif\"/>\n</p>\n\n## ARCHITECTURE\n\n### Structural Diagram\n\nThe following component diagram shows the WinFuse project components and their relations to the Windows OS (NTOS), WSL (LXCORE) and components that are provided by other projects.\n\n![Component Diagram](doc/component.svg)\n\nThe components and their interfaces are:\n\n- The **winfsp** component which is provided by the [WinFsp](https://github.com/billziss-gh/winfsp) project.\n    - The component is an NTOS File System Driver (FSD).\n    - The component provides an **FSP_FSCTL_TRANSACT** `DeviceIoControl` interface.\n    - The component is responsible for loading the **winfuse** component.\n- The **winfuse** component which is provided by the WinFuse project (this project).\n    - The component is an NTOS driver.\n    - The component provides an **FUSE_FSCTL_TRANSACT** `DeviceIoControl` interface.\n    - The component connects to the **FSP_FSCTL_TRANSACT** interface. WinFsp file system requests retrieved via this interface are translated to FUSE file system requests and become available via **FUSE_FSCTL_TRANSACT**.\n- The **wslfuse** component which is provided by the WinFuse project (this project).\n    - The component is an LXCORE driver.\n    - The component provides a **/dev/fuse** Linux interface.\n    - The component connects to the **FSP_FSCTL_TRANSACT** interface. WinFsp file system requests retrieved via this interface are translated to FUSE file system requests and become available via **/dev/fuse**.\n- The **lxldr** component which is provided by the [LxDK](https://github.com/billziss-gh/lxdk) project.\n    - The component is an LXCORE driver.\n    - The component is responsible for loading the **wslfuse** component.\n- The file system (**FS**) components which are user-mode programs provided by third parties.\n    - A Windows WinFsp file system connects to the **FSP_FSCTL_TRANSACT** interface.\n    - A Windows FUSE file system connects to the **FUSE_FSCTL_TRANSACT** interface.\n    - A Linux FUSE file system connects to the **/dev/fuse** interface.\n\n### Behavioral Diagrams\n\nThe following sequence diagrams show how the WinFuse project components interact with other components in two scenarios: (1) I/O handled by a Windows FUSE file system, and (2) I/O handled by a Linux FUSE file system.\n\n#### I/O handled by a Windows FUSE file system:\n\n![Windows FS Sequence Diagram](doc/winseq.svg)\n\n- The I/O originates with one of:\n    - A Windows process which uses a familiar API like `ReadFile` or `WriteFile`.\n    - A WSL (Linux) process which uses an API like `read(2)` or `write(2)` that LXCORE translates into the equivalent `NtReadFile` or `NtWriteFile`.\n- The Windows OS (NTOS) packages this I/O into an IRP (I/O Request Packet) and routes it to the **winfsp** FSD.\n- The **winfsp** FSD posts the request into an internal I/O queue. This request is retrieved at a later time and in a different process context via an `FSP_FSCTL_TRANSACT` (issued via `DeviceIoControl`) by the **winfuse** driver.\n- The **winfuse** driver translates the request to equivalent FUSE requests, which are then retrieved via an `FUSE_FSCTL_TRANSACT` (issued via `DeviceIoControl`) by the Windows FUSE file system.\n- The Windows FUSE file system processes the request and prepares a response, which it sends to the **winfuse** driver via another `FUSE_FSCTL_TRANSACT`.\n- The **winfuse** driver processes the FUSE response and it may issue additional FUSE requests or it may translate it to a final WinFsp response, which it sends to the **winfsp** FSD via another `FSP_FSCTL_TRANSACT`.\n- The **winfsp** FSD completes the corresponding I/O, which allows the Originating Process to resume and retrieve the response.\n\n#### I/O handled by a Linux FUSE file system:\n\n![Linux FS Sequence Diagram](doc/wslseq.svg)\n\nThis case is similar to the previous case except that the **winfuse** driver is replaced by the **wslfuse** driver that exposes the FUSE protocol via the **/dev/fuse** interface that the Linux FUSE file system understands.\n"
  },
  {
    "path": "appveyor.yml",
    "content": "version: '{build}'\n\nimage: Visual Studio 2019\n\nenvironment:\n  matrix:\n  - CONFIGURATION: Debug\n    WINFSP: rel\n    LXDK: rel\n  - CONFIGURATION: Release\n    WINFSP: rel\n    LXDK: rel\n\ninit:\n#- ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))\n\ninstall:\n- git submodule update --init --recursive\n# install WinFsp\n- appveyor AddMessage \"Install WinFsp\" -Category Information\n- if %WINFSP%==rel appveyor DownloadFile https://github.com/billziss-gh/winfsp/releases/download/v1.8B2/winfsp-1.8.20221.msi\n- if %WINFSP%==rel appveyor DownloadFile https://github.com/billziss-gh/winfsp/releases/download/v1.8B2/winfsp-tests-1.8.20221.zip\n- if %WINFSP%==src tools\\build-winfsp.bat %CONFIGURATION%\n- if %WINFSP%==src copy ext\\winfsp\\build\\VStudio\\build\\%CONFIGURATION%\\winfsp-*.msi .\n- if %WINFSP%==src copy ext\\winfsp\\build\\VStudio\\build\\%CONFIGURATION%\\winfsp-tests-*.zip .\n- for %%f in (\"winfsp-*.msi\") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000\n- for %%f in (\"winfsp-tests-*.zip\") do powershell -command \"Expand-Archive -Path %%f -DestinationPath 'C:\\Program Files (x86)\\WinFsp\\bin'\"\n# install LxDK\n- appveyor AddMessage \"Install LxDK\" -Category Information\n- if %LXDK%==rel appveyor DownloadFile https://github.com/billziss-gh/lxdk/releases/download/v0.3/lxdk-0.3.20228.msi\n- if %LXDK%==src tools\\build-lxdk.bat %CONFIGURATION%\n- if %LXDK%==src copy ext\\lxdk\\build\\VStudio\\build\\%CONFIGURATION%\\lxdk-*.msi .\n- for %%f in (\"lxdk-*.msi\") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000\n# install WSL Ubuntu 20.04 - adapted from appveyor/build-images:scripts/Windows/install_wsl.ps1\n- appveyor AddMessage \"Install WSL Ubuntu 20.04\" -Category Information\n- ps: (New-Object Net.WebClient).DownloadFile('https://aka.ms/wslubuntu2004', \"$env:TEMP\\wsl-ubuntu-2004.zip\")\n- ps: Expand-Archive -Path \"$env:TEMP\\wsl-ubuntu-2004.zip\" -DestinationPath \"C:\\WSL\\WinFuse-Ubuntu2004\" -Force\n- ps: Remove-Item \"$env:TEMP\\wsl-ubuntu-2004.zip\"\n- ps: . \"C:\\WSL\\WinFuse-Ubuntu2004\\ubuntu2004.exe\" install --root\n- ps: . \"C:\\WSL\\WinFuse-Ubuntu2004\\ubuntu2004.exe\" run adduser appveyor --gecos `\"First,Last,RoomNumber,WorkPhone,HomePhone`\" --disabled-password\n- ps: . \"C:\\WSL\\WinFuse-Ubuntu2004\\ubuntu2004.exe\" run \"echo 'appveyor:Password12!' | sudo chpasswd\"\n- ps: . \"C:\\WSL\\WinFuse-Ubuntu2004\\ubuntu2004.exe\" run usermod -aG sudo appveyor\n- ps: |\n    . \"C:\\WSL\\WinFuse-Ubuntu2004\\ubuntu2004.exe\" run \"echo -e `\"`\"appveyor\\tALL=(ALL)\\tNOPASSWD: ALL`\"`\" > /etc/sudoers.d/appveyor\"\n- ps: . \"C:\\WSL\\WinFuse-Ubuntu2004\\ubuntu2004.exe\" run chmod 0755 /etc/sudoers.d/appveyor\n- ps: . \"C:\\WSL\\WinFuse-Ubuntu2004\\ubuntu2004.exe\" config --default-user appveyor\n- wslconfig /setdefault Ubuntu-20.04\n- wsl -- lsb_release -a\n# install WSL tools\n- appveyor AddMessage \"Install WSL tools\" -Category Information\n- wsl -- sudo apt-get update; sudo apt-get install -y g++ gdb make ninja-build rsync zip libfuse3-dev\n# enable test-signing and verifier and reboot\n- appveyor AddMessage \"Change boot configuration and reboot\" -Category Information\n- bcdedit /set testsigning on\n- verifier /standard /driver winfuse-x64.sys || ver>nul\n- if exist %SystemRoot%\\memory.dmp del %SystemRoot%\\memory.dmp\n- ps: Restart-Computer -Force\n- ps: Start-Sleep -s 60\n\nbuild_script:\n- appveyor AddMessage \"Reboot complete\" -Category Information\n- tools\\build.bat %CONFIGURATION%\n- for %%f in (\"build\\VStudio\\build\\%CONFIGURATION%\\winfuse-*-x64.msi\") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000\n- copy ext\\libfuse\\build\\%CONFIGURATION%\\x86\\lib\\fuse3-x86.dll \"C:\\Program Files\\WinFuse\\opt\\libfuse\\bin\"\n- copy ext\\libfuse\\build\\%CONFIGURATION%\\x86\\lib\\fuse3-x86.lib \"C:\\Program Files\\WinFuse\\opt\\libfuse\\lib\"\n\ntest_script:\n- tools\\nmake-ext-test.bat\n- tools\\run-tests.bat %CONFIGURATION%\n- tools\\run-tests.bat %CONFIGURATION% sample\n- if exist %SystemRoot%\\memory.dmp exit 1\n\non_finish:\n- if exist %SystemRoot%\\memory.dmp (7z a memory.dmp.zip %SystemRoot%\\memory.dmp && appveyor PushArtifact memory.dmp.zip)\n- verifier /query\n#- ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))\n"
  },
  {
    "path": "doc/component.puml",
    "content": "left to right direction\nskinparam componentStyle uml2\nskinparam nodesep 50\nskinparam ranksep 30\nskinparam shadowing false\nskinparam rectangle {\n    fontcolor grey\n    borderColor grey\n    shadowing false\n}\nskinparam linetype ortho\n\nrectangle NTOS {\n    together dummy {\n        component winfuse #Salmon\n        interface \"FUSE_FSCTL\\nTRANSACT\" as FUSE_FSCTL_TRANSACT #Salmon\n        winfuse -right- FUSE_FSCTL_TRANSACT\n\n        component winfsp\n        interface \"FSP_FSCTL\\nTRANSACT\" as FSP_FSCTL_TRANSACT\n        winfsp -right- FSP_FSCTL_TRANSACT\n\n        winfsp .up.> winfuse: loads\n        winfuse -down-( FSP_FSCTL_TRANSACT\n    }\n\n    rectangle LXCORE {\n        component wslfuse #Salmon\n        interface \"/dev/fuse\" as devfuse #Salmon\n        wslfuse -right- devfuse\n\n        component lxldr\n\n        lxldr .up.> wslfuse: loads\n    }\n\n    winfsp -[hidden]- wslfuse\n    wslfuse -up-( FSP_FSCTL_TRANSACT\n}\n\ncomponent \"Windows\\nWinFsp FS\" as fspfs\nfspfs -left-( FSP_FSCTL_TRANSACT\n\ncomponent \"Windows\\nFUSE FS\" as winfs\nwinfs -left-( FUSE_FSCTL_TRANSACT\n\ncomponent \"Linux\\nFUSE FS\" as wslfs\nwslfs -left-( devfuse\n"
  },
  {
    "path": "doc/winseq.puml",
    "content": "skinparam shadowing false\nhide footbox\n\nbox \"Originating Process Context\"\n    participant \"Originating\\nProcess\" as OP\n    participant \"winfsp\" as winfspOP\nend box\nbox \"File System Process Context\"\n    participant \"winfsp\" as winfspFS\n    participant winfuse #Salmon\n    participant \"Windows\\nFUSE FS\" as FS\nend box\n\nactivate OP\nOP->winfspOP: I/O\ndeactivate OP\nactivate winfspOP\nwinfspOP-->winfspFS: Context Switch\ndeactivate winfspOP\nactivate winfspFS\nwinfspFS->winfuse: FSP_FSCTL_TRANSACT Req\ndeactivate winfspFS\nactivate winfuse\nwinfuse->FS: FUSE_FSCTL_TRANSACT Req\ndeactivate winfuse\nactivate FS\nFS->FS: Process\nactivate FS\ndeactivate FS\nFS->winfuse: FUSE_FSCTL_TRANSACT Rsp\ndeactivate FS\nactivate winfuse\nwinfuse->winfspFS: FSP_FSCTL_TRANSACT Rsp\ndeactivate winfuse\nactivate winfspFS\nwinfspFS-->OP: Context Switch and Return\ndeactivate winfspFS\nactivate OP\n"
  },
  {
    "path": "doc/wslseq.puml",
    "content": "skinparam shadowing false\nhide footbox\n\nbox \"Originating Process Context\"\n    participant \"Originating\\nProcess\" as OP\n    participant \"winfsp\" as winfspOP\nend box\nbox \"File System Process Context\"\n    participant \"winfsp\" as winfspFS\n    participant wslfuse #Salmon\n    participant \"Linux\\nFUSE FS\" as FS\nend box\n\nactivate OP\nOP->winfspOP: I/O\ndeactivate OP\nactivate winfspOP\nwinfspOP-->winfspFS: Context Switch\ndeactivate winfspOP\nactivate winfspFS\nwinfspFS->wslfuse: FSP_FSCTL_TRANSACT Req\ndeactivate winfspFS\nactivate wslfuse\nwslfuse->FS: /dev/fuse read\ndeactivate wslfuse\nactivate FS\nFS->FS: Process\nactivate FS\ndeactivate FS\nFS->wslfuse: /dev/fuse write\ndeactivate FS\nactivate wslfuse\nwslfuse->winfspFS: FSP_FSCTL_TRANSACT Rsp\ndeactivate wslfuse\nactivate winfspFS\nwinfspFS-->OP: Context Switch and Return\ndeactivate winfspFS\nactivate OP\n"
  },
  {
    "path": "ext/tlib/Commit.txt",
    "content": "Taken from github.com/billziss-gh/winfsp/ext/tlib codebase:\n    commit 847eab3da4e558e2c88504edfe18a51e4450f9e0\n\nOriginally from secfs.core/src/tlib codebase:\n    commit 16296d2ac64a7d532b1c486dd3c44af5865d4851\n"
  },
  {
    "path": "ext/tlib/callstack.c",
    "content": "/**\n * @file tlib/callstack.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/callstack.h>\n#include <stddef.h>\n#include <string.h>\n#if defined(_WIN32) || defined(_WIN64)\n#include <windows.h>\n#include <dbghelp.h>\n#pragma comment(lib, \"dbghelp.lib\")\n#elif defined(__APPLE__) || defined(__linux__)\n#include <dlfcn.h>\n#include <execinfo.h>\n#else\n#error tlib/callstack.c not implemented for this platform\n#endif\n\nvoid tlib_callstack(size_t skip, size_t count, struct tlib_callstack_s *stack)\n{\n    if (count > TLIB_MAX_SYMRET)\n        count = TLIB_MAX_SYMRET;\n    size_t naddrs = skip + count;\n    if (naddrs > TLIB_MAX_SYMCAP)\n        naddrs = TLIB_MAX_SYMCAP;\n    memset((void *)stack->syms, 0, sizeof stack->syms);\n#if defined(_WIN32) || defined(_WIN64)\n    /* SymInitialize()/SymFromAddr() are not thread-safe. Furthermore SymInitialize() should\n     * not be called more than once per process.\n     */\n    HANDLE hproc = GetCurrentProcess();\n    static SYMBOL_INFO *syminfo = 0;\n    void *addrs[TLIB_MAX_SYMCAP];\n    size_t i = 0;\n    if (0 == syminfo)\n    {\n        syminfo = (SYMBOL_INFO *)malloc(sizeof(SYMBOL_INFO) + TLIB_MAX_SYMLEN);\n        if (0 == syminfo)\n            return;\n         SymInitialize(hproc, 0, TRUE);\n    }\n    memset(syminfo, 0, sizeof(SYMBOL_INFO));\n    syminfo->SizeOfStruct = sizeof(SYMBOL_INFO);\n    syminfo->MaxNameLen = TLIB_MAX_SYMLEN;\n    naddrs = CaptureStackBackTrace(0, naddrs, addrs, 0);\n    for (void **p = addrs + skip, **endp = addrs + naddrs; endp > p; p++)\n    {\n        DWORD64 displacement = 0;\n        if (SymFromAddr(hproc, (DWORD64)*p, &displacement, syminfo))\n        {\n            stack->syms[i] = stack->symbuf[i];\n            strncpy(stack->symbuf[i], syminfo->Name, TLIB_MAX_SYMLEN);\n            stack->symbuf[i][TLIB_MAX_SYMLEN] = '\\0';\n            i++;\n        }\n    }\n#elif defined(__APPLE__) || defined(__linux__)\n    void *addrs[TLIB_MAX_SYMCAP];\n    naddrs = backtrace(addrs, naddrs);\n    size_t i = 0;\n    Dl_info syminfo;\n    for (void **p = addrs + skip, **endp = addrs + naddrs; endp > p; p++)\n    {\n        if (dladdr(*p, &syminfo) && 0 != syminfo.dli_sname)\n        {\n            stack->syms[i] = stack->symbuf[i];\n            strncpy(stack->symbuf[i], syminfo.dli_sname, TLIB_MAX_SYMLEN);\n            stack->symbuf[i][TLIB_MAX_SYMLEN] = '\\0';\n            i++;\n        }\n    }\n#endif\n}\n"
  },
  {
    "path": "ext/tlib/callstack.h",
    "content": "/**\n * @file tlib/callstack.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_CALLSTACK_H_INCLUDED\n#define TLIB_CALLSTACK_H_INCLUDED\n\n#include <stddef.h>\n\nenum\n{\n    TLIB_MAX_SYMLEN = 63,\n    TLIB_MAX_SYMRET = 8,\n    TLIB_MAX_SYMCAP = 62, /* max number of frames to capture (Windows restriction) */\n};\n\nstruct tlib_callstack_s\n{\n    const char *syms[TLIB_MAX_SYMRET + 1];\n    char symbuf[TLIB_MAX_SYMRET][TLIB_MAX_SYMLEN + 1];\n};\nvoid tlib_callstack(size_t skip, size_t count, struct tlib_callstack_s *stack);\n\n#endif\n"
  },
  {
    "path": "ext/tlib/injected/allfunc.h",
    "content": "/**\n * @file tlib/injected/allfunc.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_INJECTED_ALLFUNC_H_INCLUDED\n#define TLIB_INJECTED_ALLFUNC_H_INCLUDED\n\n#include <tlib/injected/curlfunc.h>\n#include <tlib/injected/stdfunc.h>\n\n#endif\n"
  },
  {
    "path": "ext/tlib/injected/curlfunc.c",
    "content": "/**\n * @file tlib/injected/curlfunc.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/injected/curlfunc.h>\n#define TLIB_INJECTIONS_ENABLED\n#include <tlib/injection.h>\n\n#undef curl_easy_init\n#undef curl_multi_init\n#undef curl_multi_add_handle\n#undef curl_multi_perform\n\nCURL *tlib_curl_easy_init(void)\n{\n    TLIB_INJECT(\"curl_easy_init\", return 0);\n    return curl_easy_init();\n}\nCURLM *tlib_curl_multi_init(void)\n{\n    TLIB_INJECT(\"curl_multi_init\", return 0);\n    return curl_multi_init();\n}\nCURLMcode tlib_curl_multi_add_handle(CURLM *mh, CURL *eh)\n{\n    TLIB_INJECT(\"curl_multi_add_handle\", return CURLM_INTERNAL_ERROR);\n    return curl_multi_add_handle(mh, eh);\n}\nCURLMcode tlib_curl_multi_perform(CURLM *mh, int *running_handles)\n{\n    TLIB_INJECT(\"curl_multi_perform\", return CURLM_INTERNAL_ERROR);\n    return curl_multi_perform(mh, running_handles);\n}\n"
  },
  {
    "path": "ext/tlib/injected/curlfunc.h",
    "content": "/**\n * @file tlib/injected/curlfunc.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_INJECTED_CURLFUNC_H_INCLUDED\n#define TLIB_INJECTED_CURLFUNC_H_INCLUDED\n\n#include <curl/curl.h>\n\n#if defined(TLIB_INJECTIONS_ENABLED)\n#define curl_easy_init()                tlib_curl_easy_init()\n#define curl_multi_init()               tlib_curl_multi_init()\n#define curl_multi_add_handle(mh, eh)   tlib_curl_multi_add_handle(mh, eh)\n#define curl_multi_perform(mh, rh)      tlib_curl_multi_perform(mh, rh)\n#endif\n\nCURL *tlib_curl_easy_init(void);\nCURLM *tlib_curl_multi_init(void);\nCURLMcode tlib_curl_multi_add_handle(CURLM *mh, CURL *eh);\nCURLMcode tlib_curl_multi_perform(CURLM *mh, int *running_handles);\n\n#endif\n"
  },
  {
    "path": "ext/tlib/injected/stdfunc.c",
    "content": "/**\n * @file tlib/injected/stdfunc.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/injected/stdfunc.h>\n#define TLIB_INJECTIONS_ENABLED\n#include <tlib/injection.h>\n\n#undef calloc\n#undef malloc\n#undef realloc\n\nvoid *tlib_calloc(size_t count, size_t size)\n{\n    TLIB_INJECT(\"calloc\", return 0);\n    return calloc(count, size);\n}\nvoid *tlib_malloc(size_t size)\n{\n    TLIB_INJECT(\"malloc\", return 0);\n    return malloc(size);\n}\nvoid *tlib_realloc(void *ptr, size_t size)\n{\n    TLIB_INJECT(\"realloc\", return 0);\n    return realloc(ptr, size);\n}\n"
  },
  {
    "path": "ext/tlib/injected/stdfunc.h",
    "content": "/**\n * @file tlib/injected/stdfunc.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_INJECTED_STDFUNC_H_INCLUDED\n#define TLIB_INJECTED_STDFUNC_H_INCLUDED\n\n#include <stdlib.h>\n#include <errno.h>\n\n#if defined(TLIB_INJECTIONS_ENABLED)\n#define calloc(count, size)             tlib_calloc(count, size)\n#define malloc(size)                    tlib_malloc(size)\n#define realloc(ptr, size)              tlib_realloc(ptr, size)\n#endif\n\nvoid *tlib_calloc(size_t count, size_t size);\nvoid *tlib_malloc(size_t size);\nvoid *tlib_realloc(void *ptr, size_t size);\n\n#endif\n"
  },
  {
    "path": "ext/tlib/injection.c",
    "content": "/**\n * @file tlib/injection.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/injection.h>\n#include <tlib/callstack.h>\n#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n\n#undef NDEBUG\n#include <assert.h>\n\n#define NBUCKETS                        256\nstruct injection_cond_s\n{\n    struct injection_cond_s *cnext;\n    char *sym;\n    unsigned trigger, count;\n};\nstruct injection_entry_s\n{\n    struct injection_entry_s *hnext;\n    char *name;\n    struct injection_cond_s *clist;\n};\nstruct injection_htab_s\n{\n    struct injection_entry_s **buckets;\n};\n\nstatic inline size_t hash_chars(const char *s, size_t length)\n{\n    /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */\n    size_t h = 5381;\n    for (const char *t = s + length; t > s; ++s)\n        h = 33 * h + *s;\n    return h;\n}\nstatic struct injection_htab_s *injection_htab()\n{\n    static struct injection_htab_s *htab;\n    if (0 == htab)\n    {\n        htab = calloc(1, sizeof *htab);\n        assert(0 != htab);\n        htab->buckets = calloc(NBUCKETS, sizeof(struct injection_entry_s *));\n    }\n    return htab;\n}\nstatic struct injection_entry_s *injection_lookup(const char *name)\n{\n    struct injection_htab_s *htab = injection_htab();\n    size_t i = hash_chars(name, strlen(name)) & (NBUCKETS - 1);\n    for (struct injection_entry_s *entry = htab->buckets[i]; entry; entry = entry->hnext)\n        if (0 == strcmp(entry->name, name))\n            return entry;\n    return 0;\n}\nstatic struct injection_entry_s *injection_insert(const char *name)\n{\n    struct injection_htab_s *htab = injection_htab();\n    size_t i = hash_chars(name, strlen(name)) & (NBUCKETS - 1);\n    struct injection_entry_s *entry = calloc(1, sizeof *entry);\n    assert(0 != entry);\n    entry->name = strdup(name);\n    entry->hnext = htab->buckets[i];\n    htab->buckets[i] = entry;\n    return entry;\n}\nstatic struct injection_cond_s *injection_cond_get(struct injection_entry_s *entry, const char **syms)\n{\n    struct injection_cond_s *deinjection_centry = 0;\n    for (struct injection_cond_s *centry = entry->clist; centry; centry = centry->cnext)\n        if ('*' == centry->sym[0] && '\\0' == centry->sym[1])\n            deinjection_centry = centry;\n        else\n        {\n            for (const char *sym; 0 != (sym = *syms); syms++)\n                if (0 == strcmp(centry->sym, sym))\n                    return centry;\n        }\n    return deinjection_centry;\n}\nstatic void injection_cond_set(struct injection_entry_s *entry, const char *sym, unsigned trigger)\n{\n    for (struct injection_cond_s *centry = entry->clist; centry; centry = centry->cnext)\n        if (0 == strcmp(centry->sym, sym))\n        {\n            centry->trigger = trigger;\n            return;\n        }\n    struct injection_cond_s *centry = calloc(1, sizeof *centry);\n    assert(0 != centry);\n    centry->sym = strdup(sym);\n    centry->trigger = trigger;\n    centry->cnext = entry->clist;\n    entry->clist = centry;\n}\nstatic void injection_cond_remove(struct injection_entry_s *entry, const char *sym)\n{\n    struct injection_cond_s **p = &entry->clist;\n    for (; *p; p = &(*p)->cnext)\n        if (0 == strcmp((*p)->sym, sym))\n            break;\n    if (*p) /* did we find the condition? */\n    {\n        struct injection_cond_s *q = *p;\n        *p = q->cnext;\n        free(q->sym);\n        free(q);\n    }\n}\n\nvoid *tlib_injection(const char *name)\n{\n    struct injection_entry_s *entry = injection_lookup(name);\n    if (0 == entry)\n        entry = injection_insert(name);\n    return entry;\n}\nint tlib_injection_trace(void *injection)\n{\n    if (0 == ((struct injection_entry_s *)injection)->clist)\n        return 0;\n    struct tlib_callstack_s stack;\n    tlib_callstack(2, TLIB_MAX_SYMRET, &stack);\n    struct injection_cond_s *centry = injection_cond_get(injection, stack.syms);\n    if (0 == centry)\n        return 0;\n    return centry->count++ == centry->trigger || ~0 == centry->trigger;\n}\nvoid tlib_injection_enable(const char *name, const char *sym, unsigned trigger)\n{\n    struct injection_entry_s *entry = tlib_injection(name);\n    injection_cond_set(entry, sym, trigger);\n}\nvoid tlib_injection_disable(const char *name, const char *sym)\n{\n    struct injection_entry_s *entry = tlib_injection(name);\n    injection_cond_remove(entry, sym);\n}\n"
  },
  {
    "path": "ext/tlib/injection.h",
    "content": "/**\n * @file tlib/injection.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n/* NOTE: This header may usefully be included multiple times.\n * The TLIB_INJECT() macro will be redefined based on whether\n * TLIB_INJECTIONS_ENABLED is defined.\n */\n\n#undef TLIB_INJECT\n#if defined(TLIB_INJECTIONS_ENABLED)\n#define TLIB_INJECT(name, stmt)         \\\n    do\\\n    {\\\n        static void *injection = 0;\\\n        if (0 == injection)\\\n            injection = tlib_injection(name);\\\n        if (tlib_injection_trace(injection))\\\n            stmt;\\\n    } while (0)\n#else\n#define TLIB_INJECT(name, stmt)         do {} while (0)\n#endif\n\nvoid *tlib_injection(const char *name);\nint tlib_injection_trace(void *injection);\nvoid tlib_injection_enable(const char *name, const char *sym, unsigned trigger);\nvoid tlib_injection_disable(const char *name, const char *sym);\n"
  },
  {
    "path": "ext/tlib/testsuite.c",
    "content": "/**\n * @file tlib/testsuite.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/testsuite.h>\n#include <limits.h>\n#include <setjmp.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\nstruct test\n{\n    char name[64];\n    void (*fn)(void);\n    int optional;\n    struct test *next;\n};\nstatic struct test test_suite_sentinel = { .next = &test_suite_sentinel };\nstatic struct test *test_suite_tail = &test_suite_sentinel;\nstatic struct test test_sentinel = { .next = &test_sentinel };\nstatic struct test *test_tail = &test_sentinel;\nstatic void add_test_to_list(const char *name, void (*fn)(void), int optional, struct test **tail)\n{\n    struct test *test = calloc(1, sizeof *test);\n    strncpy(test->name, name, sizeof test->name - 1);\n    test->name[sizeof test->name - 1] = '\\0';\n    test->fn = fn;\n    test->optional = optional;\n    test->next = (*tail)->next;\n    (*tail)->next = test;\n    (*tail) = test;\n}\nvoid tlib_add_test_suite(const char *name, void (*fn)(void))\n{\n    add_test_to_list(name, fn, 0, &test_suite_tail);\n}\nvoid tlib_add_test(const char *name, void (*fn)(void))\n{\n    add_test_to_list(name, fn, 0, &test_tail);\n}\nvoid tlib_add_test_opt(const char *name, void (*fn)(void))\n{\n    add_test_to_list(name, fn, 1, &test_tail);\n}\n\nstatic FILE *tlib_out, *tlib_err;\nstatic jmp_buf test_jmp_buf, *test_jmp;\nstatic char assert_buf[256];\nstatic void test_printf(const char *fmt, ...);\nstatic double run_test(struct test *test)\n{\n#if defined(_WIN64) || defined(_WIN32)\n    #pragma comment(lib, \"winmm.lib\")\n    unsigned long __stdcall timeGetTime(void);\n    unsigned long t0 = timeGetTime();\n    test->fn();\n    unsigned long t1 = timeGetTime();\n    return (t1 - t0) / 1000.0;\n#else\n    time_t t0 = time(0);\n    test->fn();\n    time_t t1 = time(0);\n    return difftime(t1, t0);\n#endif\n}\nstatic void do_test_default(struct test *test, int testno)\n{\n    if (0 != test)\n    {\n        snprintf(assert_buf, sizeof assert_buf, \"KO\\n    \");\n        char dispname[39 + 1];\n        size_t displen = strlen(test->name);\n        if (displen > sizeof dispname - 1)\n            displen = sizeof dispname - 1;\n        memcpy(dispname, test->name, displen);\n        memset(dispname + displen, '.', sizeof dispname - 1 - displen);\n        dispname[sizeof dispname - 1] = '\\0';\n        test_printf(\"%s \", dispname);\n        double d = run_test(test);\n        test_printf(\"OK %.2fs\\n\", d);\n    }\n    else\n        test_printf(\"--- COMPLETE ---\\n\");\n}\nstatic void do_test_list(struct test *test, int testno)\n{\n    if (0 != test)\n        test_printf(\"%s\\n\", test->name);\n}\nstatic void do_test_tap(struct test *test, int testno)\n{\n    if (0 != test)\n    {\n        snprintf(assert_buf, sizeof assert_buf, \"not ok %d %s\\n# \", testno + 1, test->name);\n        run_test(test);\n        test_printf(\"ok %d %s\\n\", testno + 1, test->name);\n    }\n    else\n        test_printf(\"1..%d\\n\", testno);\n}\nstatic void test_printf(const char *fmt, ...)\n{\n    va_list ap;\n    va_start(ap, fmt);\n    FILE *f = tlib_out ? tlib_out : stdout;\n    vfprintf(f, fmt, ap);\n    fflush(f);\n    va_end(ap);\n}\nvoid tlib_printf(const char *fmt, ...)\n{\n    va_list ap;\n    va_start(ap, fmt);\n    FILE *f = tlib_err ? tlib_err : stderr;\n    vfprintf(f, fmt, ap);\n    fflush(f);\n    va_end(ap);\n}\nvoid tlib_run_tests(int argc, char *argv[])\n{\n    argc--; argv++;\n    void (*do_test)(struct test *, int) = do_test_default;\n    int match_any = 1, no_abort = 0;\n    unsigned long repeat = 1;\n    for (char **ap = argv, **aendp = ap + argc; aendp > ap; ap++)\n    {\n        const char *a = *ap;\n        if ('-' == a[0])\n        {\n            if (0 == strcmp(\"--list\", a))\n                do_test = do_test_list;\n            else if (0 == strcmp(\"--tap\", a))\n                do_test = do_test_tap;\n            else if (0 == strcmp(\"--no-abort\", a))\n                no_abort = 1;\n            else if (0 == strcmp(\"--repeat-forever\", a))\n                repeat = ULONG_MAX;\n            else if ('-' == a[1])\n            {\n                fprintf(stderr, \"tlib_run_tests: unknown option %s\\n\", a);\n                exit(2);\n            }\n        }\n        else\n            match_any = 0;\n    }\n    for (struct test *test = test_suite_tail->next->next; 0 != test->fn; test = test->next)\n        test->fn();\n    while (repeat--)\n    {\n        int testno = 0;\n        for (struct test *test = test_tail->next->next; 0 != test->fn; test = test->next)\n        {\n            int match_arg = match_any && !test->optional;\n            for (char **ap = argv, **aendp = ap + argc; aendp > ap; aendp--)\n            {\n                const char *a = aendp[-1];\n                int sign = a[0];\n                if ('+' == sign)\n                    a++;\n                else if ('-' == sign)\n                {\n                    if ('-' == a[1])\n                        continue;\n                    a++;\n                }\n                size_t l = strlen(a);\n                if (0 == (0 < l && '*' == a[l - 1] ?\n                    strncmp(test->name, a, l - 1) : strcmp(test->name, a)))\n                {\n                    if ('+' == sign)\n                        match_arg = 1;\n                    else if ('-' == sign)\n                        match_arg = 0;\n                    else\n                        match_arg = !test->optional;\n                    break;\n                }\n            }\n            if (!match_arg)\n                continue;\n            assert_buf[0] = '\\0';\n            if (no_abort)\n            {\n                test_jmp = &test_jmp_buf;\n                if (0 == setjmp(*test_jmp))\n                    do_test(test, testno);\n                test_jmp = 0;\n            }\n            else\n                do_test(test, testno);\n            testno++;\n        }\n        do_test(0, testno);\n    }\n}\nvoid tlib__assert(const char *func, const char *file, int line, const char *expr)\n{\n#if defined(_WIN64) || defined(_WIN32)\n    const char *p = strrchr(file, '\\\\');\n#else\n    const char *p = strrchr(file, '/');\n#endif\n    file = 0 != p ? p + 1 : file;\n    if (0 == func)\n        test_printf(\"%sASSERT(%s) failed at: %s:%d\\n\", assert_buf, expr, file, line);\n    else\n        test_printf(\"%sASSERT(%s) failed at %s:%d:%s\\n\", assert_buf, expr, file, line, func);\n    if (0 != test_jmp)\n        longjmp(*test_jmp, 1);\n}\n"
  },
  {
    "path": "ext/tlib/testsuite.h",
    "content": "/**\n * @file tlib/testsuite.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_TESTSUITE_H_INCLUDED\n#define TLIB_TESTSUITE_H_INCLUDED\n\n#include <stdlib.h>\n\n/**\n * Assert macro\n *\n * This macro works similarly to the Standard C assert macro, except for the following differences:\n *\n * <ul>\n * <li>The macro always checks the specified expression regardless of the NDEBUG macro.</li>\n * <li>The macro aborts the execution of the current test, but not necessarily the execution of the\n * whole testsuite.</li>\n * </ul>\n */\n#define ASSERT(expr)\\\n    (!(expr) ? (tlib__assert(__func__, __FILE__, __LINE__, #expr), abort()) : (void)0)\n\n/**\n * Register a test suite for execution.\n *\n * Test suites are simple functions with prototype <code>void testsuite()</code>. When executed\n * they register individual test cases for execution.\n */\n#define TESTSUITE(fn)\\\n    do\\\n    {\\\n        void fn(void);\\\n        tlib_add_test_suite(#fn, fn);\\\n    } while (0)\n\n/**\n * Register a test case for execution.\n *\n * Test cases are simple functions with prototype <code>void testcase()</code>.\n */\n#define TEST(fn)\\\n    do\\\n    {\\\n        void fn(void);\\\n        tlib_add_test(#fn, fn);\\\n    } while (0)\n\n/**\n * Register an optional test case for execution.\n *\n * Test cases are simple functions with prototype <code>void testcase()</code>.\n * Optional tests are not executed by default.\n */\n#define TEST_OPT(fn)\\\n    do\\\n    {\\\n        void fn(void);\\\n        tlib_add_test_opt(#fn, fn);\\\n    } while (0)\n\nvoid tlib_add_test_suite(const char *name, void (*fn)(void));\nvoid tlib_add_test(const char *name, void (*fn)(void));\nvoid tlib_add_test_opt(const char *name, void (*fn)(void));\n\n/**\n * Printf function.\n *\n * Use this to produce output in the appropriate tlib file stream. This function uses the local\n * printf facilities and understands the same format strings.\n */\n#if defined(__GNUC__)\nvoid tlib_printf(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));\n#else\nvoid tlib_printf(const char *fmt, ...);\n#endif\n/**\n * Run tests.\n *\n * This function will first execute all registered test suites, thus giving them the chance to\n * register any test cases. It will then execute all registered test cases according to the\n * command line arguments passed in argv. The command line syntax is a follows:\n *\n * Usage: testprog [--list][[--tap][--no-abort][--repeat-forever] [[+-]TESTNAME...]\n *\n * <ul>\n * <li>--list - list tests only</li>\n * <li>--tap - produce output in TAP format</li>\n * <li>--no-abort - do not abort all tests when an ASSERT fails\n * (only the current test is aborted)</li>\n * <li>--repeat-forever - repeat tests forever</li>\n * </ul>\n *\n * By default all test cases are executed unless specific test cases are named. By default optional\n * test cases are not executed. To execute a specific test case specify its TESTNAME; if it is an\n * optional test case specify +TESTNAME. To excluse a test case specify -TESTNAME.\n *\n * TESTNAME may also contain a single asterisk at the end; for example, mytest* will match all test\n * cases that have names starting with \"mytest\".\n *\n * @param argc\n *     Argument count.\n * @param argv\n *     Argument vector.\n */\nvoid tlib_run_tests(int argc, char *argv[]);\n\nvoid tlib__assert(const char *func, const char *file, int line, const char *expr);\n\n#endif\n"
  },
  {
    "path": "src/fusermount/fusermount-helper.c",
    "content": "/**\n * @file fusermount-helper.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <windows.h>\n#include <winternl.h>\n\n#define PROGNAME                        \"fusermount-helper\"\n\n#undef RtlFillMemory\n#undef RtlMoveMemory\nNTSYSAPI VOID NTAPI RtlFillMemory(VOID *Destination, DWORD Length, BYTE Fill);\nNTSYSAPI VOID NTAPI RtlMoveMemory(VOID *Destination, CONST VOID *Source, DWORD Length);\n\n#pragma function(memset)\n#pragma function(memcpy)\nstatic inline\nvoid *memset(void *dst, int val, size_t siz)\n{\n    RtlFillMemory(dst, (DWORD)siz, val);\n    return dst;\n}\nstatic inline\nvoid *memcpy(void *dst, const void *src, size_t siz)\n{\n    RtlMoveMemory(dst, src, (DWORD)siz);\n    return dst;\n}\n\n#define warn(format, ...)               \\\n    printlog(GetStdHandle(STD_ERROR_HANDLE), PROGNAME \": \" format, __VA_ARGS__)\n#define fatal(ExitCode, format, ...)    (warn(format, __VA_ARGS__), ExitProcess(ExitCode))\n\nstatic void vprintlog(HANDLE h, const char *format, va_list ap)\n{\n    char buf[1024];\n        /* wvsprintf is only safe with a 1024 byte buffer */\n    size_t len;\n    DWORD BytesTransferred;\n\n    wvsprintfA(buf, format, ap);\n    buf[sizeof buf - 1] = '\\0';\n\n    len = lstrlenA(buf);\n    buf[len++] = '\\n';\n\n    WriteFile(h, buf, (DWORD)len, &BytesTransferred, 0);\n}\n\nstatic void printlog(HANDLE h, const char *format, ...)\n{\n    va_list ap;\n\n    va_start(ap, format);\n    vprintlog(h, format, ap);\n    va_end(ap);\n}\n\nNTSTATUS NTAPI NtOpenSymbolicLinkObject(PHANDLE LinkHandle,\n    ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes);\nNTSTATUS NTAPI NtMakeTemporaryObject(HANDLE Handle);\nNTSTATUS NTAPI NtClose(HANDLE Handle);\n\nstatic BOOL MountSet_Drive(PWSTR VolumeName, PWSTR MountPoint, PHANDLE PMountHandle)\n{\n    WCHAR SymlinkBuf[6];\n    UNICODE_STRING Symlink;\n    OBJECT_ATTRIBUTES Obja;\n    NTSTATUS Result;\n\n    *PMountHandle = 0;\n\n    if (!DefineDosDeviceW(DDD_RAW_TARGET_PATH, MountPoint, VolumeName))\n        return FALSE;\n\n    memcpy(SymlinkBuf, L\"\\\\??\\\\X:\", sizeof SymlinkBuf);\n    SymlinkBuf[4] = MountPoint[0];\n    Symlink.Length = Symlink.MaximumLength = sizeof SymlinkBuf;\n    Symlink.Buffer = SymlinkBuf;\n\n    memset(&Obja, 0, sizeof Obja);\n    Obja.Length = sizeof Obja;\n    Obja.ObjectName = &Symlink;\n    Obja.Attributes = OBJ_CASE_INSENSITIVE;\n\n    Result = NtOpenSymbolicLinkObject(PMountHandle, DELETE, &Obja);\n    if (NT_SUCCESS(Result))\n    {\n        Result = NtMakeTemporaryObject(*PMountHandle);\n        if (!NT_SUCCESS(Result))\n        {\n            NtClose(*PMountHandle);\n            *PMountHandle = 0;\n        }\n    }\n\n    return TRUE;\n}\n\nstatic BOOL MountSet(PWSTR VolumeName, PWSTR MountPoint, PHANDLE PMountHandle)\n{\n    *PMountHandle = 0;\n\n    if (L'*' == MountPoint[0] && ':' == MountPoint[1] && L'\\0' == MountPoint[2])\n    {\n        DWORD Drives;\n        WCHAR Drive;\n\n        Drives = GetLogicalDrives();\n        if (0 == Drives)\n            return FALSE;\n\n        for (Drive = 'Z'; 'D' <= Drive; Drive--)\n            if (0 == (Drives & (1 << (Drive - 'A'))))\n            {\n                MountPoint[0] = Drive;\n                if (MountSet_Drive(VolumeName, MountPoint, PMountHandle))\n                    return TRUE;\n            }\n        MountPoint[0] = L'*';\n        SetLastError(ERROR_NO_SUCH_DEVICE);\n            /* error code chosen for WinFsp compatibility (FspMountSet) */\n        return FALSE;\n    }\n    else if (\n        (\n            (L'A' <= MountPoint[0] && MountPoint[0] <= L'Z') ||\n            (L'a' <= MountPoint[0] && MountPoint[0] <= L'z')\n        ) && L':' == MountPoint[1] && L'\\0' == MountPoint[2])\n        return MountSet_Drive(VolumeName, MountPoint, PMountHandle);\n    else\n    {\n        SetLastError(ERROR_INVALID_PARAMETER);\n        return FALSE;\n    }\n}\n\nint wmain(int argc, wchar_t **argv)\n{\n    PWSTR VolumeName;\n    PWSTR MountPoint;\n    HANDLE MountHandle;\n    WCHAR WildMountPoint[] = L\"*:\";\n    UINT8 MountPointU8[MAX_PATH];\n    UINT8 Buffer[1];\n    DWORD BytesTransferred;\n\n    if (2 > argc || 3 < argc)\n        fatal(2, \"usage: VolumeName [WinMountPoint]\");\n\n    VolumeName = argv[1];\n    MountPoint = 2 < argc ? argv[2] : WildMountPoint;\n\n    if (!MountSet(VolumeName, MountPoint, &MountHandle))\n        fatal(1, \"cannot set Windows mount point %S (LastError=%lu)\", MountPoint, GetLastError());\n\n    if (0 == WideCharToMultiByte(CP_UTF8, 0, MountPoint, -1, MountPointU8, MAX_PATH, 0, 0))\n        fatal(1, \"invalid Windows mount point (LastError=%lu)\", GetLastError());\n\n    BytesTransferred = lstrlenA(MountPointU8) + 1;\n    if (!WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), MountPointU8, BytesTransferred, &BytesTransferred, 0))\n        fatal(1, \"cannot write to stdout (LastError=%lu)\", GetLastError());\n\n    if (!ReadFile(GetStdHandle(STD_INPUT_HANDLE), Buffer, sizeof Buffer, &BytesTransferred, 0))\n        fatal(1, \"cannot read from stdin (LastError=%lu)\", GetLastError());\n\n    return 0;\n}\n\nvoid wmainCRTStartup(void)\n{\n    DWORD Argc;\n    PWSTR *Argv;\n\n    Argv = CommandLineToArgvW(GetCommandLineW(), &Argc);\n    if (0 == Argv)\n        ExitProcess(GetLastError());\n\n    ExitProcess(wmain(Argc, Argv));\n}\n"
  },
  {
    "path": "src/fusermount/fusermount.c",
    "content": "/**\n * @file fusermount.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#define _GNU_SOURCE\n#include <errno.h>\n#include <fcntl.h>\n#include <grp.h>\n#include <getopt.h>\n#include <libgen.h>\n#include <limits.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/mount.h>\n#include <sys/socket.h>\n#include <sys/time.h>\n#include <sys/wait.h>\n#include <unistd.h>\n#include <shared/ku/wslfuse.h>\n\nstatic const char *progname;\nstatic struct\n{\n    const char *mountpoint;\n    const char *opts;\n    int unmount;\n    int lazy;\n    int quiet;\n} args;\n\nstruct mount_opts\n{\n    FSP_FSCTL_VOLUME_PARAMS VolumeParams;\n    char WinMountPoint[260];\n    int set_attr_timeout, attr_timeout;\n    int set_FileInfoTimeout,\n        set_DirInfoTimeout,\n        set_EaTimeout,\n        set_VolumeInfoTimeout,\n        set_KeepFileCache;\n    unsigned max_read;\n};\n\nstatic void warn(const char *format, ...)\n{\n    va_list ap;\n\n    va_start(ap, format);\n    if (!args.quiet)\n    {\n        fprintf(stderr, \"%s: \", progname);\n        vfprintf(stderr, format, ap);\n        fprintf(stderr, \"\\n\");\n    }\n    va_end(ap);\n}\n\nstatic const char *opt_parse_arg(const char *opt, char *buf, size_t siz)\n{\n    const char *p = opt;\n    char *q = buf, *endq = q + siz;\n\n    if (0 == p)\n        return 0;\n\n    while (endq > q && '\\0' != *p && ',' != *p)\n    {\n        if ('\\\\' == p[0] && '\\0' != p[1])\n            p++;\n        *q++ = *p++;\n    }\n\n    if (endq == q || (buf == q && '\\0' == *p))\n        return 0;\n\n    *q++ = '\\0';\n    if ('\\0' != *p)\n        p++;\n\n    return p;\n}\n\nstatic void utf8_to_utf16(const char *src0, uint16_t *dst, size_t siz)\n{\n    const uint8_t *src = src0;\n    uint16_t *dstend = dst + siz / sizeof(uint16_t);\n\n    while (dstend > dst)\n    {\n        uint32_t c = *src++;\n        uint32_t w = 0xfffd; /* unicode replacement char */\n\n        if (0x80 > c)\n            w = c;\n        else if (0xc0 > c)\n            ;\n        else if (0xe0 > c)\n        {\n            c = (c & 0x1f) << 6;\n            if (0x80 != (*src & 0x80))\n                goto copy;\n            c |= *src++ & 0x3f;\n            w = c;\n        }\n        else if (0xf0 > c)\n        {\n            c = (c & 0x0f) << 12;\n            if (0x80 != (*src & 0x80))\n                goto copy;\n            c |= (uint32_t)(*src++ & 0x3f) << 6;\n            if (0x80 != (*src & 0x80))\n                goto copy;\n            c |= *src++ & 0x3f;\n            w = c;\n        }\n        else if (0xf8 > c)\n        {\n            /* we do not support true UTF-16; just skip over 3 continuation bytes */\n            if (0x80 != (*src & 0x80))\n                goto copy;\n            src++;\n            if (0x80 != (*src & 0x80))\n                goto copy;\n            src++;\n            if (0x80 != (*src & 0x80))\n                goto copy;\n            src++;\n        }\n\n    copy:\n        *dst++ = (uint16_t)w;\n\n        if (0 == c)\n            break;\n    }\n\n    if (sizeof(uint16_t) <= siz)\n        dstend[-1] = 0;\n}\n\nstatic int get_mnt_id(const char *mountpoint)\n{\n    FILE *file = 0;\n    char line[4096];\n    char path[4096];\n    int mnt_id = -1, m;\n\n    file = fopen(\"/proc/self/mountinfo\", \"rb\");\n    if (0 == file)\n        goto exit;\n\n    while (0 != fgets(line, sizeof line, file))\n    {\n        if (2 == sscanf(line, \"%d %*d %*s %*s %4096s %*s\", &m, path) &&\n            0 == strcmp(mountpoint, path))\n        {\n            mnt_id = m;\n            break;\n        }\n    }\n\n    if (-1 == mnt_id)\n        errno = ENODEV;\n\nexit:\n    if (0 != file)\n        fclose(file);\n\n    return mnt_id;\n}\n\nstatic void mount_opt_parse(struct mount_opts *mo)\n{\n    const char *opt;\n    char optbuf[4096], *optarg, *optval, empty = '\\0';\n\n    memset(mo, 0, sizeof *mo);\n\n    mo->VolumeParams.Version = sizeof(FSP_FSCTL_VOLUME_PARAMS);\n    mo->VolumeParams.FileInfoTimeout = 1000;\n    mo->VolumeParams.FlushAndPurgeOnCleanup = 1;\n\n    /*\n     * Libfuse does not recognize any of our options and rejects them.\n     * So (for now at least) prefix our options with \"context=\", which\n     * Libfuse accepts (to support SELinux).\n     *\n     * So to pass \"Volume=X:\" use \"context=Volume=X:\".\n     */\n\n    for (\n        opt = opt_parse_arg(args.opts, optbuf, sizeof optbuf);\n        0 != opt;\n        opt = opt_parse_arg(opt, optbuf, sizeof optbuf))\n    {\n        optarg = optbuf;\n        optval = strchr(optarg, '=');\n        if (0 != optval)\n            *optval++ = '\\0';\n        else\n            optval = &empty;\n\n        if (0 == strcmp(optarg, \"context\"))\n        {\n            optarg = optval;\n            optval = strchr(optarg, '=');\n            if (0 != optval)\n                *optval++ = '\\0';\n            else\n                optval = &empty;\n        }\n\n        if (0 == strcmp(optarg, \"Volume\"))\n        {\n            strncpy(mo->WinMountPoint, optval, sizeof mo->WinMountPoint);\n            mo->WinMountPoint[sizeof mo->WinMountPoint - 1] = '\\0';\n            for (char *P = mo->WinMountPoint; *P; P++)\n                if ('/' == *P)\n                    *P = '\\\\';\n        }\n        else if (0 == strcmp(optarg, \"attr_timeout\"))\n        {\n            mo->set_attr_timeout = 1;\n            mo->attr_timeout = (int)strtol(optval, 0, 10);\n        }\n        else if (0 == strcmp(optarg, \"SectorSize\"))\n            mo->VolumeParams.SectorSize = (UINT16)strtoul(optval, 0, 10);\n        else if (0 == strcmp(optarg, \"SectorsPerAllocationUnit\"))\n            mo->VolumeParams.SectorsPerAllocationUnit = (UINT16)strtoul(optval, 0, 10);\n        else if (0 == strcmp(optarg, \"MaxComponentLength\"))\n            mo->VolumeParams.MaxComponentLength = (UINT16)strtoul(optval, 0, 10);\n        else if (0 == strcmp(optarg, \"VolumeCreationTime\"))\n            mo->VolumeParams.VolumeCreationTime = (UINT64)strtol(optval, 0, 0);\n        else if (0 == strcmp(optarg, \"VolumeSerialNumber\"))\n            mo->VolumeParams.VolumeSerialNumber = (UINT32)strtoul(optval, 0, 16);\n        else if (0 == strcmp(optarg, \"FileInfoTimeout\"))\n        {\n            mo->set_FileInfoTimeout = 1;\n            mo->VolumeParams.FileInfoTimeout = (UINT32)strtol(optval, 0, 10);\n        }\n        else if (0 == strcmp(optarg, \"DirInfoTimeout\"))\n        {\n            mo->set_DirInfoTimeout = 1;\n            mo->VolumeParams.DirInfoTimeout = (UINT32)strtol(optval, 0, 10);\n        }\n        else if (0 == strcmp(optarg, \"EaTimeout\"))\n        {\n            mo->set_EaTimeout = 1;\n            mo->VolumeParams.EaTimeout = (UINT32)strtol(optval, 0, 10);\n        }\n        else if (0 == strcmp(optarg, \"VolumeInfoTimeout\"))\n        {\n            mo->set_VolumeInfoTimeout = 1;\n            mo->VolumeParams.VolumeInfoTimeout = (UINT32)strtol(optval, 0, 10);\n        }\n        else if (0 == strcmp(optarg, \"KeepFileCache\"))\n            mo->set_KeepFileCache = 1;\n        else if (0 == strcmp(optarg, \"UNC\") || 0 == strcmp(optarg, \"VolumePrefix\"))\n        {\n            utf8_to_utf16(optval, mo->VolumeParams.Prefix,\n                sizeof mo->VolumeParams.Prefix);\n            for (WCHAR *P = mo->VolumeParams.Prefix; *P; P++)\n                if ('/' == *P)\n                    *P = '\\\\';\n        }\n        else if (0 == strcmp(optarg, \"FileSystemName\"))\n        {\n            utf8_to_utf16(\"FUSE-\", mo->VolumeParams.FileSystemName,\n                sizeof mo->VolumeParams.FileSystemName);\n            utf8_to_utf16(optval, mo->VolumeParams.FileSystemName + 5,\n                sizeof mo->VolumeParams.FileSystemName - 5 * sizeof(WCHAR));\n        }\n    }\n\n    if (!mo->set_FileInfoTimeout && mo->set_attr_timeout)\n        mo->VolumeParams.FileInfoTimeout = (UINT32)(mo->attr_timeout * 1000);\n    if (mo->set_DirInfoTimeout)\n        mo->VolumeParams.DirInfoTimeoutValid = 1;\n    if (mo->set_EaTimeout)\n        mo->VolumeParams.EaTimeoutValid = 1;\n    if (mo->set_VolumeInfoTimeout)\n        mo->VolumeParams.VolumeInfoTimeoutValid = 1;\n    if (mo->set_KeepFileCache)\n        mo->VolumeParams.FlushAndPurgeOnCleanup = 0;\n    mo->VolumeParams.CaseSensitiveSearch = 1;\n    mo->VolumeParams.CasePreservedNames = 1;\n    mo->VolumeParams.PersistentAcls = 1;\n    mo->VolumeParams.ReparsePoints = 1;\n    mo->VolumeParams.ReparsePointsAccessCheck = 0;\n    mo->VolumeParams.NamedStreams = 0;\n    mo->VolumeParams.ReadOnlyVolume = 0;\n    mo->VolumeParams.PostCleanupWhenModifiedOnly = 1;\n    mo->VolumeParams.PassQueryDirectoryFileName = 1;\n    mo->VolumeParams.DeviceControl = 1;\n    if ('\\0' == mo->VolumeParams.FileSystemName[0])\n        utf8_to_utf16(\"FUSE\", mo->VolumeParams.FileSystemName,\n            sizeof mo->VolumeParams.FileSystemName);\n\n    if (mo->VolumeParams.SectorSize < 512 ||\n        mo->VolumeParams.SectorSize > 4096)\n        mo->VolumeParams.SectorSize = 4096;\n    if (mo->VolumeParams.SectorsPerAllocationUnit == 0)\n        mo->VolumeParams.SectorsPerAllocationUnit = 1;\n    if (0 == mo->VolumeParams.MaxComponentLength || mo->VolumeParams.MaxComponentLength > 255)\n        mo->VolumeParams.MaxComponentLength = 255;\n    if (0 == mo->VolumeParams.VolumeCreationTime)\n    {\n        struct timeval tv = { 0 };\n        gettimeofday(&tv, 0);\n        mo->VolumeParams.VolumeCreationTime = (UINT64)\n            ((int64_t)tv.tv_sec * 10000000 + (int64_t)tv.tv_usec * 10 + 116444736000000000LL);\n    }\n    if (0 == mo->VolumeParams.VolumeSerialNumber)\n        mo->VolumeParams.VolumeSerialNumber =\n            (UINT32)(mo->VolumeParams.VolumeCreationTime >> 32) ^\n            (UINT32)(mo->VolumeParams.VolumeCreationTime & 0xffffffff);\n}\n\nstatic int start_winmount_helper(const char *VolumeName, char WinMountPoint[260], pid_t *pidp, int *ofdp)\n{\n    int success = 0;\n    pid_t pid;\n    int ifd[2] = { -1, -1 };\n    int ofd[2] = { -1, -1 };\n    char *argv[4];\n    char *p, *endp;\n    ssize_t bytes;\n\n    *pidp = -1;\n    *ofdp = -1;\n\n    if (-1 == pipe(ifd) || -1 == pipe(ofd))\n    {\n        warn(\"winmount: cannot create pipe: %s\", strerror(errno));\n        goto exit;\n    }\n\n    argv[0] = \"/usr/bin/fusermount-helper.exe\";\n    argv[1] = (char *)VolumeName;\n    argv[2] = '\\0' != WinMountPoint[0] ? (char *)WinMountPoint : 0;\n    argv[3] = 0;\n\n    pid = fork();\n    if (-1 == pid)\n    {\n        warn(\"winmount: cannot fork: %s\", strerror(errno));\n        goto exit;\n    }\n    else if (0 != pid)\n        *pidp = pid;\n    else\n    {\n        /* drop privileges */\n        uid_t uid = getuid();\n        gid_t gid = getgid();\n        setgroups(1, &gid);\n        setreuid(uid, uid);\n        setregid(gid, gid);\n\n        if (-1 == dup2(ifd[1], 1) || -1 == dup2(ofd[0], 0))\n        {\n            warn(\"winmount: cannot dup2: %s\", strerror(errno));\n            exit(1);\n        }\n        close(ofd[1]);\n        close(ofd[0]);\n        close(ifd[1]);\n        close(ifd[0]);\n\n        if (-1 == execv(argv[0], argv))\n            warn(\"winmount: cannot execute %s: %s\", argv[0], strerror(errno));\n        exit(1);\n    }\n\n    close(ifd[1]); ifd[1] = -1;\n    close(ofd[0]); ofd[0] = -1;\n\n    for (p = WinMountPoint, endp = WinMountPoint + 260 - 1; endp > p; p += bytes)\n    {\n        bytes = read(ifd[0], p, (size_t)(endp - p));\n        if (-1 == bytes)\n        {\n            if (EINTR != errno)\n            {\n                warn(\"winmount: cannot read output: %s\", strerror(errno));\n                goto exit;\n            }\n            bytes = 0;\n        }\n        else if (0 == bytes || 0 != memchr(p, 0, (size_t)bytes))\n        {\n            p += bytes;\n            break;\n        }\n    }\n    *p = '\\0';\n\n    if (WinMountPoint == p)\n    {\n        warn(\"winmount: no output\");\n        goto exit;\n    }\n\n    close(ifd[0]); ifd[0] = -1;\n\n    *ofdp = ofd[1]; ofd[1] = -1;\n\n    success = 1;\n\nexit:\n    if (-1 != ofd[1])\n        close(ofd[1]);\n    if (-1 != ofd[0])\n        close(ofd[0]);\n\n    if (-1 != ifd[1])\n        close(ifd[1]);\n    if (-1 != ifd[0])\n        close(ifd[0]);\n\n    return success ? 0 : -1;\n}\n\nstatic void stop_winmount_helper(pid_t pid, int ofd)\n{\n    ssize_t bytes;\n    (void)bytes;\n\n    bytes = write(ofd, \"STOP\", 4 + 1);\n    close(ofd);\n\n    waitpid(pid, 0, 0);\n}\n\nstatic int spawn_lxmount_helper(char WinMountPoint[260], const char *mountpoint, int fusefd, UINT64 VolumeId)\n{\n    /*\n     * Spawn a child process to perform a Linux mount of the WinFsp volume asynchronously.\n     *\n     * This is necessary to avoid the deadlock described below.\n     *\n     * First observe that when mount(2) happens the FUSE file system is not yet ready to\n     * accept file system requests. So any file system request will be queued within WinFsp\n     * and will not be retrieved by the FUSE file system until after (it thinks that) the\n     * mount(2) has completed.\n     *\n     * Now when mount(2) is invoked with type \"drvfs\", LXCORE attempts to open the volume\n     * passed in the source argument (e.g. if the source argument is \"Z:\", then LXCORE will\n     * attempt to open volume \"Z:\"). This should normally not be a problem because WinFsp\n     * handles volume opens without forwarding them to the user mode file system. Unfortunately\n     * some system filters convert a volume (\"Z:\") open request to a root directory (\"Z:\\\")\n     * open request, which is a request that must be handled by the user mode file system.\n     * But the user mode file system is waiting for the mount/fusermount to complete, before it\n     * can process requests. Hence deadlock!\n     *\n     * In order to work around this problem we perform the mount(2) asynchronously in a child\n     * process. This of course means that we lie to the FUSE file system that the mount(2) was\n     * successful, thus allowing it to process the root directory open request, which then\n     * allows the mount(2) call to complete. The drawback is that if the mount(2) fails for\n     * some reason the FUSE file system never hears about it. (However this is not considered\n     * a huge problem, because the FUSE file system will still service the Windows drive that\n     * we allocated for it correctly (see start_winmount_helper).)\n     */\n\n    pid_t pid;\n    int status;\n\n    /* fork the intermediate process */\n    pid = fork();\n    if (-1 == pid)\n    {\n        warn(\"lxmount: cannot fork intermediate process: %s\", strerror(errno));\n        return -1;\n    }\n    else if (0 != pid)\n    {\n        /* wait for the intermediate process */\n\t\treturn\n            pid == waitpid(pid, &status, 0) && WIFEXITED(status) && 0 == WEXITSTATUS(status) ?\n            0 :\n            -1;\n    }\n\n    /* become a session leader and ignore SIGHUP */\n    setsid();\n    signal(SIGHUP, SIG_IGN);\n\n    /* fork a second time to get the process that will perform the Linux mount */\n    pid = fork();\n    if (-1 == pid)\n    {\n        warn(\"lxmount: cannot fork mount process: %s\", strerror(errno));\n        exit(1);\n    }\n    else if (0 != pid)\n        /* exit the intermediate process; our child will be reaped by the init process */\n        exit(0);\n\n    /*\n     * MOUNT PROCESS\n     *\n     * Grand-child of original fusermount process.\n     */\n    int success = 0;\n    int mounted = 0, mnt_id;\n    WSLFUSE_IOCTL_LXMOUNT_ARG LxMountArg;\n\n    /*\n     * Close the passed fusefd and reopen /dev/fuse. We will use the reopened fd\n     * to communicate with WslFuse using special ioctl's.\n     *\n     * The reason for this is subtle: consider the earlier discussed deadlock and\n     * the case where the FUSE file system fails to service the root directory open\n     * request (e.g. because it crashed). Now we are in a situation where mount(2)\n     * is waiting for a root directory open request to complete; this request is stuck\n     * inside WinFsp; it has been retrieved by wslfuse and is either pending or\n     * processing within the FUSE file system. Suppose now that the file system\n     * terminates abruptly for some reason. The open request will never complete and\n     * hence (a form of) deadlock again!\n     *\n     * Normally this is not a problem because upon termination of the FUSE process\n     * all its file descriptors will be closed and WslFuse and WinFsp will have a\n     * chance to purge their internal I/O queues thus canceling the root directory\n     * open request, which allows mount(2) to complete. However when we forked our\n     * mount process, the original fusefd was cloned and this keeps our internal I/O\n     * queues alive. For this reason we have to close the fusefd in the mount process.\n     */\n    close(fusefd);\n    fusefd = open(\"/dev/fuse\", O_RDWR);\n    if (-1 == fusefd)\n    {\n        warn(\"lxmount: cannot open /dev/fuse: %s\", strerror(errno));\n        goto exit;\n    }\n\n    /*\n     * Mount the WinFsp volume using drvfs.\n     */\n    if (-1 == mount(WinMountPoint, mountpoint, \"drvfs\", 0, 0))\n    {\n        warn(\"lxmount: cannot mount %s: %s\", mountpoint, strerror(errno));\n        goto exit;\n    }\n    mounted = 1;\n\n    /*\n     * Get the mnt_id of the newly mounted file system.\n     */\n    mnt_id = get_mnt_id(mountpoint);\n    if (-1 == mnt_id)\n    {\n        warn(\"lxmount: cannot get mnt_id: %s\", strerror(errno));\n        goto exit;\n    }\n\n    /*\n     * Associate the WSL mnt_id with the /dev/fuse fd.\n     */\n    memset(&LxMountArg, 0, sizeof LxMountArg);\n    LxMountArg.Operation = '+';\n    LxMountArg.VolumeId = VolumeId;\n    LxMountArg.LxMountId = (UINT64)mnt_id;\n    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg))\n    {\n        warn(\"lxmount: cannot ioctl(m) /dev/fuse: %s\", strerror(errno));\n        goto exit;\n    }\n\n    success = 1;\n\nexit:\n    if (!success)\n    {\n        if (mounted)\n            umount2(mountpoint, UMOUNT_NOFOLLOW);\n    }\n\n    exit(success ? 0 : 1);\n\n    /* should not happen */\n    return -1;\n}\n\nstatic void do_mount(void)\n{\n    int success = 0;\n    struct mount_opts mo;\n    const char *env;\n    int commfd, fusefd = -1;\n    WSLFUSE_IOCTL_CREATEVOLUME_ARG CreateArg;\n    WSLFUSE_IOCTL_WINMOUNT_ARG WinMountArg;\n    pid_t winmount_pid = -1;\n    int winmount_fd = -1;\n    struct msghdr msg;\n    struct cmsghdr *cmsg;\n    char cmsgbuf[CMSG_SPACE(sizeof fusefd)];\n    struct iovec iov;\n    char dummy = 0;\n\n    mount_opt_parse(&mo);\n\n    /*\n     * Get the socket fd sent to us by the file system (via libfuse) from the environment.\n     * We will use this fd to send our /dev/fuse fd to the file system once mounting completes.\n     */\n    env = getenv(\"_FUSE_COMMFD\");\n    if (0 == env)\n    {\n        warn(\"mount: environment variable _FUSE_COMMFD missing\");\n        goto exit;\n    }\n    commfd = atoi(env);\n\n    /*\n     * Open the /dev/fuse device. We use the returned fd to communicate with WslFuse using\n     * special ioctl's. We will also return the fd to the file system via COMMFD.\n     */\n    fusefd = open(\"/dev/fuse\", O_RDWR);\n    if (-1 == fusefd)\n    {\n        warn(\"mount: cannot open /dev/fuse: %s\", strerror(errno));\n        goto exit;\n    }\n\n    /*\n     * Send an ioctl to instruct WslFuse to create a new WinFsp volume.\n     */\n    memset(&CreateArg, 0, sizeof CreateArg);\n    memcpy(&CreateArg.VolumeParams, &mo.VolumeParams, sizeof mo.VolumeParams);\n    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_CREATEVOLUME, &CreateArg))\n    {\n        warn(\"mount: cannot ioctl(C) /dev/fuse: %s\", strerror(errno));\n        goto exit;\n    }\n\n    /*\n     * Start the Windows side helper process to create the Windows mount point.\n     */\n    if (-1 == start_winmount_helper(CreateArg.VolumeName, mo.WinMountPoint, &winmount_pid, &winmount_fd))\n        goto exit;\n\n    /*\n     * Associate the Windows mount point with the /dev/fuse fd.\n     */\n    memset(&WinMountArg, 0, sizeof WinMountArg);\n    memcpy(WinMountArg.WinMountPoint, mo.WinMountPoint, sizeof WinMountArg.WinMountPoint);\n    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_WINMOUNT, &WinMountArg))\n    {\n        warn(\"mount: cannot ioctl(M) /dev/fuse: %s\", strerror(errno));\n        goto exit;\n    }\n\n    /*\n     * Send the /dev/fuse fd to the file system using COMMFD.\n     */\n    memset(&msg, 0, sizeof msg);\n    msg.msg_control = cmsgbuf;\n    msg.msg_controllen = sizeof cmsgbuf;\n    cmsg = CMSG_FIRSTHDR(&msg);\n    cmsg->cmsg_level = SOL_SOCKET;\n    cmsg->cmsg_type = SCM_RIGHTS;\n    cmsg->cmsg_len = CMSG_LEN(sizeof fusefd);\n    memcpy(CMSG_DATA(cmsg), &fusefd, sizeof fusefd);\n    msg.msg_controllen = cmsg->cmsg_len;\n    msg.msg_iov = &iov;\n    msg.msg_iovlen = 1;\n    iov.iov_base = &dummy;\n    iov.iov_len = sizeof dummy;\n    while (-1 == sendmsg(commfd, &msg, 0))\n        if (EINTR != errno)\n        {\n            warn(\"mount: cannot sendmsg to _FUSE_COMMFD: %s\", strerror(errno));\n            goto exit;\n        }\n\n    /*\n     * Spawn a child process to perform a Linux mount of the WinFsp volume asynchronously.\n     */\n    if (-1 == spawn_lxmount_helper(mo.WinMountPoint, args.mountpoint, fusefd, CreateArg.VolumeId))\n        goto exit;\n\n    success = 1;\n\nexit:\n    if (-1 != winmount_pid)\n        stop_winmount_helper(winmount_pid, winmount_fd);\n\n    if (-1 != fusefd)\n        close(fusefd);\n\n    if (!success)\n        exit(1);\n\n    exit(0);\n}\n\nstatic void do_unmount(void)\n{\n    int success = 0;\n    int fusefd = -1;\n    int mnt_id;\n    WSLFUSE_IOCTL_LXMOUNT_ARG LxMountArg;\n\n    /*\n     * Open the /dev/fuse device.\n     */\n    fusefd = open(\"/dev/fuse\", O_RDWR);\n    if (-1 == fusefd)\n    {\n        warn(\"unmount: cannot open /dev/fuse: %s\", strerror(errno));\n        goto exit;\n    }\n\n    /*\n     * Get the mnt_id of the previously mounted file system.\n     */\n    mnt_id = get_mnt_id(args.mountpoint);\n    if (-1 == mnt_id)\n    {\n        warn(\"unmount: cannot get mnt_id: %s\", strerror(errno));\n        goto exit;\n    }\n\n    /*\n     * Verify the WSL mnt_id with WslFuse.\n     */\n    memset(&LxMountArg, 0, sizeof LxMountArg);\n    LxMountArg.Operation = '?';\n    LxMountArg.LxMountId = (UINT64)mnt_id;\n    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg))\n    {\n        warn(\"unmount: unknown mountpoint %s\", args.mountpoint);\n        goto exit;\n    }\n\n    /*\n     * Unmount the previously mounted file system.\n     */\n    if (-1 == umount2(args.mountpoint, args.lazy ? MNT_DETACH : 0))\n        /* UMOUNT_NOFOLLOW not supported in WSL1 */\n    {\n        warn(\"unmount: cannot unmount %s: %s\", args.mountpoint, strerror(errno));\n        goto exit;\n    }\n\n    /*\n     * Disassociate the WSL mnt_id from the /dev/fuse fd.\n     */\n    memset(&LxMountArg, 0, sizeof LxMountArg);\n    LxMountArg.Operation = '-';\n    LxMountArg.LxMountId = (UINT64)mnt_id;\n    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg) && ENOENT != errno)\n    {\n        warn(\"unmount: cannot ioctl(m) /dev/fuse: %s\", strerror(errno));\n        goto exit;\n    }\n\n    success = 1;\n\nexit:\n    if (-1 != fusefd)\n        close(fusefd);\n\n    if (!success)\n        exit(1);\n\n    exit(0);\n}\n\nstatic char *realpath_parent(const char *path)\n{\n    char *resolved = 0;\n    char *pathcopy[2] = { 0, 0 };\n    const char *parent, *leaf;\n    char linkbuf[PATH_MAX];\n    size_t rlen, llen;\n\n    pathcopy[0] = strdup(path);\n    if (0 == pathcopy[0])\n        goto fail;\n    pathcopy[1] = strdup(path);\n    if (0 == pathcopy[1])\n        goto fail;\n\n    resolved = malloc(PATH_MAX);\n    if (0 == resolved)\n        goto fail;\n\n    parent = dirname(pathcopy[0]);\n    leaf = basename(pathcopy[1]);\n\n    if (0 == realpath(parent, resolved))\n        goto fail;\n\n    rlen = strlen(resolved);\n    llen = strlen(leaf);\n    if (PATH_MAX < rlen + llen + 2)\n    {\n        errno = ENAMETOOLONG;\n        goto fail;\n    }\n    resolved[rlen] = '/';\n    memcpy(resolved + rlen + 1, leaf, llen);\n    resolved[rlen + 1 + llen] = '\\0';\n\n    if (-1 != readlink(resolved, linkbuf, sizeof linkbuf))\n    {\n        errno = EINVAL;\n        goto fail;\n    }\n    else if (EINVAL != errno)\n        goto fail;\n\n    free(pathcopy[1]);\n    free(pathcopy[0]);\n\n    return resolved;\n\nfail:\n    free(resolved);\n\n    free(pathcopy[1]);\n    free(pathcopy[0]);\n\n    return 0;\n}\n\nstatic void do_version(void)\n{\n    fprintf(stdout, \"%s version: %s\\n\", progname, \"wslfuse\");\n    exit(0);\n}\n\nstatic void usage(void)\n{\n    warn(\n        \"%s: [options] mountpoint\\n\"\n        \"Options:\\n\"\n        \"    -h                          print help\\n\"\n        \"    -V                          print version\\n\"\n        \"    -o opt[,opt...]             mount options\\n\"\n        \"    -u                          unmount\\n\"\n        \"    -z                          lazy unmount\\n\"\n        \"    -q                          quiet\\n\"\n        \"\",\n        progname);\n    exit(2);\n}\n\nint main(int argc, char *argv[])\n{\n    progname = basename(argv[0]);\n\n    static struct option longopts[] =\n    {\n        { \"help\", no_argument, 0, 'h' },\n        { \"version\", no_argument, 0, 'V' },\n        { \"unmount\", no_argument, 0, 'u' },\n        { \"lazy\", no_argument, 0, 'z' },\n        { \"quiet\", no_argument, 0, 'q' },\n        { 0 },\n    };\n    int quiet = 0;\n    int opt;\n    while (-1 != (opt = getopt_long(argc, argv, \"hVo:uzq\", longopts, 0)))\n        switch (opt)\n        {\n        default:\n        case 'h':\n            usage();\n            break;\n        case 'V':\n            do_version();\n            break;\n        case 'o':\n            args.opts = optarg;\n            break;\n        case 'u':\n            args.unmount = 1;\n            break;\n        case 'z':\n            args.lazy = 1;\n            break;\n        case 'q':\n            quiet = 1;\n            break;\n        }\n\n    if (argc != optind + 1)\n        usage();\n    args.quiet = quiet;\n\n    if (!args.unmount)\n        args.mountpoint = realpath(argv[optind], 0);\n    else\n        args.mountpoint = realpath_parent(argv[optind]);\n    if (0 == args.mountpoint)\n    {\n        warn(\"mountpoint: %s\", strerror(errno));\n        exit(1);\n    }\n\n    if (!args.unmount)\n        do_mount();\n\n    do_unmount();\n\n    return 0;\n}\n"
  },
  {
    "path": "src/fusermount/install.sh",
    "content": "set -e\n\nif [ \"$(id -u)\" != \"0\" ]; then\n    echo \"must be run as superuser\" 1>&2; exit 1\nfi\n\ncd \"$(dirname \"$0\")\"\n\n# fusermount\ncmp_install()\n{\n    local src=\"\"\n    local dst=\"\"\n    for arg in \"$@\"; do src=\"$dst\"; dst=\"$arg\"; done\n    cmp -s \"$src\" \"$dst\" || install \"$@\"\n}\ncmp_install --backup=numbered -o0 -g0 -mu=srwx,go=rx fusermount.out /usr/bin/fusermount\ncmp_install --backup=numbered -o0 -g0 -mu=srwx,go=rx fusermount.out /usr/bin/fusermount3\ncmp_install -o0 -g0 -mu=rwx,go=rx fusermount-helper.exe /usr/bin/fusermount-helper.exe\n\n# /dev/fuse\necho c /dev/fuse 0666 root root - 10:229 > /etc/tmpfiles.d/wslfuse.conf\nsystemd-tmpfiles --create wslfuse.conf\n\necho FUSE for WSL1 user space components installed\n"
  },
  {
    "path": "src/fusermount/uninstall.sh",
    "content": "#set -x\n\nif [ \"$(id -u)\" != \"0\" ]; then\n    echo \"must be run as superuser\" 1>&2; exit 1\nfi\n\ncd \"$(dirname \"$0\")\"\n\n# /dev/fuse\nrm -f /etc/tmpfiles.d/wslfuse.conf\nrm -f /dev/fuse\n\n# fusermount\nuninstall()\n{\n    local src=\"$1\"\n    local dst=\"$2\"\n    if cmp -s \"$src\" \"$dst\"; then\n        local bak=$(ls -1rv \"$dst\".~*~ 2>/dev/null | head -1)\n        if [ -n \"$bak\" ]; then\n            mv -f \"$bak\" \"$dst\"\n        else\n            rm -f \"$dst\"\n        fi\n    fi\n}\nuninstall fusermount.out /usr/bin/fusermount\nuninstall fusermount.out /usr/bin/fusermount3\nrm -f /usr/bin/fusermount-helper.exe\n\necho FUSE for WSL1 user space components uninstalled\n"
  },
  {
    "path": "src/shared/km/cache.c",
    "content": "/**\n * @file shared/km/cache.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\n/*\n * FUSE \"entry\" cache\n *\n * The cache is implemented as a hash table that maps parent inode number, child name\n * tuples to FUSE protocol \"entries\":\n *     <parent_ino, child_name> -> <child_ino, child_attr> (\"entry\")\n *\n * There are two important complications:\n *\n * (1) Entries have an expiration time after which they may no longer be valid.\n * Entries that have expired must not be returned to users of this class and must eventually\n * be \"forgotten\" (i.e. a FUSE FORGET message must be sent to the user mode file system).\n *\n * (2) Entries may be in use when they become expired/invalid. In this case the\n * corresponding FORGET message must be delayed to ensure that the user mode file system\n * keeps the relevant inode information around (even if the associated information is\n * expired).\n *\n * To accommodate complication (1) this implementation maintains cached entries in an LRU\n * (least-recently-used) list and expires them periodically. It should be noted that this\n * implementation does not sort entries by expiration time; so it is possible for an entry\n * that has not expired but was not recently used to be purged prior to an entry that has\n * expired, but was recently used.\n *\n * To accommodate complication (2) this implementation maintains a list of monotonic\n * \"generations\" that control when entries are actually \"forgotten\". As file system\n * operations arrive, the current generation is computed from the \"interrupt time\"\n * and a reference is taken on that generation (i.e. a reference count is incremented).\n * When the operation is complete the reference on the associated generation is released\n * (i.e. the reference count is decremented). If there are no remaining references on the\n * generation (i.e. the reference count is zero) the generation can be \"forgotten\", which\n * means that all entries that have expired and have not been used since the generation's\n * time can now be \"forgotten\" (i.e. the corresponding FUSE messages can be sent).\n *\n * These two primary complications together with the fact that the implementation must\n * deal with failures and re-setting existing entries make the code rather complicated.\n */\n\nNTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_CACHE **PCache);\nVOID FuseCacheDelete(FUSE_CACHE *Cache);\nVOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache,\n    FUSE_INSTANCE *Instance, UINT64 ExpirationTime);\nNTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen);\nVOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen);\nBOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,\n    FUSE_PROTO_ENTRY *Entry, PVOID *PItem);\nVOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,\n    FUSE_PROTO_ENTRY *Entry, PVOID *PItem);\nVOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name);\nVOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item);\nVOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item);\nVOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item);\nVOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList);\nBOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE *PForgetOne);\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(PAGE, FuseCacheCreate)\n#pragma alloc_text(PAGE, FuseCacheDelete)\n#pragma alloc_text(PAGE, FuseCacheExpirationRoutine)\n#pragma alloc_text(PAGE, FuseCacheReferenceGen)\n#pragma alloc_text(PAGE, FuseCacheDereferenceGen)\n#pragma alloc_text(PAGE, FuseCacheGetEntry)\n#pragma alloc_text(PAGE, FuseCacheSetEntry)\n#pragma alloc_text(PAGE, FuseCacheRemoveEntry)\n#pragma alloc_text(PAGE, FuseCacheReferenceItem)\n#pragma alloc_text(PAGE, FuseCacheDereferenceItem)\n#pragma alloc_text(PAGE, FuseCacheQuickExpireItem)\n#pragma alloc_text(PAGE, FuseCacheDeleteForgotten)\n#pragma alloc_text(PAGE, FuseCacheForgetOne)\n#endif\n\ntypedef struct _FUSE_CACHE_ITEM FUSE_CACHE_ITEM;\n\nstruct _FUSE_CACHE\n{\n    ULONG Capacity;\n    BOOLEAN CaseInsensitive;\n    FAST_MUTEX Mutex;\n    LIST_ENTRY GenList;\n    LIST_ENTRY ItemList;\n    LIST_ENTRY ForgetList;\n    ULONG ItemCount;\n    ULONG ItemBucketCount;\n    PVOID ItemBuckets[];\n};\n\nstruct _FUSE_CACHE_GEN\n{\n    LIST_ENTRY ListEntry;\n    LONG RefCount;\n    UINT64 InterruptTime;\n};\n\nstruct _FUSE_CACHE_ITEM\n{\n    struct _FUSE_CACHE_ITEM *DictNext;\n    LIST_ENTRY ListEntry;\n    BOOLEAN NoForget;\n    ULONG Hash;\n    UINT64 ParentIno;\n    STRING Name;\n    UINT64 NLookup;\n    UINT64 ExpirationTime;\n    UINT64 LastUsedTime;\n    FUSE_PROTO_ENTRY Entry;\n    LONG QuickExpiry;\n    LONG RefCount;\n    CHAR NameBuf[];\n};\n\nstatic inline UINT64 FuseCacheForgetTime(FUSE_CACHE *Cache, UINT64 InterruptTime)\n{\n    if (!IsListEmpty(&Cache->GenList))\n    {\n        FUSE_CACHE_GEN *Gen = CONTAINING_RECORD(Cache->GenList.Flink, FUSE_CACHE_GEN, ListEntry);\n        if (InterruptTime >= Gen->InterruptTime)\n            InterruptTime = Gen->InterruptTime - 1;\n    }\n    return InterruptTime;\n}\n\nstatic inline BOOLEAN FuseCacheForgetNextItem(FUSE_CACHE *Cache,\n    UINT64 ExpirationTime, PLIST_ENTRY ForgetList)\n{\n    if (!IsListEmpty(&Cache->ForgetList))\n    {\n        FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Cache->ForgetList.Flink, FUSE_CACHE_ITEM, ListEntry);\n        if (FuseCacheForgetTime(Cache, ExpirationTime) >= Item->LastUsedTime)\n        {\n            RemoveEntryList(&Item->ListEntry);\n            InsertTailList(ForgetList, &Item->ListEntry);\n            return TRUE;\n        }\n    }\n    return FALSE;\n}\n\nstatic inline BOOLEAN FuseCacheExpireItem(FUSE_CACHE *Cache,\n    FUSE_CACHE_ITEM *Item)\n{\n    ULONG HashIndex = Item->Hash % Cache->ItemBucketCount;\n    for (FUSE_CACHE_ITEM **P = (PVOID)&Cache->ItemBuckets[HashIndex]; *P; P = &(*P)->DictNext)\n        if (*P == Item)\n        {\n            *P = (*P)->DictNext;\n            RemoveEntryList(&Item->ListEntry);\n            Cache->ItemCount--;\n            if (0 == InterlockedDecrement(&Item->RefCount))\n                InsertTailList(&Cache->ForgetList, &Item->ListEntry);\n            return TRUE;\n        }\n    return FALSE;\n}\n\nstatic inline BOOLEAN FuseCacheExpireNextItem(FUSE_CACHE *Cache,\n    UINT64 ExpirationTime)\n{\n    if (!IsListEmpty(&Cache->ItemList))\n    {\n        FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Cache->ItemList.Flink, FUSE_CACHE_ITEM, ListEntry);\n        if (ExpirationTime >= Item->ExpirationTime ||\n            InterlockedCompareExchange(&Item->QuickExpiry, 1, 1))\n            return FuseCacheExpireItem(Cache, Item);\n    }\n    return FALSE;\n}\n\nstatic inline size_t hash_chars(const char *s, size_t length)\n{\n    /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */\n    size_t h = 5381;\n    for (const char *t = s + length; t > s; ++s)\n        h = 33 * h + *s;\n    return h;\n}\n\nstatic inline size_t hash_upper_chars(const char *s, size_t length)\n{\n    /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */\n    size_t h = 5381;\n    for (const char *t = s + length; t > s; ++s)\n        h = 33 * h + RtlUpperChar(*s);\n    return h;\n}\n\nstatic inline ULONG FuseCacheHash(UINT64 ParentIno, PSTRING Name, BOOLEAN CaseInsensitive)\n{\n    return (ULONG)FuseHashMix64(ParentIno) ^\n        (0 != Name ? (ULONG)(CaseInsensitive ?\n            hash_upper_chars(Name->Buffer, Name->Length) : hash_chars(Name->Buffer, Name->Length)) : 0);\n}\n\nstatic inline FUSE_CACHE_ITEM *FuseCacheLookupHashedItem(FUSE_CACHE *Cache,\n    ULONG Hash, UINT64 ParentIno, PSTRING Name)\n{\n    FUSE_CACHE_ITEM *Item = 0;\n    ULONG HashIndex = Hash % Cache->ItemBucketCount;\n    for (FUSE_CACHE_ITEM *ItemX = Cache->ItemBuckets[HashIndex]; ItemX; ItemX = ItemX->DictNext)\n        if (ItemX->Hash == Hash &&\n            ItemX->ParentIno == ParentIno &&\n            RtlEqualString(&ItemX->Name, Name, Cache->CaseInsensitive))\n        {\n            Item = ItemX;\n            break;\n        }\n    return Item;\n}\n\nstatic inline VOID FuseCacheAddItem(FUSE_CACHE *Cache,\n    FUSE_CACHE_ITEM *Item)\n{\n    ULONG HashIndex = Item->Hash % Cache->ItemBucketCount;\n#if DBG\n    for (FUSE_CACHE_ITEM *ItemX = Cache->ItemBuckets[HashIndex]; ItemX; ItemX = ItemX->DictNext)\n        if (ItemX->Hash == Item->Hash &&\n            ItemX->ParentIno == Item->ParentIno &&\n            RtlEqualString(&ItemX->Name, &Item->Name, Cache->CaseInsensitive))\n        {\n            ASSERT(0);\n        }\n#endif\n    Item->DictNext = Cache->ItemBuckets[HashIndex];\n    Cache->ItemBuckets[HashIndex] = Item;\n    /* mark as most-recently used */\n    InsertTailList(&Cache->ItemList, &Item->ListEntry);\n    Cache->ItemCount++;\n}\n\nstatic inline FUSE_CACHE_ITEM *FuseCacheUpdateHashedItem(FUSE_CACHE *Cache,\n    ULONG Hash, UINT64 ParentIno, PSTRING Name,\n    UINT64 ExpirationTime, UINT64 LastUsedTime, FUSE_PROTO_ENTRY *Entry)\n{\n    FUSE_CACHE_ITEM *Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name);\n    if (0 != Item)\n    {\n        if (Entry->nodeid == Item->Entry.nodeid &&\n            !InterlockedCompareExchange(&Item->QuickExpiry, 1, 1))\n        {\n            Item->NLookup++;\n            Item->ExpirationTime = ExpirationTime;\n            Item->LastUsedTime = LastUsedTime;\n            RtlCopyMemory(&Item->Entry, Entry, sizeof Item->Entry);\n\n            /* mark as most-recently used */\n            RemoveEntryList(&Item->ListEntry);\n            InsertTailList(&Cache->ItemList, &Item->ListEntry);\n        }\n        else\n        {\n            FuseCacheExpireItem(Cache, Item);\n            Item = 0;\n        }\n    }\n    return Item;\n}\n\nNTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_CACHE **PCache)\n{\n    PAGED_CODE();\n\n    FUSE_CACHE *Cache;\n    ULONG CacheSize;\n\n    *PCache = 0;\n\n    if (0 == Capacity)\n        Capacity = ((PAGE_SIZE - sizeof *Cache) / sizeof Cache->ItemBuckets[0]) * 3 / 4;\n\n    CacheSize = (Capacity * 4 / 3) * sizeof Cache->ItemBuckets[0] + sizeof *Cache;\n    CacheSize = FSP_FSCTL_ALIGN_UP(CacheSize, PAGE_SIZE);\n\n    Cache = FuseAllocNonPaged(CacheSize);\n        /* FAST_MUTEX's must be in non-paged memory */\n    if (0 == Cache)\n        return STATUS_INSUFFICIENT_RESOURCES;\n\n    RtlZeroMemory(Cache, CacheSize);\n    Cache->Capacity = Capacity;\n    Cache->CaseInsensitive = CaseInsensitive;\n    ExInitializeFastMutex(&Cache->Mutex);\n    InitializeListHead(&Cache->GenList);\n    InitializeListHead(&Cache->ItemList);\n    InitializeListHead(&Cache->ForgetList);\n    Cache->ItemBucketCount = (CacheSize - sizeof *Cache) / sizeof Cache->ItemBuckets[0];\n\n    *PCache = Cache;\n\n    return STATUS_SUCCESS;\n}\n\nVOID FuseCacheDelete(FUSE_CACHE *Cache)\n{\n    PAGED_CODE();\n\n    for (PLIST_ENTRY Entry = Cache->GenList.Flink; &Cache->GenList != Entry;)\n    {\n        FUSE_CACHE_GEN *Gen = CONTAINING_RECORD(Entry, FUSE_CACHE_GEN, ListEntry);\n        Entry = Entry->Flink;\n        FuseFree(Gen);\n    }\n\n    FuseCacheDeleteForgotten(&Cache->ItemList);\n    FuseCacheDeleteForgotten(&Cache->ForgetList);\n\n    FuseFree(Cache);\n}\n\nVOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache,\n    FUSE_INSTANCE *Instance, UINT64 ExpirationTime)\n{\n    PAGED_CODE();\n\n    LIST_ENTRY ForgetList;\n\n    InitializeListHead(&ForgetList);\n\n    ExAcquireFastMutex(&Cache->Mutex);\n\n    while (FuseCacheExpireNextItem(Cache, ExpirationTime))\n        ;\n\n    while (FuseCacheForgetNextItem(Cache, ExpirationTime, &ForgetList))\n        ;\n\n    ExReleaseFastMutex(&Cache->Mutex);\n\n    for (PLIST_ENTRY Entry = ForgetList.Flink; &ForgetList != Entry;)\n    {\n        FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry);\n        Entry = Entry->Flink;\n        if (Item->NoForget)\n        {\n            RemoveEntryList(&Item->ListEntry);\n            FuseFree(Item);\n        }\n    }\n\n    if (!IsListEmpty(&ForgetList))\n    {\n        BOOLEAN Success = DEBUGTEST(90) &&\n            NT_SUCCESS(FuseProtoPostForget(Instance, &ForgetList));\n        if (!Success)\n        {\n            ASSERT(!IsListEmpty(&ForgetList));\n\n            ExAcquireFastMutex(&Cache->Mutex);\n\n            /* re-add forgotten items in the \"forget list\" */\n            RemoveEntryList(&ForgetList);\n                /* see AppendTailList comments */\n#if 0\n            /* append */\n            AppendTailList(&Cache->ForgetList, &ForgetList);\n#else\n            /* prepend */\n            PLIST_ENTRY ListToPrepend = ForgetList.Flink;\n            PLIST_ENTRY ListHead = &Cache->ForgetList;\n            PLIST_ENTRY ListBegin = ListHead->Flink;\n            ListBegin->Blink = ListToPrepend->Blink;\n            ListHead->Flink = ListToPrepend;\n            ListToPrepend->Blink->Flink = ListBegin;\n            ListToPrepend->Blink = ListHead;\n#endif\n\n            ExReleaseFastMutex(&Cache->Mutex);\n        }\n    }\n}\n\nNTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen)\n{\n    PAGED_CODE();\n\n    UINT64 InterruptTime = KeQueryInterruptTime() / 10000000 * 10000000;\n    FUSE_CACHE_GEN *Gen = 0, *NewGen = 0;\n\n    *PGen = 0;\n\n    ExAcquireFastMutex(&Cache->Mutex);\n\n    if (!IsListEmpty(&Cache->GenList))\n    {\n        Gen = CONTAINING_RECORD(Cache->GenList.Blink, FUSE_CACHE_GEN, ListEntry);\n        if (InterruptTime <= Gen->InterruptTime)\n            Gen->RefCount++;\n        else\n            Gen = 0;\n    }\n\n    ExReleaseFastMutex(&Cache->Mutex);\n\n    if (0 == Gen)\n    {\n        NewGen = FuseAlloc(sizeof *NewGen);\n        if (0 == NewGen)\n            return STATUS_INSUFFICIENT_RESOURCES;\n\n        RtlZeroMemory(NewGen, sizeof *NewGen);\n        NewGen->RefCount = 1;\n        NewGen->InterruptTime = InterruptTime;\n\n        ExAcquireFastMutex(&Cache->Mutex);\n\n        if (!IsListEmpty(&Cache->GenList))\n        {\n            Gen = CONTAINING_RECORD(Cache->GenList.Blink, FUSE_CACHE_GEN, ListEntry);\n            if (InterruptTime <= Gen->InterruptTime)\n                Gen->RefCount++;\n            else\n                Gen = 0;\n        }\n        if (0 == Gen)\n        {\n            InsertTailList(&Cache->GenList, &NewGen->ListEntry);\n\n            Gen = NewGen;\n            NewGen = 0;\n        }\n\n        ExReleaseFastMutex(&Cache->Mutex);\n    }\n\n    *PGen = Gen;\n\n    if (0 != NewGen)\n        FuseFree(NewGen);\n\n    return STATUS_SUCCESS;\n}\n\nVOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen0)\n{\n    PAGED_CODE();\n\n    FUSE_CACHE_GEN *Gen = Gen0;\n    LONG RefCount;\n\n    if (0 == Gen)\n        return;\n\n    ExAcquireFastMutex(&Cache->Mutex);\n    RefCount = --Gen->RefCount;\n    if (0 == RefCount)\n        RemoveEntryList(&Gen->ListEntry);\n    ExReleaseFastMutex(&Cache->Mutex);\n\n    if (0 == RefCount)\n        FuseFree(Gen);\n}\n\nBOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,\n    FUSE_PROTO_ENTRY *Entry, PVOID *PItem)\n{\n    PAGED_CODE();\n\n    UINT64 InterruptTime = KeQueryInterruptTime();\n    FUSE_CACHE_ITEM *Item;\n    ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive);\n\n    ExAcquireFastMutex(&Cache->Mutex);\n\n    Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name);\n    if (0 != Item)\n    {\n        if (InterruptTime < Item->ExpirationTime &&\n            !InterlockedCompareExchange(&Item->QuickExpiry, 1, 1))\n        {\n            Item->LastUsedTime = InterruptTime;\n            RtlCopyMemory(Entry, &Item->Entry, sizeof Item->Entry);\n\n            /* mark as most-recently used */\n            RemoveEntryList(&Item->ListEntry);\n            InsertTailList(&Cache->ItemList, &Item->ListEntry);\n        }\n        else\n        {\n            FuseCacheExpireItem(Cache, Item);\n            Item = 0;\n        }\n    }\n\n    ExReleaseFastMutex(&Cache->Mutex);\n\n    *PItem = Item;\n    return 0 != Item;\n}\n\nVOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,\n    FUSE_PROTO_ENTRY *Entry, PVOID *PItem)\n{\n    PAGED_CODE();\n\n    UINT64 InterruptTime = KeQueryInterruptTime();\n    UINT64 EntryTimeout = Entry->entry_valid * 10000000 + Entry->entry_valid_nsec / 100;\n    UINT64 AttrTimeout = Entry->attr_valid * 10000000 + Entry->attr_valid_nsec / 100;\n    UINT64 ExpirationTime = InterruptTime +\n        (EntryTimeout < AttrTimeout ? EntryTimeout : AttrTimeout);\n    FUSE_CACHE_ITEM *Item = 0, *NewItem = 0;\n    ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive);\n\n    ExAcquireFastMutex(&Cache->Mutex);\n\n    Item = FuseCacheUpdateHashedItem(Cache,\n        Hash, ParentIno, Name, ExpirationTime, InterruptTime, Entry);\n\n    ExReleaseFastMutex(&Cache->Mutex);\n\n    if (0 == Item)\n    {\n        NewItem = FuseAllocMustSucceed(FIELD_OFFSET(FUSE_CACHE_ITEM, NameBuf) + Name->Length);\n\n        RtlZeroMemory(NewItem, FIELD_OFFSET(FUSE_CACHE_ITEM, NameBuf));\n        NewItem->NoForget =\n            /* the root is not LOOKUP'ed; free without FORGET */\n            ParentIno == FUSE_PROTO_ROOT_INO && 1 == Name->Length && '/' == Name->Buffer[0];\n        NewItem->Hash = Hash;\n        NewItem->ParentIno = ParentIno;\n        NewItem->Name.Length = NewItem->Name.MaximumLength = Name->Length;\n        NewItem->Name.Buffer = NewItem->NameBuf;\n        NewItem->NLookup = 1;\n        NewItem->ExpirationTime = ExpirationTime;\n        NewItem->LastUsedTime = InterruptTime;\n        NewItem->RefCount = 1;\n        RtlCopyMemory(&NewItem->Entry, Entry, sizeof NewItem->Entry);\n        RtlCopyMemory(&NewItem->NameBuf, Name->Buffer, Name->Length);\n\n        ExAcquireFastMutex(&Cache->Mutex);\n\n        Item = FuseCacheUpdateHashedItem(Cache,\n            Hash, ParentIno, Name, ExpirationTime, InterruptTime, Entry);\n        if (0 == Item)\n        {\n            if (Cache->ItemCount >= Cache->Capacity)\n                FuseCacheExpireNextItem(Cache, (UINT64)-1LL);\n\n            FuseCacheAddItem(Cache, NewItem);\n\n            Item = NewItem;\n            NewItem = 0;\n        }\n\n        ExReleaseFastMutex(&Cache->Mutex);\n    }\n\n    if (0 != NewItem)\n        FuseFree(NewItem);\n\n    *PItem = Item;\n}\n\nVOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name)\n{\n    PAGED_CODE();\n\n    FUSE_CACHE_ITEM *Item;\n    ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive);\n\n    ExAcquireFastMutex(&Cache->Mutex);\n\n    Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name);\n    if (0 != Item)\n        FuseCacheExpireItem(Cache, Item);\n\n    ExReleaseFastMutex(&Cache->Mutex);\n}\n\nVOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item0)\n{\n    PAGED_CODE();\n\n    FUSE_CACHE_ITEM *Item = Item0;\n\n    InterlockedIncrement(&Item->RefCount);\n}\n\nVOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item0)\n{\n    PAGED_CODE();\n\n    FUSE_CACHE_ITEM *Item = Item0;\n    LONG RefCount;\n\n    if (0 == Item)\n        return;\n\n    RefCount = InterlockedDecrement(&Item->RefCount);\n    if (0 == RefCount)\n    {\n        ExAcquireFastMutex(&Cache->Mutex);\n        InsertTailList(&Cache->ForgetList, &Item->ListEntry);\n        ExReleaseFastMutex(&Cache->Mutex);\n    }\n}\n\nVOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item0)\n{\n    PAGED_CODE();\n\n    FUSE_CACHE_ITEM *Item = Item0;\n\n    InterlockedExchange(&Item->QuickExpiry, 1);\n}\n\nVOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList)\n{\n    PAGED_CODE();\n\n    for (PLIST_ENTRY Entry = ForgetList->Flink; ForgetList != Entry;)\n    {\n        FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry);\n        Entry = Entry->Flink;\n        FuseFree(Item);\n    }\n}\n\nBOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE *PForgetOne)\n{\n    PAGED_CODE();\n\n    PLIST_ENTRY Entry = RemoveHeadList(ForgetList);\n    if (ForgetList == Entry)\n        return FALSE;\n\n    FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry);\n    ASSERT(!Item->NoForget);\n    PForgetOne->nodeid = Item->Entry.nodeid;\n    PForgetOne->nlookup = Item->NLookup;\n    FuseFree(Item);\n\n    return TRUE;\n}\n"
  },
  {
    "path": "src/shared/km/context.c",
    "content": "/**\n * @file shared/km/context.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\nVOID FuseContextCreate(FUSE_CONTEXT **PContext,\n    FUSE_INSTANCE *Instance, FSP_FSCTL_TRANSACT_REQ *InternalRequest);\nVOID FuseContextDelete(FUSE_CONTEXT *Context);\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(PAGE, FuseContextCreate)\n#pragma alloc_text(PAGE, FuseContextDelete)\n#endif\n\nVOID FuseContextCreate(FUSE_CONTEXT **PContext,\n    FUSE_INSTANCE *Instance, FSP_FSCTL_TRANSACT_REQ *InternalRequest)\n{\n    PAGED_CODE();\n\n    FUSE_CONTEXT *Context;\n    UINT32 Kind = 0 == InternalRequest ?\n        FspFsctlTransactReservedKind : InternalRequest->Kind;\n\n    ASSERT(FspFsctlTransactKindCount > Kind);\n    if (0 == FuseOperations[Kind].Proc)\n    {\n        *PContext = FuseContextStatus(STATUS_INVALID_DEVICE_REQUEST);\n        return;\n    }\n\n    Context = FuseAlloc(sizeof *Context);\n    if (0 == Context)\n    {\n        *PContext = FuseContextStatus(STATUS_INSUFFICIENT_RESOURCES);\n        return;\n    }\n\n    RtlZeroMemory(Context, sizeof *Context);\n    Context->Instance = Instance;\n    Context->InternalRequest = InternalRequest;\n    Context->InternalResponse = (PVOID)&Context->InternalResponseBuf;\n    Context->InternalResponse->Size = sizeof(FSP_FSCTL_TRANSACT_RSP);\n    Context->InternalResponse->Kind = Kind;\n    Context->InternalResponse->Hint = 0 != InternalRequest ? InternalRequest->Hint : 0;\n    *PContext = Context;\n}\n\nVOID FuseContextDelete(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    if (FuseOpGuardTrue == Context->OpGuardResult)\n    {\n        UINT32 Kind = 0 == Context->InternalRequest ?\n            FspFsctlTransactReservedKind : Context->InternalRequest->Kind;\n        FuseOperations[Kind].Guard(Context, FALSE);\n    }\n\n    if (0 != Context->Fini)\n        Context->Fini(Context);\n    if (0 != Context->InternalRequest)\n        FuseFree(Context->InternalRequest);\n    if ((PVOID)&Context->InternalResponseBuf != Context->InternalResponse)\n        FuseFree(Context->InternalResponse);\n\n    DEBUGFILL(Context, sizeof *Context);\n    FuseFree(Context);\n}\n"
  },
  {
    "path": "src/shared/km/coro.h",
    "content": "/**\n * @file shared/km/coro.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#ifndef SHARED_KM_CORO_H_INCLUDED\n#define SHARED_KM_CORO_H_INCLUDED\n\n/*\n * Nested coroutines\n *\n * This is a simple implementation of nested coroutines for C using macros. It introduces\n * the macros coro_block, coro_await, coro_yield and coro_break that are used to create coroutines,\n * suspend/resume them and exit them. This implementation supports nested coroutines in that\n * a coroutine may invoke another coroutine and the whole stack of coroutines may be suspended\n * and later resumed.\n *\n * The implementation is able to do this by maintaining a stack of program \"points\" where\n * coroutine execution may be suspended and later resumed. The implementation achieves this by\n * (ab)using a peculiarity of the C switch statement in that it allows case: labels to appear\n * anywhere within the body of a switch statement including nested compound statements.\n *\n * While this implementation is able to maintain the stack of program \"points\" where execution\n * may be resumed, it is not able to automatically maintain important state such as activation\n * records (local variables). It is the responsibility of the programmer using these macros\n * to maintain this state. Usually this is done by moving all local variables together with the\n * space for the program \"points\" stack into a heap allocation that is then passed as an argument\n * to the coroutines.\n *\n * The original coroutine implementation was done some time around 2010 and did not support\n * nesting. It was used to facilitate the implementation of complex iterators in a C++ library.\n * It was inspired by Simon Tatham's \"Coroutines in C\":\n *     http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html\n *\n * Reference\n *\n * The coroutine state is maintained in an integer array (S) whose address is passed to the\n * \"block\" statement. The array's number of elements must be 2 plus the number of expected\n * coroutines (e.g. if you expect to have up to 3 nested coroutines, the array must have at\n * least 5 elements). The array must be initialized to 0 on initial entry to a coroutine block.\n *\n *     coro_block(S)\n *         This macro introduces a coroutine statement block { ... } where the \"await\", \"yield\",\n *         and \"break\" statements can be used. There can only be one such block within a function.\n *     coro_await(E)\n *         This macro executes the expression E, which should be an invocation of a coroutine.\n *         The nested coroutine may suspend itself, in which case the \"await\" statement exits\n *         the current coroutine statement block. The coroutine block can be reentered in which\n *         case execution will continue within the coroutine invoked by E, unless the coroutine\n *         is complete. It is an error to use \"await\" outside of a coroutine block.\n *     coro_yield\n *         This macro exits the current coroutine statement block. The coroutine block can be\n *         reentered in which case execution will continue after the \"yield\" statement. It is\n *         an error to use \"yield\" outside of a coroutine block.\n *     coro_break\n *         This macro exits the current coroutine statement block and marks it as \"complete\".\n *         If the coroutine block is reentered it exits immediately. It is an error to use \"break\"\n *         outside of a coroutine block.\n */\n#define coro_block(S)       short *coro_S__ = (S); if (!coro_active()) coro_X__:; else \\\n                            switch (coro_enter__()) for (; 0,0; coro_leave__(-1)) case 0:\n#define coro_await__(N, E)  do { E; coro_cond_leave__(N); goto coro_X__; case N:; } while (1,1)\n#define coro_yield__(N)     do { coro_leave__(N); goto coro_X__; case N:; } while (0,0)\n#define coro_break          do { coro_leave__(-1); goto coro_X__; } while (0,0)\n#define coro_active()       (-1 != coro_below__)\n#define coro_below__        (coro_S__[coro_S__[0] + 1])\n#define coro_enter__()      (coro_S__[++coro_S__[0]])\n#define coro_leave__(N)     (coro_below__ = 0, coro_S__[coro_S__[0]--] = N)\n#define coro_cond_leave__(N)if (!coro_active()) { coro_below__ = 0; break; } (coro_S__[coro_S__[0]--] = N)\n#if defined(__COUNTER__)\n#define coro_await(...)     coro_await__((__COUNTER__ + 1), (__VA_ARGS__))\n#define coro_yield          coro_yield__((__COUNTER__ + 1))\n#else\n#define coro_await(...)     coro_await__(__LINE__, (__VA_ARGS__))\n#define coro_yield          coro_yield__(__LINE__)\n#endif\n\n#endif\n"
  },
  {
    "path": "src/shared/km/debug.c",
    "content": "/**\n * @file shared/km/debug.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\n#if DBG\nULONG DebugRandom(VOID)\n{\n    static KSPIN_LOCK SpinLock = 0;\n    static ULONG Seed = 1;\n    KIRQL Irql;\n    ULONG Result;\n\n    KeAcquireSpinLock(&SpinLock, &Irql);\n\n    /* see ucrt sources */\n    Seed = Seed * 214013 + 2531011;\n    Result = (Seed >> 16) & 0x7fff;\n\n    KeReleaseSpinLock(&SpinLock, Irql);\n\n    return Result;\n}\n\nBOOLEAN DebugMemory(PVOID Memory, SIZE_T Size, BOOLEAN Test)\n{\n    BOOLEAN Result = TRUE;\n    if (!Test)\n    {\n        for (SIZE_T I = 0, N = Size / sizeof(UINT32); N > I; I++)\n        {\n            ((PUINT8)Memory)[0] = 0x0B;\n            ((PUINT8)Memory)[1] = 0xAD;\n            ((PUINT8)Memory)[2] = 0xF0;\n            ((PUINT8)Memory)[3] = 0x0D;\n            Memory = (PUINT8)Memory + sizeof(UINT32);\n        }\n    }\n    else\n    {\n        for (SIZE_T I = 0, N = Size / sizeof(UINT32); N > I; I++)\n        {\n            if (\n                ((PUINT8)Memory)[0] == 0x0B &&\n                ((PUINT8)Memory)[1] == 0xAD &&\n                ((PUINT8)Memory)[2] == 0xF0 &&\n                ((PUINT8)Memory)[3] == 0x0D\n                )\n            {\n                Result = FALSE;\n                break;\n            }\n            Memory = (PUINT8)Memory + sizeof(UINT32);\n        }\n    }\n    return Result;\n}\n\nint _snprintf(char *buf, size_t siz, const char *fmt, ...);\n\nstatic const char *FuseErrnoSignSym(INT32 Errno)\n{\n    if (0 < Errno)\n        return \"+\";\n    else if (0 > Errno)\n        return \"-\";\n    else\n        return \"\";\n}\n\nstatic const char *FuseErrnoSym(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno)\n{\n    if (0 > Errno)\n        Errno = -Errno;\n\n    switch (InstanceType)\n    {\n    default:\n    case FuseInstanceWindows:\n        switch (Errno)\n        {\n        #undef FUSE_ERRNO\n        #define FUSE_ERRNO 87\n        #include \"errnosym.i\"\n        default:\n            return \"errno:UNKNOWN\";\n        }\n    case FuseInstanceCygwin:\n        switch (Errno)\n        {\n        #undef FUSE_ERRNO\n        #define FUSE_ERRNO 67\n        #include \"errnosym.i\"\n        default:\n            return \"errno:UNKNOWN\";\n        }\n    case FuseInstanceLinux:\n        switch (Errno)\n        {\n        #undef FUSE_ERRNO\n        #define FUSE_ERRNO 76\n        #include \"errnosym.i\"\n        default:\n            return \"errno:UNKNOWN\";\n        }\n    }\n}\n\nstatic const char *FuseOpcodeSym(UINT32 Opcode)\n{\n#define SYM(x)                          case FUSE_PROTO_OPCODE_ ## x: return #x;\n\n    switch (Opcode)\n    {\n    case 0:\n        return \"EMPTY\";\n    SYM(LOOKUP)\n    SYM(FORGET)\n    SYM(GETATTR)\n    SYM(SETATTR)\n    SYM(READLINK)\n    SYM(SYMLINK)\n    SYM(MKNOD)\n    SYM(MKDIR)\n    SYM(UNLINK)\n    SYM(RMDIR)\n    SYM(RENAME)\n    SYM(LINK)\n    SYM(OPEN)\n    SYM(READ)\n    SYM(WRITE)\n    SYM(STATFS)\n    SYM(RELEASE)\n    SYM(FSYNC)\n    SYM(SETXATTR)\n    SYM(GETXATTR)\n    SYM(LISTXATTR)\n    SYM(REMOVEXATTR)\n    SYM(FLUSH)\n    SYM(INIT)\n    SYM(OPENDIR)\n    SYM(READDIR)\n    SYM(RELEASEDIR)\n    SYM(FSYNCDIR)\n    SYM(GETLK)\n    SYM(SETLK)\n    SYM(SETLKW)\n    SYM(ACCESS)\n    SYM(CREATE)\n    SYM(INTERRUPT)\n    SYM(BMAP)\n    SYM(DESTROY)\n    SYM(IOCTL)\n    SYM(POLL)\n    SYM(NOTIFY_REPLY)\n    SYM(BATCH_FORGET)\n    SYM(FALLOCATE)\n    SYM(READDIRPLUS)\n    SYM(RENAME2)\n    SYM(LSEEK)\n    SYM(COPY_FILE_RANGE)\n    default:\n        return \"INVALID\";\n    }\n\n#undef SYM\n}\n\nstatic const char *FuseDebugLogTimeString(UINT64 time, UINT32 timensec, char *Buf)\n{\n    UINT64 FileTime;\n    TIME_FIELDS TimeFields;\n\n    if (0 == time && 0 == timensec)\n        Buf[0] = '0', Buf[1] = '\\0';\n    else\n    {\n        FuseUnixTimeToFileTime(time, timensec, &FileTime);\n        RtlTimeToTimeFields((PLARGE_INTEGER)&FileTime, &TimeFields);\n        _snprintf(Buf, 32, \"%04hu-%02hu-%02huT%02hu:%02hu:%02hu.%03huZ\",\n            TimeFields.Year, TimeFields.Month, TimeFields.Day,\n            TimeFields.Hour, TimeFields.Minute, TimeFields.Second,\n            TimeFields.Milliseconds);\n    }\n\n    return Buf;\n}\n\nstatic const char *FuseDebugLogAttrString(FUSE_PROTO_ATTR *Attr, char *Buf)\n{\n    char atimebuf[32], mtimebuf[32], ctimebuf[32];\n    _snprintf(Buf, 512,\n        \"{ino=%llu, size=%llu, blocks=%llu, atime=%s, mtime=%s, ctime=%s, \"\n            \"mode=0%06o, nlink=%u, uid=%u, gid=%u, rdev=0x%x, blksize=%u}\",\n        Attr->ino,\n        Attr->size,\n        Attr->blocks,\n        FuseDebugLogTimeString(Attr->atime, Attr->atimensec, atimebuf),\n        FuseDebugLogTimeString(Attr->mtime, Attr->mtimensec, mtimebuf),\n        FuseDebugLogTimeString(Attr->ctime, Attr->ctimensec, ctimebuf),\n        Attr->mode,\n        Attr->nlink,\n        Attr->uid,\n        Attr->gid,\n        Attr->rdev,\n        Attr->blksize);\n    return Buf;\n}\n\nstatic const char *FuseDebugLogEntryString(FUSE_PROTO_ENTRY *Entry, char *Buf)\n{\n    int Len0, Len1;\n    Len0 = _snprintf(Buf, 256,\n        \"{nodeid=%llu, generation=%llu, entry_valid=%llu, entry_valid_nsec=%u, \"\n            \"attr_valid=%llu, attr_valid_nsec=%u, attr=\",\n        Entry->nodeid,\n        Entry->generation,\n        Entry->entry_valid,\n        Entry->entry_valid_nsec,\n        Entry->attr_valid,\n        Entry->attr_valid_nsec);\n    FuseDebugLogAttrString(&Entry->attr, Buf + Len0);\n    Len1 = Len0 + (int)strlen(Buf + Len0);\n    Buf[Len1] = '}';\n    Buf[Len1 + 1] = '\\0';\n    return Buf;\n}\n\nVOID FuseDebugLogRequest(FUSE_PROTO_REQ *Request)\n{\n#define LOG(fmt, ...)                   \\\n    DbgPrint(\"[%d] FUSE: %p[%06x]: <<%s[ino=%llu,uid=%u:%u,pid=%u] \" fmt \"\\n\",\\\n        KeGetCurrentIrql(),             \\\n        (PVOID)(UINT_PTR)Request->unique,\\\n        Request->len,                   \\\n        FuseOpcodeSym(Request->opcode), \\\n        Request->nodeid,                \\\n        Request->uid,                   \\\n        Request->gid,                   \\\n        Request->pid,                   \\\n        __VA_ARGS__)\n\n    if (0 == Request->len)\n    {\n        LOG(\"\", 0);\n        return;\n    }\n\n    FUSE_CONTEXT *Context = (PVOID)(UINT_PTR)Request->unique;\n    0 != Context ? Context->DebugLogOpcode = Request->opcode : 0;\n\n    char atimebuf[32], mtimebuf[32], ctimebuf[32];\n    switch (Request->opcode)\n    {\n    case FUSE_PROTO_OPCODE_LOOKUP:\n        LOG(\"name=\\\"%s\\\"\",\n            Request->req.lookup.name);\n        break;\n    case FUSE_PROTO_OPCODE_FORGET:\n        LOG(\"nlookup=%llu\",\n            Request->req.forget.nlookup);\n        break;\n    case FUSE_PROTO_OPCODE_GETATTR:\n        LOG(\"fh=%llu, flags=%u\",\n            Request->req.getattr.fh,\n            Request->req.getattr.getattr_flags);\n        break;\n    case FUSE_PROTO_OPCODE_SETATTR:\n        LOG(\"fh=%llu, valid=%x, size=%llu, atime=%s, mtime=%s, ctime=%s, mode=0%03o, uid=%u, gid=%u\",\n            Request->req.setattr.fh,\n            Request->req.setattr.valid,\n            Request->req.setattr.size,\n            FuseDebugLogTimeString(Request->req.setattr.atime, Request->req.setattr.atimensec, atimebuf),\n            FuseDebugLogTimeString(Request->req.setattr.mtime, Request->req.setattr.mtimensec, mtimebuf),\n            FuseDebugLogTimeString(Request->req.setattr.ctime, Request->req.setattr.ctimensec, ctimebuf),\n            Request->req.setattr.mode,\n            Request->req.setattr.uid,\n            Request->req.setattr.gid);\n        break;\n    case FUSE_PROTO_OPCODE_SYMLINK:\n        LOG(\"name=\\\"%s\\\", target=\\\"%s\\\"\",\n            Request->req.symlink.name,\n            Request->req.symlink.name + strlen(Request->req.symlink.name) + 1);\n        break;\n    case FUSE_PROTO_OPCODE_MKNOD:\n        LOG(\"name=\\\"%s\\\", mode=0%06o, rdev=0x%x, umask=0%03o\",\n            Request->req.mknod.name,\n            Request->req.mknod.mode,\n            Request->req.mknod.rdev,\n            Request->req.mknod.umask);\n        break;\n    case FUSE_PROTO_OPCODE_MKDIR:\n        LOG(\"name=\\\"%s\\\", mode=0%06o, umask=0%03o\",\n            Request->req.mkdir.name,\n            Request->req.mkdir.mode,\n            Request->req.mkdir.umask);\n        break;\n    case FUSE_PROTO_OPCODE_UNLINK:\n        LOG(\"name=\\\"%s\\\"\",\n            Request->req.unlink.name);\n        break;\n    case FUSE_PROTO_OPCODE_RMDIR:\n        LOG(\"name=\\\"%s\\\"\",\n            Request->req.rmdir.name);\n        break;\n    case FUSE_PROTO_OPCODE_RENAME:\n        LOG(\"oldname=\\\"%s\\\", newdir=%llu, newname=\\\"%s\\\"\",\n            Request->req.rename.name,\n            Request->req.rename.newdir,\n            Request->req.rename.name + strlen(Request->req.rename.name) + 1);\n        break;\n    case FUSE_PROTO_OPCODE_LINK:\n        LOG(\"oldino=%llu, name=\\\"%s\\\"\",\n            Request->req.link.oldnodeid,\n            Request->req.link.name);\n        break;\n    case FUSE_PROTO_OPCODE_OPEN:\n    case FUSE_PROTO_OPCODE_OPENDIR:\n        LOG(\"open_flags=0x%x\",\n            Request->req.open.flags);\n        break;\n    case FUSE_PROTO_OPCODE_READ:\n    case FUSE_PROTO_OPCODE_READDIR:\n    case FUSE_PROTO_OPCODE_READDIRPLUS:\n        LOG(\"fh=%llu, offset=%llu, size=%u, open_flags=0x%x\",\n            Request->req.read.fh,\n            Request->req.read.offset,\n            Request->req.read.size,\n            Request->req.read.flags);\n        break;\n    case FUSE_PROTO_OPCODE_WRITE:\n        LOG(\"fh=%llu, offset=%llu, size=%u, open_flags=0x%x\",\n            Request->req.write.fh,\n            Request->req.write.offset,\n            Request->req.write.size,\n            Request->req.write.flags);\n        break;\n    case FUSE_PROTO_OPCODE_RELEASE:\n    case FUSE_PROTO_OPCODE_RELEASEDIR:\n        LOG(\"fh=%llu, flags=0x%x, open_flags=0x%x\",\n            Request->req.release.fh,\n            Request->req.release.release_flags,\n            Request->req.release.flags);\n        break;\n    case FUSE_PROTO_OPCODE_FSYNC:\n    case FUSE_PROTO_OPCODE_FSYNCDIR:\n        LOG(\"fh=%llu, flags=0x%x\",\n            Request->req.fsync.fh,\n            Request->req.fsync.fsync_flags);\n        break;\n    case FUSE_PROTO_OPCODE_SETXATTR:\n        LOG(\"name=\\\"%s\\\", size=%u, flags=0x%x\",\n            Request->req.setxattr.name,\n            Request->req.setxattr.size,\n            Request->req.setxattr.flags);\n        break;\n    case FUSE_PROTO_OPCODE_GETXATTR:\n        LOG(\"name=\\\"%s\\\", size=%u\",\n            Request->req.getxattr.name,\n            Request->req.getxattr.size);\n        break;\n    case FUSE_PROTO_OPCODE_LISTXATTR:\n        LOG(\"size=%u\",\n            Request->req.listxattr.size);\n        break;\n    case FUSE_PROTO_OPCODE_REMOVEXATTR:\n        LOG(\"name=\\\"%s\\\"\",\n            Request->req.removexattr.name);\n        break;\n    case FUSE_PROTO_OPCODE_FLUSH:\n        LOG(\"fh=%llu\",\n            Request->req.flush.fh);\n        break;\n    case FUSE_PROTO_OPCODE_INIT:\n        LOG(\"major=%u, minor=%u, flags=0x%x, max_readahead=%u\",\n            Request->req.init.major,\n            Request->req.init.minor,\n            Request->req.init.flags,\n            Request->req.init.max_readahead);\n        break;\n    case FUSE_PROTO_OPCODE_ACCESS:\n        LOG(\"mask=0%o\",\n            Request->req.access.mask);\n        break;\n    case FUSE_PROTO_OPCODE_CREATE:\n        LOG(\"name=\\\"%s\\\", mode=0%06o, umask=0%03o, open_flags=0x%x\",\n            Request->req.create.name,\n            Request->req.create.mode,\n            Request->req.create.umask,\n            Request->req.create.flags);\n        break;\n    case FUSE_PROTO_OPCODE_BATCH_FORGET:\n        LOG(\"count=%u\",\n            Request->req.batch_forget.count);\n        break;\n    default:\n        LOG(\"\", 0);\n        break;\n    }\n\n#undef LOG\n}\n\nVOID FuseDebugLogResponse(FUSE_PROTO_RSP *Response)\n{\n#define LOG(fmt, ...)                   \\\n    DbgPrint(\"[%d] FUSE: %p[%06x]: >>%s[err=%s%s] \" fmt \"\\n\",\\\n        KeGetCurrentIrql(),             \\\n        (PVOID)(UINT_PTR)Response->unique,\\\n        Response->len,                  \\\n        FuseOpcodeSym(Opcode),          \\\n        FuseErrnoSignSym(Response->error),\\\n        FuseErrnoSym(InstanceType, Response->error),\\\n        __VA_ARGS__)\n\n    FUSE_CONTEXT *Context = (PVOID)(UINT_PTR)Response->unique;\n    FUSE_INSTANCE_TYPE InstanceType = 0 != Context ? Context->Instance->InstanceType : FuseInstanceWindows;\n    UINT32 Opcode = 0 != Context ? Context->DebugLogOpcode : 0;\n\n    if (0 != Response->error)\n    {\n        LOG(\"\", 0);\n        return;\n    }\n\n    char entrybuf[256 + 512];\n    switch (Opcode)\n    {\n    case FUSE_PROTO_OPCODE_LOOKUP:\n        LOG(\"entry=%s\",\n            FuseDebugLogEntryString(&Response->rsp.lookup.entry, entrybuf));\n        break;\n    case FUSE_PROTO_OPCODE_GETATTR:\n        LOG(\"attr_valid=%llu, attr_valid_nsec=%u, attr=%s\",\n            Response->rsp.getattr.attr_valid,\n            Response->rsp.getattr.attr_valid_nsec,\n            FuseDebugLogAttrString(&Response->rsp.getattr.attr, entrybuf));\n        break;\n    case FUSE_PROTO_OPCODE_SETATTR:\n        LOG(\"attr_valid=%llu, attr_valid_nsec=%u, attr=%s\",\n            Response->rsp.setattr.attr_valid,\n            Response->rsp.setattr.attr_valid_nsec,\n            FuseDebugLogAttrString(&Response->rsp.setattr.attr, entrybuf));\n        break;\n    case FUSE_PROTO_OPCODE_SYMLINK:\n        LOG(\"entry=%s\",\n            FuseDebugLogEntryString(&Response->rsp.symlink.entry, entrybuf));\n        break;\n    case FUSE_PROTO_OPCODE_MKNOD:\n        LOG(\"entry=%s\",\n            FuseDebugLogEntryString(&Response->rsp.mknod.entry, entrybuf));\n        break;\n    case FUSE_PROTO_OPCODE_MKDIR:\n        LOG(\"entry=%s\",\n            FuseDebugLogEntryString(&Response->rsp.mkdir.entry, entrybuf));\n        break;\n    case FUSE_PROTO_OPCODE_LINK:\n        LOG(\"entry=%s\",\n            FuseDebugLogEntryString(&Response->rsp.link.entry, entrybuf));\n        break;\n    case FUSE_PROTO_OPCODE_OPEN:\n    case FUSE_PROTO_OPCODE_OPENDIR:\n        LOG(\"fh=%llu, open_flags=0x%x\",\n            Response->rsp.open.fh,\n            Response->rsp.open.open_flags);\n        break;\n    case FUSE_PROTO_OPCODE_WRITE:\n        LOG(\"size=%u\",\n            Response->rsp.write.size);\n        break;\n    case FUSE_PROTO_OPCODE_STATFS:\n        LOG(\"st={blocks=%llu, bfree=%llu, bavail=%llu, files=%llu, ffree=%llu, bsize=%u, frsize=%u, namelen=%u}\",\n            Response->rsp.statfs.st.blocks,\n            Response->rsp.statfs.st.bfree,\n            Response->rsp.statfs.st.bavail,\n            Response->rsp.statfs.st.files,\n            Response->rsp.statfs.st.ffree,\n            Response->rsp.statfs.st.bsize,\n            Response->rsp.statfs.st.frsize,\n            Response->rsp.statfs.st.namelen);\n        break;\n    case FUSE_PROTO_OPCODE_GETXATTR:\n        LOG(\"size=%u\",\n            Response->rsp.getxattr.size);\n        break;\n    case FUSE_PROTO_OPCODE_LISTXATTR:\n        LOG(\"size=%u\",\n            Response->rsp.listxattr.size);\n        break;\n    case FUSE_PROTO_OPCODE_INIT:\n        LOG(\"major=%u, minor=%u, flags=0x%x, max_readahead=%u, max_write=%u\",\n            Response->rsp.init.major,\n            Response->rsp.init.minor,\n            Response->rsp.init.flags,\n            Response->rsp.init.max_readahead,\n            Response->rsp.init.max_write);\n        break;\n    case FUSE_PROTO_OPCODE_CREATE:\n        LOG(\"entry=%s, fh=%llu, open_flags=0x%x\",\n            FuseDebugLogEntryString(&Response->rsp.create.entry, entrybuf),\n            Response->rsp.create.fh,\n            Response->rsp.create.open_flags);\n        break;\n    default:\n        LOG(\"\", 0);\n        break;\n    }\n\n#undef LOG\n}\n#endif\n"
  },
  {
    "path": "src/shared/km/errno.i",
    "content": "#if FUSE_ERRNO == 87 /* Windows */\n\ncase 0: return STATUS_SUCCESS;\ncase 1: return STATUS_ACCESS_DENIED;\ncase 2: return STATUS_OBJECT_NAME_NOT_FOUND;\ncase 3: return STATUS_PROCEDURE_NOT_FOUND;\ncase 4: return STATUS_CANCELLED;\ncase 5: return STATUS_IO_DEVICE_ERROR;\ncase 6: return STATUS_FILE_INVALID;\ncase 7: return STATUS_INSUFFICIENT_RESOURCES;\ncase 8: return STATUS_INVALID_IMAGE_FORMAT;\ncase 9: return STATUS_INVALID_HANDLE;\ncase 12: return STATUS_INSUFFICIENT_RESOURCES;\ncase 13: return STATUS_ACCESS_DENIED;\ncase 14: return STATUS_ACCESS_VIOLATION;\ncase 16: return STATUS_DEVICE_BUSY;\ncase 17: return STATUS_OBJECT_NAME_COLLISION;\ncase 18: return STATUS_NOT_SAME_DEVICE;\ncase 19: return STATUS_NO_SUCH_DEVICE;\ncase 20: return STATUS_NOT_A_DIRECTORY;\ncase 21: return STATUS_FILE_IS_A_DIRECTORY;\ncase 22: return STATUS_INVALID_PARAMETER;\ncase 23: return STATUS_TOO_MANY_OPENED_FILES;\ncase 24: return STATUS_TOO_MANY_OPENED_FILES;\ncase 27: return STATUS_DISK_FULL;\ncase 28: return STATUS_DISK_FULL;\ncase 29: return STATUS_INVALID_PARAMETER;\ncase 30: return STATUS_MEDIA_WRITE_PROTECTED;\ncase 31: return STATUS_TOO_MANY_LINKS;\ncase 32: return STATUS_PIPE_BROKEN;\ncase 33: return STATUS_INVALID_PARAMETER;\ncase 34: return STATUS_INVALID_PARAMETER;\ncase 36: return STATUS_POSSIBLE_DEADLOCK;\ncase 38: return STATUS_NAME_TOO_LONG;\ncase 39: return STATUS_LOCK_NOT_GRANTED;\ncase 40: return STATUS_INVALID_DEVICE_REQUEST;\ncase 41: return STATUS_DIRECTORY_NOT_EMPTY;\ncase 42: return STATUS_INVALID_PARAMETER;\ncase 100: return STATUS_ADDRESS_ALREADY_ASSOCIATED;\ncase 103: return STATUS_CONNECTION_ACTIVE;\ncase 105: return STATUS_CANCELLED;\ncase 106: return STATUS_CONNECTION_ABORTED;\ncase 107: return STATUS_CONNECTION_REFUSED;\ncase 108: return STATUS_CONNECTION_RESET;\ncase 110: return STATUS_HOST_UNREACHABLE;\ncase 113: return STATUS_CONNECTION_ACTIVE;\ncase 114: return STATUS_REPARSE_POINT_NOT_RESOLVED;\ncase 116: return STATUS_HOST_DOWN;\ncase 117: return STATUS_CONNECTION_RESET;\ncase 118: return STATUS_NETWORK_UNREACHABLE;\ncase 119: return STATUS_INSUFFICIENT_RESOURCES;\ncase 120: return STATUS_END_OF_FILE;\ncase 121: return STATUS_CONNECTION_INVALID;\ncase 126: return STATUS_CONNECTION_INVALID;\ncase 128: return STATUS_INVALID_HANDLE;\ncase 138: return STATUS_TRANSACTION_TIMED_OUT;\n\n#elif FUSE_ERRNO == 67 /* Cygwin */\n\ncase 0: return STATUS_SUCCESS;\ncase 1: return STATUS_ACCESS_DENIED;\ncase 2: return STATUS_OBJECT_NAME_NOT_FOUND;\ncase 3: return STATUS_PROCEDURE_NOT_FOUND;\ncase 4: return STATUS_CANCELLED;\ncase 5: return STATUS_IO_DEVICE_ERROR;\ncase 6: return STATUS_FILE_INVALID;\ncase 7: return STATUS_INSUFFICIENT_RESOURCES;\ncase 8: return STATUS_INVALID_IMAGE_FORMAT;\ncase 9: return STATUS_INVALID_HANDLE;\ncase 12: return STATUS_INSUFFICIENT_RESOURCES;\ncase 13: return STATUS_ACCESS_DENIED;\ncase 14: return STATUS_ACCESS_VIOLATION;\ncase 16: return STATUS_DEVICE_BUSY;\ncase 17: return STATUS_OBJECT_NAME_COLLISION;\ncase 18: return STATUS_NOT_SAME_DEVICE;\ncase 19: return STATUS_NO_SUCH_DEVICE;\ncase 20: return STATUS_NOT_A_DIRECTORY;\ncase 21: return STATUS_FILE_IS_A_DIRECTORY;\ncase 22: return STATUS_INVALID_PARAMETER;\ncase 23: return STATUS_TOO_MANY_OPENED_FILES;\ncase 24: return STATUS_TOO_MANY_OPENED_FILES;\ncase 27: return STATUS_DISK_FULL;\ncase 28: return STATUS_DISK_FULL;\ncase 29: return STATUS_INVALID_PARAMETER;\ncase 30: return STATUS_MEDIA_WRITE_PROTECTED;\ncase 31: return STATUS_TOO_MANY_LINKS;\ncase 32: return STATUS_PIPE_BROKEN;\ncase 33: return STATUS_INVALID_PARAMETER;\ncase 34: return STATUS_INVALID_PARAMETER;\ncase 45: return STATUS_POSSIBLE_DEADLOCK;\ncase 91: return STATUS_NAME_TOO_LONG;\ncase 46: return STATUS_LOCK_NOT_GRANTED;\ncase 88: return STATUS_INVALID_DEVICE_REQUEST;\ncase 90: return STATUS_DIRECTORY_NOT_EMPTY;\ncase 138: return STATUS_INVALID_PARAMETER;\ncase 112: return STATUS_ADDRESS_ALREADY_ASSOCIATED;\ncase 120: return STATUS_CONNECTION_ACTIVE;\ncase 140: return STATUS_CANCELLED;\ncase 113: return STATUS_CONNECTION_ABORTED;\ncase 111: return STATUS_CONNECTION_REFUSED;\ncase 104: return STATUS_CONNECTION_RESET;\ncase 118: return STATUS_HOST_UNREACHABLE;\ncase 127: return STATUS_CONNECTION_ACTIVE;\ncase 92: return STATUS_REPARSE_POINT_NOT_RESOLVED;\ncase 115: return STATUS_HOST_DOWN;\ncase 126: return STATUS_CONNECTION_RESET;\ncase 114: return STATUS_NETWORK_UNREACHABLE;\ncase 105: return STATUS_INSUFFICIENT_RESOURCES;\ncase 61: return STATUS_END_OF_FILE;\ncase 67: return STATUS_CONNECTION_INVALID;\ncase 128: return STATUS_CONNECTION_INVALID;\ncase 108: return STATUS_INVALID_HANDLE;\ncase 116: return STATUS_TRANSACTION_TIMED_OUT;\n\n#elif FUSE_ERRNO == 76 /* Linux */\n\ncase 0: return STATUS_SUCCESS;\ncase 1: return STATUS_ACCESS_DENIED;\ncase 2: return STATUS_OBJECT_NAME_NOT_FOUND;\ncase 3: return STATUS_PROCEDURE_NOT_FOUND;\ncase 4: return STATUS_CANCELLED;\ncase 5: return STATUS_IO_DEVICE_ERROR;\ncase 6: return STATUS_FILE_INVALID;\ncase 7: return STATUS_INSUFFICIENT_RESOURCES;\ncase 8: return STATUS_INVALID_IMAGE_FORMAT;\ncase 9: return STATUS_INVALID_HANDLE;\ncase 12: return STATUS_INSUFFICIENT_RESOURCES;\ncase 13: return STATUS_ACCESS_DENIED;\ncase 14: return STATUS_ACCESS_VIOLATION;\ncase 16: return STATUS_DEVICE_BUSY;\ncase 17: return STATUS_OBJECT_NAME_COLLISION;\ncase 18: return STATUS_NOT_SAME_DEVICE;\ncase 19: return STATUS_NO_SUCH_DEVICE;\ncase 20: return STATUS_NOT_A_DIRECTORY;\ncase 21: return STATUS_FILE_IS_A_DIRECTORY;\ncase 22: return STATUS_INVALID_PARAMETER;\ncase 23: return STATUS_TOO_MANY_OPENED_FILES;\ncase 24: return STATUS_TOO_MANY_OPENED_FILES;\ncase 27: return STATUS_DISK_FULL;\ncase 28: return STATUS_DISK_FULL;\ncase 29: return STATUS_INVALID_PARAMETER;\ncase 30: return STATUS_MEDIA_WRITE_PROTECTED;\ncase 31: return STATUS_TOO_MANY_LINKS;\ncase 32: return STATUS_PIPE_BROKEN;\ncase 33: return STATUS_INVALID_PARAMETER;\ncase 34: return STATUS_INVALID_PARAMETER;\ncase 35: return STATUS_POSSIBLE_DEADLOCK;\ncase 36: return STATUS_NAME_TOO_LONG;\ncase 37: return STATUS_LOCK_NOT_GRANTED;\ncase 38: return STATUS_INVALID_DEVICE_REQUEST;\ncase 39: return STATUS_DIRECTORY_NOT_EMPTY;\ncase 84: return STATUS_INVALID_PARAMETER;\ncase 98: return STATUS_ADDRESS_ALREADY_ASSOCIATED;\ncase 114: return STATUS_CONNECTION_ACTIVE;\ncase 125: return STATUS_CANCELLED;\ncase 103: return STATUS_CONNECTION_ABORTED;\ncase 111: return STATUS_CONNECTION_REFUSED;\ncase 104: return STATUS_CONNECTION_RESET;\ncase 113: return STATUS_HOST_UNREACHABLE;\ncase 106: return STATUS_CONNECTION_ACTIVE;\ncase 40: return STATUS_REPARSE_POINT_NOT_RESOLVED;\ncase 100: return STATUS_HOST_DOWN;\ncase 102: return STATUS_CONNECTION_RESET;\ncase 101: return STATUS_NETWORK_UNREACHABLE;\ncase 105: return STATUS_INSUFFICIENT_RESOURCES;\ncase 61: return STATUS_END_OF_FILE;\ncase 67: return STATUS_CONNECTION_INVALID;\ncase 107: return STATUS_CONNECTION_INVALID;\ncase 88: return STATUS_INVALID_HANDLE;\ncase 110: return STATUS_TRANSACTION_TIMED_OUT;\n\n#endif\n"
  },
  {
    "path": "src/shared/km/errnosym.i",
    "content": "#if FUSE_ERRNO == 87 /* Windows */\n\ncase 0: return \"0\";\ncase 1: return \"EPERM\";\ncase 2: return \"ENOENT\";\ncase 3: return \"ESRCH\";\ncase 4: return \"EINTR\";\ncase 5: return \"EIO\";\ncase 6: return \"ENXIO\";\ncase 7: return \"E2BIG\";\ncase 8: return \"ENOEXEC\";\ncase 9: return \"EBADF\";\ncase 12: return \"ENOMEM\";\ncase 13: return \"EACCES\";\ncase 14: return \"EFAULT\";\ncase 16: return \"EBUSY\";\ncase 17: return \"EEXIST\";\ncase 18: return \"EXDEV\";\ncase 19: return \"ENODEV\";\ncase 20: return \"ENOTDIR\";\ncase 21: return \"EISDIR\";\ncase 22: return \"EINVAL\";\ncase 23: return \"ENFILE\";\ncase 24: return \"EMFILE\";\ncase 27: return \"EFBIG\";\ncase 28: return \"ENOSPC\";\ncase 29: return \"ESPIPE\";\ncase 30: return \"EROFS\";\ncase 31: return \"EMLINK\";\ncase 32: return \"EPIPE\";\ncase 33: return \"EDOM\";\ncase 34: return \"ERANGE\";\ncase 36: return \"EDEADLK\";\ncase 38: return \"ENAMETOOLONG\";\ncase 39: return \"ENOLCK\";\ncase 40: return \"ENOSYS\";\ncase 41: return \"ENOTEMPTY\";\ncase 42: return \"EILSEQ\";\ncase 100: return \"EADDRINUSE\";\ncase 103: return \"EALREADY\";\ncase 105: return \"ECANCELED\";\ncase 106: return \"ECONNABORTED\";\ncase 107: return \"ECONNREFUSED\";\ncase 108: return \"ECONNRESET\";\ncase 110: return \"EHOSTUNREACH\";\ncase 113: return \"EISCONN\";\ncase 114: return \"ELOOP\";\ncase 116: return \"ENETDOWN\";\ncase 117: return \"ENETRESET\";\ncase 118: return \"ENETUNREACH\";\ncase 119: return \"ENOBUFS\";\ncase 120: return \"ENODATA\";\ncase 121: return \"ENOLINK\";\ncase 126: return \"ENOTCONN\";\ncase 128: return \"ENOTSOCK\";\ncase 138: return \"ETIMEDOUT\";\n\n#elif FUSE_ERRNO == 67 /* Cygwin */\n\ncase 0: return \"0\";\ncase 1: return \"EPERM\";\ncase 2: return \"ENOENT\";\ncase 3: return \"ESRCH\";\ncase 4: return \"EINTR\";\ncase 5: return \"EIO\";\ncase 6: return \"ENXIO\";\ncase 7: return \"E2BIG\";\ncase 8: return \"ENOEXEC\";\ncase 9: return \"EBADF\";\ncase 12: return \"ENOMEM\";\ncase 13: return \"EACCES\";\ncase 14: return \"EFAULT\";\ncase 16: return \"EBUSY\";\ncase 17: return \"EEXIST\";\ncase 18: return \"EXDEV\";\ncase 19: return \"ENODEV\";\ncase 20: return \"ENOTDIR\";\ncase 21: return \"EISDIR\";\ncase 22: return \"EINVAL\";\ncase 23: return \"ENFILE\";\ncase 24: return \"EMFILE\";\ncase 27: return \"EFBIG\";\ncase 28: return \"ENOSPC\";\ncase 29: return \"ESPIPE\";\ncase 30: return \"EROFS\";\ncase 31: return \"EMLINK\";\ncase 32: return \"EPIPE\";\ncase 33: return \"EDOM\";\ncase 34: return \"ERANGE\";\ncase 45: return \"EDEADLK\";\ncase 91: return \"ENAMETOOLONG\";\ncase 46: return \"ENOLCK\";\ncase 88: return \"ENOSYS\";\ncase 90: return \"ENOTEMPTY\";\ncase 138: return \"EILSEQ\";\ncase 112: return \"EADDRINUSE\";\ncase 120: return \"EALREADY\";\ncase 140: return \"ECANCELED\";\ncase 113: return \"ECONNABORTED\";\ncase 111: return \"ECONNREFUSED\";\ncase 104: return \"ECONNRESET\";\ncase 118: return \"EHOSTUNREACH\";\ncase 127: return \"EISCONN\";\ncase 92: return \"ELOOP\";\ncase 115: return \"ENETDOWN\";\ncase 126: return \"ENETRESET\";\ncase 114: return \"ENETUNREACH\";\ncase 105: return \"ENOBUFS\";\ncase 61: return \"ENODATA\";\ncase 67: return \"ENOLINK\";\ncase 128: return \"ENOTCONN\";\ncase 108: return \"ENOTSOCK\";\ncase 116: return \"ETIMEDOUT\";\n\n#elif FUSE_ERRNO == 76 /* Linux */\n\ncase 0: return \"0\";\ncase 1: return \"EPERM\";\ncase 2: return \"ENOENT\";\ncase 3: return \"ESRCH\";\ncase 4: return \"EINTR\";\ncase 5: return \"EIO\";\ncase 6: return \"ENXIO\";\ncase 7: return \"E2BIG\";\ncase 8: return \"ENOEXEC\";\ncase 9: return \"EBADF\";\ncase 12: return \"ENOMEM\";\ncase 13: return \"EACCES\";\ncase 14: return \"EFAULT\";\ncase 16: return \"EBUSY\";\ncase 17: return \"EEXIST\";\ncase 18: return \"EXDEV\";\ncase 19: return \"ENODEV\";\ncase 20: return \"ENOTDIR\";\ncase 21: return \"EISDIR\";\ncase 22: return \"EINVAL\";\ncase 23: return \"ENFILE\";\ncase 24: return \"EMFILE\";\ncase 27: return \"EFBIG\";\ncase 28: return \"ENOSPC\";\ncase 29: return \"ESPIPE\";\ncase 30: return \"EROFS\";\ncase 31: return \"EMLINK\";\ncase 32: return \"EPIPE\";\ncase 33: return \"EDOM\";\ncase 34: return \"ERANGE\";\ncase 35: return \"EDEADLK\";\ncase 36: return \"ENAMETOOLONG\";\ncase 37: return \"ENOLCK\";\ncase 38: return \"ENOSYS\";\ncase 39: return \"ENOTEMPTY\";\ncase 84: return \"EILSEQ\";\ncase 98: return \"EADDRINUSE\";\ncase 114: return \"EALREADY\";\ncase 125: return \"ECANCELED\";\ncase 103: return \"ECONNABORTED\";\ncase 111: return \"ECONNREFUSED\";\ncase 104: return \"ECONNRESET\";\ncase 113: return \"EHOSTUNREACH\";\ncase 106: return \"EISCONN\";\ncase 40: return \"ELOOP\";\ncase 100: return \"ENETDOWN\";\ncase 102: return \"ENETRESET\";\ncase 101: return \"ENETUNREACH\";\ncase 105: return \"ENOBUFS\";\ncase 61: return \"ENODATA\";\ncase 67: return \"ENOLINK\";\ncase 107: return \"ENOTCONN\";\ncase 88: return \"ENOTSOCK\";\ncase 110: return \"ETIMEDOUT\";\n\n#endif\n"
  },
  {
    "path": "src/shared/km/file.c",
    "content": "/**\n * @file shared/km/file.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\nVOID FuseFileInstanceInit(FUSE_INSTANCE *Instance)\n{\n    KeInitializeSpinLock(&Instance->FileListLock);\n    InitializeListHead(&Instance->FileList);\n}\n\nVOID FuseFileInstanceFini(FUSE_INSTANCE *Instance)\n{\n    FUSE_FILE *File;\n\n    for (PLIST_ENTRY Entry = Instance->FileList.Flink; &Instance->FileList != Entry;)\n    {\n        File = CONTAINING_RECORD(Entry, FUSE_FILE, ListEntry);\n        Entry = Entry->Flink;\n        FuseCacheDereferenceItem(Instance->Cache, File->CacheItem);\n        FuseFree(File);\n    }\n}\n\nNTSTATUS FuseFileCreate(FUSE_INSTANCE *Instance, FUSE_FILE **PFile)\n{\n    KIRQL Irql;\n    FUSE_FILE *File;\n\n    *PFile = 0;\n\n    File = FuseAllocNonPaged(sizeof *File);\n        /* spinlocks must operate on non-paged memory */\n    if (0 == File)\n        return STATUS_INSUFFICIENT_RESOURCES;\n\n    RtlZeroMemory(File, sizeof *File);\n\n    KeAcquireSpinLock(&Instance->FileListLock, &Irql);\n    InsertTailList(&Instance->FileList, &File->ListEntry);\n    KeReleaseSpinLock(&Instance->FileListLock, Irql);\n\n    *PFile = File;\n\n    return STATUS_SUCCESS;\n}\n\nVOID FuseFileDelete(FUSE_INSTANCE *Instance, FUSE_FILE *File)\n{\n    KIRQL Irql;\n\n    KeAcquireSpinLock(&Instance->FileListLock, &Irql);\n    RemoveEntryList(&File->ListEntry);\n    KeReleaseSpinLock(&Instance->FileListLock, Irql);\n\n    FuseCacheDereferenceItem(Instance->Cache, File->CacheItem);\n\n    DEBUGFILL(File, sizeof *File);\n    FuseFree(File);\n}\n"
  },
  {
    "path": "src/shared/km/fuseop.c",
    "content": "/**\n * @file shared/km/fuseop.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\nstatic BOOLEAN FuseOpReserved_Init(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpReserved_Destroy(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpReserved_Forget(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpReserved(FUSE_CONTEXT *Context);\nstatic VOID FuseLookup(FUSE_CONTEXT *Context);\nstatic NTSTATUS FuseAccessCheck(\n    UINT32 FileUid, UINT32 FileGid, UINT32 FileMode,\n    UINT32 OrigUid, UINT32 OrigGid, UINT32 DesiredAccess,\n    PUINT32 PGrantedAccess);\nstatic VOID FusePrepareLookupPath(FUSE_CONTEXT *Context);\nstatic VOID FusePrepareLookupPath2(FUSE_CONTEXT *Context);\nstatic VOID FusePrepareLookupPath_ContextFini(FUSE_CONTEXT *Context);\nstatic VOID FuseLookupPath(FUSE_CONTEXT *Context);\nstatic VOID FuseCreateCheck(FUSE_CONTEXT *Context);\nstatic VOID FuseOpenCheck(FUSE_CONTEXT *Context);\nstatic VOID FuseOverwriteCheck(FUSE_CONTEXT *Context);\nstatic VOID FuseOpenTargetDirectoryCheck(FUSE_CONTEXT *Context);\nstatic VOID FuseRenameCheck(FUSE_CONTEXT *Context);\nstatic VOID FuseCreate(FUSE_CONTEXT *Context);\nstatic VOID FuseOpen(FUSE_CONTEXT *Context);\nstatic VOID FuseOpCreate_FileCreate(FUSE_CONTEXT *Context);\nstatic VOID FuseOpCreate_FileOpen(FUSE_CONTEXT *Context);\nstatic VOID FuseOpCreate_FileOpenIf(FUSE_CONTEXT *Context);\nstatic VOID FuseOpCreate_FileOverwrite(FUSE_CONTEXT *Context);\nstatic VOID FuseOpCreate_FileOverwriteIf(FUSE_CONTEXT *Context);\nstatic VOID FuseOpCreate_FileOpenTargetDirectory(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpCreate(FUSE_CONTEXT *Context);\nstatic INT FuseOgCreate(FUSE_CONTEXT *Context, BOOLEAN Acquire);\nstatic BOOLEAN FuseOpOverwrite(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpCleanup(FUSE_CONTEXT *Context);\nstatic INT FuseOgCleanup(FUSE_CONTEXT *Context, BOOLEAN Acquire);\nstatic BOOLEAN FuseOpClose(FUSE_CONTEXT *Context);\nstatic VOID FuseOpClose_ContextFini(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpRead(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpWrite(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpQueryInformation(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpSetInformation_SetBasicInfo(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpSetInformation_SetAllocationSize(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpSetInformation_SetFileSize(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpSetInformation_SetDelete(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpSetInformation_Rename(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpSetInformation(FUSE_CONTEXT *Context);\nstatic INT FuseOgSetInformation(FUSE_CONTEXT *Context, BOOLEAN Acquire);\nstatic BOOLEAN FuseOpQueryEa(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpSetEa(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpFlushBuffers(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpQueryVolumeInformation(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseAddDirInfo(FUSE_CONTEXT *Context,\n    PSTRING Name, UINT64 NextOffset, FUSE_PROTO_ATTR *Attr,\n    PVOID Buffer, ULONG Length, PULONG PBytesTransferred);\nstatic VOID FuseOpQueryDirectory_GetDirInfoByName(FUSE_CONTEXT *Context);\nstatic VOID FuseOpQueryDirectory_ReadDirectory(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpQueryDirectory(FUSE_CONTEXT *Context);\nstatic VOID FuseOpQueryDirectory_ContextFini(FUSE_CONTEXT *Context);\nstatic INT FuseOgQueryDirectory(FUSE_CONTEXT *Context, BOOLEAN Acquire);\nstatic BOOLEAN FuseOpFileSystemControl(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpDeviceControl(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpQuerySecurity(FUSE_CONTEXT *Context);\nstatic BOOLEAN FuseOpSetSecurity(FUSE_CONTEXT *Context);\nstatic VOID FuseSecurity_ContextFini(FUSE_CONTEXT *Context);\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(PAGE, FuseOpReserved_Init)\n#pragma alloc_text(PAGE, FuseOpReserved_Destroy)\n#pragma alloc_text(PAGE, FuseOpReserved_Forget)\n#pragma alloc_text(PAGE, FuseOpReserved)\n#pragma alloc_text(PAGE, FuseLookup)\n#pragma alloc_text(PAGE, FuseAccessCheck)\n#pragma alloc_text(PAGE, FusePrepareLookupPath)\n#pragma alloc_text(PAGE, FusePrepareLookupPath2)\n#pragma alloc_text(PAGE, FusePrepareLookupPath_ContextFini)\n#pragma alloc_text(PAGE, FuseLookupPath)\n#pragma alloc_text(PAGE, FuseCreateCheck)\n#pragma alloc_text(PAGE, FuseOpenCheck)\n#pragma alloc_text(PAGE, FuseOverwriteCheck)\n#pragma alloc_text(PAGE, FuseOpenTargetDirectoryCheck)\n#pragma alloc_text(PAGE, FuseRenameCheck)\n#pragma alloc_text(PAGE, FuseCreate)\n#pragma alloc_text(PAGE, FuseOpen)\n#pragma alloc_text(PAGE, FuseOpCreate_FileCreate)\n#pragma alloc_text(PAGE, FuseOpCreate_FileOpen)\n#pragma alloc_text(PAGE, FuseOpCreate_FileOpenIf)\n#pragma alloc_text(PAGE, FuseOpCreate_FileOverwrite)\n#pragma alloc_text(PAGE, FuseOpCreate_FileOverwriteIf)\n#pragma alloc_text(PAGE, FuseOpCreate_FileOpenTargetDirectory)\n#pragma alloc_text(PAGE, FuseOpCreate)\n#pragma alloc_text(PAGE, FuseOgCreate)\n#pragma alloc_text(PAGE, FuseOpOverwrite)\n#pragma alloc_text(PAGE, FuseOpCleanup)\n#pragma alloc_text(PAGE, FuseOgCleanup)\n#pragma alloc_text(PAGE, FuseOpClose)\n#pragma alloc_text(PAGE, FuseOpClose_ContextFini)\n#pragma alloc_text(PAGE, FuseOpRead)\n#pragma alloc_text(PAGE, FuseOpWrite)\n#pragma alloc_text(PAGE, FuseOpQueryInformation)\n#pragma alloc_text(PAGE, FuseOpSetInformation_SetBasicInfo)\n#pragma alloc_text(PAGE, FuseOpSetInformation_SetAllocationSize)\n#pragma alloc_text(PAGE, FuseOpSetInformation_SetFileSize)\n#pragma alloc_text(PAGE, FuseOpSetInformation_SetDelete)\n#pragma alloc_text(PAGE, FuseOpSetInformation_Rename)\n#pragma alloc_text(PAGE, FuseOpSetInformation)\n#pragma alloc_text(PAGE, FuseOgSetInformation)\n#pragma alloc_text(PAGE, FuseOpQueryEa)\n#pragma alloc_text(PAGE, FuseOpSetEa)\n#pragma alloc_text(PAGE, FuseOpFlushBuffers)\n#pragma alloc_text(PAGE, FuseOpQueryVolumeInformation)\n#pragma alloc_text(PAGE, FuseAddDirInfo)\n#pragma alloc_text(PAGE, FuseOpQueryDirectory_GetDirInfoByName)\n#pragma alloc_text(PAGE, FuseOpQueryDirectory_ReadDirectory)\n#pragma alloc_text(PAGE, FuseOpQueryDirectory)\n#pragma alloc_text(PAGE, FuseOpQueryDirectory_ContextFini)\n#pragma alloc_text(PAGE, FuseOgQueryDirectory)\n#pragma alloc_text(PAGE, FuseOpFileSystemControl)\n#pragma alloc_text(PAGE, FuseOpDeviceControl)\n#pragma alloc_text(PAGE, FuseOpQuerySecurity)\n#pragma alloc_text(PAGE, FuseOpSetSecurity)\n#pragma alloc_text(PAGE, FuseSecurity_ContextFini)\n#endif\n\nstatic BOOLEAN FuseOpReserved_Init(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseProtoSendInit(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FUSE_INSTANCE *Instance = Context->Instance;\n        if (FUSE_PROTO_VERSION != Context->FuseResponse->rsp.init.major)\n        {\n            Instance->VersionMajor = (UINT32)-1;\n            KeSetEvent(&Instance->InitEvent, 1, FALSE);\n\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_CONNECTION_REFUSED;\n            coro_break;\n        }\n\n        Instance->VersionMajor = Context->FuseResponse->rsp.init.major;\n        Instance->VersionMinor = Context->FuseResponse->rsp.init.minor;\n        // !!!: REVISIT\n        KeSetEvent(&Instance->InitEvent, 1, FALSE);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpReserved_Destroy(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseProtoSendDestroy(Context));\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpReserved_Forget(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    FUSE_INSTANCE *Instance = Context->Instance;\n\n    ASSERT(!IsListEmpty(&Context->Forget.ForgetList));\n    if (16 > Instance->VersionMinor ||\n        &Context->Forget.ForgetList == Context->Forget.ForgetList.Flink->Flink ||\n        DEBUGTEST(10))\n        FuseProtoFillForget(Context);\n    else\n        FuseProtoFillBatchForget(Context);\n\n    return FALSE;\n}\n\nstatic BOOLEAN FuseOpReserved(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    switch (Context->InternalResponse->Hint)\n    {\n    case FUSE_PROTO_OPCODE_INIT:\n        return FuseOpReserved_Init(Context);\n    case FUSE_PROTO_OPCODE_DESTROY:\n        return FuseOpReserved_Destroy(Context);\n    case FUSE_PROTO_OPCODE_FORGET:\n    case FUSE_PROTO_OPCODE_BATCH_FORGET:\n        return FuseOpReserved_Forget(Context);\n    default:\n        return FALSE;\n    }\n}\n\nstatic VOID FuseLookup(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_ENTRY EntryBuf, *Entry = &EntryBuf;\n    PVOID CacheItem;\n\n    coro_block (Context->CoroState)\n    {\n        if (!FuseCacheGetEntry(Context->Instance->Cache,\n            Context->Lookup.Ino, &Context->Lookup.Name, Entry, &CacheItem))\n        {\n            if (FUSE_PROTO_ROOT_INO == Context->Lookup.Ino &&\n                1 == Context->Lookup.Name.Length && '/' == Context->Lookup.Name.Buffer[0])\n            {\n                coro_await (FuseProtoSendGetattr(Context));\n                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                    coro_break;\n\n                RtlZeroMemory(Entry, sizeof *Entry);\n                Entry->nodeid = FUSE_PROTO_ROOT_INO;\n                Entry->entry_valid = Entry->attr_valid =\n                    Context->FuseResponse->rsp.getattr.attr_valid;\n                Entry->entry_valid_nsec = Entry->attr_valid_nsec =\n                    Context->FuseResponse->rsp.getattr.attr_valid_nsec;\n                Entry->attr = Context->FuseResponse->rsp.getattr.attr;\n            }\n            else\n            {\n                coro_await (FuseProtoSendLookup(Context));\n                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                    coro_break;\n\n                Entry = &Context->FuseResponse->rsp.lookup.entry;\n            }\n\n            FuseCacheSetEntry(\n                Context->Instance->Cache,\n                Context->Lookup.Ino, &Context->Lookup.Name, Entry, &CacheItem);\n        }\n\n        Context->Lookup.CacheItem = CacheItem;\n        Context->Lookup.Ino = Entry->nodeid;\n        Context->Lookup.Attr = Entry->attr;\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n}\n\n/* code borrowed from winfsp/src/ku/posix.c - see there for comments/explanations */\n#define FusePosixDefaultPerm            \\\n    (SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_READ_EA)\n#define FusePosixOwnerDefaultPerm       \\\n    (FusePosixDefaultPerm | DELETE | WRITE_DAC | WRITE_OWNER | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA)\nstatic inline ACCESS_MASK FusePosixMapPermissionToAccessMask(UINT32 Mode, UINT32 Perm)\n{\n    ACCESS_MASK DeleteChild = 0040000 == (Mode & 0041000) ? FILE_DELETE_CHILD : 0;\n    return\n        ((Perm & 4) ? FILE_READ_DATA : 0) |\n        ((Perm & 2) ? FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA | FILE_APPEND_DATA | DeleteChild : 0) |\n        ((Perm & 1) ? FILE_EXECUTE : 0);\n}\n\nstatic NTSTATUS FuseAccessCheck(\n    UINT32 FileUid, UINT32 FileGid, UINT32 FileMode,\n    UINT32 OrigUid, UINT32 OrigGid, UINT32 DesiredAccess,\n    PUINT32 PGrantedAccess)\n{\n    PAGED_CODE();\n\n    UINT32 FileAccess, RequiredAccess;\n\n    if (OrigUid == FileUid)\n        FileAccess = FusePosixOwnerDefaultPerm |\n            FusePosixMapPermissionToAccessMask(FileMode & ~001000, (FileMode & 0700) >> 6);\n    else if (OrigGid == FileGid)\n        FileAccess = FusePosixDefaultPerm |\n            FusePosixMapPermissionToAccessMask(FileMode, (FileMode & 0070) >> 3);\n    else\n        FileAccess = FusePosixDefaultPerm |\n            FusePosixMapPermissionToAccessMask(FileMode, (FileMode & 0007));\n\n    RequiredAccess = DesiredAccess & (STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL);\n\n    if (RequiredAccess == (FileAccess & RequiredAccess))\n    {\n        if (0 != PGrantedAccess)\n            *PGrantedAccess = FlagOn(DesiredAccess, MAXIMUM_ALLOWED) ? FileAccess : RequiredAccess;\n        return STATUS_SUCCESS;\n    }\n    else\n    {\n        if (0 != PGrantedAccess)\n            *PGrantedAccess = 0;\n        return STATUS_ACCESS_DENIED;\n    }\n}\n\nstatic VOID FusePrepareLookupPath(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    UINT32 Uid = 0, Gid = 0, Pid = 0;\n    PVOID CacheGen = 0;\n    PSTR PosixPath = 0;\n    PWSTR FileName = 0;\n    UINT64 AccessToken = 0;\n    PACCESS_TOKEN AccessTokenObject = 0;\n    UINT32 IsUserMode = 1;\n    UINT32 HasTraversePrivilege = 0;\n\n    switch (Context->InternalRequest->Kind)\n    {\n    case FspFsctlTransactCreateKind:\n        FileName = (PWSTR)Context->InternalRequest->Buffer;\n        AccessToken = Context->InternalRequest->Req.Create.AccessToken;\n        IsUserMode = Context->InternalRequest->Req.Create.UserMode;\n        HasTraversePrivilege = Context->InternalRequest->Req.Create.HasTraversePrivilege;\n        break;\n    case FspFsctlTransactCleanupKind:\n        ASSERT(Context->InternalRequest->Req.Cleanup.Delete);\n        FileName = (PWSTR)Context->InternalRequest->Buffer;\n        IsUserMode = 0;\n        HasTraversePrivilege = 1;\n        break;\n    case FspFsctlTransactSetInformationKind:\n        ASSERT(FileRenameInformation ==\n            Context->InternalRequest->Req.SetInformation.FileInformationClass);\n        FileName = (PWSTR)(Context->InternalRequest->Buffer +\n            Context->InternalRequest->Req.SetInformation.Info.Rename.NewFileName.Offset);\n        AccessToken = Context->InternalRequest->Req.SetInformation.Info.Rename.AccessToken;\n        IsUserMode = 1;\n        HasTraversePrivilege = 1;\n        break;\n    default:\n        ASSERT(FALSE);\n        Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_PARAMETER;\n        goto exit;\n    }\n\n    if (0 != FileName)\n    {\n        Context->InternalResponse->IoStatus.Status = FuseCacheReferenceGen(\n            Context->Instance->Cache, &CacheGen);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            goto exit;\n\n        Context->InternalResponse->IoStatus.Status = FspPosixMapWindowsToPosixPathEx(\n            FileName, &PosixPath, TRUE);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            goto exit;\n    }\n\n    if (0 != AccessToken)\n    {\n        Context->InternalResponse->IoStatus.Status = ObReferenceObjectByHandle(\n            FSP_FSCTL_TRANSACT_REQ_TOKEN_HANDLE(AccessToken),\n            TOKEN_QUERY,\n            *SeTokenObjectType,\n            UserMode,\n            &AccessTokenObject,\n            0/*HandleInformation*/);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            goto exit;\n\n        Context->InternalResponse->IoStatus.Status = FuseGetTokenUid(\n            AccessTokenObject, TokenUser, &Uid);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            goto exit;\n\n        Context->InternalResponse->IoStatus.Status = FuseGetTokenUid(\n            AccessTokenObject, TokenPrimaryGroup, &Gid);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            goto exit;\n\n        ObDereferenceObject(AccessTokenObject);\n\n        Pid = FSP_FSCTL_TRANSACT_REQ_TOKEN_PID(AccessToken);\n    }\n\n    Context->OrigUid = Uid;\n    Context->OrigGid = Gid;\n    Context->OrigPid = Pid;\n\n    ASSERT(0 == Context->LookupPath.OrigPath.Buffer);\n    RtlInitString(&Context->LookupPath.OrigPath, PosixPath);\n    Context->LookupPath.CacheGen = CacheGen;\n    Context->LookupPath.UserMode = IsUserMode;\n    Context->LookupPath.HasTraversePrivilege = HasTraversePrivilege;\n\n    Context->Fini = FusePrepareLookupPath_ContextFini;\n\n    Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n\nexit:\n    if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n    {\n        FspPosixDeletePath(PosixPath);\n            /* handles NULL paths */\n        FuseCacheDereferenceGen(Context->Instance->Cache, CacheGen);\n            /* handles NULL gens */\n    }\n}\n\nstatic VOID FusePrepareLookupPath2(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    PSTR PosixPath = 0;\n    PWSTR FileName = 0;\n\n    switch (Context->InternalRequest->Kind)\n    {\n    case FspFsctlTransactSetInformationKind:\n        ASSERT(FileRenameInformation ==\n            Context->InternalRequest->Req.SetInformation.FileInformationClass);\n        FileName = (PWSTR)Context->InternalRequest->Buffer;\n        break;\n    default:\n        ASSERT(FALSE);\n        Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_PARAMETER;\n        goto exit;\n    }\n\n    if (0 != FileName)\n    {\n        Context->InternalResponse->IoStatus.Status = FspPosixMapWindowsToPosixPathEx(\n            FileName, &PosixPath, TRUE);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            goto exit;\n    }\n\n    ASSERT(0 == Context->LookupPath.OrigPath.Buffer);\n    ASSERT(0 != Context->LookupPath.OrigPath2.Buffer);\n    RtlInitString(&Context->LookupPath.OrigPath, PosixPath);\n\n    Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n\nexit:\n    if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n    {\n        FspPosixDeletePath(PosixPath);\n            /* handles NULL paths */\n    }\n}\n\nstatic VOID FusePrepareLookupPath_ContextFini(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    if (FspFsctlTransactCreateKind == Context->InternalRequest->Kind &&\n        0 != Context->File)\n        FuseFileDelete(Context->Instance, Context->File);\n\n    FspPosixDeletePath(Context->LookupPath.OrigPath2.Buffer);\n        /* handles NULL paths */\n    FspPosixDeletePath(Context->LookupPath.OrigPath.Buffer);\n        /* handles NULL paths */\n    FuseCacheDereferenceGen(Context->Instance->Cache, Context->LookupPath.CacheGen);\n        /* handles NULL gens */\n}\n\nstatic VOID FuseLookupPath(FUSE_CONTEXT *Context)\n{\n#define RootName                        (1 == Context->LookupPath.Name.Length && '/' == Context->LookupPath.Name.Buffer[0])\n#define LastName                        (0 == Context->LookupPath.Remain.Length)\n#define UserMode                        (Context->LookupPath.UserMode)\n#define TravPriv                        (Context->LookupPath.HasTraversePrivilege)\n\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->LookupPath.Ino = FUSE_PROTO_ROOT_INO;\n        DEBUGFILL(&Context->Lookup.Attr, sizeof Context->Lookup.Attr);\n        while (1) /* for (;;) produces \"warning C4702: unreachable code\" */\n        {\n            FusePosixPathPrefix(&Context->LookupPath.Remain, &Context->LookupPath.Name, &Context->LookupPath.Remain);\n\n            /*\n             * - RootName:\n             *     - UserMode:\n             *         - !LastName && !TravPriv:\n             *             - Lookup\n             *             - TraverseCheck\n             *         - LastName:\n             *             - Lookup\n             *             - AccessCheck\n             *     - !UserMode:\n             *         - LastName:\n             *             - Lookup\n             * - !RootName:\n             *     - Lookup\n             *     - UserMode:\n             *         - !LastName && !TravPriv:\n             *             - TraverseCheck\n             *         - LastName:\n             *             - AccessCheck\n             */\n            if (!RootName || LastName || (UserMode && !TravPriv))\n            {\n                coro_await (FuseLookup(Context));\n                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                    coro_break;\n\n                if (UserMode)\n                {\n                    if (!LastName && !TravPriv)\n                    {\n                        Context->InternalResponse->IoStatus.Status = FuseAccessCheck(\n                            Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid,\n                            Context->LookupPath.Attr.mode,\n                            Context->OrigUid, Context->OrigGid,\n                            FILE_TRAVERSE, 0);\n                        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                            coro_break;\n                    }\n                    else if (LastName)\n                    {\n                        Context->InternalResponse->IoStatus.Status = FuseAccessCheck(\n                            Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid,\n                            Context->LookupPath.Attr.mode,\n                            Context->OrigUid, Context->OrigGid,\n                            Context->LookupPath.DesiredAccess, &Context->LookupPath.GrantedAccess);\n                        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                            coro_break;\n                    }\n                }\n            }\n\n            if (LastName)\n            {\n                ASSERT(DEBUGGOOD(&Context->Lookup.Attr, sizeof Context->Lookup.Attr));\n                break;\n            }\n        }\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n#undef TravPriv\n#undef UserMode\n#undef LastName\n#undef RootName\n}\n\nstatic VOID FuseCreateCheck(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    /*\n     * CreateCheck for a new file consists of checking the parent directory\n     * for the FILE_ADD_SUBDIRECTORY or FILE_ADD_FILE rights (depending on\n     * whether we are creating a file or directory).\n     *\n     * If the access check succeeds and MAXIMUM_ALLOWED has been requested\n     * then we go ahead and grant all access to the creator.\n     */\n\n    coro_block (Context->CoroState)\n    {\n        if (Context->InternalRequest->Req.Create.HasTrailingBackslash &&\n            !FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DIRECTORY_FILE))\n        {\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_OBJECT_NAME_INVALID;\n            coro_break;\n        }\n\n        if (Context->InternalRequest->Req.Create.HasRestorePrivilege)\n            Context->LookupPath.DesiredAccess = 0;\n        else if (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DIRECTORY_FILE))\n            Context->LookupPath.DesiredAccess = FILE_ADD_SUBDIRECTORY;\n        else\n            Context->LookupPath.DesiredAccess = FILE_ADD_FILE;\n\n        FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0);\n        coro_await (FuseLookupPath(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess =\n            FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED) ?\n                IoGetFileObjectGenericMapping()->GenericAll :\n                Context->InternalRequest->Req.Create.DesiredAccess;\n        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |=\n            Context->InternalRequest->Req.Create.GrantedAccess;\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n}\n\nstatic VOID FuseOpenCheck(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    /*\n     * OpenCheck consists of checking the file for the desired access,\n     * unless FILE_DELETE_ON_CLOSE is requested in which case we also\n     * check for DELETE access.\n     *\n     * If the access check succeeds and MAXIMUM_ALLOWED was not requested\n     * then we reset the DELETE access based on whether it was actually\n     * requested in DesiredAccess.\n     */\n\n    coro_block (Context->CoroState)\n    {\n        Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess |\n            (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DELETE_ON_CLOSE) ?\n                DELETE : 0);\n\n        Context->LookupPath.Remain = Context->LookupPath.OrigPath;\n        coro_await (FuseLookupPath(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess;\n        if (!FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED))\n            Context->InternalResponse->Rsp.Create.Opened.GrantedAccess &= ~DELETE |\n                (Context->InternalRequest->Req.Create.DesiredAccess & DELETE);\n        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |=\n            Context->InternalRequest->Req.Create.GrantedAccess;\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n}\n\nstatic VOID FuseOverwriteCheck(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    /*\n     * OverwriteCheck consists of checking the file for the desired access,\n     * unless FILE_DELETE_ON_CLOSE is requested in which case we also\n     * check for DELETE access. Furthermore we grant DELETE or FILE_WRITE_DATA\n     * access based on whether this is a Supersede or Overwrite operation.\n     *\n     * If the access check succeeds and MAXIMUM_ALLOWED was not requested\n     * then we reset the DELETE and FILE_WRITE_DATA accesses based on whether\n     * they were actually requested in DesiredAccess.\n     */\n\n    coro_block (Context->CoroState)\n    {\n        Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess |\n            (FILE_SUPERSEDE == ((Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff) ?\n                DELETE : FILE_WRITE_DATA) |\n            (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DELETE_ON_CLOSE) ?\n                DELETE : 0);\n\n        Context->LookupPath.Remain = Context->LookupPath.OrigPath;\n        coro_await (FuseLookupPath(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess;\n        if (!FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED))\n            Context->InternalResponse->Rsp.Create.Opened.GrantedAccess &= ~(DELETE | FILE_WRITE_DATA) |\n                (Context->InternalRequest->Req.Create.DesiredAccess & (DELETE | FILE_WRITE_DATA));\n        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |=\n            Context->InternalRequest->Req.Create.GrantedAccess;\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n}\n\nstatic VOID FuseOpenTargetDirectoryCheck(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    /*\n     * OpenTargetDirectoryCheck consists of checking the parent directory\n     * for the desired access.\n     */\n\n    coro_block (Context->CoroState)\n    {\n        Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess;\n\n        FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0);\n        coro_await (FuseLookupPath(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess;\n        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |=\n            Context->InternalRequest->Req.Create.GrantedAccess;\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n}\n\nstatic VOID FuseRenameCheck(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    /*\n     * RenameCheck consists of checking the new file name for DELETE access.\n     *\n     * The following assumptions are being made here for a file that is going\n     * to be replaced:\n     * -   The new file is in the same directory as the old one. In that case\n     *     there is no need for traverse access checks as they have been already\n     *     performed (if necessary) when opening the file under the existing file\n     *     name.\n     * -   The new file is in a different directory than the old one. In that case\n     *     NTOS called us with SL_OPEN_TARGET_DIRECTORY and we performed any\n     *     necessary traverse access checks at that time.\n     */\n\n    coro_block (Context->CoroState)\n    {\n        Context->LookupPath.DesiredAccess = 0;\n\n        FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0);\n        coro_await (FuseLookupPath(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->LookupPath.Ino2 = Context->LookupPath.Ino;\n\n        FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name);\n        coro_await (FuseLookup(Context));\n        if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n        {\n            if (0 != Context->InternalRequest->Req.SetInformation.Info.Rename.AccessToken)\n            {\n                Context->InternalResponse->IoStatus.Status = FuseAccessCheck(\n                    Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid,\n                    Context->LookupPath.Attr.mode,\n                    Context->OrigUid, Context->OrigGid,\n                    DELETE, &Context->LookupPath.GrantedAccess);\n                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                    coro_break;\n            }\n\n            Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n        }\n\n        Context->LookupPath.OrigPath2 = Context->LookupPath.OrigPath;\n        Context->LookupPath.Name2 = Context->LookupPath.Name;\n\n        Context->LookupPath.Ino = 0;\n        Context->LookupPath.OrigPath.Length = Context->LookupPath.OrigPath.MaximumLength = 0;\n        Context->LookupPath.OrigPath.Buffer = 0;\n        Context->LookupPath.Name.Length = Context->LookupPath.Name.MaximumLength = 0;\n        Context->LookupPath.Name.Buffer = 0;\n    }\n}\n\nstatic VOID FuseCreate(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->InternalResponse->IoStatus.Status = FuseFileCreate(Context->Instance, &Context->File);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->File->OpenFlags = 0x0100 | 0x0400 | 2 /*O_CREAT|O_EXCL|O_RDWR*/;\n\n        Context->LookupPath.Attr.rdev = 0;\n        Context->LookupPath.Attr.mode = 0777;\n        if (0 != Context->InternalRequest->Req.Create.SecurityDescriptor.Offset)\n        {\n            UINT32 Uid, Gid, Mode;\n\n            Uid = Context->OrigUid;\n            Gid = Context->OrigGid;\n            Context->InternalResponse->IoStatus.Status = FspPosixMapSecurityDescriptorToPermissions(\n                (PSECURITY_DESCRIPTOR)(Context->InternalRequest->Buffer +\n                    Context->InternalRequest->Req.Create.SecurityDescriptor.Offset),\n                (PVOID)((UINT_PTR)&Uid | 1), (PVOID)((UINT_PTR)&Gid | 1), &Mode);\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            Context->LookupPath.Attr.mode = Mode;\n            Context->LookupPath.Chown = Uid != Context->OrigUid || Gid != Context->OrigGid;\n        }\n\n        if (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DIRECTORY_FILE))\n        {\n            coro_await (FuseProtoSendMkdir(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            FuseCacheSetEntry(\n                Context->Instance->Cache,\n                Context->LookupPath.Ino, &Context->LookupPath.Name,\n                &Context->FuseResponse->rsp.mkdir.entry,\n                &Context->LookupPath.CacheItem);\n\n            Context->LookupPath.Ino = Context->FuseResponse->rsp.mkdir.entry.nodeid;\n            Context->LookupPath.Attr = Context->FuseResponse->rsp.mkdir.entry.attr;\n\n            coro_await (FuseProtoSendOpendir(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            Context->LookupPath.DisableCache =\n                BooleanFlagOn(Context->FuseResponse->rsp.open.open_flags, FUSE_PROTO_OPEN_DIRECT_IO);\n\n            Context->File->Ino = Context->LookupPath.Ino;\n            Context->File->Fh = Context->FuseResponse->rsp.open.fh;\n            Context->File->IsDirectory = TRUE;\n            Context->File->CacheItem = Context->LookupPath.CacheItem;\n            FuseCacheReferenceItem(Context->Instance->Cache,\n                Context->File->CacheItem);\n        }\n        else\n        {\n            coro_await (FuseProtoSendCreate(Context));\n            if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            {\n                FuseCacheSetEntry(\n                    Context->Instance->Cache,\n                    Context->LookupPath.Ino, &Context->LookupPath.Name,\n                    &Context->FuseResponse->rsp.create.entry,\n                    &Context->LookupPath.CacheItem);\n\n                Context->LookupPath.Ino = Context->FuseResponse->rsp.create.entry.nodeid;\n                Context->LookupPath.Attr = Context->FuseResponse->rsp.create.entry.attr;\n                Context->LookupPath.DisableCache =\n                    BooleanFlagOn(Context->FuseResponse->rsp.create.open_flags, FUSE_PROTO_OPEN_DIRECT_IO);\n\n                Context->File->Ino = Context->LookupPath.Ino;\n                Context->File->Fh = Context->FuseResponse->rsp.create.fh;\n                Context->File->CacheItem = Context->LookupPath.CacheItem;\n                FuseCacheReferenceItem(Context->Instance->Cache,\n                    Context->File->CacheItem);\n            }\n            else\n            {\n                if (STATUS_INVALID_DEVICE_REQUEST != Context->InternalResponse->IoStatus.Status)\n                    coro_break;\n\n                coro_await (FuseProtoSendMknod(Context));\n                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                    coro_break;\n\n                FuseCacheSetEntry(\n                    Context->Instance->Cache,\n                    Context->LookupPath.Ino, &Context->LookupPath.Name,\n                    &Context->FuseResponse->rsp.mknod.entry,\n                    &Context->LookupPath.CacheItem);\n\n                Context->LookupPath.Ino = Context->FuseResponse->rsp.mknod.entry.nodeid;\n                Context->LookupPath.Attr = Context->FuseResponse->rsp.mknod.entry.attr;\n\n                coro_await (FuseProtoSendOpen(Context));\n                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                    coro_break;\n\n                Context->LookupPath.DisableCache =\n                    BooleanFlagOn(Context->FuseResponse->rsp.open.open_flags, FUSE_PROTO_OPEN_DIRECT_IO);\n\n                Context->File->Ino = Context->LookupPath.Ino;\n                Context->File->Fh = Context->FuseResponse->rsp.open.fh;\n                Context->File->CacheItem = Context->LookupPath.CacheItem;\n                FuseCacheReferenceItem(Context->Instance->Cache,\n                    Context->File->CacheItem);\n            }\n        }\n\n        Context->InternalResponse->Rsp.Create.Opened.UserContext2 =\n            (UINT64)(UINT_PTR)Context->File;\n        FuseAttrToFileInfo(Context->Instance, &Context->LookupPath.Attr,\n            &Context->InternalResponse->Rsp.Create.Opened.FileInfo);\n        Context->InternalResponse->Rsp.Create.Opened.DisableCache =\n            Context->LookupPath.DisableCache;\n\n        if (Context->LookupPath.Chown)\n        {\n            UINT32 Uid, Gid, Mode;\n\n            Uid = Context->OrigUid;\n            Gid = Context->OrigGid;\n            Context->InternalResponse->IoStatus.Status = FspPosixMapSecurityDescriptorToPermissions(\n                (PSECURITY_DESCRIPTOR)(Context->InternalRequest->Buffer +\n                    Context->InternalRequest->Req.Create.SecurityDescriptor.Offset),\n                (PVOID)((UINT_PTR)&Uid | 1), (PVOID)((UINT_PTR)&Gid | 1), &Mode);\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                goto cleanup;\n\n            Context->LookupPath.Attr.uid = Uid;\n            Context->LookupPath.Attr.gid = Gid;\n            coro_await (FuseProtoSendLookupChown(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status) &&\n                STATUS_INVALID_DEVICE_REQUEST != Context->InternalResponse->IoStatus.Status)\n                goto cleanup;\n\n            FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.setattr.attr,\n                &Context->InternalResponse->Rsp.Create.Opened.FileInfo);\n        }\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n        Context->InternalResponse->IoStatus.Information = FILE_CREATED;\n\n        /* ensure that ContextFini will not free the newly opened file */\n        Context->File = 0;\n\n        coro_break;\n\n    cleanup:\n        if (Context->File->IsDirectory)\n            coro_await (FuseProtoSendReleasedir(Context));\n        else\n            coro_await (FuseProtoSendRelease(Context));\n    }\n}\n\nstatic VOID FuseOpen(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->InternalResponse->IoStatus.Status = FuseFileCreate(Context->Instance, &Context->File);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        UINT32 GrantedAccess = Context->InternalResponse->Rsp.Create.Opened.GrantedAccess;\n        switch (GrantedAccess & (FILE_READ_DATA | FILE_WRITE_DATA))\n        {\n        default:\n        case FILE_READ_DATA:\n            Context->File->OpenFlags = 0/*O_RDONLY*/;\n            break;\n        case FILE_WRITE_DATA:\n            Context->File->OpenFlags = 1/*O_WRONLY*/;\n            break;\n        case FILE_READ_DATA | FILE_WRITE_DATA:\n            Context->File->OpenFlags = 2/*O_RDWR*/;\n            break;\n        }\n\n        UINT32 Type = Context->LookupPath.Attr.mode & 0170000;\n        if (0120000/* S_IFLNK  */ == Type ||\n            0010000/* S_IFIFO  */ == Type ||\n            0020000/* S_IFCHR  */ == Type ||\n            0060000/* S_IFBLK  */ == Type ||\n            0140000/* S_IFSOCK */ == Type)\n        {\n            Context->LookupPath.DisableCache = TRUE;\n\n            Context->File->Ino = Context->LookupPath.Ino;\n            Context->File->IsReparsePoint = TRUE;\n        }\n        else\n        if (0040000/* S_IFDIR  */ == Type)\n        {\n            coro_await (FuseProtoSendOpendir(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            Context->LookupPath.DisableCache =\n                BooleanFlagOn(Context->FuseResponse->rsp.open.open_flags, FUSE_PROTO_OPEN_DIRECT_IO);\n\n            Context->File->Ino = Context->LookupPath.Ino;\n            Context->File->Fh = Context->FuseResponse->rsp.open.fh;\n            Context->File->IsDirectory = TRUE;\n        }\n        else\n        {\n            /*\n             * Some Windows applications specify FILE_APPEND_DATA without\n             * FILE_WRITE_DATA when opening files for appending.\n             *\n             * NOTE: GrantedAccess has been initialized above and there is no coro_yield or\n             * coro_await between that initialization and this use.\n             */\n            if (GrantedAccess & FILE_APPEND_DATA)\n            {\n                if (Context->File->OpenFlags == 0)\n                    Context->File->OpenFlags = 1/* O_WRONLY */;\n                Context->File->OpenFlags |= 8/*O_APPEND*/;\n            }\n\n            coro_await (FuseProtoSendOpen(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            Context->LookupPath.DisableCache =\n                BooleanFlagOn(Context->FuseResponse->rsp.open.open_flags, FUSE_PROTO_OPEN_DIRECT_IO);\n\n            Context->File->Ino = Context->LookupPath.Ino;\n            Context->File->Fh = Context->FuseResponse->rsp.open.fh;\n        }\n\n        Context->File->CacheItem = Context->LookupPath.CacheItem;\n        FuseCacheReferenceItem(Context->Instance->Cache,\n            Context->File->CacheItem);\n\n        Context->InternalResponse->Rsp.Create.Opened.UserContext2 =\n            (UINT64)(UINT_PTR)Context->File;\n        FuseAttrToFileInfo(Context->Instance, &Context->LookupPath.Attr,\n            &Context->InternalResponse->Rsp.Create.Opened.FileInfo);\n        Context->InternalResponse->Rsp.Create.Opened.DisableCache =\n            Context->LookupPath.DisableCache;\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n        Context->InternalResponse->IoStatus.Information = FILE_OPENED;\n\n        /* ensure that ContextFini will not free the newly opened file */\n        Context->File = 0;\n    }\n}\n\nstatic VOID FuseOpCreate_FileCreate(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseCreateCheck(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name);\n        coro_await (FuseCreate(Context));\n    }\n}\n\nstatic VOID FuseOpCreate_FileOpen(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseOpenCheck(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        coro_await (FuseOpen(Context));\n    }\n}\n\nstatic VOID FuseOpCreate_FileOpenIf(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseOpenCheck(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n        {\n            if (STATUS_OBJECT_NAME_NOT_FOUND != Context->InternalResponse->IoStatus.Status)\n                coro_break;\n\n            coro_await (FuseCreateCheck(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name);\n            coro_await (FuseCreate(Context));\n        }\n        else\n            coro_await (FuseOpen(Context));\n    }\n}\n\nstatic VOID FuseOpCreate_FileOverwrite(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseOverwriteCheck(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        coro_await (FuseOpen(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->IoStatus.Information = FILE_OVERWRITTEN;\n    }\n}\n\nstatic VOID FuseOpCreate_FileOverwriteIf(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseOverwriteCheck(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n        {\n            if (STATUS_OBJECT_NAME_NOT_FOUND != Context->InternalResponse->IoStatus.Status)\n                coro_break;\n\n            coro_await (FuseCreateCheck(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name);\n            coro_await (FuseCreate(Context));\n        }\n        else\n        {\n            coro_await (FuseOpen(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            Context->InternalResponse->IoStatus.Information = FILE_OVERWRITTEN;\n        }\n    }\n}\n\nstatic VOID FuseOpCreate_FileOpenTargetDirectory(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseOpenTargetDirectoryCheck(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        coro_await (FuseOpen(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name);\n        coro_await (FuseLookup(Context));\n        Context->InternalResponse->IoStatus.Information =\n            NT_SUCCESS(Context->InternalResponse->IoStatus.Status) ?\n                FILE_EXISTS : FILE_DOES_NOT_EXIST;\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n}\n\nstatic BOOLEAN FuseOpCreate(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        if (Context->InternalRequest->Req.Create.NamedStream)\n        {\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_OBJECT_NAME_INVALID;\n            coro_break;\n        }\n\n        FusePrepareLookupPath(Context);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        UINT32 Disposition = (Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff;\n        if (Context->InternalRequest->Req.Create.OpenTargetDirectory)\n            coro_await (FuseOpCreate_FileOpenTargetDirectory(Context));\n        else\n        if (FILE_CREATE == Disposition)\n            coro_await (FuseOpCreate_FileCreate(Context));\n        else\n        if (FILE_OPEN == Disposition)\n            coro_await (FuseOpCreate_FileOpen(Context));\n        else\n        if (FILE_OPEN_IF == Disposition)\n            coro_await (FuseOpCreate_FileOpenIf(Context));\n        else\n        if (FILE_OVERWRITE == Disposition)\n            coro_await (FuseOpCreate_FileOverwrite(Context));\n        else\n        if (FILE_OVERWRITE_IF == Disposition || FILE_SUPERSEDE == Disposition)\n            coro_await (FuseOpCreate_FileOverwriteIf(Context));\n        else\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_PARAMETER;\n    }\n\n    return coro_active();\n}\n\nstatic INT FuseOgCreate(FUSE_CONTEXT *Context, BOOLEAN Acquire)\n{\n    PAGED_CODE();\n\n    if (Acquire)\n    {\n        INT Result;\n        if (FILE_OPEN != ((Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff))\n            Result = FuseOpGuardAcquireExclusive(Context);\n        else\n            Result = FuseOpGuardAcquireShared(Context);\n#if DBG\n        /*\n         * In debug builds we add an artificial delay to our opens to test alertable locks.\n         */\n        if (Result)\n        {\n            UNICODE_STRING LockDly, FileName;\n            RtlInitUnicodeString(&LockDly, L\"\\\\$LOCKDLY\");\n            FileName.Length = FileName.MaximumLength =\n                Context->InternalRequest->FileName.Size - sizeof(WCHAR);\n            FileName.Buffer = (PVOID)(\n                Context->InternalRequest->Buffer + Context->InternalRequest->FileName.Offset);\n            if (RtlEqualUnicodeString(&LockDly, &FileName, FALSE))\n            {\n                LARGE_INTEGER Delay;\n                Delay.QuadPart = 5000/*ms*/ * -10000LL;\n                KeDelayExecutionThread(KernelMode, FALSE, &Delay);\n            }\n        }\n#endif\n        return Result;\n    }\n    else\n    {\n        if (FILE_OPEN != ((Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff))\n            return FuseOpGuardReleaseExclusive(Context);\n        else\n            return FuseOpGuardReleaseShared(Context);\n    }\n}\n\nstatic BOOLEAN FuseOpOverwrite(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Overwrite.UserContext2;\n\n        //Context->Setattr.Attr.size = 0;\n        coro_await (FuseProtoSendFtruncate(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FuseCacheQuickExpireItem(Context->Instance->Cache,\n            Context->File->CacheItem);\n\n        FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr,\n            &Context->InternalResponse->Rsp.Overwrite.FileInfo);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpCleanup(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        if (Context->InternalRequest->Req.Cleanup.Delete)\n        {\n            /* NOTE: CLEANUP cannot report failure! */\n\n            Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Cleanup.UserContext2;\n\n            FusePrepareLookupPath(Context);\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0);\n            coro_await (FuseLookupPath(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name);\n            if (Context->File->IsDirectory)\n                coro_await (FuseProtoSendRmdir(Context));\n            else\n                coro_await (FuseProtoSendUnlink(Context));\n\n            FuseCacheRemoveEntry(\n                Context->Instance->Cache,\n                Context->Lookup.Ino, &Context->Lookup.Name);\n\n            Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n        }\n    }\n\n    return coro_active();\n}\n\nstatic INT FuseOgCleanup(FUSE_CONTEXT *Context, BOOLEAN Acquire)\n{\n    PAGED_CODE();\n\n    if (Acquire)\n    {\n        if (Context->InternalRequest->Req.Cleanup.Delete)\n            return FuseOpGuardAcquireExclusive(Context);\n        else\n            return FuseOpGuardFalse;\n    }\n    else\n    {\n        if (Context->InternalRequest->Req.Cleanup.Delete)\n            return FuseOpGuardReleaseExclusive(Context);\n        else\n            return FuseOpGuardFalse;\n    }\n}\n\nstatic BOOLEAN FuseOpClose(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        /* NOTE: CLOSE cannot report failure! */\n\n        Context->Fini = FuseOpClose_ContextFini;\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Close.UserContext2;\n\n        if (Context->File->IsReparsePoint)\n            /* reparse points are not opened; ignore */;\n        else if (Context->File->IsDirectory)\n            coro_await (FuseProtoSendReleasedir(Context));\n        else\n            coro_await (FuseProtoSendRelease(Context));\n    }\n\n    return coro_active();\n}\n\nstatic VOID FuseOpClose_ContextFini(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    if (0 != Context->File)\n        FuseFileDelete(Context->Instance, Context->File);\n}\n\nstatic BOOLEAN FuseOpRead(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Read.UserContext2;\n\n        Context->Read.StartOffset = Context->InternalRequest->Req.Read.Offset;\n        Context->Read.Remain = Context->InternalRequest->Req.Read.Length;\n\n        Context->Read.Offset = 0;\n        while (0 != Context->Read.Remain)\n        {\n            Context->Read.Length = Context->Read.Remain;\n#if DBG\n            if (DEBUGTEST(10) && Context->Read.Length > 512)\n                Context->Read.Length = 512;\n#endif\n#if 0\n            FUSE_DEVICE_EXTENSION *Instance = FuseDeviceExtension(Context->DeviceObject);\n            if (Context->Read.Length > Instance->VolumeParams.MaxRead)\n                Context->Read.Length = Instance->VolumeParams.MaxRead;\n#endif\n\n            coro_await (FuseProtoSendRead(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            UINT32 BytesTransferred = Context->FuseResponse->len - FUSE_PROTO_RSP_HEADER_SIZE;\n            if (Context->Read.Length < BytesTransferred)\n            {\n                Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INTERNAL_ERROR;\n                coro_break;\n            }\n\n            Context->InternalResponse->IoStatus.Status = FuseSafeCopyMemory(\n                (PUINT8)(UINT_PTR)Context->InternalRequest->Req.Read.Address + Context->Write.Offset,\n                (PUINT8)Context->FuseResponse + FUSE_PROTO_RSP_HEADER_SIZE,\n                BytesTransferred);\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            Context->Read.Remain -= BytesTransferred;\n            Context->Read.Offset += BytesTransferred;\n\n            if (Context->Read.Length > BytesTransferred)\n                break;\n        }\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n        Context->InternalResponse->IoStatus.Information = Context->Read.Offset;\n        if (0 == Context->InternalResponse->IoStatus.Information)\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_END_OF_FILE;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpWrite(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.Write.UserContext2;\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->Write.Attr = Context->FuseResponse->rsp.getattr.attr;\n\n        UINT64 EndOffset;\n        Context->Write.StartOffset = Context->InternalRequest->Req.Write.Offset;\n        if (Context->InternalRequest->Req.Write.ConstrainedIo)\n        {\n            if (Context->Write.StartOffset >= Context->Write.Attr.size)\n            {\n                FuseAttrToFileInfo(Context->Instance, &Context->Write.Attr,\n                    &Context->InternalResponse->Rsp.Write.FileInfo);\n                Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n                Context->InternalResponse->IoStatus.Information = 0;\n                coro_break;\n            }\n            EndOffset = Context->Write.StartOffset + Context->InternalRequest->Req.Write.Length;\n            if (EndOffset > Context->Write.Attr.size)\n                EndOffset = Context->Write.Attr.size;\n        }\n        else\n        {\n            if ((UINT64)-1LL == Context->Write.StartOffset)\n                Context->Write.StartOffset = Context->Write.Attr.size;\n            EndOffset = Context->Write.StartOffset + Context->InternalRequest->Req.Write.Length;\n        }\n        Context->Write.Remain = (UINT32)(EndOffset - Context->Write.StartOffset);\n\n        Context->Write.Offset = 0;\n        while (0 != Context->Write.Remain)\n        {\n            FuseContextWaitRequest(Context);\n\n            Context->Write.Length = Context->Write.Remain;\n#if DBG\n            if (DEBUGTEST(10) && Context->Write.Length > 512)\n                Context->Write.Length = 512;\n#endif\n            if (Context->Write.Length > Context->FuseRequestLength - FUSE_PROTO_REQ_SIZE(write))\n                Context->Write.Length = Context->FuseRequestLength - FUSE_PROTO_REQ_SIZE(write);\n\n            Context->InternalResponse->IoStatus.Status = FuseSafeCopyMemory(\n                (PUINT8)Context->FuseRequest + FUSE_PROTO_REQ_SIZE(write),\n                (PUINT8)(UINT_PTR)Context->InternalRequest->Req.Write.Address + Context->Write.Offset,\n                Context->Write.Length);\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            coro_await (FuseProtoSendWrite(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            UINT32 BytesTransferred = Context->FuseResponse->rsp.write.size;\n            if (Context->Write.Length < BytesTransferred)\n            {\n                Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INTERNAL_ERROR;\n                coro_break;\n            }\n\n            Context->Write.Remain -= BytesTransferred;\n            Context->Write.Offset += BytesTransferred;\n\n            if (Context->Write.Length > BytesTransferred)\n                break;\n        }\n\n        if (Context->Write.Attr.size < Context->Write.StartOffset + Context->Write.Offset)\n            Context->Write.Attr.size = Context->Write.StartOffset + Context->Write.Offset;\n\n        FuseCacheQuickExpireItem(Context->Instance->Cache,\n            Context->File->CacheItem);\n\n        FuseAttrToFileInfo(Context->Instance, &Context->Write.Attr,\n            &Context->InternalResponse->Rsp.Write.FileInfo);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n        Context->InternalResponse->IoStatus.Information = Context->Write.Offset;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpQueryInformation(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryInformation.UserContext2;\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr,\n            &Context->InternalResponse->Rsp.QueryInformation.FileInfo);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpSetInformation_SetBasicInfo(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2;\n\n        if (0 != Context->InternalRequest->Req.SetInformation.Info.Basic.LastAccessTime ||\n            0 != Context->InternalRequest->Req.SetInformation.Info.Basic.LastWriteTime)\n        {\n            if (0 != Context->InternalRequest->Req.SetInformation.Info.Basic.LastAccessTime)\n                FuseFileTimeToUnixTime(Context->InternalRequest->Req.SetInformation.Info.Basic.LastAccessTime,\n                    &Context->Setattr.Attr.atime, &Context->Setattr.Attr.atimensec);\n            else\n                Context->Setattr.Attr.atimensec = FUSE_PROTO_UTIME_OMIT;\n            if (0 != Context->InternalRequest->Req.SetInformation.Info.Basic.LastWriteTime)\n                FuseFileTimeToUnixTime(Context->InternalRequest->Req.SetInformation.Info.Basic.LastWriteTime,\n                    &Context->Setattr.Attr.mtime, &Context->Setattr.Attr.mtimensec);\n            else\n                Context->Setattr.Attr.mtimensec = FUSE_PROTO_UTIME_OMIT;\n\n            coro_await (FuseProtoSendFutimens(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n        }\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FuseCacheQuickExpireItem(Context->Instance->Cache,\n            Context->File->CacheItem);\n\n        FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr,\n            &Context->InternalResponse->Rsp.SetInformation.FileInfo);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpSetInformation_SetAllocationSize(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2;\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        if (Context->FuseResponse->rsp.getattr.attr.size >\n            Context->InternalRequest->Req.SetInformation.Info.Allocation.AllocationSize)\n        {\n            Context->Setattr.Attr.size =\n                Context->InternalRequest->Req.SetInformation.Info.Allocation.AllocationSize;\n            coro_await (FuseProtoSendFtruncate(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            coro_await (FuseProtoSendFgetattr(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n        }\n\n        FuseCacheQuickExpireItem(Context->Instance->Cache,\n            Context->File->CacheItem);\n\n        FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr,\n            &Context->InternalResponse->Rsp.SetInformation.FileInfo);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpSetInformation_SetFileSize(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2;\n\n        Context->Setattr.Attr.size =\n            Context->InternalRequest->Req.SetInformation.Info.EndOfFile.FileSize;\n        coro_await (FuseProtoSendFtruncate(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FuseCacheQuickExpireItem(Context->Instance->Cache,\n            Context->File->CacheItem);\n\n        FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr,\n            &Context->InternalResponse->Rsp.SetInformation.FileInfo);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpSetInformation_SetDelete(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2;\n\n        if (Context->InternalRequest->Req.SetInformation.Info.Disposition.Delete &&\n            Context->File->IsDirectory && !Context->File->IsReparsePoint)\n        {\n            Context->QueryDirectory.NextOffset = 0;\n            Context->QueryDirectory.Length =\n                FSP_FSCTL_ALIGN_UP(sizeof(FUSE_PROTO_DIRENT) + 1, 8) +\n                FSP_FSCTL_ALIGN_UP(sizeof(FUSE_PROTO_DIRENT) + 2, 8) +\n                FSP_FSCTL_ALIGN_UP(sizeof(FUSE_PROTO_DIRENT) + 255, 8);\n                /* enough for \".\", \"..\" and an entry with a name up to 255 chars long */\n\n            coro_await (FuseProtoSendReaddir(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n\n            if (FUSE_PROTO_RSP_HEADER_SIZE + Context->QueryDirectory.Length < Context->FuseResponse->len)\n            {\n                Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INTERNAL_ERROR;\n                coro_break;\n            }\n\n            PUINT8 BufferEndP = (PUINT8)Context->FuseResponse + Context->FuseResponse->len;\n            PUINT8 BufferP = (PUINT8)Context->FuseResponse + FUSE_PROTO_RSP_HEADER_SIZE;\n            for (;;)\n            {\n                if (BufferEndP <\n                        BufferP + FIELD_OFFSET(FUSE_PROTO_DIRENT, name) ||\n                    BufferEndP <\n                        BufferP + FIELD_OFFSET(FUSE_PROTO_DIRENT, name) +\n                            ((FUSE_PROTO_DIRENT *)BufferP)->namelen)\n                    break;\n\n                FUSE_PROTO_DIRENT *Dirent = (FUSE_PROTO_DIRENT *)BufferP;\n                if ((1 == Dirent->namelen && '.' == Dirent->name[0]) ||\n                    (2 == Dirent->namelen && '.' == Dirent->name[0] && '.' == Dirent->name[1]))\n                    /*ignore*/;\n                else\n                {\n                    Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_DIRECTORY_NOT_EMPTY;\n                    coro_break;\n                }\n\n                BufferP += FSP_FSCTL_ALIGN_UP(\n                    FIELD_OFFSET(FUSE_PROTO_DIRENT, name) +\n                        ((FUSE_PROTO_DIRENT *)BufferP)->namelen,\n                    8);\n            }\n        }\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpSetInformation_Rename(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetInformation.UserContext2;\n\n        FusePrepareLookupPath(Context);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        coro_await (FuseRenameCheck(Context));\n        if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            Context->LookupPath.RenameIsDirectory = 0040000 == (Context->LookupPath.Attr.mode & 0170000);\n        else\n        if (STATUS_OBJECT_PATH_NOT_FOUND == Context->InternalResponse->IoStatus.Status ||\n            STATUS_OBJECT_NAME_NOT_FOUND == Context->InternalResponse->IoStatus.Status)\n            Context->LookupPath.RenameIsNonExistent = 1;\n        else\n            coro_break;\n\n        FusePrepareLookupPath2(Context);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0);\n        coro_await (FuseLookupPath(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name);\n\n        if (!Context->LookupPath.RenameIsNonExistent &&\n            (Context->Instance->VolumeParams->CaseSensitiveSearch ||\n                Context->LookupPath.Ino != Context->LookupPath.Ino2 ||\n                !RtlEqualString(&Context->LookupPath.Name, &Context->LookupPath.Name2, TRUE)))\n        {\n            if (0 == Context->InternalRequest->Req.SetInformation.Info.Rename.AccessToken)\n            {\n                Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_OBJECT_NAME_COLLISION;\n                coro_break;\n            }\n\n            if (Context->LookupPath.RenameIsDirectory)\n            {\n                Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_ACCESS_DENIED;\n                coro_break;\n            }\n        }\n\n        coro_await (FuseProtoSendRename(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FuseCacheRemoveEntry(\n            Context->Instance->Cache,\n            Context->LookupPath.Ino, &Context->LookupPath.Name);\n\n        FuseCacheRemoveEntry(\n            Context->Instance->Cache,\n            Context->LookupPath.Ino2, &Context->LookupPath.Name2);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpSetInformation(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    switch (Context->InternalRequest->Req.SetInformation.FileInformationClass)\n    {\n    case FileBasicInformation:\n        return FuseOpSetInformation_SetBasicInfo(Context);\n    case FileAllocationInformation:\n        return FuseOpSetInformation_SetAllocationSize(Context);\n    case FileEndOfFileInformation:\n        return FuseOpSetInformation_SetFileSize(Context);\n    case FileDispositionInformation:\n        return FuseOpSetInformation_SetDelete(Context);\n    case FileRenameInformation:\n        return FuseOpSetInformation_Rename(Context);\n    default:\n        Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_DEVICE_REQUEST;\n        return FALSE;\n    }\n}\n\nstatic INT FuseOgSetInformation(FUSE_CONTEXT *Context, BOOLEAN Acquire)\n{\n    PAGED_CODE();\n\n    if (Acquire)\n    {\n        if (FileRenameInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass)\n            return FuseOpGuardAcquireExclusive(Context);\n        else\n        if (FileDispositionInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass)\n            return FuseOpGuardAcquireShared(Context);\n        else\n            return FuseOpGuardFalse;\n    }\n    else\n    {\n        if (FileRenameInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass)\n            return FuseOpGuardReleaseExclusive(Context);\n        else\n        if (FileDispositionInformation == Context->InternalRequest->Req.SetInformation.FileInformationClass)\n            return FuseOpGuardReleaseShared(Context);\n        else\n            return FuseOpGuardFalse;\n    }\n}\n\nstatic BOOLEAN FuseOpQueryEa(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    return FALSE;\n}\n\nstatic BOOLEAN FuseOpSetEa(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    return FALSE;\n}\n\nstatic BOOLEAN FuseOpFlushBuffers(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.FlushBuffers.UserContext2;\n\n        if (0 == Context->File)\n        {\n            /* FUSE cannot flush volumes */\n            Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n            coro_break;\n        }\n\n        if (Context->File->IsDirectory)\n            coro_await (FuseProtoSendFsyncdir(Context));\n        else\n            coro_await (FuseProtoSendFsync(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status) &&\n            STATUS_INVALID_DEVICE_REQUEST != Context->InternalResponse->IoStatus.Status)\n            coro_break;\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        FuseCacheQuickExpireItem(Context->Instance->Cache,\n            Context->File->CacheItem);\n\n        FuseAttrToFileInfo(Context->Instance, &Context->FuseResponse->rsp.getattr.attr,\n            &Context->InternalResponse->Rsp.FlushBuffers.FileInfo);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpQueryVolumeInformation(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        coro_await (FuseProtoSendStatfs(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->Rsp.QueryVolumeInformation.VolumeInfo.TotalSize =\n            (UINT64)Context->FuseResponse->rsp.statfs.st.blocks *\n            (UINT64)Context->FuseResponse->rsp.statfs.st.frsize;\n        Context->InternalResponse->Rsp.QueryVolumeInformation.VolumeInfo.FreeSize =\n            (UINT64)Context->FuseResponse->rsp.statfs.st.bfree *\n            (UINT64)Context->FuseResponse->rsp.statfs.st.frsize;\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseAddDirInfo(FUSE_CONTEXT *Context,\n    PSTRING Name, UINT64 NextOffset, FUSE_PROTO_ATTR *Attr,\n    PVOID Buffer, ULONG Length, PULONG PBytesTransferred)\n{\n    PAGED_CODE();\n\n    try\n    {\n        NTSTATUS Result;\n        PVOID BufferEnd = (PUINT8)Buffer + Length;\n        FSP_FSCTL_DIR_INFO *DirInfo;\n        ULONG WideNameLength, DirInfoSize, AlignedSize;\n        WCHAR WideName[255];\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n\n        if (0 != Name)\n        {\n            Result = RtlUTF8ToUnicodeN(\n                WideName, sizeof WideName, &WideNameLength,\n                Name->Buffer, Name->Length);\n            if (STATUS_SOME_NOT_MAPPED == Result)\n                Result = STATUS_SUCCESS;\n            else if (!NT_SUCCESS(Result))\n                return TRUE; /* return SUCCESS but IGNORE */\n            FspPosixDecodeWindowsPath(WideName, WideNameLength / sizeof(WCHAR));\n\n            DirInfoSize = sizeof(FSP_FSCTL_DIR_INFO) + WideNameLength;\n            AlignedSize = FSP_FSCTL_DEFAULT_ALIGN_UP(DirInfoSize);\n\n            Buffer = (PVOID)((PUINT8)Buffer + *PBytesTransferred);\n            if ((PUINT8)Buffer + AlignedSize > (PUINT8)BufferEnd)\n                return FALSE;\n\n            DirInfo = Buffer;\n            DirInfo->Size = (UINT16)DirInfoSize;\n            FuseAttrToFileInfo(Context->Instance, Attr, &DirInfo->FileInfo);\n            DirInfo->NextOffset = NextOffset;\n            RtlCopyMemory(DirInfo->FileNameBuf, WideName, WideNameLength);\n        }\n        else\n        {\n            DirInfoSize = sizeof(UINT16);\n            AlignedSize = DirInfoSize;\n\n            Buffer = (PVOID)((PUINT8)Buffer + *PBytesTransferred);\n            if ((PUINT8)Buffer + AlignedSize > (PUINT8)BufferEnd)\n                return FALSE;\n\n            *(PUINT16)Buffer = 0;\n        }\n\n        *PBytesTransferred += AlignedSize;\n\n        return TRUE;\n    }\n    except (EXCEPTION_EXECUTE_HANDLER)\n    {\n        Context->InternalResponse->IoStatus.Status = GetExceptionCode();\n        if (FsRtlIsNtstatusExpected(Context->InternalResponse->IoStatus.Status))\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_USER_BUFFER;\n\n        return FALSE;\n    }\n}\n\nstatic VOID FuseOpQueryDirectory_GetDirInfoByName(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        {\n            PWSTR FileName = (PWSTR)(Context->InternalRequest->Buffer +\n                Context->InternalRequest->Req.QueryDirectory.Pattern.Offset);\n            PSTR PosixName;\n            Context->InternalResponse->IoStatus.Status = FspPosixMapWindowsToPosixPathEx(\n                FileName, &PosixName, TRUE);\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n            RtlInitString(&Context->QueryDirectory.OrigName, PosixName);\n        }\n\n        Context->QueryDirectory.Ino = Context->File->Ino;\n        Context->QueryDirectory.Name = Context->QueryDirectory.OrigName;\n        coro_await (FuseLookup(Context));\n\n        BOOLEAN AddDirInfoEnd = FALSE;\n        if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            AddDirInfoEnd = FuseAddDirInfo(\n                Context,\n                &Context->QueryDirectory.Name,\n                0,\n                &Context->QueryDirectory.Attr,\n                (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.Address,\n                Context->InternalRequest->Req.QueryDirectory.Length,\n                &Context->QueryDirectory.BytesTransferred);\n        else if (STATUS_OBJECT_NAME_NOT_FOUND == Context->InternalResponse->IoStatus.Status)\n            AddDirInfoEnd = TRUE;\n\n        if (AddDirInfoEnd)\n            FuseAddDirInfo(\n                Context,\n                0,\n                0,\n                0,\n                (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.Address,\n                Context->InternalRequest->Req.QueryDirectory.Length,\n                &Context->QueryDirectory.BytesTransferred);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n        Context->InternalResponse->IoStatus.Information = Context->QueryDirectory.BytesTransferred;\n    }\n}\n\nstatic VOID FuseOpQueryDirectory_ReadDirectory(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->QueryDirectory.NextOffset =\n            sizeof(UINT64) + sizeof(WCHAR) == Context->InternalRequest->Req.QueryDirectory.Marker.Size ?\n                *(PUINT64)(Context->InternalRequest->Buffer +\n                    Context->InternalRequest->Req.QueryDirectory.Marker.Offset) :\n                0;\n\n        /*\n         * The FSD has sent us a buffer of QueryDirectory.Length size that holds FSP_FSCTL_DIR_INFO\n         * entries. Assuming that the average file name length is 24 we approximate how many entries\n         * (N) we can fit in that buffer:\n         *\n         * N = QueryDirectory.Length / (sizeof(FSP_FSCTL_DIR_INFO) + (24 * sizeof(WCHAR)))\n         *\n         * We now approximate the FUSE READDIR buffer size required to fit N entries:\n         *\n         * read.size = FUSE_PROTO_RSP_HEADER_SIZE + N * (sizeof(FUSE_PROTO_DIRENT) + 24)\n         */\n        UINT32 N = Context->InternalRequest->Req.QueryDirectory.Length /\n            (sizeof(FSP_FSCTL_DIR_INFO) + (24 * sizeof(WCHAR)));\n        Context->QueryDirectory.Length = N * (sizeof(FUSE_PROTO_DIRENT) + 24);\n\n        coro_await (FuseProtoSendReaddir(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        if (FUSE_PROTO_RSP_HEADER_SIZE + Context->QueryDirectory.Length < Context->FuseResponse->len)\n        {\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INTERNAL_ERROR;\n            coro_break;\n        }\n\n        if (FUSE_PROTO_RSP_HEADER_SIZE < Context->FuseResponse->len)\n        {\n            Context->QueryDirectory.Buffer = FuseAlloc(Context->FuseResponse->len);\n            if (0 == Context->QueryDirectory.Buffer)\n            {\n                Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INSUFFICIENT_RESOURCES;\n                coro_break;\n            }\n\n            RtlCopyMemory(Context->QueryDirectory.Buffer, Context->FuseResponse, Context->FuseResponse->len);\n        }\n\n        Context->QueryDirectory.BufferEndP = Context->QueryDirectory.Buffer + Context->FuseResponse->len;\n        Context->QueryDirectory.BufferP = Context->QueryDirectory.Buffer + FUSE_PROTO_RSP_HEADER_SIZE;\n\n        for (;;)\n        {\n            if (Context->QueryDirectory.BufferEndP <\n                    Context->QueryDirectory.BufferP + FIELD_OFFSET(FUSE_PROTO_DIRENT, name) ||\n                Context->QueryDirectory.BufferEndP <\n                    Context->QueryDirectory.BufferP + FIELD_OFFSET(FUSE_PROTO_DIRENT, name) +\n                        ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->namelen)\n                break;\n\n            Context->QueryDirectory.Name.Length = Context->QueryDirectory.Name.MaximumLength = (USHORT)\n                ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->namelen;\n            Context->QueryDirectory.Name.Buffer =\n                ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->name;\n\n            if ((1 == Context->QueryDirectory.Name.Length &&\n                '.' == Context->QueryDirectory.Name.Buffer[0]) ||\n                (2 == Context->QueryDirectory.Name.Length &&\n                '.' == Context->QueryDirectory.Name.Buffer[0] &&\n                '.' == Context->QueryDirectory.Name.Buffer[1]))\n            {\n                /*\n                 * If the file system gave us a real inode number try getattr on it.\n                 * Otherwise try with the inode number from the file descriptor (this\n                 * is obviously incorrect for the parent \"..\", but we are doing the\n                 * best we can).\n                 */\n                Context->QueryDirectory.Ino =\n                    FUSE_PROTO_UNKNOWN_INO != ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->ino ?\n                        ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->ino :\n                        Context->File->Ino;\n                coro_await (FuseProtoSendGetattr(Context));\n                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                    coro_break;\n                Context->Lookup.Attr = Context->FuseResponse->rsp.getattr.attr;\n            }\n            else\n            {\n                Context->QueryDirectory.Ino = Context->File->Ino;\n                coro_await (FuseLookup(Context));\n                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                    coro_break;\n            }\n\n            BOOLEAN Added = FuseAddDirInfo(\n                Context,\n                &Context->QueryDirectory.Name,\n                ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->off,\n                &Context->QueryDirectory.Attr,\n                (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.Address,\n                Context->InternalRequest->Req.QueryDirectory.Length,\n                &Context->QueryDirectory.BytesTransferred);\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n            if (!Added)\n                break;\n\n            Context->QueryDirectory.BufferP += FSP_FSCTL_ALIGN_UP(\n                FIELD_OFFSET(FUSE_PROTO_DIRENT, name) +\n                    ((FUSE_PROTO_DIRENT *)Context->QueryDirectory.BufferP)->namelen,\n                8);\n        }\n\n        /* empty readdir response signifies end of dir; add WinFsp end-of-dir marker */\n        if (Context->QueryDirectory.BufferP == Context->QueryDirectory.Buffer + FUSE_PROTO_RSP_HEADER_SIZE)\n            FuseAddDirInfo(Context, 0, 0, 0,\n                (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.Address,\n                Context->InternalRequest->Req.QueryDirectory.Length,\n                &Context->QueryDirectory.BytesTransferred);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n        Context->InternalResponse->IoStatus.Information = Context->QueryDirectory.BytesTransferred;\n    }\n}\n\nstatic BOOLEAN FuseOpQueryDirectory(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->Fini = FuseOpQueryDirectory_ContextFini;\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.QueryDirectory.UserContext2;\n\n        Context->InternalResponse->IoStatus.Status = FuseCacheReferenceGen(\n            Context->Instance->Cache, &Context->QueryDirectory.CacheGen);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        if (0 != Context->InternalRequest->Req.QueryDirectory.Pattern.Size &&\n            Context->InternalRequest->Req.QueryDirectory.PatternIsFileName)\n            coro_await (FuseOpQueryDirectory_GetDirInfoByName(Context));\n        else\n            coro_await (FuseOpQueryDirectory_ReadDirectory(Context));\n    }\n\n    return coro_active();\n}\n\nstatic VOID FuseOpQueryDirectory_ContextFini(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    if (0 != Context->QueryDirectory.Buffer)\n        FuseFree(Context->QueryDirectory.Buffer);\n\n    FspPosixDeletePath(Context->QueryDirectory.OrigName.Buffer);\n        /* handles NULL paths */\n    FuseCacheDereferenceGen(Context->Instance->Cache, Context->QueryDirectory.CacheGen);\n        /* handles NULL gens */\n}\n\nstatic INT FuseOgQueryDirectory(FUSE_CONTEXT *Context, BOOLEAN Acquire)\n{\n    PAGED_CODE();\n\n    if (Acquire)\n        return FuseOpGuardAcquireShared(Context);\n    else\n        return FuseOpGuardReleaseShared(Context);\n}\n\nstatic BOOLEAN FuseOpFileSystemControl(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    return FALSE;\n}\n\nstatic BOOLEAN FuseOpDeviceControl(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    return FALSE;\n}\n\nstatic BOOLEAN FuseOpQuerySecurity(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->Fini = FuseSecurity_ContextFini;\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.QuerySecurity.UserContext2;\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->IoStatus.Status = FspPosixMapPermissionsToSecurityDescriptor(\n            Context->FuseResponse->rsp.getattr.attr.uid,\n            Context->FuseResponse->rsp.getattr.attr.gid,\n            Context->FuseResponse->rsp.getattr.attr.mode,\n            &Context->Security.SecurityDescriptor);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        ULONG Length = RtlLengthSecurityDescriptor(Context->Security.SecurityDescriptor);\n        if (FSP_FSCTL_TRANSACT_RSP_BUFFER_SIZEMAX < Length)\n        {\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_SECURITY_DESCR;\n            coro_break;\n        }\n\n        PVOID InternalResponse = FuseAlloc(sizeof *Context->InternalResponse + Length);\n        if (0 == InternalResponse)\n        {\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INSUFFICIENT_RESOURCES;\n            coro_break;\n        }\n        RtlZeroMemory(InternalResponse, sizeof *Context->InternalResponse);\n\n        Context->InternalResponse = InternalResponse;\n        Context->InternalResponse->Size = (UINT16)(sizeof *Context->InternalResponse + Length);\n        Context->InternalResponse->Kind = Context->InternalRequest->Kind;\n        Context->InternalResponse->Hint = Context->InternalRequest->Hint;\n        Context->InternalResponse->Rsp.QuerySecurity.SecurityDescriptor.Offset = 0;\n        Context->InternalResponse->Rsp.QuerySecurity.SecurityDescriptor.Size = (UINT16)Length;\n\n        /* RtlCopyMemory is safe here, because all buffers are in-kernel */\n        RtlCopyMemory(\n            Context->InternalResponse->Buffer, Context->Security.SecurityDescriptor, Length);\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic BOOLEAN FuseOpSetSecurity(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    coro_block (Context->CoroState)\n    {\n        Context->Fini = FuseSecurity_ContextFini;\n        Context->File = (PVOID)(UINT_PTR)Context->InternalRequest->Req.SetSecurity.UserContext2;\n\n        coro_await (FuseProtoSendFgetattr(Context));\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->InternalResponse->IoStatus.Status = FspPosixMapPermissionsToSecurityDescriptor(\n            Context->FuseResponse->rsp.getattr.attr.uid,\n            Context->FuseResponse->rsp.getattr.attr.gid,\n            Context->FuseResponse->rsp.getattr.attr.mode,\n            &Context->Security.SecurityDescriptor);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        /*\n         * BEGIN:\n         * No coro_yield or coro_await allowed, because Context->FuseResponse->rsp.getattr.attr\n         * must remain valid.\n         */\n\n        PSECURITY_DESCRIPTOR NewSecurityDescriptor = Context->Security.SecurityDescriptor;\n        Context->InternalResponse->IoStatus.Status = SeSetSecurityDescriptorInfo(\n            0,\n            (PSECURITY_INFORMATION)&Context->InternalRequest->Req.SetSecurity.SecurityInformation,\n            (PSECURITY_DESCRIPTOR)Context->InternalRequest->Buffer,\n            &NewSecurityDescriptor,\n            PagedPool,\n            IoGetFileObjectGenericMapping());\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n        FuseFreeExternal(Context->Security.SecurityDescriptor);\n        Context->Security.SecurityDescriptor = NewSecurityDescriptor;\n\n        Context->InternalResponse->IoStatus.Status = FspPosixMapSecurityDescriptorToPermissions(\n            Context->Security.SecurityDescriptor,\n            &Context->Security.Attr.uid,\n            &Context->Security.Attr.gid,\n            &Context->Security.Attr.mode);\n        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n            coro_break;\n\n        Context->Security.Attr.mode &= 07777;\n        Context->Security.Attr.mode |= (Context->FuseResponse->rsp.getattr.attr.mode & 0170000);\n\n        Context->Security.AttrValid = 0;\n        Context->Security.AttrValid |=\n            Context->Security.Attr.uid != Context->FuseResponse->rsp.getattr.attr.uid ?\n                FUSE_PROTO_SETATTR_UID : 0;\n        Context->Security.AttrValid |=\n            Context->Security.Attr.gid != Context->FuseResponse->rsp.getattr.attr.gid ?\n                FUSE_PROTO_SETATTR_GID : 0;\n        Context->Security.AttrValid |=\n            Context->Security.Attr.mode != Context->FuseResponse->rsp.getattr.attr.mode ?\n                FUSE_PROTO_SETATTR_MODE : 0;\n\n        /*\n         * END:\n         * No coro_yield or coro_await allowed, because Context->FuseResponse->rsp.getattr.attr\n         * must remain valid.\n         */\n\n        if (0 != Context->Security.AttrValid)\n        {\n            coro_await (FuseProtoSendSetattr(Context));\n            if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))\n                coro_break;\n        }\n\n        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;\n    }\n\n    return coro_active();\n}\n\nstatic VOID FuseSecurity_ContextFini(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    if (0 != Context->Security.SecurityDescriptor)\n        FuseFreeExternal(Context->Security.SecurityDescriptor);\n}\n\nFUSE_OPERATION FuseOperations[FspFsctlTransactKindCount] =\n{\n    /* FspFsctlTransactReservedKind */\n    { FuseOpReserved },\n\n    /* FspFsctlTransactCreateKind */\n    { FuseOpCreate, FuseOgCreate },\n\n    /* FspFsctlTransactOverwriteKind */\n    { FuseOpOverwrite },\n\n    /* FspFsctlTransactCleanupKind */\n    { FuseOpCleanup, FuseOgCleanup },\n\n    /* FspFsctlTransactCloseKind */\n    { FuseOpClose },\n\n    /* FspFsctlTransactReadKind */\n    { FuseOpRead },\n\n    /* FspFsctlTransactWriteKind */\n    { FuseOpWrite },\n\n    /* FspFsctlTransactQueryInformationKind */\n    { FuseOpQueryInformation },\n\n    /* FspFsctlTransactSetInformationKind */\n    { FuseOpSetInformation, FuseOgSetInformation },\n\n    /* FspFsctlTransactQueryEaKind */\n    { 0 },\n\n    /* FspFsctlTransactSetEaKind */\n    { 0 },\n\n    /* FspFsctlTransactFlushBuffersKind */\n    { FuseOpFlushBuffers },\n\n    /* FspFsctlTransactQueryVolumeInformationKind */\n    { FuseOpQueryVolumeInformation },\n\n    /* FspFsctlTransactSetVolumeInformationKind */\n    { 0 },\n\n    /* FspFsctlTransactQueryDirectoryKind */\n    { FuseOpQueryDirectory, FuseOgQueryDirectory },\n\n    /* FspFsctlTransactFileSystemControlKind */\n    { 0 },\n\n    /* FspFsctlTransactDeviceControlKind */\n    { 0 },\n\n    /* FspFsctlTransactShutdownKind */\n    { 0 },\n\n    /* FspFsctlTransactLockControlKind */\n    { 0 },\n\n    /* FspFsctlTransactQuerySecurityKind */\n    { FuseOpQuerySecurity },\n\n    /* FspFsctlTransactSetSecurityKind */\n    { FuseOpSetSecurity },\n\n    /* FspFsctlTransactQueryStreamInformationKind */\n    { 0 },\n};\n"
  },
  {
    "path": "src/shared/km/instance.c",
    "content": "/**\n * @file shared/km/instance.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\nNTSTATUS FuseInstanceInit(FUSE_INSTANCE *Instance,\n    FSP_FSCTL_VOLUME_PARAMS *VolumeParams,\n    FUSE_INSTANCE_TYPE InstanceType);\nVOID FuseInstanceFini(FUSE_INSTANCE *Instance);\nVOID FuseInstanceExpirationRoutine(FUSE_INSTANCE *Instance, UINT64 ExpirationTime);\nNTSTATUS FuseInstanceTransact(FUSE_INSTANCE *Instance,\n    FUSE_PROTO_RSP *FuseResponse, ULONG InputBufferLength,\n    FUSE_PROTO_REQ *FuseRequest, PULONG POutputBufferLength,\n    PDEVICE_OBJECT DeviceObject, PFILE_OBJECT FileObject,\n    PIRP CancellableIrp);\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(PAGE, FuseInstanceInit)\n#pragma alloc_text(PAGE, FuseInstanceFini)\n#pragma alloc_text(PAGE, FuseInstanceExpirationRoutine)\n#pragma alloc_text(PAGE, FuseInstanceTransact)\n#endif\n\nNTSTATUS FuseInstanceInit(FUSE_INSTANCE *Instance,\n    FSP_FSCTL_VOLUME_PARAMS *VolumeParams,\n    FUSE_INSTANCE_TYPE InstanceType)\n{\n    PAGED_CODE();\n\n    NTSTATUS Result;\n\n    RtlZeroMemory(Instance, sizeof *Instance);\n    Instance->VolumeParams = VolumeParams;\n    Instance->InstanceType = InstanceType;\n\n    FuseRwlockInitialize(&Instance->OpGuardLock);\n\n    Result = FuseIoqCreate(&Instance->Ioq);\n    if (!NT_SUCCESS(Result))\n        goto exit;\n\n    Result = FuseCacheCreate(0, 0/*!VolumeParams->CaseSensitiveSearch*/, &Instance->Cache);\n    if (!NT_SUCCESS(Result))\n        goto exit;\n\n    FuseFileInstanceInit(Instance);\n\n    KeInitializeEvent(&Instance->InitEvent, NotificationEvent, FALSE);\n    Result = FuseProtoPostInit(Instance);\n    if (!NT_SUCCESS(Result))\n        goto exit;\n\n    /* ensure that VolumeParams can be used for FUSE operations */\n    VolumeParams->CaseSensitiveSearch = 1; /* revisit FuseCacheCreate above if this changes */\n    VolumeParams->CasePreservedNames = 1;\n    VolumeParams->PersistentAcls = 1;\n    VolumeParams->ReparsePoints = 1;\n    VolumeParams->ReparsePointsAccessCheck = 0;\n    VolumeParams->NamedStreams = 0;\n    VolumeParams->ReadOnlyVolume = 0;\n    VolumeParams->PostCleanupWhenModifiedOnly = 1;\n    VolumeParams->PassQueryDirectoryFileName = 1;\n    VolumeParams->DeviceControl = 1;\n    VolumeParams->DirectoryMarkerAsNextOffset = 1;\n\n    Result = STATUS_SUCCESS;\n\nexit:\n    if (!NT_SUCCESS(Result))\n    {\n        if (0 != Instance->Cache)\n            FuseCacheDelete(Instance->Cache);\n\n        if (0 != Instance->Ioq)\n            FuseIoqDelete(Instance->Ioq);\n\n        FuseRwlockFinalize(&Instance->OpGuardLock);\n\n        RtlZeroMemory(Instance, sizeof *Instance);\n    }\n\n    return Result;\n}\n\nVOID FuseInstanceFini(FUSE_INSTANCE *Instance)\n{\n    PAGED_CODE();\n\n    /*\n     * The order of finalization is IMPORTANT:\n     *\n     * FuseIoqDelete must precede FuseFileInstanceFini, because the Ioq may contain Contexts\n     * that hold File's.\n     *\n     * FuseIoqDelete must precede FuseCacheDelete, because the Ioq may contain Contexts\n     * that hold CacheGen references.\n     *\n     * FuseFileInstanceFini must precede FuseCacheDelete, because some Files may hold\n     * CacheItem references.\n     */\n\n    FuseIoqDelete(Instance->Ioq);\n\n    FuseFileInstanceFini(Instance);\n\n    FuseCacheDelete(Instance->Cache);\n\n    FuseRwlockFinalize(&Instance->OpGuardLock);\n}\n\nVOID FuseInstanceExpirationRoutine(FUSE_INSTANCE *Instance, UINT64 ExpirationTime)\n{\n    PAGED_CODE();\n\n    FuseCacheExpirationRoutine(Instance->Cache, Instance, ExpirationTime);\n}\n\nNTSTATUS FuseInstanceTransact(FUSE_INSTANCE *Instance,\n    FUSE_PROTO_RSP *FuseResponse, ULONG InputBufferLength,\n    FUSE_PROTO_REQ *FuseRequest, PULONG POutputBufferLength,\n    PDEVICE_OBJECT DeviceObject, PFILE_OBJECT FileObject,\n    PIRP CancellableIrp)\n{\n    PAGED_CODE();\n\n    ULONG OutputBufferLength = *POutputBufferLength;\n    FSP_FSCTL_TRANSACT_REQ *InternalRequest = 0;\n    FSP_FSCTL_TRANSACT_RSP InternalResponse;\n    FUSE_CONTEXT *Context;\n    BOOLEAN Continue;\n    NTSTATUS Result;\n\n    *POutputBufferLength = 0;\n\n    /* check parameters */\n    if (0 != FuseResponse)\n    {\n        if (FUSE_PROTO_RSP_HEADER_SIZE > InputBufferLength ||\n            FUSE_PROTO_RSP_HEADER_SIZE > FuseResponse->len ||\n            FuseResponse->len > InputBufferLength)\n            return STATUS_INVALID_PARAMETER;\n    }\n    if (0 != FuseRequest)\n    {\n        if (FUSE_PROTO_REQ_SIZEMIN > OutputBufferLength)\n            return STATUS_BUFFER_TOO_SMALL;\n    }\n\n    if (0 != FuseResponse)\n    {\n        Context = FuseIoqEndProcessing(Instance->Ioq, FuseResponse->unique);\n        if (0 == Context)\n            goto request;\n\n#if DBG\n        if (fuse_debug & fuse_debug_dp)\n            FuseDebugLogResponse(FuseResponse);\n#endif\n\n        Continue = FuseContextProcess(Context, FuseResponse, 0, 0);\n\n        if (Continue)\n            FuseIoqPostPending(Instance->Ioq, Context);\n        else if (0 == Context->InternalRequest)\n            FuseContextDelete(Context);\n        else\n        {\n            ASSERT(FspFsctlTransactReservedKind != Context->InternalResponse->Kind);\n\n            Result = FspFsextProviderTransact(\n                DeviceObject, FileObject, Context->InternalResponse, 0);\n            FuseContextDelete(Context);\n            if (!NT_SUCCESS(Result))\n                goto exit;\n        }\n    }\n\nrequest:\n    if (0 != FuseRequest)\n    {\n        RtlZeroMemory(FuseRequest, sizeof(FUSE_PROTO_REQ));\n\n        Context = FuseIoqNextPending(Instance->Ioq);\n        if (0 == Context)\n        {\n            UINT32 VersionMajor = Instance->VersionMajor;\n            _ReadWriteBarrier();\n                /*\n                 * Compiler barrier only.\n                 *\n                 * A full memory barrier is not needed here, because:\n                 *\n                 * - WaitForSingleObject acts on a NotificationEvent that stays signaled.\n                 * - WaitForSingleObject is a memory barrier.\n                 */\n            if (0 == VersionMajor)\n            {\n                Result = FsRtlCancellableWaitForSingleObject(&Instance->InitEvent,\n                    0, CancellableIrp);\n                if (STATUS_TIMEOUT == Result || STATUS_THREAD_IS_TERMINATING == Result)\n                    Result = STATUS_CANCELLED;\n                if (!NT_SUCCESS(Result))\n                    goto exit;\n                ASSERT(STATUS_SUCCESS == Result);\n\n                VersionMajor = Instance->VersionMajor;\n            }\n            if ((UINT32)-1 == VersionMajor)\n            {\n                Result = STATUS_ACCESS_DENIED;\n                goto exit;\n            }\n\n            Result = FspFsextProviderTransact(\n                DeviceObject, FileObject, 0, &InternalRequest);\n            if (!NT_SUCCESS(Result))\n                goto exit;\n            if (0 == InternalRequest)\n            {\n                Result = STATUS_SUCCESS;\n                goto exit;\n            }\n\n            ASSERT(FspFsctlTransactReservedKind != InternalRequest->Kind);\n\n            FuseContextCreate(&Context, Instance, InternalRequest);\n            ASSERT(0 != Context);\n\n            Continue = FALSE;\n            if (!FuseContextIsStatus(Context))\n            {\n                InternalRequest = 0;\n                Continue = FuseContextProcess(Context, 0, FuseRequest, OutputBufferLength);\n            }\n        }\n        else\n        {\n            ASSERT(!FuseContextIsStatus(Context));\n            Continue = FuseContextProcess(Context, 0, FuseRequest, OutputBufferLength);\n        }\n\n        if (Continue)\n        {\n            ASSERT(!FuseContextIsStatus(Context));\n            FuseIoqStartProcessing(Instance->Ioq, Context);\n        }\n        else if (FuseContextIsStatus(Context))\n        {\n            ASSERT(0 != InternalRequest);\n            RtlZeroMemory(&InternalResponse, sizeof InternalResponse);\n            InternalResponse.Size = sizeof InternalResponse;\n            InternalResponse.Kind = InternalRequest->Kind;\n            InternalResponse.Hint = InternalRequest->Hint;\n            InternalResponse.IoStatus.Status = FuseContextToStatus(Context);\n            Result = FspFsextProviderTransact(\n                DeviceObject, FileObject, &InternalResponse, 0);\n            if (!NT_SUCCESS(Result))\n                goto exit;\n        }\n        else if (0 == Context->InternalRequest)\n        {\n            switch (Context->InternalResponse->Hint)\n            {\n            case FUSE_PROTO_OPCODE_FORGET:\n            case FUSE_PROTO_OPCODE_BATCH_FORGET:\n                if (!IsListEmpty(&Context->Forget.ForgetList))\n                    FuseIoqPostPending(Instance->Ioq, Context);\n                else\n                    FuseContextDelete(Context);\n                break;\n            }\n        }\n        else\n        {\n            Result = FspFsextProviderTransact(\n                DeviceObject, FileObject, Context->InternalResponse, 0);\n            FuseContextDelete(Context);\n            if (!NT_SUCCESS(Result))\n                goto exit;\n        }\n\n        *POutputBufferLength = FuseRequest->len;\n\n#if DBG\n        if (fuse_debug & fuse_debug_dp)\n            FuseDebugLogRequest(FuseRequest);\n#endif\n    }\n\n    Result = STATUS_SUCCESS;\n\nexit:\n    if (0 != InternalRequest)\n        FuseFreeExternal(InternalRequest);\n\n    return Result;\n}\n"
  },
  {
    "path": "src/shared/km/ioq.c",
    "content": "/**\n * @file shared/km/ioq.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\nNTSTATUS FuseIoqCreate(FUSE_IOQ **PIoq);\nVOID FuseIoqDelete(FUSE_IOQ *Ioq);\nVOID FuseIoqStartProcessing(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context);\nFUSE_CONTEXT *FuseIoqEndProcessing(FUSE_IOQ *Ioq, UINT64 Unique);\nVOID FuseIoqPostPending(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context);\nVOID FuseIoqPostPendingAndStop(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context);\nFUSE_CONTEXT *FuseIoqNextPending(FUSE_IOQ *Ioq);\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(PAGE, FuseIoqCreate)\n#pragma alloc_text(PAGE, FuseIoqDelete)\n#pragma alloc_text(PAGE, FuseIoqStartProcessing)\n#pragma alloc_text(PAGE, FuseIoqEndProcessing)\n#pragma alloc_text(PAGE, FuseIoqPostPending)\n#pragma alloc_text(PAGE, FuseIoqPostPendingAndStop)\n#pragma alloc_text(PAGE, FuseIoqNextPending)\n#endif\n\n#define FUSE_IOQ_SIZE                   1024\n\nstruct _FUSE_IOQ\n{\n    FAST_MUTEX Mutex;\n    LIST_ENTRY PendingList, ProcessList;\n    FUSE_CONTEXT *LastContext;\n    ULONG ProcessBucketCount;\n    FUSE_CONTEXT *ProcessBuckets[];\n};\n\nNTSTATUS FuseIoqCreate(FUSE_IOQ **PIoq)\n{\n    PAGED_CODE();\n\n    *PIoq = 0;\n\n    FUSE_IOQ *Ioq;\n    ULONG BucketCount = (FUSE_IOQ_SIZE - sizeof *Ioq) / sizeof Ioq->ProcessBuckets[0];\n    Ioq = FuseAllocNonPaged(FUSE_IOQ_SIZE);\n    if (0 == Ioq)\n        return STATUS_INSUFFICIENT_RESOURCES;\n    RtlZeroMemory(Ioq, FUSE_IOQ_SIZE);\n\n    ExInitializeFastMutex(&Ioq->Mutex);\n    InitializeListHead(&Ioq->PendingList);\n    InitializeListHead(&Ioq->ProcessList);\n    Ioq->ProcessBucketCount = BucketCount;\n\n    *PIoq = Ioq;\n\n    return STATUS_SUCCESS;\n}\n\nVOID FuseIoqDelete(FUSE_IOQ *Ioq)\n{\n    PAGED_CODE();\n\n    for (PLIST_ENTRY Entry = Ioq->PendingList.Flink; &Ioq->PendingList != Entry;)\n    {\n        FUSE_CONTEXT *Context = CONTAINING_RECORD(Entry, FUSE_CONTEXT, ListEntry);\n        Entry = Entry->Flink;\n        FuseContextDelete(Context);\n    }\n    for (PLIST_ENTRY Entry = Ioq->ProcessList.Flink; &Ioq->ProcessList != Entry;)\n    {\n        FUSE_CONTEXT *Context = CONTAINING_RECORD(Entry, FUSE_CONTEXT, ListEntry);\n        Entry = Entry->Flink;\n        FuseContextDelete(Context);\n    }\n    FuseFree(Ioq);\n}\n\nVOID FuseIoqStartProcessing(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    ExAcquireFastMutex(&Ioq->Mutex);\n\n    if (0 != Ioq->LastContext)\n    {\n        if (Context != Ioq->LastContext)\n        {\n            ExReleaseFastMutex(&Ioq->Mutex);\n            ASSERT(0 != Context->FuseRequest);\n            if (0 != Context->FuseRequest)\n                Context->FuseRequest->len = 0;\n            FuseContextDelete(Context);\n            return;\n        }\n        else\n            Ioq->LastContext = (PVOID)(UINT_PTR)1;\n    }\n\n    InsertTailList(&Ioq->ProcessList, &Context->ListEntry);\n\n    ULONG Index = FuseHashMixPointer(Context) % Ioq->ProcessBucketCount;\n#if DBG\n    for (FUSE_CONTEXT *ContextX = Ioq->ProcessBuckets[Index]; ContextX; ContextX = ContextX->DictNext)\n        ASSERT(ContextX != Context);\n#endif\n    ASSERT(0 == Context->DictNext);\n    Context->DictNext = Ioq->ProcessBuckets[Index];\n    Ioq->ProcessBuckets[Index] = Context;\n\n    ExReleaseFastMutex(&Ioq->Mutex);\n}\n\nFUSE_CONTEXT *FuseIoqEndProcessing(FUSE_IOQ *Ioq, UINT64 Unique)\n{\n    PAGED_CODE();\n\n    FUSE_CONTEXT *ContextHint = (PVOID)(UINT_PTR)Unique;\n    FUSE_CONTEXT *Context = 0;\n\n    ExAcquireFastMutex(&Ioq->Mutex);\n\n    ULONG Index = FuseHashMixPointer(ContextHint) % Ioq->ProcessBucketCount;\n    for (FUSE_CONTEXT **PContext = &Ioq->ProcessBuckets[Index]; *PContext; PContext = &(*PContext)->DictNext)\n    {\n        if (*PContext == ContextHint)\n        {\n            *PContext = ContextHint->DictNext;\n            ContextHint->DictNext = 0;\n\n            Context = ContextHint;\n            RemoveEntryList(&Context->ListEntry);\n\n            break;\n        }\n    }\n\n    ExReleaseFastMutex(&Ioq->Mutex);\n\n    return Context;\n}\n\nVOID FuseIoqPostPending(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    ExAcquireFastMutex(&Ioq->Mutex);\n\n    if (0 != Ioq->LastContext)\n    {\n        ExReleaseFastMutex(&Ioq->Mutex);\n        FuseContextDelete(Context);\n        return;\n    }\n\n    InsertTailList(&Ioq->PendingList, &Context->ListEntry);\n\n    ExReleaseFastMutex(&Ioq->Mutex);\n}\n\nVOID FuseIoqPostPendingAndStop(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context)\n    /*\n     * This function is used to post the last Context for processing (usually DESTROY).\n     * It clears the Pending list, but does not touch the Process list. The reason is\n     * that the last Context must be retrieved only after all in-flight Context's are\n     * done and FuseIoqNextPending checks for this condition when the last Context has\n     * been posted.\n     */\n{\n    PAGED_CODE();\n\n    ExAcquireFastMutex(&Ioq->Mutex);\n\n    if (0 != Ioq->LastContext)\n    {\n        ExReleaseFastMutex(&Ioq->Mutex);\n        FuseContextDelete(Context);\n        return;\n    }\n\n    for (PLIST_ENTRY Entry = Ioq->PendingList.Flink; &Ioq->PendingList != Entry;)\n    {\n        FUSE_CONTEXT *Temp = CONTAINING_RECORD(Entry, FUSE_CONTEXT, ListEntry);\n        Entry = Entry->Flink;\n        FuseContextDelete(Temp);\n    }\n    InitializeListHead(&Ioq->PendingList);\n\n    InsertTailList(&Ioq->PendingList, &Context->ListEntry);\n    Ioq->LastContext = Context;\n\n    ExReleaseFastMutex(&Ioq->Mutex);\n}\n\nFUSE_CONTEXT *FuseIoqNextPending(FUSE_IOQ *Ioq)\n{\n    PAGED_CODE();\n\n    ExAcquireFastMutex(&Ioq->Mutex);\n\n    if (0 != Ioq->LastContext && !IsListEmpty(&Ioq->ProcessList))\n    {\n        ExReleaseFastMutex(&Ioq->Mutex);\n        return 0;\n    }\n\n    PLIST_ENTRY Entry = Ioq->PendingList.Flink;\n    FUSE_CONTEXT *Context = &Ioq->PendingList != Entry ?\n        CONTAINING_RECORD(Entry, FUSE_CONTEXT, ListEntry) : 0;\n\n    if (0 != Context)\n        RemoveEntryList(&Context->ListEntry);\n\n    ExReleaseFastMutex(&Ioq->Mutex);\n\n    return Context;\n}\n"
  },
  {
    "path": "src/shared/km/path.c",
    "content": "/**\n * @file shared/km/path.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\nVOID FusePosixPathPrefix(PSTRING Path, PSTRING Prefix, PSTRING Remain);\nVOID FusePosixPathSuffix(PSTRING Path, PSTRING Remain, PSTRING Suffix);\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(PAGE, FusePosixPathPrefix)\n#pragma alloc_text(PAGE, FusePosixPathSuffix)\n#endif\n\nVOID FusePosixPathPrefix(PSTRING Path, PSTRING Prefix, PSTRING Remain)\n{\n    PAGED_CODE();\n\n    STRING PathBuf, PrefixBuf, RemainBuf;\n\n    PathBuf = *Path;\n    if (0 == Prefix)\n        Prefix = &PrefixBuf;\n    if (0 == Remain)\n        Remain = &RemainBuf;\n\n    PSTR P = PathBuf.Buffer, EndP = P + PathBuf.Length / sizeof(*P);\n\n    if (EndP > P && '/' == *P)\n    {\n        Prefix->Length = 1;\n        Prefix->Buffer = PathBuf.Buffer;\n    }\n    else\n    {\n        while (EndP > P && '/' != *P)\n            P++;\n\n        Prefix->Length = (USHORT)((P - PathBuf.Buffer) * sizeof *P);\n        Prefix->Buffer = PathBuf.Buffer;\n    }\n\n    while (EndP > P && '/' == *P)\n        P++;\n\n    Remain->Length = (USHORT)((EndP - P) * sizeof *P);\n    Remain->Buffer = P;\n\n    Prefix->MaximumLength = Prefix->Length;\n    Remain->MaximumLength = Remain->Length;\n}\n\nVOID FusePosixPathSuffix(PSTRING Path, PSTRING Remain, PSTRING Suffix)\n{\n    PAGED_CODE();\n\n    STRING PathBuf, RemainBuf, SuffixBuf;\n\n    PathBuf = *Path;\n    if (0 == Remain)\n        Remain = &RemainBuf;\n    if (0 == Suffix)\n        Suffix = &SuffixBuf;\n\n    PSTR P = PathBuf.Buffer, EndP = P + PathBuf.Length / sizeof(*P);\n\n    Remain->Length = PathBuf.Length;\n    Remain->Buffer = PathBuf.Buffer;\n\n    Suffix->Length = 0;\n    Suffix->Buffer = PathBuf.Buffer;\n\n    while (EndP > P)\n        if ('/' == *P)\n        {\n            Remain->Length = (USHORT)((P - PathBuf.Buffer) * sizeof *P);\n            if (0 == Remain->Length)\n                Remain->Length = 1;\n\n            while (EndP > P && '/' == *P)\n                P++;\n\n            Suffix->Length = (USHORT)((EndP - P) * sizeof *P);\n            Suffix->Buffer = P;\n        }\n        else\n            P++;\n\n    Remain->MaximumLength = Remain->Length;\n    Suffix->MaximumLength = Suffix->Length;\n}\n"
  },
  {
    "path": "src/shared/km/proto.c",
    "content": "/**\n * @file shared/km/proto.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\nNTSTATUS FuseProtoPostInit(FUSE_INSTANCE *Instance);\nVOID FuseProtoSendInit(FUSE_CONTEXT *Context);\nNTSTATUS FuseProtoPostDestroy(FUSE_INSTANCE *Instance);\nVOID FuseProtoSendDestroy(FUSE_CONTEXT *Context);\nVOID FuseProtoSendLookup(FUSE_CONTEXT *Context);\nNTSTATUS FuseProtoPostForget(FUSE_INSTANCE *Instance, PLIST_ENTRY ForgetList);\nstatic VOID FuseProtoPostForget_ContextFini(FUSE_CONTEXT *Context);\nVOID FuseProtoFillForget(FUSE_CONTEXT *Context);\nVOID FuseProtoFillBatchForget(FUSE_CONTEXT *Context);\nVOID FuseProtoSendStatfs(FUSE_CONTEXT *Context);\nVOID FuseProtoSendGetattr(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFgetattr(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFtruncate(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFutimens(FUSE_CONTEXT *Context);\nVOID FuseProtoSendLookupChown(FUSE_CONTEXT *Context);\nVOID FuseProtoSendSetattr(FUSE_CONTEXT *Context);\nVOID FuseProtoSendMkdir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendMknod(FUSE_CONTEXT *Context);\nVOID FuseProtoSendRmdir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendUnlink(FUSE_CONTEXT *Context);\nVOID FuseProtoSendRename(FUSE_CONTEXT *Context);\nVOID FuseProtoSendCreate(FUSE_CONTEXT *Context);\nVOID FuseProtoSendOpendir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendOpen(FUSE_CONTEXT *Context);\nVOID FuseProtoSendReleasedir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendRelease(FUSE_CONTEXT *Context);\nVOID FuseProtoSendReaddir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendRead(FUSE_CONTEXT *Context);\nVOID FuseProtoSendWrite(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFsyncdir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFsync(FUSE_CONTEXT *Context);\nVOID FuseAttrToFileInfo(FUSE_INSTANCE *Instance,\n    FUSE_PROTO_ATTR *Attr, FSP_FSCTL_FILE_INFO *FileInfo);\nNTSTATUS FuseNtStatusFromErrno(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno);\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(PAGE, FuseProtoPostInit)\n#pragma alloc_text(PAGE, FuseProtoSendInit)\n#pragma alloc_text(PAGE, FuseProtoPostDestroy)\n#pragma alloc_text(PAGE, FuseProtoSendDestroy)\n#pragma alloc_text(PAGE, FuseProtoSendLookup)\n#pragma alloc_text(PAGE, FuseProtoPostForget)\n#pragma alloc_text(PAGE, FuseProtoPostForget_ContextFini)\n#pragma alloc_text(PAGE, FuseProtoFillForget)\n#pragma alloc_text(PAGE, FuseProtoFillBatchForget)\n#pragma alloc_text(PAGE, FuseProtoSendStatfs)\n#pragma alloc_text(PAGE, FuseProtoSendGetattr)\n#pragma alloc_text(PAGE, FuseProtoSendFgetattr)\n#pragma alloc_text(PAGE, FuseProtoSendFtruncate)\n#pragma alloc_text(PAGE, FuseProtoSendFutimens)\n#pragma alloc_text(PAGE, FuseProtoSendLookupChown)\n#pragma alloc_text(PAGE, FuseProtoSendSetattr)\n#pragma alloc_text(PAGE, FuseProtoSendMkdir)\n#pragma alloc_text(PAGE, FuseProtoSendMknod)\n#pragma alloc_text(PAGE, FuseProtoSendRmdir)\n#pragma alloc_text(PAGE, FuseProtoSendUnlink)\n#pragma alloc_text(PAGE, FuseProtoSendRename)\n#pragma alloc_text(PAGE, FuseProtoSendCreate)\n#pragma alloc_text(PAGE, FuseProtoSendOpendir)\n#pragma alloc_text(PAGE, FuseProtoSendOpen)\n#pragma alloc_text(PAGE, FuseProtoSendReleasedir)\n#pragma alloc_text(PAGE, FuseProtoSendRelease)\n#pragma alloc_text(PAGE, FuseProtoSendReaddir)\n#pragma alloc_text(PAGE, FuseProtoSendRead)\n#pragma alloc_text(PAGE, FuseProtoSendWrite)\n#pragma alloc_text(PAGE, FuseProtoSendFsyncdir)\n#pragma alloc_text(PAGE, FuseProtoSendFsync)\n#pragma alloc_text(PAGE, FuseAttrToFileInfo)\n#pragma alloc_text(PAGE, FuseNtStatusFromErrno)\n#endif\n\n#define FUSE_PROTO_SEND_BEGIN           \\\n    coro_block(Context->CoroState)      \\\n    {                                   \\\n        FuseContextWaitRequest(Context);\n#define FUSE_PROTO_SEND_END             \\\n        FuseContextWaitResponse(Context);\\\n        Context->InternalResponse->IoStatus.Status = 0 == Context->FuseResponse->error ?\\\n            STATUS_SUCCESS :\\\n            FuseNtStatusFromErrno(Context->Instance->InstanceType, Context->FuseResponse->error);\\\n    }\n#define FUSE_PROTO_SEND_BEGIN_(OPCODE)  \\\n    coro_block(Context->CoroState)      \\\n    {                                   \\\n        if (FuseInstanceGetOpcodeENOSYS(Context->Instance, FUSE_PROTO_OPCODE_ ## OPCODE))\\\n        {                               \\\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_DEVICE_REQUEST;\\\n            coro_break;                 \\\n        }                               \\\n        FuseContextWaitRequest(Context);\n#define FUSE_PROTO_SEND_END_(OPCODE)    \\\n        FuseContextWaitResponse(Context);\\\n        Context->InternalResponse->IoStatus.Status = 0 == Context->FuseResponse->error ?\\\n            STATUS_SUCCESS :\\\n            FuseNtStatusFromErrno(Context->Instance->InstanceType, Context->FuseResponse->error);\\\n        if (STATUS_INVALID_DEVICE_REQUEST == Context->InternalResponse->IoStatus.Status)\\\n            FuseInstanceSetOpcodeENOSYS(Context->Instance, FUSE_PROTO_OPCODE_ ## OPCODE);\\\n    }\n\nstatic inline VOID FuseProtoInitRequest(FUSE_CONTEXT *Context,\n    UINT32 len, UINT32 opcode, UINT64 nodeid)\n{\n    Context->FuseRequest->len = len;\n    Context->FuseRequest->opcode = opcode;\n    Context->FuseRequest->unique = (UINT64)(UINT_PTR)Context;\n    Context->FuseRequest->nodeid = nodeid;\n    Context->FuseRequest->uid = Context->OrigUid;\n    Context->FuseRequest->gid = Context->OrigGid;\n    Context->FuseRequest->pid = Context->OrigPid;\n}\n\nNTSTATUS FuseProtoPostInit(FUSE_INSTANCE *Instance)\n{\n    PAGED_CODE();\n\n    FUSE_CONTEXT *Context;\n\n    FuseContextCreate(&Context, Instance, 0);\n    ASSERT(0 != Context);\n    if (FuseContextIsStatus(Context))\n        return FuseContextToStatus(Context);\n\n    Context->InternalResponse->Hint = FUSE_PROTO_OPCODE_INIT;\n\n    FuseIoqPostPending(Instance->Ioq, Context);\n\n    return STATUS_SUCCESS;\n}\n\nVOID FuseProtoSendInit(FUSE_CONTEXT *Context)\n    /*\n     * Send INIT message.\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(init), FUSE_PROTO_OPCODE_INIT, 0);\n        Context->FuseRequest->req.init.major = FUSE_PROTO_VERSION;\n        Context->FuseRequest->req.init.minor = FUSE_PROTO_MINOR_VERSION;\n        Context->FuseRequest->req.init.max_readahead = 0;   /* !!!: REVISIT */\n        Context->FuseRequest->req.init.flags = 0;           /* !!!: REVISIT */\n\n    FUSE_PROTO_SEND_END\n}\n\nNTSTATUS FuseProtoPostDestroy(FUSE_INSTANCE *Instance)\n{\n    PAGED_CODE();\n\n    FUSE_CONTEXT *Context;\n\n    FuseContextCreate(&Context, Instance, 0);\n    ASSERT(0 != Context);\n    if (FuseContextIsStatus(Context))\n        return FuseContextToStatus(Context);\n\n    Context->InternalResponse->Hint = FUSE_PROTO_OPCODE_DESTROY;\n\n    FuseIoqPostPendingAndStop(Instance->Ioq, Context);\n\n    return STATUS_SUCCESS;\n}\n\nVOID FuseProtoSendDestroy(FUSE_CONTEXT *Context)\n    /*\n     * Send DESTROY message.\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_HEADER_SIZE, FUSE_PROTO_OPCODE_DESTROY, 0);\n\n        if (0 != Context->Instance->ProtoSendDestroyHandler)\n            Context->Instance->ProtoSendDestroyHandler(Context->Instance->ProtoSendDestroyData);\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendLookup(FUSE_CONTEXT *Context)\n    /*\n     * Send LOOKUP message.\n     *\n     * Context->Lookup.Ino\n     *     parent directory inode number\n     * Context->Lookup.Name\n     *     name to lookup\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            (UINT32)(FUSE_PROTO_REQ_SIZE(lookup) + Context->Lookup.Name.Length + 1),\n            FUSE_PROTO_OPCODE_LOOKUP, Context->Lookup.Ino);\n        ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len);\n        RtlCopyMemory(Context->FuseRequest->req.lookup.name, Context->Lookup.Name.Buffer,\n            Context->Lookup.Name.Length);\n        Context->FuseRequest->req.lookup.name[Context->Lookup.Name.Length] = '\\0';\n\n    FUSE_PROTO_SEND_END\n}\n\nNTSTATUS FuseProtoPostForget(FUSE_INSTANCE *Instance, PLIST_ENTRY ForgetList)\n{\n    PAGED_CODE();\n\n    FUSE_CONTEXT *Context;\n\n    FuseContextCreate(&Context, Instance, 0);\n    ASSERT(0 != Context);\n    if (FuseContextIsStatus(Context))\n        return FuseContextToStatus(Context);\n\n    Context->Fini = FuseProtoPostForget_ContextFini;\n    Context->InternalResponse->Hint = FUSE_PROTO_OPCODE_FORGET;\n\n    ASSERT(ForgetList != ForgetList->Flink);\n    Context->Forget.ForgetList = *ForgetList;\n    /* fixup first/last list entry */\n    Context->Forget.ForgetList.Flink->Blink = &Context->Forget.ForgetList;\n    Context->Forget.ForgetList.Blink->Flink = &Context->Forget.ForgetList;\n\n    FuseIoqPostPending(Instance->Ioq, Context);\n\n    return STATUS_SUCCESS;\n}\n\nstatic VOID FuseProtoPostForget_ContextFini(FUSE_CONTEXT *Context)\n{\n    PAGED_CODE();\n\n    FuseCacheDeleteForgotten(&Context->Forget.ForgetList);\n}\n\nVOID FuseProtoFillForget(FUSE_CONTEXT *Context)\n    /*\n     * Fill FORGET message. This message is used to forget a single inode number.\n     *\n     * Context->Forget.ForgetList\n     *     list that contains items to forget\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_FORGET_ONE ForgetOne;\n    BOOLEAN Ok;\n\n    Ok = FuseCacheForgetOne(&Context->Forget.ForgetList, &ForgetOne);\n    ASSERT(Ok);\n\n    FuseProtoInitRequest(Context,\n        FUSE_PROTO_REQ_SIZE(forget), FUSE_PROTO_OPCODE_FORGET, ForgetOne.nodeid);\n    Context->FuseRequest->req.forget.nlookup = ForgetOne.nlookup;\n}\n\nVOID FuseProtoFillBatchForget(FUSE_CONTEXT *Context)\n    /*\n     * Fill BATCH_FORGET message. This message is used to forget multiple inode numbers.\n     *\n     * Context->Forget.ForgetList\n     *     list that contains items to forget\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_FORGET_ONE *StartP, *EndP, *P;\n\n    StartP = (PVOID)((PUINT8)Context->FuseRequest + FUSE_PROTO_REQ_SIZE(batch_forget));\n    EndP = (PVOID)((PUINT8)StartP + (FUSE_PROTO_REQ_SIZEMIN - FUSE_PROTO_REQ_SIZE(batch_forget)));\n    for (P = StartP; DEBUGTEST(90) && EndP > P && FuseCacheForgetOne(&Context->Forget.ForgetList, P); P++)\n        ;\n\n    FuseProtoInitRequest(Context,\n        (UINT32)((PUINT8)P - (PUINT8)Context->FuseRequest), FUSE_PROTO_OPCODE_BATCH_FORGET, 0);\n    ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len);\n    Context->FuseRequest->req.batch_forget.count = (ULONG)(P - StartP);\n}\n\nVOID FuseProtoSendStatfs(FUSE_CONTEXT *Context)\n    /*\n     * Send STATFS message.\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_HEADER_SIZE, FUSE_PROTO_OPCODE_STATFS, 0);\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendGetattr(FUSE_CONTEXT *Context)\n    /*\n     * Send GETATTR message.\n     *\n     * Context->Lookup.Ino\n     *     inode number to get attributes for\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(getattr), FUSE_PROTO_OPCODE_GETATTR, Context->Lookup.Ino);\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendFgetattr(FUSE_CONTEXT *Context)\n    /*\n     * Send GETATTR message given a file.\n     *\n     * Context->File->IsDirectory\n     *     true if file is a directory\n     * Context->File->Ino\n     *     inode number of related file\n     * Context->File->Fh\n     *     handle of related file; use only when file is not a directory\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        if (Context->File->IsDirectory)\n        {\n            FuseProtoInitRequest(Context,\n                FUSE_PROTO_REQ_SIZE(getattr), FUSE_PROTO_OPCODE_GETATTR, Context->File->Ino);\n        }\n        else\n        {\n            FuseProtoInitRequest(Context,\n                FUSE_PROTO_REQ_SIZE(getattr), FUSE_PROTO_OPCODE_GETATTR, Context->File->Ino);\n            Context->FuseRequest->req.getattr.getattr_flags = FUSE_PROTO_GETATTR_FH;\n            Context->FuseRequest->req.getattr.fh = Context->File->Fh;\n        }\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendFtruncate(FUSE_CONTEXT *Context)\n    /*\n     * Send SETATTR message for truncate.\n     *\n     * Context->File->Ino\n     *     inode number of related file\n     * Context->File->Fh\n     *     handle of related file\n     * Context->Setattr.Attr.size\n     *     new size of file\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino);\n        Context->FuseRequest->req.setattr.valid =\n            FUSE_PROTO_SETATTR_FH | FUSE_PROTO_SETATTR_SIZE;\n        Context->FuseRequest->req.setattr.fh = Context->File->Fh;\n        Context->FuseRequest->req.setattr.size = Context->Setattr.Attr.size;\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendFutimens(FUSE_CONTEXT *Context)\n    /*\n     * Send SETATTR message for utimens.\n     *\n     * Context->File->Ino\n     *     inode number of related file\n     * Context->File->Fh\n     *     handle of related file\n     * Context->Setattr.Attr.{atime,atimensec}\n     *     new access time of file\n     * Context->Setattr.Attr.{mtime,mtimensec}\n     *     new modification time of file\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        if (Context->File->IsDirectory)\n        {\n            FuseProtoInitRequest(Context,\n                FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino);\n        }\n        else\n        {\n            FuseProtoInitRequest(Context,\n                FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino);\n            Context->FuseRequest->req.setattr.valid = FUSE_PROTO_SETATTR_FH;\n            Context->FuseRequest->req.setattr.fh = Context->File->Fh;\n        }\n\n        if (FUSE_PROTO_UTIME_OMIT != Context->Setattr.Attr.atimensec)\n        {\n            Context->FuseRequest->req.setattr.valid |= FUSE_PROTO_SETATTR_ATIME;\n            Context->FuseRequest->req.setattr.atime = Context->Setattr.Attr.atime;\n            Context->FuseRequest->req.setattr.atimensec = Context->Setattr.Attr.atimensec;\n        }\n        if (FUSE_PROTO_UTIME_OMIT != Context->Setattr.Attr.mtimensec)\n        {\n            Context->FuseRequest->req.setattr.valid |= FUSE_PROTO_SETATTR_MTIME;\n            Context->FuseRequest->req.setattr.mtime = Context->Setattr.Attr.mtime;\n            Context->FuseRequest->req.setattr.mtimensec = Context->Setattr.Attr.mtimensec;\n        }\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendLookupChown(FUSE_CONTEXT *Context)\n    /*\n     * Send SETATTR message for chown.\n     *\n     * Context->File->IsDirectory\n     *     true if file is a directory\n     * Context->File->Ino\n     *     inode number of related file; use when file is a directory\n     * Context->File->Fh\n     *     handle of related file; use when file is not a directory\n     * Context->Lookup.Attr.uid\n     *     uid of new file\n     * Context->Lookup.Attr.gid\n     *     gid of new file\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        if (Context->File->IsDirectory)\n        {\n            FuseProtoInitRequest(Context,\n                FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino);\n            Context->FuseRequest->req.setattr.valid =\n                FUSE_PROTO_SETATTR_UID | FUSE_PROTO_SETATTR_GID;\n            Context->FuseRequest->req.setattr.uid = Context->Lookup.Attr.uid;\n            Context->FuseRequest->req.setattr.gid = Context->Lookup.Attr.gid;\n        }\n        else\n        {\n            FuseProtoInitRequest(Context,\n                FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino);\n            Context->FuseRequest->req.setattr.valid =\n                FUSE_PROTO_SETATTR_FH | FUSE_PROTO_SETATTR_UID | FUSE_PROTO_SETATTR_GID;\n            Context->FuseRequest->req.setattr.fh = Context->File->Fh;\n            Context->FuseRequest->req.setattr.uid = Context->Lookup.Attr.uid;\n            Context->FuseRequest->req.setattr.gid = Context->Lookup.Attr.gid;\n        }\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendSetattr(FUSE_CONTEXT *Context)\n    /*\n     * Send SETATTR message.\n     *\n     * Context->File->IsDirectory\n     *     true if file is a directory\n     * Context->File->Ino\n     *     inode number of related file; use when file is a directory\n     * Context->File->Fh\n     *     handle of related file; use when file is not a directory\n     * Context->Setattr.AttrValid\n     *     valid attr fields\n     * Context->Setattr.Attr\n     *     new attr of file\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        if (Context->File->IsDirectory)\n        {\n            FuseProtoInitRequest(Context,\n                FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino);\n            Context->FuseRequest->req.setattr.size = Context->Setattr.Attr.size;\n            Context->FuseRequest->req.setattr.atime = Context->Setattr.Attr.atime;\n            Context->FuseRequest->req.setattr.mtime = Context->Setattr.Attr.mtime;\n            Context->FuseRequest->req.setattr.ctime = Context->Setattr.Attr.ctime;\n            Context->FuseRequest->req.setattr.atimensec = Context->Setattr.Attr.atimensec;\n            Context->FuseRequest->req.setattr.mtimensec = Context->Setattr.Attr.mtimensec;\n            Context->FuseRequest->req.setattr.ctimensec = Context->Setattr.Attr.ctimensec;\n            Context->FuseRequest->req.setattr.mode = Context->Setattr.Attr.mode;\n            Context->FuseRequest->req.setattr.uid = Context->Setattr.Attr.uid;\n            Context->FuseRequest->req.setattr.gid = Context->Setattr.Attr.gid;\n            Context->FuseRequest->req.setattr.valid = Context->Setattr.AttrValid;\n        }\n        else\n        {\n            FuseProtoInitRequest(Context,\n                FUSE_PROTO_REQ_SIZE(setattr), FUSE_PROTO_OPCODE_SETATTR, Context->File->Ino);\n            Context->FuseRequest->req.setattr.size = Context->Setattr.Attr.size;\n            Context->FuseRequest->req.setattr.atime = Context->Setattr.Attr.atime;\n            Context->FuseRequest->req.setattr.mtime = Context->Setattr.Attr.mtime;\n            Context->FuseRequest->req.setattr.ctime = Context->Setattr.Attr.ctime;\n            Context->FuseRequest->req.setattr.atimensec = Context->Setattr.Attr.atimensec;\n            Context->FuseRequest->req.setattr.mtimensec = Context->Setattr.Attr.mtimensec;\n            Context->FuseRequest->req.setattr.ctimensec = Context->Setattr.Attr.ctimensec;\n            Context->FuseRequest->req.setattr.mode = Context->Setattr.Attr.mode;\n            Context->FuseRequest->req.setattr.uid = Context->Setattr.Attr.uid;\n            Context->FuseRequest->req.setattr.gid = Context->Setattr.Attr.gid;\n            Context->FuseRequest->req.setattr.fh = Context->File->Fh;\n            Context->FuseRequest->req.setattr.valid = Context->Setattr.AttrValid | FUSE_PROTO_SETATTR_FH;\n        }\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendMkdir(FUSE_CONTEXT *Context)\n    /*\n     * Send MKDIR message.\n     *\n     * Context->Lookup.Ino\n     *     parent directory inode number\n     * Context->Lookup.Name\n     *     name of new directory\n     * Context->Lookup.Attr.mode\n     *     mode of new directory\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            (UINT32)(FUSE_PROTO_REQ_SIZE(mkdir) + Context->Lookup.Name.Length + 1),\n            FUSE_PROTO_OPCODE_MKDIR, Context->Lookup.Ino);\n        ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len);\n        Context->FuseRequest->req.mkdir.mode = Context->Lookup.Attr.mode;\n        Context->FuseRequest->req.mkdir.umask = 0;          /* !!!: REVISIT */\n        RtlCopyMemory(Context->FuseRequest->req.mkdir.name, Context->Lookup.Name.Buffer,\n            Context->Lookup.Name.Length);\n        Context->FuseRequest->req.mkdir.name[Context->Lookup.Name.Length] = '\\0';\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendMknod(FUSE_CONTEXT *Context)\n    /*\n     * Send MKNOD message.\n     *\n     * Context->Lookup.Ino\n     *     parent directory inode number\n     * Context->Lookup.Name\n     *     name of new file\n     * Context->Lookup.Attr.mode\n     *     mode of new file\n     * Context->Lookup.Attr.rdev\n     *     device number of new file (when file is a device)\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            (UINT32)(FUSE_PROTO_REQ_SIZE(mknod) + Context->Lookup.Name.Length + 1),\n            FUSE_PROTO_OPCODE_MKNOD, Context->Lookup.Ino);\n        ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len);\n        Context->FuseRequest->req.mknod.mode = Context->Lookup.Attr.mode;\n        Context->FuseRequest->req.mknod.rdev = Context->Lookup.Attr.rdev;\n        Context->FuseRequest->req.mknod.umask = 0;          /* !!!: REVISIT */\n        RtlCopyMemory(Context->FuseRequest->req.mknod.name, Context->Lookup.Name.Buffer,\n            Context->Lookup.Name.Length);\n        Context->FuseRequest->req.mknod.name[Context->Lookup.Name.Length] = '\\0';\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendRmdir(FUSE_CONTEXT *Context)\n    /*\n     * Send RMDIR message.\n     *\n     * Context->Lookup.Ino\n     *     parent directory inode number\n     * Context->Lookup.Name\n     *     name of directory\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            (UINT32)(FUSE_PROTO_REQ_SIZE(rmdir) + Context->Lookup.Name.Length + 1),\n            FUSE_PROTO_OPCODE_RMDIR, Context->Lookup.Ino);\n        ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len);\n        RtlCopyMemory(Context->FuseRequest->req.rmdir.name, Context->Lookup.Name.Buffer,\n            Context->Lookup.Name.Length);\n        Context->FuseRequest->req.rmdir.name[Context->Lookup.Name.Length] = '\\0';\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendUnlink(FUSE_CONTEXT *Context)\n    /*\n     * Send UNLINK message.\n     *\n     * Context->Lookup.Ino\n     *     parent directory inode number\n     * Context->Lookup.Name\n     *     name of file\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            (UINT32)(FUSE_PROTO_REQ_SIZE(unlink) + Context->Lookup.Name.Length + 1),\n            FUSE_PROTO_OPCODE_UNLINK, Context->Lookup.Ino);\n        ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len);\n        RtlCopyMemory(Context->FuseRequest->req.unlink.name, Context->Lookup.Name.Buffer,\n            Context->Lookup.Name.Length);\n        Context->FuseRequest->req.unlink.name[Context->Lookup.Name.Length] = '\\0';\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendRename(FUSE_CONTEXT *Context)\n    /*\n     * Send RENAME message.\n     *\n     * Context->LookupPath.Ino\n     *     old parent directory inode number\n     * Context->LookupPath.Name\n     *     old name of file\n     * Context->LookupPath.Ino2\n     *     new parent directory inode number\n     * Context->LookupPath.Name2\n     *     new name of file\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context, (UINT32)(FUSE_PROTO_REQ_SIZE(rename) +\n            Context->LookupPath.Name.Length + 1 + Context->LookupPath.Name2.Length + 1),\n            FUSE_PROTO_OPCODE_RENAME, Context->LookupPath.Ino);\n        ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len);\n        Context->FuseRequest->req.rename.newdir = Context->LookupPath.Ino2;\n        RtlCopyMemory(Context->FuseRequest->req.rename.name,\n            Context->LookupPath.Name.Buffer,\n            Context->LookupPath.Name.Length);\n        Context->FuseRequest->req.rename.name[Context->LookupPath.Name.Length] = '\\0';\n        RtlCopyMemory(Context->FuseRequest->req.rename.name + Context->LookupPath.Name.Length + 1,\n            Context->LookupPath.Name2.Buffer,\n            Context->LookupPath.Name2.Length);\n        (Context->FuseRequest->req.rename.name + Context->LookupPath.Name.Length + 1)\n            [Context->LookupPath.Name2.Length] = '\\0';\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendCreate(FUSE_CONTEXT *Context)\n    /*\n     * Send CREATE message.\n     *\n     * Context->Lookup.Ino\n     *     parent directory inode number\n     * Context->Lookup.Name\n     *     name of new file\n     * Context->Lookup.Attr.mode\n     *     mode of new file\n     * Context->File->OpenFlags\n     *     open (O_*) flags\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN_(CREATE)\n\n        FuseProtoInitRequest(Context,\n            (UINT32)(FUSE_PROTO_REQ_SIZE(create) + Context->Lookup.Name.Length + 1),\n            FUSE_PROTO_OPCODE_CREATE, Context->Lookup.Ino);\n        ASSERT(FUSE_PROTO_REQ_SIZEMIN >= Context->FuseRequest->len);\n        Context->FuseRequest->req.create.flags = Context->File->OpenFlags;\n        Context->FuseRequest->req.create.mode = Context->Lookup.Attr.mode;\n        Context->FuseRequest->req.create.umask = 0;         /* !!!: REVISIT */\n        RtlCopyMemory(Context->FuseRequest->req.create.name, Context->Lookup.Name.Buffer,\n            Context->Lookup.Name.Length);\n        Context->FuseRequest->req.create.name[Context->Lookup.Name.Length] = '\\0';\n\n    FUSE_PROTO_SEND_END_(CREATE)\n}\n\nVOID FuseProtoSendOpendir(FUSE_CONTEXT *Context)\n    /*\n     * Send OPENDIR message.\n     *\n     * Context->Lookup.Ino\n     *     inode number of directory to open\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(open), FUSE_PROTO_OPCODE_OPENDIR, Context->Lookup.Ino);\n        Context->FuseRequest->req.open.flags = Context->File->OpenFlags;\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendOpen(FUSE_CONTEXT *Context)\n    /*\n     * Send OPEN message.\n     *\n     * Context->Lookup.Ino\n     *     inode number of file to open\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(open), FUSE_PROTO_OPCODE_OPEN, Context->Lookup.Ino);\n        Context->FuseRequest->req.open.flags = Context->File->OpenFlags;\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendReleasedir(FUSE_CONTEXT *Context)\n    /*\n     * Send RELEASEDIR message.\n     *\n     * Context->File->Ino\n     *     inode number of related directory\n     * Context->File->Fh\n     *     handle of related directory\n     * Context->File->OpenFlags\n     *     open (O_*) flags\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(release), FUSE_PROTO_OPCODE_RELEASEDIR, Context->File->Ino);\n        Context->FuseRequest->req.release.fh = Context->File->Fh;\n        Context->FuseRequest->req.release.flags = Context->File->OpenFlags;\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendRelease(FUSE_CONTEXT *Context)\n    /*\n     * Send RELEASE message.\n     *\n     * Context->File->Ino\n     *     inode number of related file\n     * Context->File->Fh\n     *     handle of related file\n     * Context->File->OpenFlags\n     *     open (O_*) flags\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(release), FUSE_PROTO_OPCODE_RELEASE, Context->File->Ino);\n        Context->FuseRequest->req.release.fh = Context->File->Fh;\n        Context->FuseRequest->req.release.flags = Context->File->OpenFlags;\n        Context->FuseRequest->req.release.release_flags = 0;/* !!!: REVISIT */\n        Context->FuseRequest->req.release.lock_owner = 0;   /* !!!: REVISIT */\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendReaddir(FUSE_CONTEXT *Context)\n    /*\n     * Send READDIR message.\n     *\n     * Context->File->Ino\n     *     inode number of related directory\n     * Context->File->Fh\n     *     handle of related directory\n     * Context->QueryDirectory.NextOffset\n     *     offset of next directory entry or 0\n     * Context->QueryDirectory.Length\n     *     readdir buffer length\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(read), FUSE_PROTO_OPCODE_READDIR, Context->File->Ino);\n        Context->FuseRequest->req.read.fh = Context->File->Fh;\n        Context->FuseRequest->req.read.offset = Context->QueryDirectory.NextOffset;\n        Context->FuseRequest->req.read.size = Context->QueryDirectory.Length;\n        Context->FuseRequest->req.read.read_flags = 0;   /* !!!: REVISIT */\n        Context->FuseRequest->req.read.lock_owner = 0;   /* !!!: REVISIT */\n        Context->FuseRequest->req.read.flags = Context->File->OpenFlags;\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendRead(FUSE_CONTEXT *Context)\n    /*\n     * Send READ message.\n     *\n     * Context->File->Ino\n     *     inode number of related file\n     * Context->File->Fh\n     *     handle of related file\n     * Context->Read.Offset\n     *     offset to read\n     * Context->Read.Length\n     *     read buffer length\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(read), FUSE_PROTO_OPCODE_READ, Context->File->Ino);\n        Context->FuseRequest->req.read.fh = Context->File->Fh;\n        Context->FuseRequest->req.read.offset = Context->Read.StartOffset + Context->Read.Offset;\n        Context->FuseRequest->req.read.size = Context->Read.Length;\n        Context->FuseRequest->req.read.read_flags = 0;   /* !!!: REVISIT */\n        Context->FuseRequest->req.read.lock_owner = 0;   /* !!!: REVISIT */\n        Context->FuseRequest->req.read.flags = Context->File->OpenFlags;\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendWrite(FUSE_CONTEXT *Context)\n    /*\n     * Send WRITE message.\n     *\n     * Context->File->Ino\n     *     inode number of related file\n     * Context->File->Fh\n     *     handle of related file\n     * Context->Write.Offset\n     *     offset to write\n     * Context->Write.Length\n     *     write buffer length\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(write) + Context->Write.Length,\n            FUSE_PROTO_OPCODE_WRITE, Context->File->Ino);\n        Context->FuseRequest->req.write.fh = Context->File->Fh;\n        Context->FuseRequest->req.write.offset = Context->Write.StartOffset + Context->Write.Offset;\n        Context->FuseRequest->req.write.size = Context->Write.Length;\n        Context->FuseRequest->req.write.write_flags = 0;   /* !!!: REVISIT */\n        Context->FuseRequest->req.write.lock_owner = 0;   /* !!!: REVISIT */\n        Context->FuseRequest->req.write.flags = Context->File->OpenFlags;\n\n    FUSE_PROTO_SEND_END\n}\n\nVOID FuseProtoSendFsyncdir(FUSE_CONTEXT *Context)\n    /*\n     * Send FSYNCDIR message.\n     *\n     * Context->File->Ino\n     *     inode number of related directory\n     * Context->File->Fh\n     *     handle of related directory\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN_(FSYNCDIR)\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(fsync), FUSE_PROTO_OPCODE_FSYNCDIR, Context->File->Ino);\n        Context->FuseRequest->req.fsync.fh = Context->File->Fh;\n\n    FUSE_PROTO_SEND_END_(FSYNCDIR)\n}\n\nVOID FuseProtoSendFsync(FUSE_CONTEXT *Context)\n    /*\n     * Send FSYNC message.\n     *\n     * Context->File->Ino\n     *     inode number of related file\n     * Context->File->Fh\n     *     handle of related file\n     */\n{\n    PAGED_CODE();\n\n    FUSE_PROTO_SEND_BEGIN_(FSYNC)\n\n        FuseProtoInitRequest(Context,\n            FUSE_PROTO_REQ_SIZE(fsync), FUSE_PROTO_OPCODE_FSYNC, Context->File->Ino);\n        Context->FuseRequest->req.fsync.fh = Context->File->Fh;\n\n    FUSE_PROTO_SEND_END_(FSYNC)\n}\n\nVOID FuseAttrToFileInfo(FUSE_INSTANCE *Instance,\n    FUSE_PROTO_ATTR *Attr, FSP_FSCTL_FILE_INFO *FileInfo)\n{\n    PAGED_CODE();\n\n    UINT64 AllocationUnit;\n\n    AllocationUnit = (UINT64)Instance->VolumeParams->SectorSize *\n        (UINT64)Instance->VolumeParams->SectorsPerAllocationUnit;\n\n    switch (Attr->mode & 0170000)\n    {\n    case 0040000: /* S_IFDIR */\n        FileInfo->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;\n        FileInfo->ReparseTag = 0;\n        break;\n    case 0010000: /* S_IFIFO */\n    case 0020000: /* S_IFCHR */\n    case 0060000: /* S_IFBLK */\n    case 0140000: /* S_IFSOCK */\n        FileInfo->FileAttributes = FILE_ATTRIBUTE_REPARSE_POINT;\n        FileInfo->ReparseTag = IO_REPARSE_TAG_NFS;\n        break;\n    case 0120000: /* S_IFLNK */\n        /* !!!: if target is directory FILE_ATTRIBUTE_DIRECTORY must also be set! */\n        FileInfo->FileAttributes = FILE_ATTRIBUTE_REPARSE_POINT;\n        FileInfo->ReparseTag = IO_REPARSE_TAG_SYMLINK;\n        break;\n    default:\n        FileInfo->FileAttributes = 0;\n        FileInfo->ReparseTag = 0;\n        break;\n    }\n\n    FileInfo->FileSize = Attr->size;\n    FileInfo->AllocationSize =\n        (FileInfo->FileSize + AllocationUnit - 1) / AllocationUnit * AllocationUnit;\n    FuseUnixTimeToFileTime(Attr->atime, Attr->atimensec, &FileInfo->LastAccessTime);\n    FuseUnixTimeToFileTime(Attr->mtime, Attr->mtimensec, &FileInfo->LastWriteTime);\n    FuseUnixTimeToFileTime(Attr->ctime, Attr->ctimensec, &FileInfo->ChangeTime);\n    FileInfo->CreationTime = FileInfo->ChangeTime;\n    FileInfo->IndexNumber = Attr->ino;\n    FileInfo->HardLinks = 0;\n    FileInfo->EaSize = 0;\n}\n\nNTSTATUS FuseNtStatusFromErrno(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno)\n{\n    PAGED_CODE();\n\n    if (0 > Errno)\n        Errno = -Errno;\n\n    switch (InstanceType)\n    {\n    default:\n    case FuseInstanceWindows:\n        switch (Errno)\n        {\n        #undef FUSE_ERRNO\n        #define FUSE_ERRNO 87\n        #include \"errno.i\"\n        default:\n            return STATUS_ACCESS_DENIED;\n        }\n    case FuseInstanceCygwin:\n        switch (Errno)\n        {\n        #undef FUSE_ERRNO\n        #define FUSE_ERRNO 67\n        #include \"errno.i\"\n        default:\n            return STATUS_ACCESS_DENIED;\n        }\n    case FuseInstanceLinux:\n        switch (Errno)\n        {\n        #undef FUSE_ERRNO\n        #define FUSE_ERRNO 76\n        #include \"errno.i\"\n        default:\n            return STATUS_ACCESS_DENIED;\n        }\n    }\n}\n"
  },
  {
    "path": "src/shared/km/proto.h",
    "content": "/**\n * @file shared/km/proto.h\n *\n * This file is derived from libfuse/include/fuse_kernel.h:\n *     FUSE: Filesystem in Userspace\n *     Copyright (C) 2001-2007  Miklos Szeredi <miklos@szeredi.hu>\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#ifndef SHARED_KM_PROTO_H_INCLUDED\n#define SHARED_KM_PROTO_H_INCLUDED\n\n#define FUSE_PROTO_VERSION              7\n#define FUSE_PROTO_MINOR_VERSION        29\n\n#define FUSE_PROTO_ROOT_INO             1\n\n#define FUSE_PROTO_UNKNOWN_INO          0xffffffff\n\nenum FUSE_PROTO_OPCODE\n{\n    FUSE_PROTO_OPCODE_LOOKUP            = 1,\n    FUSE_PROTO_OPCODE_FORGET            = 2,\n    FUSE_PROTO_OPCODE_GETATTR           = 3,\n    FUSE_PROTO_OPCODE_SETATTR           = 4,\n    FUSE_PROTO_OPCODE_READLINK          = 5,\n    FUSE_PROTO_OPCODE_SYMLINK           = 6,\n    FUSE_PROTO_OPCODE_MKNOD             = 8,\n    FUSE_PROTO_OPCODE_MKDIR             = 9,\n    FUSE_PROTO_OPCODE_UNLINK            = 10,\n    FUSE_PROTO_OPCODE_RMDIR             = 11,\n    FUSE_PROTO_OPCODE_RENAME            = 12,\n    FUSE_PROTO_OPCODE_LINK              = 13,\n    FUSE_PROTO_OPCODE_OPEN              = 14,\n    FUSE_PROTO_OPCODE_READ              = 15,\n    FUSE_PROTO_OPCODE_WRITE             = 16,\n    FUSE_PROTO_OPCODE_STATFS            = 17,\n    FUSE_PROTO_OPCODE_RELEASE           = 18,\n    FUSE_PROTO_OPCODE_FSYNC             = 20,\n    FUSE_PROTO_OPCODE_SETXATTR          = 21,\n    FUSE_PROTO_OPCODE_GETXATTR          = 22,\n    FUSE_PROTO_OPCODE_LISTXATTR         = 23,\n    FUSE_PROTO_OPCODE_REMOVEXATTR       = 24,\n    FUSE_PROTO_OPCODE_FLUSH             = 25,\n    FUSE_PROTO_OPCODE_INIT              = 26,\n    FUSE_PROTO_OPCODE_OPENDIR           = 27,\n    FUSE_PROTO_OPCODE_READDIR           = 28,\n    FUSE_PROTO_OPCODE_RELEASEDIR        = 29,\n    FUSE_PROTO_OPCODE_FSYNCDIR          = 30,\n    FUSE_PROTO_OPCODE_GETLK             = 31,\n    FUSE_PROTO_OPCODE_SETLK             = 32,\n    FUSE_PROTO_OPCODE_SETLKW            = 33,\n    FUSE_PROTO_OPCODE_ACCESS            = 34,\n    FUSE_PROTO_OPCODE_CREATE            = 35,\n    FUSE_PROTO_OPCODE_INTERRUPT         = 36,\n    FUSE_PROTO_OPCODE_BMAP              = 37,\n    FUSE_PROTO_OPCODE_DESTROY           = 38,\n    FUSE_PROTO_OPCODE_IOCTL             = 39,\n    FUSE_PROTO_OPCODE_POLL              = 40,\n    FUSE_PROTO_OPCODE_NOTIFY_REPLY      = 41,\n    FUSE_PROTO_OPCODE_BATCH_FORGET      = 42,\n    FUSE_PROTO_OPCODE_FALLOCATE         = 43,\n    FUSE_PROTO_OPCODE_READDIRPLUS       = 44,\n    FUSE_PROTO_OPCODE_RENAME2           = 45,\n    FUSE_PROTO_OPCODE_LSEEK             = 46,\n    FUSE_PROTO_OPCODE_COPY_FILE_RANGE   = 47,\n};\n\nenum FUSE_PROTO_NOTIFY_CODE\n{\n    FUSE_PROTO_NOTIFY_POLL              = 1,\n    FUSE_PROTO_NOTIFY_INVAL_INODE       = 2,\n    FUSE_PROTO_NOTIFY_INVAL_ENTRY       = 3,\n    FUSE_PROTO_NOTIFY_STORE             = 4,\n    FUSE_PROTO_NOTIFY_RETRIEVE          = 5,\n    FUSE_PROTO_NOTIFY_DELETE            = 6,\n    FUSE_PROTO_NOTIFY_CODE_MAX,\n};\n\nenum\n{\n    FUSE_PROTO_SETATTR_MODE             = (1 << 0),\n    FUSE_PROTO_SETATTR_UID              = (1 << 1),\n    FUSE_PROTO_SETATTR_GID              = (1 << 2),\n    FUSE_PROTO_SETATTR_SIZE             = (1 << 3),\n    FUSE_PROTO_SETATTR_ATIME            = (1 << 4),\n    FUSE_PROTO_SETATTR_MTIME            = (1 << 5),\n    FUSE_PROTO_SETATTR_FH               = (1 << 6),\n    FUSE_PROTO_SETATTR_ATIME_NOW        = (1 << 7),\n    FUSE_PROTO_SETATTR_MTIME_NOW        = (1 << 8),\n    FUSE_PROTO_SETATTR_LOCKOWNER        = (1 << 9),\n    FUSE_PROTO_SETATTR_CTIME            = (1 << 10),\n\n    FUSE_PROTO_OPEN_DIRECT_IO           = (1 << 0),\n    FUSE_PROTO_OPEN_KEEP_CACHE          = (1 << 1),\n    FUSE_PROTO_OPEN_NONSEEKABLE         = (1 << 2),\n    FUSE_PROTO_OPEN_CACHE_DIR           = (1 << 3),\n\n    FUSE_PROTO_GETATTR_FH               = (1 << 0),\n\n    FUSE_PROTO_INIT_ASYNC_READ          = (1 << 0),\n    FUSE_PROTO_INIT_POSIX_LOCKS         = (1 << 1),\n    FUSE_PROTO_INIT_FILE_OPS            = (1 << 2),\n    FUSE_PROTO_INIT_ATOMIC_O_TRUNC      = (1 << 3),\n    FUSE_PROTO_INIT_EXPORT_SUPPORT      = (1 << 4),\n    FUSE_PROTO_INIT_BIG_WRITES          = (1 << 5),\n    FUSE_PROTO_INIT_DONT_MASK           = (1 << 6),\n    FUSE_PROTO_INIT_SPLICE_WRITE        = (1 << 7),\n    FUSE_PROTO_INIT_SPLICE_MOVE         = (1 << 8),\n    FUSE_PROTO_INIT_SPLICE_READ         = (1 << 9),\n    FUSE_PROTO_INIT_FLOCK_LOCKS         = (1 << 10),\n    FUSE_PROTO_INIT_HAS_IOCTL_DIR       = (1 << 11),\n    FUSE_PROTO_INIT_AUTO_INVAL_DATA     = (1 << 12),\n    FUSE_PROTO_INIT_DO_READDIRPLUS      = (1 << 13),\n    FUSE_PROTO_INIT_READDIRPLUS_AUTO    = (1 << 14),\n    FUSE_PROTO_INIT_ASYNC_DIO           = (1 << 15),\n    FUSE_PROTO_INIT_WRITEBACK_CACHE     = (1 << 16),\n    FUSE_PROTO_INIT_NO_OPEN_SUPPORT     = (1 << 17),\n    FUSE_PROTO_INIT_PARALLEL_DIROPS     = (1 << 18),\n    FUSE_PROTO_INIT_HANDLE_KILLPRIV     = (1 << 19),\n    FUSE_PROTO_INIT_POSIX_ACL           = (1 << 20),\n    FUSE_PROTO_INIT_ABORT_ERROR         = (1 << 21),\n    FUSE_PROTO_INIT_MAX_PAGES           = (1 << 22),\n    FUSE_PROTO_INIT_CACHE_SYMLINKS      = (1 << 23),\n    FUSE_PROTO_INIT_NO_OPENDIR_SUPPORT  = (1 << 24),\n\n    FUSE_PROTO_IOCTL_COMPAT             = (1 << 0),\n    FUSE_PROTO_IOCTL_UNRESTRICTED       = (1 << 1),\n    FUSE_PROTO_IOCTL_RETRY              = (1 << 2),\n    FUSE_PROTO_IOCTL_32BIT              = (1 << 3),\n    FUSE_PROTO_IOCTL_DIR                = (1 << 4),\n\n    FUSE_PROTO_LK_FLOCK                 = (1 << 0),\n\n    FUSE_PROTO_POLL_SCHEDULE_NOTIFY     = (1 << 0),\n\n    FUSE_PROTO_READ_LOCKOWNER           = (1 << 1),\n\n    FUSE_PROTO_RELEASE_FLUSH            = (1 << 0),\n    FUSE_PROTO_RELEASE_FLOCK_UNLOCK     = (1 << 1),\n\n    FUSE_PROTO_WRITE_CACHE              = (1 << 0),\n    FUSE_PROTO_WRITE_LOCKOWNER          = (1 << 1),\n};\n\nenum\n{\n    FUSE_PROTO_UTIME_NOW                = ((1 << 30) - 1),\n    FUSE_PROTO_UTIME_OMIT               = ((1 << 30) - 2),\n};\n\ntypedef struct\n{\n    UINT64 blocks;\n    UINT64 bfree;\n    UINT64 bavail;\n    UINT64 files;\n    UINT64 ffree;\n    UINT32 bsize;\n    UINT32 namelen;\n    UINT32 frsize;\n    UINT32 padding;\n    UINT32 spare[6];\n} FUSE_PROTO_STATFS;\n\ntypedef struct\n{\n    UINT64 ino;\n    UINT64 size;\n    UINT64 blocks;\n    UINT64 atime;\n    UINT64 mtime;\n    UINT64 ctime;\n    UINT32 atimensec;\n    UINT32 mtimensec;\n    UINT32 ctimensec;\n    UINT32 mode;\n    UINT32 nlink;\n    UINT32 uid;\n    UINT32 gid;\n    UINT32 rdev;\n    UINT32 blksize;\n    UINT32 padding;\n} FUSE_PROTO_ATTR;\n\ntypedef struct\n{\n    UINT64 nodeid;\n    UINT64 generation;\n    UINT64 entry_valid;\n    UINT64 attr_valid;\n    UINT32 entry_valid_nsec;\n    UINT32 attr_valid_nsec;\n    FUSE_PROTO_ATTR attr;\n} FUSE_PROTO_ENTRY;\n\ntypedef struct\n{\n    UINT64 ino;\n    UINT64 off;\n    UINT32 namelen;\n    UINT32 type;\n    CHAR name[];\n} FUSE_PROTO_DIRENT;\n\ntypedef struct\n{\n    FUSE_PROTO_ENTRY entry;\n    FUSE_PROTO_DIRENT dirent;\n} FUSE_PROTO_DIRENTPLUS;\n\ntypedef struct\n{\n    UINT64 start;\n    UINT64 end;\n    UINT32 type;\n    UINT32 pid;\n} FUSE_PROTO_FILE_LOCK;\n\ntypedef struct\n{\n    UINT64 base;\n    UINT64 len;\n} FUSE_PROTO_IOCTL_IOVEC;\n\ntypedef struct\n{\n    UINT64 nodeid;\n    UINT64 nlookup;\n} FUSE_PROTO_FORGET_ONE;\n\ntypedef struct\n{\n    UINT32 len;\n    UINT32 opcode;\n    UINT64 unique;\n    UINT64 nodeid;\n    UINT32 uid;\n    UINT32 gid;\n    UINT32 pid;\n    UINT32 padding;\n    union\n    {\n        struct\n        {\n            /* LOOKUP */\n            CHAR name[];\n        } lookup;\n        struct\n        {\n            /* FORGET */\n            UINT64 nlookup;\n        } forget;\n        struct\n        {\n            /* GETATTR */\n            UINT32 getattr_flags;\n            UINT32 dummy;\n            UINT64 fh;\n        } getattr;\n        struct\n        {\n            /* SETATTR */\n            UINT32 valid;\n            UINT32 padding;\n            UINT64 fh;\n            UINT64 size;\n            UINT64 lock_owner;\n            UINT64 atime;\n            UINT64 mtime;\n            UINT64 ctime;\n            UINT32 atimensec;\n            UINT32 mtimensec;\n            UINT32 ctimensec;\n            UINT32 mode;\n            UINT32 unused4;\n            UINT32 uid;\n            UINT32 gid;\n            UINT32 unused5;\n        } setattr;\n        struct\n        {\n            /* SYMLINK */\n            CHAR name[]; /* 2 names */\n        } symlink;\n        struct\n        {\n            /* MKNOD */\n            UINT32 mode;\n            UINT32 rdev;\n            UINT32 umask;\n            UINT32 padding;\n            CHAR name[];\n        } mknod;\n        struct\n        {\n            /* MKDIR */\n            UINT32 mode;\n            UINT32 umask;\n            CHAR name[];\n        } mkdir;\n        struct\n        {\n            /* UNLINK */\n            CHAR name[];\n        } unlink;\n        struct\n        {\n            /* RMDIR */\n            CHAR name[];\n        } rmdir;\n        struct\n        {\n            /* RENAME */\n            UINT64 newdir;\n            CHAR name[]; /* 2 names */\n        } rename;\n        struct\n        {\n            /* LINK */\n            UINT64 oldnodeid;\n            CHAR name[];\n        } link;\n        struct\n        {\n            /* OPEN, OPENDIR */\n            UINT32 flags;\n            UINT32 unused;\n        } open;\n        struct\n        {\n            /* READ, READDIR, READDIRPLUS */\n            UINT64 fh;\n            UINT64 offset;\n            UINT32 size;\n            UINT32 read_flags;\n            UINT64 lock_owner;\n            UINT32 flags;\n            UINT32 padding;\n        } read;\n        struct\n        {\n            /* WRITE */\n            UINT64 fh;\n            UINT64 offset;\n            UINT32 size;\n            UINT32 write_flags;\n            UINT64 lock_owner;\n            UINT32 flags;\n            UINT32 padding;\n        } write;\n        struct\n        {\n            /* RELEASE, RELEASEDIR */\n            UINT64 fh;\n            UINT32 flags;\n            UINT32 release_flags;\n            UINT64 lock_owner;\n        } release;\n        struct\n        {\n            /* FSYNC, FSYNCDIR */\n            UINT64 fh;\n            UINT32 fsync_flags;\n            UINT32 padding;\n        } fsync;\n        struct\n        {\n            /* SETXATTR */\n            UINT32 size;\n            UINT32 flags;\n            CHAR name[];\n        } setxattr;\n        struct\n        {\n            /* GETXATTR */\n            UINT32 size;\n            UINT32 padding;\n            CHAR name[];\n        } getxattr;\n        struct\n        {\n            /* LISTXATTR */\n            UINT32 size;\n            UINT32 padding;\n        } listxattr;\n        struct\n        {\n            /* REMOVEXATTR */\n            CHAR name[];\n        } removexattr;\n        struct\n        {\n            /* FLUSH */\n            UINT64 fh;\n            UINT32 unused;\n            UINT32 padding;\n            UINT64 lock_owner;\n        } flush;\n        struct\n        {\n            /* INIT */\n            UINT32 major;\n            UINT32 minor;\n            UINT32 max_readahead;\n            UINT32 flags;\n        } init;\n        struct\n        {\n            /* GETLK, SETLK, SETLKW */\n            UINT64 fh;\n            UINT64 owner;\n            FUSE_PROTO_FILE_LOCK lk;\n            UINT32 lk_flags;\n            UINT32 padding;\n        } lk;\n        struct\n        {\n            /* ACCESS */\n            UINT32 mask;\n            UINT32 padding;\n        } access;\n        struct\n        {\n            /* CREATE */\n            UINT32 flags;\n            UINT32 mode;\n            UINT32 umask;\n            UINT32 padding;\n            CHAR name[];\n        } create;\n        struct\n        {\n            /* INTERRUPT */\n            UINT64 unique;\n        } interrupt;\n        struct\n        {\n            /* BMAP */\n            UINT64 block;\n            UINT32 blocksize;\n            UINT32 padding;\n        } bmap;\n        struct\n        {\n            /* IOCTL */\n            UINT64 fh;\n            UINT32 flags;\n            UINT32 cmd;\n            UINT64 arg;\n            UINT32 in_size;\n            UINT32 out_size;\n        } ioctl;\n        struct\n        {\n            /* POLL */\n            UINT64 fh;\n            UINT64 kh;\n            UINT32 flags;\n            UINT32 events;\n        } poll;\n        struct\n        {\n            /* NOTIFY_REPLY */\n            UINT64 dummy1;\n            UINT64 offset;\n            UINT32 size;\n            UINT32 dummy2;\n            UINT64 dummy3;\n            UINT64 dummy4;\n        } notify_reply;\n        struct\n        {\n            /* BATCH_FORGET */\n            UINT32 count;\n            UINT32 dummy;\n        } batch_forget;\n        struct\n        {\n            /* FALLOCATE */\n            UINT64 fh;\n            UINT64 offset;\n            UINT64 length;\n            UINT32 mode;\n            UINT32 padding;\n        } fallocate;\n        struct\n        {\n            /* RENAME2 */\n            UINT64 newdir;\n            UINT32 flags;\n            UINT32 padding;\n            CHAR name[]; /* 2 names */\n        } rename2;\n        struct\n        {\n            /* LSEEK */\n            UINT64 fh;\n            UINT64 offset;\n            UINT32 whence;\n            UINT32 padding;\n        } lseek;\n        struct\n        {\n            /* COPY_FILE_RANGE */\n            UINT64 fh_in;\n            UINT64 off_in;\n            UINT64 nodeid_out;\n            UINT64 fh_out;\n            UINT64 off_out;\n            UINT64 len;\n            UINT64 flags;\n        } copy_file_range;\n    } req;\n} FUSE_PROTO_REQ;\n#define FUSE_PROTO_REQ_HEADER_SIZE      ((ULONG)FIELD_OFFSET(FUSE_PROTO_REQ, req))\n#define FUSE_PROTO_REQ_SIZEMIN          8192 // FUSE_MIN_READ_BUFFER\n#define FUSE_PROTO_REQ_SIZE(F)          RTL_SIZEOF_THROUGH_FIELD(FUSE_PROTO_REQ, req.F)\n\ntypedef struct\n{\n    UINT32 len;\n    INT32 error;\n    UINT64 unique;\n    union\n    {\n        struct\n        {\n            /* LOOKUP */\n            FUSE_PROTO_ENTRY entry;\n        } lookup;\n        struct\n        {\n            /* GETATTR */\n            UINT64 attr_valid;\n            UINT32 attr_valid_nsec;\n            UINT32 dummy;\n            FUSE_PROTO_ATTR attr;\n        } getattr;\n        struct\n        {\n            /* SETATTR */\n            UINT64 attr_valid;\n            UINT32 attr_valid_nsec;\n            UINT32 dummy;\n            FUSE_PROTO_ATTR attr;\n        } setattr;\n        struct\n        {\n            /* SYMLINK */\n            FUSE_PROTO_ENTRY entry;\n        } symlink;\n        struct\n        {\n            /* MKNOD */\n            FUSE_PROTO_ENTRY entry;\n        } mknod;\n        struct\n        {\n            /* MKDIR */\n            FUSE_PROTO_ENTRY entry;\n        } mkdir;\n        struct\n        {\n            /* LINK */\n            FUSE_PROTO_ENTRY entry;\n        } link;\n        struct\n        {\n            /* OPEN, OPENDIR */\n            UINT64 fh;\n            UINT32 open_flags;\n            UINT32 padding;\n        } open;\n        struct\n        {\n            /* WRITE */\n            UINT32 size;\n            UINT32 padding;\n        } write;\n        struct\n        {\n            /* STATFS */\n            FUSE_PROTO_STATFS st;\n        } statfs;\n        struct\n        {\n            /* GETXATTR */\n            UINT32 size;\n            UINT32 padding;\n        } getxattr;\n        struct\n        {\n            /* LISTXATTR */\n            UINT32 size;\n            UINT32 padding;\n        } listxattr;\n        struct\n        {\n            /* INIT */\n            UINT32 major;\n            UINT32 minor;\n            UINT32 max_readahead;\n            UINT32 flags;\n            UINT16 max_background;\n            UINT16 congestion_threshold;\n            UINT32 max_write;\n            UINT32 time_gran;\n            UINT16 max_pages;\n            UINT16 padding;\n            UINT32 unused[8];\n        } init;\n        struct\n        {\n            /* GETLK */\n            FUSE_PROTO_FILE_LOCK lk;\n        } lk;\n        struct\n        {\n            /* CREATE */\n            FUSE_PROTO_ENTRY entry;\n            UINT64 fh;\n            UINT32 open_flags;\n            UINT32 padding;\n        } create;\n        struct\n        {\n            /* BMAP */\n            UINT64 block;\n        } bmap;\n        struct\n        {\n            /* IOCTL */\n            INT32 result;\n            UINT32 flags;\n            UINT32 in_iovs;\n            UINT32 out_iovs;\n        } ioctl;\n        struct\n        {\n            /* POLL */\n            UINT32 revents;\n            UINT32 padding;\n        } poll;\n        struct\n        {\n            /* LSEEK */\n            UINT64 offset;\n        } lseek;\n        struct\n        {\n            /* COPY_FILE_RANGE */\n            UINT32 size;\n            UINT32 padding;\n        } copy_file_range;\n        /* notify */\n        struct\n        {\n            /* NOTIFY_POLL */\n            UINT64 kh;\n        } notify_poll;\n        struct\n        {\n            /* NOTIFY_INVAL_INODE */\n            UINT64 ino;\n            INT64 off;\n            INT64 len;\n        } notify_inval_inode;\n        struct\n        {\n            /* NOTIFY_INVAL_ENTRY */\n            UINT64 parent;\n            UINT32 namelen;\n            UINT32 padding;\n        } notify_inval_entry;\n        struct\n        {\n            /* NOTIFY_STORE */\n            UINT64 nodeid;\n            UINT64 offset;\n            UINT32 size;\n            UINT32 padding;\n        } notify_store;\n        struct\n        {\n            /* NOTIFY_RETRIEVE */\n            UINT64 notify_unique;\n            UINT64 nodeid;\n            UINT64 offset;\n            UINT32 size;\n            UINT32 padding;\n        } notify_retrieve;\n        struct\n        {\n            /* NOTIFY_DELETE */\n            UINT64 parent;\n            UINT64 child;\n            UINT32 namelen;\n            UINT32 padding;\n        } notify_delete;\n    } rsp;\n} FUSE_PROTO_RSP;\n#define FUSE_PROTO_RSP_HEADER_SIZE      ((ULONG)FIELD_OFFSET(FUSE_PROTO_RSP, rsp))\n#define FUSE_PROTO_RSP_SIZE(F)          RTL_SIZEOF_THROUGH_FIELD(FUSE_PROTO_RSP, rsp.F)\n\n#endif\n"
  },
  {
    "path": "src/shared/km/shared.h",
    "content": "/**\n * @file shared/km/shared.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#ifndef SHARED_KM_SHARED_H_INCLUDED\n#define SHARED_KM_SHARED_H_INCLUDED\n\n#include <ntifs.h>\n#include <winfsp/fsext.h>\n\n/* disable warnings */\n#pragma warning(disable:4100)           /* unreferenced formal parameter */\n#pragma warning(disable:4127)           /* conditional expression is constant */\n#pragma warning(disable:4200)           /* zero-sized array in struct/union */\n#pragma warning(disable:4201)           /* nameless struct/union */\n\n#include <shared/km/coro.h>\n#include <shared/km/proto.h>\n\n/* debug */\n#if DBG\nenum\n{\n    fuse_debug_dt                       = 0x01000000,   /* DEBUGTEST switch */\n    fuse_debug_dp                       = 0x10000000,   /* DbgPrint switch */\n};\nextern __declspec(selectany) int fuse_debug = fuse_debug_dt;\nULONG DebugRandom(VOID);\nBOOLEAN DebugMemory(PVOID Memory, SIZE_T Size, BOOLEAN Test);\nVOID FuseDebugLogRequest(FUSE_PROTO_REQ *Request);\nVOID FuseDebugLogResponse(FUSE_PROTO_RSP *Response);\n#endif\n\n/* DbgPrint */\n#if DBG\n#define DbgPrint(...)                   \\\n    ((void)((fuse_debug & fuse_debug_dp) ? DbgPrint(__VA_ARGS__) : 0))\n#endif\n\n/* debug tools */\n#if DBG\n#define DEBUGLOG(fmt, ...)              \\\n    DbgPrint(\"[%d] FUSE!\" __FUNCTION__ \": \" fmt \"\\n\", KeGetCurrentIrql(), __VA_ARGS__)\n#define DEBUGTEST(Percent)              \\\n    (0 == (fuse_debug & fuse_debug_dt) || DebugRandom() <= (Percent) * 0x7fff / 100)\n#define DEBUGFILL(M, S)                 DebugMemory(M, S, FALSE)\n#define DEBUGGOOD(M, S)                 DebugMemory(M, S, TRUE)\n#else\n#define DEBUGLOG(fmt, ...)              ((void)0)\n#define DEBUGTEST(Percent)              (TRUE)\n#define DEBUGFILL(M, S)                 (TRUE)\n#define DEBUGGOOD(M, S)                 (TRUE)\n#endif\n\n/* memory allocation */\n#define FUSE_ALLOC_TAG                  'ESUF'\n#define FuseAlloc(Size)                 ExAllocatePoolWithTag(PagedPool, Size, FUSE_ALLOC_TAG)\n#define FuseAllocNonPaged(Size)         ExAllocatePoolWithTag(NonPagedPool, Size, FUSE_ALLOC_TAG)\n#define FuseAllocMustSucceed(Size)      FuseAllocatePoolMustSucceed(PagedPool, Size, FUSE_ALLOC_TAG)\n#define FuseFree(Pointer)               ExFreePoolWithTag(Pointer, FUSE_ALLOC_TAG)\n#define FuseFreeExternal(Pointer)       ExFreePool(Pointer)\n\n/* hash mix */\n/* Based on the MurmurHash3 fmix32/fmix64 function:\n * See: https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp?r=152#68\n */\nstatic inline\nUINT32 FuseHashMix32(UINT32 h)\n{\n    h ^= h >> 16;\n    h *= 0x85ebca6b;\n    h ^= h >> 13;\n    h *= 0xc2b2ae35;\n    h ^= h >> 16;\n    return h;\n}\nstatic inline\nUINT64 FuseHashMix64(UINT64 k)\n{\n    k ^= k >> 33;\n    k *= 0xff51afd7ed558ccdULL;\n    k ^= k >> 33;\n    k *= 0xc4ceb9fe1a85ec53ULL;\n    k ^= k >> 33;\n    return k;\n}\nstatic inline\nULONG FuseHashMixPointer(PVOID Pointer)\n{\n#if _WIN64\n    return (ULONG)FuseHashMix64((UINT64)Pointer);\n#else\n    return (ULONG)FuseHashMix32((UINT32)Pointer);\n#endif\n}\n\n/* POSIX paths */\nVOID FusePosixPathPrefix(PSTRING Path, PSTRING Prefix, PSTRING Remain);\nVOID FusePosixPathSuffix(PSTRING Path, PSTRING Remain, PSTRING Suffix);\n\n/* utility */\nPVOID FuseAllocatePoolMustSucceed(POOL_TYPE PoolType, SIZE_T Size, ULONG Tag);\nNTSTATUS FuseSafeCopyMemory(PVOID Dst, PVOID Src, ULONG Len);\nNTSTATUS FuseGetTokenUid(PACCESS_TOKEN Token, TOKEN_INFORMATION_CLASS InfoClass, PUINT32 PUid);\n\n/* read/write locks */\n#define FUSE_RWLOCK_USE_SEMAPHORE\n//#define FUSE_RWLOCK_USE_ERESOURCE\ntypedef struct _FUSE_RWLOCK\n{\n#if defined(FUSE_RWLOCK_USE_SEMAPHORE)\n    KSEMAPHORE OrderSem;\n    KSEMAPHORE WriteSem;\n    LONG Readers;\n#elif defined(FUSE_RWLOCK_USE_ERESOURCE)\n    ERESOURCE Resource;\n#else\n#error One of FUSE_RWLOCK_USE_SEMAPHORE or FUSE_RWLOCK_USE_ERESOURCE must be defined.\n#endif\n} FUSE_RWLOCK;\nstatic inline\nVOID FuseRwlockInitialize(FUSE_RWLOCK *Lock)\n{\n#if defined(FUSE_RWLOCK_USE_SEMAPHORE)\n    KeInitializeSemaphore(&Lock->OrderSem, 1, 1);\n    KeInitializeSemaphore(&Lock->WriteSem, 1, 1);\n    Lock->Readers = 0;\n#elif defined(FUSE_RWLOCK_USE_ERESOURCE)\n    ExInitializeResourceLite(&Lock->Resource);\n#endif\n}\nstatic inline\nVOID FuseRwlockFinalize(FUSE_RWLOCK *Lock)\n{\n#if defined(FUSE_RWLOCK_USE_SEMAPHORE)\n#elif defined(FUSE_RWLOCK_USE_ERESOURCE)\n    ExDeleteResourceLite(&Lock->Resource);\n#endif\n}\nstatic inline\nBOOLEAN FuseRwlockEnterWriter(FUSE_RWLOCK *Lock, PVOID Owner)\n{\n#if defined(FUSE_RWLOCK_USE_SEMAPHORE)\n    NTSTATUS Result;\n    Result = FsRtlCancellableWaitForSingleObject(&Lock->OrderSem, 0, 0);\n    if (STATUS_SUCCESS == Result)\n    {\n        Result = FsRtlCancellableWaitForSingleObject(&Lock->WriteSem, 0, 0);\n        KeReleaseSemaphore(&Lock->OrderSem, 1, 1, FALSE);\n    }\n    return STATUS_SUCCESS == Result;\n#elif defined(FUSE_RWLOCK_USE_ERESOURCE)\n    ExAcquireResourceExclusiveLite(&Lock->Resource, TRUE);\n    ExSetResourceOwnerPointer(&Lock->Resource, (PVOID)((UINT_PTR)Owner | 3));\n    return TRUE;\n#endif\n}\nstatic inline\nBOOLEAN FuseRwlockEnterReader(FUSE_RWLOCK *Lock, PVOID Owner)\n{\n#if defined(FUSE_RWLOCK_USE_SEMAPHORE)\n    NTSTATUS Result;\n    Result = FsRtlCancellableWaitForSingleObject(&Lock->OrderSem, 0, 0);\n    if (STATUS_SUCCESS == Result)\n    {\n        if (1 == InterlockedIncrement(&Lock->Readers))\n        {\n            Result = FsRtlCancellableWaitForSingleObject(&Lock->WriteSem, 0, 0);\n            if (STATUS_SUCCESS != Result)\n                InterlockedDecrement(&Lock->Readers);\n        }\n        KeReleaseSemaphore(&Lock->OrderSem, 1, 1, FALSE);\n    }\n    return STATUS_SUCCESS == Result;\n#elif defined(FUSE_RWLOCK_USE_ERESOURCE)\n    ExAcquireResourceSharedLite(&Lock->Resource, TRUE);\n    ExSetResourceOwnerPointer(&Lock->Resource, (PVOID)((UINT_PTR)Owner | 3));\n    return TRUE;\n#endif\n}\nstatic inline\nVOID FuseRwlockLeaveWriter(FUSE_RWLOCK *Lock, PVOID Owner)\n{\n#if defined(FUSE_RWLOCK_USE_SEMAPHORE)\n    KeReleaseSemaphore(&Lock->WriteSem, 1, 1, FALSE);\n#elif defined(FUSE_RWLOCK_USE_ERESOURCE)\n    ExReleaseResourceForThreadLite(&Lock->Resource, (ERESOURCE_THREAD)((UINT_PTR)Owner | 3));\n#endif\n}\nstatic inline\nVOID FuseRwlockLeaveReader(FUSE_RWLOCK *Lock, PVOID Owner)\n{\n#if defined(FUSE_RWLOCK_USE_SEMAPHORE)\n    if (0 == InterlockedDecrement(&Lock->Readers))\n        KeReleaseSemaphore(&Lock->WriteSem, 1, 1, FALSE);\n#elif defined(FUSE_RWLOCK_USE_ERESOURCE)\n    ExReleaseResourceForThreadLite(&Lock->Resource, (ERESOURCE_THREAD)((UINT_PTR)Owner | 3));\n#endif\n}\n\n/* FUSE instances */\ntypedef struct _FUSE_IOQ FUSE_IOQ;\ntypedef struct _FUSE_CACHE FUSE_CACHE;\ntypedef enum _FUSE_INSTANCE_TYPE\n{\n    FuseInstanceWindows = 'W',\n    FuseInstanceCygwin = 'C',\n    FuseInstanceLinux = 'L',\n} FUSE_INSTANCE_TYPE;\ntypedef struct _FUSE_INSTANCE\n{\n    FSP_FSCTL_VOLUME_PARAMS *VolumeParams;\n    FUSE_INSTANCE_TYPE InstanceType;\n    FUSE_RWLOCK OpGuardLock;\n    FUSE_IOQ *Ioq;\n    FUSE_CACHE *Cache;\n    KSPIN_LOCK FileListLock;\n    LIST_ENTRY FileList;\n    KEVENT InitEvent;\n    UINT32 VersionMajor, VersionMinor;\n    VOID (*ProtoSendDestroyHandler)(PVOID); PVOID ProtoSendDestroyData;\n    /*\n     * The following bitmap is used to remember which opcodes have returned ENOSYS.\n     *\n     * It is assumed that an opcode that returned ENOSYS once, will continue returning\n     * ENOSYS in the future. Thus an expensive message to user space can be eliminated.\n     *\n     * This bitmap may be accessed from multiple threads without locking. This is\n     * because the bitmap is used for optimization purposes ONLY, and it is ok for\n     * extraneous requests (that will result in ENOSYS) to be sent to the user mode\n     * file system.\n     */\n    UINT32 OpcodeENOSYS[2];\n} FUSE_INSTANCE;\nNTSTATUS FuseInstanceInit(FUSE_INSTANCE *Instance,\n    FSP_FSCTL_VOLUME_PARAMS *VolumeParams,\n    FUSE_INSTANCE_TYPE InstanceType);\nVOID FuseInstanceFini(FUSE_INSTANCE *Instance);\nVOID FuseInstanceExpirationRoutine(FUSE_INSTANCE *Instance, UINT64 ExpirationTime);\nNTSTATUS FuseInstanceTransact(FUSE_INSTANCE *Instance,\n    FUSE_PROTO_RSP *FuseResponse, ULONG InputBufferLength,\n    FUSE_PROTO_REQ *FuseRequest, PULONG POutputBufferLength,\n    PDEVICE_OBJECT DeviceObject, PFILE_OBJECT FileObject,\n    PIRP CancellableIrp);\nstatic inline\nBOOLEAN FuseInstanceGetOpcodeENOSYS(FUSE_INSTANCE *Instance, UINT32 Opcode)\n{\n    ASSERT(sizeof Instance->OpcodeENOSYS / sizeof Instance->OpcodeENOSYS[0] > (Opcode >> 5));\n    ASSERT(8 * sizeof Instance->OpcodeENOSYS[0] > (Opcode & 0x1f));\n    return !!(Instance->OpcodeENOSYS[Opcode >> 5] & (1 << (Opcode & 0x1f)));\n}\nstatic inline\nVOID FuseInstanceSetOpcodeENOSYS(FUSE_INSTANCE *Instance, UINT32 Opcode)\n{\n    ASSERT(sizeof Instance->OpcodeENOSYS / sizeof Instance->OpcodeENOSYS[0] > (Opcode >> 5));\n    ASSERT(8 * sizeof Instance->OpcodeENOSYS[0] > (Opcode & 0x1f));\n    Instance->OpcodeENOSYS[Opcode >> 5] |= (1 << (Opcode & 0x1f));\n}\n\n/* FUSE files */\ntypedef struct _FUSE_FILE\n{\n    LIST_ENTRY ListEntry;\n    UINT64 Ino;\n    UINT64 Fh;\n    UINT32 OpenFlags;\n    UINT32 IsDirectory:1;\n    UINT32 IsReparsePoint:1;\n    PVOID CacheItem;\n} FUSE_FILE;\nVOID FuseFileInstanceInit(FUSE_INSTANCE *Instance);\nVOID FuseFileInstanceFini(FUSE_INSTANCE *Instance);\nNTSTATUS FuseFileCreate(FUSE_INSTANCE *Instance, FUSE_FILE **PFile);\nVOID FuseFileDelete(FUSE_INSTANCE *Instance, FUSE_FILE *File);\n\n/* FUSE processing context */\ntypedef struct _FUSE_CONTEXT FUSE_CONTEXT;\ntypedef VOID FUSE_CONTEXT_FINI(FUSE_CONTEXT *Context);\ntypedef BOOLEAN FUSE_OPERATION_PROC(FUSE_CONTEXT *Context);\ntypedef INT FUSE_OPERATION_GUARD(FUSE_CONTEXT *Context, BOOLEAN Acquire);\nenum\n{\n    FuseOpGuardCancel = -1,\n    FuseOpGuardFalse = 0,\n    FuseOpGuardTrue = 1,\n};\ntypedef struct _FUSE_OPERATION\n{\n    FUSE_OPERATION_PROC *Proc;\n    FUSE_OPERATION_GUARD *Guard;\n} FUSE_OPERATION;\ntypedef struct _FUSE_CONTEXT_LOOKUP\n{\n    PVOID CacheGen;\n    PVOID CacheItem;\n    UINT64 Ino;\n    STRING Name;\n    FUSE_PROTO_ATTR Attr;\n} FUSE_CONTEXT_LOOKUP;\ntypedef struct _FUSE_CONTEXT_FORGET\n{\n    LIST_ENTRY ForgetList;\n} FUSE_CONTEXT_FORGET;\ntypedef struct _FUSE_CONTEXT_SETATTR\n{\n    FUSE_PROTO_ATTR Attr;\n    UINT32 AttrValid;\n} FUSE_CONTEXT_SETATTR;\nstruct _FUSE_CONTEXT\n{\n    FUSE_CONTEXT *DictNext;\n    LIST_ENTRY ListEntry;\n    FUSE_CONTEXT_FINI *Fini;\n    FUSE_INSTANCE *Instance;\n    FSP_FSCTL_TRANSACT_REQ *InternalRequest;\n    FSP_FSCTL_TRANSACT_RSP *InternalResponse;\n    FSP_FSCTL_DECLSPEC_ALIGN UINT8 InternalResponseBuf[sizeof(FSP_FSCTL_TRANSACT_RSP)];\n    FUSE_PROTO_REQ *FuseRequest;\n    FUSE_PROTO_RSP *FuseResponse;\n    ULONG FuseRequestLength;\n#if DBG\n    UINT32 DebugLogOpcode;\n#endif\n    INT OpGuardResult;\n    SHORT CoroState[16];\n    UINT32 OrigUid, OrigGid, OrigPid;\n    FUSE_FILE *File;\n    union\n    {\n        FUSE_CONTEXT_LOOKUP Lookup;\n        FUSE_CONTEXT_FORGET Forget;\n        struct\n        {\n            FUSE_CONTEXT_LOOKUP;\n            STRING OrigPath;\n            STRING Remain;\n            UINT32 DesiredAccess, GrantedAccess;\n            UINT32 UserMode:1;\n            UINT32 HasTraversePrivilege:1;\n            UINT32 DisableCache:1;\n            UINT32 Chown:1;\n            UINT32 RenameIsNonExistent:1;\n            UINT32 RenameIsDirectory:1;\n            /* 2 path operations (rename) */\n            STRING OrigPath2;\n            STRING Name2;\n            UINT64 Ino2;\n        } LookupPath;\n        FUSE_CONTEXT_SETATTR Setattr;\n        struct\n        {\n            FUSE_PROTO_ATTR Attr;\n            UINT64 StartOffset;\n            UINT32 Remain;\n            UINT32 Offset;\n            UINT32 Length;\n        } Read, Write;\n        struct\n        {\n            FUSE_CONTEXT_LOOKUP;\n            STRING OrigName;\n            UINT64 NextOffset;\n            UINT32 Length;\n            ULONG BytesTransferred;\n            PUINT8 Buffer, BufferEndP, BufferP;\n        } QueryDirectory;\n        struct\n        {\n            FUSE_CONTEXT_SETATTR;\n            PSECURITY_DESCRIPTOR SecurityDescriptor;\n        } Security;\n    };\n};\nextern FUSE_OPERATION FuseOperations[];\nVOID FuseContextCreate(FUSE_CONTEXT **PContext,\n    FUSE_INSTANCE *Instance, FSP_FSCTL_TRANSACT_REQ *InternalRequest);\nVOID FuseContextDelete(FUSE_CONTEXT *Context);\nstatic inline BOOLEAN FuseContextProcess(FUSE_CONTEXT *Context,\n    FUSE_PROTO_RSP *FuseResponse, FUSE_PROTO_REQ *FuseRequest, ULONG FuseRequestLength)\n{\n    ASSERT(0 == FuseRequest || 0 == FuseResponse);\n    ASSERT(0 != FuseRequest || 0 != FuseResponse);\n\n    UINT32 Kind = 0 == Context->InternalRequest ?\n        FspFsctlTransactReservedKind : Context->InternalRequest->Kind;\n\n    if (0 == Context->FuseRequest && 0 == Context->FuseResponse &&\n        0 != FuseOperations[Kind].Guard)\n    {\n        ASSERT(FuseOpGuardFalse == Context->OpGuardResult);\n        Context->OpGuardResult = FuseOperations[Kind].Guard(Context, TRUE);\n        if (FuseOpGuardCancel == Context->OpGuardResult)\n        {\n            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_CANCELLED;\n            return FALSE;\n        }\n    }\n\n    Context->FuseRequest = FuseRequest;\n    Context->FuseResponse = FuseResponse;\n    Context->FuseRequestLength = FuseRequestLength;\n\n    BOOLEAN Result = FuseOperations[Kind].Proc(Context);\n\n    if (!Result && FuseOpGuardTrue == Context->OpGuardResult)\n    {\n        FuseOperations[Kind].Guard(Context, FALSE);\n        Context->OpGuardResult = FuseOpGuardFalse;\n    }\n\n    return Result;\n}\nstatic inline\nINT FuseOpGuardResult_(BOOLEAN RwlockResult)\n{\n    ASSERT(\n        ( RwlockResult && FuseOpGuardTrue   == (((INT)RwlockResult - 1) | 1)) ||\n        (!RwlockResult && FuseOpGuardCancel == (((INT)RwlockResult - 1) | 1)));\n    return ((INT)RwlockResult - 1) | 1;\n}\nstatic inline\nINT FuseOpGuardAcquireExclusive(FUSE_CONTEXT *Context)\n{\n    return FuseOpGuardResult_(FuseRwlockEnterWriter(&Context->Instance->OpGuardLock, Context));\n}\nstatic inline\nINT FuseOpGuardAcquireShared(FUSE_CONTEXT *Context)\n{\n    return FuseOpGuardResult_(FuseRwlockEnterReader(&Context->Instance->OpGuardLock, Context));\n}\nstatic inline\nINT FuseOpGuardReleaseExclusive(FUSE_CONTEXT *Context)\n{\n    FuseRwlockLeaveWriter(&Context->Instance->OpGuardLock, Context);\n    return FuseOpGuardFalse;\n}\nstatic inline\nINT FuseOpGuardReleaseShared(FUSE_CONTEXT *Context)\n{\n    FuseRwlockLeaveReader(&Context->Instance->OpGuardLock, Context);\n    return FuseOpGuardFalse;\n}\n#define FuseContextStatus(S)            \\\n    (                                   \\\n        ASSERT(0xC0000000 == ((UINT32)(S) & 0xFFFF0000)),\\\n        (FUSE_CONTEXT *)(UINT_PTR)((UINT32)(S) & 0x0000FFFF)\\\n    )\n#define FuseContextIsStatus(C)          ((UINT_PTR)0x0000FFFF >= (UINT_PTR)(C))\n#define FuseContextToStatus(C)          ((NTSTATUS)(0xC0000000 | (UINT32)(UINT_PTR)(C)))\n#define FuseContextWaitRequest(C)       do { while (0 == (C)->FuseRequest) coro_yield; } while (0,0)\n#define FuseContextWaitResponse(C)      do { coro_yield; } while (0 == (C)->FuseResponse)\n\n/* FUSE I/O queue */\nNTSTATUS FuseIoqCreate(FUSE_IOQ **PIoq);\nVOID FuseIoqDelete(FUSE_IOQ *Ioq);\nVOID FuseIoqStartProcessing(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context);\nFUSE_CONTEXT *FuseIoqEndProcessing(FUSE_IOQ *Ioq, UINT64 Unique);\nVOID FuseIoqPostPending(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context);\nVOID FuseIoqPostPendingAndStop(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context);\nFUSE_CONTEXT *FuseIoqNextPending(FUSE_IOQ *Ioq); /* does not block! */\n\n/* FUSE \"entry\" cache */\ntypedef struct _FUSE_CACHE_GEN FUSE_CACHE_GEN;\nNTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_CACHE **PCache);\nVOID FuseCacheDelete(FUSE_CACHE *Cache);\nVOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache,\n    FUSE_INSTANCE *Instance, UINT64 ExpirationTime);\nNTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen);\nVOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen);\nBOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,\n    FUSE_PROTO_ENTRY *Entry, PVOID *PItem);\nVOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,\n    FUSE_PROTO_ENTRY *Entry, PVOID *PItem);\nVOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name);\nVOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item);\nVOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item);\nVOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item);\nVOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList);\nBOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE *PForgetOne);\n\n/* protocol implementation */\nNTSTATUS FuseProtoPostInit(FUSE_INSTANCE *Instance);\nVOID FuseProtoSendInit(FUSE_CONTEXT *Context);\nNTSTATUS FuseProtoPostDestroy(FUSE_INSTANCE *Instance);\nVOID FuseProtoSendDestroy(FUSE_CONTEXT *Context);\nVOID FuseProtoSendLookup(FUSE_CONTEXT *Context);\nNTSTATUS FuseProtoPostForget(FUSE_INSTANCE *Instance, PLIST_ENTRY ForgetList);\nVOID FuseProtoFillForget(FUSE_CONTEXT *Context);\nVOID FuseProtoFillBatchForget(FUSE_CONTEXT *Context);\nVOID FuseProtoSendStatfs(FUSE_CONTEXT *Context);\nVOID FuseProtoSendGetattr(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFgetattr(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFtruncate(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFutimens(FUSE_CONTEXT *Context);\nVOID FuseProtoSendLookupChown(FUSE_CONTEXT *Context);\nVOID FuseProtoSendSetattr(FUSE_CONTEXT *Context);\nVOID FuseProtoSendMkdir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendMknod(FUSE_CONTEXT *Context);\nVOID FuseProtoSendRmdir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendUnlink(FUSE_CONTEXT *Context);\nVOID FuseProtoSendRename(FUSE_CONTEXT *Context);\nVOID FuseProtoSendCreate(FUSE_CONTEXT *Context);\nVOID FuseProtoSendOpendir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendOpen(FUSE_CONTEXT *Context);\nVOID FuseProtoSendReleasedir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendRelease(FUSE_CONTEXT *Context);\nVOID FuseProtoSendReaddir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendRead(FUSE_CONTEXT *Context);\nVOID FuseProtoSendWrite(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFsyncdir(FUSE_CONTEXT *Context);\nVOID FuseProtoSendFsync(FUSE_CONTEXT *Context);\nVOID FuseAttrToFileInfo(FUSE_INSTANCE *Instance,\n    FUSE_PROTO_ATTR *Attr, FSP_FSCTL_FILE_INFO *FileInfo);\nstatic inline\nVOID FuseFileTimeToUnixTime(UINT64 FileTime0, PUINT64 sec, PUINT32 nsec)\n{\n    INT64 FileTime = (INT64)FileTime0 - 116444736000000000LL;\n    INT32 Remain = FileTime % 10000000;\n    *sec = (UINT64)(FileTime / 10000000);\n    *nsec = (UINT32)(0 <= Remain ? Remain : Remain + 10000000) * 100;\n}\nstatic inline\nVOID FuseUnixTimeToFileTime(UINT64 sec, UINT32 nsec, PUINT64 PFileTime)\n{\n    INT64 FileTime = (INT64)sec * 10000000 + (INT64)nsec / 100 + 116444736000000000LL;\n    *PFileTime = FileTime;\n}\nNTSTATUS FuseNtStatusFromErrno(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno);\n\n#endif\n"
  },
  {
    "path": "src/shared/km/util.c",
    "content": "/**\n * @file shared/km/util.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <shared/km/shared.h>\n\nPVOID FuseAllocatePoolMustSucceed(POOL_TYPE PoolType, SIZE_T Size, ULONG Tag);\nNTSTATUS FuseSafeCopyMemory(PVOID Dst, PVOID Src, ULONG Len);\nNTSTATUS FuseGetTokenUid(PACCESS_TOKEN Token, TOKEN_INFORMATION_CLASS InfoClass, PUINT32 PUid);\n\n#ifdef ALLOC_PRAGMA\n// !#pragma alloc_text(PAGE, FuseAllocatePoolMustSucceed)\n#pragma alloc_text(PAGE, FuseSafeCopyMemory)\n#pragma alloc_text(PAGE, FuseGetTokenUid)\n#endif\n\nstatic const LONG Delays[] =\n{\n     10/*ms*/ * -10000,\n     10/*ms*/ * -10000,\n     50/*ms*/ * -10000,\n     50/*ms*/ * -10000,\n    100/*ms*/ * -10000,\n    100/*ms*/ * -10000,\n    300/*ms*/ * -10000,\n};\n\nPVOID FuseAllocatePoolMustSucceed(POOL_TYPE PoolType, SIZE_T Size, ULONG Tag)\n{\n    // !PAGED_CODE();\n\n    PVOID Result;\n    LARGE_INTEGER Delay;\n\n    for (ULONG i = 0, n = sizeof(Delays) / sizeof(Delays[0]);; i++)\n    {\n        Result = DEBUGTEST(99) ? ExAllocatePoolWithTag(PoolType, Size, Tag) : 0;\n        if (0 != Result)\n            return Result;\n\n        Delay.QuadPart = n > i ? Delays[i] : Delays[n - 1];\n        KeDelayExecutionThread(KernelMode, FALSE, &Delay);\n    }\n}\n\nNTSTATUS FuseSafeCopyMemory(PVOID Dst, PVOID Src, ULONG Len)\n{\n    PAGED_CODE();\n\n    try\n    {\n        RtlCopyMemory(Dst, Src, Len);\n        return STATUS_SUCCESS;\n    }\n    except (EXCEPTION_EXECUTE_HANDLER)\n    {\n        NTSTATUS Result = GetExceptionCode();\n        return FsRtlIsNtstatusExpected(Result) ? STATUS_INVALID_USER_BUFFER : Result;\n    }\n}\n\nNTSTATUS FuseGetTokenUid(PACCESS_TOKEN Token, TOKEN_INFORMATION_CLASS InfoClass, PUINT32 PUid)\n{\n    PAGED_CODE();\n\n    NTSTATUS Result;\n    PVOID Info = 0;\n    PSID *PSid;\n\n    Result = SeQueryInformationToken(Token, InfoClass, &Info);\n    if (!NT_SUCCESS(Result))\n        goto exit;\n\n    switch (InfoClass)\n    {\n    case TokenUser:\n        PSid = &((PTOKEN_USER)Info)->User.Sid;\n        break;\n    case TokenOwner:\n        PSid = &((PTOKEN_OWNER)Info)->Owner;\n        break;\n    case TokenPrimaryGroup:\n        PSid = &((PTOKEN_PRIMARY_GROUP)Info)->PrimaryGroup;\n        break;\n    default:\n        ASSERT(0);\n        Result = STATUS_INVALID_PARAMETER;\n        goto exit;\n    }\n\n    Result = FspPosixMapSidToUid(*PSid, PUid);\n\nexit:\n    if (0 != Info)\n        FuseFreeExternal(Info);\n\n    return Result;\n}\n"
  },
  {
    "path": "src/shared/ku/wslfuse.h",
    "content": "/**\n * @file shared/ku/wslfuse.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#ifndef SHARED_KU_WSLFUSE_H_INCLUDED\n#define SHARED_KU_WSLFUSE_H_INCLUDED\n\n#if defined(__linux__)\n/*\n * We duplicate some of the definitions from WinFsp and WinFuse\n * to avoid having either of them as a build dependency when\n * building on Linux.\n */\n\n#include <stdint.h>\n#include <wchar.h>\n#include <linux/ioctl.h>\ntypedef char CHAR;\ntypedef uint16_t WCHAR;\ntypedef uint8_t UINT8;\ntypedef uint16_t UINT16;\ntypedef uint32_t UINT32;\ntypedef uint64_t UINT64;\n\n#define FSP_FSCTL_DISK_DEVICE_NAME      \"WinFsp.Disk\"\n#define FSP_FSCTL_NET_DEVICE_NAME       \"WinFsp.Net\"\n#define FSP_FSCTL_VOLUME_NAME_SIZE      (64 * sizeof(WCHAR))\n#define FSP_FSCTL_VOLUME_PREFIX_SIZE    (192 * sizeof(WCHAR))\n#define FSP_FSCTL_VOLUME_FSNAME_SIZE    (16 * sizeof(WCHAR))\n#define FSP_FSCTL_VOLUME_NAME_SIZEMAX   (FSP_FSCTL_VOLUME_NAME_SIZE + FSP_FSCTL_VOLUME_PREFIX_SIZE)\n#define FSP_FSCTL_VOLUME_PARAMS_V0_FIELD_DEFN\\\n    UINT16 Version;                     /* set to 0 or sizeof(FSP_FSCTL_VOLUME_PARAMS) */\\\n    /* volume information */\\\n    UINT16 SectorSize;\\\n    UINT16 SectorsPerAllocationUnit;\\\n    UINT16 MaxComponentLength;          /* maximum file name component length (bytes) */\\\n    UINT64 VolumeCreationTime;\\\n    UINT32 VolumeSerialNumber;\\\n    /* I/O timeouts, capacity, etc. */\\\n    UINT32 TransactTimeout;             /* DEPRECATED: (millis; 1 sec - 10 sec) */\\\n    UINT32 IrpTimeout;                  /* pending IRP timeout (millis; 1 min - 10 min) */\\\n    UINT32 IrpCapacity;                 /* maximum number of pending IRP's (100 - 1000)*/\\\n    UINT32 FileInfoTimeout;             /* FileInfo/Security/VolumeInfo timeout (millis) */\\\n    /* FILE_FS_ATTRIBUTE_INFORMATION::FileSystemAttributes */\\\n    UINT32 CaseSensitiveSearch:1;       /* file system supports case-sensitive file names */\\\n    UINT32 CasePreservedNames:1;        /* file system preserves the case of file names */\\\n    UINT32 UnicodeOnDisk:1;             /* file system supports Unicode in file names */\\\n    UINT32 PersistentAcls:1;            /* file system preserves and enforces access control lists */\\\n    UINT32 ReparsePoints:1;             /* file system supports reparse points */\\\n    UINT32 ReparsePointsAccessCheck:1;  /* file system performs reparse point access checks */\\\n    UINT32 NamedStreams:1;              /* file system supports named streams */\\\n    UINT32 HardLinks:1;                 /* unimplemented; set to 0 */\\\n    UINT32 ExtendedAttributes:1;        /* file system supports extended attributes */\\\n    UINT32 ReadOnlyVolume:1;\\\n    /* kernel-mode flags */\\\n    UINT32 PostCleanupWhenModifiedOnly:1;   /* post Cleanup when a file was modified/deleted */\\\n    UINT32 PassQueryDirectoryPattern:1;     /* pass Pattern during QueryDirectory operations */\\\n    UINT32 AlwaysUseDoubleBuffering:1;\\\n    UINT32 PassQueryDirectoryFileName:1;    /* pass FileName during QueryDirectory (GetDirInfoByName) */\\\n    UINT32 FlushAndPurgeOnCleanup:1;        /* keeps file off \"standby\" list */\\\n    UINT32 DeviceControl:1;                 /* support user-mode ioctl handling */\\\n    /* user-mode flags */\\\n    UINT32 UmFileContextIsUserContext2:1;   /* user mode: FileContext parameter is UserContext2 */\\\n    UINT32 UmFileContextIsFullContext:1;    /* user mode: FileContext parameter is FullContext */\\\n    UINT32 UmReservedFlags:6;\\\n    /* additional kernel-mode flags */\\\n    UINT32 AllowOpenInKernelMode:1;         /* allow kernel mode to open files when possible */\\\n    UINT32 CasePreservedExtendedAttributes:1;   /* preserve case of EA (default is UPPERCASE) */\\\n    UINT32 WslFeatures:1;                   /* support features required for WSLinux */\\\n    UINT32 KmReservedFlags:5;\\\n    WCHAR Prefix[FSP_FSCTL_VOLUME_PREFIX_SIZE / sizeof(WCHAR)]; /* UNC prefix (\\Server\\Share) */\\\n    WCHAR FileSystemName[FSP_FSCTL_VOLUME_FSNAME_SIZE / sizeof(WCHAR)];\n#define FSP_FSCTL_VOLUME_PARAMS_V1_FIELD_DEFN\\\n    /* additional fields; specify .Version == sizeof(FSP_FSCTL_VOLUME_PARAMS) */\\\n    UINT32 VolumeInfoTimeoutValid:1;    /* VolumeInfoTimeout field is valid */\\\n    UINT32 DirInfoTimeoutValid:1;       /* DirInfoTimeout field is valid */\\\n    UINT32 SecurityTimeoutValid:1;      /* SecurityTimeout field is valid*/\\\n    UINT32 StreamInfoTimeoutValid:1;    /* StreamInfoTimeout field is valid */\\\n    UINT32 EaTimeoutValid:1;            /* EaTimeout field is valid */\\\n    UINT32 KmAdditionalReservedFlags:27;\\\n    UINT32 VolumeInfoTimeout;           /* volume info timeout (millis); overrides FileInfoTimeout */\\\n    UINT32 DirInfoTimeout;              /* dir info timeout (millis); overrides FileInfoTimeout */\\\n    UINT32 SecurityTimeout;             /* security info timeout (millis); overrides FileInfoTimeout */\\\n    UINT32 StreamInfoTimeout;           /* stream info timeout (millis); overrides FileInfoTimeout */\\\n    UINT32 EaTimeout;                   /* EA timeout (millis); overrides FileInfoTimeout */\\\n    UINT32 FsextControlCode;\\\n    UINT32 Reserved32[1];\\\n    UINT64 Reserved64[2];\ntypedef struct\n{\n    FSP_FSCTL_VOLUME_PARAMS_V0_FIELD_DEFN\n    FSP_FSCTL_VOLUME_PARAMS_V1_FIELD_DEFN\n} FSP_FSCTL_VOLUME_PARAMS;\n_Static_assert(504 == sizeof(FSP_FSCTL_VOLUME_PARAMS),\n    \"sizeof(FSP_FSCTL_VOLUME_PARAMS) must be 504.\");\n#endif\n\ntypedef union\n{\n    FSP_FSCTL_VOLUME_PARAMS VolumeParams;\n    struct\n    {\n        CHAR VolumeName[(FSP_FSCTL_VOLUME_NAME_SIZEMAX / sizeof(WCHAR)) * 3 / 2];\n        UINT64 VolumeId;\n    };\n} WSLFUSE_IOCTL_CREATEVOLUME_ARG;\n#if defined(__linux__)\n_Static_assert(504 == sizeof(WSLFUSE_IOCTL_CREATEVOLUME_ARG),\n    \"sizeof(WSLFUSE_IOCTL_CREATEVOLUME_ARG) must be 504.\");\n#endif\n\ntypedef struct\n{\n    CHAR WinMountPoint[260];\n} WSLFUSE_IOCTL_WINMOUNT_ARG;\n#if defined(__linux__)\n_Static_assert(260 == sizeof(WSLFUSE_IOCTL_WINMOUNT_ARG),\n    \"sizeof(WSLFUSE_IOCTL_WINMOUNT_ARG) must be 260.\");\n#endif\n\ntypedef struct\n{\n    UINT8 Operation;\n    UINT64 VolumeId;\n    UINT64 LxMountId;\n} WSLFUSE_IOCTL_LXMOUNT_ARG;\n#if defined(__linux__)\n_Static_assert(24 == sizeof(WSLFUSE_IOCTL_LXMOUNT_ARG),\n    \"sizeof(WSLFUSE_IOCTL_LXMOUNT_ARG) must be 16.\");\n#endif\n\n/*\n * _IOWR('F', 'C', WSLFUSE_IOCTL_CREATEVOLUME_ARG)\n * sh tools/ioc.c 3 70 67 504\n */\n#define WSLFUSE_IOCTL_CREATEVOLUME      0xc1f84643\n#if defined(__linux__)\n_Static_assert(WSLFUSE_IOCTL_CREATEVOLUME == _IOWR('F', 'C', WSLFUSE_IOCTL_CREATEVOLUME_ARG),\n    \"WSLFUSE_IOCTL_CREATEVOLUME\");\n#endif\n\n/*\n * _IOW('F', 'M', WSLFUSE_IOCTL_WINMOUNT_ARG)\n * sh tools/ioc.c 1 70 77 260\n */\n#define WSLFUSE_IOCTL_WINMOUNT          0x4104464d\n#if defined(__linux__)\n_Static_assert(WSLFUSE_IOCTL_WINMOUNT == _IOW('F', 'M', WSLFUSE_IOCTL_WINMOUNT_ARG),\n    \"WSLFUSE_IOCTL_WINMOUNT\");\n#endif\n\n/*\n * _IOW('F', 'm', WSLFUSE_IOCTL_LXMOUNT_ARG)\n * sh tools/ioc.c 1 70 109 24\n */\n#define WSLFUSE_IOCTL_LXMOUNT           0x4018466d\n#if defined(__linux__)\n_Static_assert(WSLFUSE_IOCTL_LXMOUNT == _IOW('F', 'm', WSLFUSE_IOCTL_LXMOUNT_ARG),\n    \"WSLFUSE_IOCTL_LXMOUNT\");\n#endif\n\n#endif\n"
  },
  {
    "path": "src/winfuse/device.c",
    "content": "/**\n * @file winfuse/device.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <winfuse/driver.h>\n\nstatic NTSTATUS FuseDeviceInit(PDEVICE_OBJECT DeviceObject, FSP_FSCTL_VOLUME_PARAMS *VolumeParams);\nstatic VOID FuseDeviceFini(PDEVICE_OBJECT DeviceObject);\nstatic VOID FuseDeviceExpirationRoutine(PDEVICE_OBJECT DeviceObject, UINT64 ExpirationTime);\nstatic NTSTATUS FuseDeviceTransact(PDEVICE_OBJECT DeviceObject, PIRP Irp);\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(PAGE, FuseDeviceInit)\n#pragma alloc_text(PAGE, FuseDeviceFini)\n#pragma alloc_text(PAGE, FuseDeviceExpirationRoutine)\n#pragma alloc_text(PAGE, FuseDeviceTransact)\n#endif\n\nstatic NTSTATUS FuseDeviceInit(PDEVICE_OBJECT DeviceObject, FSP_FSCTL_VOLUME_PARAMS *VolumeParams)\n{\n    PAGED_CODE();\n\n    FUSE_INSTANCE *Instance = FuseInstanceFromDeviceObject(DeviceObject);\n    NTSTATUS Result;\n\n    KeEnterCriticalRegion();\n\n    Result = FuseInstanceInit(Instance, VolumeParams, FuseInstanceWindows);\n\n    KeLeaveCriticalRegion();\n\n    return Result;\n}\n\nstatic VOID FuseDeviceFini(PDEVICE_OBJECT DeviceObject)\n{\n    PAGED_CODE();\n\n    FUSE_INSTANCE *Instance = FuseInstanceFromDeviceObject(DeviceObject);\n\n    KeEnterCriticalRegion();\n\n    FuseInstanceFini(Instance);\n\n    KeLeaveCriticalRegion();\n}\n\nstatic VOID FuseDeviceExpirationRoutine(PDEVICE_OBJECT DeviceObject, UINT64 ExpirationTime)\n{\n    PAGED_CODE();\n\n    FUSE_INSTANCE *Instance = FuseInstanceFromDeviceObject(DeviceObject);\n\n    KeEnterCriticalRegion();\n\n    FuseInstanceExpirationRoutine(Instance, ExpirationTime);\n\n    KeLeaveCriticalRegion();\n}\n\nstatic NTSTATUS FuseDeviceTransact(PDEVICE_OBJECT DeviceObject, PIRP Irp)\n{\n    PAGED_CODE();\n\n    ASSERT(KeAreApcsDisabled());\n\n    PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp);\n    ASSERT(IRP_MJ_FILE_SYSTEM_CONTROL == IrpSp->MajorFunction);\n    ASSERT(IRP_MN_USER_FS_REQUEST == IrpSp->MinorFunction);\n    ASSERT(FUSE_FSCTL_TRANSACT == IrpSp->Parameters.FileSystemControl.FsControlCode);\n    ASSERT(METHOD_BUFFERED == (IrpSp->Parameters.FileSystemControl.FsControlCode & 3));\n    ASSERT(IrpSp->FileObject->FsContext2 == DeviceObject);\n\n    FUSE_INSTANCE *Instance = FuseInstanceFromDeviceObject(DeviceObject);\n    ULONG InputBufferLength = IrpSp->Parameters.FileSystemControl.InputBufferLength;\n    ULONG OutputBufferLength = IrpSp->Parameters.FileSystemControl.OutputBufferLength;\n    FUSE_PROTO_RSP *FuseResponse = 0 != InputBufferLength ? Irp->AssociatedIrp.SystemBuffer : 0;\n    FUSE_PROTO_REQ *FuseRequest = 0 != OutputBufferLength ? Irp->AssociatedIrp.SystemBuffer : 0;\n    NTSTATUS Result;\n\n    Result = FuseInstanceTransact(Instance,\n        FuseResponse, InputBufferLength,\n        FuseRequest, &OutputBufferLength,\n        IrpSp->DeviceObject, IrpSp->FileObject,\n        Irp);\n\n    Irp->IoStatus.Information = OutputBufferLength;\n\n    return Result;\n}\n\nFSP_FSEXT_PROVIDER FuseProvider =\n{\n    /* Version */\n    sizeof FuseProvider,\n\n    /* DeviceTransactCode */\n    FUSE_FSCTL_TRANSACT,\n\n    /* DeviceExtensionSize */\n    sizeof(FUSE_INSTANCE),\n\n    /* DeviceInit */\n    FuseDeviceInit,\n\n    /* DeviceFini */\n    FuseDeviceFini,\n\n    /* DeviceExpirationRoutine */\n    FuseDeviceExpirationRoutine,\n\n    /* DeviceTransact */\n    FuseDeviceTransact,\n};\n"
  },
  {
    "path": "src/winfuse/driver.c",
    "content": "/**\n * @file winfuse/driver.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <winfuse/driver.h>\n\nDRIVER_INITIALIZE DriverEntry;\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(INIT, DriverEntry)\n#endif\n\nNTSTATUS DriverEntry(\n    PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)\n{\n#if DBG\n    if (!KD_DEBUGGER_NOT_PRESENT)\n        DbgBreakPoint();\n#endif\n\n    return FspFsextProviderRegister(&FuseProvider);\n}\n"
  },
  {
    "path": "src/winfuse/driver.h",
    "content": "/**\n * @file winfuse/driver.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#ifndef WINFUSE_DRIVER_H_INCLUDED\n#define WINFUSE_DRIVER_H_INCLUDED\n\n#include <shared/km/shared.h>\n\n#define FUSE_FSCTL_TRANSACT             \\\n    CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 0xC00 + 'F', METHOD_BUFFERED, FILE_ANY_ACCESS)\n\nextern FSP_FSEXT_PROVIDER FuseProvider;\nstatic inline\nFUSE_INSTANCE *FuseInstanceFromDeviceObject(PDEVICE_OBJECT DeviceObject)\n{\n    return (PVOID)((PUINT8)DeviceObject->DeviceExtension + FuseProvider.DeviceExtensionOffset);\n}\n\n#endif\n"
  },
  {
    "path": "src/winfuse/driver.inf.in",
    "content": "[Version]\r\nSignature = \"$WINDOWS NT$\"\r\nClass = Volume\r\nClassGuid = {71a27cdd-812a-11d0-bec7-08002be2092f}\r\nCatalogFile = !CatalogFile!\r\nProvider = !Provider!\r\n\r\n[DestinationDirs]\r\nDefaultDestDir = 12\r\n\r\n[DefaultInstall]\r\nCopyFiles = Driver.CopyFiles\r\n\r\n[Driver.CopyFiles]\r\n!DriverFile!\r\n\r\n[SourceDisksFiles]\r\n!DriverFile! = 1\r\n\r\n[SourceDisksNames]\r\n1 = Disk1\r\n"
  },
  {
    "path": "src/winfuse/version.rc",
    "content": "#include <winver.h>\n\n#define STR(x)                          STR_(x)\n#define STR_(x)                         #x\n\nVS_VERSION_INFO VERSIONINFO\nFILEVERSION MyVersionWithCommas\nPRODUCTVERSION MyVersionWithCommas\nFILEFLAGSMASK VS_FFI_FILEFLAGSMASK\n#ifdef _DEBUG\nFILEFLAGS VS_FF_DEBUG\n#else\nFILEFLAGS 0\n#endif\nFILEOS VOS_NT\nFILETYPE VFT_DRV\nFILESUBTYPE VFT2_DRV_SYSTEM\nBEGIN\n    BLOCK \"StringFileInfo\"\n    BEGIN\n        BLOCK \"040904b0\"\n        BEGIN\n            VALUE \"CompanyName\", STR(MyCompanyName)\n            VALUE \"FileDescription\", STR(MyDescription)\n            VALUE \"FileVersion\", STR(MyFullVersion)\n            VALUE \"InternalName\", \"winfuse.sys\"\n            VALUE \"LegalCopyright\", STR(MyCopyright)\n            VALUE \"OriginalFilename\", \"winfuse.sys\"\n            VALUE \"ProductName\", STR(MyProductName)\n            VALUE \"ProductVersion\", STR(MyProductVersion)\n        END\n    END\n    BLOCK \"VarFileInfo\"\n    BEGIN\n        VALUE \"Translation\", 0x409, 1200\n    END\nEND\n"
  },
  {
    "path": "src/wslfuse/device.c",
    "content": "/**\n * @file wslfuse/device.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <wslfuse/driver.h>\n\n#define FUSE_MINOR                      229\n\ntypedef struct _FILE FILE;\ntypedef struct _MOUNT MOUNT;\ntypedef struct _DEVICE DEVICE;\n\nstruct _FILE\n{\n    LX_FILE Base;\n    LIST_ENTRY ListEntry;\n    DEVICE *Device;\n    MOUNT *Mount;\n    EX_PUSH_LOCK VolumeLock;\n    FSP_FSCTL_VOLUME_PARAMS VolumeParams;\n    FUSE_INSTANCE *FuseInstance;\n    UINT64 VolumeId;\n    HANDLE VolumeHandle;\n    PFILE_OBJECT VolumeFileObject;\n    HANDLE WinMountHandle;\n};\n\nstruct _MOUNT\n{\n    LONG RefCount;\n    LIST_ENTRY ListEntry;\n    UINT64 LxMountId;\n    FILE *File;\n};\n\nstruct _DEVICE\n{\n    LX_DEVICE Base;\n    EX_PUSH_LOCK MountListLock;\n    LIST_ENTRY MountList;\n};\n\nstatic VOID FuseMiscFileListInsert(FILE *File);\nstatic VOID FuseMiscFileListRemove(FILE *File);\nstatic MOUNT *FuseMiscFileListGetMount(DEVICE *Device, UINT64 VolumeId);\n\nstatic inline MOUNT *MountCreate(VOID)\n{\n    MOUNT *Mount;\n\n    Mount = FuseAllocNonPaged(sizeof *Mount);\n    if (0 == Mount)\n        return 0;\n\n    RtlZeroMemory(Mount, sizeof *Mount);\n    Mount->RefCount = 1;\n    Mount->LxMountId = (UINT64)-1LL;\n\n    return Mount;\n}\n\nstatic inline VOID MountReference(MOUNT *Mount)\n{\n    InterlockedIncrement(&Mount->RefCount);\n}\n\nstatic inline VOID MountDereference(MOUNT *Mount)\n{\n    LONG RefCount;\n\n    RefCount = InterlockedDecrement(&Mount->RefCount);\n    if (0 == RefCount)\n        FuseFree(Mount);\n}\n\nstatic VOID FileProtoSendDestroyHandler(PVOID File0)\n{\n    FILE *File = (FILE *)File0;\n    IO_STATUS_BLOCK IoStatus;\n\n    ZwFsControlFile(\n        File->VolumeHandle,\n        0/*Event*/,\n        0/*ApcRoutine*/,\n        0/*ApcContext*/,\n        &IoStatus,\n        FSP_FSCTL_STOP,\n        0/*InputBuffer*/,\n        0/*InputBufferLength*/,\n        0/*OutputBuffer*/,\n        0/*OutputBufferLength*/);\n}\n\nstatic INT FileIoctlCreateVolume(\n    FILE *File,\n    WSLFUSE_IOCTL_CREATEVOLUME_ARG *Arg)\n{\n    SIZE_T VolumeParamsSize;\n    UNICODE_STRING DevicePath;\n    WCHAR DevicePathBuf[260/*MAX_PATH*/ + sizeof(FSP_FSCTL_VOLUME_PARAMS)];\n    WCHAR *DevicePathPtr, *DevicePathEnd;\n    OBJECT_ATTRIBUTES ObjectAttributes;\n    IO_STATUS_BLOCK IoStatus;\n    FUSE_INSTANCE *FuseInstance = 0;\n    BOOLEAN InitDoneInstance = FALSE;\n    HANDLE VolumeHandle = 0;\n    PFILE_OBJECT VolumeFileObject = 0;\n    WCHAR VolumeName[FSP_FSCTL_VOLUME_NAME_SIZEMAX / sizeof(WCHAR)];\n    ULONG VolumeNameSize;\n\n    ExAcquirePushLockExclusive(&File->VolumeLock);\n\n    if (0 != File->VolumeFileObject)\n    {\n        IoStatus.Status = STATUS_INVALID_PARAMETER;\n        goto exit;\n    }\n\n    VolumeParamsSize = 0 == Arg->VolumeParams.Version ?\n        sizeof(FSP_FSCTL_VOLUME_PARAMS_V0) :\n        Arg->VolumeParams.Version;\n    if (sizeof(FSP_FSCTL_VOLUME_PARAMS) < VolumeParamsSize)\n    {\n        IoStatus.Status = STATUS_INVALID_PARAMETER;\n        goto exit;\n    }\n    RtlCopyMemory(&File->VolumeParams, &Arg->VolumeParams, VolumeParamsSize);\n\n    FuseInstance = FuseAllocNonPaged(sizeof *FuseInstance);\n    if (0 == FuseInstance)\n    {\n        IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;\n        goto exit;\n    }\n\n    IoStatus.Status = FuseInstanceInit(FuseInstance, &File->VolumeParams, FuseInstanceLinux);\n    if (!NT_SUCCESS(IoStatus.Status))\n        goto exit;\n    FuseInstance->ProtoSendDestroyHandler = FileProtoSendDestroyHandler;\n    FuseInstance->ProtoSendDestroyData = File;\n    File->VolumeParams.TransactTimeout = 3000; /* transact timeout allows poll with LxpThreadWait */\n    InitDoneInstance = TRUE;\n\n    RtlInitEmptyUnicodeString(&DevicePath, DevicePathBuf, sizeof DevicePathBuf);\n    RtlAppendUnicodeToString(&DevicePath, L'\\0' == File->VolumeParams.Prefix[0] ?\n        L\"\\\\Device\\\\\" FSP_FSCTL_DISK_DEVICE_NAME :\n        L\"\\\\Device\\\\\" FSP_FSCTL_NET_DEVICE_NAME);\n    RtlAppendUnicodeToString(&DevicePath, L\"\" FSP_FSCTL_VOLUME_PARAMS_PREFIX);\n    DevicePathPtr = (PVOID)((PUINT8)DevicePath.Buffer + DevicePath.Length);\n    DevicePathEnd = (PVOID)((PUINT8)DevicePathPtr + VolumeParamsSize * sizeof(WCHAR));\n    for (PUINT8 VolumeParamsPtr = (PVOID)&File->VolumeParams;\n        DevicePathEnd > DevicePathPtr; DevicePathPtr++, VolumeParamsPtr++)\n    {\n        WCHAR Value = 0xF000 | *VolumeParamsPtr;\n        *DevicePathPtr = Value;\n    }\n    DevicePath.Length = (USHORT)((PUINT8)DevicePathPtr - (PUINT8)DevicePath.Buffer);\n\n    InitializeObjectAttributes(\n        &ObjectAttributes,\n        &DevicePath,\n        OBJ_KERNEL_HANDLE,\n        0/*RootDirectory*/,\n        0/*SecurityDescriptor*/);\n\n    IoStatus.Status = ZwOpenFile(\n        &VolumeHandle,\n        0/*DesiredAccess*/,\n        &ObjectAttributes,\n        &IoStatus,\n        FILE_SHARE_READ | FILE_SHARE_WRITE,\n        0/*OpenOptions*/);\n    if (!NT_SUCCESS(IoStatus.Status))\n        goto exit;\n\n    IoStatus.Status = ObReferenceObjectByHandle(\n        VolumeHandle,\n        0/*DesiredAccess*/,\n        *IoFileObjectType,\n        KernelMode,\n        &VolumeFileObject,\n        0/*HandleInformation*/);\n    if (!NT_SUCCESS(IoStatus.Status))\n        goto exit;\n\n    IoStatus.Status = ZwFsControlFile(\n        VolumeHandle,\n        0/*Event*/,\n        0/*ApcRoutine*/,\n        0/*ApcContext*/,\n        &IoStatus,\n        FSP_FSCTL_VOLUME_NAME,\n        0/*InputBuffer*/,\n        0/*InputBufferLength*/,\n        VolumeName,\n        sizeof VolumeName);\n    if (!NT_SUCCESS(IoStatus.Status))\n        goto exit;\n\n    RtlZeroMemory(Arg, sizeof *Arg);\n    VolumeNameSize = (ULONG)(wcslen(VolumeName) + 1) * sizeof(WCHAR);\n    IoStatus.Status = RtlUnicodeToUTF8N(\n        Arg->VolumeName,\n        sizeof Arg->VolumeName,\n        &VolumeNameSize,\n        VolumeName,\n        VolumeNameSize);\n    if (!NT_SUCCESS(IoStatus.Status))\n        goto exit;\n    Arg->VolumeId = File->VolumeId;\n\n    File->FuseInstance = FuseInstance;\n    File->VolumeHandle = VolumeHandle;\n    InterlockedExchangePointer(&File->VolumeFileObject, VolumeFileObject);\n\n    FuseMiscFileListInsert(File);\n\n    IoStatus.Status = STATUS_SUCCESS;\n\nexit:\n    if (!NT_SUCCESS(IoStatus.Status))\n    {\n        if (0 != VolumeFileObject)\n            ObDereferenceObject(VolumeFileObject);\n\n        if (0 != VolumeHandle)\n            ZwClose(VolumeHandle);\n\n        if (InitDoneInstance)\n            FuseInstanceFini(FuseInstance);\n\n        if (0 != FuseInstance)\n            FuseFree(FuseInstance);\n    }\n\n    ExReleasePushLockExclusive(&File->VolumeLock);\n\n    /* !!!: REVISIT */\n    return NT_SUCCESS(IoStatus.Status) ? 0 : -EIO;\n}\n\nstatic INT FileIoctlWinMount(\n    FILE *File,\n    WSLFUSE_IOCTL_WINMOUNT_ARG *Arg)\n{\n    UNICODE_STRING WinMountPoint;\n    WCHAR WinMountPointBuf[4 + sizeof Arg->WinMountPoint];\n    ULONG WinMountPointSize;\n    OBJECT_ATTRIBUTES ObjectAttributes;\n    HANDLE WinMountHandle;\n    NTSTATUS Result;\n\n    ExAcquirePushLockExclusive(&File->VolumeLock);\n\n    if (0 != File->WinMountHandle)\n    {\n        Result = STATUS_INVALID_PARAMETER;\n        goto exit;\n    }\n\n    Arg->WinMountPoint[sizeof Arg->WinMountPoint - 1] = '\\0';\n    WinMountPointSize = (ULONG)strlen(Arg->WinMountPoint);\n\n    WinMountPointBuf[0] = '\\\\';\n    WinMountPointBuf[1] = '?';\n    WinMountPointBuf[2] = '?';\n    WinMountPointBuf[3] = '\\\\';\n\n    Result = RtlUTF8ToUnicodeN(\n        WinMountPointBuf + 4,\n        sizeof WinMountPointBuf - 4,\n        &WinMountPointSize,\n        Arg->WinMountPoint,\n        WinMountPointSize);\n    if (!NT_SUCCESS(Result))\n        goto exit;\n\n    WinMountPoint.Length = WinMountPoint.MaximumLength =\n        (USHORT)(4 * sizeof(WCHAR) + WinMountPointSize);\n    WinMountPoint.Buffer = WinMountPointBuf;\n\n    InitializeObjectAttributes(\n        &ObjectAttributes,\n        &WinMountPoint,\n        OBJ_KERNEL_HANDLE,\n        0/*RootDirectory*/,\n        0/*SecurityDescriptor*/);\n\n    Result = ZwOpenSymbolicLinkObject(&WinMountHandle, 0, &ObjectAttributes);\n    if (!NT_SUCCESS(Result))\n        goto exit;\n\n    File->WinMountHandle = WinMountHandle;\n\n    Result = STATUS_SUCCESS;\n\nexit:\n    ExReleasePushLockExclusive(&File->VolumeLock);\n\n    /* !!!: REVISIT */\n    return NT_SUCCESS(Result) ? 0 : -EIO;\n}\n\nstatic INT FileIoctlLxMount(\n    FILE *File,\n    WSLFUSE_IOCTL_LXMOUNT_ARG *Arg)\n{\n    DEVICE *Device = File->Device;\n    MOUNT *Mount;\n    FILE *MountFile;\n    INT Error = 0;\n\n    ExAcquirePushLockExclusive(&Device->MountListLock);\n\n    if ((UINT64)-1LL == Arg->LxMountId)\n        Mount = File->Mount;\n    else\n    {\n        Mount = 0;\n        for (PLIST_ENTRY Entry = Device->MountList.Flink; &Device->MountList != Entry;)\n        {\n            MOUNT *Temp = CONTAINING_RECORD(Entry, MOUNT, ListEntry);\n            Entry = Entry->Flink;\n            if (Temp->LxMountId == Arg->LxMountId)\n            {\n                Mount = Temp;\n                break;\n            }\n        }\n    }\n\n    switch (Arg->Operation)\n    {\n    case '+':\n        if (0 != Mount)\n        {\n            Error = -EEXIST;\n            break;\n        }\n        Mount = FuseMiscFileListGetMount(Device, Arg->VolumeId);\n        if (0 == Mount)\n        {\n            Error = -ENOENT;\n            break;\n        }\n        if ((UINT64)-1LL != Mount->LxMountId)\n        {\n            Error = -EEXIST;\n            break;\n        }\n\n        MountReference(Mount);\n        Mount->LxMountId = Arg->LxMountId;\n        InsertTailList(&Device->MountList, &Mount->ListEntry);\n        break;\n\n    case '-':\n        if (0 == Mount || (UINT64)-1LL == Mount->LxMountId)\n        {\n            Error = -ENOENT;\n            break;\n        }\n\n        MountFile = Mount->File;\n\n        RemoveEntryList(&Mount->ListEntry);\n        Mount->LxMountId = (UINT64)-1LL;\n        MountDereference(Mount);\n\n        if (0 != MountFile &&\n            0 != InterlockedCompareExchangePointer(&MountFile->VolumeFileObject, 0, 0))\n            FuseProtoPostDestroy(MountFile->FuseInstance);\n                /* ignore errors */\n        break;\n\n    case '?':\n        if (0 == Mount || (UINT64)-1LL == Mount->LxMountId)\n        {\n            Error = -ENOENT;\n            break;\n        }\n\n        break;\n\n    default:\n        Error = -EINVAL;\n        break;\n    }\n\n    ExReleasePushLockExclusive(&Device->MountListLock);\n\n    return Error;\n}\n\nstatic INT FileIoctlBegin(\n    ULONG Code,\n    PVOID Buffer,\n    PVOID *PSystemBuffer)\n{\n    ULONG Size = (Code >> 16) & 0x3fff;\n    PVOID SystemBuffer = 0;\n    INT Error;\n\n    *PSystemBuffer = 0;\n\n    if (FlagOn(Code, 0xc0000000/* _IOC_WRITE | _IOC_READ */) &&\n        0 != Size)\n    {\n        SystemBuffer = FuseAllocNonPaged(Size);\n        if (0 == SystemBuffer)\n        {\n            Error = -ENOMEM;\n            goto exit;\n        }\n\n        try\n        {\n            if (FlagOn(Code, 0x80000000/* _IOC_READ */))\n                ProbeForWrite(Buffer, Size, 1);\n            else\n                ProbeForRead(Buffer, Size, 1);\n\n            if (FlagOn(Code, 0x40000000/* _IOC_WRITE */))\n                RtlCopyMemory(SystemBuffer, Buffer, Size);\n            else\n                RtlZeroMemory(SystemBuffer, Size);\n        }\n        except (EXCEPTION_EXECUTE_HANDLER)\n        {\n            Error = -EFAULT;\n            goto exit;\n        }\n    }\n\n    *PSystemBuffer = SystemBuffer;\n    SystemBuffer = 0;\n    Error = 0;\n\nexit:\n    if (0 != SystemBuffer)\n        FuseFree(SystemBuffer);\n\n    return Error;\n}\n\nstatic INT FileIoctlEnd(\n    ULONG Code,\n    PVOID Buffer,\n    PVOID *PSystemBuffer,\n    INT Error)\n{\n    ULONG Size = (Code >> 16) & 0x3fff;\n    PVOID SystemBuffer = *PSystemBuffer;\n\n    if (0 == Error &&\n        FlagOn(Code, 0x80000000/* _IOC_READ */) &&\n        0 != Size)\n    {\n        try\n        {\n            ProbeForWrite(Buffer, Size, 1);\n            RtlCopyMemory(Buffer, SystemBuffer, Size);\n        }\n        except (EXCEPTION_EXECUTE_HANDLER)\n        {\n            Error = -EFAULT;\n            goto exit;\n        }\n    }\n\n    *PSystemBuffer = 0;\n\nexit:\n    if (0 != SystemBuffer)\n        FuseFree(SystemBuffer);\n\n    return Error;\n}\n\nstatic INT FileIoctl(\n    PLX_CALL_CONTEXT CallContext,\n    PLX_FILE File0,\n    ULONG Code,\n    PVOID Buffer)\n{\n    INT (*IoctlProc)(FILE *File, PVOID Arg);\n    FILE *File = (FILE *)File0;\n    PVOID SystemBuffer;\n    INT Error;\n\n    switch (Code)\n    {\n    case WSLFUSE_IOCTL_CREATEVOLUME:\n        IoctlProc = FileIoctlCreateVolume;\n        break;\n\n    case WSLFUSE_IOCTL_WINMOUNT:\n        IoctlProc = FileIoctlWinMount;\n        break;\n\n    case WSLFUSE_IOCTL_LXMOUNT:\n        IoctlProc = FileIoctlLxMount;\n        break;\n\n    default:\n        return -EINVAL;\n    }\n\n    Error = FileIoctlBegin(Code, Buffer, &SystemBuffer);\n    if (0 == Error)\n    {\n        Error = IoctlProc(File, SystemBuffer);\n        Error = FileIoctlEnd(Code, Buffer, &SystemBuffer, Error);\n    }\n\n    return Error;\n}\n\nstatic INT FileRead(\n    PLX_CALL_CONTEXT CallContext,\n    PLX_FILE File0,\n    PVOID Buffer,\n    SIZE_T Length,\n    POFF_T POffset,\n    PSIZE_T PBytesTransferred)\n{\n    FILE *File = (FILE *)File0;\n    ULONG OutputBufferLength;\n    PFILE_OBJECT VolumeFileObject;\n    NTSTATUS Result;\n\n    VolumeFileObject = InterlockedCompareExchangePointer(&File->VolumeFileObject, 0, 0);\n    if (0 == VolumeFileObject)\n        return -ENODEV;\n\n    for (;;)\n    {\n        OutputBufferLength = (ULONG)Length;\n        Result = FuseInstanceTransact(File->FuseInstance,\n            0, 0,\n            Buffer, &OutputBufferLength,\n            0, VolumeFileObject,\n            0);\n        if (!NT_SUCCESS(Result))\n            return STATUS_CANCELLED == Result ? -ENODEV : -EIO;\n        if (0 != OutputBufferLength)\n            break;\n\n        LARGE_INTEGER ZeroTimeout = { 0 };\n        Result = LxpThreadWait(0, &ZeroTimeout, FALSE);\n        if (STATUS_TIMEOUT != Result)\n            return -EINTR;\n    }\n\n    *PBytesTransferred = OutputBufferLength;\n\n    return 0;\n}\n\nstatic INT FileWriteVector(\n    PLX_CALL_CONTEXT CallContext,\n    PLX_FILE File0,\n    PLX_IOVECTOR IoVector,\n    POFF_T POffset,\n    ULONG Flags,\n    PSIZE_T PBytesTransferred)\n{\n    FILE *File = (FILE *)File0;\n    FUSE_PROTO_RSP FuseResponseBuf, *FuseResponse = &FuseResponseBuf;\n    ULONG InputBufferLength;\n    ULONG OutputBufferLength = 0;\n    PFILE_OBJECT VolumeFileObject;\n    NTSTATUS Result;\n    INT Error;\n\n    VolumeFileObject = InterlockedCompareExchangePointer(&File->VolumeFileObject, 0, 0);\n    if (0 == VolumeFileObject)\n        return -ENODEV;\n\n    InputBufferLength = 0;\n    for (ULONG I = 0; (ULONG)IoVector->Count > I; I++)\n        InputBufferLength += (ULONG)IoVector->Vector[I].Length;\n    if (FUSE_PROTO_RSP_HEADER_SIZE > InputBufferLength)\n        return -EINVAL;\n\n    try\n    {\n        ULONG L = sizeof(FUSE_PROTO_RSP) < InputBufferLength ?\n            FUSE_PROTO_RSP_HEADER_SIZE : sizeof(FUSE_PROTO_RSP);\n        PUINT8 P = (PUINT8)&FuseResponseBuf, EndP = P + L;\n        for (ULONG I = 0; (ULONG)IoVector->Count > I && EndP > P; I++)\n        {\n            L = (ULONG)(EndP - P);\n            if (L > (ULONG)IoVector->Vector[I].Length)\n                L = (ULONG)IoVector->Vector[I].Length;\n            RtlCopyMemory(P, IoVector->Vector[I].Buffer, L);\n            P += L;\n        }\n\n        if (sizeof(FUSE_PROTO_RSP) < InputBufferLength)\n        {\n            P = FuseAlloc(InputBufferLength);\n            if (0 == P)\n            {\n                Error = -ENOMEM;\n                goto exit;\n            }\n            FuseResponse = (PVOID)P;\n\n            L = InputBufferLength;\n            EndP = P + L;\n            for (ULONG I = 0; (ULONG)IoVector->Count > I && EndP > P; I++)\n            {\n                L = (ULONG)(EndP - P);\n                if (L > (ULONG)IoVector->Vector[I].Length)\n                    L = (ULONG)IoVector->Vector[I].Length;\n                RtlCopyMemory(P, IoVector->Vector[I].Buffer, L);\n                P += L;\n            }\n        }\n    }\n    except (EXCEPTION_EXECUTE_HANDLER)\n    {\n        Error = -EFAULT;\n        goto exit;\n    }\n\n    Result = FuseInstanceTransact(File->FuseInstance,\n        FuseResponse, InputBufferLength,\n        0, &OutputBufferLength,\n        0, VolumeFileObject,\n        0);\n    if (!NT_SUCCESS(Result))\n    {\n        Error = STATUS_CANCELLED == Result ? -ENODEV : -EIO;\n        goto exit;\n    }\n\n    *PBytesTransferred = InputBufferLength;\n\n    Error = 0;\n\nexit:\n    if (&FuseResponseBuf != FuseResponse)\n        FuseFree(FuseResponse);\n\n    return Error;\n}\n\nstatic INT FileDelete(\n    PLX_CALL_CONTEXT CallContext,\n    PLX_FILE File0)\n{\n    FILE *File = (FILE *)File0;\n    DEVICE *Device = File->Device;\n\n    if (0 != File->VolumeFileObject)\n        FuseMiscFileListRemove(File);\n\n    ExAcquirePushLockExclusive(&Device->MountListLock);\n    File->Mount->File = 0;\n    ExReleasePushLockExclusive(&Device->MountListLock);\n\n    if (0 != File->WinMountHandle)\n        ZwClose(File->WinMountHandle);\n\n    if (0 != File->VolumeFileObject)\n    {\n        ObDereferenceObject(File->VolumeFileObject);\n        ZwClose(File->VolumeHandle);\n\n        FuseInstanceFini(File->FuseInstance);\n        FuseFree(File->FuseInstance);\n    }\n\n    MountDereference(File->Mount);\n\n    return 0;\n}\n\nstatic INT DeviceOpen(\n    PLX_CALL_CONTEXT CallContext,\n    PLX_DEVICE Device0,\n    ULONG Flags,\n    PLX_FILE *PFile)\n{\n    static LX_FILE_CALLBACKS FileCallbacks =\n    {\n        .Delete = FileDelete,\n        .Ioctl = FileIoctl,\n        .Read = FileRead,\n        .WriteVector = FileWriteVector,\n    };\n    static LONG64 StaticVolumeId = -1LL;\n    DEVICE *Device = (DEVICE *)Device0;\n    MOUNT *Mount = 0;\n    FILE *File;\n    INT Error;\n\n    *PFile = 0;\n\n    Mount = MountCreate();\n    if (0 == Mount)\n    {\n        Error = -ENOMEM;\n        goto exit;\n    }\n\n    File = (FILE *)VfsFileAllocate(sizeof *File, &FileCallbacks);\n    if (0 == File)\n    {\n        Error = -ENOMEM;\n        goto exit;\n    }\n\n    /* File: initialize fields. File->Base MUST be zeroed out. */\n    RtlZeroMemory(File, sizeof *File);\n    File->Device = (DEVICE *)Device;\n    File->Mount = Mount;\n    ExInitializePushLock(&File->VolumeLock);\n    File->VolumeId = InterlockedIncrement64(&StaticVolumeId);\n\n    Mount->File = File;\n    Mount = 0;\n\n    *PFile = &File->Base;\n    Error = 0;\n\nexit:\n    if (0 != Mount)\n        MountDereference(Mount);\n\n    return Error;\n}\n\nstatic INT DeviceDelete(\n    PLX_DEVICE Device0)\n{\n    DEVICE *Device = (DEVICE *)Device0;\n    MOUNT *Mount;\n\n    for (PLIST_ENTRY Entry = Device->MountList.Flink; &Device->MountList != Entry;)\n    {\n        Mount = CONTAINING_RECORD(Entry, MOUNT, ListEntry);\n        Entry = Entry->Flink;\n        MountDereference(Mount);\n    }\n\n    return 0;\n}\n\nstatic EX_PUSH_LOCK FuseMiscLock;\nstatic LIST_ENTRY FuseMiscFileList;\nstatic KTIMER FuseMiscTimer;\nstatic KDPC FuseMiscTimerDpc;\nstatic WORK_QUEUE_ITEM FuseMiscTimerItem;\nstatic BOOLEAN FuseMiscTimerInitDone;\n\nstatic VOID FuseMiscFileListInsert(FILE *File)\n{\n    ExAcquirePushLockExclusive(&FuseMiscLock);\n\n    InsertTailList(&FuseMiscFileList, &File->ListEntry);\n\n    ExReleasePushLockExclusive(&FuseMiscLock);\n}\n\nstatic VOID FuseMiscFileListRemove(FILE *File)\n{\n    ExAcquirePushLockExclusive(&FuseMiscLock);\n\n    RemoveEntryList(&File->ListEntry);\n\n    ExReleasePushLockExclusive(&FuseMiscLock);\n}\n\nstatic MOUNT *FuseMiscFileListGetMount(DEVICE *Device, UINT64 VolumeId)\n{\n    /* NOTE:\n     * This function is assumed to be called with the Device->MountListLock\n     * acquired.\n     */\n\n    FILE *File;\n    MOUNT *Mount;\n\n    ExAcquirePushLockShared(&FuseMiscLock);\n\n    Mount = 0;\n    for (PLIST_ENTRY Entry = FuseMiscFileList.Flink; &FuseMiscFileList != Entry;)\n    {\n        File = CONTAINING_RECORD(Entry, FILE, ListEntry);\n        Entry = Entry->Flink;\n        if (File->Device == Device && File->VolumeId == VolumeId)\n        {\n            Mount = File->Mount;\n            break;\n        }\n    }\n\n    ExReleasePushLockShared(&FuseMiscLock);\n\n    return Mount;\n}\n\nstatic VOID FuseMiscExpirationRoutine(PVOID Context)\n{\n    UINT64 InterruptTime;\n    FILE *File;\n\n    InterruptTime = KeQueryInterruptTime();\n\n    ExAcquirePushLockShared(&FuseMiscLock);\n\n    for (PLIST_ENTRY Entry = FuseMiscFileList.Flink; &FuseMiscFileList != Entry;)\n    {\n        File = CONTAINING_RECORD(Entry, FILE, ListEntry);\n        Entry = Entry->Flink;\n        FuseInstanceExpirationRoutine(File->FuseInstance, InterruptTime);\n    }\n\n    ExReleasePushLockShared(&FuseMiscLock);\n}\n\nstatic VOID FuseMiscTimerDpcRoutine(PKDPC Dpc,\n    PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2)\n{\n    // !PAGED_CODE();\n\n    ExQueueWorkItem(&FuseMiscTimerItem, DelayedWorkQueue);\n}\n\nstatic VOID FuseMiscTimerInit(VOID)\n{\n    PAGED_CODE();\n\n    ExAcquirePushLockExclusive(&FuseMiscLock);\n\n    if (!FuseMiscTimerInitDone)\n    {\n        KeInitializeTimer(&FuseMiscTimer);\n        KeInitializeDpc(&FuseMiscTimerDpc, FuseMiscTimerDpcRoutine, 0);\n        ExInitializeWorkItem(&FuseMiscTimerItem, FuseMiscExpirationRoutine, 0);\n\n        LONG Period = 1000; /* 1000ms = 1s */\n        LARGE_INTEGER DueTime;\n        DueTime.QuadPart = -10000LL * Period;\n        KeSetTimerEx(&FuseMiscTimer, DueTime, Period, &FuseMiscTimerDpc);\n\n        FuseMiscTimerInitDone = TRUE;\n    }\n\n    ExReleasePushLockExclusive(&FuseMiscLock);\n}\n\nINT FuseMiscRegister(PLX_INSTANCE Instance)\n{\n    static LX_DEVICE_CALLBACKS DeviceCallbacks =\n    {\n        .Open = DeviceOpen,\n        .Delete = DeviceDelete,\n    };\n    DEVICE *Device = 0;\n    INT Error;\n\n    FuseMiscTimerInit();\n\n    Device = (DEVICE *)VfsDeviceMinorAllocate(&DeviceCallbacks, sizeof *Device);\n    if (0 == Device)\n    {\n        Error = -ENOMEM;\n        goto exit;\n    }\n\n    /* Device: initialize fields. Device->Base MUST NOT be zeroed out. */\n    ExInitializePushLock(&Device->MountListLock);\n    InitializeListHead(&Device->MountList);\n\n    LxpDevMiscRegister(Instance, &Device->Base, FUSE_MINOR);\n\n    Error = 0;\n\nexit:\n    if (0 != Device)\n        VfsDeviceMinorDereference(&Device->Base);\n\n    return Error;\n}\n\nVOID FuseMiscInitialize(VOID)\n{\n    ExInitializePushLock(&FuseMiscLock);\n    InitializeListHead(&FuseMiscFileList);\n}\n"
  },
  {
    "path": "src/wslfuse/driver.c",
    "content": "/**\n * @file wslfuse/driver.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <wslfuse/driver.h>\n\nDRIVER_INITIALIZE DriverEntry;\n\n#ifdef ALLOC_PRAGMA\n#pragma alloc_text(INIT, DriverEntry)\n#endif\n\nNTSTATUS DriverEntry(\n    PDRIVER_OBJECT DriverObject,\n    PUNICODE_STRING RegistryPath)\n{\n#if DBG\n    if (!KD_DEBUGGER_NOT_PRESENT)\n        DbgBreakPoint();\n#endif\n\n    FuseMiscInitialize();\n\n    return LxldrRegisterService(DriverObject, TRUE, FuseMiscRegister);\n}\n"
  },
  {
    "path": "src/wslfuse/driver.h",
    "content": "/**\n * @file wslfuse/driver.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#ifndef WSLFUSE_DRIVER_H_INCLUDED\n#define WSLFUSE_DRIVER_H_INCLUDED\n\n#include <shared/km/shared.h>\n#include <shared/ku/wslfuse.h>\n#include <lxdk/lxdk.h>\n\nINT FuseMiscRegister(PLX_INSTANCE Instance);\nVOID FuseMiscInitialize(VOID);\n\n#endif\n"
  },
  {
    "path": "src/wslfuse/driver.inf.in",
    "content": "[Version]\r\nSignature = \"$WINDOWS NT$\"\r\nClass = Volume\r\nClassGuid = {71a27cdd-812a-11d0-bec7-08002be2092f}\r\nCatalogFile = !CatalogFile!\r\nProvider = !Provider!\r\n\r\n[DestinationDirs]\r\nDefaultDestDir = 12\r\n\r\n[DefaultInstall]\r\nCopyFiles = Driver.CopyFiles\r\n\r\n[Driver.CopyFiles]\r\n!DriverFile!\r\n\r\n[SourceDisksFiles]\r\n!DriverFile! = 1\r\n\r\n[SourceDisksNames]\r\n1 = Disk1\r\n"
  },
  {
    "path": "src/wslfuse/version.rc",
    "content": "#include <winver.h>\n\n#define STR(x)                          STR_(x)\n#define STR_(x)                         #x\n\nVS_VERSION_INFO VERSIONINFO\nFILEVERSION MyVersionWithCommas\nPRODUCTVERSION MyVersionWithCommas\nFILEFLAGSMASK VS_FFI_FILEFLAGSMASK\n#ifdef _DEBUG\nFILEFLAGS VS_FF_DEBUG\n#else\nFILEFLAGS 0\n#endif\nFILEOS VOS_NT\nFILETYPE VFT_DRV\nFILESUBTYPE VFT2_DRV_SYSTEM\nBEGIN\n    BLOCK \"StringFileInfo\"\n    BEGIN\n        BLOCK \"040904b0\"\n        BEGIN\n            VALUE \"CompanyName\", STR(MyCompanyName)\n            VALUE \"FileDescription\", STR(MyDescription)\n            VALUE \"FileVersion\", STR(MyFullVersion)\n            VALUE \"InternalName\", \"wslfuse.sys\"\n            VALUE \"LegalCopyright\", STR(MyCopyright)\n            VALUE \"OriginalFilename\", \"wslfuse.sys\"\n            VALUE \"ProductName\", STR(MyProductName)\n            VALUE \"ProductVersion\", STR(MyProductVersion)\n        END\n    END\n    BLOCK \"VarFileInfo\"\n    BEGIN\n        VALUE \"Translation\", 0x409, 1200\n    END\nEND\n"
  },
  {
    "path": "tools/DigiCert High Assurance EV Root CA.crt",
    "content": "-----BEGIN CERTIFICATE-----\r\nMIIFOzCCAyOgAwIBAgIKYSBNtAAAAAAAJzANBgkqhkiG9w0BAQUFADB/MQswCQYD\r\nVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe\r\nMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSkwJwYDVQQDEyBNaWNyb3Nv\r\nZnQgQ29kZSBWZXJpZmljYXRpb24gUm9vdDAeFw0xMTA0MTUxOTQ1MzNaFw0yMTA0\r\nMTUxOTU1MzNaMGwxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMx\r\nGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xKzApBgNVBAMTIkRpZ2lDZXJ0IEhp\r\nZ2ggQXNzdXJhbmNlIEVWIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw\r\nggEKAoIBAQDGzOVz5vvUu+UtLTKm3+WBP8nNJUm2cSrD1ZQ0Z6IKHLBfaaZAscS3\r\nso/QmKSpQVk609yU1jzbdDikSsxNJYL3SqVTEjju80ltcZF+Y7arpl/DpIT4T2JR\r\nvvjF7Ns4kuMG5QiRDMQoQVX7y1qJFX5x6DW/TXIJPb46OFBbdzEbjbPHJEWap6xt\r\nABRaBLe6E+tRCphBQSJOZWGHgUFQpnlcid4ZSlfVLuZdHFMsfpjNGgYWpGhz0DQE\r\nE1yhcdNafFXbXmThN4cwVgTlEbQpgBLxeTmIogIRfCdmt4i3ePLKCqg4qwpkwr9m\r\nXZWEwaElHoddGlALIBLMQbtuC1E4uEvLAgMBAAGjgcswgcgwEQYDVR0gBAowCDAG\r\nBgRVHSAAMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSx\r\nPsNpA/i/RwHUmCYaCALvY2QrwzAfBgNVHSMEGDAWgBRi+wohW39DbhHaCVRQa/XS\r\nlnHxnjBVBgNVHR8ETjBMMEqgSKBGhkRodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20v\r\ncGtpL2NybC9wcm9kdWN0cy9NaWNyb3NvZnRDb2RlVmVyaWZSb290LmNybDANBgkq\r\nhkiG9w0BAQUFAAOCAgEAIIzBWe1vnGstwUo+dR1FTEFQHL2A6tmwkosGKhM/Uxae\r\nVjlqimO2eCR59X24uUehCpbC9su9omafBuGs0nkJDv083KwCDHCvPxvseH7U60sF\r\nYCbZc2GRIe2waGPglxKrb6AS7dmf0tonPLPkVvnR1IEPcb1CfKaJ3M3VvZWiq/GT\r\nEX3orDEpqF1mcEGd/HXJ1bMaOSrQhQVQi6yRysSTy3GlnaSUb1gM+m4gxAgxtYWd\r\nfoH50j3KWxiFbAqG7CIJG6V0NE9/KLyVSqsdtpiwXQmkd3Z+76eOXYT2GCTL0W2m\r\nw6GcwhB1gP+dMv3mz0M6gvfOj+FyKptit1/tlRo5XC+UbUi3AV8zL7vcLXM0iQRC\r\nChyLefmj+hfv+qEaEN/gssGV61wMBZc7NT4YiE3bbL8kiY3Ivdifezk6JKDV39Hz\r\nShqX9qZveh+wkKmzrAE5kdNht2TxPlc4A6/OetK1kPWu3DmZ1bY8l+2myxbHfWsq\r\nTJCU5kxU/R7NIOzOaJyHWOlhYL7rDsnVGX2f6Xi9DqwhdQePqW7gjGoqa5zj52W8\r\nvC08bdwE3GdFNjKvBIG8qABuYUyVxVzUjo6fL8EydL29EWUDB83vt14CV9qG1Boo\r\nNK+ISbLPpd2CVm9oqhTiWVT+/+ru7+qScCJggeMlI8CfzA9JsjWqWMM6w9kWlBA=\r\n-----END CERTIFICATE-----\r\n"
  },
  {
    "path": "tools/build-libfuse.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nif not X%1==X set Config=%1\r\nif not X%2==X set Arch=%2\r\nif not X%3==X set DESTDIR=%3\r\n\r\nif X!Config!==X (echo usage: build-libfuse Config Arch [DestDir] >&2 & goto fail)\r\n\r\nif X!Config!==XDebug set Buildtype=debug\r\nif X!Config!==XRelease set Buildtype=release\r\n\r\nrem ninja uses DESTDIR for installation\r\nif not X!DESTDIR!==X (\r\n    if exist !DESTDIR! rmdir /s/q !DESTDIR!\r\n    mkdir !DESTDIR!\r\n    pushd !DESTDIR!\r\n    set DESTDIR=!cd!\r\n    popd\r\n)\r\n\r\nset vswhere=\"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\"\r\nfor /f \"usebackq tokens=*\" %%i in (`%vswhere% -find VC\\**\\vcvarsall.bat`) do (\r\n    call \"%%i\" !Arch!\r\n)\r\n\r\nrem workaround getting Cygwin's meson/ninja\r\nset PATH=C:\\Program Files\\Meson;%PATH%\r\n\r\ncd %~dp0..\\ext\\libfuse\r\nif exist build\\!Config!\\!Arch! rmdir /s/q build\\!Config!\\!Arch!\r\nmkdir build\\!Config!\\!Arch! && cd build\\!Config!\\!Arch!\r\n\r\nmeson --buildtype=!Buildtype! -D examples=false ..\\..\\..\r\nif errorlevel 1 goto fail\r\nninja\r\nif errorlevel 1 goto fail\r\nif not X!DestDir!==X (\r\n    ninja install\r\n    if errorlevel 1 goto fail\r\n    copy ..\\..\\..\\LGPL2.txt !DestDir!\\License.txt\r\n    if errorlevel 1 goto fail\r\n)\r\n\r\nrem The pkgconfig prefix in file !InstallDir!\\lib\\pkgconfig\\fuse3.pc\r\nrem is erroneously set as: prefix=c:/\r\nrem We should somehow set it to: prefix=${pcfiledir}/../..\r\n\r\nexit /b 0\r\n\r\n:fail\r\nexit /b 1\r\n"
  },
  {
    "path": "tools/build-lxdk.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nif not X%1==X set Config=%1\r\nif not X%2==X set DestDir=%2\r\n\r\nif X!Config!==X (echo usage: build-lxdk Config [DestDir] >&2 & goto fail)\r\n\r\nif not X!DestDir!==X (\r\n    if exist !DestDir! rmdir /s/q !DestDir!\r\n    mkdir !DestDir!\r\n    pushd !DestDir!\r\n    set DestDir=!cd!\r\n    popd\r\n)\r\n\r\ncd %~dp0..\r\ncall ext\\lxdk\\tools\\build.bat %Config%\r\nif !ERRORLEVEL! neq 0 goto :fail\r\n\r\nif not X!DestDir!==X (\r\n    copy %~dp0..\\ext\\lxdk\\build\\VStudio\\build\\%Config%\\lxdk-*.msi !DestDir!\r\n)\r\n\r\nexit /b 0\r\n\r\n:fail\r\nexit /b 1\r\n"
  },
  {
    "path": "tools/build-sample.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nif not X%1==X set Config=%1\r\nif not X%2==X set Arch=%2\r\nif not X%3==X set Sample=%3\r\nif not X%4==X set DestDir=%4\r\n\r\nif X!Sample!==X (echo usage: build-sample Config Arch Sample [DestDir] >&2 & goto fail)\r\n\r\nset SampleProj=\r\nfor /F \"tokens=1,2 delims=*\" %%k in (\"!Sample!\") do (\r\n    set Sample=%%k\r\n    set SampleProj=%%l\r\n)\r\n\r\nset SampleDir=%~dp0..\\tst\r\nif not exist \"!SampleDir!\\!Sample!\" (echo sample !Sample! not found >&2 & goto fail)\r\n\r\nif not X!DestDir!==X (\r\n    if exist !DestDir! rmdir /s/q !DestDir!\r\n    mkdir !DestDir!\r\n    cd !DestDir!\r\n    xcopy /s/e/q/y \"!SampleDir!\\!Sample!\" .\r\n) else (\r\n    cd \"!SampleDir!\\!Sample!\"\r\n)\r\n\r\nset vswhere=\"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\"\r\nfor /f \"usebackq tokens=*\" %%i in (`%vswhere% -find VC\\**\\vcvarsall.bat`) do (\r\n    call \"%%i\" x64\r\n)\r\n\r\nif exist build rmdir /s/q build\r\nif X!SampleProj!==X (\r\n    devenv \"!Sample!.sln\" /build \"!Config!|!Arch!\"\r\n) else (\r\n    devenv \"!Sample!.sln\" /build \"!Config!|!Arch!\" /project \"!SampleProj!\"\r\n)\r\nif !ERRORLEVEL! neq 0 goto :fail\r\n\r\nexit /b 0\r\n\r\n:fail\r\nexit /b 1\r\n"
  },
  {
    "path": "tools/build-winfsp.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nif not X%1==X set Config=%1\r\nif not X%2==X set DestDir=%2\r\n\r\nif X!Config!==X (echo usage: build-winfsp Config [DestDir] >&2 & goto fail)\r\n\r\nif not X!DestDir!==X (\r\n    if exist !DestDir! rmdir /s/q !DestDir!\r\n    mkdir !DestDir!\r\n    pushd !DestDir!\r\n    set DestDir=!cd!\r\n    popd\r\n)\r\n\r\nset vswhere=\"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\"\r\nfor /f \"usebackq tokens=*\" %%i in (`%vswhere% -find VC\\**\\vcvarsall.bat`) do (\r\n    call \"%%i\" x64\r\n)\r\n\r\ncd %~dp0..\r\nset VS140COMNTOOLS=\r\ncall ext\\winfsp\\tools\\build.bat %Config%\r\nif !ERRORLEVEL! neq 0 goto :fail\r\n\r\nif not X!DestDir!==X (\r\n    copy %~dp0..\\ext\\winfsp\\build\\VStudio\\build\\%Config%\\winfsp-*.msi !DestDir!\r\n    copy %~dp0..\\ext\\winfsp\\build\\VStudio\\build\\%Config%\\winfsp-tests-x64.exe !DestDir!\r\n)\r\n\r\nexit /b 0\r\n\r\n:fail\r\nexit /b 1\r\n"
  },
  {
    "path": "tools/build.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nset MsiName=\"WinFuse - FUSE for the Windows kernel\"\r\nset CrossCert=\"%~dp0DigiCert High Assurance EV Root CA.crt\"\r\nset Issuer=\"DigiCert\"\r\nset Subject=\"Navimatics LLC\"\r\n\r\nset Configuration=Release\r\nset SignedPackage=\r\n\r\nif not X%1==X set Configuration=%1\r\nif not X%2==X set SignedPackage=%2\r\n\r\nset vswhere=\"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\"\r\nfor /f \"usebackq tokens=*\" %%i in (`%vswhere% -find VC\\**\\vcvarsall.bat`) do (\r\n    call \"%%i\" x64\r\n)\r\n\r\nif not X%SignedPackage%==X (\r\n    if not exist \"%~dp0..\\build\\VStudio\\build\\%Configuration%\\winfuse-*.msi\" (echo previous build not found >&2 & exit /b 1)\r\n    if not exist \"%SignedPackage%\" (echo signed package not found >&2 & exit /b 1)\r\n    del \"%~dp0..\\build\\VStudio\\build\\%Configuration%\\winfuse-*.msi\"\r\n    if exist \"%~dp0..\\build\\VStudio\\build\\%Configuration%\\winfuse.*.nupkg\" del \"%~dp0..\\build\\VStudio\\build\\%Configuration%\\winfuse.*.nupkg\"\r\n    for /R \"%SignedPackage%\" %%f in (*.sys) do (\r\n        copy \"%%f\" \"%~dp0..\\build\\VStudio\\build\\%Configuration%\" >nul\r\n    )\r\n)\r\n\r\ncd %~dp0..\\build\\VStudio\r\nset signfail=0\r\n\r\nif X%SignedPackage%==X (\r\n    if exist build\\ for /R build\\ %%d in (%Configuration%) do (\r\n        if exist \"%%d\" rmdir /s/q \"%%d\"\r\n    )\r\n\r\n    devenv winfuse.sln /build \"%Configuration%|x64\"\r\n    if errorlevel 1 goto fail\r\n    call %~dp0build-libfuse.bat %Configuration% x64 build\\%Configuration%\\libfuse\\x64\r\n    if errorlevel 1 goto fail\r\n\r\n    devenv winfuse.sln /build \"%Configuration%|x86\"\r\n    if errorlevel 1 goto fail\r\n    call %~dp0build-libfuse.bat %Configuration% x86 build\\%Configuration%\\libfuse\\x86\r\n    if errorlevel 1 goto fail\r\n\r\n    for %%f in (build\\%Configuration%\\winfuse-x64.sys build\\%Configuration%\\wslfuse-x64.sys build\\%Configuration%\\winfuse-x86.sys) do (\r\n        signtool sign /ac %CrossCert% /i %Issuer% /n %Subject% /fd sha1 /t http://timestamp.digicert.com %%f\r\n        if errorlevel 1 set /a signfail=signfail+1\r\n        signtool sign /as /ac %CrossCert% /i %Issuer% /n %Subject% /fd sha256 /tr http://timestamp.digicert.com /td sha256 %%f\r\n        if errorlevel 1 set /a signfail=signfail+1\r\n    )\r\n\r\n    pushd build\\%Configuration%\r\n    echo .OPTION EXPLICIT >driver.ddf\r\n    echo .Set CabinetFileCountThreshold=0 >>driver.ddf\r\n    echo .Set FolderFileCountThreshold=0 >>driver.ddf\r\n    echo .Set FolderSizeThreshold=0 >>driver.ddf\r\n    echo .Set MaxCabinetSize=0 >>driver.ddf\r\n    echo .Set MaxDiskFileCount=0 >>driver.ddf\r\n    echo .Set MaxDiskSize=0 >>driver.ddf\r\n    echo .Set CompressionType=MSZIP >>driver.ddf\r\n    echo .Set Cabinet=on >>driver.ddf\r\n    echo .Set Compress=on >>driver.ddf\r\n    echo .Set CabinetNameTemplate=driver.cab >>driver.ddf\r\n    echo .Set DiskDirectory1=. >>driver.ddf\r\n    echo .Set DestinationDir=x64 >>driver.ddf\r\n    echo winfuse-x64.inf >>driver.ddf\r\n    echo winfuse-x64.sys >>driver.ddf\r\n    echo wslfuse-x64.inf >>driver.ddf\r\n    echo wslfuse-x64.sys >>driver.ddf\r\n    echo .Set DestinationDir=x86 >>driver.ddf\r\n    echo winfuse-x86.inf >>driver.ddf\r\n    echo winfuse-x86.sys >>driver.ddf\r\n    makecab /F driver.ddf\r\n    signtool sign /ac %CrossCert% /i %Issuer% /n %Subject% /t http://timestamp.digicert.com driver.cab\r\n    if errorlevel 1 set /a signfail=signfail+1\r\n    popd\r\n)\r\n\r\ndevenv winfuse.sln /build \"Installer.%Configuration%|x64\"\r\nif errorlevel 1 goto fail\r\n\r\ndevenv winfuse.sln /build \"Installer.%Configuration%|x86\"\r\nif errorlevel 1 goto fail\r\n\r\nfor %%f in (build\\%Configuration%\\winfuse-*.msi) do (\r\n    signtool sign /ac %CrossCert% /i %Issuer% /n %Subject% /fd sha1 /t http://timestamp.digicert.com /d %MsiName% %%f\r\n    if errorlevel 1 set /a signfail=signfail+1\r\n    REM signtool sign /ac %CrossCert% /i %Issuer% /n %Subject% /fd sha256 /tr http://timestamp.digicert.com /td sha256 /d %MsiName% %%f\r\n    REM if errorlevel 1 set /a signfail=signfail+1\r\n)\r\n\r\nif not %signfail%==0 echo SIGNING FAILED! The product has been successfully built, but not signed.\r\n\r\nexit /b 0\r\n\r\n:fail\r\nexit /b 1\r\n"
  },
  {
    "path": "tools/debug.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\n\r\nset DebugWorkspace=winfuse\r\nset DebugPort=50000\r\nset DebugKey=1.1.1.1\r\n\r\nset RegKey=\"HKLM\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots\"\r\nset RegVal=\"KitsRoot10\"\r\nreg query %RegKey% /v %RegVal% >nul 2>&1 || (echo Cannot find Windows Kit >&2 & exit /b 1)\r\nfor /f \"tokens=2,*\" %%i in ('reg query %RegKey% /v %RegVal% ^| findstr %RegVal%') do (\r\n    set KitRoot=\"%%j\"\r\n)\r\nstart \"%DebugWorkspace%\" %KitRoot%\\Debuggers\\x64\\windbg -W %DebugWorkspace% -k net:port=%DebugPort%,key=%DebugKey%\r\n"
  },
  {
    "path": "tools/deploy.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nset Config=Debug\r\nset Suffix=x64\r\nset Deploy=C:\\Deploy\\winfuse\r\nset Target=Win10DBG\r\nset Chkpnt=winfuse\r\nif not X%1==X set Target=%1\r\nif not X%2==X set Chkpnt=%2\r\n\r\n(\r\n    echo sc create WinFsp type=filesys binPath=%%~dp0winfsp-%SUFFIX%.sys\r\n    echo sc create LxLdr type=kernel binPath=%%~dp0lxldr.sys\r\n    echo sc create WinFuse type=kernel binPath=%%~dp0winfuse-%SUFFIX%.sys\r\n    echo sc create WslFuse type=kernel binPath=%%~dp0wslfuse-%SUFFIX%.sys\r\n    echo reg add HKLM\\Software\\WinFsp\\Fsext /v 00093118 /d \"winfuse\" /f /reg:32\r\n    echo reg add HKLM\\Software\\LxDK\\Services\\wslfuse /v Depends /d \"winfsp\" /f\r\n    echo sc start winfsp\r\n    echo sc start lxldr\r\n) >%~dp0..\\build\\VStudio\\build\\%Config%\\deploy-setup.bat\r\n\r\n(set LF=^\r\n%=this line is empty=%\r\n)\r\n(\r\n    set /p =sudo mknod /dev/fuse c 10 229!LF!\r\n    set /p =sudo chmod a+w /dev/fuse!LF!\r\n    set /p =sudo cp fusermount.out /usr/bin/fusermount!LF!\r\n    set /p =sudo cp fusermount.out /usr/bin/fusermount3!LF!\r\n    set /p =sudo cp fusermount-helper.exe /usr/bin/fusermount-helper.exe!LF!\r\n    set /p =sudo chmod u+s /usr/bin/fusermount!LF!\r\n    set /p =sudo chmod u+s /usr/bin/fusermount3!LF!\r\n) <nul >%~dp0..\\build\\VStudio\\build\\%Config%\\deploy-setup.sh\r\n\r\nif exist %~dp0..\\ext\\winfsp\\build\\VStudio\\build\\%Config% (\r\n    set WINFSP=%~dp0..\\ext\\winfsp\\build\\VStudio\\build\\%Config%\\\r\n) else (\r\n    set RegKey=\"HKLM\\SOFTWARE\\WinFsp\"\r\n    set RegVal=\"InstallDir\"\r\n    reg query !RegKey! /v !RegVal! /reg:32 >nul 2>&1\r\n    if !ERRORLEVEL! equ 0 (\r\n        for /f \"tokens=2,*\" %%i in ('reg query !RegKey! /v !RegVal! /reg:32 ^| findstr !RegVal!') do (\r\n            set WINFSP=%%jbin\\\r\n        )\r\n    )\r\n    if not exist \"!WINFSP!\" (echo cannot find WinFsp installation >&2 & goto fail)\r\n)\r\n\r\nif exist %~dp0..\\ext\\lxdk\\build\\VStudio\\build\\%Config% (\r\n    set LXDK=%~dp0..\\ext\\lxdk\\build\\VStudio\\build\\%Config%\\\r\n) else (\r\n    set RegKey=\"HKLM\\SOFTWARE\\LxDK\"\r\n    set RegVal=\"InstallDir\"\r\n    reg query !RegKey! /v !RegVal! >nul 2>&1\r\n    if !ERRORLEVEL! equ 0 (\r\n        for /f \"tokens=2,*\" %%i in ('reg query !RegKey! /v !RegVal! ^| findstr !RegVal!') do (\r\n            set LXDK=%%jbin\\\r\n        )\r\n    )\r\n    if not exist \"!LXDK!\" (echo cannot find LxDK installation >&2 & goto fail)\r\n)\r\n\r\nset MEMFS_FUSE3_EXE=\r\nif exist %~dp0..\\tst\\memfs-fuse3\\build\\%Config%\\memfs-fuse3-x64.exe (\r\n    set MEMFS_FUSE3_EXE=memfs-fuse3-x64.exe fuse3-x64.dll\r\n)\r\nset MEMFS_FUSE3_OUT=\r\nif exist %~dp0..\\tst\\memfs-fuse3\\build\\%Config%\\memfs-fuse3.out (\r\n    set MEMFS_FUSE3_OUT=memfs-fuse3.out\r\n)\r\n\r\nset Files=\r\nfor %%f in (\r\n    %~dp0..\\build\\VStudio\\build\\%Config%\\\r\n        winfuse-%Suffix%.sys\r\n        wslfuse-%Suffix%.sys\r\n        winfuse-tests-%Suffix%.exe\r\n        wslfuse-tests.out\r\n        fusermount.out\r\n        fusermount-helper.exe\r\n        deploy-setup.bat\r\n        deploy-setup.sh\r\n    %~dp0..\\tst\\memfs-fuse3\\build\\%Config%\\\r\n        !MEMFS_FUSE3_EXE!\r\n        !MEMFS_FUSE3_OUT!\r\n    \"!WINFSP!\"\r\n        winfsp-%Suffix%.sys\r\n        winfsp-%Suffix%.dll\r\n    \"!LXDK!\"\r\n        lxldr.sys\r\n    ) do (\r\n    set File=%%~f\r\n    if [!File:~-1!] == [\\] (\r\n        set Dir=!File!\r\n    ) else (\r\n        if not [!Files!] == [] set Files=!Files!,\r\n        set Files=!Files!'!Dir!!File!'\r\n    )\r\n)\r\n\r\npowershell -NoProfile -ExecutionPolicy Bypass -Command \"& '%~dp0deploy.ps1' -Name '%Target%' -CheckpointName '%Chkpnt%' -Files !Files! -Destination '%Deploy%'\"\r\n"
  },
  {
    "path": "tools/deploy.ps1",
    "content": "param (\n    [Parameter(Mandatory)][string]$Name,\n    [string]$CheckpointName,\n    [Parameter(Mandatory)][string[]]$Files,\n    [Parameter(Mandatory)][string]$Destination\n)\n\nfunction Restore-VM ($Name, $CheckpointName) {\n    $VM = Get-VM -Name $Name\n    if ($VM.State -eq \"Running\") {\n        Stop-VM -Name $Name -TurnOff\n    }\n\n    if (-not $CheckpointName) {\n        $Checkpoint = Get-VMCheckpoint -VMName $Name |\n            Sort-Object -Property CreationTime -Descending |\n            select -First 1\n    } else {\n        $Checkpoint = Get-VMCheckpoint -VMName $Name -Name $CheckpointName\n    }\n    Restore-VMCheckpoint -VMCheckpoint $Checkpoint -Confirm:$false\n\n    Start-VM -Name $Name\n}\n\nfunction Deploy-VMFiles ($Name, $Files, $Destination) {\n    foreach ($File in $Files) {\n        $Leaf = Split-Path -Path $File -Leaf\n        $Dest = Join-Path $Destination $Leaf\n        Copy-VMFile -Name $Name -SourcePath $File -DestinationPath $Dest -FileSource Host -CreateFullPath -Force\n    }\n}\n\nRestore-VM -Name $Name -CheckpointName $CheckpointName\nDeploy-VMFiles -Name $Name -Files $Files -Destination $Destination\n"
  },
  {
    "path": "tools/gensrc/errno.sh",
    "content": "#!/bin/bash\n\n# run from Cygwin!\n\ngensrc() {\n    echo \"#if FUSE_ERRNO == 87 /* Windows */\"\n    echo\n    vcvars=\"$(/mnt/c/Program\\ Files\\ \\(x86\\)/Microsoft\\ Visual\\ Studio/Installer/vswhere.exe -latest -find 'VC\\**\\vcvarsall.bat')\"\n    cmd /c \"call\" \"$vcvars\" \"x64\" \"&&\" cl /nologo /EP /C errno.src 2>/dev/null | sed -e '1,/beginbeginbeginbegin/d' -e 's/\\r$//'\n    echo\n    echo \"#elif FUSE_ERRNO == 67 /* Cygwin */\"\n    echo\n    cpp -C -P errno.src | sed -e '1,/beginbeginbeginbegin/d'\n    echo\n    echo \"#elif FUSE_ERRNO == 76 /* Linux */\"\n    echo\n    # this produces very strange results without the intermediate file (GitHub microsoft/WSL#5063 ?)\n    wsl -- cpp -C -P errno.src \\| sed -e '1,/beginbeginbeginbegin/d' \\> errno.out\n    cat errno.out\n    echo\n    echo \"#endif\"\n}\n\ncd $(dirname \"$0\")\npwd\n\n(\necho '#include <errno.h>'\necho '/*beginbeginbeginbegin*/'\nawk '{ printf \"case %s: return %s;\\n\", $1, $2 }' errno.txt\n) > errno.src\ngensrc > ../../src/shared/km/errno.i\n\n(\necho '#include <errno.h>'\necho '/*beginbeginbeginbegin*/'\nawk '{ printf \"case %s: return \\\"%s\\\";\\n\", $1, $1 }' errno.txt\n) > errno.src\ngensrc > ../../src/shared/km/errnosym.i\n\nrm errno.src errno.out\n"
  },
  {
    "path": "tools/gensrc/errno.txt",
    "content": "0               STATUS_SUCCESS\nEPERM           STATUS_ACCESS_DENIED\nENOENT          STATUS_OBJECT_NAME_NOT_FOUND\nESRCH           STATUS_PROCEDURE_NOT_FOUND\nEINTR           STATUS_CANCELLED\nEIO             STATUS_IO_DEVICE_ERROR\nENXIO           STATUS_FILE_INVALID\nE2BIG           STATUS_INSUFFICIENT_RESOURCES\nENOEXEC         STATUS_INVALID_IMAGE_FORMAT\nEBADF           STATUS_INVALID_HANDLE\nENOMEM          STATUS_INSUFFICIENT_RESOURCES\nEACCES          STATUS_ACCESS_DENIED\nEFAULT          STATUS_ACCESS_VIOLATION\nEBUSY           STATUS_DEVICE_BUSY\nEEXIST          STATUS_OBJECT_NAME_COLLISION\nEXDEV           STATUS_NOT_SAME_DEVICE\nENODEV          STATUS_NO_SUCH_DEVICE\nENOTDIR         STATUS_NOT_A_DIRECTORY\nEISDIR          STATUS_FILE_IS_A_DIRECTORY\nEINVAL          STATUS_INVALID_PARAMETER\nENFILE          STATUS_TOO_MANY_OPENED_FILES\nEMFILE          STATUS_TOO_MANY_OPENED_FILES\nEFBIG           STATUS_DISK_FULL \nENOSPC          STATUS_DISK_FULL\nESPIPE          STATUS_INVALID_PARAMETER\nEROFS           STATUS_MEDIA_WRITE_PROTECTED\nEMLINK          STATUS_TOO_MANY_LINKS\nEPIPE           STATUS_PIPE_BROKEN\nEDOM            STATUS_INVALID_PARAMETER\nERANGE          STATUS_INVALID_PARAMETER\nEDEADLK         STATUS_POSSIBLE_DEADLOCK \nENAMETOOLONG    STATUS_NAME_TOO_LONG\nENOLCK          STATUS_LOCK_NOT_GRANTED \nENOSYS          STATUS_INVALID_DEVICE_REQUEST\nENOTEMPTY       STATUS_DIRECTORY_NOT_EMPTY\nEILSEQ          STATUS_INVALID_PARAMETER\nEADDRINUSE      STATUS_ADDRESS_ALREADY_ASSOCIATED\nEALREADY        STATUS_CONNECTION_ACTIVE\nECANCELED       STATUS_CANCELLED\nECONNABORTED    STATUS_CONNECTION_ABORTED\nECONNREFUSED    STATUS_CONNECTION_REFUSED\nECONNRESET      STATUS_CONNECTION_RESET\nEHOSTUNREACH    STATUS_HOST_UNREACHABLE\nEISCONN         STATUS_CONNECTION_ACTIVE\nELOOP           STATUS_REPARSE_POINT_NOT_RESOLVED\nENETDOWN        STATUS_HOST_DOWN\nENETRESET       STATUS_CONNECTION_RESET\nENETUNREACH     STATUS_NETWORK_UNREACHABLE\nENOBUFS         STATUS_INSUFFICIENT_RESOURCES\nENODATA         STATUS_END_OF_FILE\nENOLINK         STATUS_CONNECTION_INVALID\nENOTCONN        STATUS_CONNECTION_INVALID\nENOTSOCK        STATUS_INVALID_HANDLE\nETIMEDOUT       STATUS_TRANSACTION_TIMED_OUT\n"
  },
  {
    "path": "tools/ioc.c",
    "content": "///usr/bin/gcc -o /tmp/ioc.$$ \"$0\"; /tmp/ioc.$$ \"$@\"; rm /tmp/ioc.$$; exit\n\n// usage: sh ioc.c dir typ num siz\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys/ioctl.h>\n\nint main(int argc, char *argv[])\n{\n    unsigned dir, typ, num, siz;\n\n    if (5 != argc)\n    {\n        fprintf(stderr, \"usage: sh ioc.c dir typ num siz\\n\");\n        exit(2);\n    }\n\n    dir = strtoul(argv[1], 0, 0);\n    typ = strtoul(argv[2], 0, 0);\n    num = strtoul(argv[3], 0, 0);\n    siz = strtoul(argv[4], 0, 0);\n\n    printf(\n        \"dir=%u typ=%u num=%u siz=%u\\n\"\n        \"ioc=0x%08x\\n\",\n        dir, typ, num, siz,\n        _IOC(dir, typ, num, siz));\n\n    return 0;\n}\n"
  },
  {
    "path": "tools/license-headers/fix.ps1",
    "content": "#!/usr/bin/env powershell\n\nparam (\n    [Parameter(Mandatory=$true)][string]$srcfile,\n    [string]$dstfile = $srcfile\n)\n\n$content = Get-Content -Raw $srcfile\n$fileext = [System.IO.Path]::GetExtension($srcfile)\n$lichead = Get-Content -Raw \"$PSScriptRoot\\header$fileext\"\n$content = $content -replace \"(?sm)/\\*((?!\\*/).)*This file is part of((?!\\*/).)*\\*/\", $lichead\nSet-Content -Path $dstfile -NoNewline -Value $content\n"
  },
  {
    "path": "tools/license-headers/header.c",
    "content": "/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */"
  },
  {
    "path": "tools/license-headers/header.cpp",
    "content": "/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */"
  },
  {
    "path": "tools/license-headers/header.h",
    "content": "/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */"
  },
  {
    "path": "tools/nmake-ext-test.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nset vswhere=\"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe\"\r\nfor /f \"usebackq tokens=*\" %%i in (`%vswhere% -find VC\\**\\vcvarsall.bat`) do (\r\n    call \"%%i\" x64\r\n)\r\n\r\ncd %~dp0..\\ext\\winfsp\\ext\\test\r\nnmake /f Nmakefile\r\n"
  },
  {
    "path": "tools/run-tests.bat",
    "content": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nset Configuration=Release\r\nif not X%1==X set Configuration=%1\r\n\r\ncd %~dp0..\r\nset ProjRoot=%cd%\r\n\r\ncd build\\VStudio\r\nif not exist build\\%Configuration% echo === No tests found >&2 & goto fail\r\ncd build\\%Configuration%\r\n\r\nset dfl_tests=^\r\n    winfuse-tests-x64 ^\r\n    winfuse-tests-x86 ^\r\n    wslfuse-tests\r\nset opt_tests=^\r\n    sample-build-memfs-fuse3-x64 ^\r\n    sample-test0-memfs-fuse3-x64 ^\r\n    sample-test1-memfs-fuse3-x64 ^\r\n    sample-testinf-memfs-fuse3-x64 ^\r\n    sample-fsx0-memfs-fuse3-x64 ^\r\n    sample-fsx1-memfs-fuse3-x64 ^\r\n    sample-fsxinf-memfs-fuse3-x64 ^\r\n    sample-build-memfs-fuse3-x86 ^\r\n    sample-test0-memfs-fuse3-x86 ^\r\n    sample-test1-memfs-fuse3-x86 ^\r\n    sample-testinf-memfs-fuse3-x86 ^\r\n    sample-fsx0-memfs-fuse3-x86 ^\r\n    sample-fsx1-memfs-fuse3-x86 ^\r\n    sample-fsxinf-memfs-fuse3-x86 ^\r\n    sample-build-memfs-fuse3-wsl\r\n\r\nREM disable WSL tests that do not pass on AppVeyor (because it uses old Windows/WSL build)\r\nREM sample-test0-memfs-fuse3-wsl ^\r\nREM sample-test1-memfs-fuse3-wsl ^\r\nREM sample-testinf-memfs-fuse3-wsl ^\r\nREM sample-fsx0-memfs-fuse3-wsl ^\r\nREM sample-fsx1-memfs-fuse3-wsl ^\r\nREM sample-fsxinf-memfs-fuse3-wsl\r\n\r\nset tests=\r\nfor %%f in (%dfl_tests%) do (\r\n    if X%2==X (\r\n        set tests=!tests! %%f\r\n    ) else (\r\n        set test=%%f\r\n        if not \"X!test:%2=!\"==\"X!test!\" set tests=!tests! %%f\r\n    )\r\n)\r\nfor %%f in (%opt_tests%) do (\r\n    if X%2==X (\r\n        rem\r\n    ) else (\r\n        set test=%%f\r\n        if not \"X!test:%2=!\"==\"X!test!\" set tests=!tests! %%f\r\n    )\r\n)\r\n\r\nset testpass=0\r\nset testfail=0\r\nfor %%f in (%tests%) do (\r\n    echo === Running %%f\r\n\r\n    if defined APPVEYOR (\r\n        appveyor AddTest \"%%f\" -FileName None -Framework None -Outcome Running\r\n    )\r\n\r\n    pushd %cd%\r\n    call :%%f\r\n    popd\r\n\r\n    if !ERRORLEVEL! neq 0 (\r\n        set /a testfail=testfail+1\r\n\r\n        echo === Failed %%f\r\n\r\n        if defined APPVEYOR (\r\n            appveyor UpdateTest \"%%f\" -FileName None -Framework None -Outcome Failed -Duration 0\r\n        )\r\n    ) else (\r\n        set /a testpass=testpass+1\r\n\r\n        echo === Passed %%f\r\n\r\n        if defined APPVEYOR (\r\n            appveyor UpdateTest \"%%f\" -FileName None -Framework None -Outcome Passed -Duration 0\r\n        )\r\n    )\r\n    echo:\r\n)\r\n\r\nset /a total=testpass+testfail\r\necho === Total: %testpass%/%total%\r\ncall :leak-test\r\nif !ERRORLEVEL! neq 0 goto fail\r\nif not %testfail%==0 goto fail\r\n\r\nexit /b 0\r\n\r\n:fail\r\nexit /b 1\r\n\r\n:winfuse-tests-x64\r\nwinfuse-tests-x64 +*\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:winfuse-tests-x86\r\nwinfuse-tests-x86 +*\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:wslfuse-tests\r\nwsl -- sudo mknod /dev/fuse c 10 229; sudo ./wslfuse-tests.out\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-build-memfs-fuse3-x64\r\ncall :__run_sample_build memfs-fuse3 memfs-fuse3.exe x64\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-build-memfs-fuse3-x86\r\ncall :__run_sample_build memfs-fuse3 memfs-fuse3.exe x86\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-build-memfs-fuse3-wsl\r\ncall :__run_sample_build memfs-fuse3 memfs-fuse3.out x64\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:__run_sample_build\r\ncall %ProjRoot%\\tools\\build-sample.bat %Configuration% %3 %1*%2 \"%TMP%\\%1\"\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-test0-memfs-fuse3-x64\r\ncall :__run_sample_test memfs-fuse3 x64 0\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-test1-memfs-fuse3-x64\r\ncall :__run_sample_test memfs-fuse3 x64 1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-testinf-memfs-fuse3-x64\r\ncall :__run_sample_test memfs-fuse3 x64 -1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-test0-memfs-fuse3-x86\r\ncall :__run_sample_test memfs-fuse3 x86 0\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-test1-memfs-fuse3-x86\r\ncall :__run_sample_test memfs-fuse3 x86 1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-testinf-memfs-fuse3-x86\r\ncall :__run_sample_test memfs-fuse3 x86 -1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:__run_sample_test\r\nset TestExit=0\r\nstart \"\" /b \"%TMP%\\%1\\build\\%Configuration%\\%1-%2.exe\" -oFileInfoTimeout=%3 L:\r\nwaitfor 7BF47D72F6664550B03248ECFE77C7DD /t 3 2>nul\r\npushd >nul\r\ncd L: >nul 2>nul || (echo Unable to find drive L: >&2 & goto fail)\r\nL:\r\n\"C:\\Program Files (x86)\\WinFsp\\bin\\winfsp-tests-x64.exe\" ^\r\n    --external --resilient ^\r\n    create_test create_related_test create_sd_test create_notraverse_test create_backup_test ^\r\n    create_restore_test create_share_test create_curdir_test create_namelen_test ^\r\n    getfileinfo_test delete_test delete_pending_test delete_mmap_test delete_standby_test ^\r\n    rename_* ^\r\n    getvolinfo_test ^\r\n    getsecurity_test ^\r\n    rdwr_* ^\r\n    flush_* ^\r\n    lock_* ^\r\n    querydir_* ^\r\n    dirnotify_test ^\r\n    exec_*\r\nif !ERRORLEVEL! neq 0 set TestExit=1\r\npopd\r\ntaskkill /f /im %1-%2.exe\r\nexit /b !TestExit!\r\n\r\n:sample-fsx0-memfs-fuse3-x64\r\ncall :__run_sample_fsx_test memfs-fuse3 x64 0\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-fsx1-memfs-fuse3-x64\r\ncall :__run_sample_fsx_test memfs-fuse3 x64 1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-fsxinf-memfs-fuse3-x64\r\ncall :__run_sample_fsx_test memfs-fuse3 x64 -1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-fsx0-memfs-fuse3-x86\r\ncall :__run_sample_fsx_test memfs-fuse3 x86 0\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-fsx1-memfs-fuse3-x86\r\ncall :__run_sample_fsx_test memfs-fuse3 x86 1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-fsxinf-memfs-fuse3-x86\r\ncall :__run_sample_fsx_test memfs-fuse3 x86 -1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:__run_sample_fsx_test\r\nset TestExit=0\r\nstart \"\" /b \"%TMP%\\%1\\build\\%Configuration%\\%1-%2.exe\" -oFileInfoTimeout=%3 L:\r\nwaitfor 7BF47D72F6664550B03248ECFE77C7DD /t 3 2>nul\r\npushd >nul\r\ncd L: >nul 2>nul || (echo Unable to find drive L: >&2 & goto fail)\r\nL:\r\n\"%ProjRoot%\\ext\\winfsp\\ext\\test\\fstools\\src\\fsx\\fsx.exe\" -N 5000 test xxxxxx\r\nif !ERRORLEVEL! neq 0 set TestExit=1\r\npopd\r\ntaskkill /f /im %1-%2.exe\r\nexit /b !TestExit!\r\n\r\n:sample-test0-memfs-fuse3-wsl\r\ncall :__run_sample_wsl_test memfs-fuse3 0\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-test1-memfs-fuse3-wsl\r\ncall :__run_sample_wsl_test memfs-fuse3 1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-testinf-memfs-fuse3-wsl\r\ncall :__run_sample_wsl_test memfs-fuse3 -1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:__run_sample_wsl_test\r\nset TestExit=0\r\nstart \"\" /b /d \"%TMP%\\%1\\build\\%Configuration%\" wsl -- sudo sh \"/mnt/c/Program Files/WinFuse/opt/wslfuse/install.sh\"; mkdir -p mnt; ./%1.out -f -ocontext=FileInfoTimeout=%2,context=Volume=L: mnt\r\nwaitfor 7BF47D72F6664550B03248ECFE77C7DD /t 10 2>nul\r\npushd >nul\r\ncd L: >nul 2>nul || (echo Unable to find drive L: >&2 & goto fail)\r\nL:\r\n\"C:\\Program Files (x86)\\WinFsp\\bin\\winfsp-tests-x64.exe\" ^\r\n    --external --resilient ^\r\n    create_test create_related_test create_sd_test create_notraverse_test create_backup_test ^\r\n    create_restore_test create_share_test create_curdir_test create_namelen_test ^\r\n    getfileinfo_test delete_test delete_pending_test delete_mmap_test delete_standby_test ^\r\n    rename_* ^\r\n    getvolinfo_test ^\r\n    getsecurity_test ^\r\n    rdwr_* ^\r\n    flush_* ^\r\n    lock_* ^\r\n    querydir_* ^\r\n    dirnotify_test ^\r\n    exec_*\r\nif !ERRORLEVEL! neq 0 set TestExit=1\r\npopd\r\nstart \"\" /b /d \"%TMP%\\%1\\build\\%Configuration%\" wsl -- fusermount3 -u mnt\r\nexit /b !TestExit!\r\n\r\n:sample-fsx0-memfs-fuse3-wsl\r\ncall :__run_sample_fsx_wsl_test memfs-fuse3 0\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-fsx1-memfs-fuse3-wsl\r\ncall :__run_sample_fsx_wsl_test memfs-fuse3 1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:sample-fsxinf-memfs-fuse3-wsl\r\ncall :__run_sample_fsx_wsl_test memfs-fuse3 -1\r\nif !ERRORLEVEL! neq 0 goto fail\r\nexit /b 0\r\n\r\n:__run_sample_fsx_wsl_test\r\nset TestExit=0\r\nstart \"\" /b /d \"%TMP%\\%1\\build\\%Configuration%\" wsl -- sudo sh \"/mnt/c/Program Files/WinFuse/opt/wslfuse/install.sh\"; mkdir -p mnt; ./%1.out -f -ocontext=FileInfoTimeout=%2,context=Volume=L: mnt\r\nwaitfor 7BF47D72F6664550B03248ECFE77C7DD /t 10 2>nul\r\npushd >nul\r\ncd L: >nul 2>nul || (echo Unable to find drive L: >&2 & goto fail)\r\nL:\r\n\"%ProjRoot%\\ext\\winfsp\\ext\\test\\fstools\\src\\fsx\\fsx.exe\" -N 5000 test xxxxxx\r\nif !ERRORLEVEL! neq 0 set TestExit=1\r\npopd\r\nstart \"\" /b /d \"%TMP%\\%1\\build\\%Configuration%\" wsl -- fusermount3 -u mnt\r\nexit /b !TestExit!\r\n\r\n:leak-test\r\nrem wait a bit to avoid reporting lingering allocations\r\nwaitfor 7BF47D72F6664550B03248ECFE77C7DD /t 3 2>nul\r\nfor /F \"tokens=1,2 delims=:\" %%i in ('verifier /query ^| findstr ^\r\n    /c:\"Current Pool Allocations:\" ^\r\n    /c:\"CurrentPagedPoolAllocations:\" ^\r\n    /c:\"CurrentNonPagedPoolAllocations:\"'\r\n    ) do (\r\n\r\n    set FieldName=%%i\r\n    set FieldName=!FieldName: =!\r\n\r\n    set FieldValue=%%j\r\n    set FieldValue=!FieldValue: =!\r\n    set FieldValue=!FieldValue:^(=!\r\n    set FieldValue=!FieldValue:^)=!\r\n\r\n    if X!FieldName!==XCurrentPoolAllocations (\r\n        for /F \"tokens=1,2 delims=/\" %%k in (\"!FieldValue!\") do (\r\n            set NonPagedAlloc=%%k\r\n            set PagedAlloc=%%l\r\n        )\r\n    ) else if X!FieldName!==XCurrentPagedPoolAllocations (\r\n        set PagedAlloc=!FieldValue!\r\n    ) else if X!FieldName!==XCurrentNonPagedPoolAllocations (\r\n        set NonPagedAlloc=!FieldValue!\r\n    )\r\n)\r\nset /A TotalAlloc=PagedAlloc+NonPagedAlloc\r\nif !TotalAlloc! equ 0 (\r\n    echo === Leaks: None\r\n) else (\r\n    echo === Leaks: !NonPagedAlloc! NP / !PagedAlloc! P\r\n    goto fail\r\n)\r\nexit /b 0\r\n"
  },
  {
    "path": "tst/lockdly/lockdly.c",
    "content": "/*\n * Description:\n *     On debug builds of the WinFuse driver, when the special file \\$LOCKDLY is created/opened\n *     an artificial delay is introduced. This allows enough time for forcible termination of the\n *     file system (e.g. using Ctrl-C). If using non-alertable locks (kernel ERESOURCE) then the\n *     file system process should become unkillable and the lockdly.exe process should hang. If our\n *     custom implementation of alertable read-write locks (using semaphores and alertable waits)\n *     is used, then this should not happen.\n *\n * Compile:\n *     - cl lockdly.c\n *\n * Reproduce:\n *     - lockdly.exe\n *     - Quickly kill the file system process (e.g. switch to its command windows and Ctrl-C).\n *\n * Correct behavior:\n *     - Normal program termination.\n *\n * Incorrect behavior:\n *     - File system process and/or lockdly.exe process hang and become unkillable.\n */\n\n#include <windows.h>\n\nDWORD WINAPI ThreadProc(PVOID Param)\n{\n    HANDLE Handle = CreateFileW(\n        L\"$LOCKDLY\",\n        GENERIC_READ | GENERIC_WRITE,\n        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,\n        0,\n        CREATE_ALWAYS,\n        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE,\n        0);\n    if (INVALID_HANDLE_VALUE == Handle)\n        return 1;\n    \n    return 0;\n}\n\nint wmain(int argc, wchar_t *argv[])\n{\n    HANDLE Thread = CreateThread(0, 0, ThreadProc, 0, 0, 0);\n    if (0 == Thread)\n        return 1;\n    \n    Sleep(1000);\n    \n    HANDLE Handle = CreateFileW(\n        L\"$LOCKDLY\",\n        GENERIC_READ | GENERIC_WRITE,\n        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,\n        0,\n        OPEN_EXISTING,\n        0,\n        0);\n    if (INVALID_HANDLE_VALUE == Handle)\n        return 1;\n\n    WaitForSingleObject(Thread, INFINITE);\n\n    DWORD ExitCode;\n    GetExitCodeThread(Thread, &ExitCode);\n    return ExitCode;\n}\n"
  },
  {
    "path": "tst/memfs-fuse3/.gitignore",
    "content": "build\n*.ncb\n*.suo\n*.vcproj.*\n*.vcxproj.user\n*.VC.db\n*.VC.opendb\n.vs\n*.exe\n*.install\n"
  },
  {
    "path": "tst/memfs-fuse3/compat.h",
    "content": "/**\n * @file compat.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#ifndef COMPAT_H_INCLUDED\n#define COMPAT_H_INCLUDED\n\n#if defined(_WIN32) && defined(FSP_FUSE_SYM)\n#include <winfsp/winfsp.h>\n#undef fuse_main\n#define fuse_main(argc, argv, ops, data)\\\n    (FspLoad(0), fuse_main_real(argc, argv, ops, sizeof *(ops), data))\n#endif\n\n#if !defined(_WIN32) && !defined(fuse_stat)\n\ntypedef uint64_t fuse_ino_t;\n\n#define fuse_uid_t                      uid_t\n#define fuse_gid_t                      gid_t\n#define fuse_pid_t                      pid_t\n\n#define fuse_dev_t                      dev_t\n#define fuse_mode_t                     mode_t\n#define fuse_nlink_t                    nlink_t\n#define fuse_off_t                      off_t\n\n#define fuse_fsblkcnt_t                 fsblkcnt_t\n#define fuse_fsfilcnt_t                 fsfilcnt_t\n#define fuse_blksize_t                  blksize_t\n#define fuse_blkcnt_t                   blkcnt_t\n\n#define fuse_timespec                   timespec\n\n#define fuse_stat                       stat\n\n#define fuse_statvfs                    statvfs\n\n#define fuse_flock                      flock\n\n#define fuse_iovec                      iovec\n\n#endif\n\n#if !defined(S_IFMT)\n#define S_IFMT                          0170000\n#endif\n#if !defined(S_IFDIR)\n#define S_IFDIR                         0040000\n#endif\n#if !defined(S_IFCHR)\n#define S_IFCHR                         0020000\n#endif\n#if !defined(S_IFBLK)\n#define S_IFBLK                         0060000\n#endif\n#if !defined(S_IFREG)\n#define S_IFREG                         0100000\n#endif\n#if !defined(S_IFLNK)\n#define S_IFLNK                         0120000\n#endif\n#if !defined(S_IFSOCK)\n#define S_IFSOCK                        0140000\n#endif\n#if !defined(S_IFIFO)\n#define S_IFIFO                         0010000\n#endif\n\n#if defined(__APPLE__)\n#define st_atim                         st_atimespec\n#define st_ctim                         st_ctimespec\n#define st_mtim                         st_mtimespec\n#endif\n\n#if defined(__APPLE__) || defined(__linux__) || defined(__CYGWIN__)\n#include <sys/xattr.h>\n#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(_WIN32)\n#define XATTR_CREATE                    1\n#define XATTR_REPLACE                   2\n#endif\n\n#if !defined(ENOATTR)\n#define ENOATTR                         ENODATA\n#elif !defined(ENODATA)\n#define ENODATA                         ENOATTR\n#endif\n\n#endif\n"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.cpp",
    "content": "/**\n * @file memfs-fuse3.cpp\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <cerrno>\n#include <chrono>\n#include <cstring>\n#include <algorithm>\n#include <memory>\n#include <mutex>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include <fuse.h>\n#include \"compat.h\"\n\nclass memfs\n{\npublic:\n    memfs() : _ino(1), _root(std::make_shared<node_t>(_ino, S_IFDIR | 00777, 0, 0))\n    {\n    }\n\n    int main(int argc, char *argv[])\n    {\n        static fuse_operations ops =\n        {\n            getattr,\n            readlink,\n            mknod,\n            mkdir,\n            unlink,\n            rmdir,\n            symlink,\n            rename,\n            link,\n            chmod,\n            chown,\n            truncate,\n            open,\n            read,\n            write,\n            statfs,\n            flush,\n            release,\n            0, // fsync\n            setxattr,\n            getxattr,\n            listxattr,\n            removexattr,\n            opendir,\n            readdir,\n            releasedir,\n            0, // fsyncdir\n            init,\n            0, // destroy\n            0, // access\n            0, // create\n            0, // lock\n            utimens,\n            0, // bmap\n#if 0\n            ioctl,\n#endif\n        };\n        return fuse_main(argc, argv, &ops, this);\n    }\n\nprivate:\n    struct node_t\n    {\n        node_t(fuse_ino_t ino, fuse_mode_t mode, fuse_uid_t uid, fuse_gid_t gid, fuse_dev_t dev = 0)\n            : stat()\n        {\n            stat.st_ino = ino;\n            stat.st_mode = mode;\n            stat.st_nlink = 1;\n            stat.st_uid = uid;\n            stat.st_gid = gid;\n            stat.st_rdev = dev;\n            stat.st_atim = stat.st_mtim = stat.st_ctim = now();\n        }\n\n        void resize(size_t size, bool capacity)\n        {\n            if (capacity)\n            {\n                const size_t unit = 64 * 1024;\n                size_t newcap = (size + unit - 1) / unit * unit;\n                size_t oldcap = data.capacity();\n                if (newcap > oldcap)\n                    data.reserve(newcap);\n                else if (newcap < oldcap)\n                {\n                    data.resize(newcap);\n                    data.shrink_to_fit();\n                }\n            }\n            data.resize(size);\n            stat.st_size = size;\n        }\n\n        struct fuse_stat stat;\n        std::vector<uint8_t> data;\n        std::unordered_map<std::string, std::shared_ptr<node_t>> childmap;\n        std::unordered_map<std::string, std::vector<uint8_t>> xattrmap;\n    };\n\n    static fuse_timespec now()\n    {\n        using namespace std::chrono;\n        auto now = system_clock::now();\n        auto sec = floor<seconds>(now);\n        auto nsec = floor<nanoseconds>(now) - floor<nanoseconds>(sec);\n        return fuse_timespec\n        {\n            static_cast<decltype(fuse_timespec::tv_sec)>(sec.time_since_epoch().count()),\n                /* std::chrono epoch is UNIX epoch in C++20 */\n            static_cast<decltype(fuse_timespec::tv_nsec)>(nsec.count()),\n        };\n    }\n\n    static memfs *getself()\n    {\n        return static_cast<memfs *>(fuse_get_context()->private_data);\n    }\n\n    static int getattr(const char *path, struct fuse_stat *stbuf, struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path, fi);\n        if (!node)\n            return -ENOENT;\n        *stbuf = node->stat;\n        return 0;\n    }\n\n    static int readlink(const char *path, char *buf, size_t size)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path);\n        if (!node)\n            return -ENOENT;\n        if (S_IFLNK != (node->stat.st_mode & S_IFMT))\n            return EINVAL;\n        size = (std::min)(size - 1, node->data.size());\n        std::memcpy(buf, node->data.data(), size);\n        buf[size] = '\\0';\n        return 0;\n    }\n\n    static int mknod(const char *path, fuse_mode_t mode, fuse_dev_t dev)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->make_node(path, mode, dev);\n    }\n\n    static int mkdir(const char *path, fuse_mode_t mode)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->make_node(path, S_IFDIR | (mode & 07777), 0);\n    }\n\n    static int unlink(const char *path)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->remove_node(path, false);\n    }\n\n    static int rmdir(const char *path)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->remove_node(path, true);\n    }\n\n    static int symlink(const char *dstpath, const char *srcpath)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->make_node(srcpath, S_IFLNK | 00777, 0, dstpath);\n    }\n\n    static int rename(const char *oldpath, const char *newpath, unsigned int flags)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto oldlookup = self->lookup_node(oldpath);\n        auto oldprnt = std::get<0>(oldlookup);\n        auto oldname = std::get<1>(oldlookup);\n        auto oldnode = std::get<2>(oldlookup);\n        if (!oldnode)\n            return -ENOENT;\n        auto newlookup = self->lookup_node(newpath);\n        auto newprnt = std::get<0>(newlookup);\n        auto newname = std::get<1>(newlookup);\n        auto newnode = std::get<2>(newlookup);\n        if (!newprnt)\n            return -ENOENT;\n        if (newname.empty())\n            // guard against directory loop creation\n            return -EINVAL;\n        if (oldprnt == newprnt && oldname == newname)\n            return 0;\n        if (newnode)\n        {\n            if (int errc = self->remove_node(newpath, S_IFDIR == (oldnode->stat.st_mode & S_IFMT)))\n                return errc;\n        }\n        oldprnt->childmap.erase(oldname);\n        newprnt->childmap[newname] = oldnode;\n        return 0;\n    }\n\n    static int link(const char *oldpath, const char *newpath)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto oldlookup = self->lookup_node(oldpath);\n        auto oldnode = std::get<2>(oldlookup);\n        if (!oldnode)\n            return -ENOENT;\n        auto newlookup = self->lookup_node(newpath);\n        auto newprnt = std::get<0>(newlookup);\n        auto newname = std::get<1>(newlookup);\n        auto newnode = std::get<2>(newlookup);\n        if (!newprnt)\n            return -ENOENT;\n        if (newnode)\n            return -EEXIST;\n        oldnode->stat.st_nlink++;\n        newprnt->childmap[newname] = oldnode;\n        oldnode->stat.st_ctim = newprnt->stat.st_ctim = newprnt->stat.st_mtim = now();\n        return 0;\n    }\n\n    static int chmod(const char *path, fuse_mode_t mode,\n        struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path, fi);\n        if (!node)\n            return -ENOENT;\n        node->stat.st_mode = (node->stat.st_mode & S_IFMT) | (mode & 07777);\n        node->stat.st_ctim = now();\n        return 0;\n    }\n\n    static int chown(const char *path, fuse_uid_t uid, fuse_gid_t gid,\n        struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path, fi);\n        if (!node)\n            return -ENOENT;\n        if (-1 != uid)\n            node->stat.st_uid = uid;\n        if (-1 != gid)\n            node->stat.st_gid = gid;\n        node->stat.st_ctim = now();\n        return 0;\n    }\n\n    static int truncate(const char *path, fuse_off_t size,\n        struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path, fi);\n        if (!node)\n            return -ENOENT;\n        if (SIZE_MAX < size)\n            return -EFBIG;\n        node->resize(static_cast<size_t>(size), true);\n        node->stat.st_ctim = node->stat.st_mtim = now();\n        return 0;\n    }\n\n    static int open(const char *path, struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->open_node(path, false, fi);\n    }\n\n    static int read(const char *path, char *buf, size_t size, fuse_off_t off,\n        struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path, fi);\n        if (!node)\n            return -ENOENT;\n        fuse_off_t endoff = (std::min)(\n            off + static_cast<fuse_off_t>(size), static_cast<fuse_off_t>(node->data.size()));\n        if (off > endoff)\n            return 0;\n        std::memcpy(buf, node->data.data() + off, static_cast<int>(endoff - off));\n        node->stat.st_atim = now();\n        return static_cast<int>(endoff - off);\n    }\n\n    static int write(const char *path, const char *buf, size_t size, fuse_off_t off,\n        struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path, fi);\n        if (!node)\n            return -ENOENT;\n        fuse_off_t endoff = off + static_cast<fuse_off_t>(size);\n        if (SIZE_MAX < endoff)\n            return -EFBIG;\n        if (node->data.size() < endoff)\n            node->resize(static_cast<size_t>(endoff), true);\n        std::memcpy(node->data.data() + off, buf, static_cast<int>(endoff - off));\n        node->stat.st_ctim = node->stat.st_mtim = now();\n        return static_cast<int>(endoff - off);\n    }\n\n    static int statfs(const char *path, struct fuse_statvfs *stbuf)\n    {\n        std::memset(stbuf, 0, sizeof *stbuf);\n        return 0;\n    }\n\n    static int flush(const char *path, struct fuse_file_info *fi)\n    {\n        return -ENOSYS;\n    }\n\n    static int release(const char *path, struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->close_node(fi);\n    }\n\n    static int setxattr(const char *path, const char *name0, const char *value, size_t size,\n        int flags)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path);\n        if (!node)\n            return -ENOENT;\n        if (0 == std::strcmp(\"com.apple.ResourceFork\", name0))\n            return -ENOTSUP;\n        std::string name = name0;\n        if (XATTR_CREATE == flags)\n        {\n            if (node->xattrmap.end() != node->xattrmap.find(name))\n                return -EEXIST;\n        }\n        else if (XATTR_REPLACE == flags)\n        {\n            if (node->xattrmap.end() == node->xattrmap.find(name))\n                return -ENOATTR;\n        }\n        node->xattrmap[name].assign(value, value + size);\n        return 0;\n    }\n\n    static int getxattr(const char *path, const char *name0, char *value, size_t size)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path);\n        if (!node)\n            return -ENOENT;\n        if (0 == std::strcmp(\"com.apple.ResourceFork\", name0))\n            return -ENOTSUP;\n        std::string name = name0;\n        auto iter = node->xattrmap.find(name);\n        if (node->xattrmap.end() == iter)\n            return -ENOATTR;\n        if (0 != size)\n        {\n            if (iter->second.size() > size)\n                return -ERANGE;\n            std::memcpy(value, iter->second.data(), iter->second.size());\n        }\n        return static_cast<int>(iter->second.size());\n    }\n\n    static int listxattr(const char *path, char *namebuf, size_t size)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path);\n        if (!node)\n            return -ENOENT;\n        size_t copysize = 0;\n        for (auto elem : node->xattrmap)\n        {\n            size_t namesize = elem.first.size() + 1;\n            if (0 != size)\n            {\n                if (copysize + namesize > size)\n                    return -ERANGE;\n                std::memcpy(namebuf + copysize, elem.first.c_str(), namesize);\n                copysize += namesize;\n            }\n        }\n        return static_cast<int>(copysize);\n    }\n\n    static int removexattr(const char *path, const char *name0)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path);\n        if (!node)\n            return -ENOENT;\n        if (0 == std::strcmp(\"com.apple.ResourceFork\", name0))\n            return -ENOTSUP;\n        std::string name = name0;\n        return node->xattrmap.erase(name) ? 0 : -ENOATTR;\n    }\n\n    static int opendir(const char *path, struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->open_node(path, true, fi);\n    }\n\n    static int readdir(const char *path, void *buf, fuse_fill_dir_t filler, fuse_off_t off,\n        struct fuse_file_info *fi, enum fuse_readdir_flags)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path, fi);\n        if (!node)\n            return -ENOENT;\n        filler(buf, \".\", &node->stat, 0, FUSE_FILL_DIR_PLUS);\n        filler(buf, \"..\", nullptr, 0, FUSE_FILL_DIR_PLUS);\n        for (auto elem : node->childmap)\n            if (0 != filler(buf, elem.first.c_str(), &elem.second->stat, 0, FUSE_FILL_DIR_PLUS))\n                break;\n        return 0;\n    }\n\n    static int releasedir(const char *path, struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        return self->close_node(fi);\n    }\n\n    static void *init(struct fuse_conn_info *conn,\n        struct fuse_config *conf)\n    {\n        conn->want |= (conn->capable & FUSE_CAP_READDIRPLUS);\n        return getself();\n    }\n\n    static int utimens(const char *path, const struct fuse_timespec tmsp[2],\n        struct fuse_file_info *fi)\n    {\n        auto self = getself();\n        std::lock_guard<std::mutex> lock(self->_mutex);\n        auto node = self->get_node(path, fi);\n        if (!node)\n            return -ENOENT;\n        if (tmsp)\n        {\n            node->stat.st_ctim = now();\n            node->stat.st_atim = tmsp[0];\n            node->stat.st_mtim = tmsp[1];\n        }\n        else\n            node->stat.st_ctim = node->stat.st_atim = node->stat.st_mtim = now();\n        return 0;\n    }\n\n#if 0\n    static int ioctl(const char *path, int cmd, void *arg, struct fuse_file_info *fi,\n        unsigned int flags, void *data)\n    {\n        return -ENOSYS;\n    }\n#endif\n\n    std::tuple<std::shared_ptr<node_t>, std::string, std::shared_ptr<node_t>>\n        lookup_node(const char *path, node_t *ancestor = nullptr)\n    {\n        auto prnt = _root;\n        std::string name;\n        auto node = prnt;\n        for (const char *part = path, *p; *part; part = p + !!(*p))\n        {\n            for (p = part; *p && '/' != *p; p++)\n                ;\n            if (part == p)\n                continue;\n            prnt = node;\n            if (!node)\n                break;\n            name.assign(part, p);\n            auto iter = node->childmap.find(name);\n            node = node->childmap.end() != iter ? iter->second : nullptr;\n            if (ancestor && node.get() == ancestor)\n            {\n                name.assign(\"\"); // special case loop condition\n                break;\n            }\n        }\n        return std::make_tuple(prnt, name, node);\n    }\n\n    int make_node(const char *path, fuse_mode_t mode, fuse_dev_t dev, const char *data = nullptr)\n    {\n        auto lookup = lookup_node(path);\n        auto prnt = std::get<0>(lookup);\n        auto name = std::get<1>(lookup);\n        auto node = std::get<2>(lookup);\n        if (!prnt)\n            return -ENOENT;\n        if (node)\n            return -EEXIST;\n        fuse_context *context = fuse_get_context();\n        node = std::make_shared<node_t>(++_ino, mode, context->uid, context->gid, dev);\n        if (data)\n        {\n            node->resize(std::strlen(data), false);\n            std::memcpy(node->data.data(), data, node->data.size());\n        }\n        prnt->childmap[name] = node;\n        prnt->stat.st_ctim = prnt->stat.st_mtim = node->stat.st_ctim;\n        return 0;\n    }\n\n    int remove_node(const char *path, bool dir)\n    {\n        auto lookup = lookup_node(path);\n        auto prnt = std::get<0>(lookup);\n        auto name = std::get<1>(lookup);\n        auto node = std::get<2>(lookup);\n        if (!node)\n            return -ENOENT;\n        if (!dir && S_IFDIR == (node->stat.st_mode & S_IFMT))\n            return -EISDIR;\n        if (dir && S_IFDIR != (node->stat.st_mode & S_IFMT))\n            return -ENOTDIR;\n        if (0 < node->childmap.size())\n            return -ENOTEMPTY;\n        node->stat.st_nlink--;\n        prnt->childmap.erase(name);\n        node->stat.st_ctim = prnt->stat.st_ctim = prnt->stat.st_mtim = now();\n        return 0;\n    }\n\n    int open_node(const char *path, bool dir, struct fuse_file_info *fi)\n    {\n        auto node = std::get<2>(lookup_node(path));\n        if (!node)\n            return -ENOENT;\n        if (!dir && S_IFDIR == (node->stat.st_mode & S_IFMT))\n            return -EISDIR;\n        if (dir && S_IFDIR != (node->stat.st_mode & S_IFMT))\n            return -ENOTDIR;\n        // A file descriptor is a raw pointer to a shared_ptr.\n        // This has the effect of incrementing the shared_ptr\n        // refcount, thus keeping an open node around even\n        // if the node is unlinked.\n        fi->fh = (uint64_t)(uintptr_t)new std::shared_ptr<node_t>(node);\n        return 0;\n    }\n\n    int close_node(struct fuse_file_info *fi)\n    {\n        delete (std::shared_ptr<node_t> *)(uintptr_t)fi->fh;\n        return 0;\n    }\n\n    std::shared_ptr<node_t> get_node(const char *path, struct fuse_file_info *fi = nullptr)\n    {\n        if (!fi || !fi->fh)\n            return std::get<2>(lookup_node(path));\n        else\n            return *(std::shared_ptr<node_t> *)(uintptr_t)fi->fh;\n    }\n\nprivate:\n    std::mutex _mutex;\n    fuse_ino_t _ino;\n    std::shared_ptr<node_t> _root;\n};\n\nint main(int argc, char *argv[])\n{\n    return memfs().main(argc, argv);\n}\n"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.exe.vcxproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" ToolsVersion=\"14.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup Label=\"ProjectConfigurations\">\r\n    <ProjectConfiguration Include=\"Debug|Win32\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>Win32</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|Win32\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>Win32</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Debug|x64\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|x64\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n  </ItemGroup>\r\n  <PropertyGroup Label=\"Globals\">\r\n    <ProjectGuid>{CF538F42-C714-4653-B351-E72FD7B0B217}</ProjectGuid>\r\n    <Keyword>Win32Proj</Keyword>\r\n    <RootNamespace>memfsfuse3</RootNamespace>\r\n    <WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>\r\n    <WholeProgramOptimization>true</WholeProgramOptimization>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>\r\n    <WholeProgramOptimization>true</WholeProgramOptimization>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\r\n  <ImportGroup Label=\"ExtensionSettings\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"Shared\">\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Label=\"PropertySheets\" Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <PropertyGroup Label=\"UserMacros\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\r\n    <LinkIncremental>true</LinkIncremental>\r\n    <OutDir>$(SolutionDir)build\\$(Configuration)\\</OutDir>\r\n    <IntDir>$(SolutionDir)build\\$(ProjectName).build\\$(Configuration)\\$(PlatformTarget)\\</IntDir>\r\n    <TargetName>$(SolutionName)-$(PlatformTarget)</TargetName>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <LinkIncremental>true</LinkIncremental>\r\n    <OutDir>$(SolutionDir)build\\$(Configuration)\\</OutDir>\r\n    <IntDir>$(SolutionDir)build\\$(ProjectName).build\\$(Configuration)\\$(PlatformTarget)\\</IntDir>\r\n    <TargetName>$(SolutionName)-$(PlatformTarget)</TargetName>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\r\n    <LinkIncremental>false</LinkIncremental>\r\n    <OutDir>$(SolutionDir)build\\$(Configuration)\\</OutDir>\r\n    <IntDir>$(SolutionDir)build\\$(ProjectName).build\\$(Configuration)\\$(PlatformTarget)\\</IntDir>\r\n    <TargetName>$(SolutionName)-$(PlatformTarget)</TargetName>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <LinkIncremental>false</LinkIncremental>\r\n    <OutDir>$(SolutionDir)build\\$(Configuration)\\</OutDir>\r\n    <IntDir>$(SolutionDir)build\\$(ProjectName).build\\$(Configuration)\\$(PlatformTarget)\\</IntDir>\r\n    <TargetName>$(SolutionName)-$(PlatformTarget)</TargetName>\r\n  </PropertyGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\r\n    <ClCompile>\r\n      <PrecompiledHeader>\r\n      </PrecompiledHeader>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <Optimization>Disabled</Optimization>\r\n      <PreprocessorDefinitions>FUSE_USE_VERSION=32;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <AdditionalIncludeDirectories>C:\\Program Files\\WinFuse\\opt\\libfuse\\include\\fuse3</AdditionalIncludeDirectories>\r\n      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r\n      <DisableSpecificWarnings>4018</DisableSpecificWarnings>\r\n    </ClCompile>\r\n    <Link>\r\n      <SubSystem>Console</SubSystem>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n      <AdditionalDependencies>C:\\Program Files\\WinFuse\\opt\\libfuse\\lib\\fuse3-$(PlatformTarget).lib</AdditionalDependencies>\r\n      <DelayLoadDLLs>\r\n      </DelayLoadDLLs>\r\n    </Link>\r\n    <PostBuildEvent>\r\n      <Command>copy \"C:\\Program Files\\WinFuse\\opt\\libfuse\\bin\\fuse3-$(PlatformTarget).dll\" $(OutDir)\r\n</Command>\r\n    </PostBuildEvent>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <ClCompile>\r\n      <PrecompiledHeader>\r\n      </PrecompiledHeader>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <Optimization>Disabled</Optimization>\r\n      <PreprocessorDefinitions>FUSE_USE_VERSION=32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <AdditionalIncludeDirectories>C:\\Program Files\\WinFuse\\opt\\libfuse\\include\\fuse3</AdditionalIncludeDirectories>\r\n      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r\n      <DisableSpecificWarnings>4018</DisableSpecificWarnings>\r\n    </ClCompile>\r\n    <Link>\r\n      <SubSystem>Console</SubSystem>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n      <AdditionalDependencies>C:\\Program Files\\WinFuse\\opt\\libfuse\\lib\\fuse3-$(PlatformTarget).lib</AdditionalDependencies>\r\n      <DelayLoadDLLs>\r\n      </DelayLoadDLLs>\r\n    </Link>\r\n    <PostBuildEvent>\r\n      <Command>copy \"C:\\Program Files\\WinFuse\\opt\\libfuse\\bin\\fuse3-$(PlatformTarget).dll\" $(OutDir)\r\n</Command>\r\n    </PostBuildEvent>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\r\n    <ClCompile>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <PrecompiledHeader>\r\n      </PrecompiledHeader>\r\n      <Optimization>MaxSpeed</Optimization>\r\n      <FunctionLevelLinking>true</FunctionLevelLinking>\r\n      <IntrinsicFunctions>true</IntrinsicFunctions>\r\n      <PreprocessorDefinitions>FUSE_USE_VERSION=32;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <AdditionalIncludeDirectories>C:\\Program Files\\WinFuse\\opt\\libfuse\\include\\fuse3</AdditionalIncludeDirectories>\r\n      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r\n      <DisableSpecificWarnings>4018</DisableSpecificWarnings>\r\n    </ClCompile>\r\n    <Link>\r\n      <SubSystem>Console</SubSystem>\r\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r\n      <OptimizeReferences>true</OptimizeReferences>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n      <AdditionalDependencies>C:\\Program Files\\WinFuse\\opt\\libfuse\\lib\\fuse3-$(PlatformTarget).lib</AdditionalDependencies>\r\n      <DelayLoadDLLs>\r\n      </DelayLoadDLLs>\r\n    </Link>\r\n    <PostBuildEvent>\r\n      <Command>copy \"C:\\Program Files\\WinFuse\\opt\\libfuse\\bin\\fuse3-$(PlatformTarget).dll\" $(OutDir)\r\n</Command>\r\n    </PostBuildEvent>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <ClCompile>\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <PrecompiledHeader>\r\n      </PrecompiledHeader>\r\n      <Optimization>MaxSpeed</Optimization>\r\n      <FunctionLevelLinking>true</FunctionLevelLinking>\r\n      <IntrinsicFunctions>true</IntrinsicFunctions>\r\n      <PreprocessorDefinitions>FUSE_USE_VERSION=32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <SDLCheck>true</SDLCheck>\r\n      <AdditionalIncludeDirectories>C:\\Program Files\\WinFuse\\opt\\libfuse\\include\\fuse3</AdditionalIncludeDirectories>\r\n      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r\n      <DisableSpecificWarnings>4018</DisableSpecificWarnings>\r\n    </ClCompile>\r\n    <Link>\r\n      <SubSystem>Console</SubSystem>\r\n      <EnableCOMDATFolding>true</EnableCOMDATFolding>\r\n      <OptimizeReferences>true</OptimizeReferences>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n      <AdditionalDependencies>C:\\Program Files\\WinFuse\\opt\\libfuse\\lib\\fuse3-$(PlatformTarget).lib</AdditionalDependencies>\r\n      <DelayLoadDLLs>\r\n      </DelayLoadDLLs>\r\n    </Link>\r\n    <PostBuildEvent>\r\n      <Command>copy \"C:\\Program Files\\WinFuse\\opt\\libfuse\\bin\\fuse3-$(PlatformTarget).dll\" $(OutDir)\r\n</Command>\r\n    </PostBuildEvent>\r\n  </ItemDefinitionGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"compat.h\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"memfs-fuse3.cpp\" />\r\n  </ItemGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\r\n  <ImportGroup Label=\"ExtensionTargets\">\r\n  </ImportGroup>\r\n</Project>"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.exe.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup>\r\n    <Filter Include=\"Source\">\r\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\r\n      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\r\n    </Filter>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"compat.h\">\r\n      <Filter>Source</Filter>\r\n    </ClInclude>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"memfs-fuse3.cpp\">\r\n      <Filter>Source</Filter>\r\n    </ClCompile>\r\n  </ItemGroup>\r\n</Project>"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.out.vcxproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup Label=\"ProjectConfigurations\">\r\n    <ProjectConfiguration Include=\"Debug|x64\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|x64\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n  </ItemGroup>\r\n  <PropertyGroup Label=\"Globals\">\r\n    <ProjectGuid>{38ad1d24-7745-4b6e-9928-bd9731fed72a}</ProjectGuid>\r\n    <Keyword>Linux</Keyword>\r\n    <RootNamespace>memfs_fuse3_out</RootNamespace>\r\n    <MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion>\r\n    <ApplicationType>Linux</ApplicationType>\r\n    <ApplicationTypeRevision>1.0</ApplicationTypeRevision>\r\n    <TargetLinuxPlatform>Generic</TargetLinuxPlatform>\r\n    <LinuxProjectType>{2238F9CD-F817-4ECC-BD14-2524D2669B35}</LinuxProjectType>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>WSL_1_0</PlatformToolset>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>WSL_1_0</PlatformToolset>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\r\n  <ImportGroup Label=\"ExtensionSettings\" />\r\n  <ImportGroup Label=\"Shared\" />\r\n  <ImportGroup Label=\"PropertySheets\" />\r\n  <PropertyGroup Label=\"UserMacros\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <OutDir>$(SolutionDir)build\\$(Configuration)\\</OutDir>\r\n    <IntDir>$(SolutionDir)build\\$(ProjectName).build\\$(Configuration)\\$(PlatformTarget)\\</IntDir>\r\n    <TargetName>$(SolutionName)</TargetName>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <OutDir>$(SolutionDir)build\\$(Configuration)\\</OutDir>\r\n    <IntDir>$(SolutionDir)build\\$(ProjectName).build\\$(Configuration)\\$(PlatformTarget)\\</IntDir>\r\n    <TargetName>$(SolutionName)</TargetName>\r\n  </PropertyGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"memfs-fuse3.cpp\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"compat.h\" />\r\n  </ItemGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <ClCompile>\r\n      <AdditionalIncludeDirectories>/usr/include/fuse3;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r\n      <PreprocessorDefinitions>FUSE_USE_VERSION=32;</PreprocessorDefinitions>\r\n      <CppLanguageStandard>c++17</CppLanguageStandard>\r\n    </ClCompile>\r\n    <Link>\r\n      <LibraryDependencies>fuse3</LibraryDependencies>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <ClCompile>\r\n      <AdditionalIncludeDirectories>/usr/include/fuse3;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r\n      <PreprocessorDefinitions>FUSE_USE_VERSION=32;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <CppLanguageStandard>c++17</CppLanguageStandard>\r\n    </ClCompile>\r\n    <Link>\r\n      <LibraryDependencies>fuse3</LibraryDependencies>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\r\n  <ImportGroup Label=\"ExtensionTargets\" />\r\n</Project>"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.out.vcxproj.filters",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup>\r\n    <Filter Include=\"Source\">\r\n      <UniqueIdentifier>{642abec8-4756-443b-ac1f-3de5522812c2}</UniqueIdentifier>\r\n    </Filter>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"memfs-fuse3.cpp\">\r\n      <Filter>Source</Filter>\r\n    </ClCompile>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"compat.h\">\r\n      <Filter>Source</Filter>\r\n    </ClInclude>\r\n  </ItemGroup>\r\n</Project>"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.sln",
    "content": "﻿\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 16\r\nVisualStudioVersion = 16.0.30204.135\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"memfs-fuse3.exe\", \"memfs-fuse3.exe.vcxproj\", \"{CF538F42-C714-4653-B351-E72FD7B0B217}\"\r\nEndProject\r\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"memfs-fuse3.out\", \"memfs-fuse3.out.vcxproj\", \"{38AD1D24-7745-4B6E-9928-BD9731FED72A}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|x64 = Debug|x64\r\n\t\tDebug|x86 = Debug|x86\r\n\t\tRelease|x64 = Release|x64\r\n\t\tRelease|x86 = Release|x86\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x64.ActiveCfg = Debug|x64\r\n\t\t{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x64.Build.0 = Debug|x64\r\n\t\t{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x86.ActiveCfg = Debug|Win32\r\n\t\t{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x86.Build.0 = Debug|Win32\r\n\t\t{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x64.ActiveCfg = Release|x64\r\n\t\t{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x64.Build.0 = Release|x64\r\n\t\t{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x86.ActiveCfg = Release|Win32\r\n\t\t{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x86.Build.0 = Release|Win32\r\n\t\t{38AD1D24-7745-4B6E-9928-BD9731FED72A}.Debug|x64.ActiveCfg = Debug|x64\r\n\t\t{38AD1D24-7745-4B6E-9928-BD9731FED72A}.Debug|x86.ActiveCfg = Debug|x64\r\n\t\t{38AD1D24-7745-4B6E-9928-BD9731FED72A}.Release|x64.ActiveCfg = Release|x64\r\n\t\t{38AD1D24-7745-4B6E-9928-BD9731FED72A}.Release|x86.ActiveCfg = Release|x64\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {F8910224-C4C3-4B29-9EB9-AEBDDBFCC250}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  },
  {
    "path": "tst/winfuse-tests/coro-test.c",
    "content": "/**\n * @file coro-test.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <windows.h>\n#include <tlib/testsuite.h>\n#include <shared/km/coro.h>\n\nstatic void bprintf(char **b, const char *format, ...)\n{\n    va_list ap;\n    va_start(ap, format);\n    int len = wvsprintfA(*b, format, ap);\n    va_end(ap);\n    *b += len;\n}\n\nstatic int coro_break_dotest(int brk, short stack[8], char **b)\n{\n    coro_block (stack)\n    {\n        bprintf(b, \"%s\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_yield_dotest(int brk, short stack[8], char **b)\n{\n    coro_block (stack)\n    {\n        bprintf(b, \"%s:10\\n\", __FUNCTION__);\n        coro_yield;\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_loopyield_dotest(int brk, short stack[8], int *state, char **b)\n{\n    coro_block (stack)\n    {\n        while ((*state)++ < 3)\n        {\n            bprintf(b, \"%s:10:%d\\n\", __FUNCTION__, *state);\n            coro_yield;\n        }\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_await_break_dotest(int brk, short stack[8], char **b)\n{\n    coro_block (stack)\n    {\n        bprintf(b, \"%s:10\\n\", __FUNCTION__);\n        coro_await (coro_break_dotest(brk, stack, b));\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_await_yield_dotest(int brk, short stack[8], char **b)\n{\n    coro_block (stack)\n    {\n        bprintf(b, \"%s:10\\n\", __FUNCTION__);\n        coro_await (coro_yield_dotest(brk, stack, b));\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_await_loopyield_dotest(int brk, short stack[8], int *state, char **b)\n{\n    coro_block (stack)\n    {\n        bprintf(b, \"%s:10\\n\", __FUNCTION__);\n        coro_await (coro_loopyield_dotest(brk, stack, state, b));\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_loopawait_yield_dotest(int brk, short stack[8], int *state, char **b)\n{\n    coro_block (stack)\n    {\n        while ((*state)++ < 3)\n        {\n            bprintf(b, \"%s:10:%d\\n\", __FUNCTION__, *state);\n            coro_await (coro_yield_dotest(brk, stack, b));\n        }\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_await_await_yield_dotest(int brk, short stack[8], char **b)\n{\n    coro_block (stack)\n    {\n        bprintf(b, \"%s:10\\n\", __FUNCTION__);\n        coro_await (coro_await_yield_dotest(brk, stack, b));\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_await_loopawait_yield_dotest(int brk, short stack[8], int *state, char **b)\n{\n    coro_block (stack)\n    {\n        bprintf(b, \"%s:10\\n\", __FUNCTION__);\n        coro_await (coro_loopawait_yield_dotest(brk, stack, state, b));\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic int coro_loopawait_loopawait_yield_dotest(int brk, short stack[8], int *state, char **b)\n{\n    coro_block (stack)\n    {\n        while ((*state)++ < 2)\n        {\n            bprintf(b, \"%s:10:%d\\n\", __FUNCTION__, *state);\n            state[1] = 0;\n            coro_await (coro_loopawait_yield_dotest(brk, stack, state + 1, b));\n        }\n\n        bprintf(b, \"%s:20\\n\", __FUNCTION__);\n        if (brk) coro_break;\n    }\n\n    return coro_active();\n}\n\nstatic void coro_dotest(int brk)\n{\n    short stack[8];\n    int state[2];\n    char buf[2048], *b;\n\n    memset(stack, 0, sizeof stack);\n    b = buf;\n    ASSERT(!coro_break_dotest(brk, stack, &b));\n    ASSERT(!coro_break_dotest(brk, stack, &b));\n    ASSERT(0 == strcmp(buf, \"coro_break_dotest\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    b = buf;\n    ASSERT( coro_yield_dotest(brk, stack, &b));\n    ASSERT(!coro_yield_dotest(brk, stack, &b));\n    ASSERT(!coro_yield_dotest(brk, stack, &b));\n    ASSERT(0 == strcmp(buf, \"coro_yield_dotest:10\\ncoro_yield_dotest:20\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    state[0] = 0;\n    b = buf;\n    ASSERT( coro_loopyield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopyield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopyield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_loopyield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_loopyield_dotest(brk, stack, state, &b));\n    ASSERT(0 == strcmp(buf,\n        \"coro_loopyield_dotest:10:1\\n\"\n        \"coro_loopyield_dotest:10:2\\n\"\n        \"coro_loopyield_dotest:10:3\\n\"\n        \"coro_loopyield_dotest:20\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    b = buf;\n    ASSERT(!coro_await_break_dotest(brk, stack, &b));\n    ASSERT(!coro_await_break_dotest(brk, stack, &b));\n    ASSERT(0 == strcmp(buf, \"coro_await_break_dotest:10\\ncoro_break_dotest\\ncoro_await_break_dotest:20\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    b = buf;\n    ASSERT( coro_await_yield_dotest(brk, stack, &b));\n    ASSERT(!coro_await_yield_dotest(brk, stack, &b));\n    ASSERT(!coro_await_yield_dotest(brk, stack, &b));\n    ASSERT(0 == strcmp(buf, \"coro_await_yield_dotest:10\\ncoro_yield_dotest:10\\ncoro_yield_dotest:20\\ncoro_await_yield_dotest:20\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    state[0] = 0;\n    b = buf;\n    ASSERT( coro_await_loopyield_dotest(brk, stack, state, &b));\n    ASSERT( coro_await_loopyield_dotest(brk, stack, state, &b));\n    ASSERT( coro_await_loopyield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_await_loopyield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_await_loopyield_dotest(brk, stack, state, &b));\n    ASSERT(0 == strcmp(buf,\n        \"coro_await_loopyield_dotest:10\\n\"\n        \"coro_loopyield_dotest:10:1\\n\"\n        \"coro_loopyield_dotest:10:2\\n\"\n        \"coro_loopyield_dotest:10:3\\n\"\n        \"coro_loopyield_dotest:20\\n\"\n        \"coro_await_loopyield_dotest:20\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    state[0] = 0;\n    b = buf;\n    ASSERT( coro_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(0 == strcmp(buf,\n        \"coro_loopawait_yield_dotest:10:1\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:10:2\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:10:3\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:20\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    b = buf;\n    ASSERT( coro_await_await_yield_dotest(brk, stack, &b));\n    ASSERT(!coro_await_await_yield_dotest(brk, stack, &b));\n    ASSERT(!coro_await_await_yield_dotest(brk, stack, &b));\n    ASSERT(0 == strcmp(buf,\n        \"coro_await_await_yield_dotest:10\\n\"\n        \"coro_await_yield_dotest:10\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_await_yield_dotest:20\\n\"\n        \"coro_await_await_yield_dotest:20\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    state[0] = 0;\n    b = buf;\n    ASSERT( coro_await_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_await_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_await_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_await_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_await_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(0 == strcmp(buf,\n        \"coro_await_loopawait_yield_dotest:10\\n\"\n        \"coro_loopawait_yield_dotest:10:1\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:10:2\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:10:3\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:20\\n\"\n        \"coro_await_loopawait_yield_dotest:20\\n\"));\n\n    memset(stack, 0, sizeof stack);\n    state[0] = 0;\n    b = buf;\n    ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT( coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(!coro_loopawait_loopawait_yield_dotest(brk, stack, state, &b));\n    ASSERT(0 == strcmp(buf,\n        \"coro_loopawait_loopawait_yield_dotest:10:1\\n\"\n        \"coro_loopawait_yield_dotest:10:1\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:10:2\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:10:3\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:20\\n\"\n        \"coro_loopawait_loopawait_yield_dotest:10:2\\n\"\n        \"coro_loopawait_yield_dotest:10:1\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:10:2\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:10:3\\n\"\n        \"coro_yield_dotest:10\\n\"\n        \"coro_yield_dotest:20\\n\"\n        \"coro_loopawait_yield_dotest:20\\n\"\n        \"coro_loopawait_loopawait_yield_dotest:20\\n\"));\n}\n\nstatic void coro_test(void)\n{\n    coro_dotest(0);\n    coro_dotest(1);\n}\n\nvoid coro_tests(void)\n{\n    TEST(coro_test);\n}\n"
  },
  {
    "path": "tst/winfuse-tests/path-test.c",
    "content": "/**\n * @file path-test.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <winfsp/winfsp.h>\n#include <tlib/testsuite.h>\n\n#define SHARED_KM_SHARED_H_INCLUDED\n#define PAGED_CODE()\n#include <shared/km/path.c>\n\nvoid path_prefix_test(void)\n{\n    PSTR ipaths[] =\n    {\n        \"\",\n        \"/\",\n        \"//\",\n        \"/a\",\n        \"//a\",\n        \"//a/\",\n        \"//a//\",\n        \"a/\",\n        \"a//\",\n        \"a/b\",\n        \"a//b\",\n        \"foo///bar//baz\",\n        \"foo///bar//baz/\",\n        \"foo///bar//baz//\",\n        \"foo\",\n        \"/foo/bar/baz\",\n    };\n    PSTR opaths[] =\n    {\n        \"\", \"\",\n        \"/\", \"\",\n        \"/\", \"\",\n        \"/\", \"a\",\n        \"/\", \"a\",\n        \"/\", \"a/\",\n        \"/\", \"a//\",\n        \"a\", \"\",\n        \"a\", \"\",\n        \"a\", \"b\",\n        \"a\", \"b\",\n        \"foo\", \"bar//baz\",\n        \"foo\", \"bar//baz/\",\n        \"foo\", \"bar//baz//\",\n        \"foo\", \"\",\n        \"/\", \"foo/bar/baz\",\n    };\n\n    for (size_t i = 0; sizeof ipaths / sizeof ipaths[0] > i; i++)\n    {\n        STRING Path, Prefix, Remain;\n\n        Path.Length = Path.MaximumLength = (USHORT)strlen(ipaths[i]);\n        Path.Buffer = ipaths[i];\n\n        FusePosixPathPrefix(&Path, &Prefix, &Remain);\n\n        ASSERT(Prefix.Length == strlen(opaths[2 * i + 0]));\n        ASSERT(Prefix.Length == Prefix.MaximumLength);\n        ASSERT(0 == memcmp(opaths[2 * i + 0], Prefix.Buffer, Prefix.Length));\n\n        ASSERT(Remain.Length == strlen(opaths[2 * i + 1]));\n        ASSERT(Remain.Length == Remain.MaximumLength);\n        ASSERT(0 == memcmp(opaths[2 * i + 1], Remain.Buffer, Remain.Length));\n    }\n}\n\nvoid path_suffix_test(void)\n{\n    PSTR ipaths[] =\n    {\n        \"\",\n        \"/\",\n        \"//\",\n        \"/a\",\n        \"//a\",\n        \"//a/\",\n        \"//a//\",\n        \"a/\",\n        \"a//\",\n        \"a/b\",\n        \"a//b\",\n        \"foo///bar//baz\",\n        \"foo///bar//baz/\",\n        \"foo///bar//baz//\",\n        \"foo\",\n        \"/foo/bar/baz\",\n    };\n    PSTR opaths[] =\n    {\n        \"\", \"\",\n        \"/\", \"\",\n        \"/\", \"\",\n        \"/\", \"a\",\n        \"/\", \"a\",\n        \"//a\", \"\",\n        \"//a\", \"\",\n        \"a\", \"\",\n        \"a\", \"\",\n        \"a\", \"b\",\n        \"a\", \"b\",\n        \"foo///bar\", \"baz\",\n        \"foo///bar//baz\", \"\",\n        \"foo///bar//baz\", \"\",\n        \"foo\", \"\",\n        \"/foo/bar\", \"baz\",\n    };\n\n    for (size_t i = 0; sizeof ipaths / sizeof ipaths[0] > i; i++)\n    {\n        STRING Path, Remain, Suffix;\n\n        Path.Length = Path.MaximumLength = (USHORT)strlen(ipaths[i]);\n        Path.Buffer = ipaths[i];\n\n        FusePosixPathSuffix(&Path, &Remain, &Suffix);\n\n        ASSERT(Remain.Length == strlen(opaths[2 * i + 0]));\n        ASSERT(Remain.Length == Remain.MaximumLength);\n        ASSERT(0 == memcmp(opaths[2 * i + 0], Remain.Buffer, Remain.Length));\n\n        ASSERT(Suffix.Length == strlen(opaths[2 * i + 1]));\n        ASSERT(Suffix.Length == Suffix.MaximumLength);\n        ASSERT(0 == memcmp(opaths[2 * i + 1], Suffix.Buffer, Suffix.Length));\n    }\n}\n\nvoid path_tests(void)\n{\n    TEST(path_prefix_test);\n    TEST(path_suffix_test);\n}\n"
  },
  {
    "path": "tst/winfuse-tests/transact-test.c",
    "content": "/**\n * @file transact-test.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <winfsp/winfsp.h>\n#include <tlib/testsuite.h>\n#include <process.h>\n#include <strsafe.h>\n#include <shared/km/proto.h>\n\n#define FUSE_FSCTL_TRANSACT             \\\n    CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 0xC00 + 'F', METHOD_BUFFERED, FILE_ANY_ACCESS)\n\nstatic void transact_init_dotest(PWSTR DeviceName, PWSTR Prefix)\n{\n    FSP_FSCTL_VOLUME_PARAMS VolumeParams = { .Version = sizeof VolumeParams };\n    HANDLE VolumeHandle;\n    WCHAR VolumeName[MAX_PATH];\n    BOOL Success;\n    NTSTATUS Result;\n\n    if (0 != Prefix && L'\\\\' == Prefix[0] && L'\\\\' == Prefix[1])\n        wcscpy_s(VolumeParams.Prefix, sizeof VolumeParams.Prefix / sizeof(WCHAR),\n            Prefix + 1);\n    VolumeParams.FsextControlCode = FUSE_FSCTL_TRANSACT;\n    Result = FspFsctlCreateVolume(DeviceName, &VolumeParams,\n        VolumeName, sizeof VolumeName, &VolumeHandle);\n    ASSERT(STATUS_SUCCESS == Result);\n    ASSERT(0 == wcsncmp(L\"\\\\Device\\\\Volume{\", VolumeName, 15));\n    ASSERT(INVALID_HANDLE_VALUE != VolumeHandle);\n\n    FSP_FSCTL_DECLSPEC_ALIGN UINT8 RequestBuf[FUSE_PROTO_REQ_SIZEMIN];\n    FUSE_PROTO_RSP ResponseBuf;\n    FUSE_PROTO_REQ *Request = (PVOID)RequestBuf;\n    FUSE_PROTO_RSP *Response = &ResponseBuf;\n    DWORD BytesTransferred;\n\n    Success = DeviceIoControl(VolumeHandle, FUSE_FSCTL_TRANSACT,\n        0, 0, RequestBuf, sizeof RequestBuf, &BytesTransferred, 0);\n    ASSERT(Success);\n\n    ASSERT(BytesTransferred == Request->len);\n    ASSERT(FUSE_PROTO_REQ_SIZE(init) == Request->len);\n    ASSERT(FUSE_PROTO_OPCODE_INIT == Request->opcode);\n    ASSERT(0 != Request->unique);\n    ASSERT(0 == Request->nodeid);\n    ASSERT(0 == Request->uid);\n    ASSERT(0 == Request->gid);\n    ASSERT(0 == Request->pid);\n    ASSERT(0 == Request->padding);\n    ASSERT(FUSE_PROTO_VERSION == Request->req.init.major);\n    ASSERT(FUSE_PROTO_MINOR_VERSION == Request->req.init.minor);\n    // max_readahead\n    // flags\n\n    memset(Response, 0, FUSE_PROTO_RSP_SIZE(init));\n    Response->len = FUSE_PROTO_RSP_SIZE(init);\n    Response->unique = Request->unique;\n    Response->rsp.init.major = Request->req.init.major;\n    Response->rsp.init.minor = Request->req.init.minor;\n    // max_readahead\n    // flags\n    // max_background\n    // congestion_threshold\n    // max_write\n    // time_gran\n    // max_pages\n    // padding\n    // unused\n\n    Success = DeviceIoControl(VolumeHandle, FUSE_FSCTL_TRANSACT,\n        Response, Response->len, 0, 0, &BytesTransferred, 0);\n    ASSERT(Success);\n\n    Success = CloseHandle(VolumeHandle);\n    ASSERT(Success);\n}\n\nstatic void transact_init_test(void)\n{\n    transact_init_dotest(L\"WinFsp.Disk\", 0);\n    transact_init_dotest(L\"WinFsp.Net\", L\"\\\\\\\\winfuse-tests\\\\share\");\n}\n\nstatic HANDLE transact_open_close_dotest_VolumeHandle;\nstatic HANDLE transact_open_close_dotest_MainThread;\n\nstatic unsigned __stdcall transact_open_close_dotest_thread(void *FilePath)\n{\n    FspDebugLog(__FUNCTION__ \": \\\"%S\\\"\\n\", FilePath);\n\n    HANDLE Handle;\n    Handle = CreateFileW(FilePath,\n        FILE_GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);\n    if (INVALID_HANDLE_VALUE == Handle)\n        return GetLastError();\n    if (INVALID_HANDLE_VALUE != transact_open_close_dotest_VolumeHandle)\n    {\n        Sleep(300);\n        CloseHandle(transact_open_close_dotest_VolumeHandle);\n    }\n    if (0 != transact_open_close_dotest_MainThread)\n    {\n        Sleep(300);\n        if (!CancelSynchronousIo(transact_open_close_dotest_MainThread))\n        {\n            DWORD LastError = GetLastError();\n            CloseHandle(Handle);\n            return LastError;\n        }\n    }\n    CloseHandle(Handle);\n    return 0;\n}\n\nstatic void transact_open_close_dotest(PWSTR DeviceName, PWSTR Prefix, int Scenario)\n{\n    FSP_FSCTL_VOLUME_PARAMS VolumeParams = { .Version = sizeof VolumeParams };\n    HANDLE VolumeHandle;\n    WCHAR VolumeName[MAX_PATH];\n    WCHAR FilePath[MAX_PATH];\n    HANDLE Thread, MainThread = 0;\n    DWORD ExitCode;\n    BOOL Success;\n    NTSTATUS Result;\n\n    if (0 != Prefix && L'\\\\' == Prefix[0] && L'\\\\' == Prefix[1])\n        wcscpy_s(VolumeParams.Prefix, sizeof VolumeParams.Prefix / sizeof(WCHAR),\n            Prefix + 1);\n    VolumeParams.FsextControlCode = FUSE_FSCTL_TRANSACT;\n    Result = FspFsctlCreateVolume(DeviceName, &VolumeParams,\n        VolumeName, sizeof VolumeName, &VolumeHandle);\n    ASSERT(STATUS_SUCCESS == Result);\n    ASSERT(0 == wcsncmp(L\"\\\\Device\\\\Volume{\", VolumeName, 15));\n    ASSERT(INVALID_HANDLE_VALUE != VolumeHandle);\n\n    transact_open_close_dotest_VolumeHandle = 'CLOS' == Scenario ? VolumeHandle : INVALID_HANDLE_VALUE;\n    transact_open_close_dotest_MainThread = 'CNCL' == Scenario &&\n        DuplicateHandle(\n            GetCurrentProcess(),\n            GetCurrentThread(),\n            GetCurrentProcess(),\n            &MainThread,\n            0,\n            FALSE,\n            DUPLICATE_SAME_ACCESS) ?\n        MainThread : 0;\n\n    StringCbPrintfW(FilePath, sizeof FilePath, L\"%s%s\\\\file0\",\n        Prefix ? L\"\" : L\"\\\\\\\\?\\\\GLOBALROOT\", Prefix ? Prefix : VolumeName);\n    Thread = (HANDLE)_beginthreadex(0, 0, transact_open_close_dotest_thread, FilePath, 0, 0);\n    ASSERT(0 != Thread);\n\n    Sleep(1000); /* give some time to the thread to execute */\n\n    FSP_FSCTL_DECLSPEC_ALIGN UINT8 RequestBuf[FUSE_PROTO_REQ_SIZEMIN];\n    FUSE_PROTO_RSP ResponseBuf;\n    FUSE_PROTO_REQ *Request = (PVOID)RequestBuf;\n    FUSE_PROTO_RSP *Response = &ResponseBuf;\n    DWORD BytesTransferred;\n\n    for (BOOLEAN Loop = TRUE; Loop;)\n    {\n        do\n        {\n            Success = DeviceIoControl(VolumeHandle, FUSE_FSCTL_TRANSACT,\n                0, 0, RequestBuf, sizeof RequestBuf, &BytesTransferred, 0);\n            ASSERT(Success || ERROR_INVALID_HANDLE == GetLastError() || ERROR_OPERATION_ABORTED == GetLastError());\n            if (!Success && (ERROR_INVALID_HANDLE == GetLastError() || ERROR_OPERATION_ABORTED == GetLastError()))\n                goto loopexit;\n        } while (0 == BytesTransferred);\n\n        ASSERT(FUSE_PROTO_REQ_HEADER_SIZE <= BytesTransferred);\n        ASSERT(Request->len == BytesTransferred);\n\n        Response->len = 0;\n        switch (Request->opcode)\n        {\n        case FUSE_PROTO_OPCODE_INIT:\n            ASSERT(FUSE_PROTO_REQ_SIZE(init) == Request->len);\n            ASSERT(FUSE_PROTO_OPCODE_INIT == Request->opcode);\n            ASSERT(0 != Request->unique);\n            ASSERT(0 == Request->nodeid);\n            ASSERT(0 == Request->uid);\n            ASSERT(0 == Request->gid);\n            ASSERT(0 == Request->pid);\n            ASSERT(0 == Request->padding);\n            ASSERT(FUSE_PROTO_VERSION == Request->req.init.major);\n            ASSERT(FUSE_PROTO_MINOR_VERSION == Request->req.init.minor);\n            // max_readahead\n            // flags\n\n            memset(Response, 0, FUSE_PROTO_RSP_SIZE(init));\n            Response->len = FUSE_PROTO_RSP_SIZE(init);\n            Response->unique = Request->unique;\n            Response->rsp.init.major = Request->req.init.major;\n            Response->rsp.init.minor = Request->req.init.minor;\n            // max_readahead\n            // flags\n            // max_background\n            // congestion_threshold\n            // max_write\n            // time_gran\n            // max_pages\n            // padding\n            // unused\n            break;\n\n        case FUSE_PROTO_OPCODE_STATFS:\n            ASSERT(FUSE_PROTO_REQ_HEADER_SIZE == Request->len);\n            ASSERT(FUSE_PROTO_OPCODE_STATFS == Request->opcode);\n            ASSERT(0 != Request->unique);\n            ASSERT(0 == Request->nodeid);\n            ASSERT(0 == Request->uid);\n            ASSERT(0 == Request->gid);\n            ASSERT(0 == Request->pid);\n            ASSERT(0 == Request->padding);\n\n            memset(Response, 0, FUSE_PROTO_RSP_SIZE(statfs));\n            Response->len = FUSE_PROTO_RSP_SIZE(statfs);\n            Response->unique = Request->unique;\n            Response->rsp.statfs.st.blocks = 1000;\n            Response->rsp.statfs.st.bfree = 1000;\n            Response->rsp.statfs.st.frsize = 4096;\n            break;\n\n        case FUSE_PROTO_OPCODE_GETATTR:\n            ASSERT(FUSE_PROTO_REQ_SIZE(getattr) == Request->len);\n            ASSERT(FUSE_PROTO_OPCODE_GETATTR == Request->opcode);\n            ASSERT(0 != Request->unique);\n            ASSERT(FUSE_PROTO_ROOT_INO == Request->nodeid || FUSE_PROTO_ROOT_INO + 1 == Request->nodeid);\n            ASSERT(0 == Request->padding);\n            ASSERT(0 == Request->req.getattr.getattr_flags);\n            ASSERT(0 == Request->req.getattr.fh);\n\n            memset(Response, 0, FUSE_PROTO_RSP_SIZE(getattr));\n            Response->len = FUSE_PROTO_RSP_SIZE(getattr);\n            Response->unique = Request->unique;\n            Response->rsp.getattr.attr.ino = Request->nodeid;\n            Response->rsp.getattr.attr.mode = 0040777;\n            Response->rsp.getattr.attr.nlink = 1;\n            Response->rsp.getattr.attr.uid = Request->uid;\n            Response->rsp.getattr.attr.gid = Request->gid;\n            break;\n\n        case FUSE_PROTO_OPCODE_LOOKUP:\n            ASSERT(FUSE_PROTO_REQ_SIZE(lookup) + sizeof \"file0\" == Request->len);\n            ASSERT(FUSE_PROTO_OPCODE_LOOKUP == Request->opcode);\n            ASSERT(0 != Request->unique);\n            ASSERT(FUSE_PROTO_ROOT_INO == Request->nodeid);\n            ASSERT(0 != Request->uid);\n            ASSERT(0 != Request->gid);\n            ASSERT(0 != Request->pid);\n            ASSERT(0 == Request->padding);\n            ASSERT(0 == strcmp(\"file0\", Request->req.lookup.name));\n\n            memset(Response, 0, FUSE_PROTO_RSP_SIZE(lookup));\n            Response->len = FUSE_PROTO_RSP_SIZE(lookup);\n            Response->unique = Request->unique;\n            Response->rsp.lookup.entry.nodeid = FUSE_PROTO_ROOT_INO + 1;\n            Response->rsp.lookup.entry.attr.ino = FUSE_PROTO_ROOT_INO + 1;\n            Response->rsp.lookup.entry.attr.mode = 0040777;\n            Response->rsp.lookup.entry.attr.nlink = 1;\n            Response->rsp.lookup.entry.attr.uid = Request->uid;\n            Response->rsp.lookup.entry.attr.gid = Request->gid;\n            break;\n\n        case FUSE_PROTO_OPCODE_FORGET:\n        case FUSE_PROTO_OPCODE_BATCH_FORGET:\n            continue;\n\n        case FUSE_PROTO_OPCODE_OPENDIR:\n        case FUSE_PROTO_OPCODE_OPEN:\n            ASSERT(FUSE_PROTO_REQ_SIZE(open) == Request->len);\n            ASSERT(FUSE_PROTO_OPCODE_OPENDIR == Request->opcode || FUSE_PROTO_OPCODE_OPEN == Request->opcode);\n            ASSERT(0 != Request->unique);\n            ASSERT(FUSE_PROTO_ROOT_INO == Request->nodeid || FUSE_PROTO_ROOT_INO + 1 == Request->nodeid);\n            ASSERT(0 != Request->uid);\n            ASSERT(0 != Request->gid);\n            ASSERT(0 != Request->pid);\n            ASSERT(0 == Request->padding);\n            ASSERT(0 == Request->req.open.flags);\n            ASSERT(0 == Request->req.open.unused);\n\n            memset(Response, 0, FUSE_PROTO_RSP_SIZE(open));\n            Response->len = FUSE_PROTO_RSP_SIZE(open);\n            Response->unique = Request->unique;\n            Response->rsp.open.fh = 100 + Request->nodeid;\n            break;\n\n        case FUSE_PROTO_OPCODE_RELEASEDIR:\n        case FUSE_PROTO_OPCODE_RELEASE:\n            ASSERT(FUSE_PROTO_REQ_SIZE(release) == Request->len);\n            ASSERT(FUSE_PROTO_OPCODE_RELEASEDIR == Request->opcode || FUSE_PROTO_OPCODE_RELEASE == Request->opcode);\n            ASSERT(0 != Request->unique);\n            ASSERT(FUSE_PROTO_ROOT_INO == Request->nodeid || FUSE_PROTO_ROOT_INO + 1 == Request->nodeid);\n            ASSERT(0 == Request->uid);\n            ASSERT(0 == Request->gid);\n            ASSERT(0 == Request->pid);\n            ASSERT(0 == Request->padding);\n            ASSERT(\n                100 + FUSE_PROTO_ROOT_INO == Request->req.release.fh ||\n                100 + FUSE_PROTO_ROOT_INO + 1 == Request->req.release.fh);\n            ASSERT(0 == Request->req.release.flags);\n            ASSERT(0 == Request->req.release.release_flags);\n            ASSERT(0 == Request->req.release.lock_owner);\n\n            memset(Response, 0, FUSE_PROTO_RSP_HEADER_SIZE);\n            Response->len = FUSE_PROTO_RSP_HEADER_SIZE;\n            Response->unique = Request->unique;\n\n            if ('BOGU' == Scenario)\n                Response->unique = Response->unique ^ rand();\n\n            if (100 + FUSE_PROTO_ROOT_INO + 1 == Request->req.release.fh)\n                Loop = FALSE;\n            break;\n        }\n\n        Success = DeviceIoControl(VolumeHandle, FUSE_FSCTL_TRANSACT,\n            Response, Response->len, 0, 0, &BytesTransferred, 0);\n        ASSERT(Success || ERROR_INVALID_HANDLE == GetLastError() || ERROR_OPERATION_ABORTED == GetLastError());\n        if (!Success && (ERROR_INVALID_HANDLE == GetLastError() || ERROR_OPERATION_ABORTED == GetLastError()))\n            goto loopexit;\n\n        ASSERT(0 == BytesTransferred);\n    }\nloopexit:\n\n    if ('CLOS' != Scenario)\n    {\n        Success = CloseHandle(VolumeHandle);\n        ASSERT(Success);\n    }\n    if ('CNCL' == Scenario)\n    {\n        Success = CloseHandle(MainThread);\n        ASSERT(Success);\n    }\n\n    WaitForSingleObject(Thread, INFINITE);\n    GetExitCodeThread(Thread, &ExitCode);\n    CloseHandle(Thread);\n\n    ASSERT(0 == ExitCode);\n}\n\nstatic void transact_open_close_test(void)\n{\n    transact_open_close_dotest(L\"WinFsp.Disk\", 0, 0);\n    transact_open_close_dotest(L\"WinFsp.Net\", L\"\\\\\\\\winfuse-tests\\\\share\", 0);\n}\n\nstatic void transact_open_abandon_test(void)\n{\n    transact_open_close_dotest(L\"WinFsp.Disk\", 0, 'CLOS');\n    transact_open_close_dotest(L\"WinFsp.Net\", L\"\\\\\\\\winfuse-tests\\\\share\", 'CLOS');\n}\n\nstatic void transact_open_cancel_test(void)\n{\n    transact_open_close_dotest(L\"WinFsp.Disk\", 0, 'CNCL');\n    transact_open_close_dotest(L\"WinFsp.Net\", L\"\\\\\\\\winfuse-tests\\\\share\", 'CNCL');\n}\n\nstatic void transact_open_bogus_test(void)\n{\n    transact_open_close_dotest(L\"WinFsp.Disk\", 0, 'BOGU');\n    transact_open_close_dotest(L\"WinFsp.Net\", L\"\\\\\\\\winfuse-tests\\\\share\", 'BOGU');\n}\n\nvoid transact_tests(void)\n{\n    TEST(transact_init_test);\n    TEST(transact_open_close_test);\n    TEST(transact_open_abandon_test);\n    TEST(transact_open_cancel_test);\n    TEST(transact_open_bogus_test);\n}\n"
  },
  {
    "path": "tst/winfuse-tests/winfuse-tests.c",
    "content": "/**\n * @file winfuse-tests.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <winfsp/winfsp.h>\n#include <tlib/testsuite.h>\n\nint main(int argc, char *argv[])\n{\n    FspLoad(0);\n\n    TESTSUITE(coro_tests);\n    TESTSUITE(path_tests);\n    TESTSUITE(transact_tests);\n\n    tlib_run_tests(argc, argv);\n\n    return 0;\n}\n"
  },
  {
    "path": "tst/wslfuse-tests/mount-test.c",
    "content": "/**\n * @file mount-test.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <errno.h>\n#include <fcntl.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <unistd.h>\n#include <shared/ku/wslfuse.h>\n#include <tlib/testsuite.h>\n\nstatic void mount_createvol_dotest(wchar_t *Prefix)\n{\n    WSLFUSE_IOCTL_CREATEVOLUME_ARG CreateArg = { .VolumeParams.Version = sizeof(FSP_FSCTL_VOLUME_PARAMS)};\n    int fusefd, res;\n\n    if (0 != Prefix && L'\\\\' == Prefix[0] && L'\\\\' == Prefix[1])\n    {\n        /* note that on Linux: sizeof(wchar_t) != sizeof(WCHAR) */\n        wchar_t *P = Prefix + 1;\n        WCHAR *Q = CreateArg.VolumeParams.Prefix;\n        while (0 != (*Q++ = (WCHAR)*P++))\n            ;\n    }\n\n    fusefd = open(\"/dev/fuse\", O_RDWR);\n    ASSERT(-1 != fusefd);\n\n    res = ioctl(fusefd, WSLFUSE_IOCTL_CREATEVOLUME, &CreateArg);\n    ASSERT(0 == res);\n    ASSERT(0 == strncmp(CreateArg.VolumeName, \"\\\\Device\\\\Volume{\", 15));\n\n    res = close(fusefd);\n    ASSERT(0 == res);\n}\n\nstatic void mount_createvol_test(void)\n{\n    mount_createvol_dotest(0);\n    mount_createvol_dotest(L\"\\\\\\\\wslfuse-tests\\\\share\");\n}\n\n#if 0\nstatic void mount_unmount_test(void)\n{\n    WSLFUSE_IOCTL_MOUNTID_ARG MountArg;\n    int fusefd, res;\n\n    fusefd = open(\"/dev/fuse\", O_RDWR);\n    ASSERT(-1 != fusefd);\n\n    MountArg.Operation = '?';\n    MountArg.MountId = 0x42424242;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(-1 == res);\n    ASSERT(ENOENT == errno);\n\n    MountArg.Operation = '-';\n    MountArg.MountId = 0x42424242;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(-1 == res);\n    ASSERT(ENOENT == errno);\n\n    MountArg.Operation = '+';\n    MountArg.MountId = 0x42424242;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(0 == res);\n\n    MountArg.Operation = '+';\n    MountArg.MountId = 0x42424242;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(-1 == res);\n    ASSERT(EEXIST == errno);\n\n    MountArg.Operation = '?';\n    MountArg.MountId = 0x42424242;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(0 == res);\n\n    MountArg.Operation = '?';\n    MountArg.MountId = 0x43434343;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(-1 == res);\n    ASSERT(ENOENT == errno);\n\n    MountArg.Operation = '-';\n    MountArg.MountId = 0x42424242;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(0 == res);\n\n    MountArg.Operation = '-';\n    MountArg.MountId = 0x42424242;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(-1 == res);\n    ASSERT(ENOENT == errno);\n\n    MountArg.Operation = '?';\n    MountArg.MountId = 0x42424242;\n    res = ioctl(fusefd, WSLFUSE_IOCTL_MOUNTID, &MountArg);\n    ASSERT(-1 == res);\n    ASSERT(ENOENT == errno);\n\n    res = close(fusefd);\n    ASSERT(0 == res);\n}\n#endif\n\nvoid mount_tests(void)\n{\n    TEST(mount_createvol_test);\n#if 0\n    TEST(mount_unmount_test);\n#endif\n}\n"
  },
  {
    "path": "tst/wslfuse-tests/wslfuse-tests.c",
    "content": "/**\n * @file wslfuse-tests.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You can redistribute it and/or modify it under the terms of the GNU\n * Affero General Public License version 3 as published by the Free\n * Software Foundation.\n *\n * Licensees holding a valid commercial license may use this software\n * in accordance with the commercial license agreement provided in\n * conjunction with the software.  The terms and conditions of any such\n * commercial license agreement shall govern, supersede, and render\n * ineffective any application of the AGPLv3 license to this software,\n * notwithstanding of any reference thereto in the software or\n * associated repository.\n */\n\n#include <tlib/testsuite.h>\n\nint main(int argc, char *argv[])\n{\n    TESTSUITE(mount_tests);\n\n    tlib_run_tests(argc, argv);\n\n    return 0;\n}\n"
  }
]