Full Code of billziss-gh/winfuse for AI

master 8cdd7634c22d cached
83 files
487.9 KB
129.9k tokens
381 symbols
1 requests
Download .txt
Showing preview only (514K chars total). Download the full file or copy to clipboard to get everything.
Repository: billziss-gh/winfuse
Branch: master
Commit: 8cdd7634c22d
Files: 83
Total size: 487.9 KB

Directory structure:
gitextract_o7pwrk8z/

├── .gitmodules
├── Contributors.asciidoc
├── License.txt
├── README.md
├── appveyor.yml
├── doc/
│   ├── component.puml
│   ├── winseq.puml
│   └── wslseq.puml
├── ext/
│   └── tlib/
│       ├── Commit.txt
│       ├── callstack.c
│       ├── callstack.h
│       ├── injected/
│       │   ├── allfunc.h
│       │   ├── curlfunc.c
│       │   ├── curlfunc.h
│       │   ├── stdfunc.c
│       │   └── stdfunc.h
│       ├── injection.c
│       ├── injection.h
│       ├── testsuite.c
│       └── testsuite.h
├── src/
│   ├── fusermount/
│   │   ├── fusermount-helper.c
│   │   ├── fusermount.c
│   │   ├── install.sh
│   │   └── uninstall.sh
│   ├── shared/
│   │   ├── km/
│   │   │   ├── cache.c
│   │   │   ├── context.c
│   │   │   ├── coro.h
│   │   │   ├── debug.c
│   │   │   ├── errno.i
│   │   │   ├── errnosym.i
│   │   │   ├── file.c
│   │   │   ├── fuseop.c
│   │   │   ├── instance.c
│   │   │   ├── ioq.c
│   │   │   ├── path.c
│   │   │   ├── proto.c
│   │   │   ├── proto.h
│   │   │   ├── shared.h
│   │   │   └── util.c
│   │   └── ku/
│   │       └── wslfuse.h
│   ├── winfuse/
│   │   ├── device.c
│   │   ├── driver.c
│   │   ├── driver.h
│   │   ├── driver.inf.in
│   │   └── version.rc
│   └── wslfuse/
│       ├── device.c
│       ├── driver.c
│       ├── driver.h
│       ├── driver.inf.in
│       └── version.rc
├── tools/
│   ├── DigiCert High Assurance EV Root CA.crt
│   ├── build-libfuse.bat
│   ├── build-lxdk.bat
│   ├── build-sample.bat
│   ├── build-winfsp.bat
│   ├── build.bat
│   ├── debug.bat
│   ├── deploy.bat
│   ├── deploy.ps1
│   ├── gensrc/
│   │   ├── errno.sh
│   │   └── errno.txt
│   ├── ioc.c
│   ├── license-headers/
│   │   ├── fix.ps1
│   │   ├── header.c
│   │   ├── header.cpp
│   │   └── header.h
│   ├── nmake-ext-test.bat
│   └── run-tests.bat
└── tst/
    ├── lockdly/
    │   └── lockdly.c
    ├── memfs-fuse3/
    │   ├── .gitignore
    │   ├── compat.h
    │   ├── memfs-fuse3.cpp
    │   ├── memfs-fuse3.exe.vcxproj
    │   ├── memfs-fuse3.exe.vcxproj.filters
    │   ├── memfs-fuse3.out.vcxproj
    │   ├── memfs-fuse3.out.vcxproj.filters
    │   └── memfs-fuse3.sln
    ├── winfuse-tests/
    │   ├── coro-test.c
    │   ├── path-test.c
    │   ├── transact-test.c
    │   └── winfuse-tests.c
    └── wslfuse-tests/
        ├── mount-test.c
        └── wslfuse-tests.c

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

================================================
FILE: .gitmodules
================================================
[submodule "ext/libfuse"]
	path = ext/libfuse
	url = https://github.com/billziss-gh/libfuse.git
[submodule "ext/winfsp"]
	path = ext/winfsp
	url = https://github.com/billziss-gh/winfsp.git
[submodule "ext/lxdk"]
	path = ext/lxdk
	url = https://github.com/billziss-gh/lxdk.git


================================================
FILE: Contributors.asciidoc
================================================
CONTRIBUTORS
============

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

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

This 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

This document uses the asciidoc format: http://asciidoc.org.


CONTRIBUTOR AGREEMENT
---------------------

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

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

2. With respect to any worldwide copyrights, or copyright applications and registrations, in your contribution:
* 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;
* 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;
* you agree that you will not assert any moral rights in your contribution against us, our licensees or transferees;
* you agree that we may register a copyright in your contribution and exercise all ownership rights associated with it; and
* 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.

3. 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:
* 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
* at our option, to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements.

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

5. You covenant, represent, warrant and agree that:
* 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;
* to the best of your knowledge, each contribution will not violate any third party's copyrights, trademarks, patents, or other intellectual property rights; and
* each contribution shall be in compliance with U.S. export control laws and other applicable export and import laws.
* You agree to notify us if you become aware of any circumstance which would make any of the foregoing representations inaccurate in any respect.

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

7. Please add your name and email address in the CONTRIBUTOR LIST below:
* 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:
+
----
|First Last                             |name at example.com
----
* 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:
+
----
|First Last (Company and/or URL)        |name at example.com
----


CONTRIBUTOR LIST
----------------
|===
|Bill Zissimopoulos                                             |billziss at navimatics.com
|===


================================================
FILE: License.txt
================================================
The WinFuse project is Copyright (C) Bill Zissimopoulos. It is licensed
under the terms of the AGPLv3.

As a special exception to AGPLv3, Bill Zissimopoulos grants additional
permissions to Free/Libre and Open Source Software ("FLOSS") without requiring
that such software is covered by the AGPLv3.

    1. Permission to use the WinFuse DeviceIoControl interface, which allows
    programs running on native Windows to interact with WinFuse using the FUSE
    protocol.

    2. Permission to use the WinFuse /dev/fuse interface, which allows
    programs running on the Windows Subsystem for Linux to interact with
    WinFuse using the FUSE protocol.

    These permissions (and no other) are granted provided that the software:

    1. Is distributed under a license that satisfies the Free Software
    Definition Version 1.141 (https://www.gnu.org/philosophy/free-sw.en.html)
    or the Open Source Definition Version 1.9 (https://opensource.org/osd).

    2. Includes the copyright notice "WinFuse - FUSE for Windows,
    Copyright (C) Bill Zissimopoulos" and a link to the WinFuse repository in
    its user-interface and any user-facing documentation.

    3. Is not linked or distributed with proprietary (non-FLOSS) software.
    [You cannot mix FLOSS and proprietary software while using WinFuse under
    this special exception.]

Commercial licensing options are also available: Please contact
Bill Zissimopoulos <billziss at navimatics.com>.

The full text of the AGPLv3 license follows below.

-----------------------------------------------------------------------

                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

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

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

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

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

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

                       TERMS AND CONDITIONS

  0. Definitions.

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

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

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

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

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

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

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

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

  1. Source Code.

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

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

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

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

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

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

  2. Basic Permissions.

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

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

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

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

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

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

  4. Conveying Verbatim Copies.

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

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

  5. Conveying Modified Source Versions.

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

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

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

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

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

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

  6. Conveying Non-Source Forms.

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

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

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

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

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

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

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

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

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

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

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

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

  7. Additional Terms.

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

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

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

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

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

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

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

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

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

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

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

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

  8. Termination.

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

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

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

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

  9. Acceptance Not Required for Having Copies.

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

  10. Automatic Licensing of Downstream Recipients.

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

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

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

  11. Patents.

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

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

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

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

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

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

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

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

  12. No Surrender of Others' Freedom.

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

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

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

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

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

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

  15. Disclaimer of Warranty.

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

  16. Limitation of Liability.

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

  17. Interpretation of Sections 15 and 16.

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

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

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

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

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

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

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

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

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

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

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


================================================
FILE: README.md
================================================
<h1 align="center">
    WinFuse &middot; FUSE for the Windows kernel
</h1>

<p align="center">
    <b>Download</b><br>
    <a href="https://github.com/billziss-gh/winfuse/releases">
        <img src="https://img.shields.io/github/release/billziss-gh/winfuse/all.svg?label=latest&colorB=e52e4b&style=for-the-badge"/>
    </a>
    <br/>
    <br/>
    <a href="https://ci.appveyor.com/project/billziss-gh/winfuse">
        <img src="https://img.shields.io/appveyor/ci/billziss-gh/winfuse.svg"/>
    </a>
</p>

<p align="center">
    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>.
    <br/>
    <br/>
    <img src="doc/wslcap.gif"/>
</p>

## ARCHITECTURE

### Structural Diagram

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

![Component Diagram](doc/component.svg)

The components and their interfaces are:

- The **winfsp** component which is provided by the [WinFsp](https://github.com/billziss-gh/winfsp) project.
    - The component is an NTOS File System Driver (FSD).
    - The component provides an **FSP_FSCTL_TRANSACT** `DeviceIoControl` interface.
    - The component is responsible for loading the **winfuse** component.
- The **winfuse** component which is provided by the WinFuse project (this project).
    - The component is an NTOS driver.
    - The component provides an **FUSE_FSCTL_TRANSACT** `DeviceIoControl` interface.
    - 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**.
- The **wslfuse** component which is provided by the WinFuse project (this project).
    - The component is an LXCORE driver.
    - The component provides a **/dev/fuse** Linux interface.
    - 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**.
- The **lxldr** component which is provided by the [LxDK](https://github.com/billziss-gh/lxdk) project.
    - The component is an LXCORE driver.
    - The component is responsible for loading the **wslfuse** component.
- The file system (**FS**) components which are user-mode programs provided by third parties.
    - A Windows WinFsp file system connects to the **FSP_FSCTL_TRANSACT** interface.
    - A Windows FUSE file system connects to the **FUSE_FSCTL_TRANSACT** interface.
    - A Linux FUSE file system connects to the **/dev/fuse** interface.

### Behavioral Diagrams

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

#### I/O handled by a Windows FUSE file system:

![Windows FS Sequence Diagram](doc/winseq.svg)

- The I/O originates with one of:
    - A Windows process which uses a familiar API like `ReadFile` or `WriteFile`.
    - A WSL (Linux) process which uses an API like `read(2)` or `write(2)` that LXCORE translates into the equivalent `NtReadFile` or `NtWriteFile`.
- The Windows OS (NTOS) packages this I/O into an IRP (I/O Request Packet) and routes it to the **winfsp** FSD.
- 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.
- 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.
- The Windows FUSE file system processes the request and prepares a response, which it sends to the **winfuse** driver via another `FUSE_FSCTL_TRANSACT`.
- 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`.
- The **winfsp** FSD completes the corresponding I/O, which allows the Originating Process to resume and retrieve the response.

#### I/O handled by a Linux FUSE file system:

![Linux FS Sequence Diagram](doc/wslseq.svg)

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


================================================
FILE: appveyor.yml
================================================
version: '{build}'

image: Visual Studio 2019

environment:
  matrix:
  - CONFIGURATION: Debug
    WINFSP: rel
    LXDK: rel
  - CONFIGURATION: Release
    WINFSP: rel
    LXDK: rel

init:
#- ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))

install:
- git submodule update --init --recursive
# install WinFsp
- appveyor AddMessage "Install WinFsp" -Category Information
- if %WINFSP%==rel appveyor DownloadFile https://github.com/billziss-gh/winfsp/releases/download/v1.8B2/winfsp-1.8.20221.msi
- if %WINFSP%==rel appveyor DownloadFile https://github.com/billziss-gh/winfsp/releases/download/v1.8B2/winfsp-tests-1.8.20221.zip
- if %WINFSP%==src tools\build-winfsp.bat %CONFIGURATION%
- if %WINFSP%==src copy ext\winfsp\build\VStudio\build\%CONFIGURATION%\winfsp-*.msi .
- if %WINFSP%==src copy ext\winfsp\build\VStudio\build\%CONFIGURATION%\winfsp-tests-*.zip .
- for %%f in ("winfsp-*.msi") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000
- for %%f in ("winfsp-tests-*.zip") do powershell -command "Expand-Archive -Path %%f -DestinationPath 'C:\Program Files (x86)\WinFsp\bin'"
# install LxDK
- appveyor AddMessage "Install LxDK" -Category Information
- if %LXDK%==rel appveyor DownloadFile https://github.com/billziss-gh/lxdk/releases/download/v0.3/lxdk-0.3.20228.msi
- if %LXDK%==src tools\build-lxdk.bat %CONFIGURATION%
- if %LXDK%==src copy ext\lxdk\build\VStudio\build\%CONFIGURATION%\lxdk-*.msi .
- for %%f in ("lxdk-*.msi") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000
# install WSL Ubuntu 20.04 - adapted from appveyor/build-images:scripts/Windows/install_wsl.ps1
- appveyor AddMessage "Install WSL Ubuntu 20.04" -Category Information
- ps: (New-Object Net.WebClient).DownloadFile('https://aka.ms/wslubuntu2004', "$env:TEMP\wsl-ubuntu-2004.zip")
- ps: Expand-Archive -Path "$env:TEMP\wsl-ubuntu-2004.zip" -DestinationPath "C:\WSL\WinFuse-Ubuntu2004" -Force
- ps: Remove-Item "$env:TEMP\wsl-ubuntu-2004.zip"
- ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" install --root
- ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run adduser appveyor --gecos `"First,Last,RoomNumber,WorkPhone,HomePhone`" --disabled-password
- ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run "echo 'appveyor:Password12!' | sudo chpasswd"
- ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run usermod -aG sudo appveyor
- ps: |
    . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run "echo -e `"`"appveyor\tALL=(ALL)\tNOPASSWD: ALL`"`" > /etc/sudoers.d/appveyor"
- ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" run chmod 0755 /etc/sudoers.d/appveyor
- ps: . "C:\WSL\WinFuse-Ubuntu2004\ubuntu2004.exe" config --default-user appveyor
- wslconfig /setdefault Ubuntu-20.04
- wsl -- lsb_release -a
# install WSL tools
- appveyor AddMessage "Install WSL tools" -Category Information
- wsl -- sudo apt-get update; sudo apt-get install -y g++ gdb make ninja-build rsync zip libfuse3-dev
# enable test-signing and verifier and reboot
- appveyor AddMessage "Change boot configuration and reboot" -Category Information
- bcdedit /set testsigning on
- verifier /standard /driver winfuse-x64.sys || ver>nul
- if exist %SystemRoot%\memory.dmp del %SystemRoot%\memory.dmp
- ps: Restart-Computer -Force
- ps: Start-Sleep -s 60

build_script:
- appveyor AddMessage "Reboot complete" -Category Information
- tools\build.bat %CONFIGURATION%
- for %%f in ("build\VStudio\build\%CONFIGURATION%\winfuse-*-x64.msi") do start /wait msiexec /i %%f /qn INSTALLLEVEL=1000
- copy ext\libfuse\build\%CONFIGURATION%\x86\lib\fuse3-x86.dll "C:\Program Files\WinFuse\opt\libfuse\bin"
- copy ext\libfuse\build\%CONFIGURATION%\x86\lib\fuse3-x86.lib "C:\Program Files\WinFuse\opt\libfuse\lib"

test_script:
- tools\nmake-ext-test.bat
- tools\run-tests.bat %CONFIGURATION%
- tools\run-tests.bat %CONFIGURATION% sample
- if exist %SystemRoot%\memory.dmp exit 1

on_finish:
- if exist %SystemRoot%\memory.dmp (7z a memory.dmp.zip %SystemRoot%\memory.dmp && appveyor PushArtifact memory.dmp.zip)
- verifier /query
#- ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))


================================================
FILE: doc/component.puml
================================================
left to right direction
skinparam componentStyle uml2
skinparam nodesep 50
skinparam ranksep 30
skinparam shadowing false
skinparam rectangle {
    fontcolor grey
    borderColor grey
    shadowing false
}
skinparam linetype ortho

rectangle NTOS {
    together dummy {
        component winfuse #Salmon
        interface "FUSE_FSCTL\nTRANSACT" as FUSE_FSCTL_TRANSACT #Salmon
        winfuse -right- FUSE_FSCTL_TRANSACT

        component winfsp
        interface "FSP_FSCTL\nTRANSACT" as FSP_FSCTL_TRANSACT
        winfsp -right- FSP_FSCTL_TRANSACT

        winfsp .up.> winfuse: loads
        winfuse -down-( FSP_FSCTL_TRANSACT
    }

    rectangle LXCORE {
        component wslfuse #Salmon
        interface "/dev/fuse" as devfuse #Salmon
        wslfuse -right- devfuse

        component lxldr

        lxldr .up.> wslfuse: loads
    }

    winfsp -[hidden]- wslfuse
    wslfuse -up-( FSP_FSCTL_TRANSACT
}

component "Windows\nWinFsp FS" as fspfs
fspfs -left-( FSP_FSCTL_TRANSACT

component "Windows\nFUSE FS" as winfs
winfs -left-( FUSE_FSCTL_TRANSACT

component "Linux\nFUSE FS" as wslfs
wslfs -left-( devfuse


================================================
FILE: doc/winseq.puml
================================================
skinparam shadowing false
hide footbox

box "Originating Process Context"
    participant "Originating\nProcess" as OP
    participant "winfsp" as winfspOP
end box
box "File System Process Context"
    participant "winfsp" as winfspFS
    participant winfuse #Salmon
    participant "Windows\nFUSE FS" as FS
end box

activate OP
OP->winfspOP: I/O
deactivate OP
activate winfspOP
winfspOP-->winfspFS: Context Switch
deactivate winfspOP
activate winfspFS
winfspFS->winfuse: FSP_FSCTL_TRANSACT Req
deactivate winfspFS
activate winfuse
winfuse->FS: FUSE_FSCTL_TRANSACT Req
deactivate winfuse
activate FS
FS->FS: Process
activate FS
deactivate FS
FS->winfuse: FUSE_FSCTL_TRANSACT Rsp
deactivate FS
activate winfuse
winfuse->winfspFS: FSP_FSCTL_TRANSACT Rsp
deactivate winfuse
activate winfspFS
winfspFS-->OP: Context Switch and Return
deactivate winfspFS
activate OP


================================================
FILE: doc/wslseq.puml
================================================
skinparam shadowing false
hide footbox

box "Originating Process Context"
    participant "Originating\nProcess" as OP
    participant "winfsp" as winfspOP
end box
box "File System Process Context"
    participant "winfsp" as winfspFS
    participant wslfuse #Salmon
    participant "Linux\nFUSE FS" as FS
end box

activate OP
OP->winfspOP: I/O
deactivate OP
activate winfspOP
winfspOP-->winfspFS: Context Switch
deactivate winfspOP
activate winfspFS
winfspFS->wslfuse: FSP_FSCTL_TRANSACT Req
deactivate winfspFS
activate wslfuse
wslfuse->FS: /dev/fuse read
deactivate wslfuse
activate FS
FS->FS: Process
activate FS
deactivate FS
FS->wslfuse: /dev/fuse write
deactivate FS
activate wslfuse
wslfuse->winfspFS: FSP_FSCTL_TRANSACT Rsp
deactivate wslfuse
activate winfspFS
winfspFS-->OP: Context Switch and Return
deactivate winfspFS
activate OP


================================================
FILE: ext/tlib/Commit.txt
================================================
Taken from github.com/billziss-gh/winfsp/ext/tlib codebase:
    commit 847eab3da4e558e2c88504edfe18a51e4450f9e0

Originally from secfs.core/src/tlib codebase:
    commit 16296d2ac64a7d532b1c486dd3c44af5865d4851


================================================
FILE: ext/tlib/callstack.c
================================================
/**
 * @file tlib/callstack.c
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#include <tlib/callstack.h>
#include <stddef.h>
#include <string.h>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#include <dbghelp.h>
#pragma comment(lib, "dbghelp.lib")
#elif defined(__APPLE__) || defined(__linux__)
#include <dlfcn.h>
#include <execinfo.h>
#else
#error tlib/callstack.c not implemented for this platform
#endif

void tlib_callstack(size_t skip, size_t count, struct tlib_callstack_s *stack)
{
    if (count > TLIB_MAX_SYMRET)
        count = TLIB_MAX_SYMRET;
    size_t naddrs = skip + count;
    if (naddrs > TLIB_MAX_SYMCAP)
        naddrs = TLIB_MAX_SYMCAP;
    memset((void *)stack->syms, 0, sizeof stack->syms);
#if defined(_WIN32) || defined(_WIN64)
    /* SymInitialize()/SymFromAddr() are not thread-safe. Furthermore SymInitialize() should
     * not be called more than once per process.
     */
    HANDLE hproc = GetCurrentProcess();
    static SYMBOL_INFO *syminfo = 0;
    void *addrs[TLIB_MAX_SYMCAP];
    size_t i = 0;
    if (0 == syminfo)
    {
        syminfo = (SYMBOL_INFO *)malloc(sizeof(SYMBOL_INFO) + TLIB_MAX_SYMLEN);
        if (0 == syminfo)
            return;
         SymInitialize(hproc, 0, TRUE);
    }
    memset(syminfo, 0, sizeof(SYMBOL_INFO));
    syminfo->SizeOfStruct = sizeof(SYMBOL_INFO);
    syminfo->MaxNameLen = TLIB_MAX_SYMLEN;
    naddrs = CaptureStackBackTrace(0, naddrs, addrs, 0);
    for (void **p = addrs + skip, **endp = addrs + naddrs; endp > p; p++)
    {
        DWORD64 displacement = 0;
        if (SymFromAddr(hproc, (DWORD64)*p, &displacement, syminfo))
        {
            stack->syms[i] = stack->symbuf[i];
            strncpy(stack->symbuf[i], syminfo->Name, TLIB_MAX_SYMLEN);
            stack->symbuf[i][TLIB_MAX_SYMLEN] = '\0';
            i++;
        }
    }
#elif defined(__APPLE__) || defined(__linux__)
    void *addrs[TLIB_MAX_SYMCAP];
    naddrs = backtrace(addrs, naddrs);
    size_t i = 0;
    Dl_info syminfo;
    for (void **p = addrs + skip, **endp = addrs + naddrs; endp > p; p++)
    {
        if (dladdr(*p, &syminfo) && 0 != syminfo.dli_sname)
        {
            stack->syms[i] = stack->symbuf[i];
            strncpy(stack->symbuf[i], syminfo.dli_sname, TLIB_MAX_SYMLEN);
            stack->symbuf[i][TLIB_MAX_SYMLEN] = '\0';
            i++;
        }
    }
#endif
}


================================================
FILE: ext/tlib/callstack.h
================================================
/**
 * @file tlib/callstack.h
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#ifndef TLIB_CALLSTACK_H_INCLUDED
#define TLIB_CALLSTACK_H_INCLUDED

#include <stddef.h>

enum
{
    TLIB_MAX_SYMLEN = 63,
    TLIB_MAX_SYMRET = 8,
    TLIB_MAX_SYMCAP = 62, /* max number of frames to capture (Windows restriction) */
};

struct tlib_callstack_s
{
    const char *syms[TLIB_MAX_SYMRET + 1];
    char symbuf[TLIB_MAX_SYMRET][TLIB_MAX_SYMLEN + 1];
};
void tlib_callstack(size_t skip, size_t count, struct tlib_callstack_s *stack);

#endif


================================================
FILE: ext/tlib/injected/allfunc.h
================================================
/**
 * @file tlib/injected/allfunc.h
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#ifndef TLIB_INJECTED_ALLFUNC_H_INCLUDED
#define TLIB_INJECTED_ALLFUNC_H_INCLUDED

#include <tlib/injected/curlfunc.h>
#include <tlib/injected/stdfunc.h>

#endif


================================================
FILE: ext/tlib/injected/curlfunc.c
================================================
/**
 * @file tlib/injected/curlfunc.c
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#include <tlib/injected/curlfunc.h>
#define TLIB_INJECTIONS_ENABLED
#include <tlib/injection.h>

#undef curl_easy_init
#undef curl_multi_init
#undef curl_multi_add_handle
#undef curl_multi_perform

CURL *tlib_curl_easy_init(void)
{
    TLIB_INJECT("curl_easy_init", return 0);
    return curl_easy_init();
}
CURLM *tlib_curl_multi_init(void)
{
    TLIB_INJECT("curl_multi_init", return 0);
    return curl_multi_init();
}
CURLMcode tlib_curl_multi_add_handle(CURLM *mh, CURL *eh)
{
    TLIB_INJECT("curl_multi_add_handle", return CURLM_INTERNAL_ERROR);
    return curl_multi_add_handle(mh, eh);
}
CURLMcode tlib_curl_multi_perform(CURLM *mh, int *running_handles)
{
    TLIB_INJECT("curl_multi_perform", return CURLM_INTERNAL_ERROR);
    return curl_multi_perform(mh, running_handles);
}


================================================
FILE: ext/tlib/injected/curlfunc.h
================================================
/**
 * @file tlib/injected/curlfunc.h
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#ifndef TLIB_INJECTED_CURLFUNC_H_INCLUDED
#define TLIB_INJECTED_CURLFUNC_H_INCLUDED

#include <curl/curl.h>

#if defined(TLIB_INJECTIONS_ENABLED)
#define curl_easy_init()                tlib_curl_easy_init()
#define curl_multi_init()               tlib_curl_multi_init()
#define curl_multi_add_handle(mh, eh)   tlib_curl_multi_add_handle(mh, eh)
#define curl_multi_perform(mh, rh)      tlib_curl_multi_perform(mh, rh)
#endif

CURL *tlib_curl_easy_init(void);
CURLM *tlib_curl_multi_init(void);
CURLMcode tlib_curl_multi_add_handle(CURLM *mh, CURL *eh);
CURLMcode tlib_curl_multi_perform(CURLM *mh, int *running_handles);

#endif


================================================
FILE: ext/tlib/injected/stdfunc.c
================================================
/**
 * @file tlib/injected/stdfunc.c
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#include <tlib/injected/stdfunc.h>
#define TLIB_INJECTIONS_ENABLED
#include <tlib/injection.h>

#undef calloc
#undef malloc
#undef realloc

void *tlib_calloc(size_t count, size_t size)
{
    TLIB_INJECT("calloc", return 0);
    return calloc(count, size);
}
void *tlib_malloc(size_t size)
{
    TLIB_INJECT("malloc", return 0);
    return malloc(size);
}
void *tlib_realloc(void *ptr, size_t size)
{
    TLIB_INJECT("realloc", return 0);
    return realloc(ptr, size);
}


================================================
FILE: ext/tlib/injected/stdfunc.h
================================================
/**
 * @file tlib/injected/stdfunc.h
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#ifndef TLIB_INJECTED_STDFUNC_H_INCLUDED
#define TLIB_INJECTED_STDFUNC_H_INCLUDED

#include <stdlib.h>
#include <errno.h>

#if defined(TLIB_INJECTIONS_ENABLED)
#define calloc(count, size)             tlib_calloc(count, size)
#define malloc(size)                    tlib_malloc(size)
#define realloc(ptr, size)              tlib_realloc(ptr, size)
#endif

void *tlib_calloc(size_t count, size_t size);
void *tlib_malloc(size_t size);
void *tlib_realloc(void *ptr, size_t size);

#endif


================================================
FILE: ext/tlib/injection.c
================================================
/**
 * @file tlib/injection.c
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#include <tlib/injection.h>
#include <tlib/callstack.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

#undef NDEBUG
#include <assert.h>

#define NBUCKETS                        256
struct injection_cond_s
{
    struct injection_cond_s *cnext;
    char *sym;
    unsigned trigger, count;
};
struct injection_entry_s
{
    struct injection_entry_s *hnext;
    char *name;
    struct injection_cond_s *clist;
};
struct injection_htab_s
{
    struct injection_entry_s **buckets;
};

static inline size_t hash_chars(const char *s, size_t length)
{
    /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */
    size_t h = 5381;
    for (const char *t = s + length; t > s; ++s)
        h = 33 * h + *s;
    return h;
}
static struct injection_htab_s *injection_htab()
{
    static struct injection_htab_s *htab;
    if (0 == htab)
    {
        htab = calloc(1, sizeof *htab);
        assert(0 != htab);
        htab->buckets = calloc(NBUCKETS, sizeof(struct injection_entry_s *));
    }
    return htab;
}
static struct injection_entry_s *injection_lookup(const char *name)
{
    struct injection_htab_s *htab = injection_htab();
    size_t i = hash_chars(name, strlen(name)) & (NBUCKETS - 1);
    for (struct injection_entry_s *entry = htab->buckets[i]; entry; entry = entry->hnext)
        if (0 == strcmp(entry->name, name))
            return entry;
    return 0;
}
static struct injection_entry_s *injection_insert(const char *name)
{
    struct injection_htab_s *htab = injection_htab();
    size_t i = hash_chars(name, strlen(name)) & (NBUCKETS - 1);
    struct injection_entry_s *entry = calloc(1, sizeof *entry);
    assert(0 != entry);
    entry->name = strdup(name);
    entry->hnext = htab->buckets[i];
    htab->buckets[i] = entry;
    return entry;
}
static struct injection_cond_s *injection_cond_get(struct injection_entry_s *entry, const char **syms)
{
    struct injection_cond_s *deinjection_centry = 0;
    for (struct injection_cond_s *centry = entry->clist; centry; centry = centry->cnext)
        if ('*' == centry->sym[0] && '\0' == centry->sym[1])
            deinjection_centry = centry;
        else
        {
            for (const char *sym; 0 != (sym = *syms); syms++)
                if (0 == strcmp(centry->sym, sym))
                    return centry;
        }
    return deinjection_centry;
}
static void injection_cond_set(struct injection_entry_s *entry, const char *sym, unsigned trigger)
{
    for (struct injection_cond_s *centry = entry->clist; centry; centry = centry->cnext)
        if (0 == strcmp(centry->sym, sym))
        {
            centry->trigger = trigger;
            return;
        }
    struct injection_cond_s *centry = calloc(1, sizeof *centry);
    assert(0 != centry);
    centry->sym = strdup(sym);
    centry->trigger = trigger;
    centry->cnext = entry->clist;
    entry->clist = centry;
}
static void injection_cond_remove(struct injection_entry_s *entry, const char *sym)
{
    struct injection_cond_s **p = &entry->clist;
    for (; *p; p = &(*p)->cnext)
        if (0 == strcmp((*p)->sym, sym))
            break;
    if (*p) /* did we find the condition? */
    {
        struct injection_cond_s *q = *p;
        *p = q->cnext;
        free(q->sym);
        free(q);
    }
}

void *tlib_injection(const char *name)
{
    struct injection_entry_s *entry = injection_lookup(name);
    if (0 == entry)
        entry = injection_insert(name);
    return entry;
}
int tlib_injection_trace(void *injection)
{
    if (0 == ((struct injection_entry_s *)injection)->clist)
        return 0;
    struct tlib_callstack_s stack;
    tlib_callstack(2, TLIB_MAX_SYMRET, &stack);
    struct injection_cond_s *centry = injection_cond_get(injection, stack.syms);
    if (0 == centry)
        return 0;
    return centry->count++ == centry->trigger || ~0 == centry->trigger;
}
void tlib_injection_enable(const char *name, const char *sym, unsigned trigger)
{
    struct injection_entry_s *entry = tlib_injection(name);
    injection_cond_set(entry, sym, trigger);
}
void tlib_injection_disable(const char *name, const char *sym)
{
    struct injection_entry_s *entry = tlib_injection(name);
    injection_cond_remove(entry, sym);
}


================================================
FILE: ext/tlib/injection.h
================================================
/**
 * @file tlib/injection.h
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

/* NOTE: This header may usefully be included multiple times.
 * The TLIB_INJECT() macro will be redefined based on whether
 * TLIB_INJECTIONS_ENABLED is defined.
 */

#undef TLIB_INJECT
#if defined(TLIB_INJECTIONS_ENABLED)
#define TLIB_INJECT(name, stmt)         \
    do\
    {\
        static void *injection = 0;\
        if (0 == injection)\
            injection = tlib_injection(name);\
        if (tlib_injection_trace(injection))\
            stmt;\
    } while (0)
#else
#define TLIB_INJECT(name, stmt)         do {} while (0)
#endif

void *tlib_injection(const char *name);
int tlib_injection_trace(void *injection);
void tlib_injection_enable(const char *name, const char *sym, unsigned trigger);
void tlib_injection_disable(const char *name, const char *sym);


================================================
FILE: ext/tlib/testsuite.c
================================================
/**
 * @file tlib/testsuite.c
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#include <tlib/testsuite.h>
#include <limits.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct test
{
    char name[64];
    void (*fn)(void);
    int optional;
    struct test *next;
};
static struct test test_suite_sentinel = { .next = &test_suite_sentinel };
static struct test *test_suite_tail = &test_suite_sentinel;
static struct test test_sentinel = { .next = &test_sentinel };
static struct test *test_tail = &test_sentinel;
static void add_test_to_list(const char *name, void (*fn)(void), int optional, struct test **tail)
{
    struct test *test = calloc(1, sizeof *test);
    strncpy(test->name, name, sizeof test->name - 1);
    test->name[sizeof test->name - 1] = '\0';
    test->fn = fn;
    test->optional = optional;
    test->next = (*tail)->next;
    (*tail)->next = test;
    (*tail) = test;
}
void tlib_add_test_suite(const char *name, void (*fn)(void))
{
    add_test_to_list(name, fn, 0, &test_suite_tail);
}
void tlib_add_test(const char *name, void (*fn)(void))
{
    add_test_to_list(name, fn, 0, &test_tail);
}
void tlib_add_test_opt(const char *name, void (*fn)(void))
{
    add_test_to_list(name, fn, 1, &test_tail);
}

static FILE *tlib_out, *tlib_err;
static jmp_buf test_jmp_buf, *test_jmp;
static char assert_buf[256];
static void test_printf(const char *fmt, ...);
static double run_test(struct test *test)
{
#if defined(_WIN64) || defined(_WIN32)
    #pragma comment(lib, "winmm.lib")
    unsigned long __stdcall timeGetTime(void);
    unsigned long t0 = timeGetTime();
    test->fn();
    unsigned long t1 = timeGetTime();
    return (t1 - t0) / 1000.0;
#else
    time_t t0 = time(0);
    test->fn();
    time_t t1 = time(0);
    return difftime(t1, t0);
#endif
}
static void do_test_default(struct test *test, int testno)
{
    if (0 != test)
    {
        snprintf(assert_buf, sizeof assert_buf, "KO\n    ");
        char dispname[39 + 1];
        size_t displen = strlen(test->name);
        if (displen > sizeof dispname - 1)
            displen = sizeof dispname - 1;
        memcpy(dispname, test->name, displen);
        memset(dispname + displen, '.', sizeof dispname - 1 - displen);
        dispname[sizeof dispname - 1] = '\0';
        test_printf("%s ", dispname);
        double d = run_test(test);
        test_printf("OK %.2fs\n", d);
    }
    else
        test_printf("--- COMPLETE ---\n");
}
static void do_test_list(struct test *test, int testno)
{
    if (0 != test)
        test_printf("%s\n", test->name);
}
static void do_test_tap(struct test *test, int testno)
{
    if (0 != test)
    {
        snprintf(assert_buf, sizeof assert_buf, "not ok %d %s\n# ", testno + 1, test->name);
        run_test(test);
        test_printf("ok %d %s\n", testno + 1, test->name);
    }
    else
        test_printf("1..%d\n", testno);
}
static void test_printf(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    FILE *f = tlib_out ? tlib_out : stdout;
    vfprintf(f, fmt, ap);
    fflush(f);
    va_end(ap);
}
void tlib_printf(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    FILE *f = tlib_err ? tlib_err : stderr;
    vfprintf(f, fmt, ap);
    fflush(f);
    va_end(ap);
}
void tlib_run_tests(int argc, char *argv[])
{
    argc--; argv++;
    void (*do_test)(struct test *, int) = do_test_default;
    int match_any = 1, no_abort = 0;
    unsigned long repeat = 1;
    for (char **ap = argv, **aendp = ap + argc; aendp > ap; ap++)
    {
        const char *a = *ap;
        if ('-' == a[0])
        {
            if (0 == strcmp("--list", a))
                do_test = do_test_list;
            else if (0 == strcmp("--tap", a))
                do_test = do_test_tap;
            else if (0 == strcmp("--no-abort", a))
                no_abort = 1;
            else if (0 == strcmp("--repeat-forever", a))
                repeat = ULONG_MAX;
            else if ('-' == a[1])
            {
                fprintf(stderr, "tlib_run_tests: unknown option %s\n", a);
                exit(2);
            }
        }
        else
            match_any = 0;
    }
    for (struct test *test = test_suite_tail->next->next; 0 != test->fn; test = test->next)
        test->fn();
    while (repeat--)
    {
        int testno = 0;
        for (struct test *test = test_tail->next->next; 0 != test->fn; test = test->next)
        {
            int match_arg = match_any && !test->optional;
            for (char **ap = argv, **aendp = ap + argc; aendp > ap; aendp--)
            {
                const char *a = aendp[-1];
                int sign = a[0];
                if ('+' == sign)
                    a++;
                else if ('-' == sign)
                {
                    if ('-' == a[1])
                        continue;
                    a++;
                }
                size_t l = strlen(a);
                if (0 == (0 < l && '*' == a[l - 1] ?
                    strncmp(test->name, a, l - 1) : strcmp(test->name, a)))
                {
                    if ('+' == sign)
                        match_arg = 1;
                    else if ('-' == sign)
                        match_arg = 0;
                    else
                        match_arg = !test->optional;
                    break;
                }
            }
            if (!match_arg)
                continue;
            assert_buf[0] = '\0';
            if (no_abort)
            {
                test_jmp = &test_jmp_buf;
                if (0 == setjmp(*test_jmp))
                    do_test(test, testno);
                test_jmp = 0;
            }
            else
                do_test(test, testno);
            testno++;
        }
        do_test(0, testno);
    }
}
void tlib__assert(const char *func, const char *file, int line, const char *expr)
{
#if defined(_WIN64) || defined(_WIN32)
    const char *p = strrchr(file, '\\');
#else
    const char *p = strrchr(file, '/');
#endif
    file = 0 != p ? p + 1 : file;
    if (0 == func)
        test_printf("%sASSERT(%s) failed at: %s:%d\n", assert_buf, expr, file, line);
    else
        test_printf("%sASSERT(%s) failed at %s:%d:%s\n", assert_buf, expr, file, line, func);
    if (0 != test_jmp)
        longjmp(*test_jmp, 1);
}


================================================
FILE: ext/tlib/testsuite.h
================================================
/**
 * @file tlib/testsuite.h
 *
 * @copyright 2014-2019 Bill Zissimopoulos
 */

#ifndef TLIB_TESTSUITE_H_INCLUDED
#define TLIB_TESTSUITE_H_INCLUDED

#include <stdlib.h>

/**
 * Assert macro
 *
 * This macro works similarly to the Standard C assert macro, except for the following differences:
 *
 * <ul>
 * <li>The macro always checks the specified expression regardless of the NDEBUG macro.</li>
 * <li>The macro aborts the execution of the current test, but not necessarily the execution of the
 * whole testsuite.</li>
 * </ul>
 */
#define ASSERT(expr)\
    (!(expr) ? (tlib__assert(__func__, __FILE__, __LINE__, #expr), abort()) : (void)0)

/**
 * Register a test suite for execution.
 *
 * Test suites are simple functions with prototype <code>void testsuite()</code>. When executed
 * they register individual test cases for execution.
 */
#define TESTSUITE(fn)\
    do\
    {\
        void fn(void);\
        tlib_add_test_suite(#fn, fn);\
    } while (0)

/**
 * Register a test case for execution.
 *
 * Test cases are simple functions with prototype <code>void testcase()</code>.
 */
#define TEST(fn)\
    do\
    {\
        void fn(void);\
        tlib_add_test(#fn, fn);\
    } while (0)

/**
 * Register an optional test case for execution.
 *
 * Test cases are simple functions with prototype <code>void testcase()</code>.
 * Optional tests are not executed by default.
 */
#define TEST_OPT(fn)\
    do\
    {\
        void fn(void);\
        tlib_add_test_opt(#fn, fn);\
    } while (0)

void tlib_add_test_suite(const char *name, void (*fn)(void));
void tlib_add_test(const char *name, void (*fn)(void));
void tlib_add_test_opt(const char *name, void (*fn)(void));

/**
 * Printf function.
 *
 * Use this to produce output in the appropriate tlib file stream. This function uses the local
 * printf facilities and understands the same format strings.
 */
#if defined(__GNUC__)
void tlib_printf(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
#else
void tlib_printf(const char *fmt, ...);
#endif
/**
 * Run tests.
 *
 * This function will first execute all registered test suites, thus giving them the chance to
 * register any test cases. It will then execute all registered test cases according to the
 * command line arguments passed in argv. The command line syntax is a follows:
 *
 * Usage: testprog [--list][[--tap][--no-abort][--repeat-forever] [[+-]TESTNAME...]
 *
 * <ul>
 * <li>--list - list tests only</li>
 * <li>--tap - produce output in TAP format</li>
 * <li>--no-abort - do not abort all tests when an ASSERT fails
 * (only the current test is aborted)</li>
 * <li>--repeat-forever - repeat tests forever</li>
 * </ul>
 *
 * By default all test cases are executed unless specific test cases are named. By default optional
 * test cases are not executed. To execute a specific test case specify its TESTNAME; if it is an
 * optional test case specify +TESTNAME. To excluse a test case specify -TESTNAME.
 *
 * TESTNAME may also contain a single asterisk at the end; for example, mytest* will match all test
 * cases that have names starting with "mytest".
 *
 * @param argc
 *     Argument count.
 * @param argv
 *     Argument vector.
 */
void tlib_run_tests(int argc, char *argv[]);

void tlib__assert(const char *func, const char *file, int line, const char *expr);

#endif


================================================
FILE: src/fusermount/fusermount-helper.c
================================================
/**
 * @file fusermount-helper.c
 *
 * @copyright 2019-2020 Bill Zissimopoulos
 */
/*
 * This file is part of WinFuse.
 *
 * You can redistribute it and/or modify it under the terms of the GNU
 * Affero General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * Licensees holding a valid commercial license may use this software
 * in accordance with the commercial license agreement provided in
 * conjunction with the software.  The terms and conditions of any such
 * commercial license agreement shall govern, supersede, and render
 * ineffective any application of the AGPLv3 license to this software,
 * notwithstanding of any reference thereto in the software or
 * associated repository.
 */

#include <windows.h>
#include <winternl.h>

#define PROGNAME                        "fusermount-helper"

#undef RtlFillMemory
#undef RtlMoveMemory
NTSYSAPI VOID NTAPI RtlFillMemory(VOID *Destination, DWORD Length, BYTE Fill);
NTSYSAPI VOID NTAPI RtlMoveMemory(VOID *Destination, CONST VOID *Source, DWORD Length);

#pragma function(memset)
#pragma function(memcpy)
static inline
void *memset(void *dst, int val, size_t siz)
{
    RtlFillMemory(dst, (DWORD)siz, val);
    return dst;
}
static inline
void *memcpy(void *dst, const void *src, size_t siz)
{
    RtlMoveMemory(dst, src, (DWORD)siz);
    return dst;
}

#define warn(format, ...)               \
    printlog(GetStdHandle(STD_ERROR_HANDLE), PROGNAME ": " format, __VA_ARGS__)
#define fatal(ExitCode, format, ...)    (warn(format, __VA_ARGS__), ExitProcess(ExitCode))

static void vprintlog(HANDLE h, const char *format, va_list ap)
{
    char buf[1024];
        /* wvsprintf is only safe with a 1024 byte buffer */
    size_t len;
    DWORD BytesTransferred;

    wvsprintfA(buf, format, ap);
    buf[sizeof buf - 1] = '\0';

    len = lstrlenA(buf);
    buf[len++] = '\n';

    WriteFile(h, buf, (DWORD)len, &BytesTransferred, 0);
}

static void printlog(HANDLE h, const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vprintlog(h, format, ap);
    va_end(ap);
}

NTSTATUS NTAPI NtOpenSymbolicLinkObject(PHANDLE LinkHandle,
    ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes);
NTSTATUS NTAPI NtMakeTemporaryObject(HANDLE Handle);
NTSTATUS NTAPI NtClose(HANDLE Handle);

static BOOL MountSet_Drive(PWSTR VolumeName, PWSTR MountPoint, PHANDLE PMountHandle)
{
    WCHAR SymlinkBuf[6];
    UNICODE_STRING Symlink;
    OBJECT_ATTRIBUTES Obja;
    NTSTATUS Result;

    *PMountHandle = 0;

    if (!DefineDosDeviceW(DDD_RAW_TARGET_PATH, MountPoint, VolumeName))
        return FALSE;

    memcpy(SymlinkBuf, L"\\??\\X:", sizeof SymlinkBuf);
    SymlinkBuf[4] = MountPoint[0];
    Symlink.Length = Symlink.MaximumLength = sizeof SymlinkBuf;
    Symlink.Buffer = SymlinkBuf;

    memset(&Obja, 0, sizeof Obja);
    Obja.Length = sizeof Obja;
    Obja.ObjectName = &Symlink;
    Obja.Attributes = OBJ_CASE_INSENSITIVE;

    Result = NtOpenSymbolicLinkObject(PMountHandle, DELETE, &Obja);
    if (NT_SUCCESS(Result))
    {
        Result = NtMakeTemporaryObject(*PMountHandle);
        if (!NT_SUCCESS(Result))
        {
            NtClose(*PMountHandle);
            *PMountHandle = 0;
        }
    }

    return TRUE;
}

static BOOL MountSet(PWSTR VolumeName, PWSTR MountPoint, PHANDLE PMountHandle)
{
    *PMountHandle = 0;

    if (L'*' == MountPoint[0] && ':' == MountPoint[1] && L'\0' == MountPoint[2])
    {
        DWORD Drives;
        WCHAR Drive;

        Drives = GetLogicalDrives();
        if (0 == Drives)
            return FALSE;

        for (Drive = 'Z'; 'D' <= Drive; Drive--)
            if (0 == (Drives & (1 << (Drive - 'A'))))
            {
                MountPoint[0] = Drive;
                if (MountSet_Drive(VolumeName, MountPoint, PMountHandle))
                    return TRUE;
            }
        MountPoint[0] = L'*';
        SetLastError(ERROR_NO_SUCH_DEVICE);
            /* error code chosen for WinFsp compatibility (FspMountSet) */
        return FALSE;
    }
    else if (
        (
            (L'A' <= MountPoint[0] && MountPoint[0] <= L'Z') ||
            (L'a' <= MountPoint[0] && MountPoint[0] <= L'z')
        ) && L':' == MountPoint[1] && L'\0' == MountPoint[2])
        return MountSet_Drive(VolumeName, MountPoint, PMountHandle);
    else
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
}

int wmain(int argc, wchar_t **argv)
{
    PWSTR VolumeName;
    PWSTR MountPoint;
    HANDLE MountHandle;
    WCHAR WildMountPoint[] = L"*:";
    UINT8 MountPointU8[MAX_PATH];
    UINT8 Buffer[1];
    DWORD BytesTransferred;

    if (2 > argc || 3 < argc)
        fatal(2, "usage: VolumeName [WinMountPoint]");

    VolumeName = argv[1];
    MountPoint = 2 < argc ? argv[2] : WildMountPoint;

    if (!MountSet(VolumeName, MountPoint, &MountHandle))
        fatal(1, "cannot set Windows mount point %S (LastError=%lu)", MountPoint, GetLastError());

    if (0 == WideCharToMultiByte(CP_UTF8, 0, MountPoint, -1, MountPointU8, MAX_PATH, 0, 0))
        fatal(1, "invalid Windows mount point (LastError=%lu)", GetLastError());

    BytesTransferred = lstrlenA(MountPointU8) + 1;
    if (!WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), MountPointU8, BytesTransferred, &BytesTransferred, 0))
        fatal(1, "cannot write to stdout (LastError=%lu)", GetLastError());

    if (!ReadFile(GetStdHandle(STD_INPUT_HANDLE), Buffer, sizeof Buffer, &BytesTransferred, 0))
        fatal(1, "cannot read from stdin (LastError=%lu)", GetLastError());

    return 0;
}

void wmainCRTStartup(void)
{
    DWORD Argc;
    PWSTR *Argv;

    Argv = CommandLineToArgvW(GetCommandLineW(), &Argc);
    if (0 == Argv)
        ExitProcess(GetLastError());

    ExitProcess(wmain(Argc, Argv));
}


================================================
FILE: src/fusermount/fusermount.c
================================================
/**
 * @file fusermount.c
 *
 * @copyright 2019-2020 Bill Zissimopoulos
 */
/*
 * This file is part of WinFuse.
 *
 * You can redistribute it and/or modify it under the terms of the GNU
 * Affero General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * Licensees holding a valid commercial license may use this software
 * in accordance with the commercial license agreement provided in
 * conjunction with the software.  The terms and conditions of any such
 * commercial license agreement shall govern, supersede, and render
 * ineffective any application of the AGPLv3 license to this software,
 * notwithstanding of any reference thereto in the software or
 * associated repository.
 */

#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <getopt.h>
#include <libgen.h>
#include <limits.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include <shared/ku/wslfuse.h>

static const char *progname;
static struct
{
    const char *mountpoint;
    const char *opts;
    int unmount;
    int lazy;
    int quiet;
} args;

struct mount_opts
{
    FSP_FSCTL_VOLUME_PARAMS VolumeParams;
    char WinMountPoint[260];
    int set_attr_timeout, attr_timeout;
    int set_FileInfoTimeout,
        set_DirInfoTimeout,
        set_EaTimeout,
        set_VolumeInfoTimeout,
        set_KeepFileCache;
    unsigned max_read;
};

static void warn(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    if (!args.quiet)
    {
        fprintf(stderr, "%s: ", progname);
        vfprintf(stderr, format, ap);
        fprintf(stderr, "\n");
    }
    va_end(ap);
}

static const char *opt_parse_arg(const char *opt, char *buf, size_t siz)
{
    const char *p = opt;
    char *q = buf, *endq = q + siz;

    if (0 == p)
        return 0;

    while (endq > q && '\0' != *p && ',' != *p)
    {
        if ('\\' == p[0] && '\0' != p[1])
            p++;
        *q++ = *p++;
    }

    if (endq == q || (buf == q && '\0' == *p))
        return 0;

    *q++ = '\0';
    if ('\0' != *p)
        p++;

    return p;
}

static void utf8_to_utf16(const char *src0, uint16_t *dst, size_t siz)
{
    const uint8_t *src = src0;
    uint16_t *dstend = dst + siz / sizeof(uint16_t);

    while (dstend > dst)
    {
        uint32_t c = *src++;
        uint32_t w = 0xfffd; /* unicode replacement char */

        if (0x80 > c)
            w = c;
        else if (0xc0 > c)
            ;
        else if (0xe0 > c)
        {
            c = (c & 0x1f) << 6;
            if (0x80 != (*src & 0x80))
                goto copy;
            c |= *src++ & 0x3f;
            w = c;
        }
        else if (0xf0 > c)
        {
            c = (c & 0x0f) << 12;
            if (0x80 != (*src & 0x80))
                goto copy;
            c |= (uint32_t)(*src++ & 0x3f) << 6;
            if (0x80 != (*src & 0x80))
                goto copy;
            c |= *src++ & 0x3f;
            w = c;
        }
        else if (0xf8 > c)
        {
            /* we do not support true UTF-16; just skip over 3 continuation bytes */
            if (0x80 != (*src & 0x80))
                goto copy;
            src++;
            if (0x80 != (*src & 0x80))
                goto copy;
            src++;
            if (0x80 != (*src & 0x80))
                goto copy;
            src++;
        }

    copy:
        *dst++ = (uint16_t)w;

        if (0 == c)
            break;
    }

    if (sizeof(uint16_t) <= siz)
        dstend[-1] = 0;
}

static int get_mnt_id(const char *mountpoint)
{
    FILE *file = 0;
    char line[4096];
    char path[4096];
    int mnt_id = -1, m;

    file = fopen("/proc/self/mountinfo", "rb");
    if (0 == file)
        goto exit;

    while (0 != fgets(line, sizeof line, file))
    {
        if (2 == sscanf(line, "%d %*d %*s %*s %4096s %*s", &m, path) &&
            0 == strcmp(mountpoint, path))
        {
            mnt_id = m;
            break;
        }
    }

    if (-1 == mnt_id)
        errno = ENODEV;

exit:
    if (0 != file)
        fclose(file);

    return mnt_id;
}

static void mount_opt_parse(struct mount_opts *mo)
{
    const char *opt;
    char optbuf[4096], *optarg, *optval, empty = '\0';

    memset(mo, 0, sizeof *mo);

    mo->VolumeParams.Version = sizeof(FSP_FSCTL_VOLUME_PARAMS);
    mo->VolumeParams.FileInfoTimeout = 1000;
    mo->VolumeParams.FlushAndPurgeOnCleanup = 1;

    /*
     * Libfuse does not recognize any of our options and rejects them.
     * So (for now at least) prefix our options with "context=", which
     * Libfuse accepts (to support SELinux).
     *
     * So to pass "Volume=X:" use "context=Volume=X:".
     */

    for (
        opt = opt_parse_arg(args.opts, optbuf, sizeof optbuf);
        0 != opt;
        opt = opt_parse_arg(opt, optbuf, sizeof optbuf))
    {
        optarg = optbuf;
        optval = strchr(optarg, '=');
        if (0 != optval)
            *optval++ = '\0';
        else
            optval = &empty;

        if (0 == strcmp(optarg, "context"))
        {
            optarg = optval;
            optval = strchr(optarg, '=');
            if (0 != optval)
                *optval++ = '\0';
            else
                optval = &empty;
        }

        if (0 == strcmp(optarg, "Volume"))
        {
            strncpy(mo->WinMountPoint, optval, sizeof mo->WinMountPoint);
            mo->WinMountPoint[sizeof mo->WinMountPoint - 1] = '\0';
            for (char *P = mo->WinMountPoint; *P; P++)
                if ('/' == *P)
                    *P = '\\';
        }
        else if (0 == strcmp(optarg, "attr_timeout"))
        {
            mo->set_attr_timeout = 1;
            mo->attr_timeout = (int)strtol(optval, 0, 10);
        }
        else if (0 == strcmp(optarg, "SectorSize"))
            mo->VolumeParams.SectorSize = (UINT16)strtoul(optval, 0, 10);
        else if (0 == strcmp(optarg, "SectorsPerAllocationUnit"))
            mo->VolumeParams.SectorsPerAllocationUnit = (UINT16)strtoul(optval, 0, 10);
        else if (0 == strcmp(optarg, "MaxComponentLength"))
            mo->VolumeParams.MaxComponentLength = (UINT16)strtoul(optval, 0, 10);
        else if (0 == strcmp(optarg, "VolumeCreationTime"))
            mo->VolumeParams.VolumeCreationTime = (UINT64)strtol(optval, 0, 0);
        else if (0 == strcmp(optarg, "VolumeSerialNumber"))
            mo->VolumeParams.VolumeSerialNumber = (UINT32)strtoul(optval, 0, 16);
        else if (0 == strcmp(optarg, "FileInfoTimeout"))
        {
            mo->set_FileInfoTimeout = 1;
            mo->VolumeParams.FileInfoTimeout = (UINT32)strtol(optval, 0, 10);
        }
        else if (0 == strcmp(optarg, "DirInfoTimeout"))
        {
            mo->set_DirInfoTimeout = 1;
            mo->VolumeParams.DirInfoTimeout = (UINT32)strtol(optval, 0, 10);
        }
        else if (0 == strcmp(optarg, "EaTimeout"))
        {
            mo->set_EaTimeout = 1;
            mo->VolumeParams.EaTimeout = (UINT32)strtol(optval, 0, 10);
        }
        else if (0 == strcmp(optarg, "VolumeInfoTimeout"))
        {
            mo->set_VolumeInfoTimeout = 1;
            mo->VolumeParams.VolumeInfoTimeout = (UINT32)strtol(optval, 0, 10);
        }
        else if (0 == strcmp(optarg, "KeepFileCache"))
            mo->set_KeepFileCache = 1;
        else if (0 == strcmp(optarg, "UNC") || 0 == strcmp(optarg, "VolumePrefix"))
        {
            utf8_to_utf16(optval, mo->VolumeParams.Prefix,
                sizeof mo->VolumeParams.Prefix);
            for (WCHAR *P = mo->VolumeParams.Prefix; *P; P++)
                if ('/' == *P)
                    *P = '\\';
        }
        else if (0 == strcmp(optarg, "FileSystemName"))
        {
            utf8_to_utf16("FUSE-", mo->VolumeParams.FileSystemName,
                sizeof mo->VolumeParams.FileSystemName);
            utf8_to_utf16(optval, mo->VolumeParams.FileSystemName + 5,
                sizeof mo->VolumeParams.FileSystemName - 5 * sizeof(WCHAR));
        }
    }

    if (!mo->set_FileInfoTimeout && mo->set_attr_timeout)
        mo->VolumeParams.FileInfoTimeout = (UINT32)(mo->attr_timeout * 1000);
    if (mo->set_DirInfoTimeout)
        mo->VolumeParams.DirInfoTimeoutValid = 1;
    if (mo->set_EaTimeout)
        mo->VolumeParams.EaTimeoutValid = 1;
    if (mo->set_VolumeInfoTimeout)
        mo->VolumeParams.VolumeInfoTimeoutValid = 1;
    if (mo->set_KeepFileCache)
        mo->VolumeParams.FlushAndPurgeOnCleanup = 0;
    mo->VolumeParams.CaseSensitiveSearch = 1;
    mo->VolumeParams.CasePreservedNames = 1;
    mo->VolumeParams.PersistentAcls = 1;
    mo->VolumeParams.ReparsePoints = 1;
    mo->VolumeParams.ReparsePointsAccessCheck = 0;
    mo->VolumeParams.NamedStreams = 0;
    mo->VolumeParams.ReadOnlyVolume = 0;
    mo->VolumeParams.PostCleanupWhenModifiedOnly = 1;
    mo->VolumeParams.PassQueryDirectoryFileName = 1;
    mo->VolumeParams.DeviceControl = 1;
    if ('\0' == mo->VolumeParams.FileSystemName[0])
        utf8_to_utf16("FUSE", mo->VolumeParams.FileSystemName,
            sizeof mo->VolumeParams.FileSystemName);

    if (mo->VolumeParams.SectorSize < 512 ||
        mo->VolumeParams.SectorSize > 4096)
        mo->VolumeParams.SectorSize = 4096;
    if (mo->VolumeParams.SectorsPerAllocationUnit == 0)
        mo->VolumeParams.SectorsPerAllocationUnit = 1;
    if (0 == mo->VolumeParams.MaxComponentLength || mo->VolumeParams.MaxComponentLength > 255)
        mo->VolumeParams.MaxComponentLength = 255;
    if (0 == mo->VolumeParams.VolumeCreationTime)
    {
        struct timeval tv = { 0 };
        gettimeofday(&tv, 0);
        mo->VolumeParams.VolumeCreationTime = (UINT64)
            ((int64_t)tv.tv_sec * 10000000 + (int64_t)tv.tv_usec * 10 + 116444736000000000LL);
    }
    if (0 == mo->VolumeParams.VolumeSerialNumber)
        mo->VolumeParams.VolumeSerialNumber =
            (UINT32)(mo->VolumeParams.VolumeCreationTime >> 32) ^
            (UINT32)(mo->VolumeParams.VolumeCreationTime & 0xffffffff);
}

static int start_winmount_helper(const char *VolumeName, char WinMountPoint[260], pid_t *pidp, int *ofdp)
{
    int success = 0;
    pid_t pid;
    int ifd[2] = { -1, -1 };
    int ofd[2] = { -1, -1 };
    char *argv[4];
    char *p, *endp;
    ssize_t bytes;

    *pidp = -1;
    *ofdp = -1;

    if (-1 == pipe(ifd) || -1 == pipe(ofd))
    {
        warn("winmount: cannot create pipe: %s", strerror(errno));
        goto exit;
    }

    argv[0] = "/usr/bin/fusermount-helper.exe";
    argv[1] = (char *)VolumeName;
    argv[2] = '\0' != WinMountPoint[0] ? (char *)WinMountPoint : 0;
    argv[3] = 0;

    pid = fork();
    if (-1 == pid)
    {
        warn("winmount: cannot fork: %s", strerror(errno));
        goto exit;
    }
    else if (0 != pid)
        *pidp = pid;
    else
    {
        /* drop privileges */
        uid_t uid = getuid();
        gid_t gid = getgid();
        setgroups(1, &gid);
        setreuid(uid, uid);
        setregid(gid, gid);

        if (-1 == dup2(ifd[1], 1) || -1 == dup2(ofd[0], 0))
        {
            warn("winmount: cannot dup2: %s", strerror(errno));
            exit(1);
        }
        close(ofd[1]);
        close(ofd[0]);
        close(ifd[1]);
        close(ifd[0]);

        if (-1 == execv(argv[0], argv))
            warn("winmount: cannot execute %s: %s", argv[0], strerror(errno));
        exit(1);
    }

    close(ifd[1]); ifd[1] = -1;
    close(ofd[0]); ofd[0] = -1;

    for (p = WinMountPoint, endp = WinMountPoint + 260 - 1; endp > p; p += bytes)
    {
        bytes = read(ifd[0], p, (size_t)(endp - p));
        if (-1 == bytes)
        {
            if (EINTR != errno)
            {
                warn("winmount: cannot read output: %s", strerror(errno));
                goto exit;
            }
            bytes = 0;
        }
        else if (0 == bytes || 0 != memchr(p, 0, (size_t)bytes))
        {
            p += bytes;
            break;
        }
    }
    *p = '\0';

    if (WinMountPoint == p)
    {
        warn("winmount: no output");
        goto exit;
    }

    close(ifd[0]); ifd[0] = -1;

    *ofdp = ofd[1]; ofd[1] = -1;

    success = 1;

exit:
    if (-1 != ofd[1])
        close(ofd[1]);
    if (-1 != ofd[0])
        close(ofd[0]);

    if (-1 != ifd[1])
        close(ifd[1]);
    if (-1 != ifd[0])
        close(ifd[0]);

    return success ? 0 : -1;
}

static void stop_winmount_helper(pid_t pid, int ofd)
{
    ssize_t bytes;
    (void)bytes;

    bytes = write(ofd, "STOP", 4 + 1);
    close(ofd);

    waitpid(pid, 0, 0);
}

static int spawn_lxmount_helper(char WinMountPoint[260], const char *mountpoint, int fusefd, UINT64 VolumeId)
{
    /*
     * Spawn a child process to perform a Linux mount of the WinFsp volume asynchronously.
     *
     * This is necessary to avoid the deadlock described below.
     *
     * First observe that when mount(2) happens the FUSE file system is not yet ready to
     * accept file system requests. So any file system request will be queued within WinFsp
     * and will not be retrieved by the FUSE file system until after (it thinks that) the
     * mount(2) has completed.
     *
     * Now when mount(2) is invoked with type "drvfs", LXCORE attempts to open the volume
     * passed in the source argument (e.g. if the source argument is "Z:", then LXCORE will
     * attempt to open volume "Z:"). This should normally not be a problem because WinFsp
     * handles volume opens without forwarding them to the user mode file system. Unfortunately
     * some system filters convert a volume ("Z:") open request to a root directory ("Z:\")
     * open request, which is a request that must be handled by the user mode file system.
     * But the user mode file system is waiting for the mount/fusermount to complete, before it
     * can process requests. Hence deadlock!
     *
     * In order to work around this problem we perform the mount(2) asynchronously in a child
     * process. This of course means that we lie to the FUSE file system that the mount(2) was
     * successful, thus allowing it to process the root directory open request, which then
     * allows the mount(2) call to complete. The drawback is that if the mount(2) fails for
     * some reason the FUSE file system never hears about it. (However this is not considered
     * a huge problem, because the FUSE file system will still service the Windows drive that
     * we allocated for it correctly (see start_winmount_helper).)
     */

    pid_t pid;
    int status;

    /* fork the intermediate process */
    pid = fork();
    if (-1 == pid)
    {
        warn("lxmount: cannot fork intermediate process: %s", strerror(errno));
        return -1;
    }
    else if (0 != pid)
    {
        /* wait for the intermediate process */
		return
            pid == waitpid(pid, &status, 0) && WIFEXITED(status) && 0 == WEXITSTATUS(status) ?
            0 :
            -1;
    }

    /* become a session leader and ignore SIGHUP */
    setsid();
    signal(SIGHUP, SIG_IGN);

    /* fork a second time to get the process that will perform the Linux mount */
    pid = fork();
    if (-1 == pid)
    {
        warn("lxmount: cannot fork mount process: %s", strerror(errno));
        exit(1);
    }
    else if (0 != pid)
        /* exit the intermediate process; our child will be reaped by the init process */
        exit(0);

    /*
     * MOUNT PROCESS
     *
     * Grand-child of original fusermount process.
     */
    int success = 0;
    int mounted = 0, mnt_id;
    WSLFUSE_IOCTL_LXMOUNT_ARG LxMountArg;

    /*
     * Close the passed fusefd and reopen /dev/fuse. We will use the reopened fd
     * to communicate with WslFuse using special ioctl's.
     *
     * The reason for this is subtle: consider the earlier discussed deadlock and
     * the case where the FUSE file system fails to service the root directory open
     * request (e.g. because it crashed). Now we are in a situation where mount(2)
     * is waiting for a root directory open request to complete; this request is stuck
     * inside WinFsp; it has been retrieved by wslfuse and is either pending or
     * processing within the FUSE file system. Suppose now that the file system
     * terminates abruptly for some reason. The open request will never complete and
     * hence (a form of) deadlock again!
     *
     * Normally this is not a problem because upon termination of the FUSE process
     * all its file descriptors will be closed and WslFuse and WinFsp will have a
     * chance to purge their internal I/O queues thus canceling the root directory
     * open request, which allows mount(2) to complete. However when we forked our
     * mount process, the original fusefd was cloned and this keeps our internal I/O
     * queues alive. For this reason we have to close the fusefd in the mount process.
     */
    close(fusefd);
    fusefd = open("/dev/fuse", O_RDWR);
    if (-1 == fusefd)
    {
        warn("lxmount: cannot open /dev/fuse: %s", strerror(errno));
        goto exit;
    }

    /*
     * Mount the WinFsp volume using drvfs.
     */
    if (-1 == mount(WinMountPoint, mountpoint, "drvfs", 0, 0))
    {
        warn("lxmount: cannot mount %s: %s", mountpoint, strerror(errno));
        goto exit;
    }
    mounted = 1;

    /*
     * Get the mnt_id of the newly mounted file system.
     */
    mnt_id = get_mnt_id(mountpoint);
    if (-1 == mnt_id)
    {
        warn("lxmount: cannot get mnt_id: %s", strerror(errno));
        goto exit;
    }

    /*
     * Associate the WSL mnt_id with the /dev/fuse fd.
     */
    memset(&LxMountArg, 0, sizeof LxMountArg);
    LxMountArg.Operation = '+';
    LxMountArg.VolumeId = VolumeId;
    LxMountArg.LxMountId = (UINT64)mnt_id;
    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg))
    {
        warn("lxmount: cannot ioctl(m) /dev/fuse: %s", strerror(errno));
        goto exit;
    }

    success = 1;

exit:
    if (!success)
    {
        if (mounted)
            umount2(mountpoint, UMOUNT_NOFOLLOW);
    }

    exit(success ? 0 : 1);

    /* should not happen */
    return -1;
}

static void do_mount(void)
{
    int success = 0;
    struct mount_opts mo;
    const char *env;
    int commfd, fusefd = -1;
    WSLFUSE_IOCTL_CREATEVOLUME_ARG CreateArg;
    WSLFUSE_IOCTL_WINMOUNT_ARG WinMountArg;
    pid_t winmount_pid = -1;
    int winmount_fd = -1;
    struct msghdr msg;
    struct cmsghdr *cmsg;
    char cmsgbuf[CMSG_SPACE(sizeof fusefd)];
    struct iovec iov;
    char dummy = 0;

    mount_opt_parse(&mo);

    /*
     * Get the socket fd sent to us by the file system (via libfuse) from the environment.
     * We will use this fd to send our /dev/fuse fd to the file system once mounting completes.
     */
    env = getenv("_FUSE_COMMFD");
    if (0 == env)
    {
        warn("mount: environment variable _FUSE_COMMFD missing");
        goto exit;
    }
    commfd = atoi(env);

    /*
     * Open the /dev/fuse device. We use the returned fd to communicate with WslFuse using
     * special ioctl's. We will also return the fd to the file system via COMMFD.
     */
    fusefd = open("/dev/fuse", O_RDWR);
    if (-1 == fusefd)
    {
        warn("mount: cannot open /dev/fuse: %s", strerror(errno));
        goto exit;
    }

    /*
     * Send an ioctl to instruct WslFuse to create a new WinFsp volume.
     */
    memset(&CreateArg, 0, sizeof CreateArg);
    memcpy(&CreateArg.VolumeParams, &mo.VolumeParams, sizeof mo.VolumeParams);
    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_CREATEVOLUME, &CreateArg))
    {
        warn("mount: cannot ioctl(C) /dev/fuse: %s", strerror(errno));
        goto exit;
    }

    /*
     * Start the Windows side helper process to create the Windows mount point.
     */
    if (-1 == start_winmount_helper(CreateArg.VolumeName, mo.WinMountPoint, &winmount_pid, &winmount_fd))
        goto exit;

    /*
     * Associate the Windows mount point with the /dev/fuse fd.
     */
    memset(&WinMountArg, 0, sizeof WinMountArg);
    memcpy(WinMountArg.WinMountPoint, mo.WinMountPoint, sizeof WinMountArg.WinMountPoint);
    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_WINMOUNT, &WinMountArg))
    {
        warn("mount: cannot ioctl(M) /dev/fuse: %s", strerror(errno));
        goto exit;
    }

    /*
     * Send the /dev/fuse fd to the file system using COMMFD.
     */
    memset(&msg, 0, sizeof msg);
    msg.msg_control = cmsgbuf;
    msg.msg_controllen = sizeof cmsgbuf;
    cmsg = CMSG_FIRSTHDR(&msg);
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;
    cmsg->cmsg_len = CMSG_LEN(sizeof fusefd);
    memcpy(CMSG_DATA(cmsg), &fusefd, sizeof fusefd);
    msg.msg_controllen = cmsg->cmsg_len;
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    iov.iov_base = &dummy;
    iov.iov_len = sizeof dummy;
    while (-1 == sendmsg(commfd, &msg, 0))
        if (EINTR != errno)
        {
            warn("mount: cannot sendmsg to _FUSE_COMMFD: %s", strerror(errno));
            goto exit;
        }

    /*
     * Spawn a child process to perform a Linux mount of the WinFsp volume asynchronously.
     */
    if (-1 == spawn_lxmount_helper(mo.WinMountPoint, args.mountpoint, fusefd, CreateArg.VolumeId))
        goto exit;

    success = 1;

exit:
    if (-1 != winmount_pid)
        stop_winmount_helper(winmount_pid, winmount_fd);

    if (-1 != fusefd)
        close(fusefd);

    if (!success)
        exit(1);

    exit(0);
}

static void do_unmount(void)
{
    int success = 0;
    int fusefd = -1;
    int mnt_id;
    WSLFUSE_IOCTL_LXMOUNT_ARG LxMountArg;

    /*
     * Open the /dev/fuse device.
     */
    fusefd = open("/dev/fuse", O_RDWR);
    if (-1 == fusefd)
    {
        warn("unmount: cannot open /dev/fuse: %s", strerror(errno));
        goto exit;
    }

    /*
     * Get the mnt_id of the previously mounted file system.
     */
    mnt_id = get_mnt_id(args.mountpoint);
    if (-1 == mnt_id)
    {
        warn("unmount: cannot get mnt_id: %s", strerror(errno));
        goto exit;
    }

    /*
     * Verify the WSL mnt_id with WslFuse.
     */
    memset(&LxMountArg, 0, sizeof LxMountArg);
    LxMountArg.Operation = '?';
    LxMountArg.LxMountId = (UINT64)mnt_id;
    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg))
    {
        warn("unmount: unknown mountpoint %s", args.mountpoint);
        goto exit;
    }

    /*
     * Unmount the previously mounted file system.
     */
    if (-1 == umount2(args.mountpoint, args.lazy ? MNT_DETACH : 0))
        /* UMOUNT_NOFOLLOW not supported in WSL1 */
    {
        warn("unmount: cannot unmount %s: %s", args.mountpoint, strerror(errno));
        goto exit;
    }

    /*
     * Disassociate the WSL mnt_id from the /dev/fuse fd.
     */
    memset(&LxMountArg, 0, sizeof LxMountArg);
    LxMountArg.Operation = '-';
    LxMountArg.LxMountId = (UINT64)mnt_id;
    if (-1 == ioctl(fusefd, WSLFUSE_IOCTL_LXMOUNT, &LxMountArg) && ENOENT != errno)
    {
        warn("unmount: cannot ioctl(m) /dev/fuse: %s", strerror(errno));
        goto exit;
    }

    success = 1;

exit:
    if (-1 != fusefd)
        close(fusefd);

    if (!success)
        exit(1);

    exit(0);
}

static char *realpath_parent(const char *path)
{
    char *resolved = 0;
    char *pathcopy[2] = { 0, 0 };
    const char *parent, *leaf;
    char linkbuf[PATH_MAX];
    size_t rlen, llen;

    pathcopy[0] = strdup(path);
    if (0 == pathcopy[0])
        goto fail;
    pathcopy[1] = strdup(path);
    if (0 == pathcopy[1])
        goto fail;

    resolved = malloc(PATH_MAX);
    if (0 == resolved)
        goto fail;

    parent = dirname(pathcopy[0]);
    leaf = basename(pathcopy[1]);

    if (0 == realpath(parent, resolved))
        goto fail;

    rlen = strlen(resolved);
    llen = strlen(leaf);
    if (PATH_MAX < rlen + llen + 2)
    {
        errno = ENAMETOOLONG;
        goto fail;
    }
    resolved[rlen] = '/';
    memcpy(resolved + rlen + 1, leaf, llen);
    resolved[rlen + 1 + llen] = '\0';

    if (-1 != readlink(resolved, linkbuf, sizeof linkbuf))
    {
        errno = EINVAL;
        goto fail;
    }
    else if (EINVAL != errno)
        goto fail;

    free(pathcopy[1]);
    free(pathcopy[0]);

    return resolved;

fail:
    free(resolved);

    free(pathcopy[1]);
    free(pathcopy[0]);

    return 0;
}

static void do_version(void)
{
    fprintf(stdout, "%s version: %s\n", progname, "wslfuse");
    exit(0);
}

static void usage(void)
{
    warn(
        "%s: [options] mountpoint\n"
        "Options:\n"
        "    -h                          print help\n"
        "    -V                          print version\n"
        "    -o opt[,opt...]             mount options\n"
        "    -u                          unmount\n"
        "    -z                          lazy unmount\n"
        "    -q                          quiet\n"
        "",
        progname);
    exit(2);
}

int main(int argc, char *argv[])
{
    progname = basename(argv[0]);

    static struct option longopts[] =
    {
        { "help", no_argument, 0, 'h' },
        { "version", no_argument, 0, 'V' },
        { "unmount", no_argument, 0, 'u' },
        { "lazy", no_argument, 0, 'z' },
        { "quiet", no_argument, 0, 'q' },
        { 0 },
    };
    int quiet = 0;
    int opt;
    while (-1 != (opt = getopt_long(argc, argv, "hVo:uzq", longopts, 0)))
        switch (opt)
        {
        default:
        case 'h':
            usage();
            break;
        case 'V':
            do_version();
            break;
        case 'o':
            args.opts = optarg;
            break;
        case 'u':
            args.unmount = 1;
            break;
        case 'z':
            args.lazy = 1;
            break;
        case 'q':
            quiet = 1;
            break;
        }

    if (argc != optind + 1)
        usage();
    args.quiet = quiet;

    if (!args.unmount)
        args.mountpoint = realpath(argv[optind], 0);
    else
        args.mountpoint = realpath_parent(argv[optind]);
    if (0 == args.mountpoint)
    {
        warn("mountpoint: %s", strerror(errno));
        exit(1);
    }

    if (!args.unmount)
        do_mount();

    do_unmount();

    return 0;
}


================================================
FILE: src/fusermount/install.sh
================================================
set -e

if [ "$(id -u)" != "0" ]; then
    echo "must be run as superuser" 1>&2; exit 1
fi

cd "$(dirname "$0")"

# fusermount
cmp_install()
{
    local src=""
    local dst=""
    for arg in "$@"; do src="$dst"; dst="$arg"; done
    cmp -s "$src" "$dst" || install "$@"
}
cmp_install --backup=numbered -o0 -g0 -mu=srwx,go=rx fusermount.out /usr/bin/fusermount
cmp_install --backup=numbered -o0 -g0 -mu=srwx,go=rx fusermount.out /usr/bin/fusermount3
cmp_install -o0 -g0 -mu=rwx,go=rx fusermount-helper.exe /usr/bin/fusermount-helper.exe

# /dev/fuse
echo c /dev/fuse 0666 root root - 10:229 > /etc/tmpfiles.d/wslfuse.conf
systemd-tmpfiles --create wslfuse.conf

echo FUSE for WSL1 user space components installed


================================================
FILE: src/fusermount/uninstall.sh
================================================
#set -x

if [ "$(id -u)" != "0" ]; then
    echo "must be run as superuser" 1>&2; exit 1
fi

cd "$(dirname "$0")"

# /dev/fuse
rm -f /etc/tmpfiles.d/wslfuse.conf
rm -f /dev/fuse

# fusermount
uninstall()
{
    local src="$1"
    local dst="$2"
    if cmp -s "$src" "$dst"; then
        local bak=$(ls -1rv "$dst".~*~ 2>/dev/null | head -1)
        if [ -n "$bak" ]; then
            mv -f "$bak" "$dst"
        else
            rm -f "$dst"
        fi
    fi
}
uninstall fusermount.out /usr/bin/fusermount
uninstall fusermount.out /usr/bin/fusermount3
rm -f /usr/bin/fusermount-helper.exe

echo FUSE for WSL1 user space components uninstalled


================================================
FILE: src/shared/km/cache.c
================================================
/**
 * @file shared/km/cache.c
 *
 * @copyright 2019-2020 Bill Zissimopoulos
 */
/*
 * This file is part of WinFuse.
 *
 * You can redistribute it and/or modify it under the terms of the GNU
 * Affero General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * Licensees holding a valid commercial license may use this software
 * in accordance with the commercial license agreement provided in
 * conjunction with the software.  The terms and conditions of any such
 * commercial license agreement shall govern, supersede, and render
 * ineffective any application of the AGPLv3 license to this software,
 * notwithstanding of any reference thereto in the software or
 * associated repository.
 */

#include <shared/km/shared.h>

/*
 * FUSE "entry" cache
 *
 * The cache is implemented as a hash table that maps parent inode number, child name
 * tuples to FUSE protocol "entries":
 *     <parent_ino, child_name> -> <child_ino, child_attr> ("entry")
 *
 * There are two important complications:
 *
 * (1) Entries have an expiration time after which they may no longer be valid.
 * Entries that have expired must not be returned to users of this class and must eventually
 * be "forgotten" (i.e. a FUSE FORGET message must be sent to the user mode file system).
 *
 * (2) Entries may be in use when they become expired/invalid. In this case the
 * corresponding FORGET message must be delayed to ensure that the user mode file system
 * keeps the relevant inode information around (even if the associated information is
 * expired).
 *
 * To accommodate complication (1) this implementation maintains cached entries in an LRU
 * (least-recently-used) list and expires them periodically. It should be noted that this
 * implementation does not sort entries by expiration time; so it is possible for an entry
 * that has not expired but was not recently used to be purged prior to an entry that has
 * expired, but was recently used.
 *
 * To accommodate complication (2) this implementation maintains a list of monotonic
 * "generations" that control when entries are actually "forgotten". As file system
 * operations arrive, the current generation is computed from the "interrupt time"
 * and a reference is taken on that generation (i.e. a reference count is incremented).
 * When the operation is complete the reference on the associated generation is released
 * (i.e. the reference count is decremented). If there are no remaining references on the
 * generation (i.e. the reference count is zero) the generation can be "forgotten", which
 * means that all entries that have expired and have not been used since the generation's
 * time can now be "forgotten" (i.e. the corresponding FUSE messages can be sent).
 *
 * These two primary complications together with the fact that the implementation must
 * deal with failures and re-setting existing entries make the code rather complicated.
 */

NTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_CACHE **PCache);
VOID FuseCacheDelete(FUSE_CACHE *Cache);
VOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache,
    FUSE_INSTANCE *Instance, UINT64 ExpirationTime);
NTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen);
VOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen);
BOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,
    FUSE_PROTO_ENTRY *Entry, PVOID *PItem);
VOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,
    FUSE_PROTO_ENTRY *Entry, PVOID *PItem);
VOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name);
VOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item);
VOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item);
VOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item);
VOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList);
BOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE *PForgetOne);

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, FuseCacheCreate)
#pragma alloc_text(PAGE, FuseCacheDelete)
#pragma alloc_text(PAGE, FuseCacheExpirationRoutine)
#pragma alloc_text(PAGE, FuseCacheReferenceGen)
#pragma alloc_text(PAGE, FuseCacheDereferenceGen)
#pragma alloc_text(PAGE, FuseCacheGetEntry)
#pragma alloc_text(PAGE, FuseCacheSetEntry)
#pragma alloc_text(PAGE, FuseCacheRemoveEntry)
#pragma alloc_text(PAGE, FuseCacheReferenceItem)
#pragma alloc_text(PAGE, FuseCacheDereferenceItem)
#pragma alloc_text(PAGE, FuseCacheQuickExpireItem)
#pragma alloc_text(PAGE, FuseCacheDeleteForgotten)
#pragma alloc_text(PAGE, FuseCacheForgetOne)
#endif

typedef struct _FUSE_CACHE_ITEM FUSE_CACHE_ITEM;

struct _FUSE_CACHE
{
    ULONG Capacity;
    BOOLEAN CaseInsensitive;
    FAST_MUTEX Mutex;
    LIST_ENTRY GenList;
    LIST_ENTRY ItemList;
    LIST_ENTRY ForgetList;
    ULONG ItemCount;
    ULONG ItemBucketCount;
    PVOID ItemBuckets[];
};

struct _FUSE_CACHE_GEN
{
    LIST_ENTRY ListEntry;
    LONG RefCount;
    UINT64 InterruptTime;
};

struct _FUSE_CACHE_ITEM
{
    struct _FUSE_CACHE_ITEM *DictNext;
    LIST_ENTRY ListEntry;
    BOOLEAN NoForget;
    ULONG Hash;
    UINT64 ParentIno;
    STRING Name;
    UINT64 NLookup;
    UINT64 ExpirationTime;
    UINT64 LastUsedTime;
    FUSE_PROTO_ENTRY Entry;
    LONG QuickExpiry;
    LONG RefCount;
    CHAR NameBuf[];
};

static inline UINT64 FuseCacheForgetTime(FUSE_CACHE *Cache, UINT64 InterruptTime)
{
    if (!IsListEmpty(&Cache->GenList))
    {
        FUSE_CACHE_GEN *Gen = CONTAINING_RECORD(Cache->GenList.Flink, FUSE_CACHE_GEN, ListEntry);
        if (InterruptTime >= Gen->InterruptTime)
            InterruptTime = Gen->InterruptTime - 1;
    }
    return InterruptTime;
}

static inline BOOLEAN FuseCacheForgetNextItem(FUSE_CACHE *Cache,
    UINT64 ExpirationTime, PLIST_ENTRY ForgetList)
{
    if (!IsListEmpty(&Cache->ForgetList))
    {
        FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Cache->ForgetList.Flink, FUSE_CACHE_ITEM, ListEntry);
        if (FuseCacheForgetTime(Cache, ExpirationTime) >= Item->LastUsedTime)
        {
            RemoveEntryList(&Item->ListEntry);
            InsertTailList(ForgetList, &Item->ListEntry);
            return TRUE;
        }
    }
    return FALSE;
}

static inline BOOLEAN FuseCacheExpireItem(FUSE_CACHE *Cache,
    FUSE_CACHE_ITEM *Item)
{
    ULONG HashIndex = Item->Hash % Cache->ItemBucketCount;
    for (FUSE_CACHE_ITEM **P = (PVOID)&Cache->ItemBuckets[HashIndex]; *P; P = &(*P)->DictNext)
        if (*P == Item)
        {
            *P = (*P)->DictNext;
            RemoveEntryList(&Item->ListEntry);
            Cache->ItemCount--;
            if (0 == InterlockedDecrement(&Item->RefCount))
                InsertTailList(&Cache->ForgetList, &Item->ListEntry);
            return TRUE;
        }
    return FALSE;
}

static inline BOOLEAN FuseCacheExpireNextItem(FUSE_CACHE *Cache,
    UINT64 ExpirationTime)
{
    if (!IsListEmpty(&Cache->ItemList))
    {
        FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Cache->ItemList.Flink, FUSE_CACHE_ITEM, ListEntry);
        if (ExpirationTime >= Item->ExpirationTime ||
            InterlockedCompareExchange(&Item->QuickExpiry, 1, 1))
            return FuseCacheExpireItem(Cache, Item);
    }
    return FALSE;
}

static inline size_t hash_chars(const char *s, size_t length)
{
    /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */
    size_t h = 5381;
    for (const char *t = s + length; t > s; ++s)
        h = 33 * h + *s;
    return h;
}

static inline size_t hash_upper_chars(const char *s, size_t length)
{
    /* djb2: see http://www.cse.yorku.ca/~oz/hash.html */
    size_t h = 5381;
    for (const char *t = s + length; t > s; ++s)
        h = 33 * h + RtlUpperChar(*s);
    return h;
}

static inline ULONG FuseCacheHash(UINT64 ParentIno, PSTRING Name, BOOLEAN CaseInsensitive)
{
    return (ULONG)FuseHashMix64(ParentIno) ^
        (0 != Name ? (ULONG)(CaseInsensitive ?
            hash_upper_chars(Name->Buffer, Name->Length) : hash_chars(Name->Buffer, Name->Length)) : 0);
}

static inline FUSE_CACHE_ITEM *FuseCacheLookupHashedItem(FUSE_CACHE *Cache,
    ULONG Hash, UINT64 ParentIno, PSTRING Name)
{
    FUSE_CACHE_ITEM *Item = 0;
    ULONG HashIndex = Hash % Cache->ItemBucketCount;
    for (FUSE_CACHE_ITEM *ItemX = Cache->ItemBuckets[HashIndex]; ItemX; ItemX = ItemX->DictNext)
        if (ItemX->Hash == Hash &&
            ItemX->ParentIno == ParentIno &&
            RtlEqualString(&ItemX->Name, Name, Cache->CaseInsensitive))
        {
            Item = ItemX;
            break;
        }
    return Item;
}

static inline VOID FuseCacheAddItem(FUSE_CACHE *Cache,
    FUSE_CACHE_ITEM *Item)
{
    ULONG HashIndex = Item->Hash % Cache->ItemBucketCount;
#if DBG
    for (FUSE_CACHE_ITEM *ItemX = Cache->ItemBuckets[HashIndex]; ItemX; ItemX = ItemX->DictNext)
        if (ItemX->Hash == Item->Hash &&
            ItemX->ParentIno == Item->ParentIno &&
            RtlEqualString(&ItemX->Name, &Item->Name, Cache->CaseInsensitive))
        {
            ASSERT(0);
        }
#endif
    Item->DictNext = Cache->ItemBuckets[HashIndex];
    Cache->ItemBuckets[HashIndex] = Item;
    /* mark as most-recently used */
    InsertTailList(&Cache->ItemList, &Item->ListEntry);
    Cache->ItemCount++;
}

static inline FUSE_CACHE_ITEM *FuseCacheUpdateHashedItem(FUSE_CACHE *Cache,
    ULONG Hash, UINT64 ParentIno, PSTRING Name,
    UINT64 ExpirationTime, UINT64 LastUsedTime, FUSE_PROTO_ENTRY *Entry)
{
    FUSE_CACHE_ITEM *Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name);
    if (0 != Item)
    {
        if (Entry->nodeid == Item->Entry.nodeid &&
            !InterlockedCompareExchange(&Item->QuickExpiry, 1, 1))
        {
            Item->NLookup++;
            Item->ExpirationTime = ExpirationTime;
            Item->LastUsedTime = LastUsedTime;
            RtlCopyMemory(&Item->Entry, Entry, sizeof Item->Entry);

            /* mark as most-recently used */
            RemoveEntryList(&Item->ListEntry);
            InsertTailList(&Cache->ItemList, &Item->ListEntry);
        }
        else
        {
            FuseCacheExpireItem(Cache, Item);
            Item = 0;
        }
    }
    return Item;
}

NTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_CACHE **PCache)
{
    PAGED_CODE();

    FUSE_CACHE *Cache;
    ULONG CacheSize;

    *PCache = 0;

    if (0 == Capacity)
        Capacity = ((PAGE_SIZE - sizeof *Cache) / sizeof Cache->ItemBuckets[0]) * 3 / 4;

    CacheSize = (Capacity * 4 / 3) * sizeof Cache->ItemBuckets[0] + sizeof *Cache;
    CacheSize = FSP_FSCTL_ALIGN_UP(CacheSize, PAGE_SIZE);

    Cache = FuseAllocNonPaged(CacheSize);
        /* FAST_MUTEX's must be in non-paged memory */
    if (0 == Cache)
        return STATUS_INSUFFICIENT_RESOURCES;

    RtlZeroMemory(Cache, CacheSize);
    Cache->Capacity = Capacity;
    Cache->CaseInsensitive = CaseInsensitive;
    ExInitializeFastMutex(&Cache->Mutex);
    InitializeListHead(&Cache->GenList);
    InitializeListHead(&Cache->ItemList);
    InitializeListHead(&Cache->ForgetList);
    Cache->ItemBucketCount = (CacheSize - sizeof *Cache) / sizeof Cache->ItemBuckets[0];

    *PCache = Cache;

    return STATUS_SUCCESS;
}

VOID FuseCacheDelete(FUSE_CACHE *Cache)
{
    PAGED_CODE();

    for (PLIST_ENTRY Entry = Cache->GenList.Flink; &Cache->GenList != Entry;)
    {
        FUSE_CACHE_GEN *Gen = CONTAINING_RECORD(Entry, FUSE_CACHE_GEN, ListEntry);
        Entry = Entry->Flink;
        FuseFree(Gen);
    }

    FuseCacheDeleteForgotten(&Cache->ItemList);
    FuseCacheDeleteForgotten(&Cache->ForgetList);

    FuseFree(Cache);
}

VOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache,
    FUSE_INSTANCE *Instance, UINT64 ExpirationTime)
{
    PAGED_CODE();

    LIST_ENTRY ForgetList;

    InitializeListHead(&ForgetList);

    ExAcquireFastMutex(&Cache->Mutex);

    while (FuseCacheExpireNextItem(Cache, ExpirationTime))
        ;

    while (FuseCacheForgetNextItem(Cache, ExpirationTime, &ForgetList))
        ;

    ExReleaseFastMutex(&Cache->Mutex);

    for (PLIST_ENTRY Entry = ForgetList.Flink; &ForgetList != Entry;)
    {
        FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry);
        Entry = Entry->Flink;
        if (Item->NoForget)
        {
            RemoveEntryList(&Item->ListEntry);
            FuseFree(Item);
        }
    }

    if (!IsListEmpty(&ForgetList))
    {
        BOOLEAN Success = DEBUGTEST(90) &&
            NT_SUCCESS(FuseProtoPostForget(Instance, &ForgetList));
        if (!Success)
        {
            ASSERT(!IsListEmpty(&ForgetList));

            ExAcquireFastMutex(&Cache->Mutex);

            /* re-add forgotten items in the "forget list" */
            RemoveEntryList(&ForgetList);
                /* see AppendTailList comments */
#if 0
            /* append */
            AppendTailList(&Cache->ForgetList, &ForgetList);
#else
            /* prepend */
            PLIST_ENTRY ListToPrepend = ForgetList.Flink;
            PLIST_ENTRY ListHead = &Cache->ForgetList;
            PLIST_ENTRY ListBegin = ListHead->Flink;
            ListBegin->Blink = ListToPrepend->Blink;
            ListHead->Flink = ListToPrepend;
            ListToPrepend->Blink->Flink = ListBegin;
            ListToPrepend->Blink = ListHead;
#endif

            ExReleaseFastMutex(&Cache->Mutex);
        }
    }
}

NTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen)
{
    PAGED_CODE();

    UINT64 InterruptTime = KeQueryInterruptTime() / 10000000 * 10000000;
    FUSE_CACHE_GEN *Gen = 0, *NewGen = 0;

    *PGen = 0;

    ExAcquireFastMutex(&Cache->Mutex);

    if (!IsListEmpty(&Cache->GenList))
    {
        Gen = CONTAINING_RECORD(Cache->GenList.Blink, FUSE_CACHE_GEN, ListEntry);
        if (InterruptTime <= Gen->InterruptTime)
            Gen->RefCount++;
        else
            Gen = 0;
    }

    ExReleaseFastMutex(&Cache->Mutex);

    if (0 == Gen)
    {
        NewGen = FuseAlloc(sizeof *NewGen);
        if (0 == NewGen)
            return STATUS_INSUFFICIENT_RESOURCES;

        RtlZeroMemory(NewGen, sizeof *NewGen);
        NewGen->RefCount = 1;
        NewGen->InterruptTime = InterruptTime;

        ExAcquireFastMutex(&Cache->Mutex);

        if (!IsListEmpty(&Cache->GenList))
        {
            Gen = CONTAINING_RECORD(Cache->GenList.Blink, FUSE_CACHE_GEN, ListEntry);
            if (InterruptTime <= Gen->InterruptTime)
                Gen->RefCount++;
            else
                Gen = 0;
        }
        if (0 == Gen)
        {
            InsertTailList(&Cache->GenList, &NewGen->ListEntry);

            Gen = NewGen;
            NewGen = 0;
        }

        ExReleaseFastMutex(&Cache->Mutex);
    }

    *PGen = Gen;

    if (0 != NewGen)
        FuseFree(NewGen);

    return STATUS_SUCCESS;
}

VOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen0)
{
    PAGED_CODE();

    FUSE_CACHE_GEN *Gen = Gen0;
    LONG RefCount;

    if (0 == Gen)
        return;

    ExAcquireFastMutex(&Cache->Mutex);
    RefCount = --Gen->RefCount;
    if (0 == RefCount)
        RemoveEntryList(&Gen->ListEntry);
    ExReleaseFastMutex(&Cache->Mutex);

    if (0 == RefCount)
        FuseFree(Gen);
}

BOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,
    FUSE_PROTO_ENTRY *Entry, PVOID *PItem)
{
    PAGED_CODE();

    UINT64 InterruptTime = KeQueryInterruptTime();
    FUSE_CACHE_ITEM *Item;
    ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive);

    ExAcquireFastMutex(&Cache->Mutex);

    Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name);
    if (0 != Item)
    {
        if (InterruptTime < Item->ExpirationTime &&
            !InterlockedCompareExchange(&Item->QuickExpiry, 1, 1))
        {
            Item->LastUsedTime = InterruptTime;
            RtlCopyMemory(Entry, &Item->Entry, sizeof Item->Entry);

            /* mark as most-recently used */
            RemoveEntryList(&Item->ListEntry);
            InsertTailList(&Cache->ItemList, &Item->ListEntry);
        }
        else
        {
            FuseCacheExpireItem(Cache, Item);
            Item = 0;
        }
    }

    ExReleaseFastMutex(&Cache->Mutex);

    *PItem = Item;
    return 0 != Item;
}

VOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,
    FUSE_PROTO_ENTRY *Entry, PVOID *PItem)
{
    PAGED_CODE();

    UINT64 InterruptTime = KeQueryInterruptTime();
    UINT64 EntryTimeout = Entry->entry_valid * 10000000 + Entry->entry_valid_nsec / 100;
    UINT64 AttrTimeout = Entry->attr_valid * 10000000 + Entry->attr_valid_nsec / 100;
    UINT64 ExpirationTime = InterruptTime +
        (EntryTimeout < AttrTimeout ? EntryTimeout : AttrTimeout);
    FUSE_CACHE_ITEM *Item = 0, *NewItem = 0;
    ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive);

    ExAcquireFastMutex(&Cache->Mutex);

    Item = FuseCacheUpdateHashedItem(Cache,
        Hash, ParentIno, Name, ExpirationTime, InterruptTime, Entry);

    ExReleaseFastMutex(&Cache->Mutex);

    if (0 == Item)
    {
        NewItem = FuseAllocMustSucceed(FIELD_OFFSET(FUSE_CACHE_ITEM, NameBuf) + Name->Length);

        RtlZeroMemory(NewItem, FIELD_OFFSET(FUSE_CACHE_ITEM, NameBuf));
        NewItem->NoForget =
            /* the root is not LOOKUP'ed; free without FORGET */
            ParentIno == FUSE_PROTO_ROOT_INO && 1 == Name->Length && '/' == Name->Buffer[0];
        NewItem->Hash = Hash;
        NewItem->ParentIno = ParentIno;
        NewItem->Name.Length = NewItem->Name.MaximumLength = Name->Length;
        NewItem->Name.Buffer = NewItem->NameBuf;
        NewItem->NLookup = 1;
        NewItem->ExpirationTime = ExpirationTime;
        NewItem->LastUsedTime = InterruptTime;
        NewItem->RefCount = 1;
        RtlCopyMemory(&NewItem->Entry, Entry, sizeof NewItem->Entry);
        RtlCopyMemory(&NewItem->NameBuf, Name->Buffer, Name->Length);

        ExAcquireFastMutex(&Cache->Mutex);

        Item = FuseCacheUpdateHashedItem(Cache,
            Hash, ParentIno, Name, ExpirationTime, InterruptTime, Entry);
        if (0 == Item)
        {
            if (Cache->ItemCount >= Cache->Capacity)
                FuseCacheExpireNextItem(Cache, (UINT64)-1LL);

            FuseCacheAddItem(Cache, NewItem);

            Item = NewItem;
            NewItem = 0;
        }

        ExReleaseFastMutex(&Cache->Mutex);
    }

    if (0 != NewItem)
        FuseFree(NewItem);

    *PItem = Item;
}

VOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name)
{
    PAGED_CODE();

    FUSE_CACHE_ITEM *Item;
    ULONG Hash = FuseCacheHash(ParentIno, Name, Cache->CaseInsensitive);

    ExAcquireFastMutex(&Cache->Mutex);

    Item = FuseCacheLookupHashedItem(Cache, Hash, ParentIno, Name);
    if (0 != Item)
        FuseCacheExpireItem(Cache, Item);

    ExReleaseFastMutex(&Cache->Mutex);
}

VOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item0)
{
    PAGED_CODE();

    FUSE_CACHE_ITEM *Item = Item0;

    InterlockedIncrement(&Item->RefCount);
}

VOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item0)
{
    PAGED_CODE();

    FUSE_CACHE_ITEM *Item = Item0;
    LONG RefCount;

    if (0 == Item)
        return;

    RefCount = InterlockedDecrement(&Item->RefCount);
    if (0 == RefCount)
    {
        ExAcquireFastMutex(&Cache->Mutex);
        InsertTailList(&Cache->ForgetList, &Item->ListEntry);
        ExReleaseFastMutex(&Cache->Mutex);
    }
}

VOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item0)
{
    PAGED_CODE();

    FUSE_CACHE_ITEM *Item = Item0;

    InterlockedExchange(&Item->QuickExpiry, 1);
}

VOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList)
{
    PAGED_CODE();

    for (PLIST_ENTRY Entry = ForgetList->Flink; ForgetList != Entry;)
    {
        FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry);
        Entry = Entry->Flink;
        FuseFree(Item);
    }
}

BOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE *PForgetOne)
{
    PAGED_CODE();

    PLIST_ENTRY Entry = RemoveHeadList(ForgetList);
    if (ForgetList == Entry)
        return FALSE;

    FUSE_CACHE_ITEM *Item = CONTAINING_RECORD(Entry, FUSE_CACHE_ITEM, ListEntry);
    ASSERT(!Item->NoForget);
    PForgetOne->nodeid = Item->Entry.nodeid;
    PForgetOne->nlookup = Item->NLookup;
    FuseFree(Item);

    return TRUE;
}


================================================
FILE: src/shared/km/context.c
================================================
/**
 * @file shared/km/context.c
 *
 * @copyright 2019-2020 Bill Zissimopoulos
 */
/*
 * This file is part of WinFuse.
 *
 * You can redistribute it and/or modify it under the terms of the GNU
 * Affero General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * Licensees holding a valid commercial license may use this software
 * in accordance with the commercial license agreement provided in
 * conjunction with the software.  The terms and conditions of any such
 * commercial license agreement shall govern, supersede, and render
 * ineffective any application of the AGPLv3 license to this software,
 * notwithstanding of any reference thereto in the software or
 * associated repository.
 */

#include <shared/km/shared.h>

VOID FuseContextCreate(FUSE_CONTEXT **PContext,
    FUSE_INSTANCE *Instance, FSP_FSCTL_TRANSACT_REQ *InternalRequest);
VOID FuseContextDelete(FUSE_CONTEXT *Context);

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, FuseContextCreate)
#pragma alloc_text(PAGE, FuseContextDelete)
#endif

VOID FuseContextCreate(FUSE_CONTEXT **PContext,
    FUSE_INSTANCE *Instance, FSP_FSCTL_TRANSACT_REQ *InternalRequest)
{
    PAGED_CODE();

    FUSE_CONTEXT *Context;
    UINT32 Kind = 0 == InternalRequest ?
        FspFsctlTransactReservedKind : InternalRequest->Kind;

    ASSERT(FspFsctlTransactKindCount > Kind);
    if (0 == FuseOperations[Kind].Proc)
    {
        *PContext = FuseContextStatus(STATUS_INVALID_DEVICE_REQUEST);
        return;
    }

    Context = FuseAlloc(sizeof *Context);
    if (0 == Context)
    {
        *PContext = FuseContextStatus(STATUS_INSUFFICIENT_RESOURCES);
        return;
    }

    RtlZeroMemory(Context, sizeof *Context);
    Context->Instance = Instance;
    Context->InternalRequest = InternalRequest;
    Context->InternalResponse = (PVOID)&Context->InternalResponseBuf;
    Context->InternalResponse->Size = sizeof(FSP_FSCTL_TRANSACT_RSP);
    Context->InternalResponse->Kind = Kind;
    Context->InternalResponse->Hint = 0 != InternalRequest ? InternalRequest->Hint : 0;
    *PContext = Context;
}

VOID FuseContextDelete(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    if (FuseOpGuardTrue == Context->OpGuardResult)
    {
        UINT32 Kind = 0 == Context->InternalRequest ?
            FspFsctlTransactReservedKind : Context->InternalRequest->Kind;
        FuseOperations[Kind].Guard(Context, FALSE);
    }

    if (0 != Context->Fini)
        Context->Fini(Context);
    if (0 != Context->InternalRequest)
        FuseFree(Context->InternalRequest);
    if ((PVOID)&Context->InternalResponseBuf != Context->InternalResponse)
        FuseFree(Context->InternalResponse);

    DEBUGFILL(Context, sizeof *Context);
    FuseFree(Context);
}


================================================
FILE: src/shared/km/coro.h
================================================
/**
 * @file shared/km/coro.h
 *
 * @copyright 2019-2020 Bill Zissimopoulos
 */
/*
 * This file is part of WinFuse.
 *
 * You can redistribute it and/or modify it under the terms of the GNU
 * Affero General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * Licensees holding a valid commercial license may use this software
 * in accordance with the commercial license agreement provided in
 * conjunction with the software.  The terms and conditions of any such
 * commercial license agreement shall govern, supersede, and render
 * ineffective any application of the AGPLv3 license to this software,
 * notwithstanding of any reference thereto in the software or
 * associated repository.
 */

#ifndef SHARED_KM_CORO_H_INCLUDED
#define SHARED_KM_CORO_H_INCLUDED

/*
 * Nested coroutines
 *
 * This is a simple implementation of nested coroutines for C using macros. It introduces
 * the macros coro_block, coro_await, coro_yield and coro_break that are used to create coroutines,
 * suspend/resume them and exit them. This implementation supports nested coroutines in that
 * a coroutine may invoke another coroutine and the whole stack of coroutines may be suspended
 * and later resumed.
 *
 * The implementation is able to do this by maintaining a stack of program "points" where
 * coroutine execution may be suspended and later resumed. The implementation achieves this by
 * (ab)using a peculiarity of the C switch statement in that it allows case: labels to appear
 * anywhere within the body of a switch statement including nested compound statements.
 *
 * While this implementation is able to maintain the stack of program "points" where execution
 * may be resumed, it is not able to automatically maintain important state such as activation
 * records (local variables). It is the responsibility of the programmer using these macros
 * to maintain this state. Usually this is done by moving all local variables together with the
 * space for the program "points" stack into a heap allocation that is then passed as an argument
 * to the coroutines.
 *
 * The original coroutine implementation was done some time around 2010 and did not support
 * nesting. It was used to facilitate the implementation of complex iterators in a C++ library.
 * It was inspired by Simon Tatham's "Coroutines in C":
 *     http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
 *
 * Reference
 *
 * The coroutine state is maintained in an integer array (S) whose address is passed to the
 * "block" statement. The array's number of elements must be 2 plus the number of expected
 * coroutines (e.g. if you expect to have up to 3 nested coroutines, the array must have at
 * least 5 elements). The array must be initialized to 0 on initial entry to a coroutine block.
 *
 *     coro_block(S)
 *         This macro introduces a coroutine statement block { ... } where the "await", "yield",
 *         and "break" statements can be used. There can only be one such block within a function.
 *     coro_await(E)
 *         This macro executes the expression E, which should be an invocation of a coroutine.
 *         The nested coroutine may suspend itself, in which case the "await" statement exits
 *         the current coroutine statement block. The coroutine block can be reentered in which
 *         case execution will continue within the coroutine invoked by E, unless the coroutine
 *         is complete. It is an error to use "await" outside of a coroutine block.
 *     coro_yield
 *         This macro exits the current coroutine statement block. The coroutine block can be
 *         reentered in which case execution will continue after the "yield" statement. It is
 *         an error to use "yield" outside of a coroutine block.
 *     coro_break
 *         This macro exits the current coroutine statement block and marks it as "complete".
 *         If the coroutine block is reentered it exits immediately. It is an error to use "break"
 *         outside of a coroutine block.
 */
#define coro_block(S)       short *coro_S__ = (S); if (!coro_active()) coro_X__:; else \
                            switch (coro_enter__()) for (; 0,0; coro_leave__(-1)) case 0:
#define coro_await__(N, E)  do { E; coro_cond_leave__(N); goto coro_X__; case N:; } while (1,1)
#define coro_yield__(N)     do { coro_leave__(N); goto coro_X__; case N:; } while (0,0)
#define coro_break          do { coro_leave__(-1); goto coro_X__; } while (0,0)
#define coro_active()       (-1 != coro_below__)
#define coro_below__        (coro_S__[coro_S__[0] + 1])
#define coro_enter__()      (coro_S__[++coro_S__[0]])
#define coro_leave__(N)     (coro_below__ = 0, coro_S__[coro_S__[0]--] = N)
#define coro_cond_leave__(N)if (!coro_active()) { coro_below__ = 0; break; } (coro_S__[coro_S__[0]--] = N)
#if defined(__COUNTER__)
#define coro_await(...)     coro_await__((__COUNTER__ + 1), (__VA_ARGS__))
#define coro_yield          coro_yield__((__COUNTER__ + 1))
#else
#define coro_await(...)     coro_await__(__LINE__, (__VA_ARGS__))
#define coro_yield          coro_yield__(__LINE__)
#endif

#endif


================================================
FILE: src/shared/km/debug.c
================================================
/**
 * @file shared/km/debug.c
 *
 * @copyright 2019-2020 Bill Zissimopoulos
 */
/*
 * This file is part of WinFuse.
 *
 * You can redistribute it and/or modify it under the terms of the GNU
 * Affero General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * Licensees holding a valid commercial license may use this software
 * in accordance with the commercial license agreement provided in
 * conjunction with the software.  The terms and conditions of any such
 * commercial license agreement shall govern, supersede, and render
 * ineffective any application of the AGPLv3 license to this software,
 * notwithstanding of any reference thereto in the software or
 * associated repository.
 */

#include <shared/km/shared.h>

#if DBG
ULONG DebugRandom(VOID)
{
    static KSPIN_LOCK SpinLock = 0;
    static ULONG Seed = 1;
    KIRQL Irql;
    ULONG Result;

    KeAcquireSpinLock(&SpinLock, &Irql);

    /* see ucrt sources */
    Seed = Seed * 214013 + 2531011;
    Result = (Seed >> 16) & 0x7fff;

    KeReleaseSpinLock(&SpinLock, Irql);

    return Result;
}

BOOLEAN DebugMemory(PVOID Memory, SIZE_T Size, BOOLEAN Test)
{
    BOOLEAN Result = TRUE;
    if (!Test)
    {
        for (SIZE_T I = 0, N = Size / sizeof(UINT32); N > I; I++)
        {
            ((PUINT8)Memory)[0] = 0x0B;
            ((PUINT8)Memory)[1] = 0xAD;
            ((PUINT8)Memory)[2] = 0xF0;
            ((PUINT8)Memory)[3] = 0x0D;
            Memory = (PUINT8)Memory + sizeof(UINT32);
        }
    }
    else
    {
        for (SIZE_T I = 0, N = Size / sizeof(UINT32); N > I; I++)
        {
            if (
                ((PUINT8)Memory)[0] == 0x0B &&
                ((PUINT8)Memory)[1] == 0xAD &&
                ((PUINT8)Memory)[2] == 0xF0 &&
                ((PUINT8)Memory)[3] == 0x0D
                )
            {
                Result = FALSE;
                break;
            }
            Memory = (PUINT8)Memory + sizeof(UINT32);
        }
    }
    return Result;
}

int _snprintf(char *buf, size_t siz, const char *fmt, ...);

static const char *FuseErrnoSignSym(INT32 Errno)
{
    if (0 < Errno)
        return "+";
    else if (0 > Errno)
        return "-";
    else
        return "";
}

static const char *FuseErrnoSym(FUSE_INSTANCE_TYPE InstanceType, INT32 Errno)
{
    if (0 > Errno)
        Errno = -Errno;

    switch (InstanceType)
    {
    default:
    case FuseInstanceWindows:
        switch (Errno)
        {
        #undef FUSE_ERRNO
        #define FUSE_ERRNO 87
        #include "errnosym.i"
        default:
            return "errno:UNKNOWN";
        }
    case FuseInstanceCygwin:
        switch (Errno)
        {
        #undef FUSE_ERRNO
        #define FUSE_ERRNO 67
        #include "errnosym.i"
        default:
            return "errno:UNKNOWN";
        }
    case FuseInstanceLinux:
        switch (Errno)
        {
        #undef FUSE_ERRNO
        #define FUSE_ERRNO 76
        #include "errnosym.i"
        default:
            return "errno:UNKNOWN";
        }
    }
}

static const char *FuseOpcodeSym(UINT32 Opcode)
{
#define SYM(x)                          case FUSE_PROTO_OPCODE_ ## x: return #x;

    switch (Opcode)
    {
    case 0:
        return "EMPTY";
    SYM(LOOKUP)
    SYM(FORGET)
    SYM(GETATTR)
    SYM(SETATTR)
    SYM(READLINK)
    SYM(SYMLINK)
    SYM(MKNOD)
    SYM(MKDIR)
    SYM(UNLINK)
    SYM(RMDIR)
    SYM(RENAME)
    SYM(LINK)
    SYM(OPEN)
    SYM(READ)
    SYM(WRITE)
    SYM(STATFS)
    SYM(RELEASE)
    SYM(FSYNC)
    SYM(SETXATTR)
    SYM(GETXATTR)
    SYM(LISTXATTR)
    SYM(REMOVEXATTR)
    SYM(FLUSH)
    SYM(INIT)
    SYM(OPENDIR)
    SYM(READDIR)
    SYM(RELEASEDIR)
    SYM(FSYNCDIR)
    SYM(GETLK)
    SYM(SETLK)
    SYM(SETLKW)
    SYM(ACCESS)
    SYM(CREATE)
    SYM(INTERRUPT)
    SYM(BMAP)
    SYM(DESTROY)
    SYM(IOCTL)
    SYM(POLL)
    SYM(NOTIFY_REPLY)
    SYM(BATCH_FORGET)
    SYM(FALLOCATE)
    SYM(READDIRPLUS)
    SYM(RENAME2)
    SYM(LSEEK)
    SYM(COPY_FILE_RANGE)
    default:
        return "INVALID";
    }

#undef SYM
}

static const char *FuseDebugLogTimeString(UINT64 time, UINT32 timensec, char *Buf)
{
    UINT64 FileTime;
    TIME_FIELDS TimeFields;

    if (0 == time && 0 == timensec)
        Buf[0] = '0', Buf[1] = '\0';
    else
    {
        FuseUnixTimeToFileTime(time, timensec, &FileTime);
        RtlTimeToTimeFields((PLARGE_INTEGER)&FileTime, &TimeFields);
        _snprintf(Buf, 32, "%04hu-%02hu-%02huT%02hu:%02hu:%02hu.%03huZ",
            TimeFields.Year, TimeFields.Month, TimeFields.Day,
            TimeFields.Hour, TimeFields.Minute, TimeFields.Second,
            TimeFields.Milliseconds);
    }

    return Buf;
}

static const char *FuseDebugLogAttrString(FUSE_PROTO_ATTR *Attr, char *Buf)
{
    char atimebuf[32], mtimebuf[32], ctimebuf[32];
    _snprintf(Buf, 512,
        "{ino=%llu, size=%llu, blocks=%llu, atime=%s, mtime=%s, ctime=%s, "
            "mode=0%06o, nlink=%u, uid=%u, gid=%u, rdev=0x%x, blksize=%u}",
        Attr->ino,
        Attr->size,
        Attr->blocks,
        FuseDebugLogTimeString(Attr->atime, Attr->atimensec, atimebuf),
        FuseDebugLogTimeString(Attr->mtime, Attr->mtimensec, mtimebuf),
        FuseDebugLogTimeString(Attr->ctime, Attr->ctimensec, ctimebuf),
        Attr->mode,
        Attr->nlink,
        Attr->uid,
        Attr->gid,
        Attr->rdev,
        Attr->blksize);
    return Buf;
}

static const char *FuseDebugLogEntryString(FUSE_PROTO_ENTRY *Entry, char *Buf)
{
    int Len0, Len1;
    Len0 = _snprintf(Buf, 256,
        "{nodeid=%llu, generation=%llu, entry_valid=%llu, entry_valid_nsec=%u, "
            "attr_valid=%llu, attr_valid_nsec=%u, attr=",
        Entry->nodeid,
        Entry->generation,
        Entry->entry_valid,
        Entry->entry_valid_nsec,
        Entry->attr_valid,
        Entry->attr_valid_nsec);
    FuseDebugLogAttrString(&Entry->attr, Buf + Len0);
    Len1 = Len0 + (int)strlen(Buf + Len0);
    Buf[Len1] = '}';
    Buf[Len1 + 1] = '\0';
    return Buf;
}

VOID FuseDebugLogRequest(FUSE_PROTO_REQ *Request)
{
#define LOG(fmt, ...)                   \
    DbgPrint("[%d] FUSE: %p[%06x]: <<%s[ino=%llu,uid=%u:%u,pid=%u] " fmt "\n",\
        KeGetCurrentIrql(),             \
        (PVOID)(UINT_PTR)Request->unique,\
        Request->len,                   \
        FuseOpcodeSym(Request->opcode), \
        Request->nodeid,                \
        Request->uid,                   \
        Request->gid,                   \
        Request->pid,                   \
        __VA_ARGS__)

    if (0 == Request->len)
    {
        LOG("", 0);
        return;
    }

    FUSE_CONTEXT *Context = (PVOID)(UINT_PTR)Request->unique;
    0 != Context ? Context->DebugLogOpcode = Request->opcode : 0;

    char atimebuf[32], mtimebuf[32], ctimebuf[32];
    switch (Request->opcode)
    {
    case FUSE_PROTO_OPCODE_LOOKUP:
        LOG("name=\"%s\"",
            Request->req.lookup.name);
        break;
    case FUSE_PROTO_OPCODE_FORGET:
        LOG("nlookup=%llu",
            Request->req.forget.nlookup);
        break;
    case FUSE_PROTO_OPCODE_GETATTR:
        LOG("fh=%llu, flags=%u",
            Request->req.getattr.fh,
            Request->req.getattr.getattr_flags);
        break;
    case FUSE_PROTO_OPCODE_SETATTR:
        LOG("fh=%llu, valid=%x, size=%llu, atime=%s, mtime=%s, ctime=%s, mode=0%03o, uid=%u, gid=%u",
            Request->req.setattr.fh,
            Request->req.setattr.valid,
            Request->req.setattr.size,
            FuseDebugLogTimeString(Request->req.setattr.atime, Request->req.setattr.atimensec, atimebuf),
            FuseDebugLogTimeString(Request->req.setattr.mtime, Request->req.setattr.mtimensec, mtimebuf),
            FuseDebugLogTimeString(Request->req.setattr.ctime, Request->req.setattr.ctimensec, ctimebuf),
            Request->req.setattr.mode,
            Request->req.setattr.uid,
            Request->req.setattr.gid);
        break;
    case FUSE_PROTO_OPCODE_SYMLINK:
        LOG("name=\"%s\", target=\"%s\"",
            Request->req.symlink.name,
            Request->req.symlink.name + strlen(Request->req.symlink.name) + 1);
        break;
    case FUSE_PROTO_OPCODE_MKNOD:
        LOG("name=\"%s\", mode=0%06o, rdev=0x%x, umask=0%03o",
            Request->req.mknod.name,
            Request->req.mknod.mode,
            Request->req.mknod.rdev,
            Request->req.mknod.umask);
        break;
    case FUSE_PROTO_OPCODE_MKDIR:
        LOG("name=\"%s\", mode=0%06o, umask=0%03o",
            Request->req.mkdir.name,
            Request->req.mkdir.mode,
            Request->req.mkdir.umask);
        break;
    case FUSE_PROTO_OPCODE_UNLINK:
        LOG("name=\"%s\"",
            Request->req.unlink.name);
        break;
    case FUSE_PROTO_OPCODE_RMDIR:
        LOG("name=\"%s\"",
            Request->req.rmdir.name);
        break;
    case FUSE_PROTO_OPCODE_RENAME:
        LOG("oldname=\"%s\", newdir=%llu, newname=\"%s\"",
            Request->req.rename.name,
            Request->req.rename.newdir,
            Request->req.rename.name + strlen(Request->req.rename.name) + 1);
        break;
    case FUSE_PROTO_OPCODE_LINK:
        LOG("oldino=%llu, name=\"%s\"",
            Request->req.link.oldnodeid,
            Request->req.link.name);
        break;
    case FUSE_PROTO_OPCODE_OPEN:
    case FUSE_PROTO_OPCODE_OPENDIR:
        LOG("open_flags=0x%x",
            Request->req.open.flags);
        break;
    case FUSE_PROTO_OPCODE_READ:
    case FUSE_PROTO_OPCODE_READDIR:
    case FUSE_PROTO_OPCODE_READDIRPLUS:
        LOG("fh=%llu, offset=%llu, size=%u, open_flags=0x%x",
            Request->req.read.fh,
            Request->req.read.offset,
            Request->req.read.size,
            Request->req.read.flags);
        break;
    case FUSE_PROTO_OPCODE_WRITE:
        LOG("fh=%llu, offset=%llu, size=%u, open_flags=0x%x",
            Request->req.write.fh,
            Request->req.write.offset,
            Request->req.write.size,
            Request->req.write.flags);
        break;
    case FUSE_PROTO_OPCODE_RELEASE:
    case FUSE_PROTO_OPCODE_RELEASEDIR:
        LOG("fh=%llu, flags=0x%x, open_flags=0x%x",
            Request->req.release.fh,
            Request->req.release.release_flags,
            Request->req.release.flags);
        break;
    case FUSE_PROTO_OPCODE_FSYNC:
    case FUSE_PROTO_OPCODE_FSYNCDIR:
        LOG("fh=%llu, flags=0x%x",
            Request->req.fsync.fh,
            Request->req.fsync.fsync_flags);
        break;
    case FUSE_PROTO_OPCODE_SETXATTR:
        LOG("name=\"%s\", size=%u, flags=0x%x",
            Request->req.setxattr.name,
            Request->req.setxattr.size,
            Request->req.setxattr.flags);
        break;
    case FUSE_PROTO_OPCODE_GETXATTR:
        LOG("name=\"%s\", size=%u",
            Request->req.getxattr.name,
            Request->req.getxattr.size);
        break;
    case FUSE_PROTO_OPCODE_LISTXATTR:
        LOG("size=%u",
            Request->req.listxattr.size);
        break;
    case FUSE_PROTO_OPCODE_REMOVEXATTR:
        LOG("name=\"%s\"",
            Request->req.removexattr.name);
        break;
    case FUSE_PROTO_OPCODE_FLUSH:
        LOG("fh=%llu",
            Request->req.flush.fh);
        break;
    case FUSE_PROTO_OPCODE_INIT:
        LOG("major=%u, minor=%u, flags=0x%x, max_readahead=%u",
            Request->req.init.major,
            Request->req.init.minor,
            Request->req.init.flags,
            Request->req.init.max_readahead);
        break;
    case FUSE_PROTO_OPCODE_ACCESS:
        LOG("mask=0%o",
            Request->req.access.mask);
        break;
    case FUSE_PROTO_OPCODE_CREATE:
        LOG("name=\"%s\", mode=0%06o, umask=0%03o, open_flags=0x%x",
            Request->req.create.name,
            Request->req.create.mode,
            Request->req.create.umask,
            Request->req.create.flags);
        break;
    case FUSE_PROTO_OPCODE_BATCH_FORGET:
        LOG("count=%u",
            Request->req.batch_forget.count);
        break;
    default:
        LOG("", 0);
        break;
    }

#undef LOG
}

VOID FuseDebugLogResponse(FUSE_PROTO_RSP *Response)
{
#define LOG(fmt, ...)                   \
    DbgPrint("[%d] FUSE: %p[%06x]: >>%s[err=%s%s] " fmt "\n",\
        KeGetCurrentIrql(),             \
        (PVOID)(UINT_PTR)Response->unique,\
        Response->len,                  \
        FuseOpcodeSym(Opcode),          \
        FuseErrnoSignSym(Response->error),\
        FuseErrnoSym(InstanceType, Response->error),\
        __VA_ARGS__)

    FUSE_CONTEXT *Context = (PVOID)(UINT_PTR)Response->unique;
    FUSE_INSTANCE_TYPE InstanceType = 0 != Context ? Context->Instance->InstanceType : FuseInstanceWindows;
    UINT32 Opcode = 0 != Context ? Context->DebugLogOpcode : 0;

    if (0 != Response->error)
    {
        LOG("", 0);
        return;
    }

    char entrybuf[256 + 512];
    switch (Opcode)
    {
    case FUSE_PROTO_OPCODE_LOOKUP:
        LOG("entry=%s",
            FuseDebugLogEntryString(&Response->rsp.lookup.entry, entrybuf));
        break;
    case FUSE_PROTO_OPCODE_GETATTR:
        LOG("attr_valid=%llu, attr_valid_nsec=%u, attr=%s",
            Response->rsp.getattr.attr_valid,
            Response->rsp.getattr.attr_valid_nsec,
            FuseDebugLogAttrString(&Response->rsp.getattr.attr, entrybuf));
        break;
    case FUSE_PROTO_OPCODE_SETATTR:
        LOG("attr_valid=%llu, attr_valid_nsec=%u, attr=%s",
            Response->rsp.setattr.attr_valid,
            Response->rsp.setattr.attr_valid_nsec,
            FuseDebugLogAttrString(&Response->rsp.setattr.attr, entrybuf));
        break;
    case FUSE_PROTO_OPCODE_SYMLINK:
        LOG("entry=%s",
            FuseDebugLogEntryString(&Response->rsp.symlink.entry, entrybuf));
        break;
    case FUSE_PROTO_OPCODE_MKNOD:
        LOG("entry=%s",
            FuseDebugLogEntryString(&Response->rsp.mknod.entry, entrybuf));
        break;
    case FUSE_PROTO_OPCODE_MKDIR:
        LOG("entry=%s",
            FuseDebugLogEntryString(&Response->rsp.mkdir.entry, entrybuf));
        break;
    case FUSE_PROTO_OPCODE_LINK:
        LOG("entry=%s",
            FuseDebugLogEntryString(&Response->rsp.link.entry, entrybuf));
        break;
    case FUSE_PROTO_OPCODE_OPEN:
    case FUSE_PROTO_OPCODE_OPENDIR:
        LOG("fh=%llu, open_flags=0x%x",
            Response->rsp.open.fh,
            Response->rsp.open.open_flags);
        break;
    case FUSE_PROTO_OPCODE_WRITE:
        LOG("size=%u",
            Response->rsp.write.size);
        break;
    case FUSE_PROTO_OPCODE_STATFS:
        LOG("st={blocks=%llu, bfree=%llu, bavail=%llu, files=%llu, ffree=%llu, bsize=%u, frsize=%u, namelen=%u}",
            Response->rsp.statfs.st.blocks,
            Response->rsp.statfs.st.bfree,
            Response->rsp.statfs.st.bavail,
            Response->rsp.statfs.st.files,
            Response->rsp.statfs.st.ffree,
            Response->rsp.statfs.st.bsize,
            Response->rsp.statfs.st.frsize,
            Response->rsp.statfs.st.namelen);
        break;
    case FUSE_PROTO_OPCODE_GETXATTR:
        LOG("size=%u",
            Response->rsp.getxattr.size);
        break;
    case FUSE_PROTO_OPCODE_LISTXATTR:
        LOG("size=%u",
            Response->rsp.listxattr.size);
        break;
    case FUSE_PROTO_OPCODE_INIT:
        LOG("major=%u, minor=%u, flags=0x%x, max_readahead=%u, max_write=%u",
            Response->rsp.init.major,
            Response->rsp.init.minor,
            Response->rsp.init.flags,
            Response->rsp.init.max_readahead,
            Response->rsp.init.max_write);
        break;
    case FUSE_PROTO_OPCODE_CREATE:
        LOG("entry=%s, fh=%llu, open_flags=0x%x",
            FuseDebugLogEntryString(&Response->rsp.create.entry, entrybuf),
            Response->rsp.create.fh,
            Response->rsp.create.open_flags);
        break;
    default:
        LOG("", 0);
        break;
    }

#undef LOG
}
#endif


================================================
FILE: src/shared/km/errno.i
================================================
#if FUSE_ERRNO == 87 /* Windows */

case 0: return STATUS_SUCCESS;
case 1: return STATUS_ACCESS_DENIED;
case 2: return STATUS_OBJECT_NAME_NOT_FOUND;
case 3: return STATUS_PROCEDURE_NOT_FOUND;
case 4: return STATUS_CANCELLED;
case 5: return STATUS_IO_DEVICE_ERROR;
case 6: return STATUS_FILE_INVALID;
case 7: return STATUS_INSUFFICIENT_RESOURCES;
case 8: return STATUS_INVALID_IMAGE_FORMAT;
case 9: return STATUS_INVALID_HANDLE;
case 12: return STATUS_INSUFFICIENT_RESOURCES;
case 13: return STATUS_ACCESS_DENIED;
case 14: return STATUS_ACCESS_VIOLATION;
case 16: return STATUS_DEVICE_BUSY;
case 17: return STATUS_OBJECT_NAME_COLLISION;
case 18: return STATUS_NOT_SAME_DEVICE;
case 19: return STATUS_NO_SUCH_DEVICE;
case 20: return STATUS_NOT_A_DIRECTORY;
case 21: return STATUS_FILE_IS_A_DIRECTORY;
case 22: return STATUS_INVALID_PARAMETER;
case 23: return STATUS_TOO_MANY_OPENED_FILES;
case 24: return STATUS_TOO_MANY_OPENED_FILES;
case 27: return STATUS_DISK_FULL;
case 28: return STATUS_DISK_FULL;
case 29: return STATUS_INVALID_PARAMETER;
case 30: return STATUS_MEDIA_WRITE_PROTECTED;
case 31: return STATUS_TOO_MANY_LINKS;
case 32: return STATUS_PIPE_BROKEN;
case 33: return STATUS_INVALID_PARAMETER;
case 34: return STATUS_INVALID_PARAMETER;
case 36: return STATUS_POSSIBLE_DEADLOCK;
case 38: return STATUS_NAME_TOO_LONG;
case 39: return STATUS_LOCK_NOT_GRANTED;
case 40: return STATUS_INVALID_DEVICE_REQUEST;
case 41: return STATUS_DIRECTORY_NOT_EMPTY;
case 42: return STATUS_INVALID_PARAMETER;
case 100: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
case 103: return STATUS_CONNECTION_ACTIVE;
case 105: return STATUS_CANCELLED;
case 106: return STATUS_CONNECTION_ABORTED;
case 107: return STATUS_CONNECTION_REFUSED;
case 108: return STATUS_CONNECTION_RESET;
case 110: return STATUS_HOST_UNREACHABLE;
case 113: return STATUS_CONNECTION_ACTIVE;
case 114: return STATUS_REPARSE_POINT_NOT_RESOLVED;
case 116: return STATUS_HOST_DOWN;
case 117: return STATUS_CONNECTION_RESET;
case 118: return STATUS_NETWORK_UNREACHABLE;
case 119: return STATUS_INSUFFICIENT_RESOURCES;
case 120: return STATUS_END_OF_FILE;
case 121: return STATUS_CONNECTION_INVALID;
case 126: return STATUS_CONNECTION_INVALID;
case 128: return STATUS_INVALID_HANDLE;
case 138: return STATUS_TRANSACTION_TIMED_OUT;

#elif FUSE_ERRNO == 67 /* Cygwin */

case 0: return STATUS_SUCCESS;
case 1: return STATUS_ACCESS_DENIED;
case 2: return STATUS_OBJECT_NAME_NOT_FOUND;
case 3: return STATUS_PROCEDURE_NOT_FOUND;
case 4: return STATUS_CANCELLED;
case 5: return STATUS_IO_DEVICE_ERROR;
case 6: return STATUS_FILE_INVALID;
case 7: return STATUS_INSUFFICIENT_RESOURCES;
case 8: return STATUS_INVALID_IMAGE_FORMAT;
case 9: return STATUS_INVALID_HANDLE;
case 12: return STATUS_INSUFFICIENT_RESOURCES;
case 13: return STATUS_ACCESS_DENIED;
case 14: return STATUS_ACCESS_VIOLATION;
case 16: return STATUS_DEVICE_BUSY;
case 17: return STATUS_OBJECT_NAME_COLLISION;
case 18: return STATUS_NOT_SAME_DEVICE;
case 19: return STATUS_NO_SUCH_DEVICE;
case 20: return STATUS_NOT_A_DIRECTORY;
case 21: return STATUS_FILE_IS_A_DIRECTORY;
case 22: return STATUS_INVALID_PARAMETER;
case 23: return STATUS_TOO_MANY_OPENED_FILES;
case 24: return STATUS_TOO_MANY_OPENED_FILES;
case 27: return STATUS_DISK_FULL;
case 28: return STATUS_DISK_FULL;
case 29: return STATUS_INVALID_PARAMETER;
case 30: return STATUS_MEDIA_WRITE_PROTECTED;
case 31: return STATUS_TOO_MANY_LINKS;
case 32: return STATUS_PIPE_BROKEN;
case 33: return STATUS_INVALID_PARAMETER;
case 34: return STATUS_INVALID_PARAMETER;
case 45: return STATUS_POSSIBLE_DEADLOCK;
case 91: return STATUS_NAME_TOO_LONG;
case 46: return STATUS_LOCK_NOT_GRANTED;
case 88: return STATUS_INVALID_DEVICE_REQUEST;
case 90: return STATUS_DIRECTORY_NOT_EMPTY;
case 138: return STATUS_INVALID_PARAMETER;
case 112: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
case 120: return STATUS_CONNECTION_ACTIVE;
case 140: return STATUS_CANCELLED;
case 113: return STATUS_CONNECTION_ABORTED;
case 111: return STATUS_CONNECTION_REFUSED;
case 104: return STATUS_CONNECTION_RESET;
case 118: return STATUS_HOST_UNREACHABLE;
case 127: return STATUS_CONNECTION_ACTIVE;
case 92: return STATUS_REPARSE_POINT_NOT_RESOLVED;
case 115: return STATUS_HOST_DOWN;
case 126: return STATUS_CONNECTION_RESET;
case 114: return STATUS_NETWORK_UNREACHABLE;
case 105: return STATUS_INSUFFICIENT_RESOURCES;
case 61: return STATUS_END_OF_FILE;
case 67: return STATUS_CONNECTION_INVALID;
case 128: return STATUS_CONNECTION_INVALID;
case 108: return STATUS_INVALID_HANDLE;
case 116: return STATUS_TRANSACTION_TIMED_OUT;

#elif FUSE_ERRNO == 76 /* Linux */

case 0: return STATUS_SUCCESS;
case 1: return STATUS_ACCESS_DENIED;
case 2: return STATUS_OBJECT_NAME_NOT_FOUND;
case 3: return STATUS_PROCEDURE_NOT_FOUND;
case 4: return STATUS_CANCELLED;
case 5: return STATUS_IO_DEVICE_ERROR;
case 6: return STATUS_FILE_INVALID;
case 7: return STATUS_INSUFFICIENT_RESOURCES;
case 8: return STATUS_INVALID_IMAGE_FORMAT;
case 9: return STATUS_INVALID_HANDLE;
case 12: return STATUS_INSUFFICIENT_RESOURCES;
case 13: return STATUS_ACCESS_DENIED;
case 14: return STATUS_ACCESS_VIOLATION;
case 16: return STATUS_DEVICE_BUSY;
case 17: return STATUS_OBJECT_NAME_COLLISION;
case 18: return STATUS_NOT_SAME_DEVICE;
case 19: return STATUS_NO_SUCH_DEVICE;
case 20: return STATUS_NOT_A_DIRECTORY;
case 21: return STATUS_FILE_IS_A_DIRECTORY;
case 22: return STATUS_INVALID_PARAMETER;
case 23: return STATUS_TOO_MANY_OPENED_FILES;
case 24: return STATUS_TOO_MANY_OPENED_FILES;
case 27: return STATUS_DISK_FULL;
case 28: return STATUS_DISK_FULL;
case 29: return STATUS_INVALID_PARAMETER;
case 30: return STATUS_MEDIA_WRITE_PROTECTED;
case 31: return STATUS_TOO_MANY_LINKS;
case 32: return STATUS_PIPE_BROKEN;
case 33: return STATUS_INVALID_PARAMETER;
case 34: return STATUS_INVALID_PARAMETER;
case 35: return STATUS_POSSIBLE_DEADLOCK;
case 36: return STATUS_NAME_TOO_LONG;
case 37: return STATUS_LOCK_NOT_GRANTED;
case 38: return STATUS_INVALID_DEVICE_REQUEST;
case 39: return STATUS_DIRECTORY_NOT_EMPTY;
case 84: return STATUS_INVALID_PARAMETER;
case 98: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
case 114: return STATUS_CONNECTION_ACTIVE;
case 125: return STATUS_CANCELLED;
case 103: return STATUS_CONNECTION_ABORTED;
case 111: return STATUS_CONNECTION_REFUSED;
case 104: return STATUS_CONNECTION_RESET;
case 113: return STATUS_HOST_UNREACHABLE;
case 106: return STATUS_CONNECTION_ACTIVE;
case 40: return STATUS_REPARSE_POINT_NOT_RESOLVED;
case 100: return STATUS_HOST_DOWN;
case 102: return STATUS_CONNECTION_RESET;
case 101: return STATUS_NETWORK_UNREACHABLE;
case 105: return STATUS_INSUFFICIENT_RESOURCES;
case 61: return STATUS_END_OF_FILE;
case 67: return STATUS_CONNECTION_INVALID;
case 107: return STATUS_CONNECTION_INVALID;
case 88: return STATUS_INVALID_HANDLE;
case 110: return STATUS_TRANSACTION_TIMED_OUT;

#endif


================================================
FILE: src/shared/km/errnosym.i
================================================
#if FUSE_ERRNO == 87 /* Windows */

case 0: return "0";
case 1: return "EPERM";
case 2: return "ENOENT";
case 3: return "ESRCH";
case 4: return "EINTR";
case 5: return "EIO";
case 6: return "ENXIO";
case 7: return "E2BIG";
case 8: return "ENOEXEC";
case 9: return "EBADF";
case 12: return "ENOMEM";
case 13: return "EACCES";
case 14: return "EFAULT";
case 16: return "EBUSY";
case 17: return "EEXIST";
case 18: return "EXDEV";
case 19: return "ENODEV";
case 20: return "ENOTDIR";
case 21: return "EISDIR";
case 22: return "EINVAL";
case 23: return "ENFILE";
case 24: return "EMFILE";
case 27: return "EFBIG";
case 28: return "ENOSPC";
case 29: return "ESPIPE";
case 30: return "EROFS";
case 31: return "EMLINK";
case 32: return "EPIPE";
case 33: return "EDOM";
case 34: return "ERANGE";
case 36: return "EDEADLK";
case 38: return "ENAMETOOLONG";
case 39: return "ENOLCK";
case 40: return "ENOSYS";
case 41: return "ENOTEMPTY";
case 42: return "EILSEQ";
case 100: return "EADDRINUSE";
case 103: return "EALREADY";
case 105: return "ECANCELED";
case 106: return "ECONNABORTED";
case 107: return "ECONNREFUSED";
case 108: return "ECONNRESET";
case 110: return "EHOSTUNREACH";
case 113: return "EISCONN";
case 114: return "ELOOP";
case 116: return "ENETDOWN";
case 117: return "ENETRESET";
case 118: return "ENETUNREACH";
case 119: return "ENOBUFS";
case 120: return "ENODATA";
case 121: return "ENOLINK";
case 126: return "ENOTCONN";
case 128: return "ENOTSOCK";
case 138: return "ETIMEDOUT";

#elif FUSE_ERRNO == 67 /* Cygwin */

case 0: return "0";
case 1: return "EPERM";
case 2: return "ENOENT";
case 3: return "ESRCH";
case 4: return "EINTR";
case 5: return "EIO";
case 6: return "ENXIO";
case 7: return "E2BIG";
case 8: return "ENOEXEC";
case 9: return "EBADF";
case 12: return "ENOMEM";
case 13: return "EACCES";
case 14: return "EFAULT";
case 16: return "EBUSY";
case 17: return "EEXIST";
case 18: return "EXDEV";
case 19: return "ENODEV";
case 20: return "ENOTDIR";
case 21: return "EISDIR";
case 22: return "EINVAL";
case 23: return "ENFILE";
case 24: return "EMFILE";
case 27: return "EFBIG";
case 28: return "ENOSPC";
case 29: return "ESPIPE";
case 30: return "EROFS";
case 31: return "EMLINK";
case 32: return "EPIPE";
case 33: return "EDOM";
case 34: return "ERANGE";
case 45: return "EDEADLK";
case 91: return "ENAMETOOLONG";
case 46: return "ENOLCK";
case 88: return "ENOSYS";
case 90: return "ENOTEMPTY";
case 138: return "EILSEQ";
case 112: return "EADDRINUSE";
case 120: return "EALREADY";
case 140: return "ECANCELED";
case 113: return "ECONNABORTED";
case 111: return "ECONNREFUSED";
case 104: return "ECONNRESET";
case 118: return "EHOSTUNREACH";
case 127: return "EISCONN";
case 92: return "ELOOP";
case 115: return "ENETDOWN";
case 126: return "ENETRESET";
case 114: return "ENETUNREACH";
case 105: return "ENOBUFS";
case 61: return "ENODATA";
case 67: return "ENOLINK";
case 128: return "ENOTCONN";
case 108: return "ENOTSOCK";
case 116: return "ETIMEDOUT";

#elif FUSE_ERRNO == 76 /* Linux */

case 0: return "0";
case 1: return "EPERM";
case 2: return "ENOENT";
case 3: return "ESRCH";
case 4: return "EINTR";
case 5: return "EIO";
case 6: return "ENXIO";
case 7: return "E2BIG";
case 8: return "ENOEXEC";
case 9: return "EBADF";
case 12: return "ENOMEM";
case 13: return "EACCES";
case 14: return "EFAULT";
case 16: return "EBUSY";
case 17: return "EEXIST";
case 18: return "EXDEV";
case 19: return "ENODEV";
case 20: return "ENOTDIR";
case 21: return "EISDIR";
case 22: return "EINVAL";
case 23: return "ENFILE";
case 24: return "EMFILE";
case 27: return "EFBIG";
case 28: return "ENOSPC";
case 29: return "ESPIPE";
case 30: return "EROFS";
case 31: return "EMLINK";
case 32: return "EPIPE";
case 33: return "EDOM";
case 34: return "ERANGE";
case 35: return "EDEADLK";
case 36: return "ENAMETOOLONG";
case 37: return "ENOLCK";
case 38: return "ENOSYS";
case 39: return "ENOTEMPTY";
case 84: return "EILSEQ";
case 98: return "EADDRINUSE";
case 114: return "EALREADY";
case 125: return "ECANCELED";
case 103: return "ECONNABORTED";
case 111: return "ECONNREFUSED";
case 104: return "ECONNRESET";
case 113: return "EHOSTUNREACH";
case 106: return "EISCONN";
case 40: return "ELOOP";
case 100: return "ENETDOWN";
case 102: return "ENETRESET";
case 101: return "ENETUNREACH";
case 105: return "ENOBUFS";
case 61: return "ENODATA";
case 67: return "ENOLINK";
case 107: return "ENOTCONN";
case 88: return "ENOTSOCK";
case 110: return "ETIMEDOUT";

#endif


================================================
FILE: src/shared/km/file.c
================================================
/**
 * @file shared/km/file.c
 *
 * @copyright 2019-2020 Bill Zissimopoulos
 */
/*
 * This file is part of WinFuse.
 *
 * You can redistribute it and/or modify it under the terms of the GNU
 * Affero General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * Licensees holding a valid commercial license may use this software
 * in accordance with the commercial license agreement provided in
 * conjunction with the software.  The terms and conditions of any such
 * commercial license agreement shall govern, supersede, and render
 * ineffective any application of the AGPLv3 license to this software,
 * notwithstanding of any reference thereto in the software or
 * associated repository.
 */

#include <shared/km/shared.h>

VOID FuseFileInstanceInit(FUSE_INSTANCE *Instance)
{
    KeInitializeSpinLock(&Instance->FileListLock);
    InitializeListHead(&Instance->FileList);
}

VOID FuseFileInstanceFini(FUSE_INSTANCE *Instance)
{
    FUSE_FILE *File;

    for (PLIST_ENTRY Entry = Instance->FileList.Flink; &Instance->FileList != Entry;)
    {
        File = CONTAINING_RECORD(Entry, FUSE_FILE, ListEntry);
        Entry = Entry->Flink;
        FuseCacheDereferenceItem(Instance->Cache, File->CacheItem);
        FuseFree(File);
    }
}

NTSTATUS FuseFileCreate(FUSE_INSTANCE *Instance, FUSE_FILE **PFile)
{
    KIRQL Irql;
    FUSE_FILE *File;

    *PFile = 0;

    File = FuseAllocNonPaged(sizeof *File);
        /* spinlocks must operate on non-paged memory */
    if (0 == File)
        return STATUS_INSUFFICIENT_RESOURCES;

    RtlZeroMemory(File, sizeof *File);

    KeAcquireSpinLock(&Instance->FileListLock, &Irql);
    InsertTailList(&Instance->FileList, &File->ListEntry);
    KeReleaseSpinLock(&Instance->FileListLock, Irql);

    *PFile = File;

    return STATUS_SUCCESS;
}

VOID FuseFileDelete(FUSE_INSTANCE *Instance, FUSE_FILE *File)
{
    KIRQL Irql;

    KeAcquireSpinLock(&Instance->FileListLock, &Irql);
    RemoveEntryList(&File->ListEntry);
    KeReleaseSpinLock(&Instance->FileListLock, Irql);

    FuseCacheDereferenceItem(Instance->Cache, File->CacheItem);

    DEBUGFILL(File, sizeof *File);
    FuseFree(File);
}


================================================
FILE: src/shared/km/fuseop.c
================================================
/**
 * @file shared/km/fuseop.c
 *
 * @copyright 2019-2020 Bill Zissimopoulos
 */
/*
 * This file is part of WinFuse.
 *
 * You can redistribute it and/or modify it under the terms of the GNU
 * Affero General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * Licensees holding a valid commercial license may use this software
 * in accordance with the commercial license agreement provided in
 * conjunction with the software.  The terms and conditions of any such
 * commercial license agreement shall govern, supersede, and render
 * ineffective any application of the AGPLv3 license to this software,
 * notwithstanding of any reference thereto in the software or
 * associated repository.
 */

#include <shared/km/shared.h>

static BOOLEAN FuseOpReserved_Init(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpReserved_Destroy(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpReserved_Forget(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpReserved(FUSE_CONTEXT *Context);
static VOID FuseLookup(FUSE_CONTEXT *Context);
static NTSTATUS FuseAccessCheck(
    UINT32 FileUid, UINT32 FileGid, UINT32 FileMode,
    UINT32 OrigUid, UINT32 OrigGid, UINT32 DesiredAccess,
    PUINT32 PGrantedAccess);
static VOID FusePrepareLookupPath(FUSE_CONTEXT *Context);
static VOID FusePrepareLookupPath2(FUSE_CONTEXT *Context);
static VOID FusePrepareLookupPath_ContextFini(FUSE_CONTEXT *Context);
static VOID FuseLookupPath(FUSE_CONTEXT *Context);
static VOID FuseCreateCheck(FUSE_CONTEXT *Context);
static VOID FuseOpenCheck(FUSE_CONTEXT *Context);
static VOID FuseOverwriteCheck(FUSE_CONTEXT *Context);
static VOID FuseOpenTargetDirectoryCheck(FUSE_CONTEXT *Context);
static VOID FuseRenameCheck(FUSE_CONTEXT *Context);
static VOID FuseCreate(FUSE_CONTEXT *Context);
static VOID FuseOpen(FUSE_CONTEXT *Context);
static VOID FuseOpCreate_FileCreate(FUSE_CONTEXT *Context);
static VOID FuseOpCreate_FileOpen(FUSE_CONTEXT *Context);
static VOID FuseOpCreate_FileOpenIf(FUSE_CONTEXT *Context);
static VOID FuseOpCreate_FileOverwrite(FUSE_CONTEXT *Context);
static VOID FuseOpCreate_FileOverwriteIf(FUSE_CONTEXT *Context);
static VOID FuseOpCreate_FileOpenTargetDirectory(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpCreate(FUSE_CONTEXT *Context);
static INT FuseOgCreate(FUSE_CONTEXT *Context, BOOLEAN Acquire);
static BOOLEAN FuseOpOverwrite(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpCleanup(FUSE_CONTEXT *Context);
static INT FuseOgCleanup(FUSE_CONTEXT *Context, BOOLEAN Acquire);
static BOOLEAN FuseOpClose(FUSE_CONTEXT *Context);
static VOID FuseOpClose_ContextFini(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpRead(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpWrite(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpQueryInformation(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpSetInformation_SetBasicInfo(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpSetInformation_SetAllocationSize(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpSetInformation_SetFileSize(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpSetInformation_SetDelete(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpSetInformation_Rename(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpSetInformation(FUSE_CONTEXT *Context);
static INT FuseOgSetInformation(FUSE_CONTEXT *Context, BOOLEAN Acquire);
static BOOLEAN FuseOpQueryEa(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpSetEa(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpFlushBuffers(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpQueryVolumeInformation(FUSE_CONTEXT *Context);
static BOOLEAN FuseAddDirInfo(FUSE_CONTEXT *Context,
    PSTRING Name, UINT64 NextOffset, FUSE_PROTO_ATTR *Attr,
    PVOID Buffer, ULONG Length, PULONG PBytesTransferred);
static VOID FuseOpQueryDirectory_GetDirInfoByName(FUSE_CONTEXT *Context);
static VOID FuseOpQueryDirectory_ReadDirectory(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpQueryDirectory(FUSE_CONTEXT *Context);
static VOID FuseOpQueryDirectory_ContextFini(FUSE_CONTEXT *Context);
static INT FuseOgQueryDirectory(FUSE_CONTEXT *Context, BOOLEAN Acquire);
static BOOLEAN FuseOpFileSystemControl(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpDeviceControl(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpQuerySecurity(FUSE_CONTEXT *Context);
static BOOLEAN FuseOpSetSecurity(FUSE_CONTEXT *Context);
static VOID FuseSecurity_ContextFini(FUSE_CONTEXT *Context);

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, FuseOpReserved_Init)
#pragma alloc_text(PAGE, FuseOpReserved_Destroy)
#pragma alloc_text(PAGE, FuseOpReserved_Forget)
#pragma alloc_text(PAGE, FuseOpReserved)
#pragma alloc_text(PAGE, FuseLookup)
#pragma alloc_text(PAGE, FuseAccessCheck)
#pragma alloc_text(PAGE, FusePrepareLookupPath)
#pragma alloc_text(PAGE, FusePrepareLookupPath2)
#pragma alloc_text(PAGE, FusePrepareLookupPath_ContextFini)
#pragma alloc_text(PAGE, FuseLookupPath)
#pragma alloc_text(PAGE, FuseCreateCheck)
#pragma alloc_text(PAGE, FuseOpenCheck)
#pragma alloc_text(PAGE, FuseOverwriteCheck)
#pragma alloc_text(PAGE, FuseOpenTargetDirectoryCheck)
#pragma alloc_text(PAGE, FuseRenameCheck)
#pragma alloc_text(PAGE, FuseCreate)
#pragma alloc_text(PAGE, FuseOpen)
#pragma alloc_text(PAGE, FuseOpCreate_FileCreate)
#pragma alloc_text(PAGE, FuseOpCreate_FileOpen)
#pragma alloc_text(PAGE, FuseOpCreate_FileOpenIf)
#pragma alloc_text(PAGE, FuseOpCreate_FileOverwrite)
#pragma alloc_text(PAGE, FuseOpCreate_FileOverwriteIf)
#pragma alloc_text(PAGE, FuseOpCreate_FileOpenTargetDirectory)
#pragma alloc_text(PAGE, FuseOpCreate)
#pragma alloc_text(PAGE, FuseOgCreate)
#pragma alloc_text(PAGE, FuseOpOverwrite)
#pragma alloc_text(PAGE, FuseOpCleanup)
#pragma alloc_text(PAGE, FuseOgCleanup)
#pragma alloc_text(PAGE, FuseOpClose)
#pragma alloc_text(PAGE, FuseOpClose_ContextFini)
#pragma alloc_text(PAGE, FuseOpRead)
#pragma alloc_text(PAGE, FuseOpWrite)
#pragma alloc_text(PAGE, FuseOpQueryInformation)
#pragma alloc_text(PAGE, FuseOpSetInformation_SetBasicInfo)
#pragma alloc_text(PAGE, FuseOpSetInformation_SetAllocationSize)
#pragma alloc_text(PAGE, FuseOpSetInformation_SetFileSize)
#pragma alloc_text(PAGE, FuseOpSetInformation_SetDelete)
#pragma alloc_text(PAGE, FuseOpSetInformation_Rename)
#pragma alloc_text(PAGE, FuseOpSetInformation)
#pragma alloc_text(PAGE, FuseOgSetInformation)
#pragma alloc_text(PAGE, FuseOpQueryEa)
#pragma alloc_text(PAGE, FuseOpSetEa)
#pragma alloc_text(PAGE, FuseOpFlushBuffers)
#pragma alloc_text(PAGE, FuseOpQueryVolumeInformation)
#pragma alloc_text(PAGE, FuseAddDirInfo)
#pragma alloc_text(PAGE, FuseOpQueryDirectory_GetDirInfoByName)
#pragma alloc_text(PAGE, FuseOpQueryDirectory_ReadDirectory)
#pragma alloc_text(PAGE, FuseOpQueryDirectory)
#pragma alloc_text(PAGE, FuseOpQueryDirectory_ContextFini)
#pragma alloc_text(PAGE, FuseOgQueryDirectory)
#pragma alloc_text(PAGE, FuseOpFileSystemControl)
#pragma alloc_text(PAGE, FuseOpDeviceControl)
#pragma alloc_text(PAGE, FuseOpQuerySecurity)
#pragma alloc_text(PAGE, FuseOpSetSecurity)
#pragma alloc_text(PAGE, FuseSecurity_ContextFini)
#endif

static BOOLEAN FuseOpReserved_Init(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    coro_block (Context->CoroState)
    {
        coro_await (FuseProtoSendInit(Context));
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            coro_break;

        FUSE_INSTANCE *Instance = Context->Instance;
        if (FUSE_PROTO_VERSION != Context->FuseResponse->rsp.init.major)
        {
            Instance->VersionMajor = (UINT32)-1;
            KeSetEvent(&Instance->InitEvent, 1, FALSE);

            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_CONNECTION_REFUSED;
            coro_break;
        }

        Instance->VersionMajor = Context->FuseResponse->rsp.init.major;
        Instance->VersionMinor = Context->FuseResponse->rsp.init.minor;
        // !!!: REVISIT
        KeSetEvent(&Instance->InitEvent, 1, FALSE);

        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
    }

    return coro_active();
}

static BOOLEAN FuseOpReserved_Destroy(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    coro_block (Context->CoroState)
    {
        coro_await (FuseProtoSendDestroy(Context));

        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
    }

    return coro_active();
}

static BOOLEAN FuseOpReserved_Forget(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    FUSE_INSTANCE *Instance = Context->Instance;

    ASSERT(!IsListEmpty(&Context->Forget.ForgetList));
    if (16 > Instance->VersionMinor ||
        &Context->Forget.ForgetList == Context->Forget.ForgetList.Flink->Flink ||
        DEBUGTEST(10))
        FuseProtoFillForget(Context);
    else
        FuseProtoFillBatchForget(Context);

    return FALSE;
}

static BOOLEAN FuseOpReserved(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    switch (Context->InternalResponse->Hint)
    {
    case FUSE_PROTO_OPCODE_INIT:
        return FuseOpReserved_Init(Context);
    case FUSE_PROTO_OPCODE_DESTROY:
        return FuseOpReserved_Destroy(Context);
    case FUSE_PROTO_OPCODE_FORGET:
    case FUSE_PROTO_OPCODE_BATCH_FORGET:
        return FuseOpReserved_Forget(Context);
    default:
        return FALSE;
    }
}

static VOID FuseLookup(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    FUSE_PROTO_ENTRY EntryBuf, *Entry = &EntryBuf;
    PVOID CacheItem;

    coro_block (Context->CoroState)
    {
        if (!FuseCacheGetEntry(Context->Instance->Cache,
            Context->Lookup.Ino, &Context->Lookup.Name, Entry, &CacheItem))
        {
            if (FUSE_PROTO_ROOT_INO == Context->Lookup.Ino &&
                1 == Context->Lookup.Name.Length && '/' == Context->Lookup.Name.Buffer[0])
            {
                coro_await (FuseProtoSendGetattr(Context));
                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
                    coro_break;

                RtlZeroMemory(Entry, sizeof *Entry);
                Entry->nodeid = FUSE_PROTO_ROOT_INO;
                Entry->entry_valid = Entry->attr_valid =
                    Context->FuseResponse->rsp.getattr.attr_valid;
                Entry->entry_valid_nsec = Entry->attr_valid_nsec =
                    Context->FuseResponse->rsp.getattr.attr_valid_nsec;
                Entry->attr = Context->FuseResponse->rsp.getattr.attr;
            }
            else
            {
                coro_await (FuseProtoSendLookup(Context));
                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
                    coro_break;

                Entry = &Context->FuseResponse->rsp.lookup.entry;
            }

            FuseCacheSetEntry(
                Context->Instance->Cache,
                Context->Lookup.Ino, &Context->Lookup.Name, Entry, &CacheItem);
        }

        Context->Lookup.CacheItem = CacheItem;
        Context->Lookup.Ino = Entry->nodeid;
        Context->Lookup.Attr = Entry->attr;

        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
    }
}

/* code borrowed from winfsp/src/ku/posix.c - see there for comments/explanations */
#define FusePosixDefaultPerm            \
    (SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_READ_EA)
#define FusePosixOwnerDefaultPerm       \
    (FusePosixDefaultPerm | DELETE | WRITE_DAC | WRITE_OWNER | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA)
static inline ACCESS_MASK FusePosixMapPermissionToAccessMask(UINT32 Mode, UINT32 Perm)
{
    ACCESS_MASK DeleteChild = 0040000 == (Mode & 0041000) ? FILE_DELETE_CHILD : 0;
    return
        ((Perm & 4) ? FILE_READ_DATA : 0) |
        ((Perm & 2) ? FILE_WRITE_ATTRIBUTES | FILE_WRITE_DATA | FILE_APPEND_DATA | DeleteChild : 0) |
        ((Perm & 1) ? FILE_EXECUTE : 0);
}

static NTSTATUS FuseAccessCheck(
    UINT32 FileUid, UINT32 FileGid, UINT32 FileMode,
    UINT32 OrigUid, UINT32 OrigGid, UINT32 DesiredAccess,
    PUINT32 PGrantedAccess)
{
    PAGED_CODE();

    UINT32 FileAccess, RequiredAccess;

    if (OrigUid == FileUid)
        FileAccess = FusePosixOwnerDefaultPerm |
            FusePosixMapPermissionToAccessMask(FileMode & ~001000, (FileMode & 0700) >> 6);
    else if (OrigGid == FileGid)
        FileAccess = FusePosixDefaultPerm |
            FusePosixMapPermissionToAccessMask(FileMode, (FileMode & 0070) >> 3);
    else
        FileAccess = FusePosixDefaultPerm |
            FusePosixMapPermissionToAccessMask(FileMode, (FileMode & 0007));

    RequiredAccess = DesiredAccess & (STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL);

    if (RequiredAccess == (FileAccess & RequiredAccess))
    {
        if (0 != PGrantedAccess)
            *PGrantedAccess = FlagOn(DesiredAccess, MAXIMUM_ALLOWED) ? FileAccess : RequiredAccess;
        return STATUS_SUCCESS;
    }
    else
    {
        if (0 != PGrantedAccess)
            *PGrantedAccess = 0;
        return STATUS_ACCESS_DENIED;
    }
}

static VOID FusePrepareLookupPath(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    UINT32 Uid = 0, Gid = 0, Pid = 0;
    PVOID CacheGen = 0;
    PSTR PosixPath = 0;
    PWSTR FileName = 0;
    UINT64 AccessToken = 0;
    PACCESS_TOKEN AccessTokenObject = 0;
    UINT32 IsUserMode = 1;
    UINT32 HasTraversePrivilege = 0;

    switch (Context->InternalRequest->Kind)
    {
    case FspFsctlTransactCreateKind:
        FileName = (PWSTR)Context->InternalRequest->Buffer;
        AccessToken = Context->InternalRequest->Req.Create.AccessToken;
        IsUserMode = Context->InternalRequest->Req.Create.UserMode;
        HasTraversePrivilege = Context->InternalRequest->Req.Create.HasTraversePrivilege;
        break;
    case FspFsctlTransactCleanupKind:
        ASSERT(Context->InternalRequest->Req.Cleanup.Delete);
        FileName = (PWSTR)Context->InternalRequest->Buffer;
        IsUserMode = 0;
        HasTraversePrivilege = 1;
        break;
    case FspFsctlTransactSetInformationKind:
        ASSERT(FileRenameInformation ==
            Context->InternalRequest->Req.SetInformation.FileInformationClass);
        FileName = (PWSTR)(Context->InternalRequest->Buffer +
            Context->InternalRequest->Req.SetInformation.Info.Rename.NewFileName.Offset);
        AccessToken = Context->InternalRequest->Req.SetInformation.Info.Rename.AccessToken;
        IsUserMode = 1;
        HasTraversePrivilege = 1;
        break;
    default:
        ASSERT(FALSE);
        Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_PARAMETER;
        goto exit;
    }

    if (0 != FileName)
    {
        Context->InternalResponse->IoStatus.Status = FuseCacheReferenceGen(
            Context->Instance->Cache, &CacheGen);
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            goto exit;

        Context->InternalResponse->IoStatus.Status = FspPosixMapWindowsToPosixPathEx(
            FileName, &PosixPath, TRUE);
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            goto exit;
    }

    if (0 != AccessToken)
    {
        Context->InternalResponse->IoStatus.Status = ObReferenceObjectByHandle(
            FSP_FSCTL_TRANSACT_REQ_TOKEN_HANDLE(AccessToken),
            TOKEN_QUERY,
            *SeTokenObjectType,
            UserMode,
            &AccessTokenObject,
            0/*HandleInformation*/);
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            goto exit;

        Context->InternalResponse->IoStatus.Status = FuseGetTokenUid(
            AccessTokenObject, TokenUser, &Uid);
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            goto exit;

        Context->InternalResponse->IoStatus.Status = FuseGetTokenUid(
            AccessTokenObject, TokenPrimaryGroup, &Gid);
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            goto exit;

        ObDereferenceObject(AccessTokenObject);

        Pid = FSP_FSCTL_TRANSACT_REQ_TOKEN_PID(AccessToken);
    }

    Context->OrigUid = Uid;
    Context->OrigGid = Gid;
    Context->OrigPid = Pid;

    ASSERT(0 == Context->LookupPath.OrigPath.Buffer);
    RtlInitString(&Context->LookupPath.OrigPath, PosixPath);
    Context->LookupPath.CacheGen = CacheGen;
    Context->LookupPath.UserMode = IsUserMode;
    Context->LookupPath.HasTraversePrivilege = HasTraversePrivilege;

    Context->Fini = FusePrepareLookupPath_ContextFini;

    Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;

exit:
    if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
    {
        FspPosixDeletePath(PosixPath);
            /* handles NULL paths */
        FuseCacheDereferenceGen(Context->Instance->Cache, CacheGen);
            /* handles NULL gens */
    }
}

static VOID FusePrepareLookupPath2(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    PSTR PosixPath = 0;
    PWSTR FileName = 0;

    switch (Context->InternalRequest->Kind)
    {
    case FspFsctlTransactSetInformationKind:
        ASSERT(FileRenameInformation ==
            Context->InternalRequest->Req.SetInformation.FileInformationClass);
        FileName = (PWSTR)Context->InternalRequest->Buffer;
        break;
    default:
        ASSERT(FALSE);
        Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_INVALID_PARAMETER;
        goto exit;
    }

    if (0 != FileName)
    {
        Context->InternalResponse->IoStatus.Status = FspPosixMapWindowsToPosixPathEx(
            FileName, &PosixPath, TRUE);
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            goto exit;
    }

    ASSERT(0 == Context->LookupPath.OrigPath.Buffer);
    ASSERT(0 != Context->LookupPath.OrigPath2.Buffer);
    RtlInitString(&Context->LookupPath.OrigPath, PosixPath);

    Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;

exit:
    if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
    {
        FspPosixDeletePath(PosixPath);
            /* handles NULL paths */
    }
}

static VOID FusePrepareLookupPath_ContextFini(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    if (FspFsctlTransactCreateKind == Context->InternalRequest->Kind &&
        0 != Context->File)
        FuseFileDelete(Context->Instance, Context->File);

    FspPosixDeletePath(Context->LookupPath.OrigPath2.Buffer);
        /* handles NULL paths */
    FspPosixDeletePath(Context->LookupPath.OrigPath.Buffer);
        /* handles NULL paths */
    FuseCacheDereferenceGen(Context->Instance->Cache, Context->LookupPath.CacheGen);
        /* handles NULL gens */
}

static VOID FuseLookupPath(FUSE_CONTEXT *Context)
{
#define RootName                        (1 == Context->LookupPath.Name.Length && '/' == Context->LookupPath.Name.Buffer[0])
#define LastName                        (0 == Context->LookupPath.Remain.Length)
#define UserMode                        (Context->LookupPath.UserMode)
#define TravPriv                        (Context->LookupPath.HasTraversePrivilege)

    PAGED_CODE();

    coro_block (Context->CoroState)
    {
        Context->LookupPath.Ino = FUSE_PROTO_ROOT_INO;
        DEBUGFILL(&Context->Lookup.Attr, sizeof Context->Lookup.Attr);
        while (1) /* for (;;) produces "warning C4702: unreachable code" */
        {
            FusePosixPathPrefix(&Context->LookupPath.Remain, &Context->LookupPath.Name, &Context->LookupPath.Remain);

            /*
             * - RootName:
             *     - UserMode:
             *         - !LastName && !TravPriv:
             *             - Lookup
             *             - TraverseCheck
             *         - LastName:
             *             - Lookup
             *             - AccessCheck
             *     - !UserMode:
             *         - LastName:
             *             - Lookup
             * - !RootName:
             *     - Lookup
             *     - UserMode:
             *         - !LastName && !TravPriv:
             *             - TraverseCheck
             *         - LastName:
             *             - AccessCheck
             */
            if (!RootName || LastName || (UserMode && !TravPriv))
            {
                coro_await (FuseLookup(Context));
                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
                    coro_break;

                if (UserMode)
                {
                    if (!LastName && !TravPriv)
                    {
                        Context->InternalResponse->IoStatus.Status = FuseAccessCheck(
                            Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid,
                            Context->LookupPath.Attr.mode,
                            Context->OrigUid, Context->OrigGid,
                            FILE_TRAVERSE, 0);
                        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
                            coro_break;
                    }
                    else if (LastName)
                    {
                        Context->InternalResponse->IoStatus.Status = FuseAccessCheck(
                            Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid,
                            Context->LookupPath.Attr.mode,
                            Context->OrigUid, Context->OrigGid,
                            Context->LookupPath.DesiredAccess, &Context->LookupPath.GrantedAccess);
                        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
                            coro_break;
                    }
                }
            }

            if (LastName)
            {
                ASSERT(DEBUGGOOD(&Context->Lookup.Attr, sizeof Context->Lookup.Attr));
                break;
            }
        }

        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
    }

#undef TravPriv
#undef UserMode
#undef LastName
#undef RootName
}

static VOID FuseCreateCheck(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    /*
     * CreateCheck for a new file consists of checking the parent directory
     * for the FILE_ADD_SUBDIRECTORY or FILE_ADD_FILE rights (depending on
     * whether we are creating a file or directory).
     *
     * If the access check succeeds and MAXIMUM_ALLOWED has been requested
     * then we go ahead and grant all access to the creator.
     */

    coro_block (Context->CoroState)
    {
        if (Context->InternalRequest->Req.Create.HasTrailingBackslash &&
            !FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DIRECTORY_FILE))
        {
            Context->InternalResponse->IoStatus.Status = (UINT32)STATUS_OBJECT_NAME_INVALID;
            coro_break;
        }

        if (Context->InternalRequest->Req.Create.HasRestorePrivilege)
            Context->LookupPath.DesiredAccess = 0;
        else if (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DIRECTORY_FILE))
            Context->LookupPath.DesiredAccess = FILE_ADD_SUBDIRECTORY;
        else
            Context->LookupPath.DesiredAccess = FILE_ADD_FILE;

        FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0);
        coro_await (FuseLookupPath(Context));
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            coro_break;

        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess =
            FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED) ?
                IoGetFileObjectGenericMapping()->GenericAll :
                Context->InternalRequest->Req.Create.DesiredAccess;
        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |=
            Context->InternalRequest->Req.Create.GrantedAccess;

        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
    }
}

static VOID FuseOpenCheck(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    /*
     * OpenCheck consists of checking the file for the desired access,
     * unless FILE_DELETE_ON_CLOSE is requested in which case we also
     * check for DELETE access.
     *
     * If the access check succeeds and MAXIMUM_ALLOWED was not requested
     * then we reset the DELETE access based on whether it was actually
     * requested in DesiredAccess.
     */

    coro_block (Context->CoroState)
    {
        Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess |
            (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DELETE_ON_CLOSE) ?
                DELETE : 0);

        Context->LookupPath.Remain = Context->LookupPath.OrigPath;
        coro_await (FuseLookupPath(Context));
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            coro_break;

        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess;
        if (!FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED))
            Context->InternalResponse->Rsp.Create.Opened.GrantedAccess &= ~DELETE |
                (Context->InternalRequest->Req.Create.DesiredAccess & DELETE);
        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |=
            Context->InternalRequest->Req.Create.GrantedAccess;

        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
    }
}

static VOID FuseOverwriteCheck(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    /*
     * OverwriteCheck consists of checking the file for the desired access,
     * unless FILE_DELETE_ON_CLOSE is requested in which case we also
     * check for DELETE access. Furthermore we grant DELETE or FILE_WRITE_DATA
     * access based on whether this is a Supersede or Overwrite operation.
     *
     * If the access check succeeds and MAXIMUM_ALLOWED was not requested
     * then we reset the DELETE and FILE_WRITE_DATA accesses based on whether
     * they were actually requested in DesiredAccess.
     */

    coro_block (Context->CoroState)
    {
        Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess |
            (FILE_SUPERSEDE == ((Context->InternalRequest->Req.Create.CreateOptions >> 24) & 0xff) ?
                DELETE : FILE_WRITE_DATA) |
            (FlagOn(Context->InternalRequest->Req.Create.CreateOptions, FILE_DELETE_ON_CLOSE) ?
                DELETE : 0);

        Context->LookupPath.Remain = Context->LookupPath.OrigPath;
        coro_await (FuseLookupPath(Context));
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            coro_break;

        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess;
        if (!FlagOn(Context->InternalRequest->Req.Create.DesiredAccess, MAXIMUM_ALLOWED))
            Context->InternalResponse->Rsp.Create.Opened.GrantedAccess &= ~(DELETE | FILE_WRITE_DATA) |
                (Context->InternalRequest->Req.Create.DesiredAccess & (DELETE | FILE_WRITE_DATA));
        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |=
            Context->InternalRequest->Req.Create.GrantedAccess;

        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
    }
}

static VOID FuseOpenTargetDirectoryCheck(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    /*
     * OpenTargetDirectoryCheck consists of checking the parent directory
     * for the desired access.
     */

    coro_block (Context->CoroState)
    {
        Context->LookupPath.DesiredAccess = Context->InternalRequest->Req.Create.DesiredAccess;

        FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0);
        coro_await (FuseLookupPath(Context));
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            coro_break;

        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess = Context->LookupPath.GrantedAccess;
        Context->InternalResponse->Rsp.Create.Opened.GrantedAccess |=
            Context->InternalRequest->Req.Create.GrantedAccess;

        Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
    }
}

static VOID FuseRenameCheck(FUSE_CONTEXT *Context)
{
    PAGED_CODE();

    /*
     * RenameCheck consists of checking the new file name for DELETE access.
     *
     * The following assumptions are being made here for a file that is going
     * to be replaced:
     * -   The new file is in the same directory as the old one. In that case
     *     there is no need for traverse access checks as they have been already
     *     performed (if necessary) when opening the file under the existing file
     *     name.
     * -   The new file is in a different directory than the old one. In that case
     *     NTOS called us with SL_OPEN_TARGET_DIRECTORY and we performed any
     *     necessary traverse access checks at that time.
     */

    coro_block (Context->CoroState)
    {
        Context->LookupPath.DesiredAccess = 0;

        FusePosixPathSuffix(&Context->LookupPath.OrigPath, &Context->LookupPath.Remain, 0);
        coro_await (FuseLookupPath(Context));
        if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
            coro_break;

        Context->LookupPath.Ino2 = Context->LookupPath.Ino;

        FusePosixPathSuffix(&Context->LookupPath.OrigPath, 0, &Context->LookupPath.Name);
        coro_await (FuseLookup(Context));
        if (NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
        {
            if (0 != Context->InternalRequest->Req.SetInformation.Info.Rename.AccessToken)
            {
                Context->InternalResponse->IoStatus.Status = FuseAccessCheck(
                    Context->LookupPath.Attr.uid, Context->LookupPath.Attr.gid,
                    Context->LookupPath.Attr.mode,
                    Context->OrigUid, Context->OrigGid,
                    DELETE, &Context->LookupPath.GrantedAccess);
                if (!NT_SUCCESS(Context->InternalResponse->IoStatus.Status))
                    coro_break;
            }

            Context->InternalResponse->IoStatus.Status = STATUS_SUCCESS;
        }

        Context->LookupPath.OrigPath2 = Context->LookupPath.OrigPath;
        Context->LookupPath.Name2 = Context->LookupPath.Name;

        Context->LookupPath.Ino = 0;
        Context->LookupPath.OrigPath.Length = Context->LookupPath.OrigPath.MaximumLength = 0;
        Context->LookupPath.OrigPath.Buffer = 0
Download .txt
gitextract_o7pwrk8z/

├── .gitmodules
├── Contributors.asciidoc
├── License.txt
├── README.md
├── appveyor.yml
├── doc/
│   ├── component.puml
│   ├── winseq.puml
│   └── wslseq.puml
├── ext/
│   └── tlib/
│       ├── Commit.txt
│       ├── callstack.c
│       ├── callstack.h
│       ├── injected/
│       │   ├── allfunc.h
│       │   ├── curlfunc.c
│       │   ├── curlfunc.h
│       │   ├── stdfunc.c
│       │   └── stdfunc.h
│       ├── injection.c
│       ├── injection.h
│       ├── testsuite.c
│       └── testsuite.h
├── src/
│   ├── fusermount/
│   │   ├── fusermount-helper.c
│   │   ├── fusermount.c
│   │   ├── install.sh
│   │   └── uninstall.sh
│   ├── shared/
│   │   ├── km/
│   │   │   ├── cache.c
│   │   │   ├── context.c
│   │   │   ├── coro.h
│   │   │   ├── debug.c
│   │   │   ├── errno.i
│   │   │   ├── errnosym.i
│   │   │   ├── file.c
│   │   │   ├── fuseop.c
│   │   │   ├── instance.c
│   │   │   ├── ioq.c
│   │   │   ├── path.c
│   │   │   ├── proto.c
│   │   │   ├── proto.h
│   │   │   ├── shared.h
│   │   │   └── util.c
│   │   └── ku/
│   │       └── wslfuse.h
│   ├── winfuse/
│   │   ├── device.c
│   │   ├── driver.c
│   │   ├── driver.h
│   │   ├── driver.inf.in
│   │   └── version.rc
│   └── wslfuse/
│       ├── device.c
│       ├── driver.c
│       ├── driver.h
│       ├── driver.inf.in
│       └── version.rc
├── tools/
│   ├── DigiCert High Assurance EV Root CA.crt
│   ├── build-libfuse.bat
│   ├── build-lxdk.bat
│   ├── build-sample.bat
│   ├── build-winfsp.bat
│   ├── build.bat
│   ├── debug.bat
│   ├── deploy.bat
│   ├── deploy.ps1
│   ├── gensrc/
│   │   ├── errno.sh
│   │   └── errno.txt
│   ├── ioc.c
│   ├── license-headers/
│   │   ├── fix.ps1
│   │   ├── header.c
│   │   ├── header.cpp
│   │   └── header.h
│   ├── nmake-ext-test.bat
│   └── run-tests.bat
└── tst/
    ├── lockdly/
    │   └── lockdly.c
    ├── memfs-fuse3/
    │   ├── .gitignore
    │   ├── compat.h
    │   ├── memfs-fuse3.cpp
    │   ├── memfs-fuse3.exe.vcxproj
    │   ├── memfs-fuse3.exe.vcxproj.filters
    │   ├── memfs-fuse3.out.vcxproj
    │   ├── memfs-fuse3.out.vcxproj.filters
    │   └── memfs-fuse3.sln
    ├── winfuse-tests/
    │   ├── coro-test.c
    │   ├── path-test.c
    │   ├── transact-test.c
    │   └── winfuse-tests.c
    └── wslfuse-tests/
        ├── mount-test.c
        └── wslfuse-tests.c
Download .txt
SYMBOL INDEX (381 symbols across 35 files)

FILE: ext/tlib/callstack.c
  function tlib_callstack (line 21) | void tlib_callstack(size_t skip, size_t count, struct tlib_callstack_s *...

FILE: ext/tlib/callstack.h
  type tlib_callstack_s (line 19) | struct tlib_callstack_s
  type tlib_callstack_s (line 24) | struct tlib_callstack_s

FILE: ext/tlib/injected/curlfunc.c
  function CURL (line 16) | CURL *tlib_curl_easy_init(void)
  function CURLM (line 21) | CURLM *tlib_curl_multi_init(void)
  function CURLMcode (line 26) | CURLMcode tlib_curl_multi_add_handle(CURLM *mh, CURL *eh)
  function CURLMcode (line 31) | CURLMcode tlib_curl_multi_perform(CURLM *mh, int *running_handles)

FILE: ext/tlib/injection.c
  type injection_cond_s (line 17) | struct injection_cond_s
  type injection_entry_s (line 23) | struct injection_entry_s
  type injection_htab_s (line 29) | struct injection_htab_s
  function hash_chars (line 34) | static inline size_t hash_chars(const char *s, size_t length)
  type injection_htab_s (line 42) | struct injection_htab_s
  type injection_htab_s (line 44) | struct injection_htab_s
  type injection_entry_s (line 49) | struct injection_entry_s
  type injection_entry_s (line 53) | struct injection_entry_s
  type injection_htab_s (line 55) | struct injection_htab_s
  type injection_entry_s (line 57) | struct injection_entry_s
  type injection_entry_s (line 62) | struct injection_entry_s
  type injection_htab_s (line 64) | struct injection_htab_s
  type injection_entry_s (line 66) | struct injection_entry_s
  type injection_cond_s (line 73) | struct injection_cond_s
  type injection_entry_s (line 73) | struct injection_entry_s
  type injection_cond_s (line 75) | struct injection_cond_s
  type injection_cond_s (line 76) | struct injection_cond_s
  function injection_cond_set (line 87) | static void injection_cond_set(struct injection_entry_s *entry, const ch...
  function injection_cond_remove (line 102) | static void injection_cond_remove(struct injection_entry_s *entry, const...
  type injection_entry_s (line 119) | struct injection_entry_s
  function tlib_injection_trace (line 124) | int tlib_injection_trace(void *injection)
  function tlib_injection_enable (line 135) | void tlib_injection_enable(const char *name, const char *sym, unsigned t...
  function tlib_injection_disable (line 140) | void tlib_injection_disable(const char *name, const char *sym)

FILE: ext/tlib/testsuite.c
  type test (line 16) | struct test
  type test (line 23) | struct test
  type test (line 24) | struct test
  type test (line 25) | struct test
  type test (line 26) | struct test
  function add_test_to_list (line 27) | static void add_test_to_list(const char *name, void (*fn)(void), int opt...
  function tlib_add_test_suite (line 38) | void tlib_add_test_suite(const char *name, void (*fn)(void))
  function tlib_add_test (line 42) | void tlib_add_test(const char *name, void (*fn)(void))
  function tlib_add_test_opt (line 46) | void tlib_add_test_opt(const char *name, void (*fn)(void))
  function run_test (line 55) | static double run_test(struct test *test)
  function do_test_default (line 71) | static void do_test_default(struct test *test, int testno)
  function do_test_list (line 90) | static void do_test_list(struct test *test, int testno)
  function do_test_tap (line 95) | static void do_test_tap(struct test *test, int testno)
  function test_printf (line 106) | static void test_printf(const char *fmt, ...)
  function tlib_printf (line 115) | void tlib_printf(const char *fmt, ...)
  function tlib_run_tests (line 124) | void tlib_run_tests(int argc, char *argv[])
  function tlib__assert (line 202) | void tlib__assert(const char *func, const char *file, int line, const ch...

FILE: src/fusermount/fusermount-helper.c
  function vprintlog (line 51) | static void vprintlog(HANDLE h, const char *format, va_list ap)
  function printlog (line 67) | static void printlog(HANDLE h, const char *format, ...)
  function BOOL (line 81) | static BOOL MountSet_Drive(PWSTR VolumeName, PWSTR MountPoint, PHANDLE P...
  function BOOL (line 117) | static BOOL MountSet(PWSTR VolumeName, PWSTR MountPoint, PHANDLE PMountH...
  function wmain (line 155) | int wmain(int argc, wchar_t **argv)
  function wmainCRTStartup (line 187) | void wmainCRTStartup(void)

FILE: src/fusermount/fusermount.c
  type mount_opts (line 50) | struct mount_opts
  function warn (line 63) | static void warn(const char *format, ...)
  function utf8_to_utf16 (line 102) | static void utf8_to_utf16(const char *src0, uint16_t *dst, size_t siz)
  function get_mnt_id (line 160) | static int get_mnt_id(const char *mountpoint)
  function mount_opt_parse (line 191) | static void mount_opt_parse(struct mount_opts *mo)
  function start_winmount_helper (line 338) | static int start_winmount_helper(const char *VolumeName, char WinMountPo...
  function stop_winmount_helper (line 443) | static void stop_winmount_helper(pid_t pid, int ofd)
  function spawn_lxmount_helper (line 454) | static int spawn_lxmount_helper(char WinMountPoint[260], const char *mou...
  function do_mount (line 603) | static void do_mount(void)
  function do_unmount (line 716) | static void do_unmount(void)
  function do_version (line 847) | static void do_version(void)
  function usage (line 853) | static void usage(void)
  function main (line 869) | int main(int argc, char *argv[])

FILE: src/shared/km/cache.c
  type FUSE_CACHE_ITEM (line 95) | typedef struct _FUSE_CACHE_ITEM FUSE_CACHE_ITEM;
  type _FUSE_CACHE (line 97) | struct _FUSE_CACHE
  type _FUSE_CACHE_GEN (line 110) | struct _FUSE_CACHE_GEN
  type _FUSE_CACHE_ITEM (line 117) | struct _FUSE_CACHE_ITEM
  function UINT64 (line 134) | static inline UINT64 FuseCacheForgetTime(FUSE_CACHE *Cache, UINT64 Inter...
  function BOOLEAN (line 145) | static inline BOOLEAN FuseCacheForgetNextItem(FUSE_CACHE *Cache,
  function BOOLEAN (line 161) | static inline BOOLEAN FuseCacheExpireItem(FUSE_CACHE *Cache,
  function BOOLEAN (line 178) | static inline BOOLEAN FuseCacheExpireNextItem(FUSE_CACHE *Cache,
  function hash_chars (line 191) | static inline size_t hash_chars(const char *s, size_t length)
  function hash_upper_chars (line 200) | static inline size_t hash_upper_chars(const char *s, size_t length)
  function ULONG (line 209) | static inline ULONG FuseCacheHash(UINT64 ParentIno, PSTRING Name, BOOLEA...
  function FUSE_CACHE_ITEM (line 216) | static inline FUSE_CACHE_ITEM *FuseCacheLookupHashedItem(FUSE_CACHE *Cache,
  function VOID (line 232) | static inline VOID FuseCacheAddItem(FUSE_CACHE *Cache,
  function FUSE_CACHE_ITEM (line 252) | static inline FUSE_CACHE_ITEM *FuseCacheUpdateHashedItem(FUSE_CACHE *Cache,
  function NTSTATUS (line 280) | NTSTATUS FuseCacheCreate(ULONG Capacity, BOOLEAN CaseInsensitive, FUSE_C...
  function VOID (line 314) | VOID FuseCacheDelete(FUSE_CACHE *Cache)
  function VOID (line 331) | VOID FuseCacheExpirationRoutine(FUSE_CACHE *Cache,
  function NTSTATUS (line 393) | NTSTATUS FuseCacheReferenceGen(FUSE_CACHE *Cache, PVOID *PGen)
  function VOID (line 454) | VOID FuseCacheDereferenceGen(FUSE_CACHE *Cache, PVOID Gen0)
  function BOOLEAN (line 474) | BOOLEAN FuseCacheGetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING N...
  function VOID (line 511) | VOID FuseCacheSetEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING Name,
  function VOID (line 574) | VOID FuseCacheRemoveEntry(FUSE_CACHE *Cache, UINT64 ParentIno, PSTRING N...
  function VOID (line 590) | VOID FuseCacheReferenceItem(FUSE_CACHE *Cache, PVOID Item0)
  function VOID (line 599) | VOID FuseCacheDereferenceItem(FUSE_CACHE *Cache, PVOID Item0)
  function VOID (line 618) | VOID FuseCacheQuickExpireItem(FUSE_CACHE *Cache, PVOID Item0)
  function VOID (line 627) | VOID FuseCacheDeleteForgotten(PLIST_ENTRY ForgetList)
  function BOOLEAN (line 639) | BOOLEAN FuseCacheForgetOne(PLIST_ENTRY ForgetList, FUSE_PROTO_FORGET_ONE...

FILE: src/shared/km/context.c
  function VOID (line 33) | VOID FuseContextCreate(FUSE_CONTEXT **PContext,
  function VOID (line 66) | VOID FuseContextDelete(FUSE_CONTEXT *Context)

FILE: src/shared/km/debug.c
  function ULONG (line 25) | ULONG DebugRandom(VOID)
  function BOOLEAN (line 43) | BOOLEAN DebugMemory(PVOID Memory, SIZE_T Size, BOOLEAN Test)
  function VOID (line 247) | VOID FuseDebugLogRequest(FUSE_PROTO_REQ *Request)
  function VOID (line 422) | VOID FuseDebugLogResponse(FUSE_PROTO_RSP *Response)

FILE: src/shared/km/file.c
  function VOID (line 24) | VOID FuseFileInstanceInit(FUSE_INSTANCE *Instance)
  function VOID (line 30) | VOID FuseFileInstanceFini(FUSE_INSTANCE *Instance)
  function NTSTATUS (line 43) | NTSTATUS FuseFileCreate(FUSE_INSTANCE *Instance, FUSE_FILE **PFile)
  function VOID (line 66) | VOID FuseFileDelete(FUSE_INSTANCE *Instance, FUSE_FILE *File)

FILE: src/shared/km/fuseop.c
  function BOOLEAN (line 143) | static BOOLEAN FuseOpReserved_Init(FUSE_CONTEXT *Context)
  function BOOLEAN (line 174) | static BOOLEAN FuseOpReserved_Destroy(FUSE_CONTEXT *Context)
  function BOOLEAN (line 188) | static BOOLEAN FuseOpReserved_Forget(FUSE_CONTEXT *Context)
  function BOOLEAN (line 205) | static BOOLEAN FuseOpReserved(FUSE_CONTEXT *Context)
  function VOID (line 223) | static VOID FuseLookup(FUSE_CONTEXT *Context)
  function ACCESS_MASK (line 277) | static inline ACCESS_MASK FusePosixMapPermissionToAccessMask(UINT32 Mode...
  function NTSTATUS (line 286) | static NTSTATUS FuseAccessCheck(
  function VOID (line 321) | static VOID FusePrepareLookupPath(FUSE_CONTEXT *Context)
  function VOID (line 427) | static VOID FusePrepareLookupPath2(FUSE_CONTEXT *Context)
  function VOID (line 469) | static VOID FusePrepareLookupPath_ContextFini(FUSE_CONTEXT *Context)
  function VOID (line 485) | static VOID FuseLookupPath(FUSE_CONTEXT *Context)
  function VOID (line 569) | static VOID FuseCreateCheck(FUSE_CONTEXT *Context)
  function VOID (line 614) | static VOID FuseOpenCheck(FUSE_CONTEXT *Context)
  function VOID (line 650) | static VOID FuseOverwriteCheck(FUSE_CONTEXT *Context)
  function VOID (line 689) | static VOID FuseOpenTargetDirectoryCheck(FUSE_CONTEXT *Context)
  function VOID (line 715) | static VOID FuseRenameCheck(FUSE_CONTEXT *Context)
  function VOID (line 773) | static VOID FuseCreate(FUSE_CONTEXT *Context)
  function VOID (line 935) | static VOID FuseOpen(FUSE_CONTEXT *Context)
  function VOID (line 1032) | static VOID FuseOpCreate_FileCreate(FUSE_CONTEXT *Context)
  function VOID (line 1047) | static VOID FuseOpCreate_FileOpen(FUSE_CONTEXT *Context)
  function VOID (line 1061) | static VOID FuseOpCreate_FileOpenIf(FUSE_CONTEXT *Context)
  function VOID (line 1085) | static VOID FuseOpCreate_FileOverwrite(FUSE_CONTEXT *Context)
  function VOID (line 1103) | static VOID FuseOpCreate_FileOverwriteIf(FUSE_CONTEXT *Context)
  function VOID (line 1133) | static VOID FuseOpCreate_FileOpenTargetDirectory(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1156) | static BOOLEAN FuseOpCreate(FUSE_CONTEXT *Context)
  function INT (line 1197) | static INT FuseOgCreate(FUSE_CONTEXT *Context, BOOLEAN Acquire)
  function BOOLEAN (line 1239) | static BOOLEAN FuseOpOverwrite(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1268) | static BOOLEAN FuseOpCleanup(FUSE_CONTEXT *Context)
  function INT (line 1306) | static INT FuseOgCleanup(FUSE_CONTEXT *Context, BOOLEAN Acquire)
  function BOOLEAN (line 1326) | static BOOLEAN FuseOpClose(FUSE_CONTEXT *Context)
  function VOID (line 1348) | static VOID FuseOpClose_ContextFini(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1356) | static BOOLEAN FuseOpRead(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1415) | static BOOLEAN FuseOpWrite(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1507) | static BOOLEAN FuseOpQueryInformation(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1528) | static BOOLEAN FuseOpSetInformation_SetBasicInfo(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1571) | static BOOLEAN FuseOpSetInformation_SetAllocationSize(FUSE_CONTEXT *Cont...
  function BOOLEAN (line 1609) | static BOOLEAN FuseOpSetInformation_SetFileSize(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1639) | static BOOLEAN FuseOpSetInformation_SetDelete(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1701) | static BOOLEAN FuseOpSetInformation_Rename(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1770) | static BOOLEAN FuseOpSetInformation(FUSE_CONTEXT *Context)
  function INT (line 1792) | static INT FuseOgSetInformation(FUSE_CONTEXT *Context, BOOLEAN Acquire)
  function BOOLEAN (line 1818) | static BOOLEAN FuseOpQueryEa(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1825) | static BOOLEAN FuseOpSetEa(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1832) | static BOOLEAN FuseOpFlushBuffers(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1871) | static BOOLEAN FuseOpQueryVolumeInformation(FUSE_CONTEXT *Context)
  function BOOLEAN (line 1894) | static BOOLEAN FuseAddDirInfo(FUSE_CONTEXT *Context,
  function VOID (line 1960) | static VOID FuseOpQueryDirectory_GetDirInfoByName(FUSE_CONTEXT *Context)
  function VOID (line 2011) | static VOID FuseOpQueryDirectory_ReadDirectory(FUSE_CONTEXT *Context)
  function BOOLEAN (line 2137) | static BOOLEAN FuseOpQueryDirectory(FUSE_CONTEXT *Context)
  function VOID (line 2161) | static VOID FuseOpQueryDirectory_ContextFini(FUSE_CONTEXT *Context)
  function INT (line 2174) | static INT FuseOgQueryDirectory(FUSE_CONTEXT *Context, BOOLEAN Acquire)
  function BOOLEAN (line 2184) | static BOOLEAN FuseOpFileSystemControl(FUSE_CONTEXT *Context)
  function BOOLEAN (line 2191) | static BOOLEAN FuseOpDeviceControl(FUSE_CONTEXT *Context)
  function BOOLEAN (line 2198) | static BOOLEAN FuseOpQuerySecurity(FUSE_CONTEXT *Context)
  function BOOLEAN (line 2251) | static BOOLEAN FuseOpSetSecurity(FUSE_CONTEXT *Context)
  function VOID (line 2332) | static VOID FuseSecurity_ContextFini(FUSE_CONTEXT *Context)

FILE: src/shared/km/instance.c
  function NTSTATUS (line 42) | NTSTATUS FuseInstanceInit(FUSE_INSTANCE *Instance,
  function VOID (line 103) | VOID FuseInstanceFini(FUSE_INSTANCE *Instance)
  function VOID (line 129) | VOID FuseInstanceExpirationRoutine(FUSE_INSTANCE *Instance, UINT64 Expir...
  function NTSTATUS (line 136) | NTSTATUS FuseInstanceTransact(FUSE_INSTANCE *Instance,

FILE: src/shared/km/ioq.c
  type _FUSE_IOQ (line 44) | struct _FUSE_IOQ
  function NTSTATUS (line 53) | NTSTATUS FuseIoqCreate(FUSE_IOQ **PIoq)
  function VOID (line 76) | VOID FuseIoqDelete(FUSE_IOQ *Ioq)
  function VOID (line 95) | VOID FuseIoqStartProcessing(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context)
  function FUSE_CONTEXT (line 130) | FUSE_CONTEXT *FuseIoqEndProcessing(FUSE_IOQ *Ioq, UINT64 Unique)
  function VOID (line 159) | VOID FuseIoqPostPending(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context)
  function VOID (line 177) | VOID FuseIoqPostPendingAndStop(FUSE_IOQ *Ioq, FUSE_CONTEXT *Context)
  function FUSE_CONTEXT (line 211) | FUSE_CONTEXT *FuseIoqNextPending(FUSE_IOQ *Ioq)

FILE: src/shared/km/path.c
  function VOID (line 32) | VOID FusePosixPathPrefix(PSTRING Path, PSTRING Prefix, PSTRING Remain)
  function VOID (line 70) | VOID FusePosixPathSuffix(PSTRING Path, PSTRING Remain, PSTRING Suffix)

FILE: src/shared/km/proto.c
  function VOID (line 123) | static inline VOID FuseProtoInitRequest(FUSE_CONTEXT *Context,
  function NTSTATUS (line 135) | NTSTATUS FuseProtoPostInit(FUSE_INSTANCE *Instance)
  function VOID (line 153) | VOID FuseProtoSendInit(FUSE_CONTEXT *Context)
  function NTSTATUS (line 172) | NTSTATUS FuseProtoPostDestroy(FUSE_INSTANCE *Instance)
  function VOID (line 190) | VOID FuseProtoSendDestroy(FUSE_CONTEXT *Context)
  function NTSTATUS (line 233) | NTSTATUS FuseProtoPostForget(FUSE_INSTANCE *Instance, PLIST_ENTRY Forget...
  function VOID (line 258) | static VOID FuseProtoPostForget_ContextFini(FUSE_CONTEXT *Context)
  function VOID (line 265) | VOID FuseProtoFillForget(FUSE_CONTEXT *Context)
  function VOID (line 286) | VOID FuseProtoFillBatchForget(FUSE_CONTEXT *Context)
  function VOID (line 309) | VOID FuseProtoSendStatfs(FUSE_CONTEXT *Context)
  function VOID (line 374) | VOID FuseProtoSendFtruncate(FUSE_CONTEXT *Context)
  function VOID (line 400) | VOID FuseProtoSendFutimens(FUSE_CONTEXT *Context)
  function VOID (line 447) | VOID FuseProtoSendLookupChown(FUSE_CONTEXT *Context)
  function VOID (line 490) | VOID FuseProtoSendSetattr(FUSE_CONTEXT *Context)
  function VOID (line 547) | VOID FuseProtoSendMkdir(FUSE_CONTEXT *Context)
  function VOID (line 576) | VOID FuseProtoSendMknod(FUSE_CONTEXT *Context)
  function VOID (line 608) | VOID FuseProtoSendRmdir(FUSE_CONTEXT *Context)
  function VOID (line 633) | VOID FuseProtoSendUnlink(FUSE_CONTEXT *Context)
  function VOID (line 658) | VOID FuseProtoSendRename(FUSE_CONTEXT *Context)
  function VOID (line 694) | VOID FuseProtoSendCreate(FUSE_CONTEXT *Context)
  function VOID (line 726) | VOID FuseProtoSendOpendir(FUSE_CONTEXT *Context)
  function VOID (line 745) | VOID FuseProtoSendOpen(FUSE_CONTEXT *Context)
  function VOID (line 764) | VOID FuseProtoSendReleasedir(FUSE_CONTEXT *Context)
  function VOID (line 788) | VOID FuseProtoSendRelease(FUSE_CONTEXT *Context)
  function VOID (line 814) | VOID FuseProtoSendReaddir(FUSE_CONTEXT *Context)
  function VOID (line 844) | VOID FuseProtoSendRead(FUSE_CONTEXT *Context)
  function VOID (line 874) | VOID FuseProtoSendWrite(FUSE_CONTEXT *Context)
  function VOID (line 905) | VOID FuseProtoSendFsyncdir(FUSE_CONTEXT *Context)
  function VOID (line 926) | VOID FuseProtoSendFsync(FUSE_CONTEXT *Context)
  function VOID (line 947) | VOID FuseAttrToFileInfo(FUSE_INSTANCE *Instance,
  function NTSTATUS (line 993) | NTSTATUS FuseNtStatusFromErrno(FUSE_INSTANCE_TYPE InstanceType, INT32 Er...

FILE: src/shared/km/proto.h
  type FUSE_PROTO_OPCODE (line 36) | enum FUSE_PROTO_OPCODE
  type FUSE_PROTO_NOTIFY_CODE (line 85) | enum FUSE_PROTO_NOTIFY_CODE
  type FUSE_PROTO_STATFS (line 168) | typedef struct
  type FUSE_PROTO_ATTR (line 182) | typedef struct
  type FUSE_PROTO_ENTRY (line 202) | typedef struct
  type FUSE_PROTO_DIRENT (line 213) | typedef struct
  type FUSE_PROTO_DIRENTPLUS (line 222) | typedef struct
  type FUSE_PROTO_FILE_LOCK (line 228) | typedef struct
  type FUSE_PROTO_IOCTL_IOVEC (line 236) | typedef struct
  type FUSE_PROTO_FORGET_ONE (line 242) | typedef struct
  type FUSE_PROTO_REQ (line 248) | typedef struct
  type FUSE_PROTO_RSP (line 536) | typedef struct

FILE: src/shared/km/shared.h
  function UINT32 (line 84) | static inline
  function UINT64 (line 94) | static inline
  function ULONG (line 104) | static inline
  type FUSE_RWLOCK (line 126) | typedef struct _FUSE_RWLOCK
  function VOID (line 138) | static inline
  function VOID (line 149) | static inline
  function BOOLEAN (line 157) | static inline
  function BOOLEAN (line 175) | static inline
  function VOID (line 198) | static inline
  function VOID (line 207) | static inline
  type FUSE_IOQ (line 219) | typedef struct _FUSE_IOQ FUSE_IOQ;
  type FUSE_CACHE (line 220) | typedef struct _FUSE_CACHE FUSE_CACHE;
  type FUSE_INSTANCE_TYPE (line 221) | typedef enum _FUSE_INSTANCE_TYPE
  type FUSE_INSTANCE (line 227) | typedef struct _FUSE_INSTANCE
  function BOOLEAN (line 262) | static inline
  function VOID (line 269) | static inline
  type FUSE_FILE (line 278) | typedef struct _FUSE_FILE
  type FUSE_CONTEXT (line 294) | typedef struct _FUSE_CONTEXT FUSE_CONTEXT;
  type VOID (line 295) | typedef VOID FUSE_CONTEXT_FINI(FUSE_CONTEXT *Context);
  type BOOLEAN (line 296) | typedef BOOLEAN FUSE_OPERATION_PROC(FUSE_CONTEXT *Context);
  type INT (line 297) | typedef INT FUSE_OPERATION_GUARD(FUSE_CONTEXT *Context, BOOLEAN Acquire);
  type FUSE_OPERATION (line 304) | typedef struct _FUSE_OPERATION
  type FUSE_CONTEXT_LOOKUP (line 309) | typedef struct _FUSE_CONTEXT_LOOKUP
  type FUSE_CONTEXT_FORGET (line 317) | typedef struct _FUSE_CONTEXT_FORGET
  type FUSE_CONTEXT_SETATTR (line 321) | typedef struct _FUSE_CONTEXT_SETATTR
  type _FUSE_CONTEXT (line 326) | struct _FUSE_CONTEXT
  function BOOLEAN (line 395) | static inline BOOLEAN FuseContextProcess(FUSE_CONTEXT *Context,
  function INT (line 430) | static inline
  function INT (line 438) | static inline
  function INT (line 443) | static inline
  function INT (line 448) | static inline
  function INT (line 454) | static inline
  type FUSE_CACHE_GEN (line 480) | typedef struct _FUSE_CACHE_GEN FUSE_CACHE_GEN;
  function VOID (line 531) | static inline
  function VOID (line 539) | static inline

FILE: src/shared/km/util.c
  function PVOID (line 45) | PVOID FuseAllocatePoolMustSucceed(POOL_TYPE PoolType, SIZE_T Size, ULONG...
  function NTSTATUS (line 63) | NTSTATUS FuseSafeCopyMemory(PVOID Dst, PVOID Src, ULONG Len)
  function NTSTATUS (line 79) | NTSTATUS FuseGetTokenUid(PACCESS_TOKEN Token, TOKEN_INFORMATION_CLASS In...

FILE: src/shared/ku/wslfuse.h
  type CHAR (line 35) | typedef char CHAR;
  type WCHAR (line 36) | typedef uint16_t WCHAR;
  type UINT8 (line 37) | typedef uint8_t UINT8;
  type UINT16 (line 38) | typedef uint16_t UINT16;
  type UINT32 (line 39) | typedef uint32_t UINT32;
  type UINT64 (line 40) | typedef uint64_t UINT64;
  type FSP_FSCTL_VOLUME_PARAMS (line 106) | typedef struct
  type WSLFUSE_IOCTL_CREATEVOLUME_ARG (line 115) | typedef union
  type WSLFUSE_IOCTL_WINMOUNT_ARG (line 129) | typedef struct
  type WSLFUSE_IOCTL_LXMOUNT_ARG (line 138) | typedef struct

FILE: src/winfuse/device.c
  function NTSTATUS (line 36) | static NTSTATUS FuseDeviceInit(PDEVICE_OBJECT DeviceObject, FSP_FSCTL_VO...
  function VOID (line 52) | static VOID FuseDeviceFini(PDEVICE_OBJECT DeviceObject)
  function VOID (line 65) | static VOID FuseDeviceExpirationRoutine(PDEVICE_OBJECT DeviceObject, UIN...
  function NTSTATUS (line 78) | static NTSTATUS FuseDeviceTransact(PDEVICE_OBJECT DeviceObject, PIRP Irp)

FILE: src/winfuse/driver.c
  function NTSTATUS (line 30) | NTSTATUS DriverEntry(

FILE: src/winfuse/driver.h
  function FUSE_INSTANCE (line 31) | static inline

FILE: src/wslfuse/device.c
  type FILE (line 26) | typedef struct _FILE FILE;
  type MOUNT (line 27) | typedef struct _MOUNT MOUNT;
  type DEVICE (line 28) | typedef struct _DEVICE DEVICE;
  type _FILE (line 30) | struct _FILE
  type _MOUNT (line 45) | struct _MOUNT
  type _DEVICE (line 53) | struct _DEVICE
  function MOUNT (line 64) | static inline MOUNT *MountCreate(VOID)
  function VOID (line 79) | static inline VOID MountReference(MOUNT *Mount)
  function VOID (line 84) | static inline VOID MountDereference(MOUNT *Mount)
  function VOID (line 93) | static VOID FileProtoSendDestroyHandler(PVOID File0)
  function INT (line 111) | static INT FileIoctlCreateVolume(
  function INT (line 259) | static INT FileIoctlWinMount(
  function INT (line 321) | static INT FileIoctlLxMount(
  function INT (line 412) | static INT FileIoctlBegin(
  function INT (line 463) | static INT FileIoctlEnd(
  function INT (line 497) | static INT FileIoctl(
  function INT (line 536) | static INT FileRead(
  function INT (line 577) | static INT FileWriteVector(
  function INT (line 667) | static INT FileDelete(
  function INT (line 698) | static INT DeviceOpen(
  function INT (line 753) | static INT DeviceDelete(
  function VOID (line 776) | static VOID FuseMiscFileListInsert(FILE *File)
  function VOID (line 785) | static VOID FuseMiscFileListRemove(FILE *File)
  function MOUNT (line 794) | static MOUNT *FuseMiscFileListGetMount(DEVICE *Device, UINT64 VolumeId)
  function VOID (line 823) | static VOID FuseMiscExpirationRoutine(PVOID Context)
  function VOID (line 842) | static VOID FuseMiscTimerDpcRoutine(PKDPC Dpc,
  function VOID (line 850) | static VOID FuseMiscTimerInit(VOID)
  function INT (line 873) | INT FuseMiscRegister(PLX_INSTANCE Instance)
  function VOID (line 907) | VOID FuseMiscInitialize(VOID)

FILE: src/wslfuse/driver.c
  function NTSTATUS (line 30) | NTSTATUS DriverEntry(

FILE: tools/ioc.c
  function main (line 9) | int main(int argc, char *argv[])

FILE: tst/lockdly/lockdly.c
  function DWORD (line 26) | DWORD WINAPI ThreadProc(PVOID Param)
  function wmain (line 42) | int wmain(int argc, wchar_t *argv[])

FILE: tst/memfs-fuse3/compat.h
  type fuse_ino_t (line 34) | typedef uint64_t fuse_ino_t;

FILE: tst/memfs-fuse3/memfs-fuse3.cpp
  class memfs (line 35) | class memfs
    method memfs (line 38) | memfs() : _ino(1), _root(std::make_shared<node_t>(_ino, S_IFDIR | 0077...
    method main (line 42) | int main(int argc, char *argv[])
    type node_t (line 88) | struct node_t
      method node_t (line 90) | node_t(fuse_ino_t ino, fuse_mode_t mode, fuse_uid_t uid, fuse_gid_t ...
      method resize (line 102) | void resize(size_t size, bool capacity)
      type fuse_stat (line 121) | struct fuse_stat
    method fuse_timespec (line 127) | static fuse_timespec now()
    method memfs (line 141) | static memfs *getself()
    method getattr (line 146) | static int getattr(const char *path, struct fuse_stat *stbuf, struct f...
    method readlink (line 157) | static int readlink(const char *path, char *buf, size_t size)
    method mknod (line 172) | static int mknod(const char *path, fuse_mode_t mode, fuse_dev_t dev)
    method mkdir (line 179) | static int mkdir(const char *path, fuse_mode_t mode)
    method unlink (line 186) | static int unlink(const char *path)
    method rmdir (line 193) | static int rmdir(const char *path)
    method symlink (line 200) | static int symlink(const char *dstpath, const char *srcpath)
    method rename (line 207) | static int rename(const char *oldpath, const char *newpath, unsigned i...
    method link (line 238) | static int link(const char *oldpath, const char *newpath)
    method chmod (line 260) | static int chmod(const char *path, fuse_mode_t mode,
    method chown (line 273) | static int chown(const char *path, fuse_uid_t uid, fuse_gid_t gid,
    method truncate (line 289) | static int truncate(const char *path, fuse_off_t size,
    method open (line 304) | static int open(const char *path, struct fuse_file_info *fi)
    method read (line 311) | static int read(const char *path, char *buf, size_t size, fuse_off_t off,
    method write (line 328) | static int write(const char *path, const char *buf, size_t size, fuse_...
    method statfs (line 346) | static int statfs(const char *path, struct fuse_statvfs *stbuf)
    method flush (line 352) | static int flush(const char *path, struct fuse_file_info *fi)
    method release (line 357) | static int release(const char *path, struct fuse_file_info *fi)
    method setxattr (line 364) | static int setxattr(const char *path, const char *name0, const char *v...
    method getxattr (line 389) | static int getxattr(const char *path, const char *name0, char *value, ...
    method listxattr (line 411) | static int listxattr(const char *path, char *namebuf, size_t size)
    method removexattr (line 433) | static int removexattr(const char *path, const char *name0)
    method opendir (line 446) | static int opendir(const char *path, struct fuse_file_info *fi)
    method readdir (line 453) | static int readdir(const char *path, void *buf, fuse_fill_dir_t filler...
    method releasedir (line 469) | static int releasedir(const char *path, struct fuse_file_info *fi)
    type fuse_conn_info (line 476) | struct fuse_conn_info
    type fuse_config (line 477) | struct fuse_config
    method utimens (line 483) | static int utimens(const char *path, const struct fuse_timespec tmsp[2],
    method ioctl (line 503) | static int ioctl(const char *path, int cmd, void *arg, struct fuse_fil...
    method lookup_node (line 510) | std::tuple<std::shared_ptr<node_t>, std::string, std::shared_ptr<node_t>>
    method make_node (line 537) | int make_node(const char *path, fuse_mode_t mode, fuse_dev_t dev, cons...
    method remove_node (line 559) | int remove_node(const char *path, bool dir)
    method open_node (line 579) | int open_node(const char *path, bool dir, struct fuse_file_info *fi)
    method close_node (line 596) | int close_node(struct fuse_file_info *fi)
    method get_node (line 602) | std::shared_ptr<node_t> get_node(const char *path, struct fuse_file_in...
  function main (line 616) | int main(int argc, char *argv[])

FILE: tst/winfuse-tests/coro-test.c
  function bprintf (line 26) | static void bprintf(char **b, const char *format, ...)
  function coro_break_dotest (line 35) | static int coro_break_dotest(int brk, short stack[8], char **b)
  function coro_yield_dotest (line 46) | static int coro_yield_dotest(int brk, short stack[8], char **b)
  function coro_loopyield_dotest (line 60) | static int coro_loopyield_dotest(int brk, short stack[8], int *state, ch...
  function coro_await_break_dotest (line 77) | static int coro_await_break_dotest(int brk, short stack[8], char **b)
  function coro_await_yield_dotest (line 91) | static int coro_await_yield_dotest(int brk, short stack[8], char **b)
  function coro_await_loopyield_dotest (line 105) | static int coro_await_loopyield_dotest(int brk, short stack[8], int *sta...
  function coro_loopawait_yield_dotest (line 119) | static int coro_loopawait_yield_dotest(int brk, short stack[8], int *sta...
  function coro_await_await_yield_dotest (line 136) | static int coro_await_await_yield_dotest(int brk, short stack[8], char **b)
  function coro_await_loopawait_yield_dotest (line 150) | static int coro_await_loopawait_yield_dotest(int brk, short stack[8], in...
  function coro_loopawait_loopawait_yield_dotest (line 164) | static int coro_loopawait_loopawait_yield_dotest(int brk, short stack[8]...
  function coro_dotest (line 182) | static void coro_dotest(int brk)
  function coro_test (line 336) | static void coro_test(void)
  function coro_tests (line 342) | void coro_tests(void)

FILE: tst/winfuse-tests/path-test.c
  function path_prefix_test (line 29) | void path_prefix_test(void)
  function path_suffix_test (line 89) | void path_suffix_test(void)
  function path_tests (line 149) | void path_tests(void)

FILE: tst/winfuse-tests/transact-test.c
  function transact_init_dotest (line 31) | static void transact_init_dotest(PWSTR DeviceName, PWSTR Prefix)
  function transact_init_test (line 96) | static void transact_init_test(void)
  function transact_open_close_dotest_thread (line 105) | static unsigned __stdcall transact_open_close_dotest_thread(void *FilePath)
  function transact_open_close_dotest (line 133) | static void transact_open_close_dotest(PWSTR DeviceName, PWSTR Prefix, i...
  function transact_open_close_test (line 365) | static void transact_open_close_test(void)
  function transact_open_abandon_test (line 371) | static void transact_open_abandon_test(void)
  function transact_open_cancel_test (line 377) | static void transact_open_cancel_test(void)
  function transact_open_bogus_test (line 383) | static void transact_open_bogus_test(void)
  function transact_tests (line 389) | void transact_tests(void)

FILE: tst/winfuse-tests/winfuse-tests.c
  function main (line 25) | int main(int argc, char *argv[])

FILE: tst/wslfuse-tests/mount-test.c
  function mount_createvol_dotest (line 30) | static void mount_createvol_dotest(wchar_t *Prefix)
  function mount_createvol_test (line 55) | static void mount_createvol_test(void)
  function mount_unmount_test (line 62) | static void mount_unmount_test(void)
  function mount_tests (line 126) | void mount_tests(void)

FILE: tst/wslfuse-tests/wslfuse-tests.c
  function main (line 24) | int main(int argc, char *argv[])
Condensed preview — 83 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (523K chars).
[
  {
    "path": ".gitmodules",
    "chars": 276,
    "preview": "[submodule \"ext/libfuse\"]\n\tpath = ext/libfuse\n\turl = https://github.com/billziss-gh/libfuse.git\n[submodule \"ext/winfsp\"]"
  },
  {
    "path": "Contributors.asciidoc",
    "chars": 5714,
    "preview": "CONTRIBUTORS\n============\n\nThis document contains a list of all contributors to this project. Contributors that submit c"
  },
  {
    "path": "License.txt",
    "chars": 36104,
    "preview": "The WinFuse project is Copyright (C) Bill Zissimopoulos. It is licensed\nunder the terms of the AGPLv3.\n\nAs a special exc"
  },
  {
    "path": "README.md",
    "chars": 5041,
    "preview": "<h1 align=\"center\">\n    WinFuse &middot; FUSE for the Windows kernel\n</h1>\n\n<p align=\"center\">\n    <b>Download</b><br>\n "
  },
  {
    "path": "appveyor.yml",
    "chars": 4211,
    "preview": "version: '{build}'\n\nimage: Visual Studio 2019\n\nenvironment:\n  matrix:\n  - CONFIGURATION: Debug\n    WINFSP: rel\n    LXDK:"
  },
  {
    "path": "doc/component.puml",
    "chars": 1118,
    "preview": "left to right direction\nskinparam componentStyle uml2\nskinparam nodesep 50\nskinparam ranksep 30\nskinparam shadowing fals"
  },
  {
    "path": "doc/winseq.puml",
    "chars": 862,
    "preview": "skinparam shadowing false\nhide footbox\n\nbox \"Originating Process Context\"\n    participant \"Originating\\nProcess\" as OP\n "
  },
  {
    "path": "doc/wslseq.puml",
    "chars": 843,
    "preview": "skinparam shadowing false\nhide footbox\n\nbox \"Originating Process Context\"\n    participant \"Originating\\nProcess\" as OP\n "
  },
  {
    "path": "ext/tlib/Commit.txt",
    "chars": 211,
    "preview": "Taken from github.com/billziss-gh/winfsp/ext/tlib codebase:\n    commit 847eab3da4e558e2c88504edfe18a51e4450f9e0\n\nOrigina"
  },
  {
    "path": "ext/tlib/callstack.c",
    "chars": 2368,
    "preview": "/**\n * @file tlib/callstack.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/callstack.h>\n#include <s"
  },
  {
    "path": "ext/tlib/callstack.h",
    "chars": 534,
    "preview": "/**\n * @file tlib/callstack.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_CALLSTACK_H_INCLUDED\n#defi"
  },
  {
    "path": "ext/tlib/injected/allfunc.h",
    "chars": 250,
    "preview": "/**\n * @file tlib/injected/allfunc.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_INJECTED_ALLFUNC_H_"
  },
  {
    "path": "ext/tlib/injected/curlfunc.c",
    "chars": 877,
    "preview": "/**\n * @file tlib/injected/curlfunc.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/injected/curlfun"
  },
  {
    "path": "ext/tlib/injected/curlfunc.h",
    "chars": 718,
    "preview": "/**\n * @file tlib/injected/curlfunc.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_INJECTED_CURLFUNC_"
  },
  {
    "path": "ext/tlib/injected/stdfunc.c",
    "chars": 559,
    "preview": "/**\n * @file tlib/injected/stdfunc.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/injected/stdfunc."
  },
  {
    "path": "ext/tlib/injected/stdfunc.h",
    "chars": 573,
    "preview": "/**\n * @file tlib/injected/stdfunc.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_INJECTED_STDFUNC_H_"
  },
  {
    "path": "ext/tlib/injection.c",
    "chars": 4274,
    "preview": "/**\n * @file tlib/injection.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/injection.h>\n#include <t"
  },
  {
    "path": "ext/tlib/injection.h",
    "chars": 854,
    "preview": "/**\n * @file tlib/injection.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n/* NOTE: This header may usefully be in"
  },
  {
    "path": "ext/tlib/testsuite.c",
    "chars": 6333,
    "preview": "/**\n * @file tlib/testsuite.c\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#include <tlib/testsuite.h>\n#include <l"
  },
  {
    "path": "ext/tlib/testsuite.h",
    "chars": 3324,
    "preview": "/**\n * @file tlib/testsuite.h\n *\n * @copyright 2014-2019 Bill Zissimopoulos\n */\n\n#ifndef TLIB_TESTSUITE_H_INCLUDED\n#defi"
  },
  {
    "path": "src/fusermount/fusermount-helper.c",
    "chars": 5758,
    "preview": "/**\n * @file fusermount-helper.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n "
  },
  {
    "path": "src/fusermount/fusermount.c",
    "chars": 26230,
    "preview": "/**\n * @file fusermount.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * Yo"
  },
  {
    "path": "src/fusermount/install.sh",
    "chars": 713,
    "preview": "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# fuse"
  },
  {
    "path": "src/fusermount/uninstall.sh",
    "chars": 643,
    "preview": "#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# /de"
  },
  {
    "path": "src/shared/km/cache.c",
    "chars": 20284,
    "preview": "/**\n * @file shared/km/cache.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n"
  },
  {
    "path": "src/shared/km/context.c",
    "chars": 2731,
    "preview": "/**\n * @file shared/km/context.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n "
  },
  {
    "path": "src/shared/km/coro.h",
    "chars": 5114,
    "preview": "/**\n * @file shared/km/coro.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/shared/km/debug.c",
    "chars": 15950,
    "preview": "/**\n * @file shared/km/debug.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n"
  },
  {
    "path": "src/shared/km/errno.i",
    "chars": 6847,
    "preview": "#if FUSE_ERRNO == 87 /* Windows */\n\ncase 0: return STATUS_SUCCESS;\ncase 1: return STATUS_ACCESS_DENIED;\ncase 2: return S"
  },
  {
    "path": "src/shared/km/errnosym.i",
    "chars": 4474,
    "preview": "#if FUSE_ERRNO == 87 /* Windows */\n\ncase 0: return \"0\";\ncase 1: return \"EPERM\";\ncase 2: return \"ENOENT\";\ncase 3: return "
  },
  {
    "path": "src/shared/km/file.c",
    "chars": 2174,
    "preview": "/**\n * @file shared/km/file.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/shared/km/fuseop.c",
    "chars": 90093,
    "preview": "/**\n * @file shared/km/fuseop.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *"
  },
  {
    "path": "src/shared/km/instance.c",
    "chars": 9854,
    "preview": "/**\n * @file shared/km/instance.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n"
  },
  {
    "path": "src/shared/km/ioq.c",
    "chars": 6519,
    "preview": "/**\n * @file shared/km/ioq.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n *"
  },
  {
    "path": "src/shared/km/path.c",
    "chars": 2824,
    "preview": "/**\n * @file shared/km/path.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/shared/km/proto.c",
    "chars": 34522,
    "preview": "/**\n * @file shared/km/proto.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n"
  },
  {
    "path": "src/shared/km/proto.h",
    "chars": 18405,
    "preview": "/**\n * @file shared/km/proto.h\n *\n * This file is derived from libfuse/include/fuse_kernel.h:\n *     FUSE: Filesystem in"
  },
  {
    "path": "src/shared/km/shared.h",
    "chars": 19271,
    "preview": "/**\n * @file shared/km/shared.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *"
  },
  {
    "path": "src/shared/km/util.c",
    "chars": 3021,
    "preview": "/**\n * @file shared/km/util.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/shared/ku/wslfuse.h",
    "chars": 7673,
    "preview": "/**\n * @file shared/ku/wslfuse.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n "
  },
  {
    "path": "src/winfuse/device.c",
    "chars": 3902,
    "preview": "/**\n * @file winfuse/device.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/winfuse/driver.c",
    "chars": 1070,
    "preview": "/**\n * @file winfuse/driver.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/winfuse/driver.h",
    "chars": 1190,
    "preview": "/**\n * @file winfuse/driver.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/winfuse/driver.inf.in",
    "chars": 360,
    "preview": "[Version]\r\nSignature = \"$WINDOWS NT$\"\r\nClass = Volume\r\nClassGuid = {71a27cdd-812a-11d0-bec7-08002be2092f}\r\nCatalogFile ="
  },
  {
    "path": "src/winfuse/version.rc",
    "chars": 975,
    "preview": "#include <winver.h>\n\n#define STR(x)                          STR_(x)\n#define STR_(x)                         #x\n\nVS_VERS"
  },
  {
    "path": "src/wslfuse/device.c",
    "chars": 22623,
    "preview": "/**\n * @file wslfuse/device.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/wslfuse/driver.c",
    "chars": 1120,
    "preview": "/**\n * @file wslfuse/driver.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/wslfuse/driver.h",
    "chars": 965,
    "preview": "/**\n * @file wslfuse/driver.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n "
  },
  {
    "path": "src/wslfuse/driver.inf.in",
    "chars": 360,
    "preview": "[Version]\r\nSignature = \"$WINDOWS NT$\"\r\nClass = Volume\r\nClassGuid = {71a27cdd-812a-11d0-bec7-08002be2092f}\r\nCatalogFile ="
  },
  {
    "path": "src/wslfuse/version.rc",
    "chars": 975,
    "preview": "#include <winver.h>\n\n#define STR(x)                          STR_(x)\n#define STR_(x)                         #x\n\nVS_VERS"
  },
  {
    "path": "tools/DigiCert High Assurance EV Root CA.crt",
    "chars": 1904,
    "preview": "-----BEGIN CERTIFICATE-----\r\nMIIFOzCCAyOgAwIBAgIKYSBNtAAAAAAAJzANBgkqhkiG9w0BAQUFADB/MQswCQYD\r\nVQQGEwJVUzETMBEGA1UECBMKV"
  },
  {
    "path": "tools/build-libfuse.bat",
    "chars": 1416,
    "preview": "@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"
  },
  {
    "path": "tools/build-lxdk.bat",
    "chars": 569,
    "preview": "@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\ni"
  },
  {
    "path": "tools/build-sample.bat",
    "chars": 1151,
    "preview": "@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"
  },
  {
    "path": "tools/build-winfsp.bat",
    "chars": 873,
    "preview": "@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\ni"
  },
  {
    "path": "tools/build.bat",
    "chars": 4048,
    "preview": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nset MsiName=\"WinFuse - FUSE for the Windows kernel\"\r\nset Cross"
  },
  {
    "path": "tools/debug.bat",
    "chars": 512,
    "preview": "@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\\SOFTW"
  },
  {
    "path": "tools/deploy.bat",
    "chars": 3467,
    "preview": "@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"
  },
  {
    "path": "tools/deploy.ps1",
    "chars": 1115,
    "preview": "param (\n    [Parameter(Mandatory)][string]$Name,\n    [string]$CheckpointName,\n    [Parameter(Mandatory)][string[]]$Files"
  },
  {
    "path": "tools/gensrc/errno.sh",
    "chars": 1176,
    "preview": "#!/bin/bash\n\n# run from Cygwin!\n\ngensrc() {\n    echo \"#if FUSE_ERRNO == 87 /* Windows */\"\n    echo\n    vcvars=\"$(/mnt/c/"
  },
  {
    "path": "tools/gensrc/errno.txt",
    "chars": 2186,
    "preview": "0               STATUS_SUCCESS\nEPERM           STATUS_ACCESS_DENIED\nENOENT          STATUS_OBJECT_NAME_NOT_FOUND\nESRCH  "
  },
  {
    "path": "tools/ioc.c",
    "chars": 648,
    "preview": "///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"
  },
  {
    "path": "tools/license-headers/fix.ps1",
    "chars": 417,
    "preview": "#!/usr/bin/env powershell\n\nparam (\n    [Parameter(Mandatory=$true)][string]$srcfile,\n    [string]$dstfile = $srcfile\n)\n\n"
  },
  {
    "path": "tools/license-headers/header.c",
    "chars": 645,
    "preview": "/*\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 "
  },
  {
    "path": "tools/license-headers/header.cpp",
    "chars": 645,
    "preview": "/*\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 "
  },
  {
    "path": "tools/license-headers/header.h",
    "chars": 645,
    "preview": "/*\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 "
  },
  {
    "path": "tools/nmake-ext-test.bat",
    "chars": 296,
    "preview": "@echo off\r\n\r\nsetlocal\r\nsetlocal EnableDelayedExpansion\r\n\r\nset vswhere=\"%ProgramFiles(x86)%\\Microsoft Visual Studio\\Insta"
  },
  {
    "path": "tools/run-tests.bat",
    "chars": 9617,
    "preview": "@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"
  },
  {
    "path": "tst/lockdly/lockdly.c",
    "chars": 1868,
    "preview": "/*\n * Description:\n *     On debug builds of the WinFuse driver, when the special file \\$LOCKDLY is created/opened\n *   "
  },
  {
    "path": "tst/memfs-fuse3/.gitignore",
    "chars": 84,
    "preview": "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",
    "chars": 3073,
    "preview": "/**\n * @file compat.h\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You ca"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.cpp",
    "chars": 19379,
    "preview": "/**\n * @file memfs-fuse3.cpp\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n *"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.exe.vcxproj",
    "chars": 10815,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" ToolsVersion=\"14.0\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.exe.vcxproj.filters",
    "chars": 614,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbui"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.out.vcxproj",
    "chars": 3619,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project DefaultTargets=\"Build\" ToolsVersion=\"15.0\" xmlns=\"http://schemas.micro"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.out.vcxproj.filters",
    "chars": 540,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbui"
  },
  {
    "path": "tst/memfs-fuse3/memfs-fuse3.sln",
    "chars": 1904,
    "preview": "\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 16\r\nVisualStudioVersion = 16.0.3"
  },
  {
    "path": "tst/winfuse-tests/coro-test.c",
    "chars": 10649,
    "preview": "/**\n * @file coro-test.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You"
  },
  {
    "path": "tst/winfuse-tests/path-test.c",
    "chars": 3686,
    "preview": "/**\n * @file path-test.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * You"
  },
  {
    "path": "tst/winfuse-tests/transact-test.c",
    "chars": 14917,
    "preview": "/**\n * @file transact-test.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n *"
  },
  {
    "path": "tst/winfuse-tests/winfuse-tests.c",
    "chars": 969,
    "preview": "/**\n * @file winfuse-tests.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n *"
  },
  {
    "path": "tst/wslfuse-tests/mount-test.c",
    "chars": 3597,
    "preview": "/**\n * @file mount-test.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n * Yo"
  },
  {
    "path": "tst/wslfuse-tests/wslfuse-tests.c",
    "chars": 868,
    "preview": "/**\n * @file wslfuse-tests.c\n *\n * @copyright 2019-2020 Bill Zissimopoulos\n */\n/*\n * This file is part of WinFuse.\n *\n *"
  }
]

About this extraction

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

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

Copied to clipboard!