commit 62dbc6ded9560e911537a1abf181ffbe8a63d3f6 Author: yu1745 <43715680+yu1745@users.noreply.github.com> Date: Wed Sep 23 20:31:53 2026 +0200 Initial public release Fcitx 5 integration for the WeType Android ARM64 input engine, running through QEMU user mode. The AppImage ships only this project's code plus redistributable runtime pieces; the official WeType APK is downloaded from Tencent at install time, verified, and patched locally. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0c018f7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# Local WeType APK extraction and patched ARM64 runtime (APK-derived binaries). +/.deps/ +/runtime/ +/harness/engine +/harness/jinterop +/harness/probe + +# Generated builds and packaging output. +/build/ +/AppDir/ +/squashfs-root/ +/syslocal/ +/fcitx5-wetype/build/ +/fcitx5-wetype/build-*/ +/WeTypeIME-*.AppImage +/shim-diag.so +/core +/core.* +**/__pycache__/ +*.py[cod] + +# Local logs and test output. +*.log +*.csv 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..7d4588b --- /dev/null +++ b/README.md @@ -0,0 +1,136 @@ +# WeType Linux + +Linux integration for the WeType Android ARM64 input engine. The Fcitx 5 addon talks to an ARM64 harness through QEMU user mode. + +> **Unofficial project.** This is an independent interoperability project. It is not affiliated with, endorsed by, or supported by Tencent. WeType, 微信输入法 and 微信 are trademarks of Tencent. Use of the WeType engine is subject to Tencent's terms; you are responsible for complying with them. + +This repository and its AppImage contain only this project's own code plus redistributable third-party runtime pieces (QEMU user mode, ARM64 glibc, and zlib). WeType itself is never redistributed. It works like Paper's launcher for Minecraft servers: at install time, the official WeType 3.5.4 APK is downloaded from Tencent's server (`download.z.weixin.qq.com`), verified against a pinned SHA-256, and patched locally on the user's machine. + +## Install from the AppImage + +The installer needs `python3`, `patchelf`, `unzip`, and `curl` (or `wget`): + +```sh +sudo apt install python3 patchelf unzip curl # Debian, Ubuntu +sudo dnf install python3 patchelf unzip curl # Fedora (RHEL: patchelf from EPEL) +sudo pacman -S --needed python patchelf unzip curl # Arch Linux +sudo zypper install python3 patchelf unzip curl # openSUSE +``` + +The installer checks these first and prints the command for your distribution if anything is missing. It never installs packages itself. QEMU and the ARM64 C library are bundled, so no cross packages are needed. + +```sh +./WeTypeIME-Engine-x86_64.AppImage install --user # or: sudo … install --system +``` + +`install` downloads the 214 MB APK once and caches it in `${XDG_CACHE_HOME:-~/.cache}/wetype-ime`, or in `/var/cache/wetype-ime` for system installs. Use `--apk FILE` to supply an already downloaded copy; it must match the pinned SHA-256. + +The AppImage supports these commands: + +```sh +./WeTypeIME-Engine-x86_64.AppImage install --user [--apk FILE] +./WeTypeIME-Engine-x86_64.AppImage uninstall --user +sudo ./WeTypeIME-Engine-x86_64.AppImage install --system [--apk FILE] +sudo ./WeTypeIME-Engine-x86_64.AppImage uninstall --system +./WeTypeIME-Engine-x86_64.AppImage demo nihao +``` + +With no option, `install` and `uninstall` use the user scope for a regular user and the system scope for root. User installation goes under `~/.local`; system installation goes under `/usr`. The Fcitx5 addon, registration files, locally patched engine, bundled QEMU and ARM64 glibc, launchers, desktop entry, and icon are installed as ordinary files. Existing dictionaries are kept during reinstall and after uninstall. User learning data under `${XDG_DATA_HOME:-~/.local/share}/wetype-ime` is also kept. Restart Fcitx5 after installing or uninstalling, and add “微信拼音” in the Fcitx5 input method configuration. + +Before removing files, `uninstall` prints every existing installation path it will delete. It also prints the retained dictionary and APK cache paths. User uninstall lists the retained user data paths; system uninstall states the per-user data location pattern because it does not access other users' data. + +`demo` and the default command (the engine daemon) run the installed engine, so they need a prior `install`. AppImage runtime options such as `--appimage-extract` remain available. + +## Requirements for building + +The supported build host is currently x86_64 Debian or Ubuntu. Install the host tools: + +```sh +sudo apt update +sudo apt install build-essential cmake libfcitx5core-dev patchelf binutils file \ + gcc-aarch64-linux-gnu g++-aarch64-linux-gnu qemu-user-static libc6-arm64-cross \ + unzip python3 python3-dbus python3-gi curl +``` + +The harness links against ARM64 zlib. On Debian: + +```sh +sudo dpkg --add-architecture arm64 +sudo apt update +sudo apt install zlib1g-dev:arm64 +``` + +Ubuntu serves ARM64 packages from `ports.ubuntu.com` instead of the regular mirrors. First restrict the existing sources to amd64, then add the ports mirror. The example below is for 24.04 “noble”: + +```sh +sudo sed -i '/^Types:/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources +printf '%s\n' 'Types: deb' 'URIs: http://ports.ubuntu.com/ubuntu-ports' \ + 'Suites: noble noble-updates noble-security' 'Components: main universe' \ + 'Architectures: arm64' 'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg' | + sudo tee /etc/apt/sources.list.d/ubuntu-ports.sources >/dev/null +sudo dpkg --add-architecture arm64 +sudo apt update +sudo apt install zlib1g-dev:arm64 +``` + +Alternatively, set `WETYPE_ZLIB_SO` to any ARM64 `libz.so.1`. + +## Build the engine runtime + +```sh +scripts/20_build.sh # project shim + ARM64 harness; needs no APK +scripts/prepare_assets.sh # download + verify the pinned APK into .deps/wechat-ime/ +scripts/10_patch_libs.sh # patch copies of the APK libraries into runtime/ +``` + +`scripts/prepare_assets.sh /path/to/WeType.apk` uses a local APK instead of downloading. It must be the pinned 3.5.4 build. To use an already extracted APK tree, set `WETYPE_APK_ROOT` to the directory containing `lib/` and `assets/`. The patch step never modifies the APK itself. + +## Build the Fcitx 5 addon + +Build without root privileges: + +```sh +fcitx5-wetype/build.sh +``` + +The AppImage packaging step also builds this addon and includes it in the image. + +## Package the AppImage + +```sh +scripts/e2_img.sh +``` + +This builds the shim, harness, and Fcitx5 addon. It packages them with the install scripts, the host's static `qemu-aarch64-static`, and a minimal ARM64 glibc from `libc6-arm64-cross`. It needs no APK. It refuses to package if any APK-derived file ends up in `AppDir/`, so the result can be published. Never publish a build that bundles the WeType libraries or dictionaries. The license notice for the bundled third-party components is written to `usr/share/doc/wetype-ime/THIRD-PARTY.md` inside the image. + +`scripts/e2_img.sh` uses AppImage `appimagetool` 1.9.1. Set `APPIMAGETOOL` to a local copy to avoid downloading it. Set `APPIMAGE_RUNTIME` to a pinned type 2 runtime file for fully repeatable packaging. Without FUSE (containers, VMs), set `APPIMAGE_EXTRACT_AND_RUN=1`. + +## Tests and diagnostics + +- `scripts/bench_candidate_latency.py` measures candidate latency for 1–60 pinyin characters against the harness daemon directly (no Fcitx), typing either one key per request (`incremental`) or the whole string at once (`whole`). +- `scripts/test_length_threshold.py` probes incremental input, batched input, and optional backspace/replay sequences. It writes CSV and QEMU stderr logs beside the selected output path. +- `fcitx5-wetype/e2e/run_e2e.sh` runs a desktop integration check. It requires a working D-Bus session, Fcitx 5, Python D-Bus/GI bindings, QEMU, and prepared engine assets. +- `scripts/e3_verify.sh` runs the engine smoke checks against the installed engine, or against the source tree when none is installed. It runs the learning check against `runtime/`. + +The Fcitx addon writes diagnostic logs to `/tmp/wetype-harness.log` by default; override this with `WETYPE_HARNESS_LOG`. + +Example length probe against the installed engine: + +```sh +E=~/.local/lib/wetype-ime/arm64 +python3 scripts/test_length_threshold.py \ + --engine-dir $E --harness $E/wetype-harness \ + --qemu $E/qemu-aarch64-static --sysroot $E/sysroot \ + --max-length 64 --backspace-every-length +``` + +## Project layout + +- `fcitx5-wetype/`: Fcitx 5 addon source and desktop integration check. +- `harness/`, `shim/`: ARM64 JNI compatibility harness and host compatibility shims. +- `scripts/`: APK download/verification, engine patching, build, packaging, and diagnostic utilities. +- `.deps/`, `runtime/`, `AppDir/`, `squashfs-root/`: local inputs and generated output; intentionally not tracked. + +## License + +This project is licensed under the GNU General Public License v3.0 or later; see [LICENSE](LICENSE). The AppImage additionally bundles QEMU (GPL-2.0), the GNU C Library (LGPL-2.1-or-later), and zlib (Zlib license); see `usr/share/doc/wetype-ime/THIRD-PARTY.md` inside the image. The WeType engine and dictionaries are Tencent's property and are not covered by this license or distributed by this project. diff --git a/assets/wetype-ime.png b/assets/wetype-ime.png new file mode 100644 index 0000000..0fa7f3a Binary files /dev/null and b/assets/wetype-ime.png differ diff --git a/fcitx5-wetype/CMakeLists.txt b/fcitx5-wetype/CMakeLists.txt new file mode 100644 index 0000000..bfad606 --- /dev/null +++ b/fcitx5-wetype/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.16) +project(fcitx5-wetype VERSION 1.0 LANGUAGES CXX) + +include(GNUInstallDirs) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(Fcitx5Core REQUIRED) + +add_library(fcitx5-wetype MODULE src/wetype.cpp) +target_link_libraries(fcitx5-wetype PRIVATE Fcitx5::Core) + +install(TARGETS fcitx5-wetype LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}/fcitx5) +install(FILES wetype-addon.conf RENAME wetype.conf DESTINATION ${CMAKE_INSTALL_DATADIR}/fcitx5/addon) +install(FILES wetype-im.conf DESTINATION ${CMAKE_INSTALL_DATADIR}/fcitx5/inputmethod) diff --git a/fcitx5-wetype/build.sh b/fcitx5-wetype/build.sh new file mode 100755 index 0000000..88a7b4a --- /dev/null +++ b/fcitx5-wetype/build.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Build only. Installation is an explicit, separate cmake --install step. +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +BUILD_DIR="${BUILD_DIR:-$HERE/build}" + +cmake -S "$HERE" -B "$BUILD_DIR" -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-Release}" +cmake --build "$BUILD_DIR" --parallel "${JOBS:-$(nproc)}" +echo "Build complete: $BUILD_DIR" +echo "Install with: sudo cmake --install '$BUILD_DIR' --prefix /usr" diff --git a/fcitx5-wetype/e2e/dbus_wetype_test.py b/fcitx5-wetype/e2e/dbus_wetype_test.py new file mode 100644 index 0000000..d116519 --- /dev/null +++ b/fcitx5-wetype/e2e/dbus_wetype_test.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +# fcitx5-wetype 真机桌面会话 e2e — 最终版 +# 流程: SetCurrentIM(wetype-im) → 逐键 n-i-h-a-o → 空格上屏 → 断言 CommitString == 你好 +import dbus, sys, time +from dbus.mainloop.glib import DBusGMainLoop +from gi.repository import GLib + +DBusGMainLoop(set_as_default=True) +bus = dbus.SessionBus() +CTL = dbus.Interface(bus.get_object('org.fcitx.Fcitx5', '/controller'), + 'org.fcitx.Fcitx.Controller1') +IM = dbus.Interface(bus.get_object('org.fcitx.Fcitx5', '/org/freedesktop/portal/inputmethod'), + 'org.fcitx.Fcitx.InputMethod1') + +# 等引擎 dbus 就绪 +ok = False +for _ in range(10): + try: + CTL.CurrentInputMethod(); ok = True; break + except Exception: + time.sleep(1) +if not ok: + print('E2E_RESULT=FAIL (dbus 未就绪)'); sys.exit(1) + +print('group current = wetype-im (profile)', flush=True) + +committed = [] +preedits = [] +bus.add_signal_receiver(lambda *a, **k: preedits.append(str(a)[:160]), + dbus_interface='org.fcitx.Fcitx.InputContext1', + signal_name='UpdatePreedit', path_keyword='path') +bus.add_signal_receiver(lambda *a, **k: preedits.append('UpdateClientSideUI ' + str(a)[:120]), + dbus_interface='org.fcitx.Fcitx.InputContext1', + signal_name='UpdateClientSideUI', path_keyword='path') +bus.add_signal_receiver(lambda *a, **k: committed.append(str(a[0]) if a else ''), + dbus_interface='org.fcitx.Fcitx.InputContext1', + signal_name='CommitString', path_keyword='path') +CTL.SetCurrentIM('wetype-im') +time.sleep(0.5) +print('SetCurrentIM ->', CTL.CurrentInputMethod(), flush=True) +CAP = dbus.UInt64(1 | (1 << 39)) # ClientSideUI | ClientSideInputPanel +path, uuid = IM.CreateInputContext([('program', 'wetype-e2e'), ('capability', str(CAP))]) +ic = dbus.Interface(bus.get_object('org.fcitx.Fcitx5', path), 'org.fcitx.Fcitx.InputContext1') +ic.FocusIn() +time.sleep(0.5) + +loop = GLib.MainLoop() +keys = {'n': 110, 'i': 105, 'h': 104, 'a': 97, 'o': 111} +consumed = 0 +for ch in 'nihao': + r = ic.ProcessKeyEvent(dbus.UInt32(keys[ch]), dbus.UInt32(0), dbus.UInt32(0), + dbus.Boolean(False), dbus.UInt32(int(time.time()*1000) & 0xFFFFFFFF)) + consumed += bool(r) + print(f'key {ch} consumed={r}', flush=True) + for _ in range(10): + loop.get_context().iteration(False) + time.sleep(0.05) +print('consumed_total =', consumed, flush=True) +print('PREEDIT_SIGNALS =', len(preedits), preedits[:2], flush=True) +time.sleep(1) +loop.get_context().iteration(False) +print('PREEDIT_SIGNALS =', len(preedits), preedits[:3], flush=True) +print('--- 空格上屏 ---', flush=True) +ic.ProcessKeyEvent(dbus.UInt32(32), dbus.UInt32(0), dbus.UInt32(0), + dbus.Boolean(False), dbus.UInt32(int(time.time()*1000) & 0xFFFFFFFF)) +t0 = time.time() +while time.time() - t0 < 12: + loop.get_context().iteration(False) + time.sleep(0.1) + if committed: break +print('COMMITTED =', committed, flush=True) +passed = bool(consumed) and bool(committed) and '你好' in committed[0] +print('E2E_RESULT =', 'PASS' if passed else 'FAIL', flush=True) +sys.exit(0 if passed else 1) diff --git a/fcitx5-wetype/e2e/run_e2e.sh b/fcitx5-wetype/e2e/run_e2e.sh new file mode 100755 index 0000000..93bf7b5 --- /dev/null +++ b/fcitx5-wetype/e2e/run_e2e.sh @@ -0,0 +1,74 @@ +#!/bin/bash +# fcitx5-wetype 真机 e2e — 私有 dbus(前台) + 两阶段 profile +T=$(mktemp -d /tmp/wetype-e2e.XXXXXX) +trap 'rm -rf "$T"' EXIT +BASE="$(cd "$(dirname "$0")/../.." && pwd)" +ENGD="$BASE/squashfs-root/usr/lib/wetype-ime/arm64" +if [ ! -d "$ENGD" ]; then echo "缺引擎目录: 先 bash scripts/e2_img.sh && ./WeTypeIME-Engine-x86_64.AppImage --appimage-extract"; exit 9; fi +MODE="${1:-test}" + +rm -rf "$T/config" "$T/data" "$T/bus" +mkdir -p "$T/config/fcitx5" "$T/data" "$T/bus" + +dbus-daemon --session --fork --print-address=3 --print-pid=4 3>"$T/bus/addr" 4>"$T/bus/pid" +for i in $(seq 1 30); do [ -s "$T/bus/addr" ] && break; sleep 0.1; done +BUS_ADDR=$(cat "$T/bus/addr") +BUS_PID=$(cat "$T/bus/pid") +echo "BUS_ADDR=$BUS_ADDR" +export DBUS_SESSION_BUS_ADDRESS="$BUS_ADDR" +export XDG_CONFIG_HOME="$T/config" XDG_DATA_HOME="$T/data" +export XDG_DATA_DIRS="/usr/local/share:/usr/share" +export WETYPE_ENGINE_DIR="$ENGD" +unset FCITX_ADDON_DIRS + +# 阶段1: 生成 5.1.7 格式 profile +fcitx5 --disable=classicui --disable=xim --disable=waylandim > "$T/fcitx5_s1.log" 2>&1 & +P1=$! +sleep 3 +kill $P1 2>/dev/null +sleep 1 + +# 阶段2: 注入 wetype +PROF="$T/config/fcitx5/profile" +cat > "$PROF" <<'PROFEOF' +[Groups/0] +# Group Name +Name=Default +# Layout +Default Layout=us +# Default Input Method +DefaultIM=wetype-im + +[Groups/0/Items/0] +# Name +Name=wetype-im +# Layout +Layout= + +[Groups/0/Items/1] +# Name +Name=keyboard-us +# Layout +Layout= + +[GroupOrder] +0=Default +PROFEOF +grep -c 'wetype-im' "$PROF" +grep -c 'wetype-im' "$PROF" + +# 阶段3: 正式测试 +fcitx5 --disable=classicui --disable=xim --disable=waylandim > "$T/fcitx5.log" 2>&1 & +MY_FCITX=$! +sleep 3 + +if [ "$MODE" = query ]; then + python3 "$T/query_im.py"; RC=$? +else + python3 "$(dirname "$0")/dbus_wetype_test.py"; RC=$? +fi + +kill $MY_FCITX 2>/dev/null +pkill -f wetype-harness 2>/dev/null +kill $BUS_PID 2>/dev/null +exit $RC diff --git a/fcitx5-wetype/profile-example b/fcitx5-wetype/profile-example new file mode 100644 index 0000000..d62027c --- /dev/null +++ b/fcitx5-wetype/profile-example @@ -0,0 +1,19 @@ +[Groups/0] +# Group Name +Name=默认 +# Layout +DefaultLayout=us +# Default Input Method +DefaultIM=wetype + +[Groups/0/Items/0] +# Name +Name=keyboard-us +# Layout +Layout= + +[Groups/0/Items/1] +# Name +Name=wetype +# Layout +Layout= diff --git a/fcitx5-wetype/src/wetype.cpp b/fcitx5-wetype/src/wetype.cpp new file mode 100644 index 0000000..1086655 --- /dev/null +++ b/fcitx5-wetype/src/wetype.cpp @@ -0,0 +1,891 @@ +// fcitx5 微信输入法 addon — 异步事件驱动版 (2026-09-10) +// +// 架构: fcitx5 主线程 IO 事件驱动, 全程零阻塞: +// keyEvent → 写 "L c" 到引擎 stdin(内核缓冲, 不等) + 本地即时回显 buf_ +// 引擎响应(CAND)通过 EventLoop IO 事件到达 → parseCand → 更新候选面板 +// 响应与命令按 FIFO handler 队列配对, 迟到/乱序不可能发生 +// +// 引擎目录解析(按序): $WETYPE_ENGINE_DIR > ~/.local/lib/wetype-ime/arm64 > +// /usr/lib/wetype-ime/arm64 > +// ~/wetype-ime/squashfs-root/usr/lib/wetype-ime/arm64(开发回退) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fcitx { + +static constexpr int GRID_ROWS = 4; +static constexpr int GRID_COLUMNS = 5; +static constexpr int COMPACT_PAGE_SIZE = GRID_COLUMNS; +static constexpr int PAGE_SIZE = GRID_ROWS * GRID_COLUMNS; +static constexpr uint64_t CANDIDATE_DEBOUNCE_USEC = 40000; +static constexpr size_t CANDIDATE_DEBOUNCE_MAX_CHARS = 4; + +static uint64_t monotonicUsec() { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return static_cast(ts.tv_sec) * 1000000ull + ts.tv_nsec / 1000; +} + +// Display-only segmentation. The original unsegmented buffer is still sent to +// the WeType engine, so this never changes composition or candidate matching. +static std::string segmentPinyin(const std::string &raw) { + static const std::unordered_set syllables = [] { + static const char *data = + "a ai an ang ao e ei en eng er o ou " + "ba bai ban bang bao bei ben beng bi bian biao bie bin bing bo bu " + "pa pai pan pang pao pei pen peng pi pian piao pie pin ping po pou pu " + "ma mai man mang mao me mei men meng mi mian miao mie min ming miu mo mou mu " + "fa fan fang fei fen feng fo fou fu " + "da dai dan dang dao de dei den deng di dia dian diao die ding diu dong dou du duan dui dun duo " + "ta tai tan tang tao te teng ti tian tiao tie ting tong tou tu tuan tui tun tuo " + "na nai nan nang nao ne nei nen neng ng ni nian niang niao nie nin ning niu nong nou nu nuan nue nuo nv nve " + "la lai lan lang lao le lei leng li lia lian liang liao lie lin ling liu long lou lu luan lue lun luo lv " + "ga gai gan gang gao ge gei gen geng gong gou gu gua guai guan guang gui gun guo " + "ka kai kan kang kao ke kei ken keng kong kou ku kua kuai kuan kuang kui kun kuo " + "ha hai han hang hao he hei hen heng hong hou hu hua huai huan huang hui hun huo " + "za zai zan zang zao ze zei zen zeng zha zhai zhan zhang zhao zhe zhei zhen zheng zhi zhong zhou zhu zhua zhuai zhuan zhuang zhui zhun zhuo zi zong zou zu zuan zui zun zuo " + "ca cai can cang cao ce cen ceng cha chai chan chang chao che chen cheng chi chong chou chu chua chuai chuan chuang chui chun chuo ci cong cou cu cuan cui cun cuo " + "sa sai san sang sao se sen seng sha shai shan shang shao she shei shen sheng shi shou shu shua shuai shuan shuang shui shun shuo si song sou su suan sui sun suo " + "ra ran rang rao re ren reng ri rong rou ru ruan rui run ruo " + "ji jia jian jiang jiao jie jin jing jiong jiu ju juan jue jun " + "qi qia qian qiang qiao qie qin qing qiong qiu qu quan que qun " + "xi xia xian xiang xiao xie xin xing xiong xiu xu xuan xue xun " + "ya yan yang yao ye yi yin ying yo yong you yu yuan yue yun " + "wa wai wan wang wei wen weng wo wu " + "bo bei ben beng bian bie bin bing " + "ge gei gen geng gong gou gua guai guan guang gui gun guo " + "jiong juan jue jun"; + std::unordered_set result; + std::istringstream input(data); + std::string item; + while (input >> item) result.insert(item); + return result; + }(); + + std::string out; + for (size_t i = 0; i < raw.size();) { + if (raw[i] == '\'') { + out += raw[i++]; + continue; + } + size_t match = 0; + const size_t limit = std::min(raw.size(), i + 6); + for (size_t end = limit; end > i; --end) { + if (raw.find('\'', i) < end) continue; + if (syllables.count(raw.substr(i, end - i))) { + match = end - i; + break; + } + } + if (match) { + if (!out.empty() && out.back() != '\'' && out.back() != ' ') out += ' '; + out.append(raw, i, match); + i += match; + } else { + if (!out.empty() && out.back() != '\'' && out.back() != ' ') out += ' '; + out.append(raw, i, std::string::npos); + break; + } + } + return out; +} + +static Text pinyinPreedit(const std::string &buffer) { + Text text; + if (!buffer.empty()) text.append(segmentPinyin(buffer), TextFormatFlag::NoFlag); + return text; +} + +struct GridColumnCandidate : public CandidateWord { + GridColumnCandidate(Text text, std::function select) + : CandidateWord(std::move(text)), select_(std::move(select)) { + setCustomLabel(Text("")); + } + void select(InputContext *ic) const override { + if (select_) select_(ic); + } +private: + std::function select_; +}; +// 调试日志: 进 fcitx5 的 stderr, 不影响功能 +#define WLOG(...) do { fprintf(stderr, "[wetype-addon] " __VA_ARGS__); fflush(stderr); } while (0) + +// ---------------------------------------------------------------- 引擎目录解析 +static void resolveDirs(std::string &eng, std::string &dicts, std::string &work, + std::string &qemu, std::string &sysroot) { + auto existsEngine = [](const std::string &p) { + return ::access((p + "/wetype-harness").c_str(), X_OK) == 0 && + ::access((p + "/lib/libwxhld_jni.so").c_str(), R_OK) == 0; + }; + const char *home = getenv("HOME") ? getenv("HOME") : "/root"; + eng = getenv("WETYPE_ENGINE_DIR") ? getenv("WETYPE_ENGINE_DIR") : ""; + if (eng.empty() || !existsEngine(eng)) { + eng = std::string(home) + "/.local/lib/wetype-ime/arm64"; + if (!existsEngine(eng)) { + eng = "/usr/lib/wetype-ime/arm64"; + if (!existsEngine(eng)) { + eng = std::string(home) + "/wetype-ime/squashfs-root/usr/lib/wetype-ime/arm64"; // 开发回退 + } + } + } + dicts = getenv("WETYPE_DICT_DIR") ? getenv("WETYPE_DICT_DIR") : eng + "/dicts"; + // QEMU 与 ARM64 glibc 随安装一起提供;缺失时回落到系统包 + qemu = getenv("QEMU_AARCH64") ? getenv("QEMU_AARCH64") : ""; + if (qemu.empty()) + qemu = ::access((eng + "/qemu-aarch64-static").c_str(), X_OK) == 0 + ? eng + "/qemu-aarch64-static" : "qemu-aarch64-static"; + sysroot = getenv("WETYPE_SYSROOT") ? getenv("WETYPE_SYSROOT") : ""; + if (sysroot.empty()) + sysroot = ::access((eng + "/sysroot/lib/ld-linux-aarch64.so.1").c_str(), R_OK) == 0 + ? eng + "/sysroot" : "/usr/aarch64-linux-gnu"; + const char *xdg = getenv("XDG_DATA_HOME"); + std::string base = xdg && *xdg ? xdg : std::string(home) + "/.local/share"; + work = getenv("WETYPE_WORK_DIR") ? getenv("WETYPE_WORK_DIR") : base + "/wetype-ime/dict"; +} + +// ---------------------------------------------------------------- 异步引擎进程 +class EngineProc { +public: + using Handler = std::function; // "" = 失败/死亡 + + explicit EngineProc(EventLoop &loop) : loop_(loop) {} + ~EngineProc() { stop(); } + + bool alive() const { return pid_ > 0; } + bool ready() const { return state_ == State::Ready; } + bool gaveUp() const { return gaveUp_; } + void setOnReady(std::function cb) { onReady_ = std::move(cb); } + + // 非阻塞启动; 就绪走 IO 事件。指数退避防 fork 风暴(连续 5 次失败放弃)。 + bool start() { + if (pid_ > 0) return true; + if (failCount_ >= 5) { + if (!gaveUp_) { WLOG("engine gave up after %d failures\n", failCount_); gaveUp_ = true; } + return false; + } + std::string eng, dicts, work, qemu, sysroot; + resolveDirs(eng, dicts, work, qemu, sysroot); + + int inP[2], outP[2]; + if (pipe2(inP, O_CLOEXEC) < 0) return false; + if (pipe2(outP, O_CLOEXEC) < 0) { + close(inP[0]); + close(inP[1]); + return false; + } + pid_t p = fork(); + if (p < 0) { + close(inP[0]); close(inP[1]); close(outP[0]); close(outP[1]); + return false; + } + if (p == 0) { + dup2(inP[0], 0); + dup2(outP[1], 1); + close(inP[0]); + close(inP[1]); + close(outP[0]); + close(outP[1]); + const char *logPath = getenv("WETYPE_HARNESS_LOG"); + if (!logPath || !*logPath) logPath = "/tmp/wetype-harness.log"; + int logFd = open(logPath, O_WRONLY | O_CREAT | O_APPEND, 0600); + if (logFd >= 0) { dup2(logFd, 2); close(logFd); } + setenv("LD_LIBRARY_PATH", (eng + "/lib").c_str(), 1); + setenv("WETYPE_LIB_DIR", (eng + "/lib").c_str(), 1); + setenv("WETYPE_DICT_DIR", dicts.c_str(), 1); + setenv("WETYPE_ASSET_DIR", dicts.c_str(), 1); + setenv("WETYPE_WORK_DIR", work.c_str(), 1); + execlp(qemu.c_str(), qemu.c_str(), "-L", sysroot.c_str(), + (eng + "/wetype-harness").c_str(), + (eng + "/lib/libwxhld_jni.so").c_str(), "--daemon", (char *)nullptr); + _exit(127); + } + close(inP[0]); + close(outP[1]); + pid_ = p; in_ = inP[1]; out_ = outP[0]; + rbuf_.clear(); + state_ = State::Starting; + ++failCount_; + ioSource_ = loop_.addIOEvent( + out_, IOEventFlags(IOEventFlag::In), + [this](EventSourceIO *, int fd, IOEventFlags) { onReadable(fd); return true; }); + // 启动看门狗: 90s 未 READY 判失败 + timeSource_ = loop_.addTimeEvent( + CLOCK_MONOTONIC, nowUsec() + 90ull * 1000000ull, 0, + [this](EventSourceTime *, uint64_t) { onStartTimeout(); return true; }); + WLOG("engine starting (attempt %d) eng=%s\n", failCount_, eng.c_str()); + return true; + } + + void stop() { + WLOG("stop() called (pid=%d)\n", pid_); + if (pid_ > 0) { + if (in_ >= 0) { + ssize_t w = write(in_, "Q\n", 2); + (void)w; + close(in_); + in_ = -1; + } + int st = 0; + bool exited = false; + // Let the harness process Q, destroy its engine session and flush + // learned words. Bound shutdown so a wedged QEMU cannot stall Fcitx. + for (int i = 0; i < 100; ++i) { + pid_t result = waitpid(pid_, &st, WNOHANG); + if (result == pid_ || (result < 0 && errno == ECHILD)) { + exited = true; + break; + } + if (result < 0 && errno != EINTR) break; + usleep(10000); + } + if (!exited) { + kill(pid_, SIGKILL); + while (waitpid(pid_, &st, 0) < 0 && errno == EINTR) {} + } + pid_ = -1; + } + if (in_ >= 0) { close(in_); in_ = -1; } + if (out_ >= 0) { close(out_); out_ = -1; } + ioSource_.reset(); + timeSource_.reset(); + state_ = State::Dead; + failPendingHandlers(); + } + + // 异步发送: handler 在主线程(IO 事件)被调用一次; 死亡时以 "" 调用 + void send(const std::string &line, Handler h) { + if (pid_ <= 0 || in_ < 0) { if (h) h(""); return; } + WLOG("engine send command=%c bytes=%zu queued=%zu state=%d\n", + line.empty() ? '?' : line[0], line.size(), pending_.size(), + static_cast(state_)); + std::string out = line + "\n"; + ssize_t n = write(in_, out.data(), out.size()); + if (n < 0) { + WLOG("write fail errno=%d → stop\n", errno); + stop(); + if (h) h(""); + return; + } + pending_.push_back(std::move(h)); + } + +private: + enum class State { Dead, Starting, Ready }; + + static uint64_t nowUsec() { + struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000ull + ts.tv_nsec / 1000; + } + + void onReadable(int fd) { + char tmp[8192]; + ssize_t n = read(fd, tmp, sizeof tmp); + if (n <= 0) { + WLOG("engine EOF (n=%zd)\n", n); + stop(); + return; + } + rbuf_.append(tmp, n); + size_t pos; + while ((pos = rbuf_.find('\n')) != std::string::npos) { + std::string line = rbuf_.substr(0, pos); + rbuf_.erase(0, pos + 1); + onLine(line); + } + } + + void onLine(const std::string &line) { + WLOG("engine line bytes=%zu prefix=%.12s queued=%zu state=%d\n", + line.size(), line.c_str(), pending_.size(), static_cast(state_)); + if (state_ == State::Starting) { + if (line == "READY") { + state_ = State::Ready; + failCount_ = 0; + timeSource_.reset(); + WLOG("engine READY\n"); + if (onReady_) onReady_(); + } + return; // READY 前的杂音行丢弃 + } + if (state_ != State::Ready) return; + if (!line.empty() && !pending_.empty()) { + Handler h = std::move(pending_.front()); + pending_.pop_front(); + if (h) h(line); + } + } + + void onStartTimeout() { + WLOG("engine start timeout → stop\n"); + stop(); + } + + void failPendingHandlers() { + while (!pending_.empty()) { + Handler h = std::move(pending_.front()); + pending_.pop_front(); + if (h) h(""); + } + } + + EventLoop &loop_; + pid_t pid_ = -1; + int in_ = -1, out_ = -1; + std::string rbuf_; + State state_ = State::Dead; + std::deque pending_; + std::unique_ptr ioSource_; + std::unique_ptr timeSource_; + std::function onReady_; + int failCount_ = 0; + bool gaveUp_ = false; +}; + +// ---------------------------------------------------------------- 主引擎类 +class WeTypeEngine final : public InputMethodEngineV2 { +public: + explicit WeTypeEngine(Instance *instance) + : instance_(instance), eng_(instance->eventLoop()) { + signal(SIGPIPE, SIG_IGN); + std::string eng, dicts, work, qemu, sysroot; + resolveDirs(eng, dicts, work, qemu, sysroot); + WLOG("async addon init: eng=%s\n", eng.c_str()); + // Start lazily on the first pinyin key. The Android engine has a + // background warmup path that can crash after sitting idle. + } + ~WeTypeEngine() override { eng_.stop(); } + + void keyEvent(const InputMethodEntry &, KeyEvent &event) override; + + void reset(const InputMethodEntry &entry, InputContextEvent &event) override { + auto *ic = event.inputContext(); + if (!ic) return; + bool had = !buf_.empty() || !cands_.empty(); + ++revision_; + buf_.clear(); + cands_.clear(); + covers_.clear(); + candidatesCurrent_ = false; + cancelPendingCandidates(); + windowStart_ = 0; + selected_ = 0; + expandedGrid_ = false; + recoveryTried_ = false; + eng_.send("SAVE", nullptr); + eng_.send("C", nullptr); + if (had) updateUI(*ic); + } + + // 失焦/切换 IM: 彻底清理, 候选框随之消失 + void deactivate(const InputMethodEntry &entry, InputContextEvent &event) override { + auto *ic = event.inputContext(); + if (!ic) return; + // Fcitx calls deactivate before changing the active input method. If + // Shift (or another IM toggle) is pressed mid-composition, preserve + // the unfinished pinyin as literal text instead of dropping it. + if (event.type() == EventType::InputContextSwitchInputMethod && !buf_.empty()) { + WLOG("deactivate commits raw pinyin len=%zu\n", buf_.size()); + ic->commitString(buf_); + } + bool had = !buf_.empty() || !cands_.empty(); + ++revision_; + buf_.clear(); + cands_.clear(); + covers_.clear(); + candidatesCurrent_ = false; + cancelPendingCandidates(); + windowStart_ = 0; + selected_ = 0; + expandedGrid_ = false; + recoveryTried_ = false; + eng_.send("C", nullptr); + if (had) updateUI(*ic); + } + +private: + void updateUI(InputContext &ic) { + auto &panel = ic.inputPanel(); + panel.reset(); + panel.setPreedit(pinyinPreedit(buf_)); + if (!cands_.empty()) { + if (windowStart_ >= static_cast(cands_.size())) { + windowStart_ = 0; + selected_ = 0; + } + } + if (!cands_.empty()) { + const int start = windowStart_; + const int visiblePageSize = expandedGrid_ ? PAGE_SIZE : COMPACT_PAGE_SIZE; + const int end = std::min(start + visiblePageSize, cands_.size()); + const int pageCount = end - start; + if (selected_ < start || selected_ >= end) selected_ = start; + auto cl = std::make_unique(); + cl->setLayoutHint(CandidateLayoutHint::Horizontal); + if (!expandedGrid_) { + cl->setPageSize(pageCount); + for (int index = start; index < end; ++index) { + Text candidate; + candidate.append(std::to_string(index - start + 1) + " "); + candidate.append(cands_[index]); + cl->append(std::move(candidate), + [this, index](InputContext *context) { + commitCandidate(context, index); + }); + } + // The API validates this index immediately against the list + // size, so set it only after all compact candidates exist. + cl->setGlobalCursorIndex(selected_ - start); + } else { + cl->setPageSize(GRID_COLUMNS); + cl->setLabels(std::vector(GRID_COLUMNS, "")); + cl->setGlobalCursorIndex(-1); + for (int col = 0; col < GRID_COLUMNS; ++col) { + Text column; + for (int row = 0; row < GRID_ROWS; ++row) { + const int index = start + row * GRID_COLUMNS + col; + if (index < end) { + const bool selected = index == selected_; + const auto label = std::to_string(index - start + 1) + " "; + const auto flag = selected ? TextFormatFlag::HighLight + : TextFormatFlag::NoFlag; + column.append(label, flag); + column.append(cands_[index], flag); + } else { + column.append(" "); + } + if (row + 1 < GRID_ROWS) column.append("\n"); + } + const int selectedIndex = selected_; + cl->append(std::move(column), + [this, selectedIndex](InputContext *context) { + commitCandidate(context, selectedIndex); + }); + } + } + panel.setCandidateList(std::move(cl)); + } + ic.updateUserInterface(UserInterfaceComponent::InputPanel); + } + + void commitText(InputContext *ic, const std::string &text) { + WLOG("commit len=%zu revision=%llu\n", text.size(), + static_cast(revision_)); + ic->commitString(text); + ++revision_; + buf_.clear(); + cands_.clear(); + covers_.clear(); + candidatesCurrent_ = false; + cancelPendingCandidates(); + windowStart_ = 0; + selected_ = 0; + expandedGrid_ = false; + recoveryTried_ = false; + eng_.send("C", nullptr); // 重建会话 + updateUI(*ic); + } + + void commitCandidate(InputContext *ic, int index) { + if (!candidatesCurrent_ || index < 0 || index >= static_cast(cands_.size())) return; + const int cover = index < static_cast(covers_.size()) ? covers_[index] : 0; + WLOG("commit candidate index=%d count=%zu cover=%d buffer_len=%zu revision=%llu\n", index, + cands_.size(), cover, buf_.size(), static_cast(revision_)); + if (cover <= 0 || static_cast(cover) >= buf_.size()) { + eng_.send("S " + std::to_string(index), nullptr); + commitText(ic, cands_[index]); + return; + } + // The candidate covers only a prefix (e.g. 你好 of nihaoshijie): commit + // it and keep composing the rest. The engine answers S with the + // candidates for the remaining pinyin. + ic->commitString(cands_[index]); + ++revision_; + buf_.erase(0, cover); + cands_.clear(); + covers_.clear(); + candidatesCurrent_ = false; + cancelPendingCandidates(); + windowStart_ = 0; + selected_ = 0; + expandedGrid_ = false; + eng_.send("S " + std::to_string(index), candidateHandler()); + updateUI(*ic); + } + + void ensureEngine() { + if (eng_.alive() || eng_.gaveUp()) return; + spansEnabled_ = false; + if (!eng_.start()) return; + // Ask for per-candidate input spans; older harnesses answer ERR and + // keep whole-buffer selection. + eng_.send("OPT spans", [this](const std::string &resp) { + spansEnabled_ = resp == "OK"; + WLOG("candidate spans %s\n", spansEnabled_ ? "enabled" : "unavailable"); + }); + } + + void cancelPendingCandidates() { + debounceSource_.reset(); + pendingKeys_.clear(); + } + + void scheduleCandidates(const std::string &keys) { + pendingKeys_ += keys; + debounceSource_.reset(); + if (pendingKeys_.size() >= CANDIDATE_DEBOUNCE_MAX_CHARS) { + flushCandidates(); + return; + } + debounceSource_ = instance_->eventLoop().addTimeEvent( + CLOCK_MONOTONIC, monotonicUsec() + CANDIDATE_DEBOUNCE_USEC, 0, + [this](EventSourceTime *, uint64_t) { + debounceSource_.reset(); + flushCandidates(); + return true; + }); + } + + // Handles a CAND/EMPTY reply for the buffer as it is now; replies that + // arrive after the buffer changed are ignored. + EngineProc::Handler candidateHandler() { + auto ref = icRef_; + const auto expectedBuf = buf_; + const auto expectedRevision = revision_; + return [this, ref, expectedBuf, expectedRevision](const std::string &resp) { + fcitx::InputContext *ic = ref.get(); + WLOG("response len=%zu prefix=%.4s expected_revision=%llu current_revision=%llu valid_ic=%d\n", + resp.size(), resp.c_str(), static_cast(expectedRevision), + static_cast(revision_), ic ? 1 : 0); + if (!ic || expectedRevision != revision_ || expectedBuf != buf_) return; + if (resp.empty()) { + // Keep the last visible page while recovering; a transient + // missing response must not collapse the candidate panel. + updateUI(*ic); + if (!buf_.empty() && !recoveryTried_) { + recoveryTried_ = true; + WLOG("engine response lost; restarting and replaying buffer_len=%zu revision=%llu\n", + buf_.size(), static_cast(revision_)); + cancelPendingCandidates(); + ensureEngine(); + scheduleCandidates(buf_); + } + return; + } + if (resp != "EMPTY" && resp.rfind("CAND\t", 0) != 0) { + // A partial selection the engine did not keep composing + // (OK/ERR): rebuild the session from the remaining pinyin. + WLOG("unexpected candidate reply prefix=%.4s; replaying buffer_len=%zu\n", + resp.c_str(), buf_.size()); + eng_.send("C", nullptr); + scheduleCandidates(buf_); + return; + } + cands_.clear(); + covers_.clear(); + if (resp.rfind("CAND\t", 0) == 0) { + std::stringstream ss(resp.substr(5)); + std::string item; + while (std::getline(ss, item, '\t')) { + int cover = 0; + if (spansEnabled_) { + const auto colon = item.find(':'); + if (colon == std::string::npos) continue; + cover = std::atoi(item.c_str()); + item.erase(0, colon + 1); + } + if (item.empty()) continue; + cands_.push_back(item); + covers_.push_back(cover); + } + } + candidatesCurrent_ = true; + WLOG("parsed candidates=%zu buffer_len=%zu\n", cands_.size(), buf_.size()); + windowStart_ = 0; + selected_ = 0; + updateUI(*ic); + }; + } + + void flushCandidates() { + if (buf_.empty() || pendingKeys_.empty()) return; + std::string keys = std::move(pendingKeys_); + pendingKeys_.clear(); + ensureEngine(); + WLOG("send batch chars=%zu buffer_len=%zu revision=%llu\n", keys.size(), + buf_.size(), static_cast(revision_)); + eng_.send("B " + keys, candidateHandler()); + } + + Instance *instance_; + EngineProc eng_; + std::string buf_; + std::string pendingKeys_; + std::unique_ptr debounceSource_; + std::vector cands_; + std::vector covers_; // pinyin letters each candidate consumes (0 = unknown) + bool spansEnabled_ = false; + // Retained candidates remain visible during composition updates, but are + // not selectable until a result for the current buffer arrives. + bool candidatesCurrent_ = false; + int windowStart_ = 0; + int selected_ = 0; + bool expandedGrid_ = false; + bool recoveryTried_ = false; + uint64_t revision_ = 0; + TrackableObjectReference icRef_; + + void clearAll(InputContext *ic = nullptr) { + ++revision_; + buf_.clear(); + cands_.clear(); + covers_.clear(); + candidatesCurrent_ = false; + cancelPendingCandidates(); + windowStart_ = 0; + selected_ = 0; + expandedGrid_ = false; + recoveryTried_ = false; + eng_.send("C", nullptr); + if (ic) updateUI(*ic); + } + +}; + +void WeTypeEngine::keyEvent(const InputMethodEntry &, KeyEvent &event) { + auto ic = event.inputContext(); + WLOG("keyEvent sym=%d ready=%d\n", (int)event.key().sym(), eng_.ready() ? 1 : 0); + const auto sym = event.key().sym(); + bool handled = false; + icRef_ = ic->watch(); + + if (event.key().states().testAny(KeyStates{KeyState::Ctrl, KeyState::Alt, + KeyState::Super, KeyState::Super2, + KeyState::Meta, KeyState::Hyper, + KeyState::Hyper2, KeyState::Mod5})) { + return; + } + + if (!event.isRelease()) { + // Alphabet keys, including Shift/CapsLock symbols, become lowercase + // pinyin. Ctrl/Alt/Super/Meta shortcuts were passed through above. + if ((sym >= FcitxKey_a && sym <= FcitxKey_z) || + (sym >= FcitxKey_A && sym <= FcitxKey_Z)) { + if (buf_.empty()) recoveryTried_ = false; + const bool replayBuffer = !eng_.alive() && !buf_.empty(); + char c = (sym >= FcitxKey_a && sym <= FcitxKey_z) + ? static_cast('a' + (sym - FcitxKey_a)) + : static_cast('a' + (sym - FcitxKey_A)); + ensureEngine(); + ++revision_; + buf_ += c; + candidatesCurrent_ = false; + WLOG("typed alpha buffer_len=%zu pending_before=%zu revision=%llu\n", + buf_.size(), pendingKeys_.size(), static_cast(revision_)); + if (replayBuffer) cancelPendingCandidates(); + handled = true; + // Refresh the preedit immediately while keeping the last + // candidate page visible until the new engine response arrives. + updateUI(*ic); + scheduleCandidates(replayBuffer ? buf_ : std::string(1, c)); + } + // The compact single row expands to the four-row grid on Down. + else if (!buf_.empty() && candidatesCurrent_ && !cands_.empty() && + (sym == FcitxKey_Left || sym == FcitxKey_Right || + sym == FcitxKey_Up || sym == FcitxKey_Down)) { + if (!expandedGrid_) { + if (sym == FcitxKey_Down) { + expandedGrid_ = true; + } else if (sym == FcitxKey_Left && selected_ > windowStart_) { + --selected_; + } else if (sym == FcitxKey_Right && + selected_ + 1 < std::min(windowStart_ + COMPACT_PAGE_SIZE, + cands_.size())) { + ++selected_; + } + updateUI(*ic); + handled = true; + } else { + const int start = windowStart_; + const int count = std::min(PAGE_SIZE, + static_cast(cands_.size()) - start); + const int row = (selected_ - start) / GRID_COLUMNS; + const int col = (selected_ - start) % GRID_COLUMNS; + int next = selected_; + if (sym == FcitxKey_Left && col > 0) next--; + if (sym == FcitxKey_Right && col + 1 < GRID_COLUMNS && next + 1 < start + count) next++; + if (sym == FcitxKey_Up) { + if (row > 0) next -= GRID_COLUMNS; + else if (start >= GRID_COLUMNS) { + windowStart_ -= GRID_COLUMNS; + next -= GRID_COLUMNS; + } + } + if (sym == FcitxKey_Down) { + if (next + GRID_COLUMNS < start + count) next += GRID_COLUMNS; + else if (next + GRID_COLUMNS < static_cast(cands_.size())) { + windowStart_ += GRID_COLUMNS; + next += GRID_COLUMNS; + } + } + selected_ = next; + updateUI(*ic); + handled = true; + } + } + // - / = / PgUp / PgDn : move between four-row candidate grids. + else if (sym == FcitxKey_minus || sym == FcitxKey_Page_Up) { + if (!buf_.empty() && windowStart_ > 0) { + windowStart_ = std::max(0, windowStart_ - PAGE_SIZE); + selected_ = windowStart_; + updateUI(*ic); + handled = true; + } + } + else if (sym == FcitxKey_equal || sym == FcitxKey_plus || + sym == FcitxKey_KP_Add || sym == FcitxKey_Page_Down) { + if (!buf_.empty() && candidatesCurrent_ && !cands_.empty() && !expandedGrid_) { + expandedGrid_ = true; + updateUI(*ic); + handled = true; + } else if (!buf_.empty() && expandedGrid_ && + candidatesCurrent_ && windowStart_ + PAGE_SIZE < (int)cands_.size()) { + windowStart_ = std::min(windowStart_ + PAGE_SIZE, + ((static_cast(cands_.size()) - 1) / GRID_COLUMNS) * GRID_COLUMNS); + selected_ = windowStart_; + updateUI(*ic); + handled = true; + } + } + // 逗号/句号: 组词中=首选顶字+标点; 空态透传 + else if (sym == FcitxKey_comma || sym == FcitxKey_period) { + if (!buf_.empty()) { + std::string punct = (sym == FcitxKey_comma) ? "," : "."; + std::string text = !candidatesCurrent_ || cands_.empty() ? buf_ : cands_[selected_]; + if (candidatesCurrent_ && !cands_.empty()) + eng_.send("S " + std::to_string(selected_), nullptr); + WLOG("commit with punctuation text_len=%zu\n", text.size() + punct.size()); + ic->commitString(text + punct); + ++revision_; + buf_.clear(); + cands_.clear(); + covers_.clear(); + candidatesCurrent_ = false; + cancelPendingCandidates(); + windowStart_ = 0; + selected_ = 0; + expandedGrid_ = false; + eng_.send("C", nullptr); + updateUI(*ic); + handled = true; + } + } + // 数字选词(全局序号 = 页首 + 数字) + else if (sym >= FcitxKey_1 && sym <= FcitxKey_9) { + int ordinal = static_cast(sym - FcitxKey_1); + int visibleCount = expandedGrid_ ? PAGE_SIZE : COMPACT_PAGE_SIZE; + int idx = windowStart_ + ordinal; + if (ordinal < visibleCount && candidatesCurrent_ && !cands_.empty() && idx < (int)cands_.size()) { + commitCandidate(ic, idx); + handled = true; + } + } + // 空格: 上屏首选(或原文) + else if (sym == FcitxKey_space) { + if (!buf_.empty()) { + if (candidatesCurrent_ && !cands_.empty()) commitCandidate(ic, selected_); // 含部分选词与词库学习 + else commitText(ic, buf_); + handled = true; + } + } + // Enter commits the in-progress pinyin literally as Latin text. + else if (sym == FcitxKey_Return) { + if (!buf_.empty()) { + WLOG("enter commits raw pinyin len=%zu\n", buf_.size()); + commitText(ic, buf_); + handled = true; + } + } + // 退格: C 重建 + 前缀重放 + else if (sym == FcitxKey_BackSpace) { + if (!buf_.empty()) { + buf_.pop_back(); + ++revision_; + candidatesCurrent_ = false; + cancelPendingCandidates(); + handled = true; + eng_.send("C", nullptr); + if (buf_.empty()) { + cands_.clear(); + covers_.clear(); + candidatesCurrent_ = false; + windowStart_ = 0; + selected_ = 0; + expandedGrid_ = false; + updateUI(*ic); + } else { + scheduleCandidates(buf_); + updateUI(*ic); + } + } + } + // Esc: 清空 + else if (sym == FcitxKey_Escape) { + if (!buf_.empty()) { + ++revision_; + buf_.clear(); + cands_.clear(); + covers_.clear(); + candidatesCurrent_ = false; + cancelPendingCandidates(); + windowStart_ = 0; + selected_ = 0; + expandedGrid_ = false; + eng_.send("C", nullptr); + updateUI(*ic); + handled = true; + } + } + } + + if (handled) event.filterAndAccept(); +} + +class WeTypeEngineFactory : public AddonFactory { +public: + AddonInstance *create(AddonManager *manager) override { + return new WeTypeEngine(manager->instance()); + } +}; + +} // namespace fcitx + +FCITX_ADDON_FACTORY(fcitx::WeTypeEngineFactory); diff --git a/fcitx5-wetype/wetype-addon.conf b/fcitx5-wetype/wetype-addon.conf new file mode 100644 index 0000000..a60ae4e --- /dev/null +++ b/fcitx5-wetype/wetype-addon.conf @@ -0,0 +1,9 @@ +[Addon] +Name=微信输入法 +GenericName=微信拼音 +Comment=微信输入法引擎 (qemu-aarch64 常驻桥) +Category=InputMethod +Version=1.0 +OnDemand=True +Type=SharedLibrary +Library=libfcitx5-wetype diff --git a/fcitx5-wetype/wetype-im.conf b/fcitx5-wetype/wetype-im.conf new file mode 100644 index 0000000..2c5b99f --- /dev/null +++ b/fcitx5-wetype/wetype-im.conf @@ -0,0 +1,6 @@ +[InputMethod] +Name=微信拼音 +Icon=fcitx-pinyin +Label=微 +LangCode=zh_CN +Addon=wetype diff --git a/harness/dict_table.h b/harness/dict_table.h new file mode 100644 index 0000000..77129f9 --- /dev/null +++ b/harness/dict_table.h @@ -0,0 +1,43 @@ +/* 由 index.json 生成:官方词库元数据表 */ +static const struct { const char *name; int type; int version; } g_dict_table[] = { + {"sw.bin", 65560, 1643}, + {"sd.bin", 65559, 1542}, + {"tts.bin", 65573, 586}, + {"ln2py.bin", 65547, 962}, + {"ssd.bin", 65635, 32}, + {"wsd.bin", 65549, 1045}, + {"prism_v2.bin", 65578, 51}, + {"awb.bin", 65544, 1043}, + {"bwcn.bin", 65536, 1356}, + {"pskvd.bin", 65568, 1295}, + {"ap.bin", 65543, 1022}, + {"md.bin", 262145, 1022}, + {"rsd.bin", 65561, 958}, + {"stt.bin", 65572, 583}, + {"ae.bin", 65569, 1107}, + {"lmcn.bin", 131072, 1266}, + {"bwcnen.bin", 65537, 1227}, + {"cell_dict.sc.zh", 0, 867}, + {"swbd86.bin", 524291, 959}, + {"bwen.bin", 65539, 1058}, + {"mdltr.bin", 262149, 486}, + {"wtid.bin", 65682, 305}, + {"wltm.bin", 65563, 969}, + {"bccn.bin", 65538, 1028}, + {"wpen.bin", 65540, 955}, + {"wwkvc2e.bin", 65566, 992}, + {"akv.bin", 65545, 1086}, + {"wkvc2e.bin", 65553, 1535}, + {"cell_dict.ssrc.zh", 7, 1223}, + {"hp_base.bin", 262144, 1513}, + {"wlwmd.bin", 65564, 990}, + {"tcd.bin", 65570, 962}, + {"enfont.bin", 65576, 167}, + {"editwordt9.bin", 65633, 102}, + {"pcc.bin", 65565, 1008}, + {"elc.bin", 262147, 968}, + {"editpinyin.bin", 65625, 100}, + {"hwd_hand_write.bin", 524290, 1118}, + {"noun_tag_dict.bin", 65580, 48}, + {"atp.bin", 262148, 597}, +}; diff --git a/harness/engine.c b/harness/engine.c new file mode 100644 index 0000000..999ee47 --- /dev/null +++ b/harness/engine.c @@ -0,0 +1,74 @@ +/* Route A harness v2: 直调引擎平面 C API。 + * 结构体布局为静态重建(v1,待真值对拍)。 */ +#include +#include +#include +#include +#include +#include +#include + +/* 布局偏移(十进制字节,基址=传入指针) */ +#define OFF_PLATFORM 0 /* int */ +#define OFF_PTR16 16 /* 引擎读取,语义未明 */ +#define OFF_WORKDIR 24 /* char* 工作目录(引擎自动建目录) */ +#define OFF_FLOAT184 184 +#define OFF_FLOAT188 188 +#define STRUCT_SIZE 384 + +int main(int argc, char **argv) { + if (argc < 2) { fprintf(stderr, "usage: engine [platform]\n"); return 2; } + const char *lib = argv[1]; + int platform = argc > 2 ? atoi(argv[2]) : 0; + + void *h = dlopen(lib, RTLD_NOW); + if (!h) { printf("dlopen FAILED: %s\n", dlerror()); return 1; } + printf("dlopen ok: %s\n", lib); + + void *sym_uin = dlsym(h, "wxime_reset_user_id"); + printf("wxime_reset_user_id @ %p\n", sym_uin); + + void *sym_init = dlsym(h, "wxime_initialize"); + if (!sym_init) { printf("dlsym wxime_initialize FAILED: %s\n", dlerror()); return 1; } + printf("wxime_initialize @ %p\n", sym_init); + + if (mkdir("/tmp/wetype-work", 0755) && errno != EEXIST) {} + static unsigned char buf[STRUCT_SIZE]; + memset(buf, 0, sizeof buf); + *(int *)(buf + OFF_PLATFORM) = platform; + /* 引擎会 free 这些指针:必须 malloc,不能传 rodata/栈内存 */ + *(char **)(buf + OFF_WORKDIR) = strdup("/tmp/wetype-work"); + + /* uin 必须纯数字(内部 stoull),且要在 initialize 之前设 */ + const char *uin = "10000001"; + if (sym_uin) { + int ru = ((int (*)(const char *, int))sym_uin)(uin, (int)strlen(uin)); + printf("wxime_reset_user_id(%s) -> %d\n", uin, ru); + } + + /* 暴力实证:全部 {ptr,len} 对都填 uin,找出哪组是 uin 源 */ + { + static const int pair_offs[] = {48, 64, 88, 104, 120}; + for (unsigned i = 0; i < sizeof(pair_offs)/sizeof(pair_offs[0]); i++) { + char *p = strdup(uin); + *(char **)(buf + pair_offs[i]) = p; + *(int *)(buf + pair_offs[i] + 8) = (int)strlen(uin); + printf(" pair+%d -> data=%p\n", pair_offs[i], (void *)p); + } + /* +168 不是字符串对,是指向容器对象的指针:{?, ?, data@+16, count@+24}。 + 填空容器(count=0)→ 引擎跳过遍历。 */ + static unsigned char empty_container[32]; + memset(empty_container, 0, sizeof empty_container); + *(void **)(buf + 168) = empty_container; + fflush(stdout); + } + + *(float *)(buf + OFF_FLOAT184) = 1.0f; + *(float *)(buf + OFF_FLOAT188) = 1.0f; + printf("calling wxime_initialize(platform=%d, workdir=/tmp/wetype-work)...\n", platform); + fflush(stdout); + int r = ((int (*)(void *))sym_init)(buf); + printf("wxime_initialize -> %d (0x%x)\n", r, r); + fflush(stdout); + return 0; +} diff --git a/harness/jinterop.c b/harness/jinterop.c new file mode 100644 index 0000000..22d9b69 --- /dev/null +++ b/harness/jinterop.c @@ -0,0 +1,1178 @@ +#define _GNU_SOURCE +/* jinterop: 伪造迷你 JNIEnv,直接调用厂商 libwxhld_jni.so 的导出函数 + * initialize(JNIEnv*, jobject, jobject),让胶水层用真实逻辑填引擎结构体。 + * 设计: + * - jobject = JObj{类名, 字段表},字段值是我们罐头数据(canned) + * - jfieldID/jmethodID = 指向 token 结构的指针 + * - 未实现的 JNIEnv 槽位 = 记日志的 stub(返回 0),跑一轮就知道胶水要什么 + * - FindClass/GetFieldID/GetObjectField/GetStringUTFChars 是实测确认的槽位 + * (6 / 94 / 95 / 169),其余按标准 JNI 表填,双保险槽位重复挂载 */ +#include +#include +#include +#include +#include +#include "dict_table.h" +#include +#include +#include +#include +#include +#include + +#define ENV_SLOTS 300 + +typedef struct { const char *name; char type; /* s,i,l,f,z,o */ const void *val; } JField; +typedef struct JObj { unsigned long magic; const char *cls; JField f[48]; int n; } JObj; +typedef struct { unsigned long magic; unsigned char *data; long len; } JBytes; +#define JB_MAGIC 0x4a42595445530001UL +#define JO_MAGIC 0x4a4f424a45435401UL +typedef struct { const char *name; char type; const char *sig; } JIDToken; /* jfieldID/jmethodID */ + +static int g_verbose = 1; +#define LOG(...) do { if (g_verbose) { printf("[env] " __VA_ARGS__); fflush(stdout);} } while (0) + +/* ---------- 罐头数据 ---------- */ +static JObj g_initinfo; +static const char *CLS_INITINFO = "com/tencent/wxhld/info/InitInfo"; + +/* Java byte[] 模拟 */ + +/* 有界登记表仅用于事后 dump;运行时类型识别通过 JObj 自身 magic 标记。 */ +static JBytes *g_last_bytes = NULL; /* 最近创建的 byte[](String([B) 构造用) */ +static JObj *g_objs[8192]; +static int g_objn = 0; +static JObj *obj_new(const char *cls) { + JObj *o = calloc(1, sizeof(JObj)); + o->magic = JO_MAGIC; + o->cls = cls; + if (g_objn < 8192) g_objs[g_objn++] = o; + return o; +} +static void dump_all_objs(void) { + printf("=== 已构造对象(%d 个,只列有字段的) ===\n", g_objn); + for (int i = 0; i < g_objn; i++) { + JObj *o = g_objs[i]; + if (!o || o->n == 0) continue; + printf("[obj %d] %s:", i, o->cls ? o->cls : "?"); + for (int k = 0; k < o->n; k++) { + JField *f = &o->f[k]; + if (f->type == 's') printf(" %s=\"%s\"", f->name, (const char *)f->val); + else if (f->type == 'i' || f->type == 'l' || f->type == 'z') printf(" %s=%ld", f->name, (long)f->val); + else if (f->type == 'o') printf(" %s=%p", f->name, f->val); + else if (f->type == 'f') printf(" %s=%f", f->name, f->val ? *(const float *)f->val : 0.0f); + } + printf("\n"); + } + fflush(stdout); +} +static void obj_set(JObj *o, const char *name, char type, const void *val) { + if (o->n >= 48) return; /* 防越界(胶水层会反复写同一对象) */ + o->f[o->n].name = name; o->f[o->n].type = type; o->f[o->n].val = val; o->n++; +} +static JField *obj_get(JObj *o, const char *name) { + for (int i = 0; i < o->n; i++) + if (!strcmp(o->f[i].name, name)) return &o->f[i]; + return NULL; +} + +/* jstring 直接用 JObj 承载,约定字段名 ".str" */ +static JObj *str_obj(const char *s) { + JObj *o = obj_new("java/lang/String"); + obj_set(o, ".str", 's', s); + return o; +} + + +/* ---------- JNIEnv 实现 ---------- */ +static void *stub_default(void) { + void *lr = __builtin_return_address(0); + LOG("UNIMPL slot called (lr=%p)\n", lr); + return 0; +} + +/* 对象数组:JObj 伪装,cls="[L...",元素存字段里 */ +typedef struct { void **elem; int len; } JArr; + + +/* ---- 候选文本提取与顺序 dump ---- */ +static const char *cand_text(JObj *c) { + if (!c) return NULL; + JField *f = obj_get(c, "text"); + if (!f || !f->val) return NULL; + if (f->type == 's') return (const char *)f->val; /* SetObjectField 已解包 */ + if (f->type == 'o') { /* 原始 String 对象 */ + JField *sf = obj_get((JObj *)f->val, ".str"); + return sf ? (const char *)sf->val : NULL; + } + return NULL; +} +static void dump_order(void *env, void *cg, long it, int n, const char *tag) { + if (!cg || !it) { printf("[%s] 无 iterator\n", tag); return; } + JArr *a = (JArr *)((void *(*)(void *, void *, long, int))cg)(env, NULL, it, n); + if (!a) { printf("[%s] candidate_get_n -> NULL\n", tag); return; } + for (int i = 0; i < a->len; i++) { + const char *t = cand_text((JObj *)a->elem[i]); + printf("[%s] rank%d = %s\n", tag, i, t ? t : "?"); + } + fflush(stdout); +} +static char *g_clsreg[2048]; static int g_clsrn; +static const char *cls_name(void *jclass) { + if (!jclass) return "?"; + if ((unsigned long)jclass < 0x100000000UL) { + LOG("cls_name: suspicious token %p (caller lr=%p)\n", jclass, __builtin_return_address(0)); + return "?"; + } + { /* 调试:打印原始 token 与其首字 */ + static int dbg = -1; + if (dbg < 0) { const char *e = getenv("WETYPE_CLSDBG"); dbg = e ? atoi(e) : 0; } + if (dbg && dbg < 40) { + dbg++; + { const char *s = *(const char **)jclass; + char tmp[64]; int k; + for (k = 0; k < 40 && s && s[k]; k++) tmp[k] = (s[k] >= 32 && s[k] < 127) ? s[k] : '?'; + tmp[k] = 0; + LOG("cls_name(%p) -> %p \"%s\" [reg=%p regn=%d diff=%ld]\n", jclass, (void *)s, tmp, + (void *)&g_clsreg[0], g_clsrn, (long)((char *)jclass - (char *)&g_clsreg[0])); } + } + } + return *(const char **)jclass; +} + +/* ---------- --daemon 行协议状态 ---------- */ +static int g_daemon_mode = 0; +static int g_proto_fd = 1; /* 协议输出 fd(原 stdout) */ +static pthread_mutex_t g_cand_mu = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t g_cand_cv = PTHREAD_COND_INITIALIZER; +static unsigned long g_cand_callback_count = 0; +/* 候选事件队列:引擎异步搜索,一次 B 可能先收到旧输入的候选。每个事件带上 + * 同批 PendingInput.match 拼出的输入串,daemon 只回复与已发送按键一致的那个。 */ +#define CAND_QUEUE 32 +typedef struct { long it; int known; char input[256]; } CandEvent; +static CandEvent g_cand_q[CAND_QUEUE]; +static int g_cand_qn = 0; +static char g_pi_acc[256]; /* 当前批 PendingInput.match 累积(仅字母) */ +static char g_pi_last[256]; /* 最近一次完整 pendingInputs */ +static int g_pi_have = 0; +static long g_pend_it = 0; /* 已写入 newIterator、尚未回调的候选 */ +static int g_pend_known = 0; +static char g_pend_input[256]; +static void proto_printf(const char *fmt, ...) { + char b[8192]; va_list ap; va_start(ap, fmt); + int n = vsnprintf(b, sizeof b, fmt, ap); va_end(ap); + if (n > 0) { + ssize_t _w = write(g_proto_fd, b, (size_t)n); + if (_w < 0) { int e = errno; fprintf(stderr, "[proto] write FAIL fd=%d errno=%d\n", g_proto_fd, e); } + (void)_w; + } +} + +/* 引擎候选回调:只记录计数,不输出候选文本或内部指针。 */ +static long probe_listener(long a0, long a1, long a2, long a3) { + if (g_daemon_mode) { /* 通知 daemon:新候选事件到达 */ + pthread_mutex_lock(&g_cand_mu); + unsigned long callback = ++g_cand_callback_count; + long it = g_pend_it; + int known = g_pend_known; + int input_len = known ? (int)strlen(g_pend_input) : -1; + if (it) { + if (g_cand_qn == CAND_QUEUE) { /* daemon 长时间未取:丢最旧(泄漏一个 iterator) */ + memmove(g_cand_q, g_cand_q + 1, sizeof g_cand_q[0] * (CAND_QUEUE - 1)); + g_cand_qn--; + } + CandEvent *ev = &g_cand_q[g_cand_qn++]; + ev->it = it; + ev->known = known; + snprintf(ev->input, sizeof ev->input, "%s", g_pend_input); + g_pend_it = 0; + } + pthread_cond_broadcast(&g_cand_cv); + pthread_mutex_unlock(&g_cand_mu); + fprintf(stderr, "[engine] candidate callback #%lu input_len=%d known=%d\n", + callback, input_len, known); + } + return 0; +} + +static void *F_FindClass(void *env, const char *name) { + LOG("FindClass(\"%s\")\n", name); + for (int i = 0; i < g_clsrn; i++) if (!strcmp(g_clsreg[i], name)) { LOG(" -> %p (cached)\n", (void *)&g_clsreg[i]); return &g_clsreg[i]; } + if (g_clsrn < 2048) { g_clsreg[g_clsrn] = strdup(name); LOG(" -> %p (new)\n", (void *)&g_clsreg[g_clsrn]); return &g_clsreg[g_clsrn++]; } + LOG(" -> NULL (注册表满!)\n"); + return NULL; +} +static void *F_GetFieldID(void *env, void *cls, const char *name, const char *sig) { + LOG("GetFieldID(%s, %s, %s)\n", cls_name(cls), name, sig); + JIDToken *t = malloc(sizeof(JIDToken)); + t->name = strdup(name); + t->type = sig && sig[0] == 'L' ? 'o' : sig ? sig[0] : 'x'; + t->sig = strdup(sig ? sig : ""); + return t; +} +static void *F_GetStaticFieldID(void *env, void *cls, const char *name, const char *sig) { + return F_GetFieldID(env, cls, name, sig); +} +static void *F_GetObjectField(void *env, void *obj, JIDToken *id) { + LOG("GetObjectField(%s.%s)\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?"); + if (!obj) return NULL; + JField *f = obj_get((JObj *)obj, id->name); + if (f && (f->type == 'o' || f->type == 's')) { + if (f->type == 's') return str_obj((const char *)f->val); + return (void *)f->val; + } + /* auto-complete:缺失字段按签名生成空对象/空串/空数组,杜绝 null 入引擎 */ + const char *sig = id ? id->sig : ""; + if (!strcmp(sig, "Ljava/lang/String;")) return str_obj(""); + if (sig[0] == '[') { + static JArr empties[16]; static int en; + if (en < 16) { empties[en].elem = NULL; empties[en].len = 0; return &empties[en++]; } + return NULL; + } + if (sig[0] == 'L') { + static char clsnames[32][96]; static int cn; + if (cn < 32) { + const char *in = sig + 1; + char *dst = clsnames[cn]; + while (*in && *in != ';') *dst++ = *in++; + *dst = 0; + return obj_new(clsnames[cn++]); + } + } + return NULL; +} +static long F_GetIntField(void *env, void *obj, JIDToken *id) { + LOG("GetIntField(%s.%s)\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?"); + if (!obj) return 0; + JField *f = obj_get((JObj *)obj, id->name); + return f && f->type == 'i' ? (long)f->val : 0; +} +static long F_GetLongField(void *env, void *obj, JIDToken *id) { + LOG("GetLongField(%s.%s)\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?"); + if (!obj) return 0; + JField *f = obj_get((JObj *)obj, id->name); + return f && f->type == 'l' ? (long)f->val : 0; +} +static double F_GetFloatField(void *env, void *obj, JIDToken *id) { + if (!obj) return 0; + JField *f = obj_get((JObj *)obj, id->name); + return f && f->type == 'f' ? *(const float *)f->val : 0; +} +static long F_GetBooleanField(void *env, void *obj, JIDToken *id) { + if (!obj) return 0; + JField *f = obj_get((JObj *)obj, id->name); + return f && f->type == 'z' ? (long)f->val : 0; +} +static const char *F_GetStringUTFChars(void *env, void *jstr, unsigned char *isCopy) { + if (isCopy) *isCopy = 1; + if (!jstr) return NULL; + JField *f = obj_get((JObj *)jstr, ".str"); + const char *s = f ? (const char *)f->val : ""; + char *copy = strdup(s); /* 消费者/引擎会 free,必须 malloc */ + LOG("GetStringUTFChars -> \"%s\" (%p)\n", copy, (void *)copy); + return copy; +} +static void F_ReleaseStringUTFChars(void *env, void *jstr, const char *c) { + /* no-op:胶水可能先存指针再 Release,提前 free 会产生悬空指针 */ +} +static void *F_NewStringUTF(void *env, const char *s) { + LOG("NewStringUTF(\"%s\")\n", s ? s : ""); + return str_obj(s ? s : ""); +} +static void *F_GetMethodID(void *env, void *cls, const char *name, const char *sig) { + LOG("GetMethodID(%s, %s, %s)\n", cls_name(cls), name, sig); + JIDToken *t = malloc(sizeof(JIDToken)); + t->name = strdup(name); t->type = 'm'; + return t; +} +static void *F_CallObjectMethod(void *env, void *obj, JIDToken *id, ...) { + LOG("CallObjectMethod(%s.%s) -> null\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?"); + /* 常见 getter 罐头:对 InitInfo 的方法一律回 null;后续按日志补充 */ + return NULL; +} +static void F_CallVoidMethod(void *env, void *obj, JIDToken *id, ...) { + LOG("CallVoidMethod(%s.%s)\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?"); +} +static long F_CallIntMethod(void *env, void *obj, JIDToken *id, ...) { + LOG("CallIntMethod(%s.%s) -> 0\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?"); + return 0; +} +static void *F_NewGlobalRef(void *env, void *o) { return o; } +/* 判断是否为模拟 jobject。不要依赖 g_objs:那只是有界诊断目录。 */ +static int is_jobj(void *p) { + if (!p) return 0; + return ((JObj *)p)->magic == JO_MAGIC; +} +/* 引擎在每批候选回调前推送 PendingInput[],其 match 串拼起来就是本次候选对应的输入。 + * 这里在引擎线程里累积,写 newIterator 时与该 iterator 绑定。 */ +static void pending_input_field(const char *name, void *val) { + if (!strcmp(name, "match")) { + JField *sf = is_jobj(val) ? obj_get((JObj *)val, ".str") : NULL; + if (!sf || !sf->val) return; + pthread_mutex_lock(&g_cand_mu); + size_t n = strlen(g_pi_acc); + for (const char *p = sf->val; *p && n + 1 < sizeof g_pi_acc; ++p) + if (*p >= 'a' && *p <= 'z') g_pi_acc[n++] = *p; + g_pi_acc[n] = 0; + pthread_mutex_unlock(&g_cand_mu); + } else if (!strcmp(name, "pendingInputs")) { + pthread_mutex_lock(&g_cand_mu); + memcpy(g_pi_last, g_pi_acc, sizeof g_pi_last); + g_pi_acc[0] = 0; + g_pi_have = 1; + pthread_mutex_unlock(&g_cand_mu); + } +} +static void F_SetObjectField(void *env, void *obj, JIDToken *id, void *val) { + LOG("SetObjectField(%s.%s)\n", is_jobj(obj) ? ((JObj *)obj)->cls : "?", id ? id->name : "?"); + if (!is_jobj(obj)) return; + JObj *o = (JObj *)obj; + if (g_daemon_mode && id) pending_input_field(id->name, val); + if (is_jobj(val)) { + JField *sf = obj_get((JObj *)val, ".str"); + if (sf) obj_set(o, id->name, 's', sf->val); + else obj_set(o, id->name, 'o', val); + } else { + obj_set(o, id->name, 'o', val); + } +} +static void F_SetIntField(void *env, void *obj, JIDToken *id, long v) { + LOG("SetIntField(%s.%s = %ld)\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?", v); + if (obj) obj_set((JObj *)obj, id->name, 'i', (void *)v); +} +static long g_last_iterator = 0; /* 胶水层写入 CandidateList.newIterator 时捕获 */ +static void F_SetLongField(void *env, void *obj, JIDToken *id, long v) { + LOG("SetLongField(%s.%s = %ld)\n", is_jobj(obj) ? ((JObj *)obj)->cls : "null", id ? id->name : "?", v); + if (id && !strcmp(id->name, "newIterator") && v) { + g_last_iterator = v; + if (g_daemon_mode) { + pthread_mutex_lock(&g_cand_mu); + g_pend_it = v; + g_pend_known = g_pi_have; + memcpy(g_pend_input, g_pi_last, sizeof g_pend_input); + g_pi_have = 0; + g_pi_acc[0] = 0; + pthread_mutex_unlock(&g_cand_mu); + } + printf("*** 捕获 newIterator = %#lx ***\n", (unsigned long)v); + fflush(stdout); + } + if (obj) obj_set((JObj *)obj, id->name, 'l', (void *)v); +} +static void F_SetFloatField(void *env, void *obj, JIDToken *id, double v) { + LOG("SetFloatField(%s.%s = %f)\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?", v); + if (obj) { + float fv = (float)v; + obj_set((JObj *)obj, id->name, 'f', &fv); /* 注意:栈地址,仅调试用 */ + } +} +static void F_SetBooleanField(void *env, void *obj, JIDToken *id, long v) { + LOG("SetBooleanField(%s.%s = %ld)\n", obj ? ((JObj *)obj)->cls : "null", id ? id->name : "?", v); + if (obj) obj_set((JObj *)obj, id->name, 'z', (void *)v); +} +static void *F_AllocObject(void *env, void *cls) { + LOG("AllocObject(%s)\n", cls_name(cls)); + return obj_new(cls_name(cls)); +} +static void *F_NewObject(void *env, void *cls, void *mid, void *args) { + const char *cn = cls_name(cls); + LOG("NewObject(%s)\n", cn); + if (cn && !strcmp(cn, "java/lang/String") && g_last_bytes) { + { /* 新构造的 String:用最近创建的 byte[] 还原文本 */ + JBytes *b = g_last_bytes; + long n = (b->len > 0 && b->len < (1 << 20)) ? b->len : 0; + char *str = calloc(1, (size_t)n + 1); + if (b->data && n > 0) memcpy(str, b->data, (size_t)n); + JObj *o = obj_new("java/lang/String"); + obj_set(o, ".str", 's', str); + printf("[newJstring] \"%s\"\n", str); + fflush(stdout); + return o; + } + } + return obj_new(cn); +} +static void *F_GetStaticMethodID(void *env, void *cls, const char *name, const char *sig) { + LOG("GetStaticMethodID(%s, %s, %s)\n", cls_name(cls), name, sig); + JIDToken *t = malloc(sizeof(JIDToken)); + t->name = strdup(name); t->type = 'm'; + return t; +} +static void *F_GetStaticObjectField(void *env, void *cls, JIDToken *id) { + LOG("GetStaticObjectField(%s.%s) -> null\n", cls_name(cls), id ? id->name : "?"); + return NULL; +} +static long F_GetStaticIntField(void *env, void *cls, JIDToken *id) { + LOG("GetStaticIntField(%s.%s) -> 0\n", cls_name(cls), id ? id->name : "?"); + return 0; +} +static void *F_GetObjectRefType(void *env, void *o) { return (void *)1L; } + +/* RegisterNatives(env, cls, methods[], n):把 Java↔Native 映射全部打印出来。 + JNINativeMethod = { const char* name; const char* sig; void* fnPtr; } */ +typedef struct { const char *name; const char *sig; void *fn; } JNMethod; +static long F_RegisterNatives(void *env, void *cls, const JNMethod *methods, long n) { + LOG("RegisterNatives(%s, %ld methods)\n", cls_name(cls), n); + for (long i = 0; i < n; i++) + LOG(" [%ld] %s%s <- %p\n", i, methods[i].name, methods[i].sig, methods[i].fn); + return 0; /* JNI_OK */ +} +static void *F_GetDirectBufferAddress(void *env, void *buf) { return NULL; } +static void F_DeleteGlobalRef(void *env, void *o) { } +static void F_DeleteLocalRef(void *env, void *o) { } +static void *F_NewLocalRef(void *env, void *o) { return o; } +static void *F_ExceptionOccurred(void *env) { return NULL; } +static void F_ExceptionClear(void *env) { } +static unsigned char F_ExceptionCheck(void *env) { return 0; } +static long F_GetJavaVM(void *env, void **vm) { LOG("GetJavaVM\n"); static void *fakevm[32]; *vm = fakevm; return 0; } + +/* 伪 JavaVM:JNI_OnLoad 会调 GetEnv(槽 6,双重间接同 JNIEnv) */ +static void *g_env; /* 前向声明:定义在 env 布表区 */ +static void tab_v(int i, void *fn); +static void *vmtab[32]; +static void *vmptr; +static long V_GetEnv(void *vm, void **penv, long version) { + LOG("JavaVM->GetEnv(%#lx)\n", version); + *penv = g_env; + return 0; /* JNI_OK */ +} +static long V_AttachCurrentThread(void *vm, void **penv, void *args) { + LOG("AttachCurrentThread\n"); + *penv = g_env; + return 0; +} +static long V_DetachCurrentThread(void *vm) { return 0; } +static long V_DestroyJavaVM(void *vm) { return 0; } +static void build_vm(void) { + for (int i = 0; i < 32; i++) vmtab[i] = (void *)stub_default; + tab_v(3, V_DestroyJavaVM); + tab_v(4, V_AttachCurrentThread); + tab_v(5, V_DetachCurrentThread); + tab_v(6, V_GetEnv); + tab_v(7, V_AttachCurrentThread); + vmptr = vmtab; +} +typedef long (*onload_fn)(void *vm, void *reserved); +static void tab_v(int i, void *fn) { if (i >= 0 && i < 32) vmtab[i] = fn; } +static long F_GetArrayLength(void *env, void *arr) { + long n = 0; + if (arr) { + if (((JBytes *)arr)->magic == JB_MAGIC) n = ((JBytes *)arr)->len; /* byte[] */ + else n = ((JArr *)arr)->len; /* 对象数组 */ + } + LOG("GetArrayLength -> %ld\n", n); + return n; +} +static void *F_NewObjectArray(void *env, long len, void *cls, void *init) { + LOG("NewObjectArray(%ld, %s)\n", len, cls_name(cls)); + JArr *a = malloc(sizeof(JArr)); + a->len = (int)len; + a->elem = calloc(len > 0 ? len : 1, sizeof(void *)); + return a; +} +static void F_SetObjectArrayElement(void *env, void *arr, long idx, void *v) { + LOG("SetObjectArrayElement[%ld]\n", idx); + JArr *a = arr; + if (a && idx >= 0 && idx < a->len) a->elem[idx] = v; +} +static void dump_obj(JObj *o) { + if (!o) { printf(" \n"); return; } + printf(" %s {\n", o->cls); + for (int i = 0; i < o->n; i++) { + if (o->f[i].name[0] == '.') continue; + if (o->f[i].type == 's') printf(" %s = \"%s\"\n", o->f[i].name, (const char *)o->f[i].val); + else if (o->f[i].type == 'i' || o->f[i].type == 'l' || o->f[i].type == 'z') + printf(" %s = %ld\n", o->f[i].name, (long)o->f[i].val); + else if (o->f[i].type == 'f') printf(" %s = %f\n", o->f[i].name, *(float *)o->f[i].val); + else if (is_jobj((void *)o->f[i].val)) { + JObj *sv = (JObj *)o->f[i].val; + JField *sf = obj_get(sv, ".str"); + if (sf) printf(" %s = \"%s\"\n", o->f[i].name, (const char *)sf->val); + else { + printf(" %s = obj@%p n=%d cls=%p fields:", o->f[i].name, (void *)sv, sv->n, (void *)sv->cls); + for (int k = 0; k < sv->n; k++) + printf(" [%s:%c=%p]", sv->f[k].name ? sv->f[k].name : "?", sv->f[k].type, (void *)sv->f[k].val); + printf("\n"); + } + } else printf(" %s = %p\n", o->f[i].name, o->f[i].val); + } + printf(" }\n"); +} +static void *F_GetObjectArrayElement(void *env, void *arr, long idx) { + JArr *a = arr; + LOG("GetObjectArrayElement[%ld/%d]\n", idx, a ? a->len : -1); + return (a && idx >= 0 && idx < a->len) ? a->elem[idx] : NULL; +} +static void *F_GetObjectClass(void *env, void *o) { + LOG("GetObjectClass(%p, isjobj=%d)\n", o, is_jobj(o)); + if (!o) return NULL; + JObj *jo = (JObj *)o; + void *r = F_FindClass(env, jo->cls); + LOG(" -> %p\n", r); + return r; +} +static void *F_NewObjectV(void *env, void *cls, void *mid, void *args) { LOG("NewObjectV(%s)\n", cls_name(cls)); return NULL; } +static long F_GetVersion(void *env) { return 0x00010006; /* JNI 1.6 */ } +static long F_EnsureLocalCapacity(void *env, long n) { return 0; } +static long F_PushLocalFrame(void *env, long n) { return 0; } +static void *F_PopLocalFrame(void *env, void *r) { return r; } + +/* 字节数组:引擎配置可能传 dict 文件内容 */ +static void *F_NewByteArray(void *env, long len) { + LOG("NewByteArray(%ld)\n", len); + JBytes *b = malloc(sizeof(JBytes)); + b->magic = JB_MAGIC; b->len = len; b->data = len > 0 ? calloc(1, len) : NULL; + g_last_bytes = b; + return b; +} +static void F_SetByteArrayRegion(void *env, void *arr, long start, long len, const void *buf) { + JBytes *b = (JBytes *)arr; + LOG("SetByteArrayRegion(start=%ld, len=%ld)\n", start, len); + if (!b || !b->data || !buf || start < 0 || len < 0 || start + len > b->len) return; + memcpy(b->data + start, buf, (size_t)len); +} +static void *F_GetByteArrayElements(void *env, void *arr, unsigned char *isCopy) { + JBytes *b = arr; + LOG("GetByteArrayElements(%ld bytes)\n", b ? b->len : -1); + if (isCopy) *isCopy = 0; + return b ? b->data : NULL; +} +static void F_ReleaseByteArrayElements(void *env, void *arr, void *e, long mode) { } + +/* 布表:JNI env 是双重间接(env → 表指针 → 表),g_env 必须指向表指针 */ +static void *envtab[ENV_SLOTS]; +static void *envptr; +static void *g_env = &envptr; + +static void tab(int i, void *fn) { if (i >= 0 && i < ENV_SLOTS) envtab[i] = fn; } + +static void build_env(void) { + for (int i = 0; i < ENV_SLOTS; i++) envtab[i] = (void *)stub_default; + envptr = envtab; + tab(3, F_GetVersion); + tab(4, F_GetVersion); /* 双保险 */ + tab(5, F_FindClass); tab(6, F_FindClass); /* 观测确认 6 */ + tab(20, F_NewGlobalRef); + tab(21, F_DeleteGlobalRef); + tab(22, F_DeleteLocalRef); + tab(23, F_NewLocalRef); + tab(14, F_ExceptionOccurred); + tab(16, F_ExceptionClear); + tab(25, F_ExceptionCheck); + tab(31, F_GetObjectClass); + tab(32, F_GetMethodID); tab(33, F_GetMethodID); /* 观测未定,双挂 */ + tab(34, F_CallObjectMethod); + tab(61, F_CallVoidMethod); tab(60, F_CallVoidMethod); + tab(49, F_CallIntMethod); + tab(93, F_GetStaticFieldID); + tab(94, F_GetFieldID); /* 观测确认 */ + tab(95, F_GetObjectField); /* 观测确认 */ + tab(96, F_GetBooleanField); + tab(100, F_GetIntField); + tab(101, F_GetLongField); + tab(102, F_GetFloatField); + tab(167, F_NewStringUTF); + tab(169, F_GetStringUTFChars); /* 观测确认 */ + tab(170, F_ReleaseStringUTFChars); + tab(171, F_GetArrayLength); + /* 标准 JNI 表:Set* 段 104..112(之前错位 +2,导致胶水层字段写入全丢) */ + tab(104, F_SetObjectField); + tab(105, F_SetBooleanField); + tab(109, F_SetIntField); + tab(110, F_SetLongField); + tab(111, F_SetFloatField); + tab(172, F_NewObjectArray); + tab(173, F_GetObjectArrayElement); + tab(174, F_SetObjectArrayElement); + tab(26, F_AllocObject); + tab(27, F_NewObject); tab(28, F_NewObject); tab(29, F_NewObject); + tab(113, F_GetStaticMethodID); + tab(142, F_GetStaticObjectField); + tab(143, F_GetStaticIntField); + tab(208, F_SetByteArrayRegion); + tab(230, F_GetDirectBufferAddress); + tab(215, F_RegisterNatives); + tab(232, F_GetObjectRefType); + tab(176, F_NewByteArray); + tab(184, F_GetByteArrayElements); + tab(186, F_ReleaseByteArrayElements); + tab(219, F_GetJavaVM); +} + +static JObj g_sesscfg; /* daemon 重建会话复用 */ + +/* ---------- daemon:候选缓存与会话管理 ---------- */ +#define MAX_CAND 72 +static char g_ct[MAX_CAND][256]; /* 候选文本 */ +static JBytes *g_cid[MAX_CAND]; /* 候选 id byte[] */ +static int g_ccover[MAX_CAND]; /* 候选覆盖的输入字母数(cover_input_len) */ +static int g_ct_n = 0; +static long g_cur_it = 0; /* 当前 iterator(上一轮取过候选后保留) */ + +/* 引擎每次最多返回 10 个;连续分批读取并缓存 text+id 供 SEL。 */ +static int daemon_fetch_cands(void *sym_cg, void *sym_dci, long it) { + g_ct_n = 0; + if (!sym_cg || !it) return 0; + for (int batch = 0; batch < MAX_CAND / 10 && g_ct_n < MAX_CAND; ++batch) { + JArr *a = (JArr *)((void *(*)(void *, void *, long, int))sym_cg)(g_env, NULL, it, 10); + if (!a || a->len <= 0) break; + const int before = g_ct_n; + for (int i = 0; i < a->len && g_ct_n < MAX_CAND; i++) { + JObj *c = (JObj *)a->elem[i]; + const char *t = cand_text(c); + if (!t || !*t) continue; + snprintf(g_ct[g_ct_n], sizeof g_ct[0], "%s", t); + JField *idf = obj_get(c, "id"); + g_cid[g_ct_n] = (idf && idf->val) ? (JBytes *)idf->val : NULL; + JField *cf = obj_get(c, "cover_input_len"); + g_ccover[g_ct_n] = (cf && cf->type == 'i') ? (int)(long)cf->val : 0; + g_ct_n++; + } + if (a->len < 10 || g_ct_n == before) break; + } + /* 旧 iterator 归还引擎 */ + if (g_cur_it && g_cur_it != it && sym_dci) + ((void (*)(void *, void *, long))sym_dci)(g_env, NULL, g_cur_it); + g_cur_it = it; + return g_ct_n; +} + +static void daemon_free_it(void *sym_dci, long it) { + if (it && it != g_cur_it && sym_dci) ((void (*)(void *, void *, long))sym_dci)(g_env, NULL, it); +} + +/* 释放队列中尚未取走的候选事件(上一轮迟到的回调)。 */ +static void daemon_drop_events(void *sym_dci) { + CandEvent evs[CAND_QUEUE]; + pthread_mutex_lock(&g_cand_mu); + int n = g_cand_qn; + memcpy(evs, g_cand_q, sizeof evs[0] * n); + g_cand_qn = 0; + pthread_mutex_unlock(&g_cand_mu); + for (int i = 0; i < n; i++) daemon_free_it(sym_dci, evs[i].it); + if (n) fprintf(stderr, "[daemon] dropped %d late candidate events\n", n); +} + +static long mono_ms(void) { + struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; +} + +/* 等与 expected(C 以来发送的全部字母)一致的候选并返回其 iterator。 + * 引擎按搜索完成顺序回调,旧输入的候选可能先到:释放它们并继续等;长批量输入 + * 在两次搜索之间可能静默数百毫秒,所以已知输入只以 timeout_ms 为限。 + * expected 为空(部分选词后剩余串未知)时,最后一次回调后 quiet_ms 内无新回调 + * 即退回最新候选。超时退回最新候选,仍无回调返回 0。 */ +static long daemon_wait_cand(const char *expected, int timeout_ms, int quiet_ms, + void *sym_dci, int *exact) { + const long t0 = mono_ms(); + long best = 0, last_event = 0; + int skipped = 0; + *exact = 0; + pthread_mutex_lock(&g_cand_mu); + for (;;) { + if (g_cand_qn) { + CandEvent evs[CAND_QUEUE]; + int n = g_cand_qn; + memcpy(evs, g_cand_q, sizeof evs[0] * n); + g_cand_qn = 0; + pthread_mutex_unlock(&g_cand_mu); + for (int i = 0; i < n; i++) { + if (best) { daemon_free_it(sym_dci, best); skipped++; } + best = evs[i].it; + *exact = evs[i].known && !strcmp(evs[i].input, expected); + if (!*exact) + fprintf(stderr, "[daemon] candidate event input_len=%d known=%d sent_len=%zu (not current)\n", + evs[i].known ? (int)strlen(evs[i].input) : -1, evs[i].known, strlen(expected)); + } + last_event = mono_ms(); + if (*exact) break; + pthread_mutex_lock(&g_cand_mu); + continue; + } + const long now = mono_ms(); + long until = t0 + timeout_ms; + if (best && !*expected && last_event + quiet_ms < until) until = last_event + quiet_ms; + if (now >= until) { pthread_mutex_unlock(&g_cand_mu); break; } + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += (until - now) / 1000; + ts.tv_nsec += ((until - now) % 1000) * 1000000L; + if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; } + pthread_cond_timedwait(&g_cand_cv, &g_cand_mu, &ts); + } + fprintf(stderr, "[daemon] wait_cand took %ld ms exact=%d skipped=%d found=%d\n", + mono_ms() - t0, *exact, skipped, best != 0); + return best; +} + +/* 输入一个键:op='d'/'u' */ +static void daemon_key(void *sym_pi, long sid, char op, const char *payload) { + static char buf[64]; + snprintf(buf, sizeof buf, "%c %s", op, payload); + JObj in; memset(&in, 0, sizeof in); in.cls = "java/lang/String"; + obj_set(&in, ".str", 's', buf); + ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid, &in, NULL); +} + +/* 新建会话并挂探针 */ +static long daemon_new_session(void *sym_cs, void *sym_asl) { + long sid = ((long (*)(void *, void *, void *))sym_cs)(g_env, NULL, &g_sesscfg); + if (sid > 0 && sym_asl) + ((void (*)(long, void *, void *))sym_asl)(sid, (void *)probe_listener, (void *)0x1234); + return sid; +} + +/* 回复候选行。spans 模式下每项为 "<覆盖字母数>:<文本>",供前端部分选词。 */ +static void daemon_reply_cands(int got, int spans) { + if (got > 0) { + proto_printf("CAND"); + fprintf(stderr, "[daemon] response=CAND count=%d iterator=%#lx\n", g_ct_n, g_cur_it); + for (int i = 0; i < g_ct_n; i++) { + if (spans) proto_printf("\t%d:%s", g_ccover[i], g_ct[i]); + else proto_printf("\t%s", g_ct[i]); + } + proto_printf("\n"); + } else { + proto_printf("EMPTY\n"); + } + fflush(NULL); +} + +/* ---------- daemon 主循环 ---------- */ +static void run_daemon(void *h, long sid) { + void *sym_pi = dlsym(h, "_Z13process_inputP7_JNIEnvP8_jobjectlP8_jstringP11_jbyteArray"); + void *sym_cg = dlsym(h, "_Z15candidate_get_nP7_JNIEnvP8_jobjectli"); + void *sym_sc = dlsym(h, "_Z16select_candidateP7_JNIEnvP8_jobjectlP8_jstringP11_jbyteArrayS4_S6_P13_jobjectArrayS2_"); + void *sym_cs = dlsym(h, "_Z14create_sessionP7_JNIEnvP8_jobjectS2_"); + void *sym_ds = dlsym(h, "_Z15destroy_sessionP7_JNIEnvP8_jobjectl"); + void *sym_asl = dlsym(h, "wxime_add_session_listener"); + void *sym_dci = dlsym(h, "_Z17delete_candidate_iteratorP7_JNIEnvP8_jobjectl"); + if (!sym_dci) sym_dci = dlsym(h, "delete_candidate_iterator"); + + char line[512]; + char sent[256] = ""; /* C 以来发送的字母,用于识别当前输入的候选 */ + size_t sent_n = 0; + int sent_known = 1; /* 0: 部分选词或超长后无法与 PendingInput 对齐 */ + int spans = 0; /* OPT spans: 候选带覆盖长度,S 部分选词回复剩余候选 */ + proto_printf("READY\n"); + while (fgets(line, sizeof line, stdin)) { + size_t L = strlen(line); + while (L && (line[L-1] == '\n' || line[L-1] == '\r')) line[--L] = 0; + if (L == 0) continue; + fprintf(stderr, "[daemon] command=%c bytes=%zu session=%ld\n", + line[0], L, sid); + if (!strcmp(line, "Q")) break; + if (!strcmp(line, "PING")) { proto_printf("PONG\n"); fflush(NULL); fprintf(stderr, "[daemon] -> PONG\n"); continue; } + if (!strcmp(line, "OPT spans")) { spans = 1; proto_printf("OK\n"); fflush(NULL); continue; } + if (!strcmp(line, "SAVE")) { proto_printf("OK\n"); fflush(NULL); continue; } /* 选词时引擎已落盘 */ + if ((line[0] == 'L' || line[0] == 'B') && line[1] == ' ') { + /* L 单键兼容;B 把防抖窗口内的字母合并,只在末尾取一次候选。 */ + const char *keys = line + 2; + if (!*keys || !sid) { proto_printf("EMPTY\n"); fflush(NULL); continue; } + daemon_drop_events(sym_dci); + for (const char *p = keys; *p; ++p) { + char key[2] = {*p, '\0'}; + daemon_key(sym_pi, sid, 'd', key); + daemon_key(sym_pi, sid, 'u', key); /* d→u 紧跟, 引擎按序处理 */ + if (sent_known && sent_n + 1 < sizeof sent) { sent[sent_n++] = *p; sent[sent_n] = 0; } + else sent_known = 0; + if (line[0] == 'L') break; + } + + int exact = 0; + long it = daemon_wait_cand(sent_known ? sent : "", 2500, 300, sym_dci, &exact); + int got = it ? daemon_fetch_cands(sym_cg, sym_dci, it) : -1; + fprintf(stderr, "[daemon] input batch chars=%zu composition_len=%zu callbacks=%lu exact=%d iterator=%#lx candidates=%d\n", + strlen(keys), sent_n, g_cand_callback_count, exact, it, got); + daemon_reply_cands(got, spans); + continue; + } + /* S 选词。spans 模式下若候选只覆盖前缀,引擎保留剩余拼音并重新搜索: + * 回复剩余部分的 CAND/EMPTY;整段上屏仍回复 OK。 */ + if (line[0] == 'S') { + int idx = atoi(line + 1); + fprintf(stderr, "[daemon] select index=%d candidate_count=%d\n", idx, g_ct_n); + if (idx < 0 || idx >= g_ct_n || !g_cid[idx]) { proto_printf("ERR\n"); fflush(NULL); continue; } + static JObj sel; memset(&sel, 0, sizeof sel); sel.cls = "java/lang/String"; + obj_set(&sel, ".str", 's', g_ct[idx]); + const int cover = g_ccover[idx]; + const int partial = spans && sent_known && cover > 0 && (size_t)cover < sent_n; + daemon_drop_events(sym_dci); + ((void (*)(void *, void *, long, void *, void *, void *, void *, void *, void *, void *))sym_sc) + (g_env, NULL, sid, &sel, g_cid[idx], NULL, NULL, NULL, NULL, NULL); + if (!partial) { + sent_n = 0; sent[0] = 0; sent_known = 0; /* 剩余串未知,按静默回退 */ + proto_printf("OK\n"); + fflush(NULL); + continue; + } + sent_n -= (size_t)cover; + memmove(sent, sent + cover, sent_n + 1); + int exact = 0; + long it = daemon_wait_cand(sent, 2500, 300, sym_dci, &exact); + int got = it ? daemon_fetch_cands(sym_cg, sym_dci, it) : -1; + fprintf(stderr, "[daemon] partial select cover=%d rest_len=%zu exact=%d candidates=%d\n", + cover, sent_n, exact, got); + daemon_reply_cands(got, spans); + continue; + } + if (!strcmp(line, "C") && sym_cs && sym_ds) { /* C 清空输入(重建会话) */ + fprintf(stderr, "[daemon] reset begin old_session=%ld iterator=%#lx\n", sid, g_cur_it); + daemon_drop_events(sym_dci); + if (g_cur_it && sym_dci) { ((void (*)(void *, void *, long))sym_dci)(g_env, NULL, g_cur_it); g_cur_it = 0; } + ((void (*)(void *, void *, long))sym_ds)(g_env, NULL, sid); + usleep(50000); + sid = daemon_new_session(sym_cs, sym_asl); + g_ct_n = 0; g_last_iterator = 0; + sent_n = 0; sent[0] = 0; sent_known = 1; + fprintf(stderr, "[daemon] reset end new_session=%ld\n", sid); + proto_printf("OK\n"); + fflush(NULL); + continue; + } + proto_printf("ERR\n"); + fflush(NULL); + } + if (g_cur_it && sym_dci) ((void (*)(void *, void *, long))sym_dci)(g_env, NULL, g_cur_it); + if (sid > 0 && sym_ds) { /* 销毁会话促使引擎落盘用户词库 */ + ((void (*)(void *, void *, long))sym_ds)(g_env, NULL, sid); + usleep(300000); + } + proto_printf("BYE\n"); + fflush(NULL); + _exit(0); +} + +/* ---------- main ---------- */ +typedef int (*init_fn)(void *env, void *thiz, void *info); + +int main(int argc, char **argv) { + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); + for (int i = 1; i < argc; i++) + if (!strcmp(argv[i], "--daemon")) g_daemon_mode = 1; + if (g_daemon_mode) { + g_verbose = 0; /* [env] 日志全关 */ + g_proto_fd = dup(1); /* 协议走原 stdout */ + dup2(2, 1); /* 引擎/库的所有 stdout 输出 → stderr */ + setvbuf(stdout, NULL, _IONBF, 0); + } + const char *jni_lib = argc > 1 ? argv[1] : "runtime/libwxhld_jni.so"; + g_verbose = argc > 2 ? atoi(argv[2]) : 1; + if (g_daemon_mode) g_verbose = 0; + + { + char shimpath[1024]; + const char *libdir = getenv("WETYPE_LIB_DIR"); + if (g_daemon_mode && libdir && *libdir) + snprintf(shimpath, sizeof shimpath, "%s/libwetype-shim.so", libdir); + else + snprintf(shimpath, sizeof shimpath, "runtime/libwetype-shim.so"); + dlopen(shimpath, RTLD_NOW | RTLD_GLOBAL); /* 提升到全局:引擎 dlsym("free") 命中 mmap 感知版 */ + } + void *h = dlopen(jni_lib, RTLD_NOW); + if (!h) { printf("dlopen %s FAILED: %s\n", jni_lib, dlerror()); return 1; } + printf("dlopen ok: %s\n", jni_lib); + + void *sym = dlsym(h, "_Z10initializeP7_JNIEnvP8_jobjectS2_"); + if (!sym) { printf("dlsym initialize FAILED: %s\n", dlerror()); return 1; } + printf("initialize @ %p\n", sym); + + build_env(); + build_vm(); + + /* 打印全部模块基址(崩溃地址归因用) */ + { + struct link_map *lm = NULL; + if (!dlinfo(h, RTLD_DI_LINKMAP, &lm) && lm) { + for (; lm; lm = lm->l_next) + if (lm->l_name && *lm->l_name) + printf("[map] %p %s\n", (void *)lm->l_addr, lm->l_name); + fflush(stdout); + } + } + build_vm(); + + /* 先走 JNI_OnLoad(注册日志回调/Native 方法表),再调 initialize */ + void *sym_onload = dlsym(h, "JNI_OnLoad"); + if (sym_onload) { + int vr = ((onload_fn)sym_onload)((void *)&vmptr, NULL); + printf("JNI_OnLoad -> %#x\n", vr); + fflush(stdout); + } + + /* 罐头 InitInfo:字段名来自胶水运行时自报家门 */ + memset(&g_initinfo, 0, sizeof g_initinfo); + g_initinfo.magic = JO_MAGIC; + g_initinfo.cls = CLS_INITINFO; + static int platform_val = 1, devperf = 2; + obj_set(&g_initinfo, "platform", 'i', (void *)(long)platform_val); + obj_set(&g_initinfo, "uin", 's', "123456789012345"); + { + const char *wd = getenv("WETYPE_WORK_DIR"); + if (!wd || !*wd) wd = "/tmp/wetype-work"; + obj_set(&g_initinfo, "workDir", 's', wd); + const char *sp = getenv("WETYPE_ASSET_DIR"); + if (!sp || !*sp) sp = ".deps/wechat-ime/assets"; + obj_set(&g_initinfo, "sourcePath", 's', sp); + } + obj_set(&g_initinfo, "appVer", 's', "3.5.4"); + obj_set(&g_initinfo, "systemVersion", 's', "linux-6.1"); + obj_set(&g_initinfo, "deviceName", 's', "aarch64-linux"); + obj_set(&g_initinfo, "devicePerformance", 'i', (void *)(long)devperf); + obj_set(&g_initinfo, "logLevel", 'i', (void *)(long)0); + obj_set(&g_initinfo, "packageType", 'i', (void *)(long)0); + obj_set(&g_initinfo, "debugLogConfig", 's', "{}"); + /* WevisDeviceScoreInfo:浮点分数不能为 0,否则 BLAS 零尺寸崩溃 */ + { + static JObj wevis; static float cpu_s = 1.0f, gpu_s = 1.0f; + memset(&wevis, 0, sizeof wevis); + wevis.cls = "com/tencent/wxhld/info/WevisDeviceScoreInfo"; + obj_set(&wevis, "cpu_score", 'f', &cpu_s); + obj_set(&wevis, "gpu_score", 'f', &gpu_s); + obj_set(&g_initinfo, "wevisDeviceScoreInfo", 'o', &wevis); + } + + printf("calling initialize(env, NULL, InitInfo{platform=1,user_id=10000001})...\n"); + fflush(stdout); + int r = ((init_fn)sym)(g_env, NULL, &g_initinfo); + printf("initialize -> %d (0x%x)\n", r, r); + fflush(stdout); + + /* 等引擎异步初始化日志 */ + printf("--- brief async init wait ---\n"); + fflush(stdout); + usleep(300000); + + /* 词库加载:DictInfo{ path, id:I(type), version:I, assetManager },元数据来自 index.json */ + void *sym_cd = dlsym(h, "_Z11config_dictP7_JNIEnvP8_jobjectP13_jobjectArrayP8_jstring"); + if (sym_cd) { + const char *dict_dir = getenv("WETYPE_DICT_DIR"); + if (!dict_dir || !*dict_dir) + dict_dir = ".deps/wechat-ime/assets/config/beta"; + static void *elems[64]; + int dn = 0; + /* 环境变量 WETYPE_SKIP_DICTS="a.bin,b.bin" 可跳过指定词库(二分定位用) */ + const char *skip = getenv("WETYPE_SKIP_DICTS"); + char skips[512]; skips[0] = 0; + if (skip) snprintf(skips, sizeof skips, "%s", skip); + /* hp_base(超参)必须最先加载:图初始化依赖超参先行 */ + unsigned order[64], on = 0; + for (unsigned i = 0; i < sizeof(g_dict_table)/sizeof(g_dict_table[0]); i++) + if (!strcmp(g_dict_table[i].name, "hp_base.bin")) order[on++] = i; + for (unsigned i = 0; i < sizeof(g_dict_table)/sizeof(g_dict_table[0]); i++) + if (strcmp(g_dict_table[i].name, "hp_base.bin")) order[on++] = i; + for (unsigned ii = 0; + ii < sizeof(g_dict_table)/sizeof(g_dict_table[0]) && dn < 64; ii++) { + unsigned i = order[ii]; + static char paths[64][600]; + if (skip && !strcmp(skip, "ALL")) { printf(" [skip] %s\n", g_dict_table[i].name); continue; } + if (skip) { + char tmp[512]; snprintf(tmp, sizeof tmp, "%s", skips); + int dropped = 0; + for (char *tok = strtok(tmp, ","); tok; tok = strtok(NULL, ",")) + if (!strcmp(tok, g_dict_table[i].name)) { dropped = 1; break; } + if (dropped) { printf(" [skip] %s\n", g_dict_table[i].name); continue; } + } + JObj *di = obj_new("com/tencent/wxhld/info/DictInfo"); + snprintf(paths[dn], sizeof paths[dn], "%s/%s", dict_dir, g_dict_table[i].name); + obj_set(di, "path", 's', paths[dn]); + obj_set(di, "id", 'i', (void *)(long)g_dict_table[i].type); + obj_set(di, "version", 'i', (void *)(long)g_dict_table[i].version); + elems[dn] = di; + dn++; + } + static JArr g_arr; g_arr.elem = elems; g_arr.len = dn; + printf("calling config_dict(%d dicts)...\n", dn); + fflush(stdout); + if (mkdir("/tmp/wetype-work", 0755) && errno != EEXIST) {} + static char udpath[600]; + { + const char *wd = getenv("WETYPE_WORK_DIR"); + if (!wd || !*wd) wd = "/tmp/wetype-work"; + snprintf(udpath, sizeof udpath, "%s/userdict", wd); + } + static JObj g_userdict; + memset(&g_userdict, 0, sizeof g_userdict); + g_userdict.cls = "java/lang/String"; + obj_set(&g_userdict, ".str", 's', udpath); + int cr = ((int (*)(void *, void *, void *, void *))sym_cd)(g_env, NULL, &g_arr, &g_userdict); + printf("config_dict -> %d\n", cr); + fflush(stdout); + usleep(400000); + } + + /* 会话链路:让胶水自报 SessionConfig 字段 */ + void *sym_cs = dlsym(h, "_Z14create_sessionP7_JNIEnvP8_jobjectS2_"); + if (sym_cs) { + memset(&g_sesscfg, 0, sizeof g_sesscfg); + g_sesscfg.cls = "com/tencent/wxhld/info/SessionConfig"; + /* 真实 app 的 SessionConfig 默认值(keyboard_type=0 即拼音) */ + obj_set(&g_sesscfg, "app_name", 's', "com.tencent.mm"); + obj_set(&g_sesscfg, "app_scene", 'i', (void *)2); + static int kb_type = 0; + { const char *kb = getenv("WETYPE_KB"); if (kb) kb_type = atoi(kb); } + obj_set(&g_sesscfg, "keyboard_type", 'i', (void *)(long)kb_type); + obj_set(&g_sesscfg, "with_async_session_wrapper", 'z', (void *)1); + obj_set(&g_sesscfg, "with_search_candidate_instantly_session_wrapper", 'z', (void *)1); + obj_set(&g_sesscfg, "enable_pre_input", 'z', (void *)1); + obj_set(&g_sesscfg, "enable_auto_most_likely", 'z', (void *)1); + obj_set(&g_sesscfg, "enable_user_hot_word_recommend", 'z', (void *)1); + printf("calling create_session(env, NULL, SessionConfig{app_name=com.tencent.mm,kb=0})...\n"); + fflush(stdout); + long sid = ((long (*)(void *, void *, void *))sym_cs)(g_env, NULL, &g_sesscfg); + printf("create_session -> %ld\n", sid); + fflush(stdout); + + /* 注册我们自己的 native 监听器:抓引擎回调参数(iterator 应在此) */ + void *sym_asl = dlsym(h, "wxime_add_session_listener"); + if (!sym_asl) sym_asl = dlsym(h, "_Z24wxime_add_session_listenerlPFvPvS_iiES_"); + if (sym_asl) { + printf("registering probe listener on session %ld...\n", sid); + fflush(stdout); + ((void (*)(long, void *, void *))sym_asl)(sid, (void *)probe_listener, (void *)0x1234); + printf("probe listener registered\n"); + fflush(stdout); + } else { + printf("wxime_add_session_listener NOT FOUND\n"); + } + + if (g_daemon_mode) run_daemon(h, sid); /* 不返回 */ + + if (g_daemon_mode) goto one_shot_done; /* daemon 已接管 */ + void *sym_pi = dlsym(h, "_Z13process_inputP7_JNIEnvP8_jobjectlP8_jstringP11_jbyteArray"); + if (sid > 0 && sym_pi) { + /* WETYPE_INPUT 支持 ';' 分隔的多段输入(逐键) */ + const char *input_str = getenv("WETYPE_INPUT"); + if (!input_str) input_str = "d nihao"; + char seqbuf[1024]; + snprintf(seqbuf, sizeof seqbuf, "%s", input_str); + for (char *tok = strtok(seqbuf, ";"); tok; tok = strtok(NULL, ";")) { + static JObj g_inputs[64]; static int gi = 0; + if (gi >= 64) break; + JObj *g_input = &g_inputs[gi++]; + memset(g_input, 0, sizeof *g_input); + g_input->cls = "java/lang/String"; + obj_set(g_input, ".str", 's', tok); + printf("process_input(sid=%ld, \"%s\")...\n", sid, tok); + fflush(stdout); + int pr = ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid, g_input, NULL); + printf(" -> %d\n", pr); + fflush(stdout); + usleep(120000); + } + usleep(400000); + + /* dump 胶水层构造的 Java 对象(找 CandidateList.newIterator) */ + dump_all_objs(); + + /* 取候选词 */ + void *sym_cg = dlsym(h, "_Z15candidate_get_nP7_JNIEnvP8_jobjectli"); + if (sym_cg && !getenv("WETYPE_NO_CAND") && !getenv("WETYPE_TEST_LEARN")) { + /* 注意:candidate_get_n 的 long 参数是 ITERATOR(非 session id) */ + printf("calling candidate_get_n(iterator=%#lx, n=10)...\n", (unsigned long)g_last_iterator); + fflush(stdout); + void *arr = ((void *(*)(void *, void *, long, int))sym_cg)(g_env, NULL, g_last_iterator, 10); + if (arr) { + JArr *a = (JArr *)arr; + printf("=== got %d candidates ===\n", a->len); + for (int i = 0; i < a->len; i++) { + printf(" candidate[%d]:\n", i); + dump_obj((JObj *)a->elem[i]); + } + } else { + printf("candidate_get_n -> NULL\n"); + } + fflush(stdout); + } + } + + /* ---- 选词学习验证:同进程两次输入 nihao,中间选词“拟好”,比较候选顺序 ---- */ + if (getenv("WETYPE_TEST_LEARN")) { + void *sym_cg = dlsym(h, "_Z15candidate_get_nP7_JNIEnvP8_jobjectli"); + void *sym_cs2 = dlsym(h, "_Z14create_sessionP7_JNIEnvP8_jobjectS2_"); + void *sym_ds = dlsym(h, "_Z15destroy_sessionP7_JNIEnvP8_jobjectl"); + void *sym_sc = dlsym(h, "_Z16select_candidateP7_JNIEnvP8_jobjectlP8_jstringP11_jbyteArrayS4_S6_P13_jobjectArrayS2_"); + if (!(sym_cg && sym_cs2 && sym_ds && sym_sc)) { + printf("[learn] 缺符号 cg=%p cs=%p ds=%p sc=%p\n", sym_cg, sym_cs2, sym_ds, sym_sc); + _exit(3); + } + /* 1. 会话 A:输入 nihao,记录原始顺序 */ + static JObj inA; memset(&inA, 0, sizeof inA); inA.cls = "java/lang/String"; + obj_set(&inA, ".str", 's', "d n"); + ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid, &inA, NULL); + usleep(150000); + inA.f[0].val = "u n"; ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid, &inA, NULL); + usleep(50000); + const char *keys = "ihao"; + for (const char *k = keys; *k; k++) { + static char buf[8]; + snprintf(buf, sizeof buf, "d %c", *k); + inA.f[0].val = buf; ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid, &inA, NULL); + usleep(150000); + snprintf(buf, sizeof buf, "u %c", *k); + inA.f[0].val = buf; ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid, &inA, NULL); + usleep(50000); + } + printf("=== 会话A 原始候选顺序 (nihao) ===\n"); + static JBytes *sel_id = NULL; + { + JArr *a = (JArr *)((void *(*)(void *, void *, long, int))sym_cg)(g_env, NULL, g_last_iterator, 10); + if (!a) { printf("[learn] A 候选取失败\n"); _exit(5); } + for (int i = 0; i < a->len; i++) { + JObj *c = (JObj *)a->elem[i]; + const char *t = cand_text(c); + printf("[A] rank%d = %s\n", i, t ? t : "?"); + if (t && !strcmp(t, "\xe6\x8b\x9f\xe5\xa5\xbd")) { /* 拟好 */ + JField *idf = obj_get(c, "id"); + if (idf && idf->val) sel_id = (JBytes *)idf->val; + } + } + fflush(stdout); + } + if (!sel_id) { printf("[learn] 候选里没找到 拟好\n"); _exit(6); } + if (sel_id->magic != JB_MAGIC || sel_id->len <= 0) { printf("[learn] id 无效 len=%ld\n", sel_id->len); _exit(7); } + + /* 2. select_candidate(text, id, ...) */ + static JObj sel; memset(&sel, 0, sizeof sel); sel.cls = "java/lang/String"; + obj_set(&sel, ".str", 's', "\xe6\x8b\x9f\xe5\xa5\xbd"); /* 拟好 */ + printf("[learn] select_candidate(sid=%ld, 拟好, id_len=%ld)...\n", sid, sel_id->len); + ((void (*)(void *, void *, long, void *, void *, void *, void *, void *, void *, void *))sym_sc) + (g_env, NULL, sid, &sel, sel_id, NULL, NULL, NULL, NULL, NULL); + fflush(stdout); + usleep(300000); + + /* 3. 销毁会话 A(促使引擎落盘/入学习队列),再建会话 B */ + ((void (*)(void *, void *, long))sym_ds)(g_env, NULL, sid); + usleep(300000); + long sid2 = ((long (*)(void *, void *, void *))sym_cs2)(g_env, NULL, &g_sesscfg); + printf("[learn] 会话B sid=%ld\n", sid2); + if (sid2 <= 0) { printf("[learn] 会话B创建失败\n"); _exit(4); } + + /* 4. 会话 B 再输 nihao,比较顺序 */ + inA.f[0].val = "d n"; ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid2, &inA, NULL); + usleep(150000); + inA.f[0].val = "u n"; ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid2, &inA, NULL); + usleep(50000); + for (const char *k = keys; *k; k++) { + static char buf2[8]; + snprintf(buf2, sizeof buf2, "d %c", *k); + inA.f[0].val = buf2; ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid2, &inA, NULL); + usleep(150000); + snprintf(buf2, sizeof buf2, "u %c", *k); + inA.f[0].val = buf2; ((int (*)(void *, void *, long, void *, void *))sym_pi)(g_env, NULL, sid2, &inA, NULL); + usleep(50000); + } + printf("=== 会话B 选词后候选顺序 (nihao) ===\n"); + dump_order(g_env, sym_cg, g_last_iterator, 10, "B"); + printf("=== 对比:若 B 中 拟好 上到 rank0/rank1 前列,说明用户词库生效 ===\n"); + fflush(stdout); + } + + } +one_shot_done: + printf("--- done, _exit ---\n"); + fflush(stdout); + _exit(0); +} diff --git a/harness/probe.c b/harness/probe.c new file mode 100644 index 0000000..5d096db --- /dev/null +++ b/harness/probe.c @@ -0,0 +1,40 @@ +/* probe: 在 qemu-aarch64 下 dlopen 引擎库,报告成功/失败与可选符号探测 */ +#include +#include +#include + +int main(int argc, char **argv) { + if (argc < 2) { + fprintf(stderr, "usage: %s [symbol ...]\n", argv[0]); + return 2; + } + void *h = dlopen(argv[1], RTLD_NOW); + if (!h) { + fprintf(stderr, "dlopen FAILED: %s\n", dlerror()); + return 1; + } + printf("dlopen ok: %s\n", argv[1]); + for (int i = 2; i < argc; i++) { + void *s = dlsym(h, argv[i]); + printf(" dlsym(%-40s) = %p\n", argv[i], s); + dlerror(); + } + /* 自检:对 shim 句柄逐个 dlsym,验证 .gnu.hash 可查性 */ + const char *syms[] = {"fflush", "fprintf", "fwrite", "__sF", "sigsetjmp", "res_init"}; + for (int i = 0; i < 6; i++) { + void *s = dlsym(h, syms[i]); + printf(" self dlsym(%-12s) = %p %s\n", syms[i], s, s ? "" : " <-- MISS"); + dlerror(); + } + /* 最小复现:模拟 bionic 消费者调用 Fflush(&__sF[1]) */ + if (argc > 2 && !strcmp(argv[2], "--fflush-test")) { + void *ff = dlsym(h, "Fflush"); + void *sf = dlsym(h, "__sF"); + printf("fflush-test: Fflush=%p __sF=%p\n", ff, sf); + int r = ((int (*)(FILE *))ff)((FILE *)((char *)sf + 152)); + printf("fflush-test: Fflush(&__sF[1]) = %d\n", r); + r = ((int (*)(FILE *))ff)((FILE *)((char *)sf + 304)); + printf("fflush-test: Fflush(&__sF[2]) = %d\n", r); + } + return 0; +} diff --git a/scripts/10_patch_libs.sh b/scripts/10_patch_libs.sh new file mode 100755 index 0000000..bb526be --- /dev/null +++ b/scripts/10_patch_libs.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# NEEDED-name fixes + versym surgery for all runtime libs(幂等:先重拷原始库) +# 用法: 10_patch_libs.sh [输出目录,默认 runtime/]。只处理 APK 里的库;shim/libz 由 20_build.sh 产出。 +# 安装时也在用户机器上运行(AppImage install),因此只依赖 patchelf + python3。 +set -e +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +BASE="$(dirname "$SCRIPT_DIR")" +APK_ROOT="${WETYPE_APK_ROOT:-$BASE/.deps/wechat-ime}" +SRC="$APK_ROOT/lib/arm64-v8a" +OUT="${1:-$BASE/runtime}" +mkdir -p "$OUT" +cd "$OUT" + +for tool in patchelf python3; do + command -v "$tool" >/dev/null || { echo "Missing build tool: $tool" >&2; exit 1; } +done + +if [ ! -f "$SRC/libwxhld_jni.so" ]; then + echo "Missing WeType APK libraries at $SRC" >&2 + echo "Run: $BASE/scripts/prepare_assets.sh" >&2 + exit 1 +fi + +# 引擎闭包 9 库(shim 是我们自己的原生库,绝不能被手术!) +ENGINELIBS="libandromeda.so libcryptopp.so libc++_shared.so libime_net.so libowl.so \ + libprotobuf-lite.so libtensorflowlite_c.so libwcwss.so libwxhld.so libwxhld_jni.so libwechatxlog.so" + +for f in $ENGINELIBS; do + cp -f "$SRC/$f" . +done +for p in $ENGINELIBS; do + patchelf --replace-needed libc.so libc.so.6 "$p" 2>/dev/null || true + patchelf --replace-needed libm.so libm.so.6 "$p" 2>/dev/null || true + patchelf --replace-needed libdl.so libdl.so.2 "$p" 2>/dev/null || true + patchelf --replace-needed libz.so libz.so.1 "$p" 2>/dev/null || true + patchelf --replace-needed libstdc++.so libstdc++.so.6 "$p" 2>/dev/null || true + patchelf --replace-needed liblog.so libwetype-shim.so "$p" 2>/dev/null || true + patchelf --remove-needed libandroid.so "$p" 2>/dev/null || true + # 关键:去掉对 libc 的直接依赖。否则 libc 在本库局部作用域内必压过 shim 的 + # stdio 包装(fflush/fprintf… 被 bionic 步长的 __sF 指针烧穿)。 + # 摘掉后这些符号经全局作用域回落到主程序已加载的 libc,而 stdio 只剩 shim。 + patchelf --remove-needed libc.so.6 "$p" 2>/dev/null || true + # 同理必须摘干净:libm/libdl/libz 会把 libc 以深度 2 拉进本库的搜索列表, + # glibc 的 _dl_sort_maps 深度降序会让 libc 永远压过 depth-1 的 shim。 + # 这些符号统一回落到全局作用域(probe 已链 -lm -ldl -lz 兑底)。 + patchelf --remove-needed libm.so.6 "$p" 2>/dev/null || true + patchelf --remove-needed libdl.so.2 "$p" 2>/dev/null || true + patchelf --remove-needed libz.so.1 "$p" 2>/dev/null || true + # shim 必须在每个引 __sF 的库的局部作用域里且排在 libc 之前(stdio 包装生效的前提) + if ! patchelf --print-needed "$p" | grep -qx 'libwetype-shim.so'; then + patchelf --add-needed libwetype-shim.so "$p" + fi +done + +python3 "$SCRIPT_DIR/versym_surgery.py" $ENGINELIBS +python3 "$SCRIPT_DIR/12_rename_syms.py" $ENGINELIBS +python3 "$SCRIPT_DIR/promote_shim.py" $ENGINELIBS +python3 "$SCRIPT_DIR/17_disable_scan_sig.py" libwxhld.so +python3 "$SCRIPT_DIR/21_fake_appender.py" libwxhld.so + +echo "== 手术后 DT_NEEDED 抽查 (libwxhld.so)" +patchelf --print-needed libwxhld.so diff --git a/scripts/12_rename_syms.py b/scripts/12_rename_syms.py new file mode 100644 index 0000000..8f6245f --- /dev/null +++ b/scripts/12_rename_syms.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""把引擎库 .dynstr 中的 stdio 符号名原地改写(首字母大写,长度不变)。 + +背景:glibc 2.35+ _dl_sort_maps_dfs 拓扑排序会把"无依赖约束"的 shim 排到 +搜索列表末尾,导致与 libc 同名的包装符号(fflush 等)永远绑不到 shim。 +改写后这些名字(Fflush/Fprintf/…)只有 shim 导出,与顺序无关地绑定到 shim, +由 shim 完成.FILE* 映射(bionic __sF 指针 → glibc 真实流)后再转发 glibc。 +""" +import struct, sys, os + +# 需要改写的符号(全部在 wetype-shim 中有对应大写别名) +RENAMES = [ + 'fflush', 'fprintf', 'vfprintf', 'fwrite', 'fputs', 'fread', + 'fgetc', 'fputc', 'fclose', 'feof', 'ferror', + 'fseek', 'fseeko', 'ftell', 'ftello', + 'sigaction', 'sigprocmask', 'sigfillset', 'sigdelset', + 'mmap', 'munmap', 'free', 'dlerror', 'dlsym', +] + +def rename(path: str) -> str: + b = bytearray(open(path, 'rb').read()) + e_shoff, = struct.unpack_from('field8->field112 取执行上下文;移植环境下为 +NULL → vtable 虚调用崩溃。方案:.text 零洞放 helper 完整副本(帧结构一致, +PC 相对指令全部重编码),插入 obj/holder/ctx 三重空守卫,任一为空即走 +副本自身的 canary+epilogue 收尾(等价"无任务")。 +""" +import struct, sys + +SO = sys.argv[1] if len(sys.argv) > 1 else 'runtime/libwxhld.so' +CAVE = 0x59d08c +CALLSITE = 0xdbb4e8 +HELPER = 0x1e6507c +SCHED = 0x21b4c80 +RELEASE = 0x21ca210 +STKCHK = 0x1e65130 + +def w(x): return struct.pack('> 2 + assert -(1 << 25) <= off < (1 << 25) + return struct.pack('> 2 + assert -(1 << 25) <= off < (1 << 25) + return struct.pack('> 2 + assert 0 < off < (1 << 19), f'cbz {off:#x}' + return struct.pack('> 2 + assert 0 < off < (1 << 19) + return struct.pack(' 1 else 'runtime/libwxhld.so' +SITES = [0xda78c4, 0xdb8bac] + +data = bytearray(open(SO, 'rb').read()) +NOP = struct.pack('> 2 +assert -(1 << 25) <= off < (1 << 25) +data[0x96ba0:0x96ba0 + 4] = struct.pack(' 1 else 'runtime/libwxhld.so' +SITE = 0x21c0884 + +data = bytearray(open(SO, 'rb').read()) +cur = struct.unpack_from('/dev/null || { echo "Missing build tool: $tool" >&2; exit 1; } +done +mkdir -p runtime harness +if [ ! -f runtime/libz.so.1 ]; then + ZLIB_SO="${WETYPE_ZLIB_SO:-}" + for candidate in \ + /usr/lib/aarch64-linux-gnu/libz.so.1 \ + /usr/aarch64-linux-gnu/lib/libz.so.1; do + if [ -z "$ZLIB_SO" ] && [ -f "$candidate" ]; then ZLIB_SO="$candidate"; fi + done + if [ -z "$ZLIB_SO" ] || [ ! -f "$ZLIB_SO" ]; then + echo "Missing ARM64 zlib. Install zlib1g-dev:arm64 or set WETYPE_ZLIB_SO." >&2 + exit 1 + fi + cp -fL "$ZLIB_SO" runtime/libz.so.1 +fi +aarch64-linux-gnu-gcc -shared -fPIC -O2 -o runtime/libwetype-shim.so \ + shim/wetype-shim.c shim/wetype-signal.c -ldl +# shim 自身去掉全部 DT_NEEDED:glibc _dl_sort_maps 按深度重排搜索列表时, +# 依赖 libc 的 shim 会被排到 libc 之后导致 stdio 包装失效;无依赖叶子节点则稳居第一, +# 其 UND 符号(dlsym/fprintf 等)从全局作用域解析(主程序已加载 libc)。 +patchelf --remove-needed libc.so.6 runtime/libwetype-shim.so 2>/dev/null || true +patchelf --remove-needed libdl.so.2 runtime/libwetype-shim.so 2>/dev/null || true +echo "shim NEEDED 残留: $(patchelf --print-needed runtime/libwetype-shim.so | wc -l)" +aarch64-linux-gnu-gcc -O0 -g -o harness/jinterop harness/jinterop.c \ + -ldl -lpthread -Wl,--no-as-needed -lm "$PWD/runtime/libz.so.1" +aarch64-linux-gnu-gcc -O0 -g -o harness/probe harness/probe.c -ldl -lpthread \ + -Wl,--no-as-needed -lm "$PWD/runtime/libz.so.1" +echo "build ok" diff --git a/scripts/21_fake_appender.py b/scripts/21_fake_appender.py new file mode 100644 index 0000000..af1ebe3 --- /dev/null +++ b/scripts/21_fake_appender.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""logging Manager 的空 appender 兜底:避免 0x1e650a0 处对 NULL 对象做虚调用。 + 原指令 (0x1e650a0..0x1e650bb): + ldr x0,[x8,#112]; stp xzr,xzr,[x1]; str q0,[sp]; ldr x8,[x0]; ldr x8,[x8,#24]; + mov x1,sp; blr x8 + 移植环境下 x0 为 NULL。站点改为跳入 .rodata 空洞中的洞穴: + x0 非空 → 原样执行上述虚调用; + x0 为空 → 不调用,把结果槽 [sp+8] 清零(后续 ldr x19,[sp,#8]; cbz 跳过任务调度), + x0 指向洞穴内的占位对象、x1=sp,与"调用了一个空 ret"时的寄存器状态一致。 + 洞穴只用 PC 相对指令,不含绝对地址:库的装载基址随宿主 /etc/ld.so.cache 大小变化。""" +import struct, sys + +LIB = sys.argv[1] if len(sys.argv) > 1 else 'runtime/libwxhld.so' +SITE = 0x1e650a0 +AFTER_BLR = 0x1e650bc +CAVE = 0x59d08c +PLACEHOLDER = CAVE + 0x40 # 洞穴内全零占位对象 +CAVE_END = CAVE + 0x70 # 旧版补丁写到 +0x6c + +d = bytearray(open(LIB, 'rb').read()) + +def b_enc(pc, target): + return 0x14000000 | (((target - pc) >> 2) & 0x03FFFFFF) +def cbz_enc(pc, target, rt): + return 0xB4000000 | ((((target - pc) >> 2) & 0x7FFFF) << 5) | rt +def adr_enc(pc, target, rd): + imm21 = (target - pc) & 0x1FFFFF + return 0x10000000 | ((imm21 & 3) << 29) | ((imm21 >> 2) << 5) | rd + +NULL_PATH = CAVE + 0x24 +cave = [ + 0xf9403900, # +00 ldr x0, [x8, #112] + 0xa9007c3f, # +04 stp xzr, xzr, [x1] + 0x3d8003e0, # +08 str q0, [sp] + cbz_enc(CAVE + 0x0c, NULL_PATH, 0), # +0c cbz x0, null_path + 0xf9400008, # +10 ldr x8, [x0] + 0xf9400d08, # +14 ldr x8, [x8, #24] + 0x910003e1, # +18 mov x1, sp + 0xd63f0100, # +1c blr x8 + b_enc(CAVE + 0x20, AFTER_BLR), # +20 b after_blr + 0xf90007ff, # +24 null_path: str xzr, [sp, #8] + adr_enc(CAVE + 0x28, PLACEHOLDER, 0), # +28 adr x0, placeholder + 0x910003e1, # +2c mov x1, sp + b_enc(CAVE + 0x30, AFTER_BLR), # +30 b after_blr +] +assert CAVE + len(cave) * 4 <= PLACEHOLDER +d[CAVE:CAVE_END] = bytes(CAVE_END - CAVE) # 洞穴原为全零;清掉旧版写入的绝对地址 +for i, w in enumerate(cave): + struct.pack_into(' 1 else 'libwxhld_jni.so' +ASM = sys.argv[2] if len(sys.argv) > 2 else '/tmp/init_fn.asm' + +# 1) section headers: vaddr -> file offset +secs = [] +out = subprocess.run(['readelf', '-S', '-W', SO], capture_output=True, text=True).stdout +for m in re.finditer(r'\[\s*\d+\]\s+(\S+)\s+\S+\s+([0-9a-f]+)\s+([0-9a-f]+)\s+([0-9a-f]+)', out): + name, addr, off, size = m.group(1), int(m.group(2), 16), int(m.group(3), 16), int(m.group(4), 16) + if addr: + secs.append((addr, size, off, name)) + +def v2o(v): + for addr, size, off, name in secs: + if addr <= v < addr + size: + return off + (v - addr) + return None + +data = open(SO, 'rb').read() +def getstr(v): + o = v2o(v) + if o is None: + return None + e = data.find(b'\0', o) + s = data[o:e] + return s.decode('utf-8', 'replace') if 0 < len(s) < 200 else None + +# 2) parse asm: track adrp page per (reg), resolve add imm +page = {} +ldreg = {} # reg -> (base, off) 最近一次 ldr xN, [xM, #imm] +JNI = {0x30:'FindClass', 0x108:'GetMethodID', 0x110:'CallObjectMethod', 0x2f0:'GetFieldID', + 0x2f8:'GetObjectField', 0x300:'GetBooleanField', 0x308:'GetByteField', 0x310:'GetCharField', + 0x318:'GetShortField', 0x320:'GetIntField', 0x328:'GetLongField', 0x330:'GetFloatField', + 0x338:'GetDoubleField', 0x538:'NewStringUTF', 0x548:'GetStringUTFChars', 0x550:'ReleaseStringUTFChars', + 0x558:'GetArrayLength', 0x1e8:'CallVoidMethod', 0x358:'SetObjectField', 0x480:'GetStaticFieldID', + 0x488:'GetStaticObjectField', 0x5a0:'GetByteArrayElements', 0x5c0:'GetByteArrayRegion'} +prev = None +for line in open(ASM, encoding='utf-8', errors='replace'): + m = re.match(r'\s*([0-9a-f]+):\s*[0-9a-f]+\s+(adrp|add|blr|ldr|str|stur|strb|strh)\t(.*)', line) + if not m: + continue + addr, op, ops = int(m.group(1), 16), m.group(2), m.group(3) + if op == 'adrp': + r, rest = ops.split(',', 1) + pm = re.search(r'([0-9a-f]+)\s*<', rest) + if pm: + page[r.strip()] = int(pm.group(1), 16) + elif op == 'add': + parts = [p.strip() for p in ops.split(',')] + if len(parts) == 3 and parts[0] in page and parts[1] == parts[0] and parts[2].startswith('#'): + imm = int(parts[2][1:], 16) if parts[2].startswith('#0x') else int(parts[2][1:]) + s = getstr(page[parts[0]] + imm) + if s and s.isprintable() and len(s) > 1: + print(f'{addr:6x} STR "{s}"') + page.pop(parts[0], None) + elif op == 'ldr': + mm = re.match(r'(x[0-9]+), \[(x[0-9]+)(?:, #(0x[0-9a-f]+|\d+))?\]', ops) + if mm: + dst, src, offs = mm.group(1), mm.group(2), mm.group(3) + offv = int(offs, 16) if offs and offs.startswith('0x') else (int(offs) if offs else 0) + # 数据段指针解引用:adrp 页 + ldr → 读指针 → 字符串 + if src in page: + ptr_addr = page[src] + offv + o = v2o(ptr_addr) + if o is not None and o + 8 <= len(data): + ptr, = struct.unpack_from(' 1: + print(f'{addr:6x} STRP [{ptr_addr:#x}] -> "{s}"') + continue + mm = re.match(r'(x[0-9]+), \[(x[0-9]+)(?:, #(0x[0-9a-f]+|\d+))?\]', ops) + if mm: + dst, src, offs = mm.group(1), mm.group(2), mm.group(3) + offv = int(offs, 16) if offs and offs.startswith('0x') else (int(offs) if offs else 0) + st = ldreg.get(src) + if st is not None: # src 是 JNIEnv 或函数表 → dst 成为函数表/函数指针 + ldreg[dst] = st + offv if ldreg.get('_table') == src or st >= 0 else st + if ldreg.get('_env') == src: + ldreg[dst] = 'TABLE' + elif ldreg.get(dst) == 'TABLE' or (ldreg.get(src) == 'TABLE' and dst == src): + ldreg[dst] = offv + elif op == 'mov': + mm = re.match(r'(x[0-9]+), (x[0-9]+)', ops) + if mm and mm.group(2) == 'x0': + ldreg[mm.group(1)] = 'ENV' + ldreg['_env'] = mm.group(1) + elif op == 'blr': + r = ops.strip() + v = ldreg.get(r) + if v == 'TABLE' or v is None: + name = '?' + else: + name = JNI.get(v, f'jni+{v:#x}') + print(f'{addr:6x} CALL {name} (*{r})') + elif op in ('str', 'stur', 'strb', 'strh'): + mm = re.search(r'\[(x[0-9]+|sp)(?:, #(0x[0-9a-f]+|\d+))?\]', ops) + if mm: + off = mm.group(2) + offv = int(off[1:], 16) if off and off.startswith('#0x') else (int(off[1:]) if off else 0) + print(f'{addr:6x} STORE [{mm.group(1)}, +{offv:#x}] {ops.split(",")[0]}') diff --git a/scripts/appimage_manage.sh b/scripts/appimage_manage.sh new file mode 100644 index 0000000..31387a2 --- /dev/null +++ b/scripts/appimage_manage.sh @@ -0,0 +1,198 @@ +#!/bin/bash +# Called by AppRun inside the mounted AppImage or an extracted AppDir. +set -euo pipefail + +appdir="${1:?missing AppDir}" +action="${2:?missing action}" +shift 2 + +usage() { + echo "Usage: AppImage install [--user|--system] [--apk FILE]" >&2 + echo " AppImage uninstall [--user|--system]" >&2 + exit 2 +} + +case "$action" in install|uninstall) ;; *) usage ;; esac +scope= +apk= +while [ "$#" -gt 0 ]; do + case "$1" in + --user) scope=user ;; + --system) scope=system ;; + --apk) + [ "$action" = install ] && [ -n "${2:-}" ] || usage + apk="$(readlink -f "$2")"; shift ;; + *) usage ;; + esac + shift +done +if [ -z "$scope" ]; then + if [ "$(id -u)" -eq 0 ]; then scope=system; else scope=user; fi +fi + +if [ "$scope" = system ]; then + if [ "$(id -u)" -ne 0 ]; then + echo "系统安装需要 root 权限;请使用 sudo,或选择 --user。" >&2 + exit 1 + fi + prefix=/usr + if command -v pkg-config >/dev/null 2>&1 && + [ "$(pkg-config --variable=prefix Fcitx5Module 2>/dev/null || true)" = /usr ]; then + fcitx_libdir="$(pkg-config --variable=libdir Fcitx5Module)" + case "$fcitx_libdir" in /usr/lib|/usr/lib/*|/usr/lib64) ;; *) fcitx_libdir= ;; esac + else + fcitx_libdir= + fi + if [ -z "$fcitx_libdir" ]; then + triplet="$(gcc -dumpmachine 2>/dev/null || true)" + if [ -n "$triplet" ] && [ -d "/usr/lib/$triplet/fcitx5" ]; then + fcitx_libdir="/usr/lib/$triplet" + elif [ -d /usr/lib64/fcitx5 ]; then + fcitx_libdir=/usr/lib64 + else + fcitx_libdir=/usr/lib + fi + fi + addon_dir="$fcitx_libdir/fcitx5" + apk_cache=/var/cache/wetype-ime +else + prefix="$HOME/.local" + addon_dir="$prefix/lib/fcitx5" + apk_cache="${XDG_CACHE_HOME:-$HOME/.cache}/wetype-ime" +fi + +src="$appdir/usr" +eng="$prefix/lib/wetype-ime/arm64" +src_eng="$src/lib/wetype-ime/arm64" +src_scripts="$src/lib/wetype-ime/scripts" +addon="$addon_dir/libfcitx5-wetype.so" +addon_conf="$prefix/share/fcitx5/addon/wetype.conf" +im_conf="$prefix/share/fcitx5/inputmethod/wetype-im.conf" +desktop="$prefix/share/applications/wetype-ime.desktop" +icon="$prefix/share/icons/hicolor/256x256/apps/wetype-ime.png" + +print_existing_paths() { + local label="$1" path="$2" + if [ -e "$path" ] || [ -L "$path" ]; then + if [ -d "$path" ] && [ ! -L "$path" ]; then + find "$path" -print0 | LC_ALL=C sort -z | while IFS= read -r -d '' entry; do + printf ' [%s] %s\n' "$label" "$entry" + done + else + printf ' [%s] %s\n' "$label" "$path" + fi + fi +} + +# Check everything up front and print a copy-paste command; never install packages ourselves. +check_install_deps() { + local missing=() cmd tool id= + for tool in python3 patchelf unzip sha256sum; do + command -v "$tool" >/dev/null 2>&1 || missing+=("$tool") + done + if [ -z "$apk" ] && ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then + missing+=(curl) + fi + [ "${#missing[@]}" -eq 0 ] && return + + echo "缺少安装依赖:${missing[*]}" >&2 + if [ -r /etc/os-release ]; then + id="$(. /etc/os-release; echo " ${ID:-} ${ID_LIKE:-} ")" + fi + case "$id" in + *" debian "*|*" ubuntu "*) cmd="sudo apt install python3 patchelf unzip curl" ;; + *" arch "*) cmd="sudo pacman -S --needed python patchelf unzip curl" ;; + *" fedora "*|*" rhel "*|*" centos "*) + cmd="sudo dnf install python3 patchelf unzip curl(RHEL/CentOS 上 patchelf 来自 EPEL)" ;; + *" suse "*|*" opensuse "*) cmd="sudo zypper install python3 patchelf unzip curl" ;; + esac + if [ -n "${cmd:-}" ]; then + echo "请先运行:$cmd" >&2 + else + echo "请用发行版的包管理器安装上述命令。" >&2 + fi + exit 1 +} + +if [ "$action" = install ]; then + for required in \ + "$src_eng/wetype-harness" "$src_eng/wetype-ime-demo.sh" \ + "$src_eng/lib/libwetype-shim.so" "$src_eng/lib/libz.so.1" \ + "$src_eng/qemu-aarch64-static" "$src_eng/sysroot/lib/ld-linux-aarch64.so.1" \ + "$src_scripts/prepare_assets.sh" "$src_scripts/10_patch_libs.sh" \ + "$src/lib/fcitx5/libfcitx5-wetype.so" \ + "$src/share/fcitx5/addon/wetype.conf" \ + "$src/share/fcitx5/inputmethod/wetype-im.conf" \ + "$src/share/applications/wetype-ime.desktop" \ + "$src/share/icons/hicolor/256x256/apps/wetype-ime.png" \ + "$src/bin/wetype-ime-engine" "$src/bin/wetype-demo"; do + if [ ! -f "$required" ]; then + echo "AppImage 缺少安装文件:$required" >&2 + exit 1 + fi + done + check_install_deps + # Paper 式:WeType APK 从腾讯官方服务器下载(或用 --apk 指定),校验 SHA-256 后在本机打补丁。 + stage="$(mktemp -d "${TMPDIR:-/tmp}/wetype-install.XXXXXX")" + trap 'rm -rf "$stage"' EXIT + WETYPE_APK_ROOT="$stage/apk" WETYPE_APK_CACHE="$apk_cache" \ + bash "$src_scripts/prepare_assets.sh" ${apk:+"$apk"} + echo "正在本机修补 WeType 引擎库…" + WETYPE_APK_ROOT="$stage/apk" bash "$src_scripts/10_patch_libs.sh" "$stage/lib" >/dev/null + cp -a --no-preserve=ownership "$src_eng/lib/." "$stage/lib/" + + mkdir -p "$eng" "$eng/dicts" "$addon_dir" \ + "$(dirname "$addon_conf")" "$(dirname "$im_conf")" \ + "$(dirname "$desktop")" "$(dirname "$icon")" "$prefix/bin" + rm -rf "$eng/lib" + cp -a --no-preserve=ownership "$stage/lib" "$eng/lib" + for dict in "$stage/apk/assets/config/beta"/*; do # keep existing dictionaries + [ -e "$eng/dicts/${dict##*/}" ] || cp -a --no-preserve=ownership "$dict" "$eng/dicts/" + done + install -m 755 "$src_eng/wetype-harness" "$eng/wetype-harness" + install -m 755 "$src_eng/wetype-ime-demo.sh" "$eng/wetype-ime-demo.sh" + install -m 755 "$src_eng/qemu-aarch64-static" "$eng/qemu-aarch64-static" + rm -rf "$eng/sysroot" + cp -a --no-preserve=ownership "$src_eng/sysroot" "$eng/sysroot" + install -m 755 "$src/bin/wetype-ime-engine" "$prefix/bin/wetype-ime-engine" + install -m 755 "$src/bin/wetype-demo" "$prefix/bin/wetype-demo" + install -m 755 "$src/lib/fcitx5/libfcitx5-wetype.so" "$addon" + install -m 644 "$src/share/fcitx5/addon/wetype.conf" "$addon_conf" + if [ "$scope" = user ]; then + # Fcitx5 never searches ~/.local/lib/fcitx5; an absolute Library= (without .so) is honored. + sed -i "s|^Library=.*|Library=${addon%.so}|" "$addon_conf" + fi + install -m 644 "$src/share/fcitx5/inputmethod/wetype-im.conf" "$im_conf" + install -m 644 "$src/share/applications/wetype-ime.desktop" "$desktop" + install -m 644 "$src/share/icons/hicolor/256x256/apps/wetype-ime.png" "$icon" + echo "安装完成 ($scope)。Fcitx5 插件:$addon" + echo "请重启 Fcitx5,并在输入法配置中添加“微信拼音”。" +else + echo "卸载清单 ($scope),以下路径均在 AppImage 之外:" + for path in "$addon" "$addon_conf" "$im_conf" "$desktop" "$icon" \ + "$prefix/bin/wetype-ime-engine" "$prefix/bin/wetype-demo" \ + "$eng/wetype-harness" "$eng/wetype-ime-demo.sh" "$eng/qemu-aarch64-static"; do + print_existing_paths 删除 "$path" + done + print_existing_paths 删除 "$eng/lib" + print_existing_paths 删除 "$eng/sysroot" + print_existing_paths 保留词库 "$eng/dicts" + print_existing_paths 保留APK缓存 "$apk_cache" + if [ "$scope" = user ]; then + user_data="${XDG_DATA_HOME:-$HOME/.local/share}/wetype-ime" + print_existing_paths 保留用户数据 "$user_data" + else + echo ' [保留用户数据] 各用户的 ${XDG_DATA_HOME:-$HOME/.local/share}/wetype-ime(系统卸载不访问)' + fi + rm -f "$addon" "$addon_conf" "$im_conf" "$desktop" "$icon" \ + "$prefix/bin/wetype-ime-engine" "$prefix/bin/wetype-demo" \ + "$eng/wetype-harness" "$eng/wetype-ime-demo.sh" "$eng/qemu-aarch64-static" + rm -rf "$eng/lib" "$eng/sysroot" + echo "卸载完成 ($scope)。预置词库保留在:$eng/dicts" + echo "用户学习数据未清理。请重启 Fcitx5。" +fi + +# Reload a running user session when possible; a restart is still needed for new modules. +if command -v fcitx5-remote >/dev/null 2>&1 && [ "$(id -u)" -ne 0 ]; then + fcitx5-remote -r >/dev/null 2>&1 || true +fi diff --git a/scripts/appimage_run.sh b/scripts/appimage_run.sh new file mode 100644 index 0000000..f5bee07 --- /dev/null +++ b/scripts/appimage_run.sh @@ -0,0 +1,33 @@ +#!/bin/bash +set -e +HERE="$(dirname "$(readlink -f "$0")")" + +# The AppImage carries no WeType binaries; demo and engine run from an installation. +installed_bin() { + local prefix + for prefix in "$HOME/.local" /usr; do + if [ -x "$prefix/bin/$1" ] && [ -f "$prefix/lib/wetype-ime/arm64/lib/libwxhld_jni.so" ]; then + echo "$prefix/bin/$1" + return + fi + done + echo "WeType 引擎尚未安装。请先运行:$(basename "${APPIMAGE:-$0}") install" >&2 + exit 1 +} + +case "${1:-}" in + install|uninstall) + action="$1" + shift + exec "$HERE/usr/lib/wetype-ime/appimage-manage.sh" "$HERE" "$action" "$@" + ;; + demo) + shift + bin="$(installed_bin wetype-demo)" + exec "$bin" "$@" + ;; + *) + bin="$(installed_bin wetype-ime-engine)" + exec "$bin" "$@" + ;; +esac diff --git a/scripts/bench_candidate_latency.py b/scripts/bench_candidate_latency.py new file mode 100755 index 0000000..791b51a --- /dev/null +++ b/scripts/bench_candidate_latency.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Benchmark WeType candidate response time for 1..N pinyin characters. + +Talks to the ARM64 harness daemon through QEMU user mode directly (no Fcitx, +no D-Bus), using the same line protocol as the addon: + B -> CAND\t... | EMPTY + C -> OK (reset composition by recreating the session) + Q -> quit + +Modes: + incremental type one character per B request; the latency at length N is + the time to get candidates after the N-th keystroke. + whole reset, then send all N characters in a single B request. + +Daemon startup and C resets are excluded from the measured latency. The +daemon waits at most 2500 ms for a candidate callback, so an EMPTY response +near that value is reported as a callback timeout rather than real latency. +""" + +import argparse +import csv +import os +import select +import statistics +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +CALLBACK_TIMEOUT_MS = 2500 +CASES = { + "nihao": "nihao", + "ni": "ni", + "sentence": "nijuedexiaogouruhe", +} + + +def repeated(text: str, length: int) -> str: + return (text * ((length + len(text) - 1) // len(text)))[:length] + + +class Daemon: + def __init__(self, args, work_dir: str, log_path: Path): + env = os.environ.copy() + env.update({ + "LD_LIBRARY_PATH": f"{args.engine_dir}/lib", + "WETYPE_LIB_DIR": f"{args.engine_dir}/lib", + "WETYPE_DICT_DIR": f"{args.engine_dir}/dicts", + "WETYPE_ASSET_DIR": f"{args.engine_dir}/dicts", + "WETYPE_WORK_DIR": work_dir, + "WETYPE_HARNESS_LOG": str(log_path), + }) + command = [args.qemu, "-L", args.sysroot, str(args.harness), + str(args.engine_dir / "lib/libwxhld_jni.so"), "--daemon"] + self.timeout = args.timeout + self.stderr_file = open(log_path, "a", encoding="utf-8") + started = time.monotonic() + self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=self.stderr_file, + text=True, bufsize=1, env=env) + ready = self.read_line(args.startup_timeout) + if ready != "READY": + self.close() + raise RuntimeError(f"expected READY, received {ready!r}") + self.startup_ms = (time.monotonic() - started) * 1000 + + def read_line(self, timeout: float) -> str: + ready, _, _ = select.select([self.proc.stdout], [], [], timeout) + if not ready: + raise TimeoutError(f"no protocol response after {timeout:.1f}s") + line = self.proc.stdout.readline() + if not line: + raise EOFError(f"daemon exited (returncode={self.proc.poll()})") + return line.rstrip("\r\n") + + def request(self, command: str): + before = time.perf_counter() + self.proc.stdin.write(command + "\n") + self.proc.stdin.flush() + response = self.read_line(self.timeout) + return response, (time.perf_counter() - before) * 1000 + + def reset(self) -> None: + response, _ = self.request("C") + if response != "OK": + raise RuntimeError(f"C returned {response!r}") + + def close(self) -> None: + if self.proc.poll() is None: + try: + self.proc.stdin.write("Q\n") + self.proc.stdin.flush() + self.proc.wait(timeout=5) + except (OSError, subprocess.TimeoutExpired): + self.proc.kill() + self.proc.wait() + self.stderr_file.close() + + +def classify(response: str, elapsed_ms: float): + if response.startswith("CAND\t"): + return "CAND", len(response.split("\t")) - 1 + if response == "EMPTY": + return ("EMPTY_TIMEOUT" if elapsed_ms >= CALLBACK_TIMEOUT_MS * 0.95 else "EMPTY"), 0 + return f"UNEXPECTED:{response[:40]}", 0 + + +class Bench: + def __init__(self, args): + self.args = args + self.rows = [] + self.daemon = None + self.restarts = 0 + self.tmp = tempfile.TemporaryDirectory(prefix="wetype-bench-") + self.log_path = Path(args.output).with_suffix(".stderr.log") + self.log_path.write_text("", encoding="utf-8") + + def ensure_daemon(self) -> Daemon: + if self.daemon is None: + self.daemon = Daemon(self.args, self.tmp.name, self.log_path) + print(f"# daemon ready in {self.daemon.startup_ms:.0f} ms", flush=True) + return self.daemon + + def drop_daemon(self, exc: Exception) -> None: + print(f"# daemon failure: {exc}; restarting (log={self.log_path})", + file=sys.stderr, flush=True) + if self.daemon: + self.daemon.close() + self.daemon = None + self.restarts += 1 + + def record(self, mode, case, rep, length, status, count, elapsed_ms): + self.rows.append([mode, case, rep, length, status, count, + "" if elapsed_ms is None else f"{elapsed_ms:.2f}"]) + + def run_incremental(self, case: str, text: str, rep: int, measured: bool) -> None: + length = 0 + try: + daemon = self.ensure_daemon() + daemon.reset() + for length, char in enumerate(text, 1): + response, ms = daemon.request(f"B {char}") + status, count = classify(response, ms) + if measured: + self.record("incremental", case, rep, length, status, count, ms) + if status.startswith("UNEXPECTED"): + break + except (EOFError, TimeoutError, BrokenPipeError, OSError, RuntimeError) as exc: + if measured: + self.record("incremental", case, rep, length, "CRASH_OR_TIMEOUT", 0, None) + self.drop_daemon(exc) + + def run_whole(self, case: str, text: str, rep: int, measured: bool) -> None: + for length in range(1, len(text) + 1): + try: + daemon = self.ensure_daemon() + daemon.reset() + response, ms = daemon.request(f"B {text[:length]}") + status, count = classify(response, ms) + except (EOFError, TimeoutError, BrokenPipeError, OSError, RuntimeError) as exc: + status, count, ms = "CRASH_OR_TIMEOUT", 0, None + self.drop_daemon(exc) + if measured: + self.record("whole", case, rep, length, status, count, ms) + + def run(self) -> None: + args = self.args + runners = {"incremental": self.run_incremental, "whole": self.run_whole} + for mode in args.modes: + for case in args.cases: + text = repeated(CASES[case], args.max_length) + print(f"# mode={mode} case={case} chars={len(text)} " + f"warmup={args.warmup} reps={args.reps}", flush=True) + for rep in range(-args.warmup, args.reps): + runners[mode](case, text, rep, measured=rep >= 0) + if self.daemon: + self.daemon.close() + self.tmp.cleanup() + + +def percentile(values, q): + ordered = sorted(values) + index = min(len(ordered) - 1, max(0, round(q * (len(ordered) - 1)))) + return ordered[index] + + +def summarize(rows, modes, cases, max_length): + print() + for mode in modes: + for case in cases: + print(f"== mode={mode} case={case} (ms) ==") + print(f"{'len':>3} {'min':>8} {'median':>8} {'p90':>8} {'max':>8} " + f"{'cands':>5} {'ok/n':>6} notes") + for length in range(1, max_length + 1): + sel = [r for r in rows if r[0] == mode and r[1] == case and r[3] == length] + if not sel: + continue + ok = [float(r[6]) for r in sel if r[4] == "CAND"] + counts = [r[5] for r in sel if r[4] == "CAND"] + bad = sorted({r[4] for r in sel if r[4] != "CAND"}) + if ok: + print(f"{length:>3} {min(ok):>8.1f} {statistics.median(ok):>8.1f} " + f"{percentile(ok, 0.9):>8.1f} {max(ok):>8.1f} " + f"{round(statistics.median(counts)):>5} {len(ok):>3}/{len(sel):<2} " + f"{','.join(bad)}") + else: + print(f"{length:>3} {'-':>8} {'-':>8} {'-':>8} {'-':>8} {'-':>5} " + f"{0:>3}/{len(sel):<2} {','.join(bad)}") + print() + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--engine-dir", type=Path, default=Path("/usr/lib/wetype-ime/arm64")) + parser.add_argument("--harness", type=Path, default=None) + parser.add_argument("--qemu", default="qemu-aarch64-static") + parser.add_argument("--sysroot", default="/usr/aarch64-linux-gnu") + parser.add_argument("--min-length", type=int, default=1, + help="shortest length included in the summary") + parser.add_argument("--max-length", type=int, default=60) + parser.add_argument("--modes", nargs="+", choices=["incremental", "whole"], + default=["incremental", "whole"]) + parser.add_argument("--cases", nargs="+", choices=list(CASES), default=list(CASES)) + parser.add_argument("--reps", type=int, default=5) + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--timeout", type=float, default=10.0, + help="per-request protocol timeout in seconds") + parser.add_argument("--startup-timeout", type=float, default=60.0) + parser.add_argument("--output", default="/tmp/wetype-candidate-latency.csv") + args = parser.parse_args() + args.engine_dir = args.engine_dir.resolve() + args.harness = (args.harness or args.engine_dir / "wetype-harness").resolve() + if not 1 <= args.min_length <= args.max_length <= 500: + parser.error("need 1 <= --min-length <= --max-length <= 500") + if args.reps < 1 or args.warmup < 0: + parser.error("--reps must be >= 1 and --warmup >= 0") + for required in (args.harness, args.engine_dir / "lib/libwxhld_jni.so", + args.engine_dir / "dicts"): + if not required.exists(): + parser.error(f"required engine path does not exist: {required}") + + bench = Bench(args) + bench.run() + rows = [r for r in bench.rows if r[3] >= args.min_length] + with open(args.output, "w", newline="", encoding="utf-8") as output_file: + writer = csv.writer(output_file) + writer.writerow(["mode", "case", "rep", "length", "status", "candidates", "elapsed_ms"]) + writer.writerows(rows) + summarize(rows, args.modes, args.cases, args.max_length) + print(f"# daemon restarts: {bench.restarts}") + print(f"# CSV: {args.output}") + print(f"# stderr log: {bench.log_path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/e1_appdir.sh b/scripts/e1_appdir.sh new file mode 100755 index 0000000..4a88469 --- /dev/null +++ b/scripts/e1_appdir.sh @@ -0,0 +1,137 @@ +#!/bin/bash +# e1_appdir.sh — 组装 WeType 输入法 AppDir(对齐 doubao-ime-linux b1 布局) +# AppDir 只含本项目自己的代码(Paper 式):不含任何 APK 里的库或词库。 +# 结构: +# AppDir/usr/lib/wetype-ime/arm64/{lib/{libwetype-shim.so,libz.so.1},wetype-harness,wetype-ime-demo.sh} +# AppDir/usr/lib/wetype-ime/arm64/{qemu-aarch64-static,sysroot/lib/} QEMU + ARM64 glibc(第三方,可再分发) +# AppDir/usr/lib/wetype-ime/scripts/ 安装时下载官方 APK、校验 SHA-256 并在本机打补丁 +# AppDir/usr/bin/{wetype-ime-engine,wetype-demo} +# AppDir/usr/lib/fcitx5/libfcitx5-wetype.so +# 用户可写数据: $XDG_DATA_HOME/wetype-ime/dict (运行时由 harness 通过 WETYPE_WORK_DIR 使用) +set -e +BASE="$(cd "$(dirname "$0")/.." && pwd)" # wetype-ime-linux 根 +APPDIR="$BASE/AppDir" +ENG="$APPDIR/usr/lib/wetype-ime/arm64" +PATCH_SCRIPTS="prepare_assets.sh 10_patch_libs.sh versym_surgery.py 12_rename_syms.py + promote_shim.py 17_disable_scan_sig.py 21_fake_appender.py" + +# Build the project's own ARM64 shim and harness (no APK input needed). +bash "$BASE/scripts/20_build.sh" + +# Package the host Fcitx5 addon along with the ARM64 engine. +"$BASE/fcitx5-wetype/build.sh" +ADDON_SO="$BASE/fcitx5-wetype/build/libfcitx5-wetype.so" +[ -f "$ADDON_SO" ] || { echo "Missing Fcitx5 addon: $ADDON_SO" >&2; exit 1; } + +rm -rf "$APPDIR" +mkdir -p "$ENG/lib" "$APPDIR/usr/lib/wetype-ime/scripts" "$APPDIR/usr/bin" \ + "$APPDIR/usr/lib/fcitx5" "$APPDIR/usr/share/fcitx5/addon" \ + "$APPDIR/usr/share/fcitx5/inputmethod" "$APPDIR/usr/lib/wetype-ime" \ + "$APPDIR/usr/share/applications" \ + "$APPDIR/usr/share/icons/hicolor/256x256/apps" + +# 1. 自有 ARM64 组件 + demo;WeType 引擎库与词库由 install 在用户机器上生成 +cp "$BASE/runtime/libwetype-shim.so" "$BASE/runtime/libz.so.1" "$ENG/lib/" +cp "$BASE/harness/jinterop" "$ENG/wetype-harness" +cp "$BASE/src/wetype-ime-demo.sh" "$ENG/" +chmod +x "$ENG/wetype-ime-demo.sh" + +# 1b. 第三方运行时:静态 QEMU user 模式 + 最小 ARM64 glibc(均可再分发,见 THIRD-PARTY) +QEMU_BIN="${QEMU_AARCH64:-$(command -v qemu-aarch64-static || true)}" +SYSROOT_SRC="${WETYPE_SYSROOT:-/usr/aarch64-linux-gnu}" +[ -n "$QEMU_BIN" ] && [ -x "$QEMU_BIN" ] || { echo "Missing qemu-aarch64-static (qemu-user-static)" >&2; exit 1; } +file -L "$QEMU_BIN" | grep -q 'static' || { echo "$QEMU_BIN is not statically linked" >&2; exit 1; } +cp -L "$QEMU_BIN" "$ENG/qemu-aarch64-static" +mkdir -p "$ENG/sysroot/lib" +for so in ld-linux-aarch64.so.1 libc.so.6 libm.so.6 libdl.so.2 libpthread.so.0; do + [ -f "$SYSROOT_SRC/lib/$so" ] || { echo "Missing ARM64 glibc: $SYSROOT_SRC/lib/$so (libc6-arm64-cross)" >&2; exit 1; } + cp -L "$SYSROOT_SRC/lib/$so" "$ENG/sysroot/lib/" +done +pkg_version() { dpkg-query -W -f '${Version}' "$1" 2>/dev/null || echo unknown; } +mkdir -p "$APPDIR/usr/share/doc/wetype-ime" +cat > "$APPDIR/usr/share/doc/wetype-ime/THIRD-PARTY.md" < "$APPDIR/usr/bin/wetype-ime-engine" < "$APPDIR/usr/bin/wetype-demo" < "$APPDIR/usr/share/applications/wetype-ime.desktop" <<'EOF' +[Desktop Entry] +Type=Application +Name=WeType IME Engine +Comment=微信输入法引擎(候选词驱动, qemu-aarch64 桥) +Exec=wetype-demo nihao +Icon=wetype-ime +Categories=Utility; +Terminal=true +EOF +cp "$BASE/assets/wetype-ime.png" "$APPDIR/usr/share/icons/hicolor/256x256/apps/wetype-ime.png" +cp "$BASE/assets/wetype-ime.png" "$APPDIR/wetype-ime.png" +cp "$APPDIR/usr/share/applications/wetype-ime.desktop" "$APPDIR/" + +# 7. 防线:AppDir 内绝不能出现 APK 派生文件 +leaked="$(find "$APPDIR" \( -name 'libwxhld*' -o -name 'libandromeda*' -o -name 'libcryptopp*' \ + -o -name 'libc++_shared*' -o -name 'libime_net*' -o -name 'libowl*' -o -name 'libprotobuf-lite*' \ + -o -name 'libtensorflowlite*' -o -name 'libwcwss*' -o -name 'libwechatxlog*' \ + -o -name 'index.json' -o -name '*.bin' -o -name '*.apk' \) -print)" +if [ -n "$leaked" ]; then + echo "AppDir 含有 APK 派生文件,拒绝打包:" >&2 + echo "$leaked" >&2 + exit 1 +fi + +echo "== AppDir 就绪 ==" +du -sh "$APPDIR" diff --git a/scripts/e2_img.sh b/scripts/e2_img.sh new file mode 100755 index 0000000..bc72088 --- /dev/null +++ b/scripts/e2_img.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# e2_img.sh — AppImage packaging with a pinned appimagetool release. +set -eo pipefail +BASE="$(cd "$(dirname "$0")/.." && pwd)" +cd "$BASE" +TOOL="${APPIMAGETOOL:-$BASE/.deps/tools/appimagetool-1.9.1-x86_64.AppImage}" +if [ ! -x "$TOOL" ]; then + echo "== 下载 appimagetool 1.9.1 ==" + mkdir -p "$(dirname "$TOOL")" + curl -fL --retry 3 -o "$TOOL" \ + https://github.com/AppImage/appimagetool/releases/download/1.9.1/appimagetool-x86_64.AppImage + chmod +x "$TOOL" +fi +bash scripts/e1_appdir.sh +cp AppDir/usr/share/applications/wetype-ime.desktop AppDir/ +ARCH="${ARCH:-$(uname -m)}" +OUT="WeTypeIME-Engine-${ARCH}.AppImage" +rm -f WeTypeIME-Engine-*.AppImage +TOOL_ARGS=(--comp zstd) +if [ -n "${APPIMAGE_RUNTIME:-}" ]; then + TOOL_ARGS+=(--runtime-file "$APPIMAGE_RUNTIME") +fi +ARCH="$ARCH" "$TOOL" "${TOOL_ARGS[@]}" AppDir "$OUT" 2>&1 | tail -3 +ls -la "$OUT" | awk '{print $5, $9}' +if [ -f WeTypeIME-Engine-x86_64.AppImage ]; then + ls -la WeTypeIME-Engine-x86_64.AppImage | awk '{print $5, $9}' +fi diff --git a/scripts/e3_verify.sh b/scripts/e3_verify.sh new file mode 100755 index 0000000..2c377a1 --- /dev/null +++ b/scripts/e3_verify.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# e3_verify.sh — 交付版验证矩阵 (对齐 doubao b3/b7) +set -e +BASE="$(cd "$(dirname "$0")/.." && pwd)" +cd "$BASE" +WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/wetype-verify.XXXXXX")" +trap 'rm -rf "$WORK_DIR"' EXIT +# 优先验证已安装的引擎(AppImage install 生成),否则用源码树 runtime/ +if [ -z "${WETYPE_ENGINE_DIR:-}" ]; then + for d in "$HOME/.local/lib/wetype-ime/arm64" /usr/lib/wetype-ime/arm64; do + if [ -f "$d/lib/libwxhld_jni.so" ]; then export WETYPE_ENGINE_DIR="$d"; break; fi + done +fi +echo "引擎目录: ${WETYPE_ENGINE_DIR:-$BASE (源码树)}" +mkdir -p "$WORK_DIR/userdict/v5" "$WORK_DIR/userdict/user_hot_word" +export WETYPE_WORK_DIR="$WORK_DIR" +echo "--- 1. nihao → 候选 ---" +bash src/wetype-ime-demo.sh nihao | tail -1 +echo "--- 2. zhongguo → 候选 ---" +bash src/wetype-ime-demo.sh zhongguo | tail -1 +echo "--- 3. 用户词库目录 ---" +ls "$WETYPE_WORK_DIR/userdict/" 2>/dev/null || echo "(尚未生成)" +echo "--- 4. 选词学习验证 (拟好 rank2 → 选词后 rank1) ---" +WETYPE_TEST_LEARN=1 LD_LIBRARY_PATH="$PWD/runtime" \ + timeout 150 "${QEMU_AARCH64:-qemu-aarch64-static}" -L "${WETYPE_SYSROOT:-/usr/aarch64-linux-gnu}" \ + ./harness/jinterop runtime/libwxhld_jni.so 2>/dev/null | grep -E '\[A\] rank|\[B\] rank' | head -6 diff --git a/scripts/prepare_assets.sh b/scripts/prepare_assets.sh new file mode 100755 index 0000000..d76f675 --- /dev/null +++ b/scripts/prepare_assets.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Fetch (or take) the pinned WeType APK and extract only the files this project uses. +# The binary patches target one exact build, so every APK is checked against its SHA-256. +set -euo pipefail + +WETYPE_VERSION=3.5.4 +WETYPE_APK_URL="https://download.z.weixin.qq.com/app/android/$WETYPE_VERSION/wxkb_1308_32.apk" +WETYPE_APK_SHA256=7b57a5a9ab3aefd30413165f298213961bd201815ab48c6ad205c3b2950a90fb + +BASE="$(cd "$(dirname "$0")/.." && pwd)" +APK="${1:-}" +DEST="${WETYPE_APK_ROOT:-$BASE/.deps/wechat-ime}" +CACHE="${WETYPE_APK_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/wetype-ime}" + +if [[ $# -gt 1 || "$APK" == -* ]]; then + echo "Usage: $0 [/path/to/WeType-$WETYPE_VERSION.apk]" >&2 + echo "Without an APK, WeType $WETYPE_VERSION is downloaded from Tencent's official server." >&2 + exit 2 +fi +for tool in unzip sha256sum; do + command -v "$tool" >/dev/null || { echo "Missing dependency: $tool" >&2; exit 1; } +done + +apk_ok() { [[ "$(sha256sum "$1" | cut -d' ' -f1)" == "$WETYPE_APK_SHA256" ]]; } + +if [[ -z "$APK" ]]; then + APK="$CACHE/wetype_$WETYPE_VERSION.apk" + if [[ -f "$APK" ]] && apk_ok "$APK"; then + echo "Using cached WeType $WETYPE_VERSION APK: $APK" + else + mkdir -p "$CACHE" + echo "Downloading WeType $WETYPE_VERSION APK (214 MB) from $WETYPE_APK_URL" + if command -v curl >/dev/null; then + curl -fL --retry 3 -o "$APK.part" "$WETYPE_APK_URL" + elif command -v wget >/dev/null; then + wget -O "$APK.part" "$WETYPE_APK_URL" + else + echo "Missing dependency: curl or wget" >&2 + exit 1 + fi + mv "$APK.part" "$APK" + fi +elif [[ ! -f "$APK" ]]; then + echo "APK not found: $APK" >&2 + exit 1 +fi + +if ! apk_ok "$APK"; then + echo "SHA-256 mismatch for $APK" >&2 + echo "Only WeType $WETYPE_VERSION ($WETYPE_APK_SHA256) is supported." >&2 + exit 1 +fi + +TMP="$(mktemp -d "${TMPDIR:-/tmp}/wetype-apk.XXXXXX")" +trap 'rm -rf "$TMP"' EXIT + +unzip -q "$APK" 'lib/arm64-v8a/*' 'assets/config/beta/*' -d "$TMP" +[[ -f "$TMP/lib/arm64-v8a/libwxhld_jni.so" ]] || { + echo "APK is missing lib/arm64-v8a/libwxhld_jni.so" >&2 + exit 1 +} +[[ -f "$TMP/assets/config/beta/index.json" ]] || { + echo "APK is missing assets/config/beta/index.json" >&2 + exit 1 +} + +mkdir -p "$DEST" +rm -rf "$DEST/lib" "$DEST/assets" +cp -a "$TMP/lib" "$TMP/assets" "$DEST/" +printf 'Prepared APK inputs at %s\n' "$DEST" diff --git a/scripts/promote_shim.py b/scripts/promote_shim.py new file mode 100644 index 0000000..90922a8 --- /dev/null +++ b/scripts/promote_shim.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""把 libwetype-shim.so 提为库的第一个 DT_NEEDED。 +patchelf --add-needed 只能追加到末尾(排在 libc 之后,stdio 包装无法压过 glibc 原版), +这里直接交换动态数组里两个 DT_NEEDED 的字符串偏移,把 shim 挪到最前。 +""" +import struct, sys, os + +DT_NEEDED = 1 +SHIM = b'libwetype-shim.so' + +def reorder(path: str) -> str: + b = bytearray(open(path, 'rb').read()) + e_phoff, = struct.unpack_from(' str: + return (text * ((length + len(text) - 1) // len(text)))[:length] + + +def read_line(proc: subprocess.Popen, timeout: float) -> str: + ready, _, _ = select.select([proc.stdout], [], [], timeout) + if not ready: + raise TimeoutError(f"no protocol response after {timeout:.1f}s") + line = proc.stdout.readline() + if not line: + raise EOFError(f"daemon exited (returncode={proc.poll()})") + return line.rstrip("\r\n") + + +def classify(response: str): + if response == "OK": + return "OK", 0 + if response.startswith("CAND\t"): + return "CAND", len(response.split("\t")) - 1 + if response == "EMPTY": + return "EMPTY", 0 + return f"UNEXPECTED:{response[:40]}", 0 + + +def run_case(name: str, sequence: str, batch_size: int, args, result_rows: list) -> None: + with tempfile.TemporaryDirectory(prefix=f"wetype-{name}-") as work_dir: + log_path = Path(args.output).with_name(f"{Path(args.output).stem}-{name}.stderr.log") + env = os.environ.copy() + env.update({ + "LD_LIBRARY_PATH": f"{args.engine_dir}/lib", + "WETYPE_LIB_DIR": f"{args.engine_dir}/lib", + "WETYPE_DICT_DIR": f"{args.engine_dir}/dicts", + "WETYPE_ASSET_DIR": f"{args.engine_dir}/dicts", + "WETYPE_WORK_DIR": work_dir, + "WETYPE_HARNESS_LOG": str(log_path), + }) + command = [args.qemu, "-L", args.sysroot, str(args.harness), + str(args.engine_dir / "lib/libwxhld_jni.so"), "--daemon"] + started = time.monotonic() + with open(log_path, "w", encoding="utf-8") as stderr_file: + proc = subprocess.Popen(command, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=stderr_file, + text=True, bufsize=1, env=env) + try: + ready = read_line(proc, args.timeout) + if ready != "READY": + raise RuntimeError(f"expected READY, received {ready!r}") + print(f"# case={name} chars={len(sequence)} batch={batch_size}", flush=True) + length = 0 + + def request(command: str, phase: str, prefix: str) -> str: + nonlocal length + before = time.monotonic() + proc.stdin.write(command + "\n") + proc.stdin.flush() + response = read_line(proc, args.timeout) + elapsed_ms = (time.monotonic() - before) * 1000 + status, count = classify(response) + row = [name, batch_size, length, phase, prefix, status, count, + f"{elapsed_ms:.1f}", ""] + result_rows.append(row) + print(",".join(map(str, row[:-1]))) + return status + + if args.backspace_every_length: + for length, char in enumerate(sequence, 1): + prefix = sequence[:length] + status = request(f"B {char}", "TYPE", prefix) + if status.startswith("UNEXPECTED:"): + break + if request("C", "BACKSPACE_CLEAR", sequence[:length - 1]) != "OK": + raise RuntimeError("C did not return OK during backspace simulation") + if length > 1: + status = request(f"B {sequence[:length - 1]}", + "BACKSPACE_REPLAY", sequence[:length - 1]) + if status.startswith("UNEXPECTED:"): + break + status = request(f"B {char}", "RETYPE", prefix) + if status.startswith("UNEXPECTED:"): + break + else: + while length < len(sequence): + chunk = sequence[length:length + batch_size] + length += len(chunk) + status = request(f"B {chunk}", "TYPE", sequence[:length]) + if status.startswith("UNEXPECTED:"): + break + proc.stdin.write("Q\n") + proc.stdin.flush() + try: + read_line(proc, args.timeout) + except (EOFError, TimeoutError): + pass + proc.wait(timeout=args.timeout) + except (EOFError, TimeoutError, BrokenPipeError, OSError) as exc: + code = proc.poll() + result_rows.append([name, batch_size, length, "CRASH_OR_TIMEOUT", + sequence[:length], "CRASH_OR_TIMEOUT", 0, "", str(exc)]) + print(f"# {name}: CRASH_OR_TIMEOUT: {exc}; returncode={code}; log={log_path}", + file=sys.stderr, flush=True) + if proc.poll() is None: + proc.kill() + proc.wait() + finally: + if proc.stdin and not proc.stdin.closed: + proc.stdin.close() + print(f"# {name}: elapsed={time.monotonic() - started:.1f}s log={log_path}", + flush=True) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--engine-dir", type=Path, + default=Path("/usr/lib/wetype-ime/arm64")) + parser.add_argument("--harness", type=Path, default=None) + parser.add_argument("--qemu", default="qemu-aarch64-static") + parser.add_argument("--sysroot", default="/usr/aarch64-linux-gnu") + parser.add_argument("--max-length", type=int, default=32) + parser.add_argument("--batch-sizes", type=int, nargs="+", default=[1, 4], + help="characters sent per B request (addon normally caps batches at 4)") + parser.add_argument("--backspace-every-length", action="store_true", + help="at each length, simulate Backspace (C + replay) and retype") + parser.add_argument("--cases", nargs="+", + choices=["nihao_repeat", "ni_repeat", "sentence_ni_juede_xiaogouruhe"], + default=None) + parser.add_argument("--timeout", type=float, default=10.0) + parser.add_argument("--output", default="/tmp/wetype-length-threshold.csv") + args = parser.parse_args() + args.engine_dir = args.engine_dir.resolve() + args.harness = (args.harness or args.engine_dir / "wetype-harness").resolve() + if args.max_length < 1: + parser.error("--max-length must be positive") + for required in (args.harness, args.engine_dir / "lib/libwxhld_jni.so", + args.engine_dir / "dicts"): + if not required.exists(): + parser.error(f"required engine path does not exist: {required}") + + cases = { + "nihao_repeat": repeated("nihao", args.max_length), + "ni_repeat": repeated("ni", args.max_length), + "sentence_ni_juede_xiaogouruhe": repeated("nijuede" + "xiaogouruhe", + args.max_length), + } + rows = [] + print("case,batch_size,length,phase,prefix,status,candidates,elapsed_ms") + for batch_size in args.batch_sizes: + if batch_size < 1 or batch_size > 16: + parser.error("batch sizes must be between 1 and 16") + selected_cases = args.cases or list(cases) + for name in selected_cases: + run_case(name, cases[name], batch_size, args, rows) + with open(args.output, "w", newline="", encoding="utf-8") as output_file: + writer = csv.writer(output_file) + writer.writerow(["case", "batch_size", "length", "phase", "prefix", "status", + "candidates", "elapsed_ms", "detail"]) + writer.writerows(rows) + print(f"# CSV: {args.output}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/versym_surgery.py b/scripts/versym_surgery.py new file mode 100644 index 0000000..264e145 --- /dev/null +++ b/scripts/versym_surgery.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""ELF surgery for WeType arm64 libs → glibc/qemu-aarch64. + +glibc 2.39 dl-version.c 铁律(源码实测): +- l_versions 仅当 ndx_high>0(存在 VERNEED 或 VERDEF)才分配; +- VERNEED 在 → match_symbol 校验 "LIBC" 版本(bionic 版本名 glibc 没有)→ 报错; +- VERNEED 删掉后: + * 无 VERDEF 的库:ndx_high=0 → l_versions=NULL、l_versyms=NULL, + 但 DT_VERSYM tag 还在 → dl-reloc 读 l_versyms[symidx] → 空指针崩。 + ⇒ 必须连 DT_VERSYM tag 一起删(此后所有符号查找走无版本路径)。 + * 有 VERDEF 的库(tflite):ndx_high>0 → 走分配分支时 + map->l_versyms = D_PTR(map, l_info[VERSYM]),若 VERSYM tag 已删则 + 对 NULL 动态项解引用(Elf64_Dyn.d_un 恰在 +8)→ 崩。 + ⇒ 必须保留 DT_VERSYM,并把 .gnu.version 条目全写 0: + l_versions[0] 恒为 calloc 零槽(hash=0)→ 查找自动降级为无版本。 +""" +import struct, sys, os + +DT_VERNEED = 0x6ffffffe +DT_VERSYM = 0x6ffffff0 +DT_VERDEF = 0x6ffffffd + +def patch(path: str) -> str: + b = bytearray(open(path, 'rb').read()) + e_phoff, = struct.unpack_from(' +#include +#include +#include + +#define GZ_HEAD 0xCAFEF00DBEEF0001ULL +#define GZ_TAIL 0xCAFEF00DBEEF0002ULL +#define GZ_PAD 32 +typedef struct { unsigned long magic; size_t size; void *site; unsigned long pad; } GzHead; + +static void *(*r_malloc)(size_t); +static void *(*r_calloc)(size_t, size_t); +static void *(*r_realloc)(void *, size_t); +static void (*r_free)(void *); +static int inited; + +#define LIVE_MAX 200000 +static struct { unsigned char *raw; size_t size; void *site; int alive; } live[LIVE_MAX]; +static int live_n, free_cnt; + +static void init(void) { + if (inited) return; + r_malloc = dlsym(RTLD_NEXT, "malloc"); + r_calloc = dlsym(RTLD_NEXT, "calloc"); + r_realloc = dlsym(RTLD_NEXT, "realloc"); + r_free = dlsym(RTLD_NEXT, "free"); + inited = 1; +} +void *malloc(size_t n) { + init(); + unsigned char *raw = r_malloc(n + sizeof(GzHead) + GZ_PAD); + if (!raw) return 0; + GzHead *h = (GzHead *)raw; + h->magic = GZ_HEAD; h->size = n; h->site = __builtin_return_address(0); h->pad = 0; + *(unsigned long *)(raw + sizeof(GzHead) + n) = GZ_TAIL; + if (live_n < LIVE_MAX) { live[live_n].raw = raw; live[live_n].size = n; live[live_n].site = h->site; live[live_n].alive = 1; live_n++; } + return raw + sizeof(GzHead); +} +void *calloc(size_t a, size_t b) { + init(); + size_t n = a * b; + void *p = malloc(n); + if (p) memset(p, 0, n); + return p; +} +void *realloc(void *q, size_t n) { + init(); + if (!q) return malloc(n); + GzHead *h = (GzHead *)((unsigned char *)q - sizeof(GzHead)); + if (h->magic != GZ_HEAD) { void *p = r_realloc(q, n); if (p) fprintf(stderr, "[dg] realloc 非 wrapping 块 %p\n", q); return p; } + size_t old = h->size; + void *p = malloc(n); + if (p) { memcpy(p, q, old < n ? old : n); free(q); } + return p; +} +void free(void *p) { + init(); + if (!p) { r_free(0); return; } + unsigned char *raw = (unsigned char *)p - sizeof(GzHead); + GzHead *h = (GzHead *)raw; + if (h->magic == GZ_HEAD) { + if (*(unsigned long *)(raw + sizeof(GzHead) + h->size) != GZ_TAIL) + fprintf(stderr, "[dg] 越界写!! site=%p size=%lu\n", h->site, (unsigned long)h->size); + if (++free_cnt % 200 == 0) + for (int i = 0; i < live_n; i++) + if (live[i].alive && *(unsigned long *)(live[i].raw + sizeof(GzHead) + live[i].size) != GZ_TAIL) { + fprintf(stderr, "[dg-audit] #%d site=%p size=%lu 被踩!\n", i, live[i].site, (unsigned long)live[i].size); + live[i].alive = 0; + } + h->magic = 0; + r_free(raw); + } else { + r_free(p); /* 非包装块:ld.so 早期分配等 */ + } +} diff --git a/shim/wetype-shim.c b/shim/wetype-shim.c new file mode 100644 index 0000000..41af84c --- /dev/null +++ b/shim/wetype-shim.c @@ -0,0 +1,604 @@ +#define _GNU_SOURCE +/* libwetype-shim: bionic liblog/__sF 替身,仅覆盖微信输入法引擎闭包实际引用的符号。 + 未覆盖的符号在 dlopen 报错时按需补充。 */ +#include +#include +#include +#include +#include + +/* ---- bionic __sF:bionic 代码按 sizeof(bionic FILE)=152 计算各元素的地址, + 而真 glibc FILE 是 216B+vtable,两种布局无法共存于同一块内存。 + 方案:__sF 只做 3×152B 占位符,拦截所有 FILE* 传参的 stdio 入口, + 把落在占位区间内的指针映射回 glibc 真实 stdin/stdout/stderr 后转发。 */ +#include +#include +#include +#include + +char __sF[3 * 152]; +#define WSF_STRIDE 152 + +static FILE *wsf_map(FILE *p) { + unsigned long off = (unsigned long)p - (unsigned long)(void *)__sF; + if (off < 3 * WSF_STRIDE) { + switch (off / WSF_STRIDE) { + case 0: return stdin; + case 1: return stdout; + default: return stderr; + } + } + return p; +} + +/* RTLD_NEXT 取真函数,惰性初始化 */ +/* RTLD_NEXT 取真函数,惰性初始化(显式类型,避开 __typeof__ 限制) */ +static int (*real_fclose)(FILE *); +static int (*real_feof)(FILE *); +static int (*real_ferror)(FILE *); +static int (*real_fflush)(FILE *); +static int (*real_fgetc)(FILE *); +static int (*real_fputc)(int, FILE *); +static int (*real_fputs)(const char *, FILE *); +static size_t (*real_fread)(void *, size_t, size_t, FILE *); +static size_t (*real_fwrite)(const void *, size_t, size_t, FILE *); +static int (*real_fseek)(FILE *, long, int); +static int (*real_fseeko)(FILE *, off_t, int); +static long (*real_ftell)(FILE *); +static off_t (*real_ftello)(FILE *); +static int (*real_vfprintf)(FILE *, const char *, va_list); + +static int w_is_self(void *p) { + Dl_info a, b; + if (!dladdr((void *)w_is_self, &a)) return 0; + if (!dladdr(p, &b)) return 0; + return a.dli_fbase == b.dli_fbase; +} +static void *wreal(const char *n, void *cur) { + if (cur) return cur; + void *p = dlsym(RTLD_NEXT, n); + if (!p || w_is_self(p)) { + /* shim 以依赖身份被 RTLD_LOCAL 加载时不在全局作用域,RTLD_NEXT 会失败; + 回退 RTLD_DEFAULT(全局作用域),若解析回自身则放弃防递归 */ + p = dlsym(RTLD_DEFAULT, n); + if (p && w_is_self(p)) p = 0; + } + return p; +} + +#define WSTDIO(name, ret, argdecl, arguse, realargs) \ +static ret w_##name(argdecl) { \ + return ((ret (*)())wreal(#name, real_##name))(realargs); \ +} + +static int w_fclose(FILE *f) { return ((int (*)(FILE *))wreal("fclose", real_fclose))(wsf_map(f)); } +static int w_feof(FILE *f) { return ((int (*)(FILE *))wreal("feof", real_feof))(wsf_map(f)); } +static int w_ferror(FILE *f) { return ((int (*)(FILE *))wreal("ferror", real_ferror))(wsf_map(f)); } +static int w_fflush(FILE *f) { return ((int (*)(FILE *))wreal("fflush", real_fflush))(wsf_map(f)); } +static int w_fgetc(FILE *f) { return ((int (*)(FILE *))wreal("fgetc", real_fgetc))(wsf_map(f)); } +static int w_fputc(int c, FILE *f) { return ((int (*)(int, FILE *))wreal("fputc", real_fputc))(c, wsf_map(f)); } +static int w_fputs(const char *s, FILE *f) { return ((int (*)(const char *, FILE *))wreal("fputs", real_fputs))(s, wsf_map(f)); } +static size_t w_fread(void *b, size_t n, size_t m, FILE *f) { return ((size_t (*)(void *, size_t, size_t, FILE *))wreal("fread", real_fread))(b, n, m, wsf_map(f)); } +static size_t w_fwrite(const void *b, size_t n, size_t m, FILE *f) { return ((size_t (*)(const void *, size_t, size_t, FILE *))wreal("fwrite", real_fwrite))(b, n, m, wsf_map(f)); } +static int w_fseek(FILE *f, long o, int w) { return ((int (*)(FILE *, long, int))wreal("fseek", real_fseek))(wsf_map(f), o, w); } +static int w_fseeko(FILE *f, off_t o, int w) { return ((int (*)(FILE *, off_t, int))wreal("fseeko", real_fseeko))(wsf_map(f), o, w); } +static long w_ftell(FILE *f) { return ((long (*)(FILE *))wreal("ftell", real_ftell))(wsf_map(f)); } +static off_t w_ftello(FILE *f) { return ((off_t (*)(FILE *))wreal("ftello", real_ftello))(wsf_map(f)); } +static int w_vfprintf(FILE *f, const char *fmt, va_list ap) { return ((int (*)(FILE *, const char *, va_list))wreal("vfprintf", real_vfprintf))(wsf_map(f), fmt, ap); } + +int fclose(FILE *f) { return w_fclose(f); } +int feof(FILE *f) { return w_feof(f); } +int ferror(FILE *f) { return w_ferror(f); } +int fflush(FILE *f) { return w_fflush(f); } +int fgetc(FILE *f) { return w_fgetc(f); } +int fputc(int c, FILE *f) { return w_fputc(c, f); } +int fputs(const char *s, FILE *f) { return w_fputs(s, f); } +size_t fread(void *b, size_t n, size_t m, FILE *f) { return w_fread(b, n, m, f); } +size_t fwrite(const void *b, size_t n, size_t m, FILE *f) { return w_fwrite(b, n, m, f); } +int fseek(FILE *f, long o, int w) { return w_fseek(f, o, w); } +int fseeko(FILE *f, off_t o, int w) { return w_fseeko(f, o, w); } +long ftell(FILE *f) { return w_ftell(f); } +off_t ftello(FILE *f) { return w_ftello(f); } +int fprintf(FILE *f, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + int r = w_vfprintf(f, fmt, ap); + va_end(ap); + return r; +} + +static const char *prio_name(int prio) { + switch (prio) { + case 2: return "V"; case 3: return "D"; case 4: return "I"; + case 5: return "W"; case 6: return "E"; case 7: return "F"; + default: return "?"; + } +} + +int __android_log_write(int prio, const char *tag, const char *text) { + return fprintf(stderr, "[alog %s/%s] %s\n", prio_name(prio), tag ? tag : "-", text ? text : ""); +} + +int __android_log_vprint(int prio, const char *tag, const char *fmt, va_list ap) { + char buf[4096]; + vsnprintf(buf, sizeof(buf), fmt ? fmt : "", ap); + return __android_log_write(prio, tag, buf); +} + +int __android_log_print(int prio, const char *tag, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + int r = __android_log_vprint(prio, tag, fmt, ap); + va_end(ap); + return r; +} + +int __android_log_buf_write(int bufID, int prio, const char *tag, const char *text) { + (void)bufID; + return __android_log_write(prio, tag, text); +} + +int __android_log_buf_print(int bufID, int prio, const char *tag, const char *fmt, ...) { + (void)bufID; + va_list ap; + va_start(ap, fmt); + int r = __android_log_vprint(prio, tag, fmt, ap); + va_end(ap); + return r; +} + +int __android_log_is_loggable(int prio, const char *tag, int def) { + (void)prio; (void)tag; + return def; +} + +/* ---- bionic abort 消息接甲:libc++_shared 引用,转为 stderr 打印 ---- */ +void android_set_abort_message(const char *msg) { + fprintf(stderr, "[abort-message] %s\n", msg ? msg : "(null)"); +} + +/* ---- bionic errno 入口 ---- */ +int *__errno(void) { + return __errno_location(); +} + +/* ---- bionic system property 接甲:返回空值,按需再伪造具体属性 ---- */ +#include + +int __system_property_get(const char *name, char *value) { + (void)name; + if (value) value[0] = '\0'; + return 0; +} + +const void *__system_property_find(const char *name) { + (void)name; + return NULL; +} + +void __system_property_read_callback(const void *pi, + void (*cb)(void *, const char *, const char *, unsigned int), + void *cookie) { + (void)pi; (void)cb; (void)cookie; +} + +int __system_property_foreach(void (*cb)(const void *, void *), void *cookie) { + (void)cb; (void)cookie; + return 0; +} + +int android_get_device_api_level(void) { + return 34; /* 冒充 Android 14 */ +} + +/* ---- Android looper 接甲(andromeda):假 looper,poll 恒超时 ---- */ +static int fake_looper; + +void *ALooper_prepare(void) { return &fake_looper; } +void ALooper_acquire(void *looper) { (void)looper; } +void ALooper_release(void *looper) { (void)looper; } +int ALooper_pollOnce(int timeoutMs, int *outFd, int *outEvents, void **outData) { + if (outFd) *outFd = -1; + if (outEvents) *outEvents = 0; + if (outData) *outData = 0; + (void)timeoutMs; + return 3; /* ALOOPER_POLL_TIMEOUT */ +} +int ALooper_addFd(void *looper, int fd, int ident, int events, + int (*cb)(int, int, void *), void *data) { + (void)looper; (void)fd; (void)ident; (void)events; (void)cb; (void)data; + return 1; +} +int ALooper_removeFd(void *looper, int fd) { (void)looper; (void)fd; return 1; } + +/* ---- bionic resolver:wxhld 引用,glibc 的 res_init 不可直接等价,空实现 ---- */ +int res_init(void) { return 0; } + +/* ---- bionic __pthread_cleanup_push/pop:glibc 无此导出(只有 __pthread_cleanup_routine)。 + xlog 等库直接引用。自维护链表实现,语义与 bionic 宏展开一致。 ---- */ +typedef struct wpcu { + struct wpcu *prev; + void (*fn)(void *); + void *arg; +} wpcu_t; +static wpcu_t *g_wpcu_top; +void __pthread_cleanup_push(wpcu_t *c, void (*fn)(void *), void *arg) { + c->prev = g_wpcu_top; c->fn = fn; c->arg = arg; g_wpcu_top = c; +} +void __pthread_cleanup_pop(wpcu_t *c, int execute) { + g_wpcu_top = c->prev; + if (execute && c->fn) c->fn(c->arg); +} + +/* ---- NDK AAsset 家族:磁盘文件后端。引擎读词库用 openFileDescriptor 拿 fd。 ---- */ +typedef struct { FILE *f; long size; } wasset_t; +static const char *g_asset_roots[] = { + "assets/", "runtime/assets/", ".deps/wechat-ime/assets/", +}; +void *AAssetManager_fromJava(void *env, void *am) { + (void)env; (void)am; + static int wam_token; + return &wam_token; +} +void *AAssetManager_open(void *mgr, const char *path, long mode) { + (void)mgr; (void)mode; + char full[600]; + for (unsigned i = 0; i < sizeof(g_asset_roots)/sizeof(g_asset_roots[0]); i++) { + snprintf(full, sizeof full, "%s%s", g_asset_roots[i], path); + FILE *f = fopen(full, "rb"); + if (!f) continue; + fseek(f, 0, SEEK_END); + long size = ftell(f); + fseek(f, 0, SEEK_SET); + wasset_t *a = malloc(sizeof(wasset_t)); + a->f = f; a->size = size; + return a; + } + return NULL; +} +long AAsset_openFileDescriptor(void *asset, int *fd, long *offset) { + wasset_t *a = asset; + if (!a || !a->f) return -1; + *fd = dup(fileno(a->f)); + *offset = 0; + return 0; +} +void AAsset_close(void *asset) { + wasset_t *a = asset; + if (a) { if (a->f) fclose(a->f); free(a); } +} + +/* ---- 大写别名:消费者库的 .dynstr 已被 12_rename_syms.py 改写指向这些名字。 + 名字独一无二,符号查找顺序无关。 ---- */ +int Fflush(FILE *f) { return w_fflush(f); } +int Fprintf(FILE *f, const char *fmt, ...) { + va_list ap; va_start(ap, fmt); + int r = w_vfprintf(f, fmt, ap); + va_end(ap); return r; +} +int Vfprintf(FILE *f, const char *fmt, va_list ap) { return w_vfprintf(f, fmt, ap); } +int Fwrite(const void *b, size_t n, size_t m, FILE *f) { return w_fwrite(b, n, m, f); } +int Fputs(const char *s, FILE *f) { return w_fputs(s, f); } +size_t Fread(void *b, size_t n, size_t m, FILE *f) { return w_fread(b, n, m, f); } +int Fgetc(FILE *f) { return w_fgetc(f); } +int Fputc(int c, FILE *f) { return w_fputc(c, f); } +int Fclose(FILE *f) { return w_fclose(f); } +int Feof(FILE *f) { return w_feof(f); } +int Ferror(FILE *f) { return w_ferror(f); } +int Fseek(FILE *f, long o, int w) { return w_fseek(f, o, w); } +int Fseeko(FILE *f, off_t o, int w) { return w_fseeko(f, o, w); } +long Ftell(FILE *f) { return w_ftell(f); } +off_t Ftello(FILE *f) { return w_ftello(f); } + +/* ---- bionic FORTIFY _chk 桩(glibc 没有,其余 __*_chk glibc 自带) ---- */ +#include +#include +#include +#include + +size_t __strlen_chk(const char *s, size_t n) { (void)n; return strlen(s); } +char *__strchr_chk(const char *p, int ch, size_t n) { (void)n; return strchr(p, ch); } +char *__strrchr_chk(const char *p, int ch, size_t n) { (void)n; return strrchr(p, ch); } +char *__strncpy_chk2(char *dst, const char *src, size_t n, + size_t dst_size, size_t src_size) { + (void)dst_size; (void)src_size; + return strncpy(dst, src, n); +} +void __FD_SET_chk(int fd, fd_set *set, size_t sz) { (void)sz; FD_SET(fd, set); } +void __FD_CLR_chk(int fd, fd_set *set, size_t sz) { (void)sz; FD_CLR(fd, set); } +int __FD_ISSET_chk(int fd, fd_set *set, size_t sz) { (void)sz; return FD_ISSET(fd, set); } + + +/* ============ mmap 区间登记:free(mmap指针) → munmap ============ */ +#define MM_MAX 4096 +static struct { void *base; size_t len; } g_mm[MM_MAX]; +static int g_mm_n = 0; +static volatile int g_mm_lock = 0; +static __thread int g_inmm = 0; +static int mm_contains(void *p); +static void mm_lock(void) { while (__sync_lock_test_and_set(&g_mm_lock, 1)) ; } +static void mm_unlock(void) { __sync_lock_release(&g_mm_lock); } +void *mmap(void *addr, size_t len, int prot, int flags, int fd, long off) { + void *(*r)(void *, size_t, int, int, int, long) = wreal("mmap", 0); + void *p = r(addr, len, prot, flags, fd, off); + if (p != (void *)-1 && !g_inmm) { + g_inmm = 1; + mm_lock(); + if (g_mm_n < MM_MAX) { g_mm[g_mm_n].base = p; g_mm[g_mm_n].len = len; g_mm_n++; } + mm_unlock(); + g_inmm = 0; + } + return p; +} +int munmap(void *addr, size_t len) { + int (*r)(void *, size_t) = wreal("munmap", 0); + if (!g_inmm) { + g_inmm = 1; + mm_lock(); + for (int i = 0; i < g_mm_n; i++) + if (g_mm[i].base == addr) { g_mm[i] = g_mm[g_mm_n - 1]; g_mm_n--; break; } + mm_unlock(); + g_inmm = 0; + } + return r(addr, len); +} +/* ============ 分配登记表:只释放自己分配的指针 ============ + * 引擎在 bionic(jemalloc)上开发,会把非 malloc 指针/被踩坏的指针丢给 free; + * glibc 严格校验直接 abort("free(): invalid pointer/size")。这里保留 glibc + * 堆语义(引擎依赖它),但把每个 malloc 结果登记下来:free 时只有在登记表中 + * 的指针才真正交给 glibc 释放,其余一律跳过(泄漏可接受,换来不崩)。 + */ +#define REG_BITS 21 +#define REG_SIZE (1u << REG_BITS) +typedef struct { void *p; size_t n; } RegEnt; +static RegEnt *g_reg = 0; +static volatile int g_reg_lock = 0; +static void reg_lock(void) { while (__sync_lock_test_and_set(&g_reg_lock, 1)) {} } +static void reg_unlock(void) { __sync_lock_release(&g_reg_lock); } +void *Malloc(size_t n); +void Free(void *p); +static void dbg(const char *fmt, ...) { + char b[256]; va_list ap; va_start(ap, fmt); + int n = vsnprintf(b, sizeof b, fmt, ap); va_end(ap); + if (n > 0) { ssize_t _w = write(2, b, n); (void)_w; } +} +static void reg_init(void) { + if (g_reg) return; + long r = syscall(SYS_mmap, 0, REG_SIZE * sizeof(RegEnt), PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + if (r > 0) { + g_reg = (RegEnt *)r; + char b[160]; + int n = snprintf(b, sizeof b, "[reg] 登记表 %u 槽 %zu MB [shim] Malloc=%p Free=%p\n", + REG_SIZE, (size_t)(REG_SIZE * sizeof(RegEnt)) >> 20, + (void *)&Malloc, (void *)&Free); + if (n > 0) { ssize_t _w = write(2, b, n); (void)_w; } + } +} +static unsigned int reg_hash(void *p) { + unsigned long long x = (unsigned long long)(unsigned long)p >> 4; + x *= 0x9E3779B97F4A7C15ULL; + return (unsigned int)(x >> (64 - REG_BITS)); +} +#define REG_TOMB ((void *)1) +static void reg_put(void *p, size_t n) { + if (!p) return; + if (!g_reg) reg_init(); + if (!g_reg) return; + reg_lock(); + unsigned int i = reg_hash(p); + int placed = 0; + unsigned int tomb = (unsigned int)-1; + for (unsigned int k = 0; k < REG_SIZE; k++) { + unsigned int j = (i + k) & (REG_SIZE - 1); + if (g_reg[j].p == p) { g_reg[j].n = n; placed = 1; break; } + if (g_reg[j].p == REG_TOMB && tomb == (unsigned int)-1) tomb = j; + if (!g_reg[j].p) { + if (tomb != (unsigned int)-1) j = tomb; + g_reg[j].p = p; g_reg[j].n = n; placed = 1; break; + } + } + reg_unlock(); + (void)placed; +} +static int reg_take(void *p, size_t *n) { + if (!g_reg) return 0; + reg_lock(); + unsigned int i = reg_hash(p); + int found = 0; + for (unsigned int k = 0; k < REG_SIZE; k++) { + unsigned int j = (i + k) & (REG_SIZE - 1); + if (!g_reg[j].p) break; + if (g_reg[j].p == p) { if (n) *n = g_reg[j].n; g_reg[j].p = REG_TOMB; found = 1; break; } + } + reg_unlock(); + return found; +} +static int reg_has(void *p) { + if (!g_reg || !p) return 0; + reg_lock(); + unsigned int i = reg_hash(p); + int found = 0; + for (unsigned int k = 0; k < REG_SIZE; k++) { + unsigned int j = (i + k) & (REG_SIZE - 1); + if (!g_reg[j].p) break; + if (g_reg[j].p == p) { found = 1; break; } + } + reg_unlock(); + return found; +} +void *Malloc(size_t n) { + void *(*r)(size_t) = wreal("malloc", 0); + { static int t = 0; if (t < 6) { t++; dbg("[ma] r=%p n=%zu c=%p\n", (void *)r, n, __builtin_return_address(0)); } } + void *p = r(n); + reg_put(p, n); + { static int t = 0; if (t < 6) { t++; dbg("[ma] -> p=%p\n", p); } } + return p; +} +void *Calloc(size_t a, size_t b) { + void *(*r)(size_t, size_t) = wreal("calloc", 0); + void *p = r(a, b); + reg_put(p, a * b); + return p; +} +void *Realloc(void *q, size_t n) { + if (!q) return Malloc(n); + if (reg_has(q)) { + void *(*r)(void *, size_t) = wreal("realloc", 0); + size_t old = 0; + reg_take(q, &old); + void *p = r(q, n); + reg_put(p, n); + return p; + } + void *(*r)(void *, size_t) = wreal("realloc", 0); /* 非本分配器指针:原样透传 */ + return r(q, n); +} +void *Memalign(size_t align, size_t n) { + void *(*r)(size_t, size_t) = wreal("memalign", 0); + void *p = r(align, n); + reg_put(p, n); + return p; +} +void *Aligned_alloc(size_t align, size_t n) { + void *(*r)(size_t, size_t) = wreal("aligned_alloc", 0); + if (!r) r = wreal("memalign", 0); + void *p = r(align, n); + reg_put(p, n); + return p; +} +int Posix_memalign(void **out, size_t align, size_t n) { + int (*r)(void **, size_t, size_t) = wreal("posix_memalign", 0); + int rc = r(out, align, n); + if (!rc) reg_put(*out, n); + return rc; +} +size_t Malloc_usable_size(void *p) { + if (reg_has(p)) { + size_t n = 0; + reg_lock(); + unsigned int i = reg_hash(p); + for (unsigned int k = 0; k < REG_SIZE; k++) { + unsigned int j = (i + k) & (REG_SIZE - 1); + if (!g_reg[j].p) break; + if (g_reg[j].p == p) { n = g_reg[j].n; break; } + } + reg_unlock(); + return n; + } + size_t (*r)(void *) = wreal("malloc_usable_size", 0); + return r ? r(p) : 0; +} +/* 兼容旧名(引擎若直接调用小写) */ +void *malloc(size_t n) { return Malloc(n); } +void *calloc(size_t a, size_t b) { return Calloc(a, b); } +void *realloc(void *q, size_t n) { return Realloc(q, n); } +static __thread int g_in_free = 0; +static void (*g_libc_free_body)(void *) = 0; /* 惰性取 libc free 体(避免硬编码基址) */ +static void shim_free_impl(void *p) { + if (!p) return; + if (mm_contains(p)) return; /* arena/mmap 内部指针:引擎自治,忽略 */ + { /* 默认:基线透传(与引擎在 bionic 上一致);WETYPE_REG_FREE=1 才启用登记表 */ + const char *e = getenv("WETYPE_REG_FREE"); + if (!e || strcmp(e, "1")) { + if (!g_libc_free_body) { + void *fp = dlsym(RTLD_NEXT, "free"); + if (!fp) fp = dlsym(RTLD_DEFAULT, "free"); + if (!fp) fp = (void *)0x400000A96BA0; + { + unsigned int insn = *(volatile unsigned int *)fp; + if ((insn & 0xFC000000u) == 0x14000000u) fp = (char *)fp + 4; + } + g_libc_free_body = (void (*)(void *))fp; + dbg("[freebody] dlsym=%p -> %p\n", fp, (void *)g_libc_free_body); + } + g_libc_free_body(p); + return; + } + } + if (!g_libc_free_body) { + void *fp = dlsym(RTLD_NEXT, "free"); + if (!fp) fp = dlsym(RTLD_DEFAULT, "free"); + if (!fp) fp = (void *)0x400000A96BA0; + { /* 若入口已被跳板 b 指令覆盖(0x14 高位),则 +4 取原始函数体 */ + unsigned int insn = *(volatile unsigned int *)fp; + if ((insn & 0xFC000000u) == 0x14000000u) fp = (char *)fp + 4; + } + g_libc_free_body = (void (*)(void *))fp; + } + if (!g_in_free) { + g_in_free = 1; + if (reg_take(p, 0)) { g_libc_free_body(p); g_in_free = 0; return; } /* 自己分配的:真释放 */ + g_in_free = 0; + { static int sk = 0; if (sk < 200) { sk++; char b[96]; int n = snprintf(b, sizeof b, "[free-skip] p=%p c=%p\n", p, __builtin_return_address(0)); if (n > 0) { ssize_t _w = write(2, b, n); (void)_w; } } } + return; /* 非本分配器指针(libc 内部/静态/已踩坏):跳过,防 glibc abort */ + } + g_libc_free_body(p); +} +void free(void *p) { shim_free_impl(p); } +/* ============ Mmap/Munmap/Free:改名消费者的 mmap 感知释放 ============ */ +void *Mmap(void *addr, size_t len, int prot, int flags, int fd, long off) { + return mmap(addr, len, prot, flags, fd, off); +} +int Munmap(void *addr, size_t len) { + return munmap(addr, len); +} +static int mm_contains(void *p) { + if (g_inmm) return 0; + int hit; + g_inmm = 1; + mm_lock(); + for (int i = 0; i < g_mm_n; i++) + if ((char *)p >= (char *)g_mm[i].base && + (char *)p < (char *)g_mm[i].base + g_mm[i].len) { hit = 1; mm_unlock(); g_inmm = 0; return hit; } + mm_unlock(); + g_inmm = 0; + return 0; +} +void Free(void *p) { + if (!p) return; + if (mm_contains(p)) return; /* arena/mmap 内部指针:引擎自治,忽略 */ + shim_free_impl(p); +} +/* ============ Dlerror:永不返回 NULL ============ + * 引擎有 strlen(dlerror()) 的调用(libandromeda+0x252724):glibc 无错误时 + * dlerror() 返回 NULL,直接 strlen(NULL) 崩溃;返回空串保持语义安全。 + */ +char *Dlerror(void) { + char *(*r)(void) = wreal("dlerror", 0); + char *e = r ? r() : 0; + return e ? e : (char *)""; +} +/* ============ Wdlsym:引擎的 dlsym("free") 命中 mmap 感知分配器 ============ */ +void *Dlsym(void *handle, const char *name) { + void *(*r)(void *, const char *) = wreal("dlsym", 0); + if (name) { + if (!strcmp(name, "free") || !strcmp(name, "malloc") || !strcmp(name, "calloc") || + !strcmp(name, "realloc") || !strcmp(name, "mmap") || !strcmp(name, "munmap")) + fprintf(stderr, "[Dlsym] %s\n", name); + if (!strcmp(name, "free")) return (void *)free; + if (!strcmp(name, "malloc")) return (void *)malloc; + if (!strcmp(name, "calloc")) return (void *)calloc; + if (!strcmp(name, "realloc")) return (void *)realloc; + if (!strcmp(name, "mmap")) return (void *)mmap; + if (!strcmp(name, "munmap")) return (void *)munmap; + } + { + void *res = r(handle, name); + /* JNI 库以 RTLD_LOCAL 加载,其依赖 libc++_shared 的符号不在全局作用域, + 引擎 dlsym(RTLD_NEXT,"__cxa_throw") 会得 NULL → 调用即崩。 + 回退:拿已加载的 libc++_shared 句柄再查一次。 */ + if (!res && name) { + static void *cpph = (void *)-2; + if (cpph == (void *)-2) cpph = dlopen("libc++_shared.so", RTLD_NOW | RTLD_NOLOAD); + if (cpph && cpph != (void *)-2) res = r(cpph, name); + } + static int t = 0; + if (t < 300) { + t++; + dbg("[Dlsym] %s -> %p%s\n", name ? name : "(null)", res, res ? "" : " <<< NULL"); + } + return res; + } +} +/* 信号族接甲见 wetype-signal.c(需脱离 glibc signal.h 原型约束编译) */ diff --git a/shim/wetype-signal.c b/shim/wetype-signal.c new file mode 100644 index 0000000..d2f7d46 --- /dev/null +++ b/shim/wetype-signal.c @@ -0,0 +1,134 @@ +/* wetype-signal: bionic 信号族接甲(脱离 glibc signal.h 原型约束编译)。 + bionic: sigset_t = 8B(64 信号),struct sigaction { flags@0, handler@8, mask@16 }; + glibc: sigset_t = 128B, struct sigaction { handler@0, mask@8, flags@136, restorer@144 }。 + 直接透传会越界读写调用方栈,必须逐字段翻译。 + 实现体全部为 static(本地直调,无 PLT 竞争),导出名 + 大写别名都只做薄转发。 */ +#include +#include + +#ifndef SYS_rt_sigprocmask +#define SYS_rt_sigprocmask 135 /* aarch64 */ +#endif +#define W_SIG_BLOCK 0 +#define W_SIG_UNBLOCK 1 +#define W_SIG_SETMASK 2 + +/* glibc struct sigaction 布局镜像(aarch64 LP64) */ +struct wglibc_sigaction { + void *handler; + unsigned long mask[16]; /* 128B */ + int flags; + void *restorer; +}; + +extern int __sigaction(int, const struct wglibc_sigaction *, struct wglibc_sigaction *); +extern long syscall(long, ...); + +/* bionic aarch64 布局镜像 */ +struct wbionic_sigaction { + unsigned int sa_flags; + void *sa_handler; + unsigned long sa_mask; /* 8B sigset */ +}; + +static int w_sigaction(int signum, const struct wbionic_sigaction *act, + struct wbionic_sigaction *oact) { + struct wglibc_sigaction ga, go, *gp = 0; + if (act) { + __builtin_memset(&ga, 0, sizeof(ga)); + ga.handler = act->sa_handler; + ga.flags = (int)act->sa_flags; + ga.mask[0] = act->sa_mask; + gp = &ga; + } + int r = __sigaction(signum, gp, oact ? &go : 0); + if (oact) { + oact->sa_handler = go.handler; + oact->sa_flags = (unsigned int)go.flags; + oact->sa_mask = go.mask[0]; + } + return r; +} + +static int w_sigprocmask(int how, const unsigned long *set, unsigned long *oldset) { + /* 内核 rt_sigprocmask 原生 8B sigset,绕开 glibc 的 128B 读法 */ + return (int)syscall(SYS_rt_sigprocmask, (long)how, set, oldset, 8UL); +} + +static int w_sigfillset(unsigned long *set) { *set = ~0UL; return 0; } + +static int w_sigdelset(unsigned long *set, int signum) { + if (signum >= 1 && signum <= 64) *set &= ~(1UL << (signum - 1)); + return 0; +} + +/* ---- sigsetjmp/siglongjmp:wcwss 引的是 bionic 符号,glibc 无此导出, + 且 glibc jmp_buf(~312B) 大于 bionic jmp_buf(256B),不能透传。 + 自存自恢复,只用缓冲区前 176B,两侧全在本文件内自洽。 ---- */ +void *sigsetjmp(unsigned long *env, int savemask) { + long old = 0; + __asm__ __volatile__( + "stp x19, x20, [%0, #0]\n\t" + "stp x21, x22, [%0, #16]\n\t" + "stp x23, x24, [%0, #32]\n\t" + "stp x25, x26, [%0, #48]\n\t" + "stp x27, x28, [%0, #64]\n\t" + "stp x29, x30, [%0, #80]\n\t" + "mov x1, sp\n\t" + "str x1, [%0, #96]\n\t" + "stp d8, d9, [%0, #104]\n\t" + "stp d10, d11, [%0, #120]\n\t" + "stp d12, d13, [%0, #136]\n\t" + "stp d14, d15, [%0, #152]" + :: "r"(env) : "x1", "memory"); + env[21] = (unsigned long)(savemask ? 1 : 0); + if (savemask) { + syscall(SYS_rt_sigprocmask, W_SIG_SETMASK, 0L, &old, 8UL); + env[22] = (unsigned long)old; + } + return 0; /* 直接返回路径恒为 0 */ +} + +void siglongjmp(unsigned long *env, int val) { + if (env[21]) { + unsigned long m = env[22]; + syscall(SYS_rt_sigprocmask, W_SIG_SETMASK, &m, 0L, 8UL); + } + __asm__ __volatile__( + "ldp x19, x20, [%0, #0]\n\t" + "ldp x21, x22, [%0, #16]\n\t" + "ldp x23, x24, [%0, #32]\n\t" + "ldp x25, x26, [%0, #48]\n\t" + "ldp x27, x28, [%0, #64]\n\t" + "ldp x29, x30, [%0, #80]\n\t" + "ldr x1, [%0, #96]\n\t" + "mov sp, x1\n\t" + "ldp d8, d9, [%0, #104]\n\t" + "ldp d10, d11, [%0, #120]\n\t" + "ldp d12, d13, [%0, #136]\n\t" + "ldp d14, d15, [%0, #152]\n\t" + "mov x0, %1\n\t" + "cmp x0, #0\n\t" + "csinc x0, x0, xzr, ne\n\t" + "br x30" + :: "r"(env), "r"((unsigned long)val) : "x0", "x1", "memory"); + __builtin_unreachable(); +} + +/* ---- 导出层:小写(消费者 dynstr 未改写的)与大写(12_rename_syms.py 改写的)---- */ +int sigaction(int signum, const struct wbionic_sigaction *act, struct wbionic_sigaction *oact) { + return w_sigaction(signum, act, oact); +} +int sigprocmask(int how, const unsigned long *set, unsigned long *oldset) { + return w_sigprocmask(how, set, oldset); +} +int sigfillset(unsigned long *set) { return w_sigfillset(set); } +int sigdelset(unsigned long *set, int signum) { return w_sigdelset(set, signum); } +int Sigaction(int signum, const struct wbionic_sigaction *act, struct wbionic_sigaction *oact) { + return w_sigaction(signum, act, oact); +} +int Sigprocmask(int how, const unsigned long *set, unsigned long *oldset) { + return w_sigprocmask(how, set, oldset); +} +int Sigfillset(unsigned long *set) { return w_sigfillset(set); } +int Sigdelset(unsigned long *set, int signum) { return w_sigdelset(set, signum); } diff --git a/src/wetype-ime-demo.sh b/src/wetype-ime-demo.sh new file mode 100755 index 0000000..7accd8a --- /dev/null +++ b/src/wetype-ime-demo.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# WeType 引擎 CLI 演示: wetype-ime-demo.sh <拼音串> → 候选词 +# 用法: bash wetype-ime-demo.sh nihao (引擎目录由 WETYPE_ENGINE_DIR 指定, 默认开发目录) +set -e +WORD="${1:-nihao}" +ENG="${WETYPE_ENGINE_DIR:-$(cd "$(dirname "$0")/.." && pwd)}" +HARNESS="$ENG/harness/jinterop" +[ -x "$HARNESS" ] || HARNESS="$ENG/wetype-harness" +LIBDIR="$ENG/lib" +[ -d "$LIBDIR" ] || LIBDIR="$ENG/runtime" # 开发目录布局 +DICTS="${WETYPE_DICT_DIR:-$ENG/dicts}" +[ -d "$DICTS" ] || DICTS="$ENG/.deps/wechat-ime/assets/config/beta" # source checkout +WORK="${WETYPE_WORK_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/wetype-ime/dict}" +QEMU="${QEMU_AARCH64:-}" +if [ -z "$QEMU" ]; then # 安装包自带 QEMU/ARM64 glibc,源码树回落到系统包 + if [ -x "$ENG/qemu-aarch64-static" ]; then QEMU="$ENG/qemu-aarch64-static"; else QEMU=qemu-aarch64-static; fi +fi +SYSROOT="${WETYPE_SYSROOT:-}" +if [ -z "$SYSROOT" ]; then + if [ -f "$ENG/sysroot/lib/ld-linux-aarch64.so.1" ]; then SYSROOT="$ENG/sysroot"; else SYSROOT=/usr/aarch64-linux-gnu; fi +fi + +mkdir -p "$WORK/userdict/v5" "$WORK/userdict/user_hot_word" + +# 拼音串 → L 命令序列 +CMDS="PING" +for ((i=0; i<${#WORD}; i++)); do CMDS+="|L ${WORD:$i:1}"; done +CMDS+="|Q" + +printf '%b\n' "${CMDS//|/\\n}" | \ + env LD_LIBRARY_PATH="$LIBDIR" WETYPE_LIB_DIR="$LIBDIR" WETYPE_DICT_DIR="$DICTS" \ + WETYPE_WORK_DIR="$WORK" \ + "$QEMU" -L "$SYSROOT" "$HARNESS" "$([ -f "$LIBDIR/libwxhld_jni.so" ] && echo "$LIBDIR/libwxhld_jni.so" || echo runtime/libwxhld_jni.so)" --daemon 2>/dev/null | \ + while IFS= read -r line; do + case "$line" in + CAND*) echo "候选: ${line#CAND$'\t'}" | tr '\t' ' ' ;; + esac + done