Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
home:mkoutny:kdump
python-crush
_service:obs_scm:crush-2023.0.dev1702041137+8ae...
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File _service:obs_scm:crush-2023.0.dev1702041137+8ae4b21.obscpio of Package python-crush
07070100000000000081A40000000000000000000000016573163100000034000000000000000000000000000000000000002B00000000crush-2023.0.dev1702041137+8ae4b21/.flake8[flake8] extend-ignore = W503 max-line-length = 100 07070100000001000081A4000000000000000000000001657316310000004F000000000000000000000000000000000000002E00000000crush-2023.0.dev1702041137+8ae4b21/.gitignore__pycache__/ .mypy_cache/ *.egg-info/ dist/ example/ build/ internal_notes.txt 07070100000002000081A4000000000000000000000001657316310000894D000000000000000000000000000000000000002B00000000crush-2023.0.dev1702041137+8ae4b21/LICENSE 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>. 07070100000003000081A4000000000000000000000001657316310000008F000000000000000000000000000000000000002C00000000crush-2023.0.dev1702041137+8ae4b21/MakefilePRJ = crush all: check sort check: -mypy -p $(PRJ) -pylint $(PRJ) -flake8 $(PRJ) sort: -isort $(PRJ) -black $(PRJ) .PHONY: check sort 07070100000004000081A40000000000000000000000016573163100000B23000000000000000000000000000000000000002D00000000crush-2023.0.dev1702041137+8ae4b21/README.md# crush `crush` is an experimental attempt to, at least partially, rewrite [crash-util](https://github.com/crash-utility/crash/) using Python and a more modern [drgn](https://github.com/crash-utility/crash/) backend. The code is in its early days, is subjected to a massive rewrite at any point, and important functions are not (_yet_) implemented. ## Usage Type `python -m crush.crush -h` first. A vmcore, a vmlinux file and, optionally, a folder with module debug symbols have to be specified. For instance: ``` $ python -m crush.crush -c vmcore -l vmlinux -m folder/with/debuginfo ``` Once started, the tool will greet you with a `crush>` prompt. To get an overview of all currently supported commands, type `help`. For each command, type `<command> -h` to get a more detailed usage info. ## Dependencies * `drgn` * `python-asteval` * `python-capstone` * `python-prettytable` * `python-pyxdg` As a rule of thumb, the latest `drgn` should be used even if it means using a git snapshot. ## Installation `python-flit` is used as a build backend. To build a wheel, install `python-build` and run: ``` $ python -m build ``` To install a wheel, make sure `python-installer` is available, and then run: ``` $ python -m installer --destdir=/some/dir dist/crush-…-.whl ``` This will also generate a startup Python script under `<destdir>/usr/bin` named `crush` which should be used instead of invoking `python -m crush.crush`. Pre-built packages are available: * for Arch Linux: [here](https://build.opensuse.org/project/show/home:post-factum:crush) [![OBS Status](https://build.opensuse.org/projects/home:post-factum:crush/packages/crush/badge.svg?type=default)](https://build.opensuse.org/package/show/home:post-factum:crush/crush) * for Fedora: [here](https://copr.fedorainfracloud.org/coprs/pfactum/crush) ![Copr Status](https://copr.fedorainfracloud.org/coprs/pfactum/crush/package/crush/status_image/last_build.png) The packages are automatically rebuilt on each push. ## Contributing Feel free to [open an issue](https://codeberg.org/pf-kernel/crush/issues/new), create a [pull request](https://codeberg.org/pf-kernel/crush/pulls), or mail me directly: [oleksandr@redhat.com](mailto:oleksandr@redhat.com). Please use the following linters on your code: * `flake8` * `mypy` * `pylint` and format it with: * `black` * `isort` Having the aforementined tools installed, you may just type `make`, and all the checks and formatting adjustments will be invoked automatically. ## Licensing This tool is being developed by me, a Red Hat engineer, during my business hours, whatever that means for licensing, author- and ownership. The code is licensed under terms and conditions of GPLv3 or, at your option, any later version. See [LICENSE](https://codeberg.org/pf-kernel/crush/src/branch/master/LICENSE) file for more details. 07070100000005000041ED0000000000000000000000056573163100000000000000000000000000000000000000000000002900000000crush-2023.0.dev1702041137+8ae4b21/crush07070100000006000081A400000000000000000000000165731631000002C0000000000000000000000000000000000000002E00000000crush-2023.0.dev1702041137+8ae4b21/crush.specName: {{{ git_dir_name }}} Version: {{{ git_dir_version }}} Release: 1%{?dist} Summary: A drgn-based crash-util replacement BuildArch: noarch URL: https://codeberg.org/pf-kernel/crush VCS: {{{ git_dir_vcs }}} License: GPLv3+ BuildRequires: python3-devel Source: {{{ git_dir_pack }}} %description crush is an experimental attempt to, at least partially, rewrite crash-util using Python and a more modern drgn backend. %generate_buildrequires %pyproject_buildrequires %prep {{{ git_dir_setup_macro }}} %build %pyproject_wheel %install %pyproject_install %pyproject_save_files %{name} %files -f %{pyproject_files} %doc README.md %license LICENSE %{_bindir}/crush %changelog {{{ git_dir_changelog }}} 07070100000007000081A40000000000000000000000016573163100000042000000000000000000000000000000000000003500000000crush-2023.0.dev1702041137+8ae4b21/crush/__init__.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later 07070100000008000041ED0000000000000000000000026573163100000000000000000000000000000000000000000000003200000000crush-2023.0.dev1702041137+8ae4b21/crush/commands07070100000009000081A40000000000000000000000016573163100000042000000000000000000000000000000000000003E00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/__init__.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later 0707010000000A000081A40000000000000000000000016573163100000481000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/ascii.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from binascii import Error, a2b_hex from sys import byteorder from typing import Optional from drgn import PlatformFlags from crush.commands.common import Command from crush.helpers.common import bin2ascii def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="ascii", description="Convert raw hex sequence to ASCII") parser.add_argument("hex", nargs="+", help="hex sequence to convert") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None val = [] if cmd.ctx.prog.platform.flags & PlatformFlags.IS_LITTLE_ENDIAN: vmcore_endianness = "little" else: vmcore_endianness = "big" for i in args.hex: try: raw = a2b_hex(i) except Error as exc: cmd.errln(str(exc)) return -1 # TODO: needs testing on big-endian host if byteorder == vmcore_endianness: raw = raw[::-1] asc = bin2ascii(raw) val.append(asc) cmd.println(" ".join(val)) return 0 0707010000000B000081A40000000000000000000000016573163100001C49000000000000000000000000000000000000003800000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/bt.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn import Architecture, FaultError, stack_trace from prettytable import PrettyTable from crush.commands.common import Command from crush.commands.rd import read_content from crush.helpers.common import Address, address_to_module_name, demangle, wreg from crush.helpers.sched import task_header, tasks_from_stdin # TODO: trampolines? something else? PPC64_SP_OFFSET = 0x18 def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="bt", description="Show task stack trace") parser.add_argument( "pid", nargs="*", default=None, help="PID or struct task_struct address(es)" ) parser.add_argument("-i", "--inline", action="store_true", help="show inline frames") parser.add_argument( "-r", "--registers", action="store_true", help="show registers within each frame", ) parser.add_argument( "-f", "--frame-content", action="store_true", help="show each frame content" ) parser.add_argument( "-s", "--stringify", action="store_true", help="try to convert frame content binary data into ASCII", ) parser.add_argument( "-S", "--symbolify", action="store_true", help="resolve symbols within frame content", ) try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None tasks = tasks_from_stdin(cmd.ctx, args.pid, cmd.stdin) for task in tasks: cmd.println(task_header(task)) trace = [] try: trace = stack_trace(task) except FaultError: cmd.println("(no stack)") continue # TODO: narrow down the exception except Exception as exc: # pylint: disable=broad-except cmd.errln(f"Unable to get a stack trace: {exc}") continue for i, frame in enumerate(trace): if not args.inline and frame.is_inline: continue # TODO: stop-gap against infinite s390x stack unwinding if frame.pc == 0: break match cmd.ctx.prog.platform.arch: case Architecture.X86_64: stack_ptr = frame.registers()["rsp"] case Architecture.PPC64: stack_ptr = frame.registers()["r1"] + PPC64_SP_OFFSET case Architecture.S390X: stack_ptr = frame.registers()["r15"] case Architecture.AARCH64: stack_ptr = frame.registers()["sp"] case _: stack_ptr = None # TODO: stop-gap against infinite s390x stack unwinding if stack_ptr == 0: break frame_num = f"#{i}" frame_line = f"{frame_num:>4s}" if stack_ptr is not None: frame_line += " " + f"[{wreg(cmd.ctx, stack_ptr)}]" demangled = demangle(cmd.ctx, frame.pc) if demangled is not None: frame_line += " " + f"at {demangled}" try: src_file, src_line, src_column = frame.source() except LookupError: src_file = None src_line = 0 src_column = 0 if src_file is not None: frame_line += " " + "in" + " " + src_file if src_line != 0: frame_line += f":{src_line}" if src_column != 0: frame_line += f":{src_column}" else: frame_line += " " + wreg(cmd.ctx, frame.pc) if frame.is_inline: frame_line += " " + "(inline)" match cmd.ctx.prog.platform.arch: case Architecture.X86_64 | Architecture.S390X | Architecture.AARCH64: module_name = address_to_module_name(cmd.ctx, frame.pc) if module_name is not None: frame_line += " " + f"[{module_name}]" case Architecture.PPC64: # TODO: avoid FaultError "No way to translate" for now pass cmd.println(frame_line) if (not frame.is_inline and frame.interrupted) or args.registers: table = PrettyTable() table.border = False table.header = False regs = frame.registers() row = [] j = 0 for reg in regs: row.append(reg + ":") row.append(wreg(cmd.ctx, regs[reg])) j += 1 if j > 2: table.add_row(row) row = [] j = 0 if j != 0: for _ in range(0, 3 - j): row.append("") row.append("") if row: table.add_row(row) table.align = "l" table.align["Field 1"] = "r" # type: ignore table.align["Field 3"] = "r" # type: ignore table.align["Field 5"] = "r" # type: ignore cmd.println(table.get_string()) if args.frame_content and not frame.is_inline and i < len(trace) - 1: next_frame = trace[i + 1] match cmd.ctx.prog.platform.arch: case Architecture.X86_64: next_stack_ptr = next_frame.registers()["rsp"] frame_size = ((next_stack_ptr - stack_ptr) // 8) % 2**64 case Architecture.PPC64: next_stack_ptr = next_frame.registers()["r1"] + PPC64_SP_OFFSET frame_size = ((next_stack_ptr - stack_ptr) // 8) % 2**64 case Architecture.S390X: next_stack_ptr = next_frame.registers()["r15"] frame_size = ((next_stack_ptr - stack_ptr) // 8) % 2**64 case Architecture.AARCH64: next_stack_ptr = next_frame.registers()["sp"] frame_size = ((next_stack_ptr - stack_ptr) // 8) % 2**64 case _: next_stack_ptr = None frame_size = None # 16 KiB if frame_size is not None and frame_size < 0x4000: buf = read_content( cmd.ctx, [Address(None, None, stack_ptr)], frame_size, None, False, args.stringify, args.symbolify, ) table = PrettyTable() table.border = False table.header = False table.align = "l" for row in buf: table.add_row(row) cmd.println(table.get_string()) cmd.println("") return 0 0707010000000C000081A400000000000000000000000165731631000005C3000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/calc.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import List, Optional from asteval import Interpreter from prettytable import PrettyTable from crush.commands.common import Command def bits_set(num: int) -> List[int]: ret: List[int] = [] if num < 0: num = abs(num) while num: bit = num & (~num + 1) ret.insert(0, bit.bit_length() - 1) num ^= bit return ret def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="calc", description="Evaluate math expression") parser.add_argument("-b", "--binary", action="store_true", help="show result in binary") parser.add_argument("-x", "--hex", action="store_true", help="show result in hex") parser.add_argument("expression", nargs="+", help="math expression to evaluate") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None aeval = Interpreter() val = aeval(" ".join(args.expression)) table = PrettyTable() table.border = False table.header = False table.align = "r" table.add_row(["ans =", val]) if args.hex or args.binary: table.add_row(["", ""]) if args.hex: table.add_row(["Hex:", hex(val)]) if args.binary: table.add_row(["Bin:", bin(val)]) table.add_row(["Bits set:", bits_set(val)]) table.max_width = 70 return cmd.println(table.get_string()) 0707010000000D000081A400000000000000000000000165731631000001E4000000000000000000000000000000000000003D00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/cmdline.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="cmdline", description="Show kernel command line options") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None return cmd.println(cmd.ctx.prog["saved_command_line"].string_().decode()) 0707010000000E000081A40000000000000000000000016573163100002301000000000000000000000000000000000000003C00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/common.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later import readline from importlib import import_module from pathlib import Path from shlex import shlex from subprocess import run from sys import stderr from traceback import print_exc from typing import Dict, List, Optional, Tuple from drgn import Object from xdg import BaseDirectory from crush.context import Context from crush.textbuffer import TextBuffer Commands: Dict[str, List] = { "ascii": [], "bt": [], "calc": [], "cmdline": [], "const": [], "dis": [], "dmesg": [ "log", ], "ext": [], "files": [], "finfo": [], "fn": [], "help": [], "info": [], "lag": [], "list": [], "lsmod": [ "mod", ], "mem": [], "mount": [], "pcpu": [], "ps": [], "quit": [ "exit", "q", ], "rd": [], "search": [], "set": [], "slabs": [], "struct": [], "sym": [], "swap": [], "taint": [], "tree": [], "type": [], "uname": [], "var": [], "vtop": [], } def print_err(*args, **kwargs): print(*args, file=stderr, **kwargs) class Command: def __init__(self, ctx: Context, argv: List[str], stdin: Optional[TextBuffer], piped: bool): self.ctx = ctx self.argv = argv self.stdin = stdin self.piped = piped self.stdout = TextBuffer() def println(self, string: str): if self.piped: self.stdout.append(string) else: print(string) def errln(self, string: str): print_err(string) def wrapper(cmd: Command) -> Tuple[Optional[TextBuffer], Optional[int]]: try: module = import_module(f"crush.commands.{cmd.argv[0]}") except ModuleNotFoundError as exc: print_err(exc) if cmd.ctx.debug_mode: print_exc() return None, -1 try: func = getattr(module, "main") except AttributeError as exc: print_err(exc) if cmd.ctx.debug_mode: print_exc() return None, -2 try: ret = func(cmd) except Exception as exc: # pylint: disable=broad-except print_err(f"Exception occurred while executing command: {type(exc).__name__}: {exc}") if cmd.ctx.debug_mode: print_exc() ret = -255 return cmd.stdout, ret def struct_exists(ctx: Context, name: str) -> bool: try: name = name.split(".")[0] _ = Object(ctx.prog, f"struct {name} *", 0) except (LookupError, SyntaxError): return False return True def var_exists(ctx: Context, name: str) -> bool: # probably, one really wanted `head` command from outside # but not struct hash *head[32] from init/initramfs.c var_overrides = ["head"] if name in var_overrides: return False try: _ = ctx.prog.variable(name) except (LookupError, SyntaxError): return False return True def type_exists(ctx: Context, name: str) -> bool: try: name = name.split(".")[0] _ = ctx.prog.type(name) except (LookupError, SyntaxError): return False return True def const_exists(ctx: Context, name: str) -> bool: try: _ = ctx.prog.constant(name) except (LookupError, SyntaxError): return False return True def fn_exists(ctx: Context, name: str) -> bool: try: _ = ctx.prog.function(name) except (LookupError, SyntaxError): return False return True def resolve(ctx: Context, args: List[str]) -> Tuple[str, bool, bool, Optional[List[str]]]: cmd = args[0] for resolution, aliases in Commands.items(): if cmd == resolution: return resolution, False, False, None if cmd in aliases: return resolution, True, False, None if not cmd.startswith("!"): if len(args) == 2 and struct_exists(ctx, cmd): return "struct", False, True, None if var_exists(ctx, cmd): return "var", False, True, None if type_exists(ctx, f"struct {cmd}"): return "type", False, True, ["struct"] if type_exists(ctx, cmd): return "type", False, True, None if const_exists(ctx, cmd): return "const", False, True, None if fn_exists(ctx, cmd): return "fn", False, True, None return "execve", False, True, None return "execve", False, False, None def command(ctx: Context, val: str) -> bool: stdin: Optional[TextBuffer] = TextBuffer() stdout = None if val.strip() == "": return False parser = shlex(instream=val, posix=True, punctuation_chars=True) parser.wordchars += "!+:," # independent sets of commands (separated by `;`) clusters = [] tokens: List[str] = [] while True: token = parser.get_token() if token is parser.eof: break if token == ";": clusters.append(tokens) tokens = [] elif token: tokens.append(token) if tokens: clusters.append(tokens) for cluster in clusters: commands = [] argv: List[str] = [] skip_once = False for index, arg in enumerate(cluster): if skip_once: skip_once = False continue if arg == "|": if argv: commands.append(argv) argv = [] elif arg in [">", ">>", "<", "<<"]: # TODO: handle stdin/stdout redirection # currently can be worked around by `cat … | …` and `… | tee …` try: _direction = cluster[index + 1] # noqa: F841 except IndexError: print_err("Syntax error") return False commands.append(argv) argv = [] skip_once = True else: argv.append(arg) if argv: commands.append(argv) for index, argv in enumerate(commands): name, aliased, guessed, prefix = resolve(ctx, argv) piped = index != len(commands) - 1 stdout = None ret: Optional[int] = None match name: case "quit": return True case "execve": if not guessed: argv[0] = argv[0][1:] inp = None if stdin is not None: inp = "\n".join(stdin).encode() try: # pylint: disable=subprocess-run-check res = run(argv, input=inp, capture_output=True) except Exception as exc: # pylint: disable=broad-except print_err(exc) else: ret = res.returncode if res.stdout != b"": stdout = TextBuffer() for line in res.stdout.decode().split("\n"): stdout.append(line) if not piped: if stdout is not None: print("\n".join(stdout)) if res.stderr != b"": for line in res.stderr.decode().split("\n"): print_err(line) case _: if aliased: argv[0] = name if prefix is not None: argv = prefix + argv if guessed: argv = [name] + argv stdout_raw, ret = wrapper(Command(ctx, argv, stdin, piped)) stdout = TextBuffer() if stdout_raw is not None: for line in stdout_raw: for subline in line.split("\n"): stdout.append(subline) if ret is not None and ret != 0: if ret != -255: print_err(f"Command returned a non-zero exit code: {ret}") break stdin = stdout return False def repl(ctx: Context) -> bool: val = input("crush> ") return command(ctx, val) def loop(ctx: Context) -> None: histdir = BaseDirectory.xdg_data_home + "/crush" histfile = histdir + "/history" Path(histdir).mkdir(parents=True, exist_ok=True) if Path(histfile).exists(): readline.read_history_file(histfile) readline.set_history_length(1000) while True: try: val = repl(ctx) readline.write_history_file(histfile) if val: return except EOFError: return except KeyboardInterrupt: print() 0707010000000F000081A40000000000000000000000016573163100000411000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/const.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from crush.commands.common import Command from crush.context import Context def get_const(ctx: Context, string: str, is_hex: bool) -> str: val = ctx.prog.constant(string).value_() if is_hex: return hex(val) return str(val) def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="const", description="Show given constant") parser.add_argument("-x", "--hex", action="store_true", help="show value in hex") parser.add_argument("const", nargs="+", help="constant name") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None for i in args.const: if i == "-" and cmd.stdin is not None: for j in cmd.stdin: if j != "": cmd.println(get_const(cmd.ctx, j.strip(), args.hex)) else: cmd.println(get_const(cmd.ctx, i, args.hex)) return 0 07070100000010000081A40000000000000000000000016573163100001F48000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/dis.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import List, Optional from capstone import ( CS_ARCH_ARM64, CS_ARCH_PPC, CS_ARCH_SYSZ, CS_ARCH_X86, CS_MODE_32, CS_MODE_64, CS_MODE_ARM, CS_MODE_BIG_ENDIAN, CS_MODE_LITTLE_ENDIAN, CS_OPT_SYNTAX_ATT, Cs, CsError, CsInsn, ) from capstone.arm64 import ARM64_OP_IMM from capstone.ppc import PPC_OP_IMM from capstone.systemz import SYSZ_OP_IMM from capstone.x86 import X86_OP_IMM, X86_OP_MEM from drgn import Architecture, PlatformFlags from prettytable import PrettyTable from crush.commands.common import Command from crush.context import Context from crush.helpers.common import demangle, try_int class DisasmLine: """ Represents a disassembler line containing instruction details and demangler hints. Attributes ---------- insn: capstone.CsInsn CPU instruction symbolic: str textual representation of CPU instruction address hints: List[str] textual representation of memory addresses the CPU instruction operates on Methods ------- get_hints(): returns textual representation of memory addresses the CPU instruction operates on get_insn_address(): returns CPU instruction address in memory get_symbolic(): returns textual representation of CPU instruction address get_insn_mnemonic(): returns CPU instruction mnemonic get_insn_op_str(): returns textual representation of CPU instruction operands """ def __init__(self, ctx: Context, arch: int, mode: int, insn: CsInsn): self.insn = insn demangled = demangle(ctx, insn.address) if demangled is None: self.symbolic = "?" else: self.symbolic = demangled self.hints = [] # skip if data instruction is encountered try: operands = insn.operands except CsError: return # TODO: also other architectures for i in operands: if arch == CS_ARCH_X86: if i.type == X86_OP_IMM: if mode == CS_MODE_64: imm = i.imm % 2**64 else: imm = None if imm is not None: demangled = demangle(ctx, imm) if demangled is not None: self.hints.append(demangled) elif i.type == X86_OP_MEM: if i.mem.base != 0: reg = insn.reg_name(i.mem.base) if reg == "rip": dst = (insn.address + insn.size + i.mem.disp) % 2**64 demangled = demangle(ctx, dst) hint = hex(dst) if demangled is not None: hint += " " + "<" + demangled + ">" self.hints.append(hint) if i.mem.index != 0 and i.mem.disp != 0: dst = i.mem.disp % 2**64 demangled = demangle(ctx, dst) hint = hex(dst) if demangled is not None: hint += " " + "<" + demangled + ">" self.hints.append(hint) elif arch == CS_ARCH_PPC: if i.type == PPC_OP_IMM: imm = i.imm % 2**64 demangled = demangle(ctx, imm) if demangled is not None: self.hints.append(demangled) elif arch == CS_ARCH_SYSZ: if i.type == SYSZ_OP_IMM: imm = i.imm % 2**64 demangled = demangle(ctx, imm) if demangled is not None: self.hints.append(demangled) elif arch == CS_ARCH_ARM64: if i.type == ARM64_OP_IMM: imm = i.imm % 2**64 demangled = demangle(ctx, imm) if demangled is not None: self.hints.append(demangled) # TODO: resolve to source code file:line:column # https://github.com/osandov/drgn/pull/180 def get_hints(self) -> List[str]: return self.hints def get_insn_address(self) -> int: return self.insn.address def get_symbolic(self) -> str: return self.symbolic def get_insn_mnemonic(self) -> str: return self.insn.mnemonic def get_insn_op_str(self) -> str: return self.insn.op_str def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="dis", description="Disassemble a given function") parser.add_argument("fn", metavar="fn[+0xoffset]", help="function name or address") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None if "+" in args.fn: entity, size_to_read = args.fn.split("+") size_to_read = try_int(size_to_read) if size_to_read == 0: size_to_read = None else: entity = args.fn size_to_read = None val = try_int(entity) if val is not None: symbol_address = val if size_to_read is None: size_to_read = cmd.ctx.get_word_size() else: symbol = cmd.ctx.prog.symbol(entity) symbol_address = symbol.address if size_to_read is None: size_to_read = symbol.size instr = cmd.ctx.prog.read(symbol_address, size_to_read) # declare what RHEL supports match cmd.ctx.prog.platform.arch: case Architecture.X86_64: arch = CS_ARCH_X86 mode = CS_MODE_64 syntax = CS_OPT_SYNTAX_ATT case Architecture.I386: # TODO: not tested arch = CS_ARCH_X86 mode = CS_MODE_32 syntax = CS_OPT_SYNTAX_ATT case Architecture.AARCH64: arch = CS_ARCH_ARM64 mode = CS_MODE_ARM syntax = None case Architecture.PPC64: if cmd.ctx.prog.platform.flags & PlatformFlags.IS_LITTLE_ENDIAN: # TODO: issues with slabs and modules; # looks like something is wrong with virtual memory address translation # bt, dis work just fine though # https://github.com/ptesarik/libkdumpfile/issues/58 arch = CS_ARCH_PPC mode = CS_MODE_64 + CS_MODE_LITTLE_ENDIAN else: # TODO: same ^^ arch = CS_ARCH_PPC mode = CS_MODE_64 + CS_MODE_BIG_ENDIAN syntax = None case Architecture.S390X: # TODO: some instructions like `mvcl %r2,%r0` get recognised as `(bad)` # https://github.com/capstone-engine/capstone/issues/1545 arch = CS_ARCH_SYSZ mode = CS_MODE_BIG_ENDIAN syntax = None case _: cmd.errln("Unsupported architecture") return -1 dis = Cs(arch, mode) if syntax is not None: dis.syntax = syntax dis.skipdata = True dis.skipdata_setup = ("(bad)", None, None) dis.detail = True disasm_lines = [] for i in dis.disasm(instr, symbol_address): disasm_lines.append(DisasmLine(cmd.ctx, arch, mode, i)) table = PrettyTable() table.border = False table.header = False table.align = "l" for i in disasm_lines: if i.get_hints(): hints = "# " + ",".join(i.get_hints()) else: hints = "" table.add_row( [ hex(i.get_insn_address()), "<" + i.get_symbolic() + ">:", i.get_insn_mnemonic(), i.get_insn_op_str(), hints, ] ) return cmd.println(table.get_string()) 07070100000011000081A40000000000000000000000016573163100000647000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/dmesg.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from datetime import datetime, timezone from typing import Optional from drgn.helpers.linux.printk import get_dmesg, get_printk_records from crush.commands.common import Command from crush.helpers.time import get_timekeeper, get_uptime_ns def get_dmesg_human_ts(boot_time_s: int) -> str: lines = [] for record in get_printk_records(): timestamp = ( datetime.fromtimestamp(boot_time_s + (record.timestamp // 1_000_000_000), timezone.utc) .astimezone() .strftime("%a %b %e %T %Z %Y") ) lines.append(f'[{timestamp}] {record.text.decode(errors="replace")}') lines.append("") # So we get a trailing newline. return "\n".join(lines) def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="dmesg", description="Show kernel long content") parser.add_argument( "--human-timestamps", "-T", action="store_true", help="print human-readable timestamps" ) try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None if not args.human_timestamps: # Print default timestamps cmd.println(get_dmesg().decode(errors="replace")) else: # Print human-readable timestmaps timekeeper = get_timekeeper(cmd.ctx) uptime_ns = get_uptime_ns(cmd.ctx) uptime_s = uptime_ns // 1_000_000_000 boot_time_s = timekeeper.xtime_sec.value_() - uptime_s cmd.println(get_dmesg_human_ts(boot_time_s)) return 0 07070100000012000081A400000000000000000000000165731631000004E2000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/ext.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from importlib.machinery import SourceFileLoader from importlib.util import module_from_spec, spec_from_loader from traceback import print_exc from typing import Optional from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="ext", description="Run external crush Python script") parser.add_argument("script", help="path to script") parser.add_argument("args", nargs="*", help="script arguments") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None loader = SourceFileLoader("extmodule", args.script) spec = spec_from_loader("extmodule", loader) if spec is not None: extmodule = module_from_spec(spec) try: loader.exec_module(extmodule) except FileNotFoundError as exc: cmd.println(str(exc)) return -1 try: return extmodule.main(cmd) except Exception as exc: # pylint: disable=broad-except cmd.println(str(exc)) if cmd.ctx.debug_mode: print_exc() return -2 return -3 07070100000013000081A40000000000000000000000016573163100000A73000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/files.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn.helpers.linux.fs import d_path, for_each_file from prettytable import PrettyTable from crush.commands.common import Command from crush.helpers.common import try_int from crush.helpers.sched import task_header, tasks_from_stdin def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="files", description="Show task files") parser.add_argument( "-R", "--reference", help="Show only files matching the reference " + "(struct file, inode, dentry, private_data)", ) parser.add_argument( "pid", nargs="*", default=None, help="PID or struct task_struct address(es)" ) try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None reference = try_int(args.reference) tasks = tasks_from_stdin(cmd.ctx, args.pid, cmd.stdin) for task in tasks: cmd.println(task_header(task)) if task.files.value_() == 0: files = 0 else: files = len(list(for_each_file(task))) if files != 0: records = [] for file_desc, file in for_each_file(task): if file.value_() == 0: continue if reference is not None: if ( file.value_() != reference and file.f_inode.value_() != reference and file.f_path.dentry.value_() != reference and file.private_data.value_() != reference ): continue fd_str = hex(file_desc) inode = hex(file.f_inode.value_()) dentry = hex(file.f_path.dentry.value_()) path = d_path(file.f_path).decode() if path in ("[anon_inodefs]", "[sockfs]"): path = file.f_path.dentry.d_name.name.string_().decode() file = hex(file.value_()) records.append([fd_str, file, inode, dentry, path]) if records: table = PrettyTable() table.border = False table.align = "l" table.field_names = ["FD", "FILE", "INODE", "DENTRY", "PATH"] for record in records: table.add_row(record) cmd.println(table.get_string()) cmd.println("") else: cmd.println("(no files to show)") else: cmd.println("(no files)") return 0 07070100000014000081A400000000000000000000000165731631000008B5000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/finfo.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn import Object from drgn.helpers.linux.fs import dentry_path from prettytable import PrettyTable from crush.commands.common import Command from crush.helpers.common import try_int def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="finfo", description="Show information about file(s)") # TODO: -i for struct inode, -f for struct file parser.add_argument( "--dentry", "-d", action="store_true", help="Treat input as struct dentry address(es)", ) parser.add_argument("addrs", nargs="*", default=None, help="Memory address(es)") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None if args.addrs is None and cmd.stdin is None: cmd.errln("No input given") return -1 addrs = [] if args.addrs is not None: for i in args.addrs: if i == "-": if cmd.stdin is not None: for j in cmd.stdin: if not j == "": addrs.append(try_int(j)) else: addrs.append(try_int(i)) else: if cmd.stdin is not None: for i in cmd.stdin: if not i == "": addrs.append(try_int(i)) table = PrettyTable() table.border = False table.align = "l" if args.dentry: table.field_names = ["DENTRY", "INODE", "SUPERBLOCK", "PATH"] for addr in addrs: dentry = Object(cmd.ctx.prog, "struct dentry *", addr) inode = dentry.d_inode superblock = dentry.d_sb # TODO: dentry_path() tells nothing if dentry is inotify or UNIX # (or probably any other "virtual" file) table.add_row( [ hex(dentry.value_()), hex(inode.value_()), hex(superblock.value_()), dentry_path(dentry).decode(), ] ) cmd.println(table.get_string()) cmd.println("") return 0 07070100000015000081A400000000000000000000000165731631000002D7000000000000000000000000000000000000003800000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/fn.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="fn", description="Show given function") parser.add_argument("fn", nargs="+", help="function name") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None for i in args.fn: if i == "-" and cmd.stdin is not None: for j in cmd.stdin: if j != "": cmd.println(cmd.ctx.prog.function(j.strip())) else: cmd.println(cmd.ctx.prog.function(i)) return 0 07070100000016000081A40000000000000000000000016573163100000767000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/help.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from prettytable import PrettyTable from crush.commands.common import Command, Commands def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="help", description="Show available commands") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None table = PrettyTable() table.align = "l" table.border = False table.header = False col = 0 row = [] for main_cmd, aliases in Commands.items(): if not aliases: row.append(main_cmd) else: row.append(main_cmd + "(" + ",".join(aliases) + ")") col += 1 if col >= 10: table.add_row(row) col = 0 row = [] if col != 0: for _ in range(col, 10): row.append("") table.add_row(row) msg = f"""Built-ins available: {table.get_string()} To get a help on a specific command type `<command> -h`. Commands (including built-ins, extensions and external commands) can be piped, for instance: \t# this will print the backtraces of all running kernel threads \tcrush> ps -bKR | bt - To force the command to be interpreted as an external one, prepend it with `!`, for instance: \t# this will execute a system-wide `ps` command, not a built-in \tcrush> !ps If an ambiguous command is typed in, for instance, `task_struct` instead of `type struct task_struct`, or `grep` instead of `!grep`, then `crush` guesses how to interpret the input in the following order: \t1. built-in \t2. struct with address (if one argument is provided) \t3. variable \t4. struct without address \t5. type \t6. constant \t7. function \t8. external command""" for line in msg.split("\n"): cmd.println(line) return 0 07070100000017000081A40000000000000000000000016573163100000B07000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/info.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from datetime import datetime, timezone from typing import Optional from drgn.helpers.common.format import number_in_binary_units from drgn.helpers.linux.cpumask import for_each_online_cpu, for_each_possible_cpu from drgn.helpers.linux.mm import totalram_pages from drgn.helpers.linux.pid import for_each_task from drgn.helpers.linux.sched import loadavg from prettytable import PrettyTable from crush.commands.common import Command from crush.helpers.time import get_timekeeper, get_uptime_ns def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="info", description="Show generic information about vmcore") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None table = PrettyTable() table.border = False table.header = False timekeeper = get_timekeeper(cmd.ctx) # TODO: panic string / task (?), tainted mark table.add_row(["VMCORE:", cmd.ctx.get_vmcore()]) table.add_row(["VMLINUX:", cmd.ctx.get_vmlinux()]) timestamp_str = ( datetime.fromtimestamp(timekeeper.xtime_sec.value_(), timezone.utc) .astimezone() .strftime("%a %b %e %T %Z %Y") ) table.add_row(["DATE:", timestamp_str]) uptime_ns = get_uptime_ns(cmd.ctx) uptime_s = uptime_ns // 1_000_000_000 days = uptime_s // 86400 uptime_s -= days * 86400 hours = uptime_s // 3600 uptime_s -= hours * 3600 mins = uptime_s // 60 secs = uptime_s - mins * 60 uptime_str = "" if days != 0: plural = "" if days == 1 else "s" uptime_str += f"{days} day{plural}" + ", " uptime_str += f"{hours:02}:{mins:02}:{secs:02}" table.add_row(["UPTIME:", uptime_str]) table.add_row(["HOSTNAME:", cmd.ctx.prog["init_uts_ns"].name.nodename.string_().decode()]) table.add_row(["RELEASE:", cmd.ctx.prog["init_uts_ns"].name.release.string_().decode()]) table.add_row(["VERSION:", cmd.ctx.prog["init_uts_ns"].name.version.string_().decode()]) online_cpus = len(list(for_each_online_cpu())) possible_cpus = len(list(for_each_possible_cpu())) cpus_line = f"{online_cpus}" if online_cpus != possible_cpus: cpus_line += " " + f"online, {possible_cpus - online_cpus} offline" table.add_row(["CPUS:", cpus_line]) totalram = totalram_pages() * cmd.ctx.get_page_size() table.add_row(["MEMORY:", f"{number_in_binary_units(totalram)}"]) table.add_row(["TASKS:", f"{len(list(for_each_task()))}"]) table.add_row(["LOADAVG:", ", ".join(f"{i:.2f}" for i in loadavg())]) table.add_row(["CONFIG_HZ:", cmd.ctx.get_config_hz()]) table.align["Field 1"] = "r" table.align["Field 2"] = "l" cmd.println(table.get_string()) return 0 07070100000018000081A40000000000000000000000016573163100000908000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/lag.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn.helpers.linux.cpumask import for_each_online_cpu from drgn.helpers.linux.percpu import per_cpu from prettytable import PrettyTable from crush.commands.common import Command def format_timestamp(_field: str, value: str) -> str: nsecs = int(value) if nsecs == -1: return "-" secs = nsecs / 1_000_000_000 return f"{secs:.3f}" def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="lag", description="Show CPU lag information") parser.add_argument("--all", "-a", action="store_true", help="show all CPUs regardless of lag") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None try: watchdog_thresh = cmd.ctx.prog["watchdog_thresh"].value_() * 1_000_000_000 except KeyError: # TODO: s390x doesn't have it? watchdog_thresh = -1 most_fresh = -1 most_fresh_cpu = -1 for cpu in for_each_online_cpu(): rq_clock = per_cpu(cmd.ctx.prog["runqueues"], cpu).clock.value_() if rq_clock > most_fresh: most_fresh = rq_clock most_fresh_cpu = cpu cpus = [] for cpu in for_each_online_cpu(): rq_clock = per_cpu(cmd.ctx.prog["runqueues"], cpu).clock.value_() if cpu == most_fresh_cpu: cpus.append([cpu, -1, "most recent"]) else: diff = most_fresh - rq_clock if watchdog_thresh != -1: lags_too_much = diff / watchdog_thresh > 0.75 lags_too_little = diff / watchdog_thresh < 0.75 if args.all or not lags_too_little: cpus.append([cpu, diff, "!!!" if lags_too_much else ""]) else: cpus.append([cpu, diff, ""]) if len(cpus) > 1: table = PrettyTable() table.border = False table.align = "l" table.field_names = ["CPU", "LAG, s", "NOTE"] table.custom_format["LAG, s"] = format_timestamp for i in cpus: table.add_row(i) cmd.println(table.get_string(sortby="LAG, s")) else: cmd.println("No lagging CPUs") # TODO: also evaluate (hr)timers lag return 0 07070100000019000081A400000000000000000000000165731631000004BA000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/list.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn import Object from drgn.helpers import ValidationError from drgn.helpers.linux.list import validate_list_for_each from prettytable import PrettyTable from crush.commands.common import Command from crush.helpers.common import resolve def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="list", description="Iterate over a linked list") # TODO: add offset, reverse options parser.add_argument("head", help="struct list_head address") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None table = PrettyTable() table.border = False table.header = False table.align = "l" addrs = resolve(cmd.ctx, args.head) for i in addrs: addr = i.get_addr() list_head = Object(cmd.ctx.prog, "struct list_head *", addr) try: for j in validate_list_for_each(list_head): table.add_row([hex(j.value_())]) except ValidationError as exc: table.add_row([str(exc)]) cmd.println(table.get_string()) return 0 0707010000001A000081A40000000000000000000000016573163100000B1E000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/lsmod.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn.helpers.common.format import decode_flags from drgn.helpers.linux.cpumask import for_each_possible_cpu from drgn.helpers.linux.list import list_for_each_entry from drgn.helpers.linux.percpu import per_cpu_ptr from prettytable import PrettyTable from crush.commands.common import Command from crush.helpers.common import contains from crush.helpers.module import MOD_INIT_TEXT, MOD_TEXT def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="lsmod", description="List loaded modules") parser.add_argument("--tainted", "-T", action="store_true", help="show tainting modules only") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None modules = [] for mod in list_for_each_entry("struct module", cmd.ctx.prog["modules"].address_of_(), "list"): if args.tainted and mod.taints == 0: continue addr = hex(mod.value_()) name = mod.name.string_().decode() if contains(mod, "init_layout") and contains(mod, "core_layout"): size = (mod.init_layout.size + mod.core_layout.size).value_() elif contains(mod, "init_size") and contains(mod, "core_size"): size = (mod.init_size + mod.core_size).value_() elif contains(mod, "mem"): size = (mod.mem[MOD_INIT_TEXT].size + mod.mem[MOD_TEXT].size).value_() else: raise NotImplementedError("`struct module` layout is not supported") if contains(mod, "refcnt"): refcnt = mod.refcnt.counter.value_() - 1 elif contains(mod, "refptr"): refcnt = 0 for i in for_each_possible_cpu(): pmod = per_cpu_ptr(mod.refptr, i) refcnt += pmod.incs.value_() refcnt -= pmod.decs.value_() else: raise NotImplementedError("`struct module` layout is not supported") taints = decode_flags(mod.taints, [("P", 0), ("O", 12), ("U", 13), ("T", 29)]) used_by = [] for use in list_for_each_entry( "struct module_use", mod.source_list.address_of_(), "source_list" ): used_by.append(use.source.name.string_().decode()) modules.append([addr, name, size, refcnt, taints, ", ".join(used_by)]) if modules: table = PrettyTable() table.border = False table.field_names = ["ADDR", "NAME", "SIZE", "REFCNT", "TAINTS", "USED BY"] table.align = "l" for j in modules: table.add_row(j) cmd.println(table.get_string()) return 0 if args.tainted: cmd.println("(no tainted modules)") return 0 cmd.println("(no modules)") return 0 0707010000001B000081A40000000000000000000000016573163100000EB4000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/mem.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn import Object from drgn.helpers.linux.mm import totalram_pages from prettytable import PrettyTable from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="mem", description="Show memory information") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None table = PrettyTable() table.border = False table.field_names = ["", "PAGES", "MiB", "%"] table.align = "r" nr_free_pages_idx = cmd.ctx.prog["NR_FREE_PAGES"] if "NR_KERNEL_STACK_KB" in cmd.ctx.prog: nr_kernel_stack_idx = cmd.ctx.prog["NR_KERNEL_STACK_KB"] nr_kernel_stack_in_kb = True elif "NR_KERNEL_STACK" in cmd.ctx.prog: nr_kernel_stack_idx = cmd.ctx.prog["NR_KERNEL_STACK"] nr_kernel_stack_in_kb = False else: raise NotImplementedError("Unable to enumerate kernel stack size") if cmd.ctx.symbol_exists("vm_zone_stat"): zone_stats = cmd.ctx.prog["vm_zone_stat"] elif cmd.ctx.symbol_exists("vm_stat"): zone_stats = cmd.ctx.prog["vm_stat"] else: cmd.errln("Unable to get VM zone stats") return -1 if cmd.ctx.symbol_exists("vm_node_stat"): node_stats = cmd.ctx.prog["vm_node_stat"] else: node_stats = None page_size = cmd.ctx.get_page_size() totalram = totalram_pages() * page_size totalram_mib = f"{totalram / 2**20:.2f}" nr_free_pages = zone_stats[nr_free_pages_idx].counter.value_() nr_free_mib = f"{nr_free_pages * page_size / 2**20:.2f}" nr_free_pct = f"{nr_free_pages / totalram_pages() * 100:.2f}" nr_used_pages = totalram_pages() - nr_free_pages nr_used_mib = f"{nr_used_pages * page_size / 2**20:.2f}" nr_used_pct = f"{nr_used_pages / totalram_pages() * 100:.2f}" # NR_KERNEL_STACK/NR_KERNEL_STACK_KB migrated from zone to node # in 991e7673859e, but RHEL 8 kernels are not very consistent with this vmstat_text = cmd.ctx.prog.symbol("vmstat_text") for i, ptr in enumerate( range(vmstat_text.address, vmstat_text.address + vmstat_text.size, cmd.ctx.get_word_size()) ): string = Object(cmd.ctx.prog, "char **", ptr)[0].string_().decode() if string == "nr_kernel_stack": if i in (9, 16): if nr_kernel_stack_in_kb: kernel_stack_kb = zone_stats[nr_kernel_stack_idx].counter.value_() kernel_stack_pages = int(kernel_stack_kb * 2**10 / page_size) else: kernel_stack_pages = zone_stats[nr_kernel_stack_idx].counter.value_() kernel_stack_kb = kernel_stack_pages * page_size / 2**10 elif i in (53, 54, 55): kernel_stack_kb = node_stats[nr_kernel_stack_idx].counter.value_() kernel_stack_pages = int(kernel_stack_kb * 2**10 / page_size) else: raise NotImplementedError(f"`nr_kernel_stack` text index is not known: {i}") nr_kernel_stack_pages = f"{kernel_stack_pages}" nr_kernel_stack_mib = f"{kernel_stack_kb / 2**10:.2f}" nr_kernel_stack_pct = f"{kernel_stack_pages / totalram_pages() * 100:.2f}" table.add_row(["TOTAL", totalram_pages(), totalram_mib, ""]) table.add_row(["USED", nr_used_pages, nr_used_mib, nr_used_pct]) table.add_row(["FREE", nr_free_pages, nr_free_mib, nr_free_pct]) table.add_row(["", "", "", ""]) table.add_row(["KSTACK", nr_kernel_stack_pages, nr_kernel_stack_mib, nr_kernel_stack_pct]) # TODO: add rest from /proc/meminfo cmd.println(table.get_string()) return 0 0707010000001C000081A400000000000000000000000165731631000004E6000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/mount.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn.helpers.linux.fs import for_each_mount, mount_dst, mount_fstype, mount_src from prettytable import PrettyTable from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="mount", description="Show mountpoints") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None table = PrettyTable() table.border = False table.align = "l" table.field_names = ["MOUNT", "SUPER_BLOCK", "TYPE", "DEV", "MOUNTPOINT"] for mount_struct in for_each_mount(): mount = hex(mount_struct.value_()) superblock_ptr = mount_struct.mnt.mnt_sb.value_() superblock = hex(superblock_ptr) if superblock_ptr != 0: mtype = mount_fstype(mount_struct).decode() devname = mount_src(mount_struct).decode() dirname = mount_dst(mount_struct).decode() else: mtype = "?" devname = "?" dirname = "?" table.add_row([mount, superblock, mtype, devname, dirname]) cmd.println(table.get_string()) return 0 0707010000001D000081A400000000000000000000000165731631000008C9000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/pcpu.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn import Object from drgn.helpers.linux.cpumask import for_each_online_cpu from drgn.helpers.linux.percpu import percpu_counter_sum from prettytable import PrettyTable from crush.commands.common import Command from crush.helpers.common import parse_cpu_range, resolve def main(cmd: Command) -> Optional[int]: parser = ArgumentParser( prog="pcpu", description="""Calculate sum of a per-CPU counter. Show per-CPU offsets if no address argument is given""", ) parser.add_argument( "--cpu", "-C", dest="cpu_filters", action="extend", nargs="+", help="show per-CPU offsets for given CPUs only", ) parser.add_argument("address", nargs="?", default=None, help="struct percpu_counter address") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None if args.address is None: cpu_list = [] if args.cpu_filters: for str_arg in args.cpu_filters: cpu_list.extend(parse_cpu_range(str_arg)) table = PrettyTable() table.align = "l" table.border = False table.field_names = ["CPU", "OFFSET"] table.align["CPU"] = "r" # type: ignore for cpu in for_each_online_cpu(): if cpu_list and cpu not in cpu_list: continue table.add_row([cpu, hex(cmd.ctx.prog["__per_cpu_offset"][cpu].value_())]) cmd.println(table.get_string()) return 0 addrs = [] if args.address == "-" and cmd.stdin is not None: for i in cmd.stdin: if i != "": addrs += resolve(cmd.ctx, i.strip()) else: addrs = resolve(cmd.ctx, args.address) table = PrettyTable() table.align = "r" table.border = False table.header = False for addr in addrs: vaddr = addr.get_addr() fbc = Object(cmd.ctx.prog, "struct percpu_counter *", vaddr) pcpu_sum = percpu_counter_sum(fbc) table.add_row([hex(vaddr) + ":", pcpu_sum]) cmd.println(table.get_string()) return 0 0707010000001E000081A40000000000000000000000016573163100003439000000000000000000000000000000000000003800000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/ps.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Dict, List, Optional from drgn import Object from drgn.helpers.linux.mm import totalram_pages from drgn.helpers.linux.percpu import per_cpu from prettytable import PrettyTable from crush.commands.common import Command from crush.context import Context from crush.helpers.common import parse_cpu_range from crush.helpers.sched import ( is_active, is_group_leader, is_kthread, task_cpu, task_niceval, task_policy_to_str, task_rss, task_rtprio, task_state_to_char, tasks_from_stdin, ) PS_MEM_NO_MM = -1 PS_MEM_KTHREAD_OR_UTHREAD = -2 def is_eligible( ctx: Object, task: Object, tasks: List[Object], cpu_list: List[int], active_filters: List[str], state_filters: List[str], policy_filters: List[str], space_filters: List[str], other_filters: List[str], ) -> bool: cpu = task_cpu(task) active = is_active(ctx, task) state = task_state_to_char(task) policy = task_policy_to_str(task) if task not in tasks: return False if cpu_list and cpu not in cpu_list: return False if active_filters and not active: return False if state_filters and state not in state_filters: return False if policy_filters and policy not in policy_filters: return False if space_filters and not ( ("K" in space_filters and is_kthread(task)) or ("U" in space_filters and not is_kthread(task)) ): return False if other_filters and not ("G" in other_filters and is_group_leader(task)): return False return True def populate( ctx: Context, table: PrettyTable, task: Object, group_leader_eligible: bool, bare: bool ) -> None: taskp = hex(task.value_()) if bare: table.add_row([taskp]) else: pid = task.pid.value_() ppid = task.real_parent.pid.value_() policy = task_policy_to_str(task) rt_prio = task_rtprio(task) nice_val = task_niceval(task) comm = task.comm.string_().decode() cpu = task_cpu(task) rq_clock = per_cpu(ctx.prog["runqueues"], cpu).clock.value_() task_clock = task.sched_info.last_arrival.value_() time = rq_clock - task_clock state = task_state_to_char(task) state += "X" if is_active(ctx, task) else "" mm_struct = task.mm if not is_kthread(task) and ( is_group_leader(task) or (not is_group_leader(task) and not group_leader_eligible) ): rss: Optional[int] = task_rss(task) if rss is None: rss = PS_MEM_NO_MM vsz = PS_MEM_NO_MM pmem = float(PS_MEM_NO_MM) else: page_size = ctx.get_page_size() rss *= page_size pmem = rss / (totalram_pages() * ctx.get_page_size()) * 100 vsz = mm_struct.total_vm.value_() * page_size else: rss = PS_MEM_KTHREAD_OR_UTHREAD vsz = PS_MEM_KTHREAD_OR_UTHREAD pmem = float(PS_MEM_KTHREAD_OR_UTHREAD) tcomm = comm if not is_group_leader(task) and group_leader_eligible: tcomm = "+-" + comm if rt_prio != 0: prio = str(rt_prio) nice = "-" else: # rt_prio == 0 means running on CFS, hence nice value applies prio = "-" nice = str(nice_val) table.add_row( [time, pid, ppid, cpu, policy, prio, nice, taskp, state, pmem, rss, vsz, tcomm] ) def sort_int(val: List[str]) -> int: try: return int(val[0]) except ValueError: return 0 def format_timestamp(_field: str, value: str) -> str: nsecs = int(value) msecs = nsecs // 1_000_000 days = msecs // 86_400_000 msecs %= 86_400_000 hours = msecs // 3_600_000 msecs %= 3_600_000 mins = msecs // 60_000 msecs %= 60_000 secs = msecs // 1_000 msecs %= 1_000 return f"[{days: 4d} {hours:02d}:{mins:02d}:{secs:02d}.{msecs:03d}]" def format_memory(_field: str, value: str) -> str: if value == PS_MEM_NO_MM: return "-" if value == PS_MEM_KTHREAD_OR_UTHREAD: return "" return str(int(value) // 1_024) def format_memory_pct(_field: str, value: str) -> str: if value == float(PS_MEM_NO_MM): return "-" if value == float(PS_MEM_KTHREAD_OR_UTHREAD): return "" return f"{value:.2f}" def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="ps", description="Show information on processes") parser.add_argument( "pid", nargs="*", default=None, help="PID or struct task_struct address(es)" ) # modifiers parser.add_argument("--summary", "-s", action="store_true", help="show task states summary") parser.add_argument( "--bare", "-b", action="store_true", help="show struct task_struct pointers only", ) parser.add_argument( "--by-rss", "-r", action="store_true", help="sort tasks by RSS usage (implies -U and -G)", ) parser.add_argument( "--by-vsz", "-v", action="store_true", help="sort tasks by VSZ usage (implies -U and -G)", ) parser.add_argument( "--by-time", "-t", action="store_true", help="sort tasks by runqueue timestamp", ) # filters # - cpu parser.add_argument( "--cpu", "-C", dest="cpu_filters", action="extend", nargs="+", help="show tasks assigned to a CPU", ) # - active parser.add_argument( "--active", "-X", dest="active_filters", action="append_const", const="X", help="show active tasks", ) # - state parser.add_argument( "--running", "-R", dest="state_filters", action="append_const", const="R", help="show running tasks", ) parser.add_argument( "--sleeping", "-S", dest="state_filters", action="append_const", const="S", help="show tasks in interruptible sleep", ) parser.add_argument( "--disksleep", "-D", dest="state_filters", action="append_const", const="D", help="show tasks in uninterruptible sleep", ) parser.add_argument( "--zombie", "-Z", dest="state_filters", action="append_const", const="Z", help="show zombie tasks", ) parser.add_argument( "--parked", "-P", dest="state_filters", action="append_const", const="P", help="show parked tasks", ) parser.add_argument( "--idle", "-I", dest="state_filters", action="append_const", const="I", help="show idle tasks", ) parser.add_argument( "--waking", "-W", dest="state_filters", action="append_const", const="W", help="show waking tasks", ) parser.add_argument( "--wakekill", "-A", dest="state_filters", action="append_const", const="A", help="show wakekill tasks", ) # - sched policy parser.add_argument( "--normal", "-N", dest="policy_filters", action="append_const", const="OT", help="show SCHED_OTHER tasks", ) parser.add_argument( "--fifo", "-F", dest="policy_filters", action="append_const", const="FF", help="show SCHED_FIFO tasks", ) parser.add_argument( "--rr", "-O", dest="policy_filters", action="append_const", const="RR", help="show SCHED_RR tasks", ) parser.add_argument( "--batch", "-B", dest="policy_filters", action="append_const", const="BA", help="show SCHED_BATCH tasks", ) parser.add_argument( "--pidle", "-L", dest="policy_filters", action="append_const", const="ID", help="show SCHED_IDLE tasks", ) parser.add_argument( "--deadline", "-E", dest="policy_filters", action="append_const", const="DL", help="show SCHED_DEADLINE tasks", ) # - kernel/user parser.add_argument( "--kernel", "-K", dest="space_filters", action="append_const", const="K", help="show kernel tasks only", ) parser.add_argument( "--user", "-U", dest="space_filters", action="append_const", const="U", help="show userspace tasks only", ) # - other parser.add_argument( "--group-leader", "-G", dest="other_filters", action="append_const", const="G", help="hide userspace threads", ) try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None sorting = args.by_rss + args.by_vsz + args.by_time if sorting > 1: cmd.errln("Incompatible arguments") return -1 if args.bare and sorting: cmd.errln("Incompatible arguments") return -1 if args.by_rss or args.by_vsz: args.group_leader = True if not args.other_filters: args.other_filters = [] args.other_filters.append("G") args.user = True if not args.space_filters: args.space_filters = [] args.space_filters.append("U") if ( args.cpu_filters or args.active_filters or args.state_filters or args.policy_filters or args.space_filters or args.other_filters ) and args.summary: cmd.errln("Incompatible arguments") return -1 cpu_list = [] if args.cpu_filters: for str_arg in args.cpu_filters: cpu_list.extend(parse_cpu_range(str_arg)) tasks = tasks_from_stdin(cmd.ctx, args.pid, cmd.stdin, True) if args.summary: states = {} for task in tasks: state = task_state_to_char(task) if state not in states: states[state] = 0 states[state] += 1 table = PrettyTable() table.header = False table.border = False for state_char, task_count in states.items(): table.add_row([state_char + ":", task_count]) table.align = "l" cmd.println(table.get_string()) else: table = PrettyTable() table.border = False if args.bare: table.header = False else: table.field_names = [ "TIME", "PID", "PPID", "CPU", "SP", "PRIO", "NICE", "TASK", "ST", "%MEM", "RSS", "VSZ", "COMM", ] table.align = "l" # pylint: disable=unsupported-assignment-operation table.align["PRIO"] = "r" # type: ignore table.align["NICE"] = "r" # type: ignore # pylint: enable=unsupported-assignment-operation table.custom_format["TIME"] = format_timestamp table.custom_format["%MEM"] = format_memory_pct table.custom_format["RSS"] = format_memory table.custom_format["VSZ"] = format_memory tgids: Dict[int, List] = {} for task in tasks: if task is None: continue tgidh = task.group_leader.value_() if tgidh not in tgids: tgids[tgidh] = [] if task.group_leader == task: continue tgids[tgidh].append(task) for task_address, threads in tgids.items(): task = Object(cmd.ctx.prog, "struct task_struct *", task_address) group_leader_eligible = is_eligible( cmd.ctx, task, tasks, cpu_list, args.active_filters, args.state_filters, args.policy_filters, args.space_filters, args.other_filters, ) if group_leader_eligible: populate(cmd.ctx, table, task, True, args.bare) for thread in threads: if is_eligible( cmd.ctx, thread, tasks, cpu_list, args.active_filters, args.state_filters, args.policy_filters, args.space_filters, args.other_filters, ): populate(cmd.ctx, table, thread, group_leader_eligible, args.bare) if args.by_rss: sortby = "RSS" elif args.by_vsz: sortby = "VSZ" elif args.by_time: sortby = "TIME" else: sortby = None cmd.println(table.get_string(sortby=sortby, sort_key=sort_int)) return 0 0707010000001F000081A4000000000000000000000001657316310000149D000000000000000000000000000000000000003800000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/rd.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Dict, List, Optional from prettytable import PrettyTable from crush.commands.common import Command from crush.context import Context from crush.helpers.common import Address, bin2ascii, demangle, resolve, wreg def read_content( ctx: Context, addrs: List[Address], size: int, word_size: Optional[int], phys: bool, stringify: bool, symbolify: bool, ) -> List[List]: val = [] if word_size is None: word_size = ctx.get_word_size() for i in addrs: addr = i.get_addr() word: List[Dict] = [] if stringify: word_str = [] addr_to_show = None steps = range(0, int(size)) for j in steps: addr_to_read = addr + j * word_size if addr_to_show is None: addr_to_show = addr_to_read match word_size: case 1: word_raw = ctx.prog.read_u8(addr_to_read, physical=phys) case 2: word_raw = ctx.prog.read_u16(addr_to_read, physical=phys) case 4: word_raw = ctx.prog.read_u32(addr_to_read, physical=phys) case 8: word_raw = ctx.prog.read_u64(addr_to_read, physical=phys) case _: raise ValueError(f"Unexpected word size: {word_size}") if symbolify: symbolic = demangle(ctx, word_raw) if symbolic is not None: word.append({"resolved": True, "qual": symbolic}) else: word.append({"resolved": False, "qual": word_raw}) else: word.append({"resolved": False, "qual": word_raw}) if stringify: raw = ctx.prog.read(addr_to_read, word_size, physical=phys) word_str.append(bin2ascii(raw)) if len(word) == 2 or j == steps[-1]: if word[0]["resolved"]: row = [hex(addr_to_show) + ":", word[0]["qual"]] else: content = word[0]["qual"] row = [ hex(addr_to_show) + ":", wreg(ctx, content, word_size, False), ] if len(word) == 2: if word[1]["resolved"]: row += [word[1]["qual"]] else: content = word[1]["qual"] row += [wreg(ctx, content, word_size, False)] elif j == steps[-1]: row += [""] if stringify: text = word_str[0] if len(word) == 2: text += word_str[1] row += [text] else: row += [""] val.append(row) word = [] if stringify: word_str = [] addr_to_show = None return val def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="rd", description="Read a content of memory") parser.add_argument( "-s", "--stringify", action="store_true", help="try to convert binary data into ASCII", ) parser.add_argument( "-S", "--symbolify", action="store_true", help="try to resolve addresses into symbols", ) parser.add_argument( "-p", "--physical", action="store_true", help="treat memory address as physical" ) parser.add_argument( "-8", "--byte", dest="word_size", action="store_const", const=1, help="word size is 1 byte", ) parser.add_argument( "-16", "--two-bytes", dest="word_size", action="store_const", const=2, help="word size is 2 byte", ) parser.add_argument( "-32", "--four-bytes", dest="word_size", action="store_const", const=4, help="word size is 4 byte", ) parser.add_argument( "-64", "--eight-bytes", dest="word_size", action="store_const", const=8, help="word size is 8 byte", ) parser.add_argument("address", help="memory address to read from") parser.add_argument("size", nargs="?", default=1, help="amount of words to read") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None addrs = [] if args.address == "-" and cmd.stdin is not None: for i in cmd.stdin: if i != "": addrs += resolve(cmd.ctx, i.strip()) else: addrs = resolve(cmd.ctx, args.address) buf = read_content( cmd.ctx, addrs, args.size, args.word_size, args.physical, args.stringify, args.symbolify, ) table = PrettyTable() table.border = False table.header = False table.align = "l" for i in buf: table.add_row(i) table.max_width = 40 cmd.println(table.get_string()) return 0 07070100000020000081A40000000000000000000000016573163100000A03000000000000000000000000000000000000003C00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/search.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from math import ceil from typing import Optional from drgn.helpers.linux.pid import for_each_task from prettytable import PrettyTable from crush.commands.common import Command from crush.commands.rd import read_content from crush.helpers.common import Address from crush.helpers.sched import task_header def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="search", description="Search for memory content") parser.add_argument( "-s", "--stringify", action="store_true", help="try to convert binary data into ASCII", ) parser.add_argument( "-S", "--symbolify", action="store_true", help="try to resolve addresses into symbols", ) # TODO: search works on task stacks by default # since full memory search is barely usable due to speed # TODO: other goodies from crash-util: search throughout all the memory, # physical address, mask etc parser.add_argument("value", help="hex sequence to search for") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None # TODO: also account for leading zeroes what = int(args.value, 16) length = ceil(len(hex(what)[2:]) / 2) for task in for_each_task(): stack_address = task.stack # TODO: no stack size hardcoding stack_size = 0x4000 stack = cmd.ctx.prog.read(stack_address, stack_size) contents = [] # TODO: little vs big # use struct instead of .to_bytes() maybe? offset = stack.find(what.to_bytes(length, "little")) while not offset == -1: content = read_content( cmd.ctx, [Address(None, None, stack_address + offset)], 1, None, False, args.stringify, args.symbolify, ) # TODO: this won't show what's found in real time contents.append(content[0]) offset = stack.find(what.to_bytes(length, "little"), offset + 1) if contents: cmd.println(task_header(task)) table = PrettyTable() table.border = False table.header = False table.align = "r" for content in contents: table.add_row(content) cmd.println(table.get_string()) cmd.println("") return 0 07070100000021000081A40000000000000000000000016573163100000379000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/set.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from crush.commands.common import Command from crush.helpers.sched import task_handle_to_task, task_header def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="set", description="Set internal variables") parser.add_argument("pid", nargs="?", default=None, help="set context to a given task") parser.add_argument("--panic", "-p", action="store_true", help="set context to a panic task") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None if args.pid is not None: cmd.ctx.current = task_handle_to_task(cmd.ctx, args.pid) elif args.panic: cmd.ctx.current = cmd.ctx.prog.crashed_thread().object cmd.println(task_header(cmd.ctx.current)) return 0 07070100000022000081A40000000000000000000000016573163100000BF1000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/slabs.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional, Union from drgn import Object, cast from drgn.helpers.linux.list import list_for_each_entry from drgn.helpers.linux.nodemask import for_each_online_node from drgn.helpers.linux.slab import for_each_slab_cache from prettytable import PrettyTable from crush.commands.common import Command from crush.helpers.common import contains OO_SHIFT = 16 def sort_slabs(val: str) -> Union[int, str]: try: return int(val[0][:-1]) except ValueError: return val def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="slabs", description="Show information about SLAB subsystem") parser.add_argument("--by-name", "-n", action="store_true", help="sort by name") parser.add_argument("--by-size", "-s", action="store_true", help="sort by memory usage") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None if args.by_name: sortby = "NAME" elif args.by_size: sortby = "MEM" else: sortby = None table = PrettyTable() table.border = False table.align = "r" table.field_names = [ "NAME", "KMEM_CACHE", "OBJSIZE", "ALLOCATED", "TOTAL", "SLABS", "SSIZE", "MEM", ] page_size = cmd.ctx.get_page_size() # upstream kernel commit 4da1984edb struct_page = Object(cmd.ctx.prog, "struct page *", 0) if contains(struct_page, "next"): # RHEL 7 slab_list_member = "next" elif contains(struct_page, "slab_list"): # RHEL 8, 9 slab_list_member = "slab_list" elif contains(struct_page, "lru"): # v6.2 slab_list_member = "lru" for slab in for_each_slab_cache(): addr = hex(slab.value_()) objsize = slab.object_size.value_() name = slab.name.string_().decode() slabs = 0 total = 0 free = 0 for node in for_each_online_node(): slabs += slab.node[node].nr_slabs.counter.value_() total += slab.node[node].total_objects.counter.value_() # TODO: needs verification for page in list_for_each_entry( "struct page", slab.node[node].partial.address_of_(), slab_list_member ): if contains(page, "objects"): free += page.objects.value_() - page.inuse.value_() else: struct_slab = cast("struct slab *", page) free += struct_slab.objects.value_() - struct_slab.inuse.value_() allocated = total - free ssize_bytes = 2 ** (slab.oo.x.value_() >> OO_SHIFT) * page_size ssize = str(ssize_bytes // 2**10) + "k" mem = str(slabs * ssize_bytes // 2**10) + "k" table.add_row([name, addr, objsize, allocated, total, slabs, ssize, mem]) cmd.println(table.get_string(sortby=sortby, sort_key=sort_slabs)) return 0 07070100000023000081A400000000000000000000000165731631000010E0000000000000000000000000000000000000003C00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/struct.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn import Object from crush.commands.common import Command from crush.helpers.common import resolve def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="struct", description="Show a content of a given structure") parser.add_argument("-a", "--member-address", action="store_true", help="show member address") parser.add_argument( "-d", "--no-dereference", action="store_true", help="do not dereference leaf pointer", ) parser.add_argument( "-s", "--no-struct-type", action="store_true", help="do not show struct type" ) parser.add_argument( "-t", "--member-types", action="store_true", help="show struct member types", ) parser.add_argument( "-Y", "--do-not-symbolify", action="store_true", help="do not resolve addresses into symbols", ) parser.add_argument("structure", help="structure name") parser.add_argument("address", help="structure address") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None struct_name = args.structure.split(".")[0] struct_members = ".".join(args.structure.split(".")[1:]).split(",") addrs = [] if args.address == "-" and cmd.stdin is not None: for i in cmd.stdin: if not i == "": addrs += resolve(cmd.ctx, i.strip()) else: addrs = resolve(cmd.ctx, args.address) for addr in addrs: struct_addr = addr.get_addr() struct = Object(cmd.ctx.prog, f"struct {struct_name} *", struct_addr) struct_prefix = "" # prepend per-CPU info if addr.is_percpu(): struct_prefix = f"[{addr.get_cpu()}]:" + " " if struct_members == [""]: # dump the whole struct if no struct members are specified # TODO: is no_dereference actually useful here? # how to make members not to be dereferenced, # but still dereference the outer struct? struct_str = struct.format_( dereference=not args.no_dereference, symbolize=not args.do_not_symbolify, type_name=not args.no_struct_type, member_type_names=args.member_types, ) cmd.println(f"{struct_prefix}{struct_str}") else: # dump struct type (if not asked otherwise) and address if args.no_struct_type: cmd.println(f"{struct_prefix}*0x{struct_addr:x} = " + "{") else: cmd.println(f"{struct_prefix}*({struct.type_})0x{struct_addr:x} = " + "{") # go through supplied struct members for member in struct_members: leaf = struct leaf_path_steps = [] for step in member.split("."): # dig through nested struct members leaf = leaf.member_(step) leaf_path_steps.append(step) leaf_prefix = "" # dump struct member address within the struct if args.member_address: leaf_prefix = f"[0x{leaf.address_:x}]" + " " # dump a path to a nested struct member leaf_path = ".".join(leaf_path_steps) # dump the struct member # note that both type name and member type names depend on args.member_types # as these are struct members, not the outer struct itself leaf_suffix = leaf.format_( dereference=not args.no_dereference, symbolize=not args.do_not_symbolify, type_name=args.member_types, member_type_names=args.member_types, ) # shape the struct member line leaf_str = f"{leaf_prefix}.{leaf_path} = {leaf_suffix}" # indent struct members for leaf_line in leaf_str.split("\n"): cmd.println(f"\t{leaf_line}") # close the struct cmd.println("}") return 0 07070100000024000081A400000000000000000000000165731631000006C7000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/swap.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn.helpers.linux.fs import d_path from prettytable import PrettyTable from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="swap", description="Show swap information") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None nr_swapfiles = cmd.ctx.prog["nr_swapfiles"] swap_info = cmd.ctx.prog["swap_info"] page_size = cmd.ctx.get_page_size() swaps = [] for i in range(0, nr_swapfiles): swap_info_struct = swap_info[i] swap_info_struct_addr = hex(swap_info_struct.value_()) flags = hex(swap_info_struct.flags) prio = swap_info_struct.prio.value_() total = swap_info_struct.pages.value_() * page_size total_mib = f"{total / 2**20:.2f}" inuse = swap_info_struct.inuse_pages.value_() * page_size inuse_mib = f"{inuse / 2**20:.2f}" pct_used = f"{inuse / total * 100:.2f}" file = d_path(swap_info_struct.swap_file.f_path).decode() swaps.append([swap_info_struct_addr, flags, prio, total_mib, inuse_mib, pct_used, file]) if swaps: table = PrettyTable() table.border = False table.field_names = [ "swap_info_struct", "FLAGS", "PRIO", "TOTAL, MiB", "IN USE, MiB", "% USED", "FILE", ] table.align = "r" for j in swaps: table.add_row(j) cmd.println(table.get_string()) return 0 cmd.println("(no swap)") return 0 07070100000025000081A40000000000000000000000016573163100000597000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/sym.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from crush.commands.common import Command from crush.helpers.common import demangle, resolve, try_int def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="sym", description="Show information on a given symbol") parser.add_argument("sym", nargs="+", help="symbol name or address") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None syms = [] for i in args.sym: if i == "-" and cmd.stdin is not None: for j in cmd.stdin: if j != "": syms.append(j) else: syms.append(i) for i in syms: val = try_int(i) if val is None: addrs = resolve(cmd.ctx, i) for j in addrs: addr = j.get_addr() sym_str = hex(addr) try: sym_str += "," + " " + repr(cmd.ctx.prog.symbol(i)) except LookupError: # TODO: a more elegant way to handle per-CPU variables like `cpu_info`? pass cmd.println(sym_str) else: sym = demangle(cmd.ctx, val) if sym is not None: cmd.println(sym + "," + " " + repr(cmd.ctx.prog.symbol(val))) return 0 07070100000026000081A400000000000000000000000165731631000004B3000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/taint.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn.helpers.common.format import decode_flags from crush.commands.common import Command taint_flags = [ ("PROPRIETARY_MODULE", 0), ("FORCED_MODULE", 1), ("CPU_OUT_OF_SPEC", 2), ("FORCED_RMMOD", 3), ("MACHINE_CHECK", 4), ("BAD_PAGE", 5), ("USER", 6), ("DIE", 7), ("OVERRIDDEN_ACPI_TABLE", 8), ("WARN", 9), ("CRAP", 10), ("FIRMWARE_WORKAROUND", 11), ("OOT_MODULE", 12), ("UNSIGNED_MODULE", 13), ("SOFTLOCKUP", 14), ("LIVEPATCH", 15), ("AUX", 16), ("RANDSTRUCT", 17), ("HARDWARE_UNSUPPORTED", 28), ("TECH_PREVIEW", 29), ] def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="taint", description="Show and decode tainting flags") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None tainted_mask = cmd.ctx.prog["tainted_mask"].value_() if tainted_mask == 0: cmd.println("(not tainted)") return 0 cmd.println(hex(tainted_mask) + ": " + decode_flags(tainted_mask, taint_flags)) return 0 07070100000027000081A40000000000000000000000016573163100000613000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/tree.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn import Object # from drgn.helpers.linux.radixtree import radix_tree_for_each from drgn.helpers.linux.rbtree import rbtree_inorder_for_each from prettytable import PrettyTable from crush.commands.common import Command from crush.helpers.common import resolve def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="tree", description="Iterate over a tree") parser.add_argument("-t", "--type", choices=["ra", "rb"], help="tree type") # TODO: add offset, reverse options, xarray, rb_node as starting point parser.add_argument("root", help="root address") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None table = PrettyTable() table.border = False table.header = False table.align = "l" addrs = resolve(cmd.ctx, args.root) for i in addrs: addr = i.get_addr() if args.type == "ra": # TODO: needs verification pass # radix_tree_root = Object(cmd.ctx.prog, "struct radix_tree_root *", addr) # for i in radix_tree_for_each(radix_tree_root): # print(i) elif args.type == "rb": rb_root = Object(cmd.ctx.prog, "struct rb_root *", addr) for j in rbtree_inorder_for_each(rb_root): table.add_row([hex(j.value_())]) cmd.println(table.get_string()) return 0 07070100000028000081A40000000000000000000000016573163100000637000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/type.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="type", description="Show information about a given type") parser.add_argument("type", nargs="+", help="type of interest") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None type_def = " ".join(cmd.argv[1:]) type_name = type_def.split(".", maxsplit=1)[0] type_members = ".".join(type_def.split(".")[1:]).split(",") for i in type_members: type_struct = cmd.ctx.prog.type(type_name) offset = 0 path = [] if not i == "": for j in i.split("."): found = False for k in type_struct.members: if k.name == j: path.append(k.name) type_struct = k.type offset += k.bit_offset found = True break if not found: cmd.errln(f"Member `.{j}` of `{type_name}` doesn't exist") return -1 if path: cmd.println( "[" + hex(int(offset / 8)) + "]" + " " + str(type_struct) + " " + "." + ".".join(path) ) else: cmd.println(type_struct) return 0 07070100000029000081A400000000000000000000000165731631000001F4000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/uname.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="uname", description="Show kernel version information") try: _ = parser.parse_args(cmd.argv[1:]) except SystemExit: return None cmd.println(cmd.ctx.prog["linux_banner"].string_().decode().replace("\n", "")) return 0 0707010000002A000081A40000000000000000000000016573163100000876000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/var.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn import FaultError, TypeKind from drgn.helpers.linux.percpu import per_cpu from crush.commands.common import Command from crush.helpers.common import parse_cpu_range def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="var", description="Show a content of a given variable") parser.add_argument("-x", "--hex", action="store_true", help="show value in hex") parser.add_argument("var", help="variable name") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None # TODO: can this code be merged with resolve() helper? if ":" in args.var: varname, cpu = args.var.split(":") cpu = parse_cpu_range(cpu) else: varname = args.var cpu = None variable = cmd.ctx.prog.variable(varname) kind = variable.type_.kind match kind: case TypeKind.INT: if cpu is not None: for i in cpu: val = per_cpu(variable, i) if args.hex: cmd.println(hex(val)) else: cmd.println(val) else: val = variable.value_() if args.hex: cmd.println(hex(val)) else: cmd.println(val) case TypeKind.ARRAY: elemtype = variable[0].type_.kind match elemtype: case TypeKind.INT: match variable[0].type_.name: case "char": cmd.println(variable.string_().decode()) case _: cmd.println(str(variable)) case TypeKind.POINTER: try: cmd.println(variable) except FaultError: # TODO: array of struct pointers cmd.println(repr(variable)) case _: cmd.println(variable) return 0 0707010000002B000081A40000000000000000000000016573163100000545000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/commands/vtop.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from drgn.helpers.linux.mm import ( follow_page, follow_phys, page_to_pfn, page_to_phys, vmalloc_to_page, ) from prettytable import PrettyTable from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="vtop", description="Translate virtual address to a physical one") parser.add_argument( "--user", "-u", action="store_true", help="treat address as a userspace one" ) parser.add_argument("address", help="virtual address") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None table = PrettyTable() table.align = "r" table.border = False table.header = False addr = int(args.address, 16) if args.user: page = follow_page(cmd.ctx.current.mm, addr) phys = follow_phys(cmd.ctx.current.mm, addr) else: page = vmalloc_to_page(addr) phys = page_to_phys(page) | (addr & ((1 << cmd.ctx.prog["PAGE_SHIFT"]) - 1)) pfn = page_to_pfn(page) table.add_row(["PAGE", hex(page.value_())]) table.add_row(["PFN", hex(pfn)]) table.add_row(["PHYS", hex(phys)]) cmd.println(table.get_string()) return 0 0707010000002C000081A400000000000000000000000165731631000011A7000000000000000000000000000000000000003400000000crush-2023.0.dev1702041137+8ae4b21/crush/context.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from typing import Dict, List, Optional from drgn import PlatformFlags, Program, set_default_prog from drgn.helpers.linux.kconfig import get_kconfig class Context: """ Represents a crush context which contains drgn prog, current task, debug information and symbols cache. Attributes ---------- prog: drgn.Program reference to drgn prog current: drgn.Object reference to a current task vmcore: str path to a vmcore file debug_info: List[str] list of files containing debug symbols debug_mode: bool indicates if extra debugging output is enabled symcache: Dict[int, Optional[str]] cache of virtual address mappings to their symbolic names + offset page_size: int size of one page in bytes modcache: Dict[int, Optional[str]] cache of virtual address mappings to their module names word_size: int the size of the word on this platform config_hz: int CONFIG_HZ value Methods ------- in_symcache(addr): Checks if a symbolic representation of a given address is in cache get_from_symcache(addr): Gets a symbolic representation of a given address from cache put_to_symcache(addr, val): Puts a symbolic representation of a given address to cache get_page_size(): Returns a page size in_modcache(addr): Checks if a module name that corresponds to a given address is in cache get_from_modcache(addr): Gets a module name that corresponds to a given address from cache put_to_modcache(addr, val): Puts a module name that corresponds to a given address to cache get_word_size(): Returns the size of the word on this platform get_config_hz(): Returns CONFIG_HZ value get_vmcore(): Returns a path to a vmcore file get_vmlinux(): Returns a path to a vmlinux file get_banner(): Returns kernel banner symbol_exists(): Checks if a given symbol exists """ def __init__( self, prog: Program, vmcore: str, debug_info: List[str], config_hz: int, debug_mode: bool ): self.prog = prog set_default_prog(self.prog) self.current = prog.crashed_thread().object self.vmcore = vmcore self.debug_info = debug_info self.debug_mode = debug_mode self.symcache: Dict[int, Optional[str]] = {} self.page_size = prog["PAGE_SIZE"].value_() self.modcache: Dict[int, Optional[str]] = {} if not prog.platform.flags & PlatformFlags.IS_64_BIT: self.word_size = 4 else: self.word_size = 8 if config_hz is not None: self.config_hz = config_hz else: self.config_hz = -1 try: self.config_hz = int(get_kconfig(prog)["CONFIG_HZ"]) except LookupError: pass if self.config_hz == -1: try: # block/mq-deadline.c # static const int write_expire = 5 * HZ self.config_hz = prog["write_expire"].value_() // 5 except KeyError: pass if self.config_hz == -1: print("Unable to get CONFIG_HZ value, defaulting to 1000") self.config_hz = 1000 def in_symcache(self, addr: int) -> bool: return addr in self.symcache def get_from_symcache(self, addr: int) -> Optional[str]: return self.symcache[addr] def put_to_symcache(self, addr: int, val: Optional[str]) -> None: self.symcache[addr] = val def get_page_size(self) -> int: return self.page_size def in_modcache(self, addr: int) -> bool: return addr in self.modcache def get_from_modcache(self, addr: int) -> Optional[str]: return self.modcache[addr] def put_to_modcache(self, addr: int, val: Optional[str]) -> None: self.modcache[addr] = val def get_word_size(self) -> int: return self.word_size def get_config_hz(self) -> int: return self.config_hz def get_vmcore(self) -> str: return self.vmcore def get_vmlinux(self) -> str: return self.debug_info[0] def symbol_exists(self, sym: str) -> bool: try: _ = self.prog[sym] except KeyError: return False return True 0707010000002D000081A4000000000000000000000001657316310000131C000000000000000000000000000000000000003200000000crush-2023.0.dev1702041137+8ae4b21/crush/crush.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later import tomllib from argparse import ArgumentParser from importlib.metadata import PackageNotFoundError, version from os import walk from os.path import join from pathlib import Path from resource import RLIMIT_NOFILE, getrlimit, setrlimit from sys import stdout from drgn import FaultError, MissingDebugInfoError, Program from drgn.helpers.linux.list import list_for_each_entry from xdg import BaseDirectory from crush.commands.common import command, loop, print_err from crush.context import Context MOD_SUFFIX = ".ko.debug" def launch() -> None: try: # installed package app_ver = version(__package__) except PackageNotFoundError: # development folder with open("pyproject.toml", "rb") as prj_file: app_ver = tomllib.load(prj_file)["project"]["version"] parser = ArgumentParser(description="A drgn-based crash-util replacement") parser.add_argument("-v", "--version", action="version", version=f"{__package__} v{app_ver}") parser.add_argument("--vmcore", "-c", type=str, required=True, help="path to vmcore") parser.add_argument("--vmlinux", "-l", type=str, required=True, help="path to vmlinux") parser.add_argument("--mods", "-m", type=str, help="path to modules debuginfo") parser.add_argument("--hz", "-z", type=int, help="CONFIG_HZ value") parser.add_argument("--crushrc", "-r", type=str, help="path to crushrc") parser.add_argument( "--debug-mode", "-d", action="store_true", help="enable debug mode for development purposes", ) args = parser.parse_args() prog = Program() try: prog.set_core_dump(args.vmcore) except (FileNotFoundError, ValueError) as exc: print_err(args.vmcore + ":" + " " + str(exc)) return print("Loading kernel debug info...", end="") stdout.flush() try: prog.load_debug_info([args.vmlinux]) except MissingDebugInfoError as exc: print_err() print_err(exc) return print(" done") debug_info = [] debug_info.append(args.vmlinux) loaded_mod_names = [] try: for mod in list_for_each_entry("struct module", prog["modules"].address_of_(), "list"): loaded_mod_names.append(mod.name.string_().decode().replace("-", "_")) except FaultError: # TODO: ppc64le: Cannot get page I/O address: No way to translate pass mod_debug_info = [] if args.mods is not None: for root, _, files in walk(args.mods): for file_name in files: if not file_name.endswith(MOD_SUFFIX): continue file_name_normalised = file_name.replace("-", "_") file_name_normalised = file_name_normalised[ : len(file_name_normalised) - len(MOD_SUFFIX) ] if file_name_normalised in loaded_mod_names: mod_debug_info.append(join(root, file_name)) nofiles = len(mod_debug_info) if nofiles != 0: (curr_nofiles_soft, curr_nofiles_hard) = getrlimit(RLIMIT_NOFILE) new_nofiles_soft = curr_nofiles_soft new_nofiles_hard = curr_nofiles_hard if nofiles > curr_nofiles_hard: new_nofiles_hard = int(nofiles * 2) if nofiles > curr_nofiles_soft: new_nofiles_soft = min(int(nofiles * 1.5), curr_nofiles_hard) if new_nofiles_soft != curr_nofiles_soft or new_nofiles_hard != curr_nofiles_hard: print("Raising RLIMIT_NOFILE...", end="") setrlimit(RLIMIT_NOFILE, (new_nofiles_soft, new_nofiles_hard)) print(" done") plural = "" if nofiles == 1 else "s" print(f"Loading modules debug info from {nofiles} file{plural}...", end="") stdout.flush() try: prog.load_debug_info(mod_debug_info) except MissingDebugInfoError as exc: print_err() print_err(exc) return print(" done") debug_info += mod_debug_info context = Context(prog, args.vmcore, debug_info, args.hz, args.debug_mode) print("") command(context, "info") print("") crushrcs = [ Path.home().joinpath(".crushrc"), ] if not BaseDirectory.xdg_config_home == "": crushrcs.append(BaseDirectory.xdg_config_home + "/crush/crushrc") else: crushrcs.append(Path.home().joinpath("config/crushrc/crushrc")) if args.crushrc is not None: crushrcs.append(args.crushrc) for crushrc in crushrcs: if Path(crushrc).exists(): with open(crushrc, encoding="utf-8") as file: for cmd in file.readlines(): if command(context, cmd): return loop(context) if __name__ == "__main__": launch() 0707010000002E000041ED0000000000000000000000026573163100000000000000000000000000000000000000000000002D00000000crush-2023.0.dev1702041137+8ae4b21/crush/ext0707010000002F000081A40000000000000000000000016573163100000042000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/ext/__init__.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later 07070100000030000081A40000000000000000000000016573163100000372000000000000000000000000000000000000003600000000crush-2023.0.dev1702041137+8ae4b21/crush/ext/hello.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from argparse import ArgumentParser from typing import Optional from crush.commands.common import Command def main(cmd: Command) -> Optional[int]: parser = ArgumentParser(prog="hello", description="Hello World") parser.add_argument("args", nargs="*", help="arguments") try: args = parser.parse_args(cmd.argv[1:]) except SystemExit: return None cmd.println("Hello, world! Script arguments are:") cmd.println("") for argi, arg in enumerate(args.args): cmd.println(f"\targv[{argi}] = " + arg) cmd.println("") stdin_len = 0 if cmd.stdin is None else len(cmd.stdin) cmd.println(f"Lines in script's stdin: {stdin_len}.") cmd.println("") jiffies = cmd.ctx.prog["jiffies"].value_() cmd.println(f"vmcore jiffies: 0x{jiffies:x}") return 0 07070100000031000041ED0000000000000000000000026573163100000000000000000000000000000000000000000000003100000000crush-2023.0.dev1702041137+8ae4b21/crush/helpers07070100000032000081A400000000000000000000000165731631000019B1000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/helpers/common.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from typing import List, Optional, Union from drgn import FaultError, Object from drgn.helpers.linux.cpumask import for_each_possible_cpu from drgn.helpers.linux.list import list_for_each_entry from drgn.helpers.linux.percpu import per_cpu, per_cpu_ptr from drgn.helpers.linux.slab import find_containing_slab_cache, slab_object_info from crush.context import Context from crush.helpers.module import MOD_TEXT class Address: """ Represents a virtual address, possibly with per-CPU indications. Attributes ---------- cpu: Optional[int] per-CPU index percpu: Optional[int] per-CPU offset addr: int full virtual address Methods ------- is_percpu(): checks if the address has per-CPU indicators get_cpu(): returns a per-CPU index get_addr(): returns full virtual address """ def __init__(self, cpu: Optional[int], percpu: Optional[int], addr: int): self.cpu = cpu self.percpu = percpu self.addr = addr def is_percpu(self) -> bool: return self.percpu is not None def get_cpu(self) -> Optional[int]: return self.cpu def get_addr(self) -> int: return self.addr def bin2ascii(raw: bytes) -> str: # TODO: raw.decode("ascii", errors = "replace") # but I'd like to have "." (dot) as a replacement marker val = [] for i in raw: # although space (32) is printable # skip it to make it explicitly visible if 33 <= i <= 126: val.append(chr(i)) else: val.append(".") return "".join(val) def parse_cpu_range(string: str) -> List[int]: val = [] if string == "a": for cpu in for_each_possible_cpu(): val.append(cpu) else: for chunk in string.split(","): if "-" in chunk: left, right = chunk.split("-") left_x, left_y = int(left), int(right) val.extend(range(left_x, left_y + 1)) else: left_x = int(chunk) val.append(left_x) for cpu in val: if cpu not in for_each_possible_cpu(): raise ValueError(f"CPU {cpu} is not available") return val def try_int(string: Optional[str], base=16) -> Optional[int]: if string is None: return None try: val = int(string, base) return val except ValueError: return None def resolve(ctx: Context, string: str) -> List[Address]: addrs = [] if ":" in string: qual, cpu_str = string.split(":") cpu = parse_cpu_range(cpu_str) else: qual = string cpu = None if "+" in qual: qual, offset_str = qual.split("+") offset = int(offset_str, 16) else: offset = 0 val: Union[int, None, str] = try_int(qual) if val is None: val = qual if cpu is not None: if isinstance(val, int): obj = Object(ctx.prog, "void *", val) for i in cpu: addrs.append(Address(i, val, per_cpu_ptr(obj, i).value_())) elif isinstance(val, str): obj = ctx.prog[val] for i in cpu: addrs.append(Address(i, obj.address_, per_cpu(obj, i).address_)) else: if isinstance(val, int): addrs.append(Address(None, None, val + offset)) elif isinstance(val, str): addrs.append(Address(None, None, ctx.prog.symbol(val).address + offset)) return addrs def demangle(ctx: Context, addr: int) -> Optional[str]: # TODO: on s390x NULL is apparently a valid address, but it decodes to # __decode_fail, so just filter it out; # on s390x there's _text symbol, compare the address to it? if addr == 0: return None if ctx.in_symcache(addr): return ctx.get_from_symcache(addr) try: # discard unreadable addresses ctx.prog.read_word(addr) except FaultError: ctx.put_to_symcache(addr, None) return None try: symbol = ctx.prog.symbol(addr) offset = addr - symbol.address chunk = symbol.name if offset != 0: chunk += "+" + hex(offset) ctx.put_to_symcache(addr, chunk) return chunk except (LookupError, OverflowError): pass try: kmem_cache = find_containing_slab_cache(addr) obj_info = slab_object_info(addr) except NotImplementedError: # TODO: PPC64 address translation is WIP kmem_cache = None obj_info = None if kmem_cache is not None and kmem_cache.value_() != 0: allocated = obj_info and obj_info.allocated chunk = ( ("[" if allocated else "") + kmem_cache.name.string_().decode() + ":" + hex(addr) + ("]" if allocated else "") ) ctx.put_to_symcache(addr, chunk) return chunk return None def wreg(ctx: Context, val: int, word_size: Optional[int] = None, x_prefix: bool = True) -> str: ret = "" if x_prefix: ret += "0x" if word_size is None: word_size = ctx.get_word_size() hex_width = word_size * 2 return f"{val:0{hex_width}x}" def address_to_module_name(ctx: Context, addr: int) -> Optional[str]: if ctx.in_modcache(addr): return ctx.get_from_modcache(addr) for mod in list_for_each_entry("struct module", ctx.prog["modules"].address_of_(), "list"): if contains(mod, "module_core"): module_begin = mod.module_core.value_() module_end = module_begin + mod.core_size.value_() elif contains(mod, "core_layout"): module_begin = mod.core_layout.base.value_() module_end = module_begin + mod.core_layout.size.value_() elif contains(mod, "mem"): module_begin = mod.mem[MOD_TEXT].base.value_() module_end = module_begin + mod.mem[MOD_TEXT].size.value_() else: raise NotImplementedError("`struct module` layout is not supported") if module_begin <= addr < module_end: module_name = mod.name.string_().decode() ctx.put_to_modcache(addr, module_name) return module_name ctx.put_to_modcache(addr, None) return None def contains(obj: Object, member: str) -> bool: try: _ = obj.member_(member) except (TypeError, LookupError): return False return True 07070100000033000081A40000000000000000000000016573163100000062000000000000000000000000000000000000003B00000000crush-2023.0.dev1702041137+8ae4b21/crush/helpers/module.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later MOD_TEXT = 0 MOD_INIT_TEXT = 4 07070100000034000081A40000000000000000000000016573163100001883000000000000000000000000000000000000003A00000000crush-2023.0.dev1702041137+8ae4b21/crush/helpers/sched.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from typing import List, Optional from drgn import FaultError, Object from drgn.helpers.linux.cpumask import for_each_online_cpu from drgn.helpers.linux.fs import d_path from drgn.helpers.linux.list import list_for_each_entry from drgn.helpers.linux.percpu import per_cpu, percpu_counter_sum from drgn.helpers.linux.pid import find_task, for_each_task from drgn.helpers.linux.sched import idle_task from crush.context import Context from crush.helpers.common import contains, try_int from crush.textbuffer import TextBuffer MM_FILEPAGES = 0 MM_ANONPAGES = 1 PF_KTHREAD = 0x00200000 # include/linux/sched/prio.h MAX_NICE = 19 MIN_NICE = -20 NICE_WIDTH = MAX_NICE - MIN_NICE + 1 MAX_RT_PRIO = 100 DEFAULT_PRIO = MAX_RT_PRIO + NICE_WIDTH // 2 def is_kthread(task: Object) -> bool: return task.flags & PF_KTHREAD def is_group_leader(task: Object) -> bool: return task.group_leader == task def task_handle_to_task(ctx: Context, task_handle: str) -> Optional[Object]: # filter out non-dec and non-hex input if try_int(task_handle) is None: raise ValueError(f"Unable to parse task handle: {task_handle}") # try PID pid = try_int(task_handle, base=10) if pid is not None: task = find_task(pid) if task.value_() != 0: return task # try task_struct address try: addr = try_int(task_handle) ctx.prog.read_word(addr) # TODO: on s390x this happily returns with no exception # for things like 0x3; # must find another way to filter this out return Object(ctx.prog, "struct task_struct *", addr) except FaultError: pass raise ProcessLookupError(f"Task does not exist: {task_handle}") def task_cpu(task: Object) -> int: if contains(task, "cpu"): return task.cpu.value_() elif contains(task, "wake_cpu"): return task.wake_cpu.value_() else: raise NotImplementedError("`struct task_struct` layout is not supported") def task_rtprio(task: Object) -> int: return task.rt_priority.value_() def task_niceval(task: Object) -> int: static_prio = task.static_prio.value_() return static_prio - DEFAULT_PRIO def task_header(task: Object) -> str: pid = task.pid.value_() addr = hex(task.value_()) cpu = task_cpu(task) comm = task.comm.string_().decode() task_fs = task.fs if task_fs.value_() == 0: root = "N/A" pwd = "N/A" else: root = d_path(task_fs.root).decode() pwd = d_path(task_fs.pwd).decode() return f"PID: {pid}\tTASK: {addr}\tCPU: {cpu}\tCOMMAND: {comm}\tROOT: {root}\tPWD: {pwd}" def tasks_from_stdin( ctx: Context, pids: List[str], stdin: Optional[TextBuffer], default_all: bool = False, ) -> List[Object]: tasks = [] if not pids: if default_all: for i in for_each_task(): tasks.append(i) for i in for_each_online_cpu(): tasks.append(idle_task(i)) else: tasks.append(ctx.current) else: for task in pids: if task == "-" and stdin is not None: for i in stdin: if not i == "": tasks.append(task_handle_to_task(ctx, i.strip())) else: tasks.append(task_handle_to_task(ctx, task)) return tasks def is_active(ctx: Context, task: Object) -> bool: cpu = task_cpu(task) return per_cpu(ctx.prog["runqueues"], cpu).curr == task def task_state_to_char(task: Object) -> str: EXIT_NONE = 0x0000 EXIT_DEAD = 0x0010 EXIT_ZOMBIE = 0x0020 TASK_RUNNING = 0x0000 TASK_INTERRUPTIBLE = 0x0001 TASK_UNINTERRUPTIBLE = 0x0002 TASK_PARKED = 0x0040 TASK_WAKEKILL = 0x0100 TASK_WAKING = 0x0200 TASK_NOLOAD = 0x0400 if contains(task, "state"): state = task.state.value_() elif contains(task, "__state"): state = task.__state.value_() else: raise NotImplementedError("`struct task_struct` layout is not supported") exit_state = task.exit_state.value_() # TODO: stopped, traced, dead if exit_state & EXIT_DEAD or exit_state & EXIT_ZOMBIE: return "Z" if state == TASK_RUNNING and exit_state == EXIT_NONE: return "R" if state & TASK_INTERRUPTIBLE and exit_state == EXIT_NONE: return "S" if state & TASK_NOLOAD and state & TASK_UNINTERRUPTIBLE and exit_state == EXIT_NONE: return "I" if state & TASK_UNINTERRUPTIBLE and exit_state == EXIT_NONE: return "D" if state & TASK_WAKING and exit_state == EXIT_NONE: return "W" if state & TASK_PARKED and exit_state == EXIT_NONE: return "P" if state & TASK_WAKEKILL and exit_state == EXIT_NONE: return "A" return "?" def task_policy_to_str(task: Object) -> str: match task.policy: case 0: return "OT" case 1: return "FF" case 2: return "RR" case 3: return "BA" case 4: return "IS" case 5: return "ID" case 6: return "DL" case _: return "??" def task_rss(task: Object) -> Optional[int]: # TODO: memory stats calculation differs across kernel versions # some kernels do not have split RSS accounting group_leader = task.group_leader mm_struct = group_leader.mm if mm_struct.value_() == 0: return None if contains(mm_struct.rss_stat, "count"): ret = ( mm_struct.rss_stat.count[MM_FILEPAGES].counter.value_() + mm_struct.rss_stat.count[MM_ANONPAGES].counter.value_() ) thread_list = group_leader.signal.thread_head.address_of_() for thread in list_for_each_entry("struct task_struct", thread_list, "thread_node"): ret += ( thread.rss_stat.count[MM_FILEPAGES].value_() + thread.rss_stat.count[MM_ANONPAGES].value_() ) else: ret = percpu_counter_sum(mm_struct.rss_stat[MM_FILEPAGES]) + percpu_counter_sum( mm_struct.rss_stat[MM_ANONPAGES] ) return ret 07070100000035000081A40000000000000000000000016573163100000494000000000000000000000000000000000000003900000000crush-2023.0.dev1702041137+8ae4b21/crush/helpers/time.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from crush.commands.common import Context from crush.helpers.common import contains def get_timekeeper(ctx: Context): if ctx.symbol_exists("tk_core"): timekeeper = ctx.prog["tk_core"].timekeeper elif ctx.symbol_exists("timekeeper"): timekeeper = ctx.prog["timekeeper"] else: raise NotImplementedError("Timekeeping structure is not supported") return timekeeper def get_uptime_ns(ctx: Context): timekeeper = get_timekeeper(ctx) if not contains(timekeeper, "tkr_mono"): jiffies = ctx.prog["jiffies"].value_() wrapped = jiffies & 0xFFFFFFFF00000000 if wrapped: wrapped -= 0x100000000 jiffies &= 0x00000000FFFFFFFF jiffies |= wrapped jiffies += 300 * ctx.config_hz uptime_ns = jiffies * (1_000 // ctx.config_hz) * 1_000_000 elif not contains(timekeeper.tkr_mono.base, "tv64"): uptime_ns = (timekeeper.tkr_mono.base + timekeeper.offs_boot).value_() else: uptime_ns = (timekeeper.tkr_mono.base.tv64 + timekeeper.offs_boot.tv64).value_() return uptime_ns 07070100000036000081A4000000000000000000000001657316310000043A000000000000000000000000000000000000003700000000crush-2023.0.dev1702041137+8ae4b21/crush/textbuffer.py#!/usr/bin/env python # SPDX-License-Identifier: GPL-3.0-or-later from typing import Any class TextBuffer: """ Represents a text buffer that is passed between commands as stdin and stdout. Attributes ---------- buffer: List[str] list of text lines constituting a text buffer index: int current buffer iterator index Methods ------- append(string): adds a new text line to the buffer """ def __init__(self, *inp): self.buffer = [] if len(inp) == 1: self.__init_arg1(inp) self.index = 0 def __init_arg1(self, args): self.append(args[0]) def append(self, string: Any) -> None: self.buffer.append(str(string)) def __iter__(self): return self def __next__(self): try: result = self.buffer[self.index] except IndexError as exc: self.index = 0 raise StopIteration from exc self.index += 1 return result def __len__(self) -> int: return len(self.buffer) 07070100000037000081A400000000000000000000000165731631000005EF000000000000000000000000000000000000003200000000crush-2023.0.dev1702041137+8ae4b21/pyproject.toml[build-system] requires = [ "flit" ] build-backend = "flit_core.buildapi" [project] name = "crush" version = "2023.1.alpha1" description = "A drgn-based crash-util replacement" license = { file = "LICENSE" } readme = "README.md" authors = [ { name = "Oleksandr Natalenko", email = "oleksandr@redhat.com" }, ] keywords = [ "analyse", "crash", "dragon", "drgn", "hang", "kdump", "kernel", "lockup", "panic", "vmcore" ] classifiers = [ "Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: Customer Service", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3", "Topic :: Software Development :: Debuggers", "Topic :: Software Development :: Disassemblers", "Topic :: System :: Operating System Kernels :: Linux", "Topic :: Utilities", ] dependencies = [ "asteval", "capstone", "drgn", "prettytable", "pyxdg", ] [project.urls] homepage = "https://codeberg.org/pf-kernel/crush" binary = "https://build.opensuse.org/project/show/home:post-factum:crush" [project.scripts] crush = "crush.crush:launch" [tool.mypy] ignore_missing_imports = true [tool.pylint.'MESSAGES CONTROL'] # TODO: clean up all the pylint complaints disable = "C0114,C0115,C0116,R0801,R0902,R0911,R0912,R0913,R0914,R0915,R0916,R1702,W0511,E1120" [tool.isort] profile = "black" [tool.black] line-length = 100 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!336 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor