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 <noreply@anthropic.com>
This commit is contained in:
commit
62dbc6ded9
40 files changed
+5658
No files matched your search
+24
@@ -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
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU 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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU 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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -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.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.5 KiB |
@@ -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)
|
||||
Executable
+10
@@ -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"
|
||||
@@ -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)
|
||||
Executable
+74
@@ -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
|
||||
@@ -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=
|
||||
@@ -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 <fcitx/instance.h>
|
||||
#include <fcitx/addonfactory.h>
|
||||
#include <fcitx/addonmanager.h>
|
||||
#include <fcitx/inputmethodengine.h>
|
||||
#include <fcitx/inputcontext.h>
|
||||
#include <fcitx/inputcontextmanager.h>
|
||||
#include <fcitx/inputpanel.h>
|
||||
#include <fcitx/text.h>
|
||||
#include <fcitx/candidatelist.h>
|
||||
#include <fcitx-utils/keysym.h>
|
||||
#include <fcitx-utils/event.h>
|
||||
#include <fcitx-utils/trackableobject.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <csignal>
|
||||
#include <cerrno>
|
||||
#include <cstdint>
|
||||
#include <ctime>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/wait.h>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <sstream>
|
||||
#include <unordered_set>
|
||||
|
||||
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<uint64_t>(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<std::string> 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<std::string> 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<void(InputContext *)> select)
|
||||
: CandidateWord(std::move(text)), select_(std::move(select)) {
|
||||
setCustomLabel(Text(""));
|
||||
}
|
||||
void select(InputContext *ic) const override {
|
||||
if (select_) select_(ic);
|
||||
}
|
||||
private:
|
||||
std::function<void(InputContext *)> 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<void(const std::string &)>; // "" = 失败/死亡
|
||||
|
||||
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<void()> 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<int>(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<int>(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<Handler> pending_;
|
||||
std::unique_ptr<EventSourceIO> ioSource_;
|
||||
std::unique_ptr<EventSourceTime> timeSource_;
|
||||
std::function<void()> 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<int>(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<int>(start + visiblePageSize, cands_.size());
|
||||
const int pageCount = end - start;
|
||||
if (selected_ < start || selected_ >= end) selected_ = start;
|
||||
auto cl = std::make_unique<CommonCandidateList>();
|
||||
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<GridColumnCandidate>(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<std::string>(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<GridColumnCandidate>(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<unsigned long long>(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<int>(cands_.size())) return;
|
||||
const int cover = index < static_cast<int>(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<unsigned long long>(revision_));
|
||||
if (cover <= 0 || static_cast<size_t>(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<unsigned long long>(expectedRevision),
|
||||
static_cast<unsigned long long>(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<unsigned long long>(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<unsigned long long>(revision_));
|
||||
eng_.send("B " + keys, candidateHandler());
|
||||
}
|
||||
|
||||
Instance *instance_;
|
||||
EngineProc eng_;
|
||||
std::string buf_;
|
||||
std::string pendingKeys_;
|
||||
std::unique_ptr<EventSourceTime> debounceSource_;
|
||||
std::vector<std::string> cands_;
|
||||
std::vector<int> 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<InputContext> 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<char>('a' + (sym - FcitxKey_a))
|
||||
: static_cast<char>('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<unsigned long long>(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<int>(windowStart_ + COMPACT_PAGE_SIZE,
|
||||
cands_.size())) {
|
||||
++selected_;
|
||||
}
|
||||
updateUI(*ic);
|
||||
handled = true;
|
||||
} else {
|
||||
const int start = windowStart_;
|
||||
const int count = std::min<int>(PAGE_SIZE,
|
||||
static_cast<int>(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<int>(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<int>(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<int>(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);
|
||||
@@ -0,0 +1,9 @@
|
||||
[Addon]
|
||||
Name=微信输入法
|
||||
GenericName=微信拼音
|
||||
Comment=微信输入法引擎 (qemu-aarch64 常驻桥)
|
||||
Category=InputMethod
|
||||
Version=1.0
|
||||
OnDemand=True
|
||||
Type=SharedLibrary
|
||||
Library=libfcitx5-wetype
|
||||
@@ -0,0 +1,6 @@
|
||||
[InputMethod]
|
||||
Name=微信拼音
|
||||
Icon=fcitx-pinyin
|
||||
Label=微
|
||||
LangCode=zh_CN
|
||||
Addon=wetype
|
||||
@@ -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},
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
/* Route A harness v2: 直调引擎平面 C API。
|
||||
* 结构体布局为静态重建(v1,待真值对拍)。 */
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <dlfcn.h>
|
||||
#include <sys/stat.h>
|
||||
#include <errno.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
/* 布局偏移(十进制字节,基址=传入指针) */
|
||||
#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 <libwxhld.so> [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;
|
||||
}
|
||||
+1178
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
||||
/* probe: 在 qemu-aarch64 下 dlopen 引擎库,报告成功/失败与可选符号探测 */
|
||||
#include <dlfcn.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 2) {
|
||||
fprintf(stderr, "usage: %s <lib.so> [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;
|
||||
}
|
||||
Executable
+62
@@ -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
|
||||
@@ -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('<Q', b, 0x28)
|
||||
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', b, 0x3a)
|
||||
shs = [struct.unpack_from('<IIQQQQIIQQ', b, e_shoff + j * e_shentsize)
|
||||
for j in range(e_shnum)]
|
||||
shstrtab = shs[e_shstrndx]
|
||||
sstr = b[shstrtab[4]:shstrtab[4] + shstrtab[5]]
|
||||
total = 0
|
||||
for s in shs:
|
||||
if bytes(sstr[s[0]:]).split(b'\0')[0] != b'.dynstr':
|
||||
continue
|
||||
start, size = s[4], s[5]
|
||||
dynstr = bytearray(b[start:start + size])
|
||||
n = 0
|
||||
for name in RENAMES:
|
||||
pat = b'\0' + name.encode() + b'\0'
|
||||
rep = b'\0' + name[0].upper().encode() + name[1:].encode() + b'\0'
|
||||
pos = dynstr.find(pat)
|
||||
while pos != -1:
|
||||
dynstr[pos:pos + len(rep)] = rep
|
||||
n += 1
|
||||
pos = dynstr.find(pat, pos + 1)
|
||||
b[start:start + size] = dynstr
|
||||
total += n
|
||||
open(path, 'wb').write(b)
|
||||
return f"{os.path.basename(path)}: {total} syms renamed"
|
||||
|
||||
if __name__ == '__main__':
|
||||
for p in sys.argv[1:]:
|
||||
print(rename(p))
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""BLAS 空上下文保护补丁(最终版)。
|
||||
|
||||
uarm helper(0x1e6507c) 从 obj->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('<I', x)
|
||||
def bl(src, dst):
|
||||
off = (dst - src) >> 2
|
||||
assert -(1 << 25) <= off < (1 << 25)
|
||||
return struct.pack('<I', 0x94000000 | (off & 0x3FFFFFF))
|
||||
def b(src, dst):
|
||||
off = (dst - src) >> 2
|
||||
assert -(1 << 25) <= off < (1 << 25)
|
||||
return struct.pack('<I', 0x14000000 | (off & 0x3FFFFFF))
|
||||
def cbz(rt, src, dst):
|
||||
off = (dst - src) >> 2
|
||||
assert 0 < off < (1 << 19), f'cbz {off:#x}'
|
||||
return struct.pack('<I', 0xB4000000 | ((off & 0x7FFFF) << 5) | rt)
|
||||
def cbnz(rt, src, dst):
|
||||
off = (dst - src) >> 2
|
||||
assert 0 < off < (1 << 19)
|
||||
return struct.pack('<I', 0xB5000000 | ((off & 0x7FFFF) << 5) | rt)
|
||||
|
||||
data = bytearray(open(SO, 'rb').read())
|
||||
orig = bytes(data[HELPER:HELPER + 0x90])
|
||||
|
||||
E = bytearray()
|
||||
E += orig[0x00:0x1c] # 00 prologue + canary setup
|
||||
E += cbz(0, CAVE + 0x1c, CAVE + 0x7c) # 1c cbz x0, exit
|
||||
E += orig[0x1c:0x24] # 20 ldr x8,[x0,#8]; ldr q0,[x1]
|
||||
E += cbz(8, CAVE + 0x28, CAVE + 0x7c) # 28 cbz x8, exit
|
||||
E += orig[0x24:0x28] # 2c ldr x0,[x8,#112]
|
||||
E += cbz(0, CAVE + 0x30, CAVE + 0x7c) # 30 cbz x0, exit
|
||||
E += orig[0x28:0x44] # 34 stp/str/ldr/ldr/mov/blr
|
||||
E += orig[0x40:0x44] # 4c ldr x19,[sp,#8]
|
||||
E += cbz(19, CAVE + 0x50, CAVE + 0x7c) # 50 cbz x19, exit
|
||||
E += orig[0x48:0x54] # 54 add x1,x19,#8; mov x0,#-1
|
||||
E += bl(CAVE + 0x5c, SCHED) # 5c bl schedule
|
||||
E += cbnz(0, CAVE + 0x60, CAVE + 0x7c) # 60 cbnz x0, exit
|
||||
E += orig[0x58:0x70] # 64 ldr/mov/ldr/blr/mov
|
||||
E += bl(CAVE + 0x78, RELEASE) # 78 bl __release_weak
|
||||
# exit = 0x7c:
|
||||
E += orig[0x70:0x8c] # 7c canary check + epilogue(b.ne 在 0x88)
|
||||
# 重编码洞内 0x88 处的 b.ne → STKCHK
|
||||
ne_pos = CAVE + 0x88
|
||||
E[0x88:0x8c] = b(ne_pos, STKCHK)
|
||||
|
||||
data[CAVE:CAVE + len(E)] = E
|
||||
data[CALLSITE:CALLSITE + 4] = bl(CALLSITE, CAVE)
|
||||
open(SO, 'wb').write(data)
|
||||
print(f'patched: {CALLSITE:#x} → cave {CAVE:#x} ({len(E)}B) [副本+三重守卫]')
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""hyper_params 缺失绕过补丁。
|
||||
|
||||
hp_base 解析在移植环境失败(堆溢出源),hyper_params_ 恒为 NULL →
|
||||
ConfigDicts:912 与加载作用域两处 `cbz hyper_params_, throw` 必然触发异常,
|
||||
新资源被丢弃,config_dict 永远失败。
|
||||
本补丁 NOP 掉两处守卫(0xda78c4 / 0xdb8bac),让资源在无超参的情况下
|
||||
强制安装(NN 排序降级,传统词典路径可用)。
|
||||
注意:必须配合 WETYPE_SKIP_DICTS 跳过 hp_base.bin,否则其解析会破坏堆。
|
||||
"""
|
||||
import struct, sys
|
||||
|
||||
SO = sys.argv[1] if len(sys.argv) > 1 else 'runtime/libwxhld.so'
|
||||
SITES = [0xda78c4, 0xdb8bac]
|
||||
|
||||
data = bytearray(open(SO, 'rb').read())
|
||||
NOP = struct.pack('<I', 0xD503201F)
|
||||
for s in SITES:
|
||||
data[s:s + 4] = NOP
|
||||
open(SO, 'wb').write(data)
|
||||
print('patched: NOP hyper_params_ guards @', ', '.join(hex(s) for s in SITES))
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
"""libc free 跳板补丁。
|
||||
|
||||
把 sysroot 的 libc.so.6 拷入 syslocal/lib/ 并在其 free 符号入口写入
|
||||
`b shim_Free`(qemu-user 无 ASLR,shim/libc 装载地址恒定):
|
||||
libc free 入口 0x400000A96BA0 → shim Free 0x400000D04390
|
||||
shim Free 的透传目标 = libc free+4 = 0x400000A96BA4(见 shim 源码 g_libc_free_body)。
|
||||
效果:所有经 PLT 的 free(含 libc++_shared operator delete)都先经过
|
||||
mmap 区间识别——arena 指针不再送进 glibc 的严格检查。
|
||||
"""
|
||||
import struct, shutil, sys, subprocess
|
||||
|
||||
SHIM_FREE_GUEST = 0x400000c50000 + 0x4814
|
||||
LIBC_FREE_GUEST = 0x400000A96BA0 # libc 基址 0x400000a00000 + 0x96ba0
|
||||
LIBC_SRC = '/usr/aarch64-linux-gnu/lib/libc.so.6'
|
||||
DST = 'syslocal/lib/libc.so.6'
|
||||
|
||||
shutil.copyfile(LIBC_SRC, DST)
|
||||
data = bytearray(open(DST, 'rb').read())
|
||||
|
||||
# 验证入口指令是预期的 cbz x0(防止布局漂移)
|
||||
cur = struct.unpack_from('<I', data, 0x96ba0)[0]
|
||||
assert cur == 0xB4000880, f'libc free 入口指令漂移: {cur:#x}'
|
||||
|
||||
off = (SHIM_FREE_GUEST - LIBC_FREE_GUEST) >> 2
|
||||
assert -(1 << 25) <= off < (1 << 25)
|
||||
data[0x96ba0:0x96ba0 + 4] = struct.pack('<I', 0x14000000 | (off & 0x3FFFFFF))
|
||||
open(DST, 'wb').write(data)
|
||||
print(f'trampoline: libc free @{LIBC_FREE_GUEST:#x} → shim Free @{SHIM_FREE_GUEST:#x}')
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
"""禁用后台 scan_signature 环境完整性与词库反篡改校验补丁。
|
||||
|
||||
微信键盘引擎后台定时触发 scan_signature (0x21c0884),在 Linux/QEMU 环境下
|
||||
词库校验失败后走向异常解引用分支,导致定期触发 SIGSEGV (signal 11)。
|
||||
本补丁在 scan_signature 入口写入 ret (0xd65f03c0),直接提前返回,根治崩溃。
|
||||
"""
|
||||
import struct, sys
|
||||
|
||||
SO = sys.argv[1] if len(sys.argv) > 1 else 'runtime/libwxhld.so'
|
||||
SITE = 0x21c0884
|
||||
|
||||
data = bytearray(open(SO, 'rb').read())
|
||||
cur = struct.unpack_from('<I', data, SITE)[0]
|
||||
|
||||
# 如果未打补丁,入口指令应为 stp x29, x30, [sp, #-96]! (0xa9ba7bfd)
|
||||
RET = struct.pack('<I', 0xd65f03c0)
|
||||
if cur == 0xa9ba7bfd:
|
||||
data[SITE:SITE+4] = RET
|
||||
open(SO, 'wb').write(data)
|
||||
print(f'patched: disabled scan_signature @ {SITE:#x} with ret')
|
||||
elif cur == 0xd65f03c0:
|
||||
print(f'already patched: scan_signature @ {SITE:#x} has ret')
|
||||
else:
|
||||
raise RuntimeError(f'unexpected instruction @ {SITE:#x}: {cur:#x}')
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the project's own ARM64 pieces (shim + harness) into runtime/ and harness/.
|
||||
# Needs no APK input; scripts/10_patch_libs.sh adds the patched WeType libraries.
|
||||
set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
for tool in aarch64-linux-gnu-gcc patchelf; do
|
||||
command -v "$tool" >/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"
|
||||
@@ -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('<I', d, CAVE + i * 4, w)
|
||||
# 站点:b cave + 2 nop(SITE+8 的 str q0 已由洞穴执行)
|
||||
struct.pack_into('<I', d, SITE, b_enc(SITE, CAVE))
|
||||
struct.pack_into('<I', d, SITE + 4, 0xd503201f)
|
||||
struct.pack_into('<I', d, SITE + 8, 0xd503201f)
|
||||
open(LIB, 'wb').write(d)
|
||||
print(f'fake appender patched (PC-relative): cave={CAVE:#x} site={SITE:#x}')
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
cd "$(dirname "$0")/.."
|
||||
export LD_LIBRARY_PATH="$PWD/runtime"
|
||||
exec qemu-aarch64-static -L /usr/aarch64-linux-gnu ./harness/probe "$@"
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python3
|
||||
"""解析 libwxhld_jni initialize() 的反汇编:
|
||||
adrp+add 构造的地址 → .rodata 字符串(Java 字段名/签名),
|
||||
配合 ldr/blr(JNIEnv 表调用)与 str 偏移,输出字段→结构体偏移映射。"""
|
||||
import re, struct, subprocess, sys
|
||||
|
||||
SO = sys.argv[1] if len(sys.argv) > 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('<Q', data, o)
|
||||
s = getstr(ptr)
|
||||
if s and s.isprintable() and len(s) > 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]}')
|
||||
@@ -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
|
||||
@@ -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
|
||||
Executable
+259
@@ -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 <keys> -> 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())
|
||||
Executable
+137
@@ -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" <<NOTICE
|
||||
# Third-party components bundled in this AppImage
|
||||
|
||||
| Component | Files | License | Version (Debian/Ubuntu package) |
|
||||
|---|---|---|---|
|
||||
| QEMU user mode | usr/lib/wetype-ime/arm64/qemu-aarch64-static | GPL-2.0 | qemu-user-static $(pkg_version qemu-user-static) |
|
||||
| GNU C Library (ARM64) | usr/lib/wetype-ime/arm64/sysroot/lib/* | LGPL-2.1-or-later | libc6-arm64-cross $(pkg_version libc6-arm64-cross) |
|
||||
| zlib (ARM64) | usr/lib/wetype-ime/arm64/lib/libz.so.1 | Zlib | zlib1g:arm64 $(pkg_version zlib1g:arm64) |
|
||||
|
||||
These binaries are unmodified copies from the build host's distribution packages.
|
||||
Corresponding source code is available from the distribution's source archive
|
||||
(for Ubuntu: \`apt-get source qemu cross-toolchain-base zlib\` with the versions above,
|
||||
or https://launchpad.net/ubuntu/+source/qemu, /cross-toolchain-base, /zlib), and from
|
||||
https://www.qemu.org, https://www.gnu.org/software/libc and https://zlib.net.
|
||||
|
||||
WeType (微信输入法) itself is NOT included: its libraries and dictionaries are downloaded
|
||||
from Tencent's server and patched on the user's machine at install time.
|
||||
NOTICE
|
||||
|
||||
# 2. 安装时运行的下载/校验/补丁脚本
|
||||
for f in $PATCH_SCRIPTS; do
|
||||
cp "$BASE/scripts/$f" "$APPDIR/usr/lib/wetype-ime/scripts/"
|
||||
done
|
||||
chmod +x "$APPDIR"/usr/lib/wetype-ime/scripts/*.sh
|
||||
|
||||
# 3. 引擎启动器(行协议 REPL,fcitx5 addon 也 exec 它)
|
||||
cat > "$APPDIR/usr/bin/wetype-ime-engine" <<EOF
|
||||
#!/bin/bash
|
||||
ENG="\$(dirname "\$(readlink -f "\$0")")/../lib/wetype-ime/arm64"
|
||||
USRDATA="\${XDG_DATA_HOME:-\$HOME/.local/share}/wetype-ime"
|
||||
mkdir -p "\$USRDATA/dict/userdict/v5" "\$USRDATA/dict/userdict/user_hot_word"
|
||||
QEMU="\${QEMU_AARCH64:-\$ENG/qemu-aarch64-static}"
|
||||
exec env LD_LIBRARY_PATH="\$ENG/lib" \\
|
||||
WETYPE_LIB_DIR="\$ENG/lib" \\
|
||||
WETYPE_DICT_DIR="\$ENG/dicts" \\
|
||||
WETYPE_ASSET_DIR="\$ENG/dicts" \\
|
||||
WETYPE_WORK_DIR="\$USRDATA/dict" \\
|
||||
"\$QEMU" -L "\${WETYPE_SYSROOT:-\$ENG/sysroot}" \\
|
||||
"\$ENG/wetype-harness" "\$ENG/lib/libwxhld_jni.so" --daemon
|
||||
EOF
|
||||
chmod +x "$APPDIR/usr/bin/wetype-ime-engine"
|
||||
|
||||
# 4. CLI 演示启动器
|
||||
cat > "$APPDIR/usr/bin/wetype-demo" <<EOF
|
||||
#!/bin/bash
|
||||
ENG="\$(dirname "\$(readlink -f "\$0")")/../lib/wetype-ime/arm64"
|
||||
WETYPE_ENGINE_DIR="\$ENG" bash "\$ENG/wetype-ime-demo.sh" "\$@"
|
||||
EOF
|
||||
chmod +x "$APPDIR/usr/bin/wetype-demo"
|
||||
|
||||
# 5. Fcitx5 addon, registration files, and AppImage entry point
|
||||
cp "$ADDON_SO" "$APPDIR/usr/lib/fcitx5/libfcitx5-wetype.so"
|
||||
cp "$BASE/fcitx5-wetype/wetype-addon.conf" "$APPDIR/usr/share/fcitx5/addon/wetype.conf"
|
||||
cp "$BASE/fcitx5-wetype/wetype-im.conf" "$APPDIR/usr/share/fcitx5/inputmethod/wetype-im.conf"
|
||||
cp "$BASE/scripts/appimage_manage.sh" "$APPDIR/usr/lib/wetype-ime/appimage-manage.sh"
|
||||
cp "$BASE/scripts/appimage_run.sh" "$APPDIR/AppRun"
|
||||
chmod +x "$APPDIR/AppRun" "$APPDIR/usr/lib/wetype-ime/appimage-manage.sh"
|
||||
|
||||
# 6. desktop + icon
|
||||
cat > "$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"
|
||||
Executable
+27
@@ -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
|
||||
Executable
+26
@@ -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
|
||||
Executable
+70
@@ -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"
|
||||
@@ -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('<Q', b, 0x20)
|
||||
e_phentsize, e_phnum = struct.unpack_from('<HH', b, 0x36)
|
||||
dyn_off = dyn_sz = None
|
||||
for i in range(e_phnum):
|
||||
ph = e_phoff + i * e_phentsize
|
||||
if struct.unpack_from('<I', b, ph)[0] == 2:
|
||||
dyn_off = struct.unpack_from('<Q', b, ph + 8)[0]
|
||||
dyn_sz = struct.unpack_from('<Q', b, ph + 32)[0]
|
||||
break
|
||||
if dyn_off is None:
|
||||
return f"{os.path.basename(path)}: no PT_DYNAMIC"
|
||||
|
||||
# dynstr 定位
|
||||
e_shoff, = struct.unpack_from('<Q', b, 0x28)
|
||||
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', b, 0x3a)
|
||||
shs = [struct.unpack_from('<IIQQQQIIQQ', b, e_shoff + j * e_shentsize)
|
||||
for j in range(e_shnum)]
|
||||
shstrtab = shs[e_shstrndx]
|
||||
sstr = b[shstrtab[4]:shstrtab[4] + shstrtab[5]]
|
||||
dynstr_off = dynstr_sz = None
|
||||
for s in shs:
|
||||
name = bytes(sstr[s[0]:]).split(b'\0')[0]
|
||||
if name == b'.dynstr':
|
||||
dynstr_off, dynstr_sz = s[4], s[5]
|
||||
break
|
||||
if dynstr_off is None:
|
||||
return f"{os.path.basename(path)}: no .dynstr"
|
||||
strtab = bytes(b[dynstr_off:dynstr_off + dynstr_sz])
|
||||
|
||||
def str_of(off):
|
||||
return bytes(strtab[off:strtab.index(b'\0', off)])
|
||||
|
||||
needed = [] # (动态数组文件偏移, strtab offset)
|
||||
i = dyn_off
|
||||
while i < dyn_off + dyn_sz:
|
||||
tag, val = struct.unpack_from('<QQ', b, i)
|
||||
if tag == 0:
|
||||
break
|
||||
if tag == DT_NEEDED:
|
||||
needed.append((i, val))
|
||||
i += 16
|
||||
if not needed:
|
||||
return f"{os.path.basename(path)}: no NEEDED"
|
||||
|
||||
shim_off = strtab.find(SHIM + b'\0')
|
||||
first_i, first_val = needed[0]
|
||||
if first_val == shim_off:
|
||||
return f"{os.path.basename(path)}: shim already first"
|
||||
# 找到 shim 的 NEEDED 项并和第一项交换字符串偏移
|
||||
for idx_i, val in needed:
|
||||
if val == shim_off:
|
||||
struct.pack_into('<QQ', b, first_i, DT_NEEDED, shim_off)
|
||||
struct.pack_into('<QQ', b, idx_i, DT_NEEDED, first_val)
|
||||
open(path, 'wb').write(b)
|
||||
return f"{os.path.basename(path)}: shim promoted to first NEEDED"
|
||||
return f"{os.path.basename(path)}: shim not in NEEDED"
|
||||
|
||||
if __name__ == '__main__':
|
||||
for p in sys.argv[1:]:
|
||||
print(reorder(p))
|
||||
Executable
+181
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Probe WeType's candidate/engine behavior as pinyin composition grows.
|
||||
|
||||
Each case gets a fresh daemon/session and isolated user dictionary. Characters
|
||||
are sent incrementally using the same B protocol as the Fcitx addon. Results
|
||||
are printed as CSV; daemon stderr is saved beside the CSV for crash diagnosis.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import os
|
||||
import select
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def repeated(text: str, length: int) -> 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())
|
||||
@@ -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('<Q', b, 0x20)
|
||||
e_phentsize, e_phnum = struct.unpack_from('<HH', b, 0x36)
|
||||
|
||||
dyn_off = dyn_sz = None
|
||||
for i in range(e_phnum):
|
||||
ph = e_phoff + i * e_phentsize
|
||||
if struct.unpack_from('<I', b, ph)[0] == 2:
|
||||
dyn_off = struct.unpack_from('<Q', b, ph + 8)[0]
|
||||
dyn_sz = struct.unpack_from('<Q', b, ph + 32)[0]
|
||||
break
|
||||
if dyn_off is None:
|
||||
return f"{os.path.basename(path)}: no PT_DYNAMIC, skip"
|
||||
|
||||
has_verdef = has_versym = False
|
||||
i = dyn_off
|
||||
while i < dyn_off + dyn_sz:
|
||||
tag, _ = struct.unpack_from('<QQ', b, i)
|
||||
if tag == 0:
|
||||
break
|
||||
if tag == DT_VERNEED:
|
||||
struct.pack_into('<QQ', b, i, 0x6ffffff9, 0) # 伪装 RELACOUNT:0
|
||||
elif tag == DT_VERDEF:
|
||||
has_verdef = True
|
||||
elif tag == DT_VERSYM:
|
||||
has_versym = True
|
||||
i += 16
|
||||
|
||||
n = 0
|
||||
if has_verdef and has_versym:
|
||||
# 保留 VERSYM,条目全写 0(l_versions[0] 必为空名 → 无版本查找)
|
||||
e_shoff, = struct.unpack_from('<Q', b, 0x28)
|
||||
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', b, 0x3a)
|
||||
shs = [struct.unpack_from('<IIQQQQIIQQ', b, e_shoff + j * e_shentsize)
|
||||
for j in range(e_shnum)]
|
||||
shstr = shs[e_shstrndx]
|
||||
strtab = b[shstr[4]:shstr[4] + shstr[5]]
|
||||
for s in shs:
|
||||
if bytes(strtab[s[0]:]).split(b'\0')[0] == b'.gnu.version':
|
||||
for j in range(s[4], s[4] + s[5], 2):
|
||||
struct.pack_into('<H', b, j, 0)
|
||||
n += 1
|
||||
elif has_versym:
|
||||
# 无 VERDEF:VERNEED 删掉后 ndx_high=0,l_versions/l_versyms 都不会分配,
|
||||
# VERSYM tag 留着必崩 → 一并删除(再次扫描:VERNEED 槽位已是 RELACOUNT)
|
||||
i = dyn_off
|
||||
while i < dyn_off + dyn_sz:
|
||||
tag, _ = struct.unpack_from('<QQ', b, i)
|
||||
if tag == 0:
|
||||
break
|
||||
if tag == DT_VERSYM:
|
||||
struct.pack_into('<QQ', b, i, 0x6ffffff9, 0)
|
||||
break
|
||||
i += 16
|
||||
|
||||
open(path, 'wb').write(b)
|
||||
return (f"{os.path.basename(path)}: VERNEED removed, "
|
||||
f"VERSYM {'kept, %d entries→0' % n if has_verdef else 'removed (无 VERDEF)'}")
|
||||
if __name__ == '__main__':
|
||||
for p in sys.argv[1:]:
|
||||
print(patch(p))
|
||||
@@ -0,0 +1,77 @@
|
||||
/* 诊断版分配器拦截:LD_PRELOAD 用。无 __thread(避免早期 TLS 崩溃)。 */
|
||||
#define _GNU_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <dlfcn.h>
|
||||
|
||||
#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 早期分配等 */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
#define _GNU_SOURCE
|
||||
/* libwetype-shim: bionic liblog/__sF 替身,仅覆盖微信输入法引擎闭包实际引用的符号。
|
||||
未覆盖的符号在 dlopen 报错时按需补充。 */
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
/* ---- bionic __sF:bionic 代码按 sizeof(bionic FILE)=152 计算各元素的地址,
|
||||
而真 glibc FILE 是 216B+vtable,两种布局无法共存于同一块内存。
|
||||
方案:__sF 只做 3×152B 占位符,拦截所有 FILE* 传参的 stdio 入口,
|
||||
把落在占位区间内的指针映射回 glibc 真实 stdin/stdout/stderr 后转发。 */
|
||||
#include <dlfcn.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
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 <stddef.h>
|
||||
|
||||
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 <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/time.h>
|
||||
#include <sys/select.h>
|
||||
|
||||
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 原型约束编译) */
|
||||
@@ -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 <unistd.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
#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); }
|
||||
Executable
+38
@@ -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
|
||||
Reference in new issue
Block a user