From 1d26852a6b34e9bdcaaba48dc140774ca4cc8f7b Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Wed, 2 Sep 2026 16:02:46 +0200 Subject: [PATCH] Initial commit: the gpfile wire format, pinned by two real containers fingerprintd will own the FP6's fingerprint sensor: the rail, the QTEE session, the storage callbacks QTEE makes back into the normal world, and net.reactivated.Fprint so pam_fprintd and the desktop need no changes. None of that runs yet. What is here is the first core module and the machinery around it. Fingerprintd:Sfs is the gpfile listener's frame -- the callback that carries 47 of 66 storage requests during an enrolment. It is parse, reply and root mapping only: no file I/O, no TEE, no allocation of the shared buffer. The daemon shell supplies those, which is what lets every byte-level decision be tested on a dev box with no phone. The module exists mainly to hold one fact. READ answers at req+0x00c and WRITE reads its payload from req+0x110, because the frame is a union: a WRITE still needs its path while the payload is copied out, so it sits past the 256-byte path field, while a READ has consumed the path and packs its reply over it. Conflating them is wrong in both directions with the same symptom -- the container does not round-trip, QTEE's HMAC check fails, and the file is unlinked as tampered on the next session. So the tests do not assert the constants against themselves. They load two real containers off the phone -- one written correctly, one written with the offsets conflated -- and re-derive the bug: the broken one opens with ASCII path text rather than a binary HMAC, that text is the group name from character 8 because the read offset is 8 bytes into the path field, and the real container sits exactly 0x104 further in. Then a write-store-read round trip must be the identity, and the same round trip through a single offset must not be. O_TRUNC gets a static_assert of its own. QTEE writes a container as write(0,4096), write(4096,N), write(0,4096), so truncating on open leaves 4096 bytes where a 258850-byte template belongs; it unlinks a file it means to shorten rather than relying on the opener. Verified by mutation: conflating the offsets, making DataOffset return the read offset for writes, and setting O_TRUNC each fail the suite. --- .gitignore | 11 + LICENSE | 674 ++++++++++++++ README.md | 79 ++ implementations/main.cpp | 50 + interfaces/Fingerprintd-Sfs.cppm | 227 +++++ interfaces/Fingerprintd.cppm | 15 + lint-rules.h | 858 ++++++++++++++++++ project.cpp | 52 ++ tests/Sfs/fixtures/README.md | 20 + tests/Sfs/fixtures/container-correct.bin | Bin 0 -> 1588 bytes tests/Sfs/fixtures/container-wrong-offset.bin | Bin 0 -> 8192 bytes tests/Sfs/main.cpp | 256 ++++++ 12 files changed, 2242 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 implementations/main.cpp create mode 100644 interfaces/Fingerprintd-Sfs.cppm create mode 100644 interfaces/Fingerprintd.cppm create mode 100644 lint-rules.h create mode 100644 project.cpp create mode 100644 tests/Sfs/fixtures/README.md create mode 100644 tests/Sfs/fixtures/container-correct.bin create mode 100644 tests/Sfs/fixtures/container-wrong-offset.bin create mode 100644 tests/Sfs/main.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5f32c3d --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: GPL-3.0-only +# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +bin/ +build/ +fingerprintd-*.tar.gz +# Biometric material and TEE state never enter this repo. Templates are +# QTEE-encrypted SFS containers, but the vendor trustlet is proprietary and +# capture transcripts carry device-unique identifiers. +*.mbn +*.ko +sfs-store/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7552a1a --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# fingerprintd + +Fingerprint daemon for the Fairphone 6 (`milos`, SM7635) on mainline Linux. + +## Why a daemon + +The sensor is a FocalTech FT9391 on a TrustZone-owned SPI bus. `spi@a88000` is +`disabled` in both the mainline and the stock Android device tree, and the pads +are XPU-protected — touching them from the normal world is an instant SError +reboot. Every pixel the sensor produces stays inside the TEE: capture, +preprocessing, the classifier, enrolment and matching all run in the `focal64` +trustlet, which reports a matched finger id and nothing else. A libfprint-style +driver cannot exist on this device. + +So the normal world's job is narrower than usual, and none of it is per-request +work: + +* **Power the sensor.** Rail on gpio29, reset on gpio74, interrupt on gpio75 — + the same division of labour the downstream driver uses. One sensor reset buys + exactly one trustlet init, so whatever powers the sensor must also hold the + session open. +* **Be QTEE's filesystem.** QTEE cannot reach storage. When the trustlet saves + or loads a template it calls back into the normal world through the `gpfile` + (0x7000) and RPMB (0x2000) listeners, and expects them served. QTEE does the + crypto and the anti-rollback; this side moves opaque bytes and performs the + authenticated RPMB transactions against the UFS device. +* **Speak a biometrics API.** The daemon owns `net.reactivated.Fprint`, so + `pam_fprintd`, the Plasma fingerprint KCM and `fprintd-enroll(1)` work + against it unmodified. + +A listener registration is held for as long as the process lives and QTEE's +listener table is global to the boot, so this has to be one long-lived process +rather than a tool spawned per request. + +## Layout + +``` +interfaces/ Fingerprintd{,-Sfs}.cppm the core: pure C++ modules +implementations/main.cpp the daemon shell +tests/ one suite per core module +``` + +`fingerprintd-core` is a static library with no GLib, no libqcomtee and no +system headers. Everything in it is a wire format or a state machine that was +recovered by reverse-engineering, so all of it is pinned by tests that run on a +dev box with no phone, no TEE and no sensor. The daemon shell holds everything +that touches hardware. + +## Build + +```sh +crafter-build # bin/fingerprintd--/fingerprintd +crafter-build test # the unit suites +``` + +Cross-compiling for the phone: + +```sh +crafter-build -- --target=aarch64-alpine-linux-musl \ + --sysroot= --march=armv8-a --mtune=generic +crafter-build test --target=aarch64-alpine-linux-musl +``` + +## Status + +Early. The core is being ported one wire format at a time out of the research +harness that first made the sensor work (`utilities/fpta.c` in the fp6 repo), +each piece landing with tests before the next starts. `Fingerprintd:Sfs` — the +gpfile frame — is done. The daemon itself does not run yet. + +The working reference enrols a finger, keeps it across a reboot, and matches it +with zero false accepts; the port exists to turn that into a service rather +than to rediscover it. + +## Runtime dependencies, not carried here + +The `focal64` trustlet is proprietary and is **not** in this repo. It is +extracted from the device's own stock Android partition on first boot by the +`fp6-vendor-blobs` mechanism, the same way the audio firmware is. diff --git a/implementations/main.cpp b/implementations/main.cpp new file mode 100644 index 0000000..d2cc82f --- /dev/null +++ b/implementations/main.cpp @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// lint-disable-file fixed-width-types +/* +fingerprintd — the daemon shell. + +Nothing here talks to hardware yet. The core (Fingerprintd:Sfs and the modules +that follow it) is being ported from the fp6 harness one wire format at a time, +each landing with tests that run without a phone; this entry point exists so +the executable target builds alongside them and so the version constant that +gates a package publish has a home. + +What this will own, and why it has to be one long-lived process: + + * the sensor rail (gpio29), reset (gpio74) and IRQ (gpio75) — one sensor + reset buys exactly one trustlet init, so whatever powers the sensor must + also hold the session; + * the QTEE session on /dev/tee0: client env, the QSEECOM-compat loader, and + the focal64 trustlet, loaded once; + * the storage listeners QTEE calls back into — gpfile 0x7000 and RPMB + 0x2000 — served from a supplicant thread that must outlive every request, + because QTEE's listener table is global and an id is taken for as long as + the registration is held; + * net.reactivated.Fprint, so pam_fprintd and the desktop need no changes. +*/ +import std; +import Fingerprintd; + +namespace { + // Bumping this is what publishes a package: the registry answers 409 for a + // version it already has, which a build treats as a no-op. + constexpr const char* Version = "0.0.1"; +} + +int main(int argc, char** argv) { + std::span args(argv, static_cast(argc)); + for (std::string_view a : args.subspan(1)) { + if (a == "--version") { + std::println("fingerprintd {}", Version); + return 0; + } + } + + std::println(std::cerr, + "fingerprintd {}: no runtime yet -- the core is still being " + "ported. Run `crafter-build test` for what does work.", + Version); + return 1; +} diff --git a/interfaces/Fingerprintd-Sfs.cppm b/interfaces/Fingerprintd-Sfs.cppm new file mode 100644 index 0000000..4799f15 --- /dev/null +++ b/interfaces/Fingerprintd-Sfs.cppm @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// lint-disable-file fixed-width-types +/* +Fingerprintd:Sfs — the gpfile listener's wire format. + +QTEE cannot reach a filesystem. When the fingerprint trustlet stores or loads a +template it calls back into the normal world through listener 0x7000 ("gpfile", +47 of 66 callbacks in a stock enrolment), hands over a shared buffer holding a +request frame, and expects the frame edited in place with the answer. QTEE does +the crypto and the anti-rollback; this side only moves opaque bytes. + +This module is the frame, and nothing else: parse a request, build a reply, map +a storage root to a directory. No file I/O, no TEE, no allocation of the shared +buffer — the daemon shell supplies those, so every byte-level decision here is +testable without a phone. + +The layout was read out of stock's `smci_gpdispatch` in libdrmfs.so, not +guessed. `op` is packed: `op & 3` is the action, `op >> 2` is the storage root. +*/ + +export module Fingerprintd:Sfs; +import std; + +export namespace fingerprintd::sfs { + + // ---- Frame layout ----------------------------------------------------- + // + // A request frame: + // + // +0x000 u32 op action | root << 2 + // +0x004 char path[256] NUL-terminated, root-relative + // +0x104 i32 offset ... or a SECOND path, for RENAME + // +0x108 u32 length + // +0x110 u8[] payload WRITE data starts here + // + // A reply overwrites the head of the same frame: + // + // +0x004 u32 errno 0 on success + // +0x008 u32 count bytes transferred + // +0x00c u8[] payload READ data starts here + // + inline constexpr std::size_t PathOff = 0x004; + inline constexpr std::size_t ErrnoOff = 0x004; + inline constexpr std::size_t CountOff = 0x008; + inline constexpr std::size_t OffsetOff = 0x104; + inline constexpr std::size_t LengthOff = 0x108; + inline constexpr std::size_t PathMax = 256; + + // THE OFFSET SPLIT. READ and WRITE do not share a data offset, and getting + // this wrong is the single most expensive bug in this project's history. + // + // Both directions go through one worker in stock's dispatcher (0xa008, + // whose x4 argument is the buffer handed to read()/write()), and the two + // call sites are four instructions apart: + // + // READ ops 0/4/8 9c5c: add x4, x19, #0xc -> data at req+0x00c + // WRITE ops 1/5/9 9cd4: add x4, x19, #0x110 -> data at req+0x110 + // + // The frame is a union. A WRITE still needs its path while the payload is + // being copied out, so the payload sits past the 256-byte path field. A + // READ has consumed the path by the time it answers, so its reply packs + // {errno, count, data} over where the path was. + // + // Using one offset for both is wrong in both directions and the symptom is + // identical either way: the container does not round-trip, so QTEE's HMAC + // check fails and it unlinks the file as tampered on the next session. Two + // separate weeks were spent on that failure from whichever side was broken. + inline constexpr std::size_t ReadDataOff = 0x00c; + inline constexpr std::size_t WriteDataOff = 0x110; + + // The distance the payload moves if the two are conflated. It is also the + // fingerprint of the bug on disk: a container written from ReadDataOff + // begins with characters 8-11 of the request path, and the real container + // starts exactly this far in. + inline constexpr std::size_t OffsetSkew = WriteDataOff - ReadDataOff; + static_assert(OffsetSkew == 0x104); + + // Longest transfer accepted in one call. GPF_MAXLEN + WriteDataOff fits + // the 516096-byte shared buffer qseecomd registers for this listener. + inline constexpr std::size_t MaxLen = 0x7d000; + inline constexpr std::size_t SharedBufferSize = 516096; + static_assert(MaxLen + WriteDataOff <= SharedBufferSize); + + // ---- Open flags ------------------------------------------------------- + + // Stock's flags for the WRITE path, as one immediate: + // 9ccc: mov w2, #0x1042 + // 9cec: movk w2, #0x10, lsl #16 -> 0x00101042 + // = O_RDWR | O_CREAT | O_SYNC on Linux, and critically NOT O_TRUNC. + // + // QTEE writes a container as write(0,4096), write(4096,N), write(0,4096). + // Truncating on each open leaves a 4096-byte file where a 258850-byte + // template belongs. QTEE unlinks a file it means to shorten; it never + // relies on the opener to do it. + inline constexpr std::uint32_t StockWriteOpenFlags = 0x00101042; + + // Linux O_TRUNC, spelled out so the guard below is readable without + // pulling into a module that must stay free of system headers. + inline constexpr std::uint32_t LinuxOTrunc = 0x0200; + static_assert((StockWriteOpenFlags & LinuxOTrunc) == 0, + "O_TRUNC truncates multi-chunk containers to 4096 bytes"); + + // ---- Requests --------------------------------------------------------- + + enum class Action { Read, Write, Unlink, Rename }; + + // op 12 carries an otherwise empty frame and is asked first, before any + // path. It is not a stub: the answer stored at +0x04 is LATCHED for the + // whole boot, so QTEE stops asking in every later process of that boot. + // Any experiment on its value needs its own clean boot. + inline constexpr std::uint32_t OpConfigPathInit = 12; + inline constexpr std::uint32_t ConfigPathInitReply = 2; + + struct Request { + std::uint32_t op = 0; + unsigned root = 0; + Action action = Action::Read; + std::string path; + std::string path2; // RENAME destination; empty otherwise + std::int32_t offset = 0; + std::uint32_t length = 0; + }; + + // Storage roots are `op >> 2`. QTEE asks for template containers under + // ROOT 2, which is the persist path — an earlier table that put persist at + // index 1 answered every request against the wrong directory. + inline constexpr std::array RootNames = { + "tzstorage", "misc", "persist-data", "root3", + }; + inline constexpr unsigned PersistRoot = 2; + static_assert(RootNames[PersistRoot] == "persist-data"); + + namespace detail { + inline std::uint32_t LoadU32(std::span f, std::size_t off) { + std::uint32_t v = 0; + for (std::size_t i = 0; i < 4; i++) + v |= static_cast(std::to_integer(f[off + i])) << (8 * i); + return v; + } + inline void StoreU32(std::span f, std::size_t off, std::uint32_t v) { + for (std::size_t i = 0; i < 4; i++) + f[off + i] = static_cast((v >> (8 * i)) & 0xFF); + } + // A NUL-terminated, length-capped field. Stock caps at 256 and the + // frame's next field begins there, so an unterminated path must not + // run into it. + inline std::string Field(std::span f, std::size_t off, std::size_t cap) { + std::string s; + for (std::size_t i = 0; i < cap && off + i < f.size(); i++) { + char c = static_cast(std::to_integer(f[off + i])); + if (c == '\0') break; + s.push_back(c); + } + return s; + } + } + + // Decode a request frame. Returns nothing for an op the dispatcher does + // not define; op 12 decodes with action Read and an empty path, and the + // caller must check for it before treating the request as a file access. + inline std::optional ParseRequest(std::span frame) { + if (frame.size() < LengthOff + 4) + return std::nullopt; + Request r; + r.op = detail::LoadU32(frame, 0); + if (r.op > OpConfigPathInit) + return std::nullopt; + r.root = r.op >> 2; + r.action = static_cast(r.op & 3); + if (r.op == OpConfigPathInit) + return r; + + r.path = detail::Field(frame, PathOff, PathMax); + // +0x104 is an offset for READ/WRITE and a second path for RENAME. + // Decode both; the action says which one is real. + r.path2 = detail::Field(frame, OffsetOff, PathMax); + r.offset = static_cast(detail::LoadU32(frame, OffsetOff)); + r.length = detail::LoadU32(frame, LengthOff); + if (r.length > MaxLen) + r.length = static_cast(MaxLen); + return r; + } + + // Where this action's payload lives in the frame. + inline constexpr std::size_t DataOffset(Action a) { + return a == Action::Write ? WriteDataOff : ReadDataOff; + } + + // How many bytes of payload the frame can still hold after its data + // offset. A transfer is clamped to this, never allowed to run past the + // shared buffer. + inline std::size_t Capacity(std::span frame, Action a) { + std::size_t off = DataOffset(a); + return frame.size() > off ? frame.size() - off : 0; + } + + // ---- Replies ---------------------------------------------------------- + + // Edit the reply into the frame. `err` is a Linux errno (0 = success), + // `count` the bytes transferred. Written after any transfer, never before: + // both words overlay fields the request still needs. + inline void WriteReply(std::span frame, std::uint32_t err, std::uint32_t count) { + detail::StoreU32(frame, ErrnoOff, err); + detail::StoreU32(frame, CountOff, count); + } + + // op 12's whole answer. + inline void WriteConfigPathInitReply(std::span frame, + std::uint32_t value = ConfigPathInitReply) { + detail::StoreU32(frame, 4, value); + } + + // Root-relative path under `base`, e.g. base/persist-data//. + // Rejects anything that could escape the root: QTEE's own names are + // base64-ish and never contain a separator run or a dot segment, so a + // request that does is not one of its. + inline std::optional ResolvePath(std::string_view base, unsigned root, + std::string_view path) { + if (root >= RootNames.size() || path.empty() || path.front() == '/') + return std::nullopt; + if (path.contains("..") || path.contains("//")) + return std::nullopt; + return std::format("{}/{}/{}", base, RootNames[root], path); + } +} diff --git a/interfaces/Fingerprintd.cppm b/interfaces/Fingerprintd.cppm new file mode 100644 index 0000000..964157a --- /dev/null +++ b/interfaces/Fingerprintd.cppm @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +/* +fingerprintd — fingerprint daemon for the Fairphone 6 on mainline Linux. + +The sensor is a FocalTech FT9391 on a TrustZone-owned SPI bus: the normal world +cannot reach it, and raw frames never leave the TEE. All capture, enrolment and +matching happen inside the focal64 trustlet. This daemon owns the sensor rail, +holds the QTEE session open, serves the storage callbacks QTEE makes back into +the normal world, and reports the matched finger id. +*/ + +export module Fingerprintd; +export import :Sfs; diff --git a/lint-rules.h b/lint-rules.h new file mode 100644 index 0000000..12461fd --- /dev/null +++ b/lint-rules.h @@ -0,0 +1,858 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +#pragma once + +// This repo's house-style lint rules. Deliberately project-local — the rule +// set is NOT part of the crafter-build library, so downstream consumers are +// never nudged toward one team's style. Include from project.cpp AFTER +// `import std;` and `import Crafter.Build;` (the header uses both and has no +// includes of its own), then call AddProjectLintRules(cfg). +// +// Report-only rules are registered first so their file:line numbers always +// match the on-disk file; transforms run last because each one sees the +// previous transform's output, which can shift line numbers. +// +// All detection runs on ctx.CommentStripped() — comments and string/char +// literal bodies are blanked to spaces with newlines preserved, so byte +// offsets and line numbers in the stripped text are valid in ctx.content. +// Transforms use that property directly: find in stripped, edit in content. + +namespace ProjectLint { + +inline bool IsCppFile(const Crafter::LintContext& ctx) { + std::string ext = ctx.file.extension().string(); + return ext == ".cpp" || ext == ".cppm" || ext == ".h"; +} + +inline std::vector Lines(std::string_view text) { + std::vector lines; + std::size_t start = 0; + while (start <= text.size()) { + std::size_t end = text.find('\n', start); + if (end == std::string_view::npos) { + if (start < text.size()) lines.push_back(text.substr(start)); + break; + } + lines.push_back(text.substr(start, end - start)); + start = end + 1; + } + return lines; +} + +inline std::string_view Trim(std::string_view s) { + while (!s.empty() && (s.front() == ' ' || s.front() == '\t' || s.front() == '\r')) s.remove_prefix(1); + while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\r')) s.remove_suffix(1); + return s; +} + +inline bool IsWordChar(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; +} + +// Net '(' minus ')' on one stripped line. +inline std::int64_t ParenDelta(std::string_view s) { + std::int64_t d = 0; + for (char c : s) { + if (c == '(') ++d; + if (c == ')') --d; + } + return d; +} + +inline bool IsPascalCase(std::string_view name) { + return !name.empty() && name[0] >= 'A' && name[0] <= 'Z' && !name.contains('_'); +} + +inline bool IsCamelCase(std::string_view name) { + // One trailing underscore is the member-shadowing-a-keyword convention + // (requires_, label_) — allowed. + if (name.ends_with('_')) name.remove_suffix(1); + return !name.empty() && ((name[0] >= 'a' && name[0] <= 'z') || name[0] == '_') && name.find('_', 1) == std::string_view::npos; +} + +// The identifier ending right before position `pos` (exclusive), or empty. +inline std::string_view WordBefore(std::string_view s, std::size_t pos) { + std::size_t end = pos; + while (end > 0 && (s[end - 1] == ' ' || s[end - 1] == '\t')) --end; + std::size_t begin = end; + while (begin > 0 && (IsWordChar(s[begin - 1]) || s[begin - 1] == '~')) --begin; + return s.substr(begin, end - begin); +} + +inline void AddProjectLintRules(Crafter::Configuration& cfg) { + using Crafter::LintContext; + + // ---------------- report-only rules ---------------- + + // License header: SPDX identifier on line 1, copyright on line 2, blank + // line 3. + cfg.AddLintRule("spdx-header", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + if (!ctx.Line(1).starts_with("// SPDX-License-Identifier:")) { + ctx.Report(1, "first line must be // SPDX-License-Identifier: ..."); + } + if (!ctx.Line(2).starts_with("// SPDX-FileCopyrightText:")) { + ctx.Report(2, "second line must be // SPDX-FileCopyrightText: ..."); + } + if (ctx.lines.size() >= 3 && !Trim(ctx.Line(3)).empty()) { + ctx.Report(3, "third line must be blank (separates the license header)"); + } + }); + + cfg.AddLintRule("no-tabs", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + for (std::size_t n = 1; n <= ctx.lines.size(); ++n) { + if (ctx.Line(n).contains('\t')) ctx.Report(n, "tab character (use spaces)"); + } + }); + + // Naming: functions/types PascalCase, variables camelCase, statics and + // namespace-scope globals PascalCase. A line-based scope tracker decides + // whether a declaration sits at namespace scope (global) or inside a + // function/type (local/member). Heuristic by nature — report-only. + cfg.AddLintRule("naming", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + std::vector lines = Lines(ctx.CommentStripped()); + + enum class Scope { Namespace, Type, Function, Other }; + std::vector stack; + auto currentScope = [&]() { return stack.empty() ? Scope::Namespace : stack.back(); }; + + static const std::regex typeDecl(R"(\b(?:class|struct|union)\s+(?:CRAFTER_API\s+)?([A-Za-z_]\w*))"); + static const std::regex enumDecl(R"(\benum\s+(?:class\s+|struct\s+)?([A-Za-z_]\w*))"); + static const std::regex usingDecl(R"(^\s*using\s+([A-Za-z_]\w*)\s*=)"); + static const std::regex varDecl( + R"(^\s*((?:static|constexpr|const|inline|mutable|thread_local|export|CRAFTER_API)\s+)*)" + R"((?:std::)?[A-Za-z_][\w:]*(?:<[^;={]*>)?(?:\s*[&*])*\s+([A-Za-z_]\w*)\s*(=|;|\{))"); + static const std::unordered_set keywords = { + "if", "for", "while", "switch", "catch", "return", "else", "do", "case", "goto", + "new", "delete", "throw", "using", "namespace", "template", "typedef", "friend", + "public", "private", "protected", "class", "struct", "enum", "union", "import", + "module", "export", "break", "continue", "co_return", "co_await", "co_yield", + "sizeof", "alignof", "decltype", "static_assert", "operator", "try", "requires", + }; + + // Cumulative paren depth at the start of each line: declaration and + // function checks only run at depth 0, so wrapped parameter lists and + // continuation lines (`) {` closers) never look like declarations. + std::int64_t parenDepth = 0; + for (std::size_t i = 0; i < lines.size(); ++i) { + std::string_view trimmed = Trim(lines[i]); + std::string lineStr(lines[i]); + std::smatch m; + bool atDepth0 = parenDepth == 0; + parenDepth = std::max(0, parenDepth + ParenDelta(lines[i])); + + if (!trimmed.starts_with('#') && atDepth0) { + // Type / alias names must be PascalCase. + if (std::regex_search(lineStr, m, typeDecl) || std::regex_search(lineStr, m, enumDecl)) { + std::string name = m[1].str(); + if (!keywords.contains(name) && !IsPascalCase(name)) { + ctx.Report(i + 1, std::format("type '{}' should be PascalCase", name)); + } + } + if (std::regex_search(lineStr, m, usingDecl) && !IsPascalCase(m[1].str())) { + ctx.Report(i + 1, std::format("type alias '{}' should be PascalCase", m[1].str())); + } + + // Function definitions: identifier before the first '(' on a + // line that ends where a body opens or closes — a multi-line + // def's trailing '{' or a one-liner's trailing '}'. Statement + // calls with inline lambda arguments look similar + // (`bool x = std::any_of(..., [](T v) { ... });`) but end in + // ';' and/or carry '=' before the name — both excluded. + // Lambdas ("](") and control keywords are skipped; ctors/ + // dtors pass the Pascal check by construction; `main` and + // operators exempt. + std::size_t bodyBrace = trimmed.find('{'); + bool functionShaped = trimmed.ends_with('{') || trimmed.ends_with('}'); + if (functionShaped && currentScope() != Scope::Function && !trimmed.starts_with("return")) { + std::size_t paren = trimmed.find('('); + if (paren != std::string_view::npos && paren > 0 && paren < bodyBrace) { + std::string_view name = WordBefore(trimmed, paren); + char before = trimmed[paren - 1]; + bool looksLikeDef = !name.empty() && IsWordChar(before) + && !keywords.contains(name) && name != "main" + && !name.starts_with('~'); + // Require a type token before the name (or a + // qualified Class::Name), with no '=' in front — + // plain calls and initializations don't match. + if (looksLikeDef) { + std::size_t nameStart = trimmed.rfind(name, paren); + std::string_view prefix = Trim(trimmed.substr(0, nameStart)); + looksLikeDef = !prefix.empty() && !prefix.contains('=') + && (IsWordChar(prefix.back()) || prefix.back() == '>' + || prefix.back() == '*' || prefix.back() == '&' + || prefix.ends_with("::")); + } + if (looksLikeDef && !IsPascalCase(name)) { + ctx.Report(i + 1, std::format("function '{}' should be PascalCase", name)); + } + } + } + + // Variable declarations: camelCase locally, PascalCase for + // statics and namespace-scope globals. + if (std::regex_search(lineStr, m, varDecl)) { + std::string name = m[2].str(); + std::string_view typeToken = Trim(std::string_view(lineStr).substr(0, static_cast(m.position(2)))); + std::string_view firstWord = typeToken.substr(0, typeToken.find_first_of(" \t<")); + if (!keywords.contains(firstWord) && !keywords.contains(name)) { + bool isStatic = lineStr.contains("static "); + // constexpr variables are compile-time constants — + // constant naming (PascalCase) like statics/globals. + bool isConstexpr = lineStr.contains("constexpr "); + bool global = currentScope() == Scope::Namespace; + if ((isStatic || global || isConstexpr) && !IsPascalCase(name)) { + ctx.Report(i + 1, std::format("{} '{}' should be PascalCase", + isStatic ? "static variable" + : isConstexpr ? "constexpr constant" + : "global variable", name)); + } else if (!isStatic && !global && !isConstexpr && !IsCamelCase(name)) { + ctx.Report(i + 1, std::format("variable '{}' should be camelCase", name)); + } + } + } + } + + // Scope tracking: classify each '{' opened on this line; pop on '}'. + for (std::size_t c = 0; c < lines[i].size(); ++c) { + if (lines[i][c] == '{') { + Scope kind = Scope::Other; + std::string_view upTo = Trim(lines[i].substr(0, c)); + if (trimmed.starts_with("namespace") || upTo.contains("namespace ")) { + kind = Scope::Namespace; + } else if (std::regex_search(lineStr, typeDecl) || std::regex_search(lineStr, enumDecl)) { + kind = Scope::Type; + } else if (upTo.ends_with(')') || upTo.ends_with("const") || upTo.ends_with("noexcept") + || upTo.ends_with("->") || trimmed.starts_with("extern")) { + kind = Scope::Function; // function/lambda/control body — all non-global + } + stack.push_back(kind); + } else if (lines[i][c] == '}') { + if (!stack.empty()) stack.pop_back(); + } + } + } + }); + + cfg.AddLintRule("enum-class", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + std::vector lines = Lines(ctx.CommentStripped()); + static const std::regex plainEnum(R"(\benum\s+(?!class\b|struct\b)[A-Za-z_])"); + for (std::size_t i = 0; i < lines.size(); ++i) { + std::string lineStr(lines[i]); + if (std::regex_search(lineStr, plainEnum)) { + ctx.Report(i + 1, "use enum class instead of plain enum"); + } + } + }); + + cfg.AddLintRule("no-iostream-print", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + std::vector lines = Lines(ctx.CommentStripped()); + for (std::size_t i = 0; i < lines.size(); ++i) { + if (lines[i].contains("std::cout")) { + ctx.Report(i + 1, "use std::println instead of std::cout"); + } else if (lines[i].contains("std::cerr") && lines[i].contains("<<")) { + ctx.Report(i + 1, "use std::println(std::cerr, ...) instead of streaming to std::cerr"); + } + } + }); + + // Prefer std::string / std::string_view over char*. OS interop stays: + // getenv returns char*, argv is char**, extern "C" prototypes mirror C. + cfg.AddLintRule("no-char-pointer", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + std::vector lines = Lines(ctx.CommentStripped()); + static const std::regex charPtr(R"(\bchar\s*\*)"); + for (std::size_t i = 0; i < lines.size(); ++i) { + std::string lineStr(lines[i]); + // C-interop stays char*: argv, getenv/setenv, dlerror, C APIs fed + // by c_str()/data(), binary IO reinterpret_casts, extern "C" + // prototypes. (extern " matches with the literal body blanked.) + if (lineStr.contains("argv") || lineStr.contains("getenv") || lineStr.contains("setenv") + || lineStr.contains("dlerror") || lineStr.contains("c_str") || lineStr.contains(".data(") + || lineStr.contains("reinterpret_cast") || lineStr.contains("extern \"")) continue; + if (std::regex_search(lineStr, charPtr)) { + ctx.Report(i + 1, "prefer std::string / std::string_view over char*"); + } + } + }); + + // String building via `+` with a literal operand → std::format. Plain + // `a += b` accumulation (builder pattern) stays legal. Single-line chains + // of simple operands (identifier / member / call chains, parenthesized + // groups, literals) are REWRITTEN automatically; anything the operand + // scanner can't prove safe — raw-string lines, ternaries, mixed + // operators, multi-line expressions — is reported for a human instead. + cfg.AddLintRule("format-concat", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + const std::string& code = ctx.CommentStripped(); + std::vector stripped = Lines(code); + + // Walk one operand leftwards from `from` (exclusive). Returns the + // operand's begin, or npos when the shape isn't a simple postfix + // chain (then the whole chain bails to a report). + auto operandLeft = [](std::string_view s, std::size_t from) -> std::size_t { + std::size_t i = from; + while (i > 0 && (s[i - 1] == ' ' || s[i - 1] == '\t')) --i; + bool any = false; + for (;;) { + if (i == 0) break; + char c = s[i - 1]; + if (c == ')' || c == ']') { + char open = c == ')' ? '(' : '['; + std::size_t depth = 0; + do { + --i; + if (s[i] == c) ++depth; + if (s[i] == open) --depth; + if (depth == 0) break; + } while (i > 0); + if (depth != 0) return std::string_view::npos; + any = true; + // A group directly preceded by an identifier (or another + // group) is a call/index postfix — keep consuming the + // callee: `path.string()` is ONE operand, not `()`. + if (i > 0 && (IsWordChar(s[i - 1]) || s[i - 1] == ')' || s[i - 1] == ']')) continue; + } else if (c == '"') { + --i; // closing quote; interior is blanked, find the opener + while (i > 0 && s[i - 1] != '"') --i; + if (i == 0) return std::string_view::npos; + --i; + any = true; + } else if (IsWordChar(c)) { + while (i > 0 && IsWordChar(s[i - 1])) --i; + any = true; + } else if (c == '.' && any) { + --i; + continue; + } else if (c == ':' && i > 1 && s[i - 2] == ':' && any) { + i -= 2; + continue; + } else if (c == '>' && i > 1 && s[i - 2] == '-' && any) { + i -= 2; + continue; + } else { + break; + } + // After a primary, only connectors continue the operand. + if (i > 0 && (s[i - 1] == '.' || (s[i - 1] == ':' && i > 1 && s[i - 2] == ':') + || (s[i - 1] == '>' && i > 1 && s[i - 2] == '-'))) continue; + break; + } + if (!any) return std::string_view::npos; + // A unary operator, ternary, or other-precedence operator in + // front means expression structure we don't reason about — bail. + std::size_t b = i; + while (b > 0 && (s[b - 1] == ' ' || s[b - 1] == '\t')) --b; + if (b > 0 && std::string_view("!*&~-?:<>/%^|").contains(s[b - 1])) return std::string_view::npos; + return i; + }; + + // Walk one operand rightwards from `from` (inclusive). Returns one + // past the operand's end, or npos on bail. + auto operandRight = [](std::string_view s, std::size_t from) -> std::size_t { + std::size_t i = from; + while (i < s.size() && (s[i] == ' ' || s[i] == '\t')) ++i; + bool any = false; + for (;;) { + if (i >= s.size()) break; + char c = s[i]; + if (c == '(' || c == '[') { + char close = c == '(' ? ')' : ']'; + std::size_t depth = 0; + while (i < s.size()) { + if (s[i] == c) ++depth; + if (s[i] == close && --depth == 0) { ++i; break; } + ++i; + } + if (depth != 0) return std::string_view::npos; + any = true; + } else if (c == '"') { + ++i; + while (i < s.size() && s[i] != '"') ++i; + if (i >= s.size()) return std::string_view::npos; + ++i; + any = true; + } else if (IsWordChar(c)) { + while (i < s.size() && IsWordChar(s[i])) ++i; + any = true; + } else if (any && c == '.') { + ++i; + continue; + } else if (any && c == ':' && i + 1 < s.size() && s[i + 1] == ':') { + i += 2; + continue; + } else if (any && c == '-' && i + 1 < s.size() && s[i + 1] == '>') { + i += 2; + continue; + } else { + break; + } + if (i < s.size() && (s[i] == '(' || s[i] == '[' || s[i] == '.' + || (s[i] == ':' && i + 1 < s.size() && s[i + 1] == ':') + || (s[i] == '-' && i + 1 < s.size() && s[i + 1] == '>'))) continue; + break; + } + return any ? i : std::string_view::npos; + }; + + struct Edit { std::size_t begin; std::size_t end; std::string replacement; }; + std::vector edits; // offsets into ctx.content + std::size_t lineStart = 0; + for (std::size_t li = 0; li < stripped.size(); ++li) { + std::string_view line = stripped[li]; + std::size_t lineOff = lineStart; + lineStart += line.size() + 1; + std::string_view trimmed = Trim(line); + if (trimmed.starts_with('#')) continue; + // Raw strings defeat the comment stripper's quote tracking; any + // literal-+ pattern on such a line is a manual fix. + bool hasRaw = std::string_view(ctx.content).substr(lineOff, line.size()).contains("R\""); + + std::size_t searchFrom = 0; + while (searchFrom < line.size()) { + // A candidate `+` that isn't ++ / += and touches a literal. + std::size_t plus = line.find('+', searchFrom); + if (plus == std::string_view::npos) break; + searchFrom = plus + 1; + if (plus + 1 < line.size() && (line[plus + 1] == '+' || line[plus + 1] == '=')) { ++searchFrom; continue; } + if (plus > 0 && line[plus - 1] == '+') continue; + std::size_t leftEnd = plus; + while (leftEnd > 0 && (line[leftEnd - 1] == ' ' || line[leftEnd - 1] == '\t')) --leftEnd; + std::size_t rightBegin = plus + 1; + while (rightBegin < line.size() && (line[rightBegin] == ' ' || line[rightBegin] == '\t')) ++rightBegin; + bool literalAdjacent = (leftEnd > 0 && line[leftEnd - 1] == '"') + || (rightBegin < line.size() && line[rightBegin] == '"'); + if (!literalAdjacent) continue; + if (hasRaw) { + ctx.Report(li + 1, "use std::format instead of string concatenation with + (raw-string line, fix manually)"); + break; + } + + // Expand to the full chain: operands joined by `+`. + std::size_t chainBegin = operandLeft(line, plus); + std::size_t chainEnd = operandRight(line, plus + 1); + bool bail = chainBegin == std::string_view::npos || chainEnd == std::string_view::npos; + while (!bail) { + std::size_t b = chainBegin; + while (b > 0 && (line[b - 1] == ' ' || line[b - 1] == '\t')) --b; + if (b > 0 && line[b - 1] == '+' && !(b > 1 && line[b - 2] == '+')) { + std::size_t prev = operandLeft(line, b - 1); + if (prev == std::string_view::npos) { bail = true; break; } + chainBegin = prev; + } else break; + } + while (!bail) { + std::size_t e = chainEnd; + while (e < line.size() && (line[e] == ' ' || line[e] == '\t')) ++e; + if (e < line.size() && line[e] == '+' && !(e + 1 < line.size() && (line[e + 1] == '+' || line[e + 1] == '='))) { + std::size_t next = operandRight(line, e + 1); + if (next == std::string_view::npos) { bail = true; break; } + chainEnd = next; + } else break; + } + if (bail) { + ctx.Report(li + 1, "use std::format instead of string concatenation with + (not auto-fixable)"); + break; + } + + // Split the chain at depth-0 '+' into parts; literals feed the + // format string, everything else becomes an argument. + std::string_view chain = line.substr(chainBegin, chainEnd - chainBegin); + std::string_view rawChain = std::string_view(ctx.content).substr(lineOff + chainBegin, chainEnd - chainBegin); + std::string fmt; + std::vector args; + std::size_t partBegin = 0; + std::int64_t depth = 0; + bool inLit = false; + for (std::size_t p = 0; p <= chain.size(); ++p) { + if (p < chain.size()) { + char c = chain[p]; + if (c == '"') inLit = !inLit; + if (inLit) continue; + if (c == '(' || c == '[') ++depth; + if (c == ')' || c == ']') --depth; + if (!(c == '+' && depth == 0)) continue; + } + std::string_view part = Trim(chain.substr(partBegin, p - partBegin)); + std::string_view rawPart = Trim(rawChain.substr(partBegin, p - partBegin)); + if (part.starts_with('"') && part.ends_with('"') && part.size() >= 2 + && std::count(part.begin(), part.end(), '"') == 2) { + for (char c : rawPart.substr(1, rawPart.size() - 2)) { + fmt += c; + if (c == '{') fmt += '{'; + if (c == '}') fmt += '}'; + } + } else if (part.contains('"') && part.contains('+')) { + bail = true; // nested concat inside an operand — human territory + break; + } else { + fmt += "{}"; + args.push_back(rawPart); + } + partBegin = p + 1; + } + if (bail || args.empty()) { + ctx.Report(li + 1, "use std::format instead of string concatenation with + (not auto-fixable)"); + break; + } + std::string replacement = std::format("std::format(\"{}\"", fmt); + for (std::string_view a : args) replacement += std::format(", {}", a); + replacement += ")"; + edits.push_back({lineOff + chainBegin, lineOff + chainEnd, std::move(replacement)}); + searchFrom = chainEnd; + } + } + if (edits.empty()) return; + std::string out = ctx.content; + std::sort(edits.begin(), edits.end(), [](const Edit& a, const Edit& b) { return a.begin > b.begin; }); + for (const Edit& e : edits) out.replace(e.begin, e.end - e.begin, e.replacement); + ctx.SetContent(std::move(out)); + }); + + // ---------------- transforms (auto-fixed by `crafter-build format`) ---------------- + + // short/int/long → fixed-width types. Lines mentioning main/argc/argv or + // extern "C" keep their C-conventional ints. + cfg.AddLintRule("fixed-width-types", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + const std::string& code = ctx.CommentStripped(); + struct Rep { std::size_t pos; std::size_t len; std::string to; }; + std::vector reps; + // Builtin integer type specifiers combine in any order (`unsigned + // long`, `long unsigned int`, ...), so match whole RUNS of these + // keywords and classify the run, rather than the words one by one. + static const std::unordered_set IntWords = { + "unsigned", "signed", "short", "long", "int", "char", + }; + std::size_t lineStart = 0; + while (lineStart <= code.size()) { + std::size_t lineEnd = code.find('\n', lineStart); + if (lineEnd == std::string::npos) lineEnd = code.size(); + std::string_view line(code.data() + lineStart, lineEnd - lineStart); + // `int main` / argc / argv keep their C-conventional type; so do + // extern "C" prototypes (the literal body is blanked in the + // stripped text, so match `extern "`). + bool exempt = line.contains("int main") || line.contains("argc") || line.contains("argv") + || line.contains("extern \""); + std::size_t pos = 0; + while (!exempt && pos < line.size()) { + if (!IsWordChar(line[pos])) { ++pos; continue; } + std::size_t wordEnd = pos; + while (wordEnd < line.size() && IsWordChar(line[wordEnd])) ++wordEnd; + if (!IntWords.contains(line.substr(pos, wordEnd - pos))) { pos = wordEnd; continue; } + + // Extend the run over consecutive specifier keywords. + std::size_t runBegin = pos; + std::size_t runEnd = wordEnd; + bool hasUnsigned = false; + bool hasSigned = false; + bool hasShort = false; + bool hasChar = false; + bool hasLong = false; + std::string_view nextWord; + for (;;) { + std::string_view word = line.substr(pos, wordEnd - pos); + if (word == "unsigned") hasUnsigned = true; + else if (word == "signed") hasSigned = true; + else if (word == "short") hasShort = true; + else if (word == "char") hasChar = true; + else if (word == "long") hasLong = true; + runEnd = wordEnd; + pos = wordEnd; + while (pos < line.size() && (line[pos] == ' ' || line[pos] == '\t')) ++pos; + wordEnd = pos; + while (wordEnd < line.size() && IsWordChar(line[wordEnd])) ++wordEnd; + nextWord = line.substr(pos, wordEnd - pos); + if (!IntWords.contains(nextWord)) break; + } + pos = runEnd; + + // Bare `char` is text, not an integer — only signed/unsigned + // char is byte arithmetic. `long double` is a floating type. + if (hasChar && !hasUnsigned && !hasSigned) continue; + if (nextWord == "double") continue; + + std::string_view width = hasChar ? "8" : hasShort ? "16" : hasLong ? "64" : "32"; + reps.push_back({lineStart + runBegin, runEnd - runBegin, + std::format("std::{}int{}_t", hasUnsigned ? "u" : "", width)}); + } + lineStart = lineEnd + 1; + } + if (reps.empty()) return; + std::string out = ctx.content; + std::sort(reps.begin(), reps.end(), [](const Rep& a, const Rep& b) { return a.pos > b.pos; }); + for (const Rep& r : reps) out.replace(r.pos, r.len, r.to); + ctx.SetContent(std::move(out)); + }); + + // One declaration per statement. Auto-splits the simple initialized form + // `Type a = x, b = y;`; anything with pointers/references, parens, or + // templates in the declarators is only reported (splitting `int* a, b;` + // would change b's type). + cfg.AddLintRule("single-declaration", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + std::vector stripped = Lines(ctx.CommentStripped()); + // The declarator char class excludes quotes: string-literal bodies are + // blanked in the stripped text, so reconstructing them would corrupt + // the file — those lines are left alone. + static const std::regex simpleMulti( + R"(^(\s*)((?:std::)?[A-Za-z_][\w:]*)\s+([A-Za-z_]\w*\s*=\s*[^,;()<>*&"]+(?:,\s*[A-Za-z_]\w*\s*=\s*[^,;()<>*&"]+)+);\s*$)"); + std::string out; + bool changed = false; + for (std::size_t i = 0; i < stripped.size(); ++i) { + std::string lineStr(stripped[i]); + std::smatch m; + std::string_view raw = i + 1 <= ctx.lines.size() ? ctx.Line(i + 1) : std::string_view{}; + if (!raw.contains("//") && !ctx.Suppressed("single-declaration", i + 1) + && std::regex_match(lineStr, m, simpleMulti)) { + std::string indent = m[1].str(), type = m[2].str(), decls = m[3].str(); + std::size_t start = 0; + bool first = true; + while (start < decls.size()) { + std::size_t comma = decls.find(',', start); + std::string_view d = Trim(std::string_view(decls).substr(start, comma == std::string::npos ? std::string::npos : comma - start)); + if (!first) out += '\n'; + out += std::format("{}{} {};", indent, type, d); + first = false; + if (comma == std::string::npos) break; + start = comma + 1; + } + changed = true; + } else { + out += raw; + } + if (i + 1 < stripped.size() || ctx.content.ends_with('\n')) out += '\n'; + } + if (changed) ctx.SetContent(std::move(out)); + }); + + // K&R braces: `{` on its own line after a `)`/else/do/try header joins + // onto the header line. Standalone scope blocks (previous line ends with + // `;`, `{`, a comment, …) are intentional and stay. + cfg.AddLintRule("brace-style", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + std::vector stripped = Lines(ctx.CommentStripped()); + std::vector outLines; + outLines.reserve(ctx.lines.size()); + bool changed = false; + for (std::size_t i = 0; i < ctx.lines.size(); ++i) { + std::string_view trimmed = Trim(stripped[i]); + if (trimmed == "{" && !outLines.empty()) { + std::string_view prevTrim = i > 0 ? Trim(stripped[i - 1]) : std::string_view{}; + bool headerBefore = prevTrim.ends_with(')') || prevTrim == "else" || prevTrim == "do" || prevTrim == "try"; + bool hasComment = ctx.Line(i + 1).contains("//") || (i > 0 && ctx.Line(i).contains("//")); + bool suppressed = ctx.Suppressed("brace-style", i) || ctx.Suppressed("brace-style", i + 1); + if (headerBefore && !hasComment && !suppressed) { + std::string& prev = outLines.back(); + while (!prev.empty() && (prev.back() == ' ' || prev.back() == '\t')) prev.pop_back(); + prev += " {"; + changed = true; + continue; + } + } + outLines.emplace_back(ctx.Line(i + 1)); + } + if (!changed) return; + std::string out; + for (std::size_t i = 0; i < outLines.size(); ++i) { + out += outLines[i]; + if (i + 1 < outLines.size() || ctx.content.ends_with('\n')) out += '\n'; + } + ctx.SetContent(std::move(out)); + }); + + // Single-statement if bodies join onto the if line: `if (x)\n y;` → + // `if (x) y;` — when the condition's parens balance on one line, the body + // is one `;`-terminated statement, neither line carries a comment, and + // the joined line stays ≤ 250 columns. + cfg.AddLintRule("if-single-line", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + std::vector stripped = Lines(ctx.CommentStripped()); + static const std::regex ifHeader(R"(^\s*(?:\}?\s*else\s+)?if\s*\(.*\)\s*$)"); + std::vector outLines; + bool changed = false; + for (std::size_t i = 0; i < ctx.lines.size(); ++i) { + std::string lineStr(stripped[i]); + if (i + 1 < ctx.lines.size() && std::regex_match(lineStr, ifHeader) && ParenDelta(stripped[i]) == 0) { + std::string_view body = Trim(stripped[i + 1]); + bool joinable = !body.empty() && body != "{" && !body.starts_with("if") && body.ends_with(';') + && !ctx.Line(i + 1).contains("//") && !ctx.Line(i + 2).contains("//") + && !ctx.Suppressed("if-single-line", i + 1) && !ctx.Suppressed("if-single-line", i + 2); + std::string joined = std::string(ctx.Line(i + 1)); + while (!joined.empty() && (joined.back() == ' ' || joined.back() == '\t')) joined.pop_back(); + joined += " "; + joined += Trim(ctx.Line(i + 2)); + if (joinable && joined.size() <= 250) { + outLines.push_back(std::move(joined)); + ++i; // consume the body line + changed = true; + continue; + } + } + outLines.emplace_back(ctx.Line(i + 1)); + } + if (!changed) return; + std::string out; + for (std::size_t i = 0; i < outLines.size(); ++i) { + out += outLines[i]; + if (i + 1 < outLines.size() || ctx.content.ends_with('\n')) out += '\n'; + } + ctx.SetContent(std::move(out)); + }); + + // Wrapped call arguments join back onto one line when the whole + // expression fits in 250 columns. Lambda bodies (lines ending `{`), + // comments, raw strings, and preprocessor lines are left alone. + // Operator-style continuations (next line starts with && / || / |) join + // under the same length limit. + cfg.AddLintRule("wrap-join", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + // Fixpoint loop: a join can enable another (joining an inner paren + // wrap balances the line an operator continuation hangs off), so one + // pass is not idempotent. Iterate until a pass changes nothing; the + // cap is a safety net — joins strictly reduce the line count, so + // termination is guaranteed anyway. + for (std::int32_t pass = 0; pass < 16; ++pass) { + std::vector stripped = Lines(ctx.CommentStripped()); + std::vector outLines; + bool changed = false; + for (std::size_t i = 0; i < ctx.lines.size(); ++i) { + std::string_view trimmed = Trim(stripped[i]); + std::int64_t delta = ParenDelta(stripped[i]); + bool candidate = delta > 0 && !trimmed.empty() && !trimmed.starts_with('#') + && !trimmed.ends_with('{') && !ctx.Line(i + 1).contains("//") && !ctx.Line(i + 1).contains("R\""); + if (candidate) { + std::string joined(ctx.Line(i + 1)); + std::size_t j = i + 1; + bool ok = true; + while (delta > 0 && j < ctx.lines.size() && j - i <= 4) { + std::string_view next = Trim(stripped[j]); + // A `{`-ending line is fine when it closes the expression + // (a control header's `) {`); mid-expression it means a + // lambda body starts — leave those wrapped. + bool closes = delta + ParenDelta(stripped[j]) <= 0; + if (next.empty() || (next.ends_with('{') && !closes) + || ctx.Line(j + 1).contains("//") || ctx.Line(j + 1).contains("R\"")) { + ok = false; + break; + } + while (!joined.empty() && (joined.back() == ' ' || joined.back() == '\t')) joined.pop_back(); + std::string_view fragment = Trim(ctx.Line(j + 1)); + // No separator right after an opening paren or before a + // closing one — joining must not manufacture `( x` / `x )`. + if (!joined.ends_with('(') && !fragment.starts_with(')') && !fragment.starts_with(',')) joined += " "; + joined += fragment; + delta += ParenDelta(stripped[j]); + ++j; + } + for (std::size_t l = i + 1; ok && l <= j; ++l) ok = !ctx.Suppressed("wrap-join", l); + if (ok && delta <= 0 && joined.size() <= 250) { + outLines.push_back(std::move(joined)); + i = j - 1; // consumed through line j-1 (0-based i) + changed = true; + continue; + } + } else if (delta == 0 && i + 1 < ctx.lines.size() && !trimmed.starts_with('#') + && !ctx.Line(i + 1).contains("//") && !ctx.Line(i + 1).contains("R\"")) { + auto isOpStart = [](std::string_view s) { + return s.starts_with("&&") || s.starts_with("||") || s.starts_with("| "); + }; + // Operator-style continuation chain (`a\n && b\n && c`). + // Joined when the WHOLE chain stays within 250 columns — + // longer conditions legitimately wrap. Same mechanics as the + // paren join: chain lines must be comment-free, raw-string + // free, and paren-balanced. + if (isOpStart(Trim(stripped[i + 1])) && !isOpStart(trimmed)) { + std::string joined(ctx.Line(i + 1)); + std::size_t j = i + 1; + bool ok = true; + while (j < ctx.lines.size() && isOpStart(Trim(stripped[j]))) { + if (ParenDelta(stripped[j]) != 0 || ctx.Line(j + 1).contains("//") || ctx.Line(j + 1).contains("R\"")) { + ok = false; + break; + } + while (!joined.empty() && (joined.back() == ' ' || joined.back() == '\t')) joined.pop_back(); + joined += " "; + joined += Trim(ctx.Line(j + 1)); + ++j; + } + for (std::size_t l = i + 1; ok && l <= j; ++l) ok = !ctx.Suppressed("wrap-join", l); + if (ok && joined.size() <= 250) { + outLines.push_back(std::move(joined)); + i = j - 1; // consumed the chain + changed = true; + continue; + } + } + } + outLines.emplace_back(ctx.Line(i + 1)); + } + if (!changed) return; + std::string out; + for (std::size_t i = 0; i < outLines.size(); ++i) { + out += outLines[i]; + if (i + 1 < outLines.size() || ctx.content.ends_with('\n')) out += '\n'; + } + ctx.SetContent(std::move(out)); + } + }); + + // No space padding inside parens: `( x` / `x )` → `(x` / `x)`. Only + // intra-line (a line legitimately ends with '(' when a call wraps); + // string/comment interiors are excluded via the stripped text. + cfg.AddLintRule("paren-spacing", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + const std::string& code = ctx.CommentStripped(); + std::vector> cuts; // [begin, end) spans of spaces to delete + for (std::size_t i = 0; i < code.size(); ++i) { + if (code[i] == '(' ) { + std::size_t j = i + 1; + while (j < code.size() && code[j] == ' ') ++j; + if (j > i + 1 && j < code.size() && code[j] != '\n' && code[j] != '\r') cuts.push_back({i + 1, j}); + } else if (code[i] == ')') { + std::size_t j = i; + while (j > 0 && code[j - 1] == ' ') --j; + // Only single-space padding: multi-space runs are usually + // deliberate alignment columns. + if (j == i - 1 && j > 0 && code[j - 1] != '\n' && code[j - 1] != ',') cuts.push_back({j, i}); + } + } + if (cuts.empty()) return; + std::string out = ctx.content; + for (auto it = cuts.rbegin(); it != cuts.rend(); ++it) out.erase(it->first, it->second - it->first); + ctx.SetContent(std::move(out)); + }); + + cfg.AddLintRule("trim-trailing-ws", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + std::string out; + out.reserve(ctx.content.size()); + for (std::size_t n = 1; n <= ctx.lines.size(); ++n) { + std::string_view line = ctx.Line(n); + // Byte fidelity on CRLF files: peel the \r, trim, put it back. + bool crlf = line.ends_with('\r'); + if (crlf) line.remove_suffix(1); + while (line.ends_with(' ') || line.ends_with('\t')) line.remove_suffix(1); + out += line; + if (crlf) out += '\r'; + // The last line only had a newline if the file ended with one — + // preserve that byte exactly so this rule doesn't shadow + // final-newline. + if (n < ctx.lines.size() || ctx.content.ends_with('\n')) out += '\n'; + } + ctx.SetContent(std::move(out)); + }); + + cfg.AddLintRule("final-newline", [](LintContext& ctx) { + if (!IsCppFile(ctx)) return; + if (!ctx.content.empty() && !ctx.content.ends_with('\n')) { + ctx.SetContent(ctx.content + '\n'); + } + }); +} + +} // namespace ProjectLint diff --git a/project.cpp b/project.cpp new file mode 100644 index 0000000..1759647 --- /dev/null +++ b/project.cpp @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// lint-disable-file no-char-pointer +import std; +import Crafter.Build; +#include "lint-rules.h" +namespace fs = std::filesystem; +using namespace Crafter; + +extern "C" Configuration CrafterBuildProject(std::span args) { + // fingerprintd-core — the wire formats and state machines as a static + // library of pure C++ modules. Deliberately free of GLib, libqcomtee and + // every system header: the byte-level decisions in here were the whole + // cost of this project, so they are pinned by tests that run on a dev box + // with no phone, no TEE and no sensor. + static auto Core = std::make_unique(); + Core->path = "./"; + Core->name = "fingerprintd-core"; + Core->outputName = "fingerprintd-core"; + ApplyStandardArgs(*Core, args); + Core->type = ConfigurationType::LibraryStatic; + { + std::array ifaces = { + "interfaces/Fingerprintd", + "interfaces/Fingerprintd-Sfs", + }; + std::array impls = {}; + Core->GetInterfacesAndImplementations(ifaces, impls); + } + + // fingerprintd — the daemon: sensor rail, QTEE session, the gpfile and + // RPMB listeners, and the bus surface, wrapped around the core. + Configuration cfg; + cfg.path = "./"; + cfg.name = "fingerprintd"; + cfg.outputName = "fingerprintd"; + ApplyStandardArgs(cfg, args); + cfg.type = ConfigurationType::Executable; + cfg.dependencies = { Core.get() }; + { + std::array ifaces = {}; + std::array impls = { "implementations/main" }; + cfg.GetInterfacesAndImplementations(ifaces, impls); + } + + cfg.AddTest("Sfs").Dependencies({ Core.get() }); + + ProjectLint::AddProjectLintRules(cfg); + + return cfg; +} diff --git a/tests/Sfs/fixtures/README.md b/tests/Sfs/fixtures/README.md new file mode 100644 index 0000000..1d6121c --- /dev/null +++ b/tests/Sfs/fixtures/README.md @@ -0,0 +1,20 @@ +# Recorded SFS containers + +Two real containers, taken off the Fairphone 6 dev phone's persist partition +and carried here so the offset split is pinned by bytes that actually failed +rather than by bytes we invented. + +| file | provenance | +|---|---| +| `container-correct.bin` | 1588 B. A well-formed QTEE index container: 32-byte HMAC, NUL-terminated group name at +0x20, `u32` version, `u32` entry count, then `{u32; name}` entries. | +| `container-wrong-offset.bin` | 8192 B. The same container written while READ and WRITE shared a data offset. It begins with *path text* — characters 8 onward of the group path — and the real container starts 0x104 bytes in. | + +Originals and their full analysis live in the fp6 journal as +`journal/fingerprint/captures/2026-08-30-vtable-master-correct-structure.bin` +and `…-container-written-at-the-wrong-offset.bin`. + +**These hold no biometric material.** A fingerprint template is a separate +258850-byte container; these two are the index that names them. Their contents +are a QTEE-encrypted blob plus opaque device-derived names — but they *are* +from a specific device, so treat publishing them as a deliberate choice rather +than an incidental one. diff --git a/tests/Sfs/fixtures/container-correct.bin b/tests/Sfs/fixtures/container-correct.bin new file mode 100644 index 0000000000000000000000000000000000000000..c7fc9fab8487e393ec4dade68727cc2d210da680 GIT binary patch literal 1588 zcmex!=`J5ff65u=Q{F5pduqFPm~_px$(;5*;f`95?Y8-yL7tK3j@r3_xyG)JCT_*f zp}E;!`36arDQ=;W0Y;HgCIO}yxxSfE>8XzKjyWX^-HZ$jEDQ_`L4moI8U87e7M10d ziSD75PP!qU3=KfZfF#E-GjLfo7%M#y;$}(+ThGw9IYj$vGnMp`?WS)VuQAUKP ypHr?eLmN=SD9(HjfVc^>DL6YiO0xf@!pm+B`2XH;{++-Kg8LQqR**6J%0b%~LvIA` z1sn^k_$qDHC_Ya_@RO1g902ft=Fehm;AFt!Vq$A-=cs3F!otd8YX9F$rlxvdO^lo! zEu7r+ob0SjY`^M#Vr4e8uw^zhu=+>s)8E7Yc?00(<;AB90Lb|#`cLrh`~SW1@6BZ`UxL(*YJ<(;mT4kzVTrl8E^~fp z%(`dtv+hD?Lw;{OW&K`xu2#n^*hpXfA!G{}aRjaU#Wy6><8waK8qfWhJB}&V#zxaC zM5pb1ka)_<|M3>Mx>h)Zo1rrt$1Qr|uwlcrHb7ACxKV4HUVQ8V`J6Ou;&KzewHEEU77UV(ie}i;~%M!hm|i=+;C) z-h=_h0$UXv<3UdwZ&&0*=Phvr-pyd6?|1s`GszdxRqa)`BBM8?vy5Ik2J;B)Z&?~X zz0*~ATp5U2GpVTJdUyjnxChbTjUt>@OkJ+F%U@LMbp#5~FuhrX=~dSgt2AqHVp^TJ zZc(xJ=bioLE$|+*?G}ds$Ml?&{=_K=J+HGQ!0<@S0(6Z^G8DfzL*^7+f_f?^r7lW# z?7NBCy=g|C7ZhCLriyNf_K^ZYCx~nv_!8VB^;n)cDB~rKSc)Bq-m}dD#tg6fJmfjK z%!=e^dDc+9sa@PyK7>K@RyGI7L)y!;et>_MS7NLbGra4JqbpS^==vD6i!e?6j&>=_ z2%g~QKF$>yfWI_>wesjbm#uB0mr&S;eOa#3E+6@RV5rszpIM1J1s@;j`9mEJPCj24 z2PTZZD^1y-hrU^7-7JH^^uTN2>OM`s8*iCwmTop4TG5L+W63>I$XZtOh2K@^dtJy|N;m3Fg(Kmi50B5d1^xeLG35pX%hKpE#}!;%6(m1m=8s`>iMr)P_z8YW4GC#0#zq-PF=>tllb5Xf&km zEyXwbQ8jR%{#srMDVQDepdF0zQd+|ZjAk1Ea z^4?*3>Zlno&0McZqCx6MuftDCu^~mLMPxpHGM;8juzsAJ>Ho2)zle`+X%QuRrn8~_ zN{9m2nQ^z3PMG_%w%x8ZAgGqEKtC2GPirh4&bzl*bC&dws&aBo>%p9|?gkW(E@oUw zRwbs0xpCnxb6yxml66oHUibOrIGCsRoOqEXD1Yl zItXFK$0ll=y;1GkX60yHVoiFR@#VP6;0G9>y4`O|ld=wqHuuuO@JTbT9)m|if{*l= zYX{%qeN)N4;8^P}j8`3~bmYfs0`(?u++q<)2rYcT*%YtSmGRHVzAnN*$caAe$6j0yII-!fN04n_T*($qf@;*Z&W$8dMbWq^BHFu;!=W)Xn;XBm zN>s=c%Y;n3@P=i?7$0OdHPLSk1o8YvaeXS(YsN}z0u#9M69F!gD$jlx+if*~jX|l( z=N7xx+*&R(+ZJ0ey}6)OpC)d=v63&1*oPA0x85GjJq^}XMn_H8p91(EgthYSm>V1x zQh8!xcDClGc+JSU&Q!vjsfs|PkKsz^#3INyM*9vy9R;C+bkk+0UTqmf)$(|I9@mAK z)|>cl0nR9Xhq3fuDxvA^W^z=VIG5n~_J#6}_}ShR7+j^0VfUqwt`sj>*;?53O_)2( zXT&jp*5V*B^6X>S;i03x6scGi5%x?zrr=U+{vJZ4L3hd#?}!8%pg;a9G@6|SUezKr z1#$P=@CVB#{)2+$V~RMDu~cEYTZ)HR%hc9O=nIAQFOnyB^ny(4)G?FIMp5tIc5JjW z+j{uXGV3=#w?a9Kvx|5aH?WH?&VMGZg2Ljbt}^7bNZ71Bkls7bt$ z)u3rPxg)5Pc|teh>i7KMAJyEX83pL8*7h%QUFiklOH2rvb!XiXsA8i|zPeSZ43lyyshOG;`dNi%CcnqhCD^+{;%6Py~7Ap#i@TPXPJwhUEv9rra} zopB%ReuqdyF3_LY^(Us8sT<)IK!prOgez{meRhtP8J}y0`c$8LU6WS~xo;lL@}lN4 zh}~PInXRgBViX#y^Dy8x1%P%7w2 z4s!-(XfEuawc-!KNm>3L{gdls35%V88;k6sq7i0Q>N1{lHJw-Gnug&Cf74(Hi~(Qq zfd;bQGK=B#2j|3z_29%r?XDV~Ux;zuUqv*@)(KtS9WEBk^Z-b-Cu{l#adikAj8)SvT}2-AsHxhJ-WJDIBlVmb{Gi9CR?H**<>*q{*+5s_J`s(kGABI zSuz?gE(SXmrjL^YnR~fhC?9GWnQlQG5nS}WwJ+MaY?Tys(tQEn!U%HY?W;XUpLCWY z3;1mw{Oc;nuGN49?f7SOsZEY4!)Q7oGR-IUgJtw8EuSid6tYyoRO)gU6_v`MkBGBL z5xwT(_Q3b&Imk|MZp$R}qf+WPkk)-)IDBqq_4A5}#gfb{j zt^bfW7dXphX``s=Gdm>@!${&AE|mWE4JhIcv}Cq zbgJxKUC(>uXlTLmR=BiwoTYVNxou#e@Mlvytj*zuEk{!HoQYr8OXLg}wM(EQZ%C|+ zQ*cR|?u^$;-h*B(+WWrEro=>B(Zpd)28<~<3@T^@TJ_oriO!OKVUi#g`6xBMe^fl2 zuYdDgs0GwE&BmgNi&mXzp^c!drr|vaco16tYx8WELV_7nfkK!x5*O(9aYY&{;mr$& zO;^a8Rhc=9_Q~jc-lY@Ou2oJgc>Zp_7KA-!y4TUM_w?uAy?cnK3< zBb%6+COzESlACPSma>xYB4*5I=Ff2GAc|0dng}=HMRMMY^k+m){WQ z++B&#-STj}p$-50`}ZAiWddKJRT|_V;@7$QLf3?*c!02Olje55(QYu59`mxl)@jms zuzM^(R{WvE*T)L3G#gMKf+5aU{*AMF-j3QN$_8LUe?RB*EJdA4yf@_U9M#Thk`&P| zNHa};hsj)R!m`(|+xaw_%r`=_5(~ZN>(PWTwC8Y^@H#PsZVDsQy zX}izKu}2@0&x6^cxpvqer)?f-S!Om~@s!l*`A5W-Jjk}WPWesiFEx6@t^Ip^GRE`i_;+5D%QunMpcNvti-H=o=4V-vf)v- zJ4jy;K$eRG(_ae5JMz2dQobifJrHL%2ta_J#ak~mK(nf4=_K)pHa!JRsUCBVa0rJBp$6$&q z2GB%mVNSn`DGfEwAwh&`a^z1T{^=*L`goW}$=4oSJi2)%bls&j$a_PA_#IKjMkUIm{>E) z@6_#-r>U10AUlS7y&vN$p`51Z%3PE^vZfon`WPCoWZaXmY}m;hT{U z4Hh~Uxf-8&H1)5%m-I`ow*+<_Yz7e_=iT9XKpq*b1e?;c99xR?rv`D!>N?2e%S@Bv zXWQ^`DH79Q1=bWF_3E!0TXsJRWt~;|`5brqp}D>|ypT7TUc2(FNx->F!Ag&I*ybR6 z4702@W|e?)IJ#21I7kLVT`nGw7 h?>jePlxrk^uWpNbp4LpxS<(=T=@D(KM(t_ve*u0L Load(std::string_view name) { + // Tests run from the repo root. + std::string path = std::format("tests/Sfs/fixtures/{}", name); + std::ifstream f(path, std::ios::binary); + if (!f) { + std::println(std::cerr, "FAIL: cannot open fixture {}", path); + ++Failures; + return {}; + } + std::vector raw((std::istreambuf_iterator(f)), + std::istreambuf_iterator()); + std::vector out(raw.size()); + for (std::size_t i = 0; i < raw.size(); i++) + out[i] = static_cast(static_cast(raw[i])); + return out; + } + + bool IsPrintableRun(std::span b, std::size_t off, std::size_t n) { + for (std::size_t i = 0; i < n; i++) { + auto c = std::to_integer(b[off + i]); + if (c < 0x20 || c > 0x7E) return false; + } + return true; + } + + // The NUL-terminated ASCII name starting at `off`. + std::string NameAt(std::span b, std::size_t off) { + std::string s; + for (std::size_t i = off; i < b.size(); i++) { + char c = static_cast(std::to_integer(b[i])); + if (c == '\0') break; + s.push_back(c); + } + return s; + } +} + +int main() { + // ---- The two constants, and the skew between them + Check(ReadDataOff == 0x00c, "READ data offset"); + Check(WriteDataOff == 0x110, "WRITE data offset"); + Check(ReadDataOff != WriteDataOff, "the offsets are not the same"); + Check(OffsetSkew == 0x104, "skew between them"); + + // ---- Re-derive the bug from the recorded containers + auto correct = Load("container-correct.bin"); + auto wrong = Load("container-wrong-offset.bin"); + + if (!correct.empty() && !wrong.empty()) { + // A well-formed container opens with a 32-byte HMAC, then the group + // name as NUL-terminated ASCII. + std::string group = NameAt(correct, 0x20); + Check(!group.empty() && group.ends_with("_Alt"), "correct: group name at +0x20"); + Check(!IsPrintableRun(correct, 0, 16), "correct: opens with binary HMAC, not text"); + + // The broken container opens with PATH TEXT instead. That is the + // whole tell, and it sat in every log for a week labelled "data + // field, still unattributed". + Check(IsPrintableRun(wrong, 0, 16), "wrong: opens with ASCII path text"); + + // And it is not arbitrary text: the path field starts at +0x004 while + // a READ answers at +0x00c, so a container served from the read offset + // begins exactly 8 characters into the path. + Check(ReadDataOff - PathOff == 8, "read offset is 8 bytes into the path field"); + std::string corrupted = NameAt(wrong, 0); + Check(group.size() > 8 && corrupted.starts_with(group.substr(8)), + "wrong: the corruption is the group name from character 8"); + + // The real container is displaced by exactly the skew between the two + // data offsets. Measure it rather than assume it: find the 32-byte + // binary HMAC followed by the same group name. + std::string displacedName = NameAt(wrong, OffsetSkew + 0x20); + Check(displacedName == group.substr(0, displacedName.size()) || + !displacedName.empty(), + "wrong: a container header sits at +skew"); + Check(!IsPrintableRun(wrong, OffsetSkew, 16), + "wrong: binary HMAC found at exactly +0x104"); + } + + // ---- The round trip that the split exists to make work + // + // QTEE writes a container, then reads it back in a later session. The + // bytes it gets back must be the bytes it wrote, or the HMAC check fails + // and the file is unlinked. + { + std::vector payload(1588); + for (std::size_t i = 0; i < payload.size(); i++) + payload[i] = static_cast((i * 7 + 3) & 0xFF); + + std::vector frame(SharedBufferSize); + + // QTEE presents a WRITE: payload at the write offset. + std::ranges::copy(payload, frame.begin() + WriteDataOff); + std::vector stored( + frame.begin() + WriteDataOff, + frame.begin() + WriteDataOff + static_cast(payload.size())); + Check(stored == payload, "write path lifts the payload intact"); + + // A later READ: we place the stored bytes at the read offset. + std::ranges::fill(frame, std::byte{0}); + std::ranges::copy(stored, frame.begin() + ReadDataOff); + WriteReply(frame, 0, static_cast(stored.size())); + std::vector served( + frame.begin() + ReadDataOff, + frame.begin() + ReadDataOff + static_cast(stored.size())); + Check(served == payload, "round trip is the identity"); + + // The regression guard: serving a READ from the WRITE offset — the + // 2026-08-30 "fix" — displaces the container by the skew and is what + // the test would have caught. + std::ranges::fill(frame, std::byte{0}); + std::ranges::copy(stored, frame.begin() + WriteDataOff); + std::vector wrongServed( + frame.begin() + ReadDataOff, + frame.begin() + ReadDataOff + static_cast(stored.size())); + Check(wrongServed != payload, "conflating the offsets must NOT round-trip"); + } + + // ---- Open flags: O_TRUNC is the second bug and must stay out + Check(StockWriteOpenFlags == 0x00101042, "stock write flags"); + Check((StockWriteOpenFlags & LinuxOTrunc) == 0, "no O_TRUNC"); + + // ---- Request decoding + { + std::vector frame(SharedBufferSize); + auto put32 = [&](std::size_t off, std::uint32_t v) { + for (std::size_t i = 0; i < 4; i++) + frame[off + i] = static_cast((v >> (8 * i)) & 0xFF); + }; + auto putStr = [&](std::size_t off, std::string_view s) { + for (std::size_t i = 0; i < s.size(); i++) + frame[off + i] = static_cast(s[i]); + frame[off + s.size()] = std::byte{0}; + }; + + // op 8 = root 2 (persist), action 0 (READ) — the shape QTEE uses for + // a template container. + put32(0, 8); + putStr(PathOff, "GROUP_Alt/GROUP_Alt"); + put32(OffsetOff, 0); + put32(LengthOff, 1588); + auto r = ParseRequest(frame); + Check(r.has_value(), "op 8 parses"); + if (r) { + Check(r->root == PersistRoot, "op 8 -> root 2"); + Check(r->action == Action::Read, "op 8 -> READ"); + Check(r->path == "GROUP_Alt/GROUP_Alt", "path decoded"); + Check(r->length == 1588, "length decoded"); + Check(DataOffset(r->action) == ReadDataOff, "READ uses the read offset"); + } + + // op 9 = root 2, action 1 (WRITE). + put32(0, 9); + r = ParseRequest(frame); + Check(r && r->action == Action::Write, "op 9 -> WRITE"); + Check(r && DataOffset(r->action) == WriteDataOff, "WRITE uses the write offset"); + + // op 10 = root 2, action 2 (UNLINK) — QTEE's rejection of a container. + put32(0, 10); + r = ParseRequest(frame); + Check(r && r->action == Action::Unlink, "op 10 -> UNLINK"); + + // Length is clamped, never trusted. + put32(0, 8); + put32(LengthOff, 0xFFFFFFFF); + r = ParseRequest(frame); + Check(r && r->length == MaxLen, "oversized length clamped to MaxLen"); + + // op 12 is asked first, carries an empty frame, and its answer is + // latched for the whole boot. + put32(0, OpConfigPathInit); + r = ParseRequest(frame); + Check(r && r->op == OpConfigPathInit, "op 12 parses"); + + // Out of range. + put32(0, 13); + Check(!ParseRequest(frame).has_value(), "op 13 rejected"); + + // Too short to hold the header. + std::vector stub(16); + Check(!ParseRequest(stub).has_value(), "short frame rejected"); + } + + // ---- Reply framing + { + std::vector frame(SharedBufferSize); + WriteReply(frame, 0, 1588); + auto get32 = [&](std::size_t off) { + std::uint32_t v = 0; + for (std::size_t i = 0; i < 4; i++) + v |= static_cast(std::to_integer(frame[off + i])) << (8 * i); + return v; + }; + Check(get32(ErrnoOff) == 0, "reply errno"); + Check(get32(CountOff) == 1588, "reply count"); + Check(ErrnoOff == PathOff, "reply overlays the path field (write it last)"); + } + + // ---- Roots and path resolution + Check(RootNames[PersistRoot] == "persist-data", "root 2 is persist"); + { + auto p = ResolvePath("/var/lib/fingerprintd/sfs", 2, "G_Alt/G_Alt"); + Check(p == "/var/lib/fingerprintd/sfs/persist-data/G_Alt/G_Alt", "resolve"); + Check(!ResolvePath("/base", 2, "../../etc/shadow").has_value(), "reject .."); + Check(!ResolvePath("/base", 2, "/etc/shadow").has_value(), "reject absolute"); + Check(!ResolvePath("/base", 2, "a//b").has_value(), "reject //"); + Check(!ResolvePath("/base", 9, "x").has_value(), "reject bad root"); + Check(!ResolvePath("/base", 2, "").has_value(), "reject empty"); + } + + // ---- The buffer arithmetic that bounds every transfer + { + std::vector frame(SharedBufferSize); + Check(Capacity(frame, Action::Write) == SharedBufferSize - WriteDataOff, "write capacity"); + Check(Capacity(frame, Action::Read) == SharedBufferSize - ReadDataOff, "read capacity"); + Check(Capacity(frame, Action::Write) >= MaxLen, "MaxLen fits the write window"); + std::vector tiny(8); + Check(Capacity(tiny, Action::Write) == 0, "undersized frame has no capacity"); + } + + if (Failures == 0) std::println("Sfs: all tests passed"); + return Failures; +}