├── .gitignore ├── CHANGELOG.rst ├── CONTRIBUTING.rst ├── LICENSE ├── README.rst ├── gdbmongo ├── .gitignore ├── __init__.py ├── abseil_printers.py ├── aligned_printer.py ├── boost_printers.py ├── bsonmisc_printer.py ├── bsonobj_printer.py ├── date_printer.py ├── decorable_printer.py ├── detect_toolchain.py ├── gdbutil.py ├── interaction.py ├── libstdcxxutil.py ├── lock_manager_printer.py ├── objectid_printer.py ├── printer_protocol.py ├── static_immortal_printer.py ├── status_printer.py ├── stdlib_printers.py ├── stdlib_printers.pyi ├── stdlib_printers_loader.py ├── stdlib_xmethods.py ├── stdlib_xmethods.pyi ├── string_data_printer.py ├── thread_name_printer.py ├── timestamp_printer.py └── uuid_printer.py ├── pyproject.toml ├── setup.cfg ├── stubs ├── gdb │ ├── __init__.pyi │ ├── _architecture.pyi │ ├── _basic.pyi │ ├── _errors.pyi │ ├── _frame.pyi │ ├── _inferior.pyi │ ├── _inferiorthread.pyi │ ├── _lazy_string.pyi │ ├── _objfile.pyi │ ├── _progspace.pyi │ ├── _symbol.pyi │ ├── _type.pyi │ ├── _value.pyi │ ├── events.pyi │ ├── printing.pyi │ └── xmethod.pyi ├── pydocstyle │ ├── __init__.pyi │ └── cli.pyi ├── pylint │ ├── __init__.pyi │ └── lint.pyi └── yapf │ └── __init__.pyi ├── tests ├── test_detect_toolchain.py ├── test_formatting.py ├── test_interaction.py ├── test_linting.py └── test_stdlib_printers.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 105 | __pypackages__/ 106 | 107 | # Celery stuff 108 | celerybeat-schedule 109 | celerybeat.pid 110 | 111 | # SageMath parsed files 112 | *.sage.py 113 | 114 | # Environments 115 | .env 116 | .venv 117 | env/ 118 | venv/ 119 | ENV/ 120 | env.bak/ 121 | venv.bak/ 122 | 123 | # Spyder project settings 124 | .spyderproject 125 | .spyproject 126 | 127 | # Rope project settings 128 | .ropeproject 129 | 130 | # mkdocs documentation 131 | /site 132 | 133 | # mypy 134 | .mypy_cache/ 135 | .dmypy.json 136 | dmypy.json 137 | 138 | # Pyre type checker 139 | .pyre/ 140 | 141 | # pytype static type analyzer 142 | .pytype/ 143 | 144 | # Cython debug symbols 145 | cython_debug/ 146 | 147 | # PyCharm 148 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 149 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 150 | # and can be added to the global gitignore or merged into this file. For a more nuclear 151 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 152 | #.idea/ 153 | -------------------------------------------------------------------------------- /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | 0.16.0 (2025-02-13) 5 | ------------------- 6 | 7 | * Support binaries built with MongoDB v5 toolchain. 8 | 9 | 0.15.2 (2025-02-02) 10 | ------------------- 11 | 12 | * Fix listing decorations of upcoming MongoDB 8.1. This includes accessing LockManager on global 13 | ServiceContext. 14 | 15 | 0.15.1 (2024-05-19) 16 | ------------------- 17 | 18 | * Fix detecting libstdc++ version for Clang sanitizer builds. 19 | * Fix listing decorations of MongoDB 8.0. This includes accessing LockManager on global 20 | ServiceContext. 21 | 22 | 0.15.0 (2024-04-29) 23 | ------------------- 24 | 25 | * Support dumping LockManager from core dump of MongoDB 8.0. 26 | * Fix mongo::StringData pretty printer and mongo::BSONObj pretty printer which consumes it. 27 | 28 | 0.14.0 (2023-09-30) 29 | ------------------- 30 | 31 | * Include OperationContext* in output for LockManager dump. 32 | 33 | 0.13.0 (2023-09-29) 34 | ------------------- 35 | 36 | * Include thread’s name and number in output for LockManager dump. 37 | * Fix detecting compiler version when cross-platform debugging. 38 | 39 | 0.12.0 (2023-09-22) 40 | ------------------- 41 | 42 | * Support displaying thread names in core dump of MongoDB 4.4, 5.0, and 6.0. 43 | 44 | 0.11.0 (2023-09-16) 45 | ------------------- 46 | 47 | * Support displaying contents of partitions within CursorManager. 48 | 49 | 0.10.0 (2023-09-03) 50 | ------------------- 51 | 52 | * Support dumping LockManager from core dump of MongoDB 7.1. 53 | 54 | 0.9.0 (2023-08-26) 55 | ------------------ 56 | 57 | * Support dumping LockManager from core dump of MongoDB 7.0. 58 | 59 | 0.8.1 (2023-03-04) 60 | ------------------ 61 | 62 | * Fix two Python exceptions from thread names logic when no program or core dump was loaded. 63 | * Fix boost::optional pretty printer for scalar types. 64 | 65 | 0.8.0 (2023-02-04) 66 | ------------------ 67 | 68 | * Always register gdbmongo pretty printers with GDB itself but continue defaulting them to off. 69 | * Support displaying thread names in core dump of MongoDB 6.2. 70 | 71 | 0.7.0 (2022-12-24) 72 | ------------------ 73 | 74 | * Support binaries built with MongoDB v4 toolchain. 75 | 76 | 0.6.0 (2022-11-18) 77 | ------------------ 78 | 79 | * Support dumping LockManager from core dump of MongoDB 6.2. 80 | * Fix resource type names in output of MongoDB 4.4.15, 5.0.10, and 6.0.0. 81 | 82 | 0.5.1 (2022-08-25) 83 | ------------------ 84 | 85 | * Fix detecting MongoDB toolchain from --install-action=hardlink executables. 86 | 87 | 0.5.0 (2022-07-31) 88 | ------------------ 89 | 90 | * Format BSON binary subtype 4 as UUID. 91 | * Include ErrorExtraInfo in output for Status and StatusWith. 92 | 93 | 0.4.0 (2022-04-09) 94 | ------------------ 95 | 96 | * Support detecting libstdc++ version in MongoDB binaries back to 4.2.0 and 4.4.0. 97 | * Support decoding BSONObjs even when they contain dates exceeding datetime.MAXYEAR (= 9999). 98 | 99 | 0.3.0 (2022-03-26) 100 | ------------------ 101 | 102 | * Include database name in dump of DatabaseShardingState ResourceMutexes. 103 | * Avoid truncating namespace strings in LockManager dump. 104 | 105 | 0.2.0 (2022-03-05) 106 | ------------------ 107 | 108 | * Support dumping LockManager from core dump of MongoDB 4.2, 4.4, and 5.0. 109 | 110 | 0.1.0 (2022-02-26) 111 | ------------------ 112 | 113 | * Initial release. 114 | * Support dumping LockManager from core dump of MongoDB 5.3. 115 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Running tests locally 6 | ===================== 7 | 8 | .. code-block:: console 9 | 10 | $ python -m pip install --upgrade tox 11 | $ tox 12 | 13 | Fixing formatting errors 14 | ------------------------ 15 | 16 | .. code-block:: console 17 | 18 | $ tox -e format 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ================== 2 | gdb-mongodb-server 3 | ================== 4 | 5 | About 6 | ===== 7 | 8 | The *gdbmongo* package contains GDB pretty printers and commands for 9 | debugging the MongoDB Server. Its primary target audience is MongoDB 10 | employees. 11 | 12 | Motivation 13 | ---------- 14 | 15 | The *gdbmongo* package is mostly born out of joy from tinkering with 16 | low-level constructs while writing GDB pretty printers. There are some 17 | explicit areas for what it aims to achieve: 18 | 19 | 1. GDB pretty printers and commands which only work against live MongoDB 20 | processes are of limited value. This is because the hang analyzer is 21 | only granted enough time in Evergreen to save a core file for each of 22 | the lingering processes. Further analysis is deferred until later by 23 | making use of these saved core files. GDB pretty printers and 24 | commands which are implemented by walking in-memory data structures 25 | and not by executing C++ code **can run against core dumps** and are 26 | therefore more widely applicable. 27 | 28 | 2. New versions of the MongoDB Server are released regularly. Each new 29 | git branch fragments the tooling for testing the server. This can 30 | cause development on older branches to feel foreign and awkward 31 | because so many new enhancements were made in the meantime. Flipping 32 | the model so there’s **a single version which attempts to work with 33 | all supported MongoDB versions** can potentially enable more things 34 | to “just work.” Another way to think about it is that the new GDB 35 | pretty printers and commands may not be getting built for new MongoDB 36 | Server functionality and instead may be getting built for a 37 | newly-recognized debugging need. 38 | 39 | Installation 40 | ============ 41 | 42 | The *gdbmongo* package must be loaded into the Python installation that 43 | the GDB process is running. In particular, launching ``gdb`` from within 44 | a Python virtual environment won’t give the GDB process access to the 45 | Python packages defined within the virtual environment. This is because 46 | ``gdb`` is dynamically linked against *libpython* and therefore always 47 | uses the site-packages of the base installation. 48 | 49 | Adding the following snippet to a .gdbinit file will cause ``gdb`` at 50 | launch time to attempt to install the *gdbmongo* package if it isn’t 51 | already installed. 52 | 53 | .. code-block:: python 54 | 55 | # In your ~/.gdbinit: 56 | python 57 | try: 58 | import gdbmongo 59 | except ImportError: 60 | import sys 61 | if sys.prefix.startswith("/opt/mongodbtoolchain/"): 62 | import subprocess 63 | subprocess.run([sys.prefix + "/bin/python3", "-m", "pip", "install", "gdbmongo"], check=True) 64 | import gdbmongo 65 | else: 66 | import warnings 67 | warnings.warn("Not attempting to install gdbmongo into non MongoDB toolchain Python") 68 | 69 | if "gdbmongo" in dir(): 70 | gdbmongo.register_printers() 71 | end 72 | 73 | If you don’t plan to use the GDB pretty printers defined in the 74 | mongodb/mongo repository then you may want to consider enabling some of 75 | the other printers defined by the *gdbmongo* package by default. 76 | 77 | .. pull-quote:: 78 | 79 | register_printers(\*, essentials=True, stdlib=False, abseil=False, boost=False, mongo_extras=False) 80 | Register the pretty printers defined by the gdbmongo package with GDB itself. 81 | 82 | The pretty printer collections other than gdbmongo-essentials are defaulted to off to avoid 83 | conflicting with the pretty printers defined in the mongodb/mongo repository. 84 | 85 | Regardless of whether you choose to enable these other pretty printers 86 | by default, each of the gdbmongo-\* pretty printer collections can still 87 | be enabled later on within GDB. For example, the gdbmongo-mongo-extras 88 | pretty printer collection can be enabled with the following command: 89 | 90 | .. code-block:: 91 | 92 | (gdb) enable pretty-printer global gdbmongo-mongo-extras 93 | 94 | *Tip*: Use ``info pretty-printer``, ``enable pretty-printer``, 95 | ``disable pretty-printer``, and ``print /r`` to inspect and toggle the 96 | state of any GDB pretty printers. 97 | 98 | Usage 99 | ===== 100 | 101 | The *gdbmongo* package is a nascent GDB extension and quite limited in 102 | what it can do right now. But, if you’re looking to dump the contents of 103 | the global ``LockManager`` in a core dump, then you can run the 104 | following commands: 105 | 106 | .. code-block:: python 107 | 108 | (gdb) python lock_mgr = gdbmongo.LockManagerPrinter.from_global() 109 | (gdb) python print(lock_mgr.val) 110 | -------------------------------------------------------------------------------- /gdbmongo/.gitignore: -------------------------------------------------------------------------------- 1 | _version.py 2 | -------------------------------------------------------------------------------- /gdbmongo/__init__.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """The gdbmongo package contains GDB pretty printers and commands for debugging the MongoDB Server. 17 | 18 | Its primary target audience is MongoDB employees. 19 | """ 20 | 21 | import typing 22 | 23 | try: 24 | import gdb 25 | except ImportError: 26 | # There is no gdb module when we're running the Python unit tests. We skip doing the imports for 27 | # the actual GDB pretty printers because they expect there to always be a gdb module defined. 28 | pass 29 | else: 30 | from gdbmongo.interaction import register_printers 31 | from gdbmongo.lock_manager_printer import LockManagerPrinter 32 | 33 | __version__: typing.Optional[str] 34 | 35 | try: 36 | from gdbmongo._version import version as __version__ 37 | except ImportError: 38 | # The package is not installed so we don't bother giving it a version number. 39 | __version__ = None 40 | -------------------------------------------------------------------------------- /gdbmongo/abseil_printers.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2018-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printers for absl:: container types.""" 17 | 18 | import typing 19 | 20 | import gdb 21 | 22 | from gdbmongo import stdlib_printers 23 | from gdbmongo.gdbutil import gdb_resolve_type 24 | from gdbmongo.printer_protocol import PrettyPrinterProtocol, SupportsDisplayHint 25 | 26 | 27 | # absl::container_internals::CommonFields isn't a type which is likely to be printed so we don't 28 | # bother registering it with GDB. 29 | # 30 | # pylint: disable-next=too-few-public-methods 31 | class _AbslRawHashSetCommonFieldsPrinter: 32 | """Pretty-printer for absl::container_internals::CommonFields.""" 33 | 34 | def __init__(self, container: gdb.Value, /) -> None: 35 | try: 36 | # The code structure for absl::lts_20230802::container_internal::raw_hash_set was 37 | # changed to have an explicit type for its non-templated members. 38 | gdb.lookup_type("absl::lts_20230802::container_internal::CommonFields") 39 | except gdb.error as err: 40 | if not err.args[0].startswith("No type named "): 41 | raise 42 | 43 | settings = container 44 | control = container["ctrl_"] 45 | size = container["size_"] 46 | slots = container["slots_"] 47 | else: 48 | try: 49 | common_fields_storage_type = gdb.lookup_type( 50 | "absl::lts_20230802::container_internal::internal_compressed_tuple::Storage" 51 | "") 52 | except gdb.error as err: 53 | if not err.args[0].startswith("No type named "): 54 | raise 55 | 56 | # Abseil uses `inline namespace lts_20230802 { ... }` for its container types. This 57 | # can inhibit GDB from resolving type names when the inline namespace appears within 58 | # a template argument. 59 | common_fields_storage_type = gdb.lookup_type( 60 | "absl::lts_20230802::container_internal::internal_compressed_tuple::Storage" 61 | "") 62 | 63 | # The Hash, Eq, or Alloc functors may not be zero-sized objects. 64 | # mongo::LogicalSessionIdHash is one such example. An explicit cast is needed to 65 | # disambiguate which `value` member variable of the CompressedTuple is to be accessed. 66 | settings = container["settings_"].cast(common_fields_storage_type)["value"] 67 | control = settings["control_"] 68 | 69 | # Sampling is disabled and so HashtablezInfoHandle{} is a zero-sized object. We can 70 | # therefore treat the entire compressed tuple as the storage for the container's size. 71 | # https://github.com/mongodb/mongo/blob/r8.0.0-rc3/src/third_party/abseil-cpp/dist/absl/container/internal/raw_hash_set.h#L1049-L1052 72 | size = settings["compressed_tuple_"]["value"] 73 | 74 | container_type = container.type.strip_typedefs() 75 | container_typename = (container_type.tag 76 | if container_type.tag is not None else container_type.name) 77 | assert container_typename is not None 78 | slot_type = gdb.lookup_type(container_typename + "::slot_type") 79 | slots = settings["slots_"].cast(slot_type.pointer()) 80 | 81 | self.capacity = int(settings["capacity_"]) 82 | self.control = control 83 | self.size = int(size) 84 | self.slots = slots 85 | 86 | 87 | # pylint: disable-next=invalid-name 88 | def AbslHashContainerIterator(settings: _AbslRawHashSetCommonFieldsPrinter, 89 | /) -> typing.Iterator[gdb.Value]: 90 | """Return a generator of every node in the given absl::container_internal::raw_hash_set or 91 | derived class. 92 | """ 93 | # We search for any in-use `slots_` among the `ctrl_` bytes and return them. 94 | # https://github.com/mongodb/mongo/blob/r7.0.0/src/third_party/abseil-cpp/dist/absl/container/internal/raw_hash_set.h#L1948-L1951 95 | # https://github.com/mongodb/mongo/blob/r7.0.0/src/third_party/abseil-cpp/dist/absl/container/internal/raw_hash_set.h#L330 96 | for i in range(settings.capacity): 97 | is_full = int(settings.control[i]) >= 0 98 | if is_full: 99 | yield settings.slots[i] 100 | 101 | 102 | # pylint: disable-next=missing-class-docstring 103 | # pylint: disable-next=too-few-public-methods 104 | class AbslPrinterProtocol(PrettyPrinterProtocol, SupportsDisplayHint, typing.Protocol): 105 | 106 | template_name: typing.ClassVar[str] 107 | type_aliases: typing.ClassVar[typing.Iterable[str]] 108 | 109 | 110 | class AbslHashSetPrinterBase(AbslPrinterProtocol): 111 | # pylint: disable=missing-function-docstring 112 | """Pretty-printer base class for absl::node_hash_set and absl::flat_hash_set.""" 113 | 114 | def __init__(self, val: gdb.Value, /) -> None: 115 | self.element_type = val.type.template_argument(0) 116 | self.settings = _AbslRawHashSetCommonFieldsPrinter(val) 117 | self.val = val 118 | 119 | gdb_resolve_type(self.element_type) 120 | 121 | @staticmethod 122 | def display_hint() -> typing.Literal["array"]: 123 | return "array" 124 | 125 | def to_string(self) -> str: 126 | return (f"{self.template_name}<{self.element_type}> with" 127 | f" {stdlib_printers.num_elements(self.settings.size)}") 128 | 129 | def children(self) -> typing.Iterator[typing.Tuple[str, gdb.Value]]: 130 | count = 0 131 | for elem in AbslHashContainerIterator(self.settings): 132 | # The first element in the tuple here is technically ignored when the value is printed 133 | # because we've configured an "array" display hint. Regardless, we use the same 134 | # convention for it as StdSetPrinter and Tr1UnorderedSetPrinter both do. 135 | yield (f"[{count}]", self._extract_element(elem)) 136 | count += 1 137 | 138 | def _extract_element(self, elem_val: gdb.Value, /) -> gdb.Value: 139 | raise NotImplementedError("AbslHashSetPrinterBase._extract_element") 140 | 141 | 142 | class AbslNodeHashSetPrinter(AbslHashSetPrinterBase): 143 | """Pretty-printer for absl::node_hash_set.""" 144 | 145 | template_name = "absl::node_hash_set" 146 | type_aliases = ("absl::lts_20210324::node_hash_set", "absl::lts_20211102::node_hash_set", 147 | "absl::lts_20230802::node_hash_set") 148 | 149 | def _extract_element(self, elem_val: gdb.Value, /) -> gdb.Value: 150 | # https://github.com/mongodb/mongo/blob/r7.0.0/src/third_party/abseil-cpp/dist/absl/container/internal/node_hash_policy.h#L75 151 | return elem_val.dereference() 152 | 153 | 154 | class AbslFlatHashSetPrinter(AbslHashSetPrinterBase): 155 | """Pretty-printer for absl::flat_hash_set.""" 156 | 157 | template_name = "absl::flat_hash_set" 158 | type_aliases = ("absl::lts_20210324::flat_hash_set", "absl::lts_20211102::flat_hash_set", 159 | "absl::lts_20230802::flat_hash_set") 160 | 161 | def _extract_element(self, elem_val: gdb.Value, /) -> gdb.Value: 162 | # https://github.com/mongodb/mongo/blob/r7.0.0/src/third_party/abseil-cpp/dist/absl/container/flat_hash_set.h#L478 163 | return elem_val 164 | 165 | 166 | class AbslHashMapPrinterBase(AbslPrinterProtocol): 167 | # pylint: disable=missing-function-docstring 168 | """Pretty-printer base class for absl::node_hash_map and absl::flat_hash_map.""" 169 | 170 | def __init__(self, val: gdb.Value, /) -> None: 171 | self.key_type = val.type.template_argument(0) 172 | self.value_type = val.type.template_argument(1) 173 | self.settings = _AbslRawHashSetCommonFieldsPrinter(val) 174 | self.val = val 175 | 176 | gdb_resolve_type(self.key_type) 177 | gdb_resolve_type(self.value_type) 178 | 179 | @staticmethod 180 | def display_hint() -> typing.Literal["map"]: 181 | return "map" 182 | 183 | def to_string(self) -> str: 184 | return (f"{self.template_name}<{self.key_type}, {self.value_type}> with" 185 | f" {stdlib_printers.num_elements(self.settings.size)}") 186 | 187 | def children(self) -> typing.Iterator[typing.Tuple[str, gdb.Value]]: 188 | for (i, (key, value)) in enumerate(self.items()): 189 | # The first elements in the tuples here are technically ignored when the value is 190 | # printed because we've configured a "map" display hint. Regardless, we use the same 191 | # convention for them as StdMapPrinter and Tr1UnorderedMapPrinter both do. 192 | yield (f"[{i}]", key) 193 | yield (f"[{i}]", value) 194 | 195 | def items(self) -> typing.Iterator[typing.Tuple[gdb.Value, gdb.Value]]: 196 | """Return a generator of key-value pairs.""" 197 | for kvp in AbslHashContainerIterator(self.settings): 198 | (key, value) = self._extract_key_value_pair(kvp) 199 | yield (key, value) 200 | 201 | def _extract_key_value_pair(self, kvp_value: gdb.Value, 202 | /) -> typing.Tuple[gdb.Value, gdb.Value]: 203 | raise NotImplementedError("AbslHashMapPrinterBase._extract_key_value_pair") 204 | 205 | 206 | class AbslNodeHashMapPrinter(AbslHashMapPrinterBase): 207 | """Pretty-printer for absl::node_hash_map.""" 208 | 209 | template_name = "absl::node_hash_map" 210 | type_aliases = ("absl::lts_20210324::node_hash_map", "absl::lts_20211102::node_hash_map", 211 | "absl::lts_20230802::node_hash_map") 212 | 213 | def _extract_key_value_pair(self, kvp_value: gdb.Value, 214 | /) -> typing.Tuple[gdb.Value, gdb.Value]: 215 | # https://github.com/mongodb/mongo/blob/r7.0.0/src/third_party/abseil-cpp/dist/absl/container/node_hash_map.h#L580 216 | return (kvp_value["first"], kvp_value["second"]) 217 | 218 | 219 | class AbslFlatHashMapPrinter(AbslHashMapPrinterBase): 220 | """Pretty-printer for absl::flat_hash_map.""" 221 | 222 | template_name = "absl::flat_hash_map" 223 | type_aliases = ("absl::lts_20210324::flat_hash_map", "absl::lts_20211102::flat_hash_map", 224 | "absl::lts_20230802::flat_hash_map") 225 | 226 | def _extract_key_value_pair(self, kvp_value: gdb.Value, 227 | /) -> typing.Tuple[gdb.Value, gdb.Value]: 228 | # https://github.com/mongodb/mongo/blob/r7.0.0/src/third_party/abseil-cpp/dist/absl/container/flat_hash_map.h#L586-L588 229 | return (kvp_value["key"], kvp_value["value"]["second"]) 230 | 231 | 232 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 233 | """Add the Abseil printers to the pretty printer collection given.""" 234 | for printer in (AbslNodeHashSetPrinter, AbslFlatHashSetPrinter, AbslNodeHashMapPrinter, 235 | AbslFlatHashMapPrinter): 236 | pretty_printer.add_printer(printer.template_name, f"^{printer.template_name}<.*>$", printer) 237 | 238 | for printer_alias in printer.type_aliases: 239 | pretty_printer.add_printer(printer_alias, f"^{printer_alias}<.*>$", printer) 240 | -------------------------------------------------------------------------------- /gdbmongo/aligned_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2023-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printer for the mongo::Aligned type.""" 17 | 18 | import gdb 19 | 20 | from gdbmongo.boost_printers import SingletonPrinterBase 21 | from gdbmongo.gdbutil import gdb_resolve_type 22 | from gdbmongo.printer_protocol import PrettyPrinterProtocol 23 | 24 | 25 | class AlignedPrinter(PrettyPrinterProtocol, SingletonPrinterBase): 26 | # pylint: disable=missing-function-docstring 27 | """Pretty-printer for mongo::Aligned.""" 28 | 29 | def __init__(self, val: gdb.Value, /) -> None: 30 | self.element_type = val.type.template_argument(0) 31 | self.val = val 32 | 33 | gdb_resolve_type(self.element_type) 34 | 35 | def to_string(self) -> str: 36 | return f"mongo::Aligned<{self.element_type}>" 37 | 38 | def value(self) -> gdb.Value: 39 | storage = self.val["_storage"]["__data"] 40 | contained_value = storage.cast(self.element_type.pointer()).dereference() 41 | return contained_value 42 | 43 | 44 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 45 | """Add the AlignedPrinter to the pretty printer collection given.""" 46 | pretty_printer.add_printer("mongo::Aligned", "^mongo::Aligned<.*>$", AlignedPrinter) 47 | -------------------------------------------------------------------------------- /gdbmongo/boost_printers.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2023-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printers for boost:: types.""" 17 | 18 | import abc 19 | import typing 20 | 21 | import gdb 22 | 23 | from gdbmongo.gdbutil import gdb_resolve_type 24 | from gdbmongo.printer_protocol import PrettyPrinterProtocol, SupportsChildren, SupportsDisplayHint 25 | 26 | 27 | class SingletonPrinterBase(SupportsChildren, SupportsDisplayHint): 28 | # pylint: disable=missing-function-docstring 29 | """Class to define conventions for displaying a container of a single value.""" 30 | 31 | @staticmethod 32 | def display_hint() -> typing.Literal["array"]: 33 | return "array" 34 | 35 | def children(self) -> typing.Iterator[typing.Tuple[str, gdb.Value]]: 36 | # Ideally we would have returned `contained_value` in the to_string() method and skipped 37 | # defining a children() method at all. But that approach causes GDB to not display the 38 | # addresses for Xmethods like get() on std::unique_ptr and std::shared_ptr types for any 39 | # members within `contained_value`. We display the contained value as if it was an array of 40 | # size 1 to keep the GDB output more compact as a compromise. 41 | contained_value = self.value() 42 | yield ("", contained_value) 43 | 44 | @abc.abstractmethod 45 | def value(self) -> gdb.Value: 46 | """Return the contained value.""" 47 | raise NotImplementedError 48 | 49 | 50 | class BoostOptionalPrinter(PrettyPrinterProtocol, SingletonPrinterBase): 51 | # pylint: disable=missing-function-docstring 52 | """Pretty-printer for boost::optional.""" 53 | 54 | def __init__(self, val: gdb.Value, /) -> None: 55 | self.element_type = val.type.template_argument(0) 56 | self.is_initialized = bool(val["m_initialized"]) 57 | self.val = val 58 | 59 | gdb_resolve_type(self.element_type) 60 | 61 | def to_string(self) -> str: 62 | if self.is_initialized: 63 | return f"boost::optional<{self.element_type}>" 64 | 65 | return "boost::none" 66 | 67 | def children(self) -> typing.Iterator[typing.Tuple[str, gdb.Value]]: 68 | if self.is_initialized: 69 | yield from SingletonPrinterBase.children(self) 70 | 71 | def value(self) -> gdb.Value: 72 | if not self.is_initialized: 73 | raise ValueError("Cannot extract value from boost::none") 74 | 75 | storage = self.val["m_storage"] 76 | # boost::optional is either stored using boost::optional_detail::aligned_storage or 77 | # using direct storage of `T`. Scalar types are able to take advantage of direct storage. 78 | # 79 | # https://www.boost.org/doc/libs/1_79_0/libs/optional/doc/html/boost_optional/tutorial/performance_considerations.html 80 | if storage.type.strip_typedefs().code == gdb.TYPE_CODE_STRUCT: 81 | storage = storage["dummy_"]["data"] 82 | contained_value = storage.cast(self.element_type.pointer()).dereference() 83 | else: 84 | contained_value = storage 85 | 86 | return contained_value 87 | 88 | 89 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 90 | """Add the Boost printers to the pretty printer collection given.""" 91 | pretty_printer.add_printer("boost::optional", "^boost::optional<.*>$", BoostOptionalPrinter) 92 | -------------------------------------------------------------------------------- /gdbmongo/bsonmisc_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printers for BSON-related utility classes received by mongo::BSONObjBuilder for appending 17 | specific data types. These utility classes realistically won't appear as variables or members in 18 | other C++ classes but are leveraged as gdb.Types which gdbmongo.bsonobj_printer.BSONObjPrinter can 19 | represent those data types as. 20 | """ 21 | 22 | import ctypes 23 | import dataclasses 24 | import struct 25 | 26 | import gdb 27 | 28 | from gdbmongo.objectid_printer import MongoOID 29 | from gdbmongo.printer_protocol import SupportsToString 30 | from gdbmongo.string_data_printer import MongoStringData 31 | 32 | 33 | # pylint: disable-next=invalid-name 34 | # pylint: disable-next=too-few-public-methods 35 | class c_int32(ctypes.c_int32): 36 | """Wrapper class for ctypes.c_int32 to avoid implicit conversion to int.""" 37 | 38 | 39 | # pylint: disable-next=invalid-name 40 | # pylint: disable-next=too-few-public-methods 41 | class c_void_p(ctypes.c_void_p): 42 | """Wrapper class for ctypes.c_void_p to avoid implicit conversion to int.""" 43 | 44 | 45 | @dataclasses.dataclass 46 | class MongoBSONBinData(ctypes.Structure): 47 | """Structure with a memory layout compatible with that of mongo::BSONBinData. 48 | 49 | This class is useful for constructing gdb.Value objects of type mongo::BSONBinData out of 50 | selected portions of a buffer read with gdb.Inferior.read_memory(). 51 | 52 | .. code-block:: python 53 | 54 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 55 | binary_data = MongoBSONBinData.unpack_from(self.val["_objdata"], view=objdata) 56 | yield (f"{i}", binary_data.to_value()) 57 | """ 58 | 59 | data: c_void_p 60 | length: c_int32 61 | type: c_int32 62 | 63 | @classmethod 64 | def unpack_from(cls, val: gdb.Value, /, *, view: memoryview) -> "MongoBSONBinData": 65 | """Read a length-prefixed blob of binary data starting from the beginning of the given 66 | buffer. 67 | """ 68 | fmt = " gdb.Value: 73 | """Convert the structure to a gdb.Value of type mongo::BSONBinData.""" 74 | typ = gdb.lookup_type("mongo::BSONBinData") 75 | return gdb.Value(memoryview(self), typ) 76 | 77 | 78 | setattr(MongoBSONBinData, "_fields_", 79 | [(field.name, field.type) for field in dataclasses.fields(MongoBSONBinData)]) 80 | 81 | 82 | @dataclasses.dataclass 83 | class MongoBSONCode(ctypes.Structure): 84 | """Structure with a memory layout compatible with that of mongo::BSONCode. 85 | 86 | This class is useful for constructing gdb.Value objects of type mongo::BSONCode out of selected 87 | portions of a buffer read with gdb.Inferior.read_memory(). 88 | 89 | .. code-block:: python 90 | 91 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 92 | javascript = MongoBSONCode.unpack_from(self.val["_objdata"], view=objdata) 93 | yield (f"{i}", javascript.to_value()) 94 | """ 95 | 96 | code: MongoStringData 97 | 98 | @classmethod 99 | def unpack_from(cls, val: gdb.Value, /, *, view: memoryview) -> "MongoBSONCode": 100 | """Read a length-prefixed string from the beginning of the given buffer.""" 101 | code = MongoStringData.from_pascalstring(val, view=view) 102 | return cls(code=code) 103 | 104 | def to_value(self) -> gdb.Value: 105 | """Convert the structure to a gdb.Value of type mongo::BSONCode.""" 106 | typ = gdb.lookup_type("mongo::BSONCode") 107 | return gdb.Value(memoryview(self), typ) 108 | 109 | 110 | setattr(MongoBSONCode, "_fields_", 111 | [(field.name, field.type) for field in dataclasses.fields(MongoBSONCode)]) 112 | 113 | 114 | @dataclasses.dataclass 115 | class MongoBSONDBRef(ctypes.Structure): 116 | """Structure with a memory layout compatible with that of mongo::BSONDBRef. 117 | 118 | This class is useful for constructing gdb.Value objects of type mongo::BSONDBRef out of selected 119 | portions of a buffer read with gdb.Inferior.read_memory(). 120 | 121 | .. code-block:: python 122 | 123 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 124 | db_pointer = MongoBSONDBRef.unpack_from(self.val["_objdata"], view=objdata) 125 | yield (f"{i}", db_pointer.to_value()) 126 | """ 127 | 128 | namespace: MongoStringData 129 | oid: MongoOID 130 | 131 | @classmethod 132 | def unpack_from(cls, val: gdb.Value, /, *, view: memoryview) -> "MongoBSONDBRef": 133 | """Read a length-prefixed string and a 12-byte ObjectId starting from the beginning of the 134 | given buffer. 135 | """ 136 | namespace = MongoStringData.from_pascalstring(val, view=view) 137 | offset = namespace.size.value + 4 138 | object_id = MongoOID.unpack_from(view[offset:]) 139 | return cls(namespace=namespace, oid=object_id) 140 | 141 | def to_value(self) -> gdb.Value: 142 | """Convert the structure to a gdb.Value of type mongo::BSONDBRef.""" 143 | typ = gdb.lookup_type("mongo::BSONDBRef") 144 | return gdb.Value(memoryview(self), typ) 145 | 146 | 147 | setattr(MongoBSONDBRef, "_fields_", 148 | [(field.name, field.type) for field in dataclasses.fields(MongoBSONDBRef)]) 149 | 150 | 151 | @dataclasses.dataclass 152 | class MongoBSONRegEx(ctypes.Structure): 153 | """Structure with a memory layout compatible with that of mongo::BSONRegEx. 154 | 155 | This class is useful for constructing gdb.Value objects of type mongo::BSONRegEx out of selected 156 | portions of a buffer read with gdb.Inferior.read_memory(). 157 | 158 | .. code-block:: python 159 | 160 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 161 | regexp = MongoBSONRegEx.unpack_from(self.val["_objdata"], view=objdata) 162 | yield (f"{i}", regexp.to_value()) 163 | """ 164 | 165 | pattern: MongoStringData 166 | flags: MongoStringData 167 | 168 | @classmethod 169 | def unpack_from(cls, val: gdb.Value, /, *, view: memoryview) -> "MongoBSONRegEx": 170 | """Read two null-terminated strings starting from the beginning of the given buffer.""" 171 | pattern = MongoStringData.from_cstring(val, maxsize=len(view)) 172 | offset = pattern.size.value + 1 173 | flags = MongoStringData.from_cstring(val + offset, maxsize=len(view) - offset) 174 | return cls(pattern=pattern, flags=flags) 175 | 176 | def to_value(self) -> gdb.Value: 177 | """Convert the structure to a gdb.Value of type mongo::BSONRegEx.""" 178 | typ = gdb.lookup_type("mongo::BSONRegEx") 179 | return gdb.Value(memoryview(self), typ) 180 | 181 | 182 | setattr(MongoBSONRegEx, "_fields_", 183 | [(field.name, field.type) for field in dataclasses.fields(MongoBSONRegEx)]) 184 | 185 | 186 | @dataclasses.dataclass 187 | class MongoBSONSymbol(ctypes.Structure): 188 | """Structure with a memory layout compatible with that of mongo::BSONSymbol. 189 | 190 | This class is useful for constructing gdb.Value objects of type mongo::BSONSymbol out of 191 | selected portions of a buffer read with gdb.Inferior.read_memory(). 192 | 193 | .. code-block:: python 194 | 195 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 196 | symbol = MongoBSONSymbol.unpack_from(self.val["_objdata"], view=objdata) 197 | yield (f"{i}", symbol.to_value()) 198 | """ 199 | 200 | symbol: MongoStringData 201 | 202 | @classmethod 203 | def unpack_from(cls, val: gdb.Value, /, *, view: memoryview) -> "MongoBSONSymbol": 204 | """Read a length-prefixed string from the beginning of the given buffer.""" 205 | symbol = MongoStringData.from_pascalstring(val, view=view) 206 | return cls(symbol=symbol) 207 | 208 | def to_value(self) -> gdb.Value: 209 | """Convert the structure to a gdb.Value of type mongo::BSONSymbol.""" 210 | typ = gdb.lookup_type("mongo::BSONSymbol") 211 | return gdb.Value(memoryview(self), typ) 212 | 213 | 214 | setattr(MongoBSONSymbol, "_fields_", 215 | [(field.name, field.type) for field in dataclasses.fields(MongoBSONSymbol)]) 216 | 217 | 218 | # pylint: disable-next=too-few-public-methods 219 | class UndefinedLabelerPrinter(SupportsToString): 220 | # pylint: disable=missing-function-docstring 221 | """Pretty-printer for literal undefined value.""" 222 | 223 | def __init__(self, val: gdb.Value, /) -> None: 224 | self.val = val 225 | 226 | def to_string(self) -> str: 227 | return "undefined" 228 | 229 | 230 | # pylint: disable-next=too-few-public-methods 231 | class NullLabelerPrinter(SupportsToString): 232 | # pylint: disable=missing-function-docstring 233 | """Pretty-printer for literal null value.""" 234 | 235 | def __init__(self, val: gdb.Value, /) -> None: 236 | self.val = val 237 | 238 | def to_string(self) -> str: 239 | return "null" 240 | 241 | 242 | # pylint: disable-next=too-few-public-methods 243 | class MinKeyLabelerPrinter(SupportsToString): 244 | # pylint: disable=missing-function-docstring 245 | """Pretty-printer for literal MinKey value.""" 246 | 247 | def __init__(self, val: gdb.Value, /) -> None: 248 | self.val = val 249 | 250 | def to_string(self) -> str: 251 | return "MinKey()" 252 | 253 | 254 | # pylint: disable-next=too-few-public-methods 255 | class MaxKeyLabelerPrinter(SupportsToString): 256 | # pylint: disable=missing-function-docstring 257 | """Pretty-printer for literal MaxKey value.""" 258 | 259 | def __init__(self, val: gdb.Value, /) -> None: 260 | self.val = val 261 | 262 | def to_string(self) -> str: 263 | return "MaxKey()" 264 | 265 | 266 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 267 | """Add the BSON-related printers to the pretty printer collection given.""" 268 | pretty_printer.add_printer("mongo::MaxKeyLabeler", "^mongo::MaxKeyLabeler$", 269 | MaxKeyLabelerPrinter) 270 | pretty_printer.add_printer("mongo::MinKeyLabeler", "^mongo::MinKeyLabeler$", 271 | MinKeyLabelerPrinter) 272 | pretty_printer.add_printer("mongo::NullLabeler", "^mongo::NullLabeler$", NullLabelerPrinter) 273 | pretty_printer.add_printer("mongo::UndefinedLabeler", "^mongo::UndefinedLabeler$", 274 | UndefinedLabelerPrinter) 275 | -------------------------------------------------------------------------------- /gdbmongo/date_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printer for the mongo::Date_t type.""" 17 | 18 | import ctypes 19 | import datetime 20 | import dataclasses 21 | import struct 22 | import typing 23 | 24 | import gdb 25 | 26 | from gdbmongo.printer_protocol import PrettyPrinterProtocol 27 | 28 | 29 | # pylint: disable-next=invalid-name 30 | # pylint: disable-next=too-few-public-methods 31 | class c_int64(ctypes.c_int64): 32 | """Wrapper class for ctypes.c_int64 to avoid implicit conversion to int.""" 33 | 34 | 35 | @dataclasses.dataclass 36 | class MongoDateT(ctypes.Structure): 37 | """Structure with a memory layout compatible with that of mongo::Date_t. 38 | 39 | This class is useful for constructing gdb.Value objects of type mongo::Date_t out of selected 40 | portions of a buffer read with gdb.Inferior.read_memory(). These synthetic gdb.Values can then 41 | be formatted by DatePrinter like normal. 42 | 43 | .. code-block:: python 44 | 45 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 46 | date_t = MongoDateT.unpack_from(objdata) 47 | yield (f"{i}", date_t.to_value()) 48 | """ 49 | 50 | millis: c_int64 51 | 52 | @classmethod 53 | def unpack_from(cls, buffer: memoryview, /) -> "MongoDateT": 54 | """Read an 8-byte date starting from the beginning of the given buffer.""" 55 | fmt = " gdb.Value: 60 | """Convert the structure to a gdb.Value of type mongo::Date_t.""" 61 | typ = gdb.lookup_type("mongo::Date_t") 62 | return gdb.Value(memoryview(self), typ) 63 | 64 | 65 | setattr(MongoDateT, "_fields_", 66 | [(field.name, field.type) for field in dataclasses.fields(MongoDateT)]) 67 | 68 | 69 | class DatePrinter(PrettyPrinterProtocol): 70 | # pylint: disable=missing-function-docstring 71 | """Pretty-printer for mongo::Date_t.""" 72 | 73 | def __init__(self, val: gdb.Value, /) -> None: 74 | self.val = val 75 | self.millis = int(val["millis"]) 76 | self.formattable = (0 <= self.millis < 32535215999000) # "3000-12-31T23:59:59Z" 77 | 78 | def to_string(self) -> typing.Optional[str]: 79 | if not self.formattable: 80 | return None 81 | 82 | (seconds, millis) = divmod(self.millis, 1000) 83 | date_t = datetime.datetime.fromtimestamp( 84 | seconds, tz=datetime.timezone.utc).replace(microsecond=millis * 1000) 85 | 86 | return date_t.isoformat(timespec="milliseconds") 87 | 88 | def children(self) -> typing.Iterator[typing.Tuple[str, gdb.Value]]: 89 | if self.formattable: 90 | return 91 | 92 | yield ("millis", gdb.Value(self.millis)) 93 | 94 | 95 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 96 | """Add the DatePrinter to the pretty printer collection given.""" 97 | pretty_printer.add_printer("mongo::Date_t", "^mongo::Date_t$", DatePrinter) 98 | -------------------------------------------------------------------------------- /gdbmongo/detect_toolchain.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Detect info about the MongoDB toolchain used to compile an executable.""" 17 | 18 | import os 19 | import pathlib 20 | import re 21 | import shlex 22 | import shutil 23 | import subprocess 24 | import tempfile 25 | import typing 26 | import warnings 27 | 28 | 29 | class ToolchainInfo(typing.NamedTuple): 30 | """Info about the MongoDB toolchain used to compile an executable.""" 31 | 32 | compiler: typing.Optional[str] 33 | libstdcxx_python_home: typing.Optional[pathlib.Path] 34 | 35 | 36 | StrOrBytesPath = typing.Union[str, bytes, os.PathLike] 37 | 38 | 39 | class ToolchainVersionDetector: 40 | """Detect info about the MongoDB toolchain used to compile an executable.""" 41 | 42 | gcc_version_regexp = re.compile(rb"(?:^|\x00)(GCC: \(GNU\) \d+\.\d+\.\d+)(?:\x00|$)") 43 | clang_version_regexp = re.compile(rb"(?:^|\x00)(MongoDB clang version \d+\.\d+\.\d+)") 44 | 45 | libstdcxx_python_home_v3 = pathlib.Path("/opt/mongodbtoolchain/v3/share/gcc-8.5.0/python") 46 | libstdcxx_python_home_v4 = pathlib.Path("/opt/mongodbtoolchain/v4/share/gcc-11.3.0/python") 47 | libstdcxx_python_home_v5 = pathlib.Path("/opt/mongodbtoolchain/v5/share/gcc-14.2.0/python") 48 | 49 | def __init__(self, executable: StrOrBytesPath, /): 50 | """Initialize the ToolchainVersionDetector with the pathname of an executable.""" 51 | self.executable = executable 52 | 53 | @classmethod 54 | def locate_objcopy(cls) -> typing.Optional[str]: 55 | """Return the location of an objcopy executable from the MongoDB toolchain.""" 56 | # The objcopy executable in the MongoDB v4 toolchain supports reading binaries which were 57 | # compiled for a different platform. We prefer using it for this reason. However, not all 58 | # Evergreen distros have the MongoDB v4 toolchain available and so we also allow falling 59 | # back to the MongoDB v3 toolchain. 60 | return shutil.which( 61 | "objcopy", path=os.pathsep.join( 62 | ("/opt/mongodbtoolchain/v4/bin/", "/opt/mongodbtoolchain/v3/bin/"))) 63 | 64 | @classmethod 65 | def readelf(cls, executable: StrOrBytesPath, /) -> bytes: 66 | """Return the ELF .comment section of the executable. 67 | 68 | The ELF .comment section contains information about which compiler(s) were used in building 69 | the executable. 70 | """ 71 | if (objcopy := cls.locate_objcopy()) is None: 72 | warnings.warn( 73 | "Unable to locate a known objcopy executable. Is the MongoDB toolchain installed?") 74 | return b"" 75 | 76 | with tempfile.NamedTemporaryFile() as output_file: 77 | # objcopy overwrites the input executable when only given one positional argument. 78 | # /dev/null is specified as the second positional argument to simultaneously prevent the 79 | # executable file from being overwritten and to discard the generated copy. 80 | result = subprocess.run([ 81 | objcopy, "--dump-section", f".comment={str(output_file.name)}", executable, 82 | "/dev/null" 83 | ], capture_output=True, check=False, encoding="utf-8", text=True) 84 | 85 | if result.returncode == 0: 86 | return output_file.read() 87 | 88 | warnings.warn(f"Unable to detect the compiler version in {shlex.quote(str(executable))}." 89 | f" {result.stderr}") 90 | return b"" 91 | 92 | @classmethod 93 | def parse_gcc_version(cls, raw_elf_section: bytes, /) -> typing.Optional[str]: 94 | """Extract the GCC compiler version from the ELF .comment section text. 95 | 96 | It is expected for a GCC compiler version to be listed due to the use of libstdc++ in all 97 | MongoDB binaries. 98 | """ 99 | if (match := cls.gcc_version_regexp.search(raw_elf_section)) is not None: 100 | return match.group(1).decode() 101 | 102 | return None 103 | 104 | @classmethod 105 | def parse_clang_version(cls, raw_elf_section: bytes, /) -> typing.Optional[str]: 106 | """Extract the clang compiler version from ELF .comment section text, if present.""" 107 | if (match := cls.clang_version_regexp.search(raw_elf_section)) is not None: 108 | return match.group(1).decode() 109 | 110 | return None 111 | 112 | @classmethod 113 | def parse_libstdcxx_python_home_from_gcc_version(cls, gcc_version: str, 114 | /) -> typing.Optional[pathlib.Path]: 115 | """Return the /opt/mongodbtoolchain/vN/share/gcc-X.Y.Z/python directory associated with a 116 | particular GCC compiler version. 117 | """ 118 | if gcc_version.endswith((" 8.5.0", " 8.3.0", " 8.2.0")): 119 | # The v3 toolchain was upgraded from GCC 8.2.0 to GCC 8.3.0 in BUILD-12151 and upgraded 120 | # again from GCC 8.3.0 to GCC 8.5.0 in BUILD-12619. The gcc-8.5.0/ directory is used for 121 | # binaries compiled with any of those compiler versions because we expect the machine to 122 | # be running the latest version of the MongoDB toolchain, even when it is for inspecting 123 | # older binaries. 124 | return cls.libstdcxx_python_home_v3 125 | 126 | if gcc_version.endswith((" 11.3.0", " 11.2.0")): 127 | # The v4 toolchain was upgraded from GCC 11.2.0 to GCC 11.3.0 in BUILD-14919 prior to 128 | # the official v4 toolchain rollout. The gcc-11.3.0/ directory is used for binaries 129 | # compiled with any of those compiler versions because we expect the machine to be 130 | # running the latest version of the MongoDB toolchain, even when it is for inspecting 131 | # older binaries. 132 | return cls.libstdcxx_python_home_v4 133 | 134 | if gcc_version.endswith(" 14.2.0"): 135 | return cls.libstdcxx_python_home_v5 136 | 137 | warnings.warn( 138 | "Unable to determine the location of the libstdc++ GDB pretty printers. Please file a" 139 | " GitHub issue against https://github.com/visemet/gdb-mongodb-server and mention your " 140 | f"compiler version was {gcc_version}") 141 | return None 142 | 143 | @classmethod 144 | def parse_libstdcxx_python_home_from_clang_version(cls, clang_version: str, 145 | /) -> typing.Optional[pathlib.Path]: 146 | """Return the /opt/mongodbtoolchain/vN/share/gcc-X.Y.Z/python directory associated with a 147 | particular Clang compiler version. 148 | """ 149 | if clang_version.endswith(" 7.0.1"): 150 | return cls.libstdcxx_python_home_v3 151 | 152 | if clang_version.endswith(" 12.0.1"): 153 | return cls.libstdcxx_python_home_v4 154 | 155 | if clang_version.endswith((" 19.1.7", " 19.1.0")): 156 | return cls.libstdcxx_python_home_v5 157 | 158 | warnings.warn( 159 | "Unable to determine the location of the libstdc++ GDB pretty printers. Please file a" 160 | " GitHub issue against https://github.com/visemet/gdb-mongodb-server and mention your " 161 | f"compiler version was {clang_version}") 162 | return None 163 | 164 | def detect(self) -> ToolchainInfo: 165 | """Detect info about the MongoDB toolchain used to compile an executable.""" 166 | if not (raw_elf_section := self.readelf(self.executable)): 167 | return ToolchainInfo(None, None) 168 | 169 | if (clang_version := self.parse_clang_version(raw_elf_section)) is not None: 170 | compiler = clang_version 171 | parse_libstdcxx_python_home = self.parse_libstdcxx_python_home_from_clang_version 172 | elif (gcc_version := self.parse_gcc_version(raw_elf_section)) is not None: 173 | compiler = gcc_version 174 | parse_libstdcxx_python_home = self.parse_libstdcxx_python_home_from_gcc_version 175 | else: 176 | warnings.warn( 177 | f"Unable to detect the compiler version in {shlex.quote(str(self.executable))}." 178 | " The executable doesn't appear to have been compiled with libstdc++ based on" 179 | f" its ELF .comment section: {raw_elf_section!r}") 180 | return ToolchainInfo(None, None) 181 | 182 | if (libstdcxx_python_home := parse_libstdcxx_python_home(compiler)) is None: 183 | return ToolchainInfo(None, None) 184 | 185 | return ToolchainInfo(compiler=compiler, libstdcxx_python_home=libstdcxx_python_home) 186 | -------------------------------------------------------------------------------- /gdbmongo/gdbutil.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Utility functions for gdb.Types and gdb.Values.""" 17 | 18 | import typing 19 | 20 | import gdb 21 | 22 | 23 | def gdb_lookup_value(symbol_name: str, /) -> typing.Optional[gdb.Value]: 24 | """Return the gdb.Value corresponding to the symbol name given.""" 25 | if (symbol := gdb.lookup_symbol(symbol_name)[0]) is not None: 26 | return symbol.value() 27 | 28 | return None 29 | 30 | 31 | def gdb_resolve_type(typ: gdb.Type, /) -> gdb.Type: 32 | """Look up the name of a C++ type with any typedefs, pointers, and references stripped. 33 | 34 | This function is useful in contexts where template arguments can be pointers because GDB may not 35 | load the fields of the templated entity otherwise. 36 | """ 37 | typ = typ.strip_typedefs() 38 | 39 | while typ.code in (gdb.TYPE_CODE_PTR, gdb.TYPE_CODE_REF): 40 | typ = typ.target().strip_typedefs() 41 | 42 | if typ.code == gdb.TYPE_CODE_FUNC: 43 | return typ 44 | 45 | typename = typ.tag if typ.tag is not None else typ.name 46 | assert typename is not None 47 | return gdb.lookup_type(typename) 48 | 49 | 50 | def gdb_is_libthread_db_loaded() -> bool: 51 | """Return True if the libthread_db library is initialized, and return False otherwise. 52 | 53 | Thread debugging in GDB is not available when either (a) the libthread_db library is not found 54 | or (b) when the found version is not compatible with the libpthread library. Only when thread 55 | debugging is available can GDB inspect thread-local variables, for example. 56 | """ 57 | try: 58 | gdb.execute("maintenance check libthread-db", to_string=True) 59 | return True 60 | except gdb.error as err: 61 | if err.args[0] != "No libthread_db loaded": 62 | raise 63 | 64 | return False 65 | 66 | 67 | def gdb_are_debug_symbols_loaded() -> bool: 68 | """Return False if debug symbols are not present, and return True otherwise. 69 | 70 | This function is not guaranteed to return False when debug symbols only exist for some of the 71 | program's shared libraries. Instead, this function returning False should imply to the caller 72 | that looking up symbols, types, values, etc. in GDB is unlikely to succeed and would preferably 73 | be avoided. 74 | """ 75 | try: 76 | ret = gdb.execute("info address main", to_string=True) 77 | return not ret.endswith(" in a file compiled without debugging.\n") 78 | except gdb.error as err: 79 | if not err.args[0].startswith("No symbol "): 80 | raise 81 | 82 | return False 83 | -------------------------------------------------------------------------------- /gdbmongo/interaction.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Register the pretty printers defined by the gdbmongo package with GDB itself.""" 17 | 18 | import re 19 | import typing 20 | import warnings 21 | 22 | import gdb 23 | import gdb.printing 24 | 25 | from gdbmongo import (abseil_printers, aligned_printer, boost_printers, bsonmisc_printer, 26 | bsonobj_printer, date_printer, decorable_printer, lock_manager_printer, 27 | objectid_printer, static_immortal_printer, status_printer, 28 | string_data_printer, thread_name_printer, timestamp_printer, uuid_printer) 29 | from gdbmongo.detect_toolchain import ToolchainVersionDetector 30 | from gdbmongo.gdbutil import gdb_are_debug_symbols_loaded, gdb_is_libthread_db_loaded 31 | from gdbmongo.printer_protocol import SupportsChildren, SupportsToString 32 | from gdbmongo.stdlib_printers_loader import resolve_import 33 | 34 | # gdb.current_objfile() would very likely be None at the moment gdbmongo.register_printers() is 35 | # called. There also hasn't been a need to enable or disable specific pretty printers on a 36 | # per-program basis. This is because debugging a core file isn't compatible with debugging multiple 37 | # programs in a single GDB session. We therefore make the global registration of the pretty 38 | # printers which was already happening here explicit. 39 | # 40 | # pylint: disable-next=invalid-name 41 | _register_globally = None 42 | 43 | 44 | def _import_libstdcxx_printers(executable: str, /, *, register_libstdcxx_printers: bool) -> None: 45 | """Import the version of the libstdc++ GDB pretty printers corresponding to the version of the 46 | MongoDB toolchain the executable was compiled with. Register the imported module on sys.modules 47 | and optionally register the pretty printers with GDB itself, if requested. 48 | """ 49 | detector = ToolchainVersionDetector(executable) 50 | toolchain_info = detector.detect() 51 | 52 | (module, register_module) = resolve_import(toolchain_info) 53 | register_module() 54 | 55 | if register_libstdcxx_printers: 56 | module.register_libstdcxx_printers(_register_globally) 57 | 58 | 59 | def _set_thread_names(all_threads: typing.Tuple[gdb.InferiorThread, ...], /) -> None: 60 | """Update the name of each thread as viewed by GDB based on the contents of the 61 | mongo::(anonymous namespace)::ThreadNameInfo thread-local variable. 62 | """ 63 | assert all_threads, "No threads. Is a program running? Is a core dump loaded?" 64 | 65 | if not gdb_is_libthread_db_loaded(): 66 | warnings.warn( 67 | "libthread_db library is not available. Is a core dump being debugged for a platform" 68 | " different from its host? Output from the `info threads` command will be limited.") 69 | return 70 | 71 | if not gdb_are_debug_symbols_loaded(): 72 | warnings.warn( 73 | "Debug symbols are not available. Is the executable file stripped? Unable to assign" 74 | " thread names from stored thread-local variables.") 75 | return 76 | 77 | original_thread = gdb.selected_thread() 78 | original_frame = gdb.selected_frame() 79 | 80 | try: 81 | for thread in all_threads: 82 | thread.switch() 83 | if thread_name := thread_name_printer.get_thread_name(): 84 | thread.name = thread_name 85 | finally: 86 | if original_thread.is_valid(): 87 | original_thread.switch() 88 | if original_frame.is_valid(): 89 | original_frame.select() 90 | 91 | 92 | # pylint: disable-next=too-few-public-methods 93 | class RegexpCollectionPrettyPrinter(gdb.printing.RegexpCollectionPrettyPrinter): 94 | """Pretty-printer collection which supports adding subprinters and recognizing gdb.Types based 95 | on a regular expression. It avoids constructing an instance of the subprinter when the given 96 | gdb.Value is optimized out. This enables subprinter classes to access member variables, etc. in 97 | their __init__() method without worrying about raising a gdb.error as a result. 98 | """ 99 | 100 | def __call__(self, val: gdb.Value, /) -> typing.Union[SupportsToString, SupportsChildren, None]: 101 | if val.is_optimized_out: 102 | # Attempting to pretty-print a value which is optimized out will likely result in a 103 | # Python exception so we don't even bother to try. 104 | return None 105 | 106 | return super().__call__(val) 107 | 108 | 109 | def register_printers(*, essentials: bool = True, stdlib: bool = False, abseil: bool = False, 110 | boost: bool = False, mongo_extras: bool = False) -> None: 111 | """Register the pretty printers defined by the gdbmongo package with GDB itself. 112 | 113 | The pretty printer collections other than gdbmongo-essentials are defaulted to off to avoid 114 | conflicting with the pretty printers defined in the mongodb/mongo repository. 115 | """ 116 | # pylint: disable=attribute-defined-outside-init 117 | # Maybe https://github.com/PyCQA/pylint/issues/4987 would help. 118 | pretty_printer_essentials = RegexpCollectionPrettyPrinter("gdbmongo-essentials") 119 | pretty_printer_essentials.enabled = essentials 120 | lock_manager_printer.add_printers(pretty_printer_essentials) 121 | gdb.printing.register_pretty_printer(_register_globally, pretty_printer_essentials) 122 | 123 | pretty_printer_abseil = RegexpCollectionPrettyPrinter("gdbmongo-absl") 124 | pretty_printer_abseil.enabled = abseil 125 | abseil_printers.add_printers(pretty_printer_abseil) 126 | gdb.printing.register_pretty_printer(_register_globally, pretty_printer_abseil) 127 | 128 | pretty_printer_boost = RegexpCollectionPrettyPrinter("gdbmongo-boost") 129 | pretty_printer_boost.enabled = boost 130 | boost_printers.add_printers(pretty_printer_boost) 131 | gdb.printing.register_pretty_printer(_register_globally, pretty_printer_boost) 132 | 133 | pretty_printer_mongo_extras = RegexpCollectionPrettyPrinter("gdbmongo-mongo-extras") 134 | pretty_printer_mongo_extras.enabled = mongo_extras 135 | aligned_printer.add_printers(pretty_printer_mongo_extras) 136 | bsonmisc_printer.add_printers(pretty_printer_mongo_extras) 137 | bsonobj_printer.add_printers(pretty_printer_mongo_extras) 138 | date_printer.add_printers(pretty_printer_mongo_extras) 139 | decorable_printer.add_printers(pretty_printer_mongo_extras) 140 | objectid_printer.add_printers(pretty_printer_mongo_extras) 141 | static_immortal_printer.add_printers(pretty_printer_mongo_extras) 142 | status_printer.add_printers(pretty_printer_mongo_extras) 143 | string_data_printer.add_printers(pretty_printer_mongo_extras) 144 | timestamp_printer.add_printers(pretty_printer_mongo_extras) 145 | uuid_printer.add_printers(pretty_printer_mongo_extras) 146 | gdb.printing.register_pretty_printer(_register_globally, pretty_printer_mongo_extras) 147 | 148 | def initialize_environment(executable: str, /) -> None: 149 | _import_libstdcxx_printers(executable, register_libstdcxx_printers=stdlib) 150 | 151 | if all_threads := gdb.selected_inferior().threads(): 152 | _set_thread_names(all_threads) 153 | 154 | # pylint: disable-next=dangerous-default-value 155 | def ensure_disconnected_on_attach_first_stop(cell: list[bool] = [False], /) -> None: 156 | ([was_called], cell[:]) = (cell, [True]) 157 | if not was_called: 158 | gdb.events.stop.disconnect(on_attach_first_stop) 159 | 160 | if (executable := gdb.selected_inferior().progspace.filename) is not None: 161 | initialize_environment(executable) 162 | else: 163 | 164 | def on_attach_first_stop(event: gdb.StopEvent) -> None: 165 | """Import the libstdc++ GDB pretty printers following the `attach ` command being 166 | run in GDB. 167 | """ 168 | gdb.events.stop.disconnect(on_attach_first_stop) 169 | 170 | # We only intend to handle the stop event when first attaching to a program. Signals and 171 | # breakpoints also trigger "normal stop" events but they are reported as subclasses of 172 | # gdb.StopEvent and so we return early for any derived types. 173 | # 174 | # pylint: disable-next=unidiomatic-typecheck 175 | if type(event) is not gdb.StopEvent: 176 | return 177 | 178 | if (executable := gdb.selected_inferior().progspace.filename) is None: 179 | return 180 | 181 | # Call disconnect() as soon as we have an executable file because we only want to 182 | # trigger the import once. 183 | gdb.events.before_prompt.disconnect(on_user_at_prompt) 184 | 185 | initialize_environment(executable) 186 | 187 | def on_user_at_prompt() -> None: 188 | """Import the libstdc++ GDB pretty printers after either the `attach ` or 189 | `core-file ` commands were run in GDB and control has returned to the user. 190 | """ 191 | ensure_disconnected_on_attach_first_stop() 192 | 193 | if (executable := gdb.selected_inferior().progspace.filename) is None: 194 | # The `attach` command would have filled in the filename so we only need to check if 195 | # a core dump has been loaded with the executable file also being loaded. 196 | target_info = gdb.execute("info target", to_string=True) 197 | if re.match(r"^Local core dump file:", target_info): 198 | warnings.warn( 199 | "Unable to locate the libstdc++ GDB pretty printers without an executable" 200 | " file. Try running the `file` command with the path to the executable file" 201 | " and reloading the core dump with the `core-file` command") 202 | return 203 | 204 | # Call disconnect() as soon as we have an executable file because we only want to 205 | # trigger the import once. 206 | gdb.events.before_prompt.disconnect(on_user_at_prompt) 207 | 208 | initialize_environment(executable) 209 | 210 | gdb.events.stop.connect(on_attach_first_stop) 211 | gdb.events.before_prompt.connect(on_user_at_prompt) 212 | -------------------------------------------------------------------------------- /gdbmongo/libstdcxxutil.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2025-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Utility functions for libstdc++ types.""" 17 | 18 | import gdb 19 | 20 | from gdbmongo import stdlib_xmethods 21 | 22 | 23 | def shared_ptr_get(obj: gdb.Value, /) -> gdb.Value: 24 | """Return the stored T* pointer underlying a std::shared_ptr.""" 25 | xmethod_worker = stdlib_xmethods.SharedPtrMethodsMatcher().match(obj.type, "get") 26 | return xmethod_worker(obj) 27 | 28 | 29 | def unique_ptr_get(obj: gdb.Value, /) -> gdb.Value: 30 | """Return the stored T* pointer underlying a std::unique_ptr.""" 31 | xmethod_worker = stdlib_xmethods.UniquePtrMethodsMatcher().match(obj.type, "get") 32 | 33 | # UniquePtrGetWorker.__call__(self, obj) is implemented by first calling obj.dereference() on 34 | # the supplied argument. This behavior for UniquePtrGetWorker was introduced by 35 | # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77990 and is therefore present in all versions of 36 | # the libstdc++ pretty printers for the MongoDB toolchain. We pass in `obj.address` to 37 | # UniquePtrGetWorker to cancel out the obj.dereference() call. 38 | return xmethod_worker(obj.address) 39 | 40 | 41 | def vector_size(obj: gdb.Value, /) -> gdb.Value: 42 | """Return the number of elements in a std::vector.""" 43 | xmethod_worker = stdlib_xmethods.VectorMethodsMatcher().match(obj.type, "size") 44 | return xmethod_worker(obj) 45 | -------------------------------------------------------------------------------- /gdbmongo/objectid_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printer for the mongo::OID type.""" 17 | 18 | import ctypes 19 | import dataclasses 20 | import typing 21 | 22 | import gdb 23 | 24 | from gdbmongo.printer_protocol import SupportsToString 25 | 26 | 27 | @dataclasses.dataclass 28 | class MongoOID(ctypes.Structure): 29 | """Structure with a memory layout compatible with that of mongo::OID. 30 | 31 | This class is useful for constructing gdb.Value objects of type mongo::OID out of selected 32 | portions of a buffer read with gdb.Inferior.read_memory(). These synthetic gdb.Values can then 33 | be formatted by ObjectIdPrinter like normal. 34 | 35 | .. code-block:: python 36 | 37 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 38 | object_id = MongoOID.unpack_from(objdata) 39 | yield (f"{i}", object_id.to_value()) 40 | """ 41 | 42 | if typing.TYPE_CHECKING: 43 | data: ctypes.Array[ctypes.c_char] 44 | else: 45 | data: ctypes.c_char * 12 46 | 47 | @classmethod 48 | def unpack_from(cls, buffer: memoryview, /) -> "MongoOID": 49 | """Read a 12-byte ObjectId starting from the beginning of the given buffer.""" 50 | return cls.from_buffer(buffer) 51 | 52 | def to_value(self) -> gdb.Value: 53 | """Convert the structure to a gdb.Value of type mongo::OID.""" 54 | typ = gdb.lookup_type("mongo::OID") 55 | return gdb.Value(memoryview(self), typ) 56 | 57 | 58 | setattr(MongoOID, "_fields_", [(field.name, field.type) for field in dataclasses.fields(MongoOID)]) 59 | 60 | 61 | # pylint: disable-next=too-few-public-methods 62 | class ObjectIdPrinter(SupportsToString): 63 | # pylint: disable=missing-function-docstring 64 | """Pretty-printer for mongo::OID.""" 65 | 66 | def __init__(self, val: gdb.Value, /) -> None: 67 | self.val = val 68 | self.data = val["_data"] 69 | 70 | def to_string(self) -> str: 71 | unsigned_char = gdb.lookup_type("unsigned char") 72 | data = bytearray(int(self.data[i].cast(unsigned_char)) for i in range(12)) 73 | return f'ObjectId("{data.hex()}")' 74 | 75 | 76 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 77 | """Add the ObjectIdPrinter to the pretty printer collection given.""" 78 | pretty_printer.add_printer("mongo::OID", "^mongo::OID$", ObjectIdPrinter) 79 | -------------------------------------------------------------------------------- /gdbmongo/printer_protocol.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Shim to expose the typing.Protocols defined in stubs/gdb/printing.pyi as concrete classes when 17 | being referenced inside GDB. 18 | """ 19 | 20 | import typing 21 | 22 | # pylint: disable=protected-access 23 | # pylint: disable=missing-class-docstring 24 | # pylint: disable=too-few-public-methods 25 | 26 | if typing.TYPE_CHECKING: 27 | import gdb._lazy_string 28 | import gdb.printing 29 | 30 | LazyString = gdb._lazy_string.LazyString 31 | PrettyPrinterProtocol = gdb.printing._PrettyPrinterProtocol 32 | SupportsChildren = gdb.printing._SupportsChildren 33 | SupportsDisplayHint = gdb.printing._SupportsDisplayHint 34 | SupportsToString = gdb.printing._SupportsToString 35 | else: 36 | import gdb 37 | 38 | # gdb_pymodule_addobject() isn't called for its LazyString class so we expose the type here 39 | # ourselves. This attribute won't be used to construct LazyString instances directly. Instead, 40 | # it'll be used for type checking and satisfying Mypy. 41 | LazyString = type(gdb.parse_and_eval("(char *) 0").lazy_string(length=0)) 42 | 43 | class SupportsChildren(typing.Protocol): 44 | ... 45 | 46 | class SupportsDisplayHint(typing.Protocol): 47 | ... 48 | 49 | class SupportsToString(typing.Protocol): 50 | ... 51 | 52 | class PrettyPrinterProtocol(SupportsToString, SupportsChildren, typing.Protocol): 53 | ... 54 | -------------------------------------------------------------------------------- /gdbmongo/static_immortal_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2023-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printer for the mongo::StaticImmortal type.""" 17 | 18 | import gdb 19 | 20 | from gdbmongo.boost_printers import SingletonPrinterBase 21 | from gdbmongo.gdbutil import gdb_resolve_type 22 | from gdbmongo.printer_protocol import PrettyPrinterProtocol 23 | 24 | 25 | class StaticImmortalPrinter(PrettyPrinterProtocol, SingletonPrinterBase): 26 | # pylint: disable=missing-function-docstring 27 | """Pretty-printer for mongo::StaticImmortal.""" 28 | 29 | def __init__(self, val: gdb.Value, /) -> None: 30 | self.element_type = val.type.template_argument(0) 31 | self.val = val 32 | 33 | gdb_resolve_type(self.element_type) 34 | 35 | def to_string(self) -> str: 36 | return f"mongo::StaticImmortal<{self.element_type}>" 37 | 38 | def value(self) -> gdb.Value: 39 | storage = self.val["_storage"]["__data"] 40 | contained_value = storage.cast(self.element_type.pointer()).dereference() 41 | return contained_value 42 | 43 | 44 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 45 | """Add the StaticImmortalPrinter to the pretty printer collection given.""" 46 | pretty_printer.add_printer("mongo::StaticImmortal", "^mongo::StaticImmortal<.*>$", 47 | StaticImmortalPrinter) 48 | -------------------------------------------------------------------------------- /gdbmongo/status_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printers for Status-related error types.""" 17 | 18 | import typing 19 | 20 | import gdb 21 | 22 | from gdbmongo.libstdcxxutil import shared_ptr_get 23 | from gdbmongo.printer_protocol import SupportsChildren, SupportsToString 24 | 25 | 26 | # pylint: disable-next=too-few-public-methods 27 | class ErrorExtraInfoPrinter(SupportsToString): 28 | # pylint: disable=missing-function-docstring 29 | """Pretty-printer for mongo::ErrorExtraInfo. 30 | 31 | The presence of this pretty printer suppresses the vtbl-related information GDB displays by 32 | default for base classes with virtual methods. 33 | 34 | = { 35 | _vptr.ErrorExtraInfo = 0x7ffff... 36 | }, 37 | 38 | The mongo::ErrorExtraInfo base class doesn't have any interesting data members and so the 39 | virtual table information ends up being noise for the reader. 40 | """ 41 | 42 | def __init__(self, val: gdb.Value, /) -> None: 43 | self.val = val 44 | 45 | def to_string(self) -> str: 46 | # Returning a string from to_string() is what suppresses the vtbl-related information. 47 | # Displaying the address of the ErrorExtraInfo is somewhat arbitrary but at least keeps the 48 | # GDB output more compact. 49 | return hex(int(self.val.address)) 50 | 51 | 52 | # pylint: disable-next=too-few-public-methods 53 | class ErrorInfoPrinter(SupportsChildren): 54 | # pylint: disable=missing-function-docstring 55 | """Pretty-printer for mongo::ErrorInfo.""" 56 | 57 | def __init__(self, val: gdb.Value, /) -> None: 58 | self.val = val 59 | self.code = val["code"] 60 | self.reason = val["reason"] 61 | self.extra = val["extra"] 62 | 63 | def children(self) -> typing.Iterator[typing.Tuple[str, gdb.Value]]: 64 | yield ("code", self.code) 65 | yield ("reason", self.reason) 66 | 67 | if (extra_info_ptr := shared_ptr_get(self.extra)) != 0: 68 | extra_info = extra_info_ptr.dereference() 69 | # The ErrorExtraInfo object must be cast to the derived type for GDB to actually display 70 | # its members from the derived type. 71 | yield ("extra", extra_info.cast(extra_info.dynamic_type)) 72 | 73 | 74 | # pylint: disable-next=too-few-public-methods 75 | class StatusPrinter(SupportsToString): 76 | # pylint: disable=missing-function-docstring 77 | """Pretty-printer for mongo::Status.""" 78 | 79 | def __init__(self, val: gdb.Value, /) -> None: 80 | self.val = val 81 | 82 | error = val["_error"] 83 | if error.type.code != gdb.TYPE_CODE_PTR: 84 | # The type of the `Status::_error` member was changed from ErrorInfo* to 85 | # boost::intrusive_ptr as part of SERVER-52904 in MongoDB 5.1. 86 | error = error["px"] 87 | 88 | self.error = error 89 | 90 | def to_string(self) -> typing.Union[str, gdb.Value]: 91 | if self.error == 0: 92 | return "Status::OK()" 93 | 94 | # We display the error Status directly as the ErrorInfo object. This keeps the GDB output 95 | # more compact by omitting the mention of the "_error" field. 96 | return self.error.dereference() 97 | 98 | 99 | # pylint: disable-next=too-few-public-methods 100 | class StatusWithPrinter(SupportsToString): 101 | # pylint: disable=missing-function-docstring 102 | """Pretty-printer for mongo::StatusWith.""" 103 | 104 | def __init__(self, val: gdb.Value, /) -> None: 105 | self.val = val 106 | self.status = val["_status"] 107 | self.opt_value = val["_t"] 108 | 109 | def to_string(self) -> gdb.Value: 110 | status = StatusPrinter(self.status) 111 | if status.error != 0: 112 | return self.status 113 | 114 | return self.opt_value 115 | 116 | 117 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 118 | """Add the Status-related printers to the pretty printer collection given.""" 119 | pretty_printer.add_printer("mongo::ErrorExtraInfo", "^mongo::ErrorExtraInfo$", 120 | ErrorExtraInfoPrinter) 121 | pretty_printer.add_printer("mongo::Status::ErrorInfo", "^mongo::Status::ErrorInfo$", 122 | ErrorInfoPrinter) 123 | pretty_printer.add_printer("mongo::Status", "^mongo::Status$", StatusPrinter) 124 | pretty_printer.add_printer("mongo::StatusWith", "^mongo::StatusWith<.*>$", StatusWithPrinter) 125 | -------------------------------------------------------------------------------- /gdbmongo/stdlib_printers.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Proxy for the gdb.libstdcxx.v6.printers submodule. 17 | 18 | This module exists so GDB pretty printers defined in the gdbmongo package can refer to 19 | gdbmongo.stdlib_printers.XX types without caring around which version of the MongoDB toolchain the 20 | libstdc++ GDB pretty printers were loaded from. The intended usage in GDB pretty printers resembles 21 | the following Python snippet: 22 | 23 | .. code-block:: python 24 | 25 | # The `from gdbmongo.stdlib_printers import ...` syntax cannot be used because it would attempt 26 | # to reference an attribute before the gdb.libstdcxx.v6 module has been registered in 27 | # sys.modules. 28 | import gdbmongo.stdlib_printers 29 | 30 | class MyPrinter: 31 | 32 | def __init__(self, val: gdb.Value, /) -> None: 33 | self.val = val 34 | self.pipeline = val["_pipeline"] 35 | 36 | def to_string(self) -> str: 37 | # The class is aliased here as a local variable for some brevity. 38 | StdVectorPrinter = gdbmongo.stdlib_printers.StdVectorPrinter 39 | iterator = StdVectorPrinter("std::vector", self.pipeline).children() 40 | for (index, (_, stage)) in enumerate(iterator): 41 | ... 42 | """ 43 | 44 | import importlib 45 | import types 46 | import typing 47 | 48 | import gdbmongo.stdlib_printers_loader 49 | 50 | 51 | def _resolve_printers_submodule() -> types.ModuleType: 52 | """Import the gdb.libstdcxx.v6.printers submodule.""" 53 | return importlib.import_module(".printers", package=gdbmongo.stdlib_printers_loader.MODULE_NAME) 54 | 55 | 56 | def __getattr__(name: str) -> typing.Any: 57 | return getattr(_resolve_printers_submodule(), name) 58 | 59 | 60 | def __dir__() -> typing.List[str]: 61 | return dir(_resolve_printers_submodule()) 62 | -------------------------------------------------------------------------------- /gdbmongo/stdlib_printers.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/python/libstdcxx/v6/printers.py""" 17 | 18 | import abc 19 | import typing 20 | 21 | import gdb 22 | 23 | from gdbmongo.printer_protocol import LazyString 24 | 25 | 26 | def num_elements(num: int, /) -> str: 27 | ... 28 | 29 | 30 | def function_pointer_to_name(func: gdb.Value, /) -> typing.Optional[str]: 31 | ... 32 | 33 | 34 | class __PrettyPrinterProtocol(gdb.printing._PrettyPrinterProtocol, typing.Protocol): 35 | # The typename argument isn't part of GDB's pretty printing API. The pretty printers defined in 36 | # the gdb.libstdcxx.v6.printers package aren't registered individually and instead accept a 37 | # string corresponding to the C++ type for the subprinter. 38 | def __init__(self, typename: str, val: gdb.Value, /) -> None: 39 | ... 40 | 41 | def to_string(self) -> str | gdb.Value | LazyString | None: 42 | ... 43 | 44 | def children(self) -> typing.Iterator[typing.Tuple[str, gdb.Value]]: 45 | ... 46 | 47 | 48 | class SharedPointerPrinter(__PrettyPrinterProtocol): 49 | 50 | def __init__(self, typename: typing.Literal["std::shared_ptr"], val: gdb.Value, /): 51 | ... 52 | 53 | 54 | class UniquePointerPrinter(__PrettyPrinterProtocol): 55 | 56 | def __init__(self, typename: typing.Literal["std::unique_ptr"], val: gdb.Value, /): 57 | ... 58 | 59 | 60 | class StdListPrinter(__PrettyPrinterProtocol): 61 | 62 | def __init__(self, typename: typing.Literal["std::list"], val: gdb.Value, /): 63 | ... 64 | 65 | 66 | class StdListIteratorPrinter(__PrettyPrinterProtocol): 67 | 68 | def __init__(self, typename: typing.Literal["std::list::iterator"], val: gdb.Value, /): 69 | ... 70 | 71 | 72 | class StdFwdListIteratorPrinter(__PrettyPrinterProtocol): 73 | 74 | def __init__(self, typename: typing.Literal["std::forward_list::iterator"], val: gdb.Value, /): 75 | ... 76 | 77 | 78 | class StdVectorPrinter(__PrettyPrinterProtocol): 79 | 80 | def __init__(self, typename: typing.Literal["std::vector"], val: gdb.Value, /): 81 | ... 82 | 83 | class Iterator(typing.Iterator[typing.Tuple[str, gdb.Value]], metaclass=abc.ABCMeta): 84 | ... 85 | 86 | def children(self) -> Iterator: 87 | ... 88 | 89 | 90 | class StdVectorIteratorPrinter(__PrettyPrinterProtocol): 91 | 92 | def __init__(self, typename: typing.Literal["std::vector::iterator"], val: gdb.Value, /): 93 | ... 94 | 95 | 96 | class StdTuplePrinter(__PrettyPrinterProtocol): 97 | 98 | def __init__(self, typename: typing.Literal["std::tuple"], val: gdb.Value, /): 99 | ... 100 | 101 | 102 | class StdStackOrQueuePrinter(__PrettyPrinterProtocol): 103 | 104 | def __init__(self, typename: typing.Literal["std::stack", "std::queue"], val: gdb.Value, /): 105 | ... 106 | 107 | 108 | class StdRbtreeIteratorPrinter(__PrettyPrinterProtocol): 109 | 110 | def __init__(self, typename: typing.Literal["std::map::iterator", "std::set::iterator"], 111 | val: gdb.Value, /): 112 | ... 113 | 114 | 115 | # StdDebugIteratorPrinter is only valid for --dbg=on builds. 116 | class StdDebugIteratorPrinter(__PrettyPrinterProtocol): 117 | ... 118 | 119 | 120 | class StdMapPrinter(__PrettyPrinterProtocol): 121 | 122 | def __init__(self, typename: typing.Literal["std::map"], val: gdb.Value, /): 123 | ... 124 | 125 | 126 | class StdSetPrinter(__PrettyPrinterProtocol): 127 | 128 | def __init__(self, typename: typing.Literal["std::set"], val: gdb.Value, /): 129 | ... 130 | 131 | 132 | class StdBitsetPrinter(__PrettyPrinterProtocol): 133 | 134 | def __init__(self, typename: typing.Literal["std::bitset"], val: gdb.Value, /): 135 | ... 136 | 137 | 138 | class StdDequePrinter(__PrettyPrinterProtocol): 139 | 140 | def __init__(self, typename: typing.Literal["std::deque"], val: gdb.Value, /): 141 | ... 142 | 143 | 144 | class StdDequeIteratorPrinter(__PrettyPrinterProtocol): 145 | 146 | def __init__(self, typename: typing.Literal["std::deque::iterator"], val: gdb.Value, /): 147 | ... 148 | 149 | 150 | class StdStringPrinter(__PrettyPrinterProtocol): 151 | 152 | # Intentionally not constraining `typename` to be typing.Literal["std::basic_string"] because 153 | # the argument is used by StdStringPrinter to set its `new_string` attribute based on whether 154 | # the type contains "::__cxx11::basic_string". 155 | def __init__(self, typename: str, val: gdb.Value, /): 156 | ... 157 | 158 | 159 | class Tr1UnorderedSetPrinter(__PrettyPrinterProtocol): 160 | 161 | def __init__(self, typename: typing.Literal["tr1::unordered_set"], val: gdb.Value, /): 162 | ... 163 | 164 | 165 | class Tr1UnorderedMapPrinter(__PrettyPrinterProtocol): 166 | 167 | def __init__(self, typename: typing.Literal["tr1::unordered_map"], val: gdb.Value, /): 168 | ... 169 | 170 | 171 | class StdForwardListPrinter(__PrettyPrinterProtocol): 172 | 173 | def __init__(self, typename: typing.Literal["std::forward_list"], val: gdb.Value, /): 174 | ... 175 | 176 | 177 | class StdExpAnyPrinter(__PrettyPrinterProtocol): 178 | 179 | def __init__(self, typename: typing.Literal["std::any", "std::experimental::any"], 180 | val: gdb.Value, /): 181 | ... 182 | 183 | 184 | class StdExpOptionalPrinter(__PrettyPrinterProtocol): 185 | 186 | def __init__(self, typename: typing.Literal["std::optional", "std::experimental::optional"], 187 | val: gdb.Value, /): 188 | ... 189 | 190 | 191 | class StdVariantPrinter(__PrettyPrinterProtocol): 192 | 193 | def __init__(self, typename: typing.Literal["std::variant"], val: gdb.Value, /): 194 | ... 195 | 196 | 197 | class StdNodeHandlePrinter(__PrettyPrinterProtocol): 198 | ... 199 | 200 | 201 | class StdExpStringViewPrinter(__PrettyPrinterProtocol): 202 | 203 | def __init__(self, typename: typing.Literal["std::basic_string_view", 204 | "std::experimental::basic_string_view"], 205 | val: gdb.Value, /): 206 | ... 207 | 208 | 209 | class StdExpPathPrinter(__PrettyPrinterProtocol): 210 | 211 | def __init__(self, typename: typing.Literal["std::filesystem::path", 212 | "std::experimental::filesystem::path"], 213 | val: gdb.Value, /): 214 | ... 215 | 216 | 217 | class StdPairPrinter(__PrettyPrinterProtocol): 218 | 219 | def __init__(self, typename: typing.Literal["std::pair"], val: gdb.Value, /): 220 | ... 221 | 222 | 223 | # The following classes are only present in 224 | # /opt/mongodbtoolchain/v4/share/gcc-11.2.0/python/libstdcxx/v6/printers.py. 225 | 226 | 227 | class __StdBitIteratorPrinter(__PrettyPrinterProtocol): 228 | ... 229 | 230 | 231 | class __StdBitReferencePrinter(__PrettyPrinterProtocol): 232 | ... 233 | 234 | 235 | class __StdPathPrinter(__PrettyPrinterProtocol): 236 | 237 | def __init__(self, typename: typing.Literal["std::filesystem::path"], val: gdb.Value, /): 238 | ... 239 | 240 | 241 | class __StdCmpCatPrinter(__PrettyPrinterProtocol): 242 | ... 243 | 244 | 245 | StdBitIteratorPrinter: typing.Optional[typing.Type[__StdBitIteratorPrinter]] 246 | StdBitReferencePrinter: typing.Optional[typing.Type[__StdBitReferencePrinter]] 247 | StdPathPrinter: typing.Optional[typing.Type[__StdPathPrinter]] 248 | StdCmpCatPrinter: typing.Optional[typing.Type[__StdCmpCatPrinter]] 249 | -------------------------------------------------------------------------------- /gdbmongo/stdlib_printers_loader.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Load the module containing the libstdc++ GDB pretty printers.""" 17 | 18 | import importlib.util 19 | import sys 20 | import types 21 | import typing 22 | 23 | import gdbmongo.detect_toolchain 24 | 25 | # The module name is somewhat arbitrary because it'll be hidden by accesses through 26 | # gdbmongo.stdlib_printers. But gdb.libstdcxx.v6 at least matches the documentation in 27 | # https://sourceware.org/gdb/onlinedocs/gdb/Writing-a-Pretty_002dPrinter.html. 28 | MODULE_NAME = "gdb.libstdcxx.v6" 29 | 30 | 31 | def resolve_import(toolchain_info: gdbmongo.detect_toolchain.ToolchainInfo, 32 | /) -> typing.Tuple[types.ModuleType, typing.Callable[[], None]]: 33 | """Load the module containing the libstdc++ GDB pretty printers. 34 | 35 | Returns a pair of the gdb.libstdcxx.v6 module and a 0-argument function to register the module 36 | in sys.modules so later Python import statements from it can be made. In particular, invoking 37 | the 0-argument function will NOT have registered the pretty printers with GDB itself. The caller 38 | must take care to call register_libstdcxx_printers() on the returned module object. 39 | """ 40 | if (libstdcxx_python_home := toolchain_info.libstdcxx_python_home) is None: 41 | raise ValueError("Unable to import libstdc++ GDB pretty printers") 42 | 43 | module_location = libstdcxx_python_home.joinpath("libstdcxx", "v6", "__init__.py") 44 | spec = importlib.util.spec_from_file_location(MODULE_NAME, module_location) 45 | assert spec is not None 46 | module = importlib.util.module_from_spec(spec) 47 | # Unlike in https://docs.python.org/3.9/library/importlib.html#importing-a-source-file-directly, 48 | # we aren't adding an entry to sys.modules yet. It is the caller's responsibility to do so and 49 | # therefore helps centralize all of the registration side effects. The gdb.libstdcxx.v6 package 50 | # doesn't depend on there being an entry in sys.modules when it is executed anyway. 51 | assert spec.loader is not None 52 | spec.loader.exec_module(module) 53 | 54 | def register_module() -> None: 55 | sys.modules[MODULE_NAME] = module 56 | 57 | return module, register_module 58 | -------------------------------------------------------------------------------- /gdbmongo/stdlib_xmethods.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Proxy for the gdb.libstdcxx.v6.xmethods submodule. 17 | 18 | This module exists so GDB pretty printers defined in the gdbmongo package can refer to 19 | gdbmongo.stdlib_xmethods.XX types without caring around which version of the MongoDB toolchain the 20 | libstdc++ GDB pretty printers were loaded from. The intended usage in GDB pretty printers resembles 21 | the following Python snippet: 22 | 23 | .. code-block:: python 24 | 25 | # The `from gdbmongo.stdlib_xmethods import ...` syntax cannot be used because it would attempt 26 | # to reference an attribute before the gdb.libstdcxx.v6 module has been registered in 27 | # sys.modules. 28 | import gdbmongo.stdlib_xmethods 29 | 30 | class MyPrinter: 31 | 32 | def __init__(self, val: gdb.Value, /) -> None: 33 | self.val = val 34 | self.cursor = val["_cursor"] 35 | 36 | def to_string(self) -> str: 37 | xmethod_worker = stdlib_xmethods.UniquePtrMethodsMatcher().match( 38 | self.cursor.type, "operator*") 39 | 40 | cursor = xmethod_worker(self.cursor) 41 | ... 42 | """ 43 | 44 | import importlib 45 | import types 46 | import typing 47 | 48 | import gdbmongo.stdlib_printers_loader 49 | 50 | 51 | def _resolve_xmethods_submodule() -> types.ModuleType: 52 | """Import the gdb.libstdcxx.v6.xmethods submodule.""" 53 | return importlib.import_module(".xmethods", package=gdbmongo.stdlib_printers_loader.MODULE_NAME) 54 | 55 | 56 | def __getattr__(name: str) -> typing.Any: 57 | return getattr(_resolve_xmethods_submodule(), name) 58 | 59 | 60 | def __dir__() -> typing.List[str]: 61 | return dir(_resolve_xmethods_submodule()) 62 | -------------------------------------------------------------------------------- /gdbmongo/stdlib_xmethods.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/python/libstdcxx/v6/xmethods.py""" 17 | 18 | import typing 19 | 20 | import gdb 21 | 22 | 23 | # Intentionally diverging from the true class hierarchy by not inheriting from 24 | # gdb.xmethod.XMethodWorker. However, this enables us to keep the signature for __call__ more 25 | # constrained. 26 | class ArrayWorkerBase: 27 | 28 | def __init__(self, val_type: gdb.Type, size: gdb.Value, /) -> None: 29 | ... 30 | 31 | 32 | class ArraySizeWorker(ArrayWorkerBase): 33 | 34 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 35 | ... 36 | 37 | 38 | class ArrayEmptyWorker(ArrayWorkerBase): 39 | 40 | def __call__(self, obj: gdb.Value, /) -> bool: 41 | ... 42 | 43 | 44 | class ArrayFrontWorker(ArrayWorkerBase): 45 | 46 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 47 | ... 48 | 49 | 50 | class ArrayBackWorker(ArrayWorkerBase): 51 | 52 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 53 | ... 54 | 55 | 56 | class ArrayAtWorker(ArrayWorkerBase): 57 | 58 | def __call__(self, obj: gdb.Value, index: gdb.Value, /) -> gdb.Value: 59 | ... 60 | 61 | 62 | class ArraySubscriptWorker(ArrayWorkerBase): 63 | 64 | def __call__(self, obj: gdb.Value, index: gdb.Value, /) -> gdb.Value: 65 | ... 66 | 67 | 68 | class ArrayMethodsMatcher: 69 | 70 | @typing.overload 71 | def match(self, class_type: gdb.Type, method_name: typing.Literal["size"], 72 | /) -> ArraySizeWorker: 73 | ... 74 | 75 | @typing.overload 76 | def match(self, class_type: gdb.Type, method_name: typing.Literal["empty"], 77 | /) -> ArrayEmptyWorker: 78 | ... 79 | 80 | @typing.overload 81 | def match(self, class_type: gdb.Type, method_name: typing.Literal["front"], 82 | /) -> ArrayFrontWorker: 83 | ... 84 | 85 | @typing.overload 86 | def match(self, class_type: gdb.Type, method_name: typing.Literal["back"], 87 | /) -> ArrayBackWorker: 88 | ... 89 | 90 | @typing.overload 91 | def match(self, class_type: gdb.Type, method_name: typing.Literal["at"], /) -> ArrayAtWorker: 92 | ... 93 | 94 | @typing.overload 95 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator[]"], 96 | /) -> ArraySubscriptWorker: 97 | ... 98 | 99 | 100 | # Intentionally diverging from the true class hierarchy by not inheriting from 101 | # gdb.xmethod.XMethodWorker. However, this enables us to keep the signature for __call__ more 102 | # constrained. 103 | class DequeWorkerBase: 104 | 105 | def __init__(self, val_type: gdb.Type, /) -> None: 106 | ... 107 | 108 | 109 | class DequeEmptyWorker(DequeWorkerBase): 110 | 111 | def __call__(self, obj: gdb.Value, /) -> bool: 112 | ... 113 | 114 | 115 | class DequeSizeWorker(DequeWorkerBase): 116 | 117 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 118 | ... 119 | 120 | 121 | class DequeFrontWorker(DequeWorkerBase): 122 | 123 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 124 | ... 125 | 126 | 127 | class DequeBackWorker(DequeWorkerBase): 128 | 129 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 130 | ... 131 | 132 | 133 | class DequeSubscriptWorker(DequeWorkerBase): 134 | 135 | def __call__(self, obj: gdb.Value, subscript: gdb.Value, /) -> gdb.Value: 136 | ... 137 | 138 | 139 | class DequeAtWorker(DequeWorkerBase): 140 | 141 | def __call__(self, obj: gdb.Value, index: gdb.Value, /) -> gdb.Value: 142 | ... 143 | 144 | 145 | class DequeMethodsMatcher: 146 | 147 | @typing.overload 148 | def match(self, class_type: gdb.Type, method_name: typing.Literal["empty"], 149 | /) -> DequeEmptyWorker: 150 | ... 151 | 152 | @typing.overload 153 | def match(self, class_type: gdb.Type, method_name: typing.Literal["size"], 154 | /) -> DequeSizeWorker: 155 | ... 156 | 157 | @typing.overload 158 | def match(self, class_type: gdb.Type, method_name: typing.Literal["front"], 159 | /) -> DequeFrontWorker: 160 | ... 161 | 162 | @typing.overload 163 | def match(self, class_type: gdb.Type, method_name: typing.Literal["back"], 164 | /) -> DequeBackWorker: 165 | ... 166 | 167 | @typing.overload 168 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator[]"], 169 | /) -> DequeSubscriptWorker: 170 | ... 171 | 172 | @typing.overload 173 | def match(self, class_type: gdb.Type, method_name: typing.Literal["at"], /) -> DequeAtWorker: 174 | ... 175 | 176 | 177 | # Intentionally diverging from the true class hierarchy by not inheriting from 178 | # gdb.xmethod.XMethodWorker. However, this enables us to keep the signature for __call__ more 179 | # constrained. 180 | class ForwardListWorkerBase: 181 | 182 | def __init__(self, val_type: gdb.Type, node_type: gdb.Type, /) -> None: 183 | ... 184 | 185 | 186 | class ForwardListEmptyWorker(ForwardListWorkerBase): 187 | 188 | def __call__(self, obj: gdb.Value, /) -> bool: 189 | ... 190 | 191 | 192 | class ForwardListFrontWorker(ForwardListWorkerBase): 193 | 194 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 195 | ... 196 | 197 | 198 | class ForwardListMethodsMatcher: 199 | 200 | @typing.overload 201 | def match(self, class_type: gdb.Type, method_name: typing.Literal["empty"], 202 | /) -> ForwardListEmptyWorker: 203 | ... 204 | 205 | @typing.overload 206 | def match(self, class_type: gdb.Type, method_name: typing.Literal["front"], 207 | /) -> ForwardListFrontWorker: 208 | ... 209 | 210 | 211 | # Intentionally diverging from the true class hierarchy by not inheriting from 212 | # gdb.xmethod.XMethodWorker. However, this enables us to keep the signature for __call__ more 213 | # constrained. 214 | class ListWorkerBase: 215 | 216 | def __init__(self, val_type: gdb.Type, node_type: gdb.Type, /): 217 | ... 218 | 219 | 220 | class ListEmptyWorker(ListWorkerBase): 221 | 222 | def __call__(self, obj: gdb.Value, /) -> bool: 223 | ... 224 | 225 | 226 | class ListSizeWorker(ListWorkerBase): 227 | 228 | def __call__(self, obj: gdb.Value, /) -> int: 229 | ... 230 | 231 | 232 | class ListFrontWorker(ListWorkerBase): 233 | 234 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 235 | ... 236 | 237 | 238 | class ListBackWorker(ListWorkerBase): 239 | 240 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 241 | ... 242 | 243 | 244 | class ListMethodsMatcher: 245 | 246 | @typing.overload 247 | def match(self, class_type: gdb.Type, method_name: typing.Literal["empty"], 248 | /) -> ListEmptyWorker: 249 | ... 250 | 251 | @typing.overload 252 | def match(self, class_type: gdb.Type, method_name: typing.Literal["size"], /) -> ListSizeWorker: 253 | ... 254 | 255 | @typing.overload 256 | def match(self, class_type: gdb.Type, method_name: typing.Literal["front"], 257 | /) -> ListFrontWorker: 258 | ... 259 | 260 | @typing.overload 261 | def match(self, class_type: gdb.Type, method_name: typing.Literal["back"], /) -> ListBackWorker: 262 | ... 263 | 264 | 265 | # Intentionally diverging from the true class hierarchy by not inheriting from 266 | # gdb.xmethod.XMethodWorker. However, this enables us to keep the signature for __call__ more 267 | # constrained. 268 | class VectorWorkerBase: 269 | 270 | def __init__(self, val_type: gdb.Type, /) -> None: 271 | ... 272 | 273 | 274 | class VectorEmptyWorker(VectorWorkerBase): 275 | 276 | def __call__(self, obj: gdb.Value, /) -> bool: 277 | ... 278 | 279 | 280 | class VectorSizeWorker(VectorWorkerBase): 281 | 282 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 283 | ... 284 | 285 | 286 | class VectorFrontWorker(VectorWorkerBase): 287 | 288 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 289 | ... 290 | 291 | 292 | class VectorBackWorker(VectorWorkerBase): 293 | 294 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 295 | ... 296 | 297 | 298 | class VectorAtWorker(VectorWorkerBase): 299 | 300 | def __call__(self, obj: gdb.Value, index: gdb.Value, /) -> gdb.Value: 301 | ... 302 | 303 | 304 | class VectorSubscriptWorker(VectorWorkerBase): 305 | 306 | def __call__(self, obj: gdb.Value, subscript: gdb.Value, /) -> gdb.Value: 307 | ... 308 | 309 | 310 | class VectorMethodsMatcher: 311 | 312 | @typing.overload 313 | def match(self, class_type: gdb.Type, method_name: typing.Literal["empty"], 314 | /) -> VectorEmptyWorker: 315 | ... 316 | 317 | @typing.overload 318 | def match(self, class_type: gdb.Type, method_name: typing.Literal["size"], 319 | /) -> VectorSizeWorker: 320 | ... 321 | 322 | @typing.overload 323 | def match(self, class_type: gdb.Type, method_name: typing.Literal["front"], 324 | /) -> VectorFrontWorker: 325 | ... 326 | 327 | @typing.overload 328 | def match(self, class_type: gdb.Type, method_name: typing.Literal["back"], 329 | /) -> VectorBackWorker: 330 | ... 331 | 332 | @typing.overload 333 | def match(self, class_type: gdb.Type, method_name: typing.Literal["at"], /) -> VectorAtWorker: 334 | ... 335 | 336 | @typing.overload 337 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator[]"], 338 | /) -> VectorSubscriptWorker: 339 | ... 340 | 341 | 342 | # Intentionally diverging from the true class hierarchy by not inheriting from 343 | # gdb.xmethod.XMethodWorker. However, this enables us to keep the signature for __call__ more 344 | # constrained. 345 | class AssociativeContainerWorkerBase: 346 | 347 | def __init__(self, unordered: bool, /): 348 | ... 349 | 350 | 351 | class AssociativeContainerEmptyWorker(AssociativeContainerWorkerBase): 352 | 353 | def __call__(self, obj: gdb.Value, /) -> bool: 354 | ... 355 | 356 | 357 | class AssociativeContainerSizeWorker(AssociativeContainerWorkerBase): 358 | 359 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 360 | ... 361 | 362 | 363 | class AssociativeContainerMethodsMatcher: 364 | 365 | def __init__(self, name: typing.Literal["set", "map", "multiset", "multimap", "unordered_set", 366 | "unordered_map", "unordered_multiset", 367 | "unordered_multimap"], /): 368 | ... 369 | 370 | @typing.overload 371 | def match(self, class_type: gdb.Type, method_name: typing.Literal["empty"], 372 | /) -> AssociativeContainerEmptyWorker: 373 | ... 374 | 375 | @typing.overload 376 | def match(self, class_type: gdb.Type, method_name: typing.Literal["size"], 377 | /) -> AssociativeContainerSizeWorker: 378 | ... 379 | 380 | 381 | class UniquePtrGetWorker: 382 | 383 | def __init__(self, elem_type: gdb.Type, /): 384 | ... 385 | 386 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 387 | ... 388 | 389 | 390 | class UniquePtrDerefWorker(UniquePtrGetWorker): 391 | ... 392 | 393 | 394 | # Intentionally diverging from the true class hierarchy by not inheriting from UniquePtrGetWorker. 395 | # However, this enables us to keep the signature for __call__ more constrained. 396 | class UniquePtrSubscriptWorker: 397 | 398 | def __init__(self, elem_type: gdb.Type, /): 399 | ... 400 | 401 | def __call__(self, obj: gdb.Value, index: gdb.Value, /) -> gdb.Value: 402 | ... 403 | 404 | 405 | class UniquePtrMethodsMatcher: 406 | 407 | @typing.overload 408 | def match(self, class_type: gdb.Type, method_name: typing.Literal["get"], 409 | /) -> UniquePtrGetWorker: 410 | ... 411 | 412 | @typing.overload 413 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator->"], 414 | /) -> UniquePtrGetWorker: 415 | ... 416 | 417 | @typing.overload 418 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator*"], 419 | /) -> UniquePtrDerefWorker: 420 | ... 421 | 422 | @typing.overload 423 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator[]"], 424 | /) -> UniquePtrSubscriptWorker: 425 | ... 426 | 427 | 428 | # Intentionally diverging from the true class hierarchy by not inheriting from 429 | # gdb.xmethod.XMethodWorker. However, this enables us to keep the signature for __call__ more 430 | # constrained. 431 | class SharedPtrGetWorker: 432 | 433 | def __init__(self, elem_type: gdb.Type, /): 434 | ... 435 | 436 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 437 | ... 438 | 439 | 440 | class SharedPtrDerefWorker(SharedPtrGetWorker): 441 | 442 | def __call__(self, obj: gdb.Value, /) -> gdb.Value: 443 | ... 444 | 445 | 446 | # Intentionally diverging from the true class hierarchy by not inheriting from SharedPtrGetWorker. 447 | # However, this enables us to keep the signature for __call__ more constrained. 448 | class SharedPtrSubscriptWorker: 449 | 450 | def __init__(self, elem_type: gdb.Type, /): 451 | ... 452 | 453 | def __call__(self, obj: gdb.Value, index: gdb.Value, /) -> gdb.Value: 454 | ... 455 | 456 | 457 | # Intentionally diverging from the true class hierarchy by not inheriting from 458 | # gdb.xmethod.XMethodWorker. However, this enables us to keep the signature for __call__ more 459 | # constrained. 460 | class SharedPtrUseCountWorker: 461 | 462 | def __init__(self, elem_type: gdb.Type, /): 463 | ... 464 | 465 | def __call__(self, obj: gdb.Value, /) -> int | gdb.Value: 466 | ... 467 | 468 | 469 | # Intentionally diverging from the true class hierarchy by not inheriting from 470 | # SharedPtrUseCountWorker. However, this enables us to keep the signature for __call__ more 471 | # constrained. 472 | class SharedPtrUniqueWorker: 473 | 474 | def __init__(self, elem_type: gdb.Type, /): 475 | ... 476 | 477 | def __call__(self, obj: gdb.Value, /) -> bool: 478 | ... 479 | 480 | 481 | class SharedPtrMethodsMatcher: 482 | 483 | @typing.overload 484 | def match(self, class_type: gdb.Type, method_name: typing.Literal["get"], 485 | /) -> SharedPtrGetWorker: 486 | ... 487 | 488 | @typing.overload 489 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator->"], 490 | /) -> SharedPtrGetWorker: 491 | ... 492 | 493 | @typing.overload 494 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator*"], 495 | /) -> SharedPtrDerefWorker: 496 | ... 497 | 498 | @typing.overload 499 | def match(self, class_type: gdb.Type, method_name: typing.Literal["operator[]"], 500 | /) -> SharedPtrSubscriptWorker: 501 | ... 502 | 503 | @typing.overload 504 | def match(self, class_type: gdb.Type, method_name: typing.Literal["use_count"], 505 | /) -> SharedPtrUseCountWorker: 506 | ... 507 | 508 | @typing.overload 509 | def match(self, class_type: gdb.Type, method_name: typing.Literal["unique"], 510 | /) -> SharedPtrUniqueWorker: 511 | ... 512 | -------------------------------------------------------------------------------- /gdbmongo/string_data_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printers for string-related data types.""" 17 | 18 | import abc 19 | import ctypes 20 | import dataclasses 21 | import struct 22 | import typing 23 | 24 | import gdb 25 | 26 | from gdbmongo import stdlib_printers 27 | from gdbmongo.gdbutil import gdb_lookup_value 28 | from gdbmongo.printer_protocol import LazyString, SupportsDisplayHint, SupportsToString 29 | 30 | 31 | class ValueAsPythonStringMixin(SupportsToString): 32 | # pylint: disable=missing-function-docstring 33 | """Class to add support for converting a gdb.Value into a Python string from the to_string() 34 | method of the subclass. 35 | 36 | This class is really only appropriate to use on types which represent string data. One clue can 37 | be the display_hint() method of the subclass returns "string". 38 | """ 39 | 40 | @abc.abstractmethod 41 | def to_string(self) -> typing.Union[str, gdb.Value, LazyString, None]: 42 | raise NotImplementedError 43 | 44 | def string(self) -> str: 45 | """Return the value as a Python string.""" 46 | ret = self.to_string() 47 | assert ret is not None 48 | 49 | if isinstance(ret, gdb.Value): 50 | return ret.string() 51 | if isinstance(ret, LazyString): 52 | # LazyString.value() can only be called for non-nullptr strings. 53 | return ret.value().string(length=ret.length) if ret.address != 0 else "" 54 | return ret 55 | 56 | 57 | class StdStringPrinter(SupportsDisplayHint, ValueAsPythonStringMixin): 58 | # pylint: disable=missing-function-docstring 59 | """Pretty-printer for std::string. 60 | 61 | This class wraps a gdb.libstdcxx.v6.printers.StdStringPrinter instance to support extracting the 62 | gdb.Value as a Python string. gdb.Value.__str__() returns a Python string according to how the 63 | value would be **printed** by GDB. It causes the value to be awkwardly double-quoted and 64 | possibly truncated due to the user's `set print elements` setting. This class avoids both of 65 | these issues by instead calling gdb.Value.string(). 66 | """ 67 | 68 | def __init__(self, val: gdb.Value, /) -> None: 69 | self.val = val 70 | 71 | typ = val.type.strip_typedefs() 72 | typename = typ.tag if typ.tag is not None else typ.name 73 | assert typename is not None 74 | self.printer = stdlib_printers.StdStringPrinter(typename, val) 75 | 76 | @staticmethod 77 | def display_hint() -> typing.Literal["string"]: 78 | return "string" 79 | 80 | def to_string(self) -> typing.Union[str, gdb.Value, LazyString, None]: 81 | return self.printer.to_string() 82 | 83 | 84 | # pylint: disable-next=invalid-name 85 | # pylint: disable-next=too-few-public-methods 86 | class c_char_p(ctypes.c_char_p): 87 | """Wrapper class for ctypes.c_char_p to avoid implicit conversion to bytes.""" 88 | 89 | 90 | # pylint: disable-next=invalid-name 91 | # pylint: disable-next=too-few-public-methods 92 | class c_size_t(ctypes.c_size_t): 93 | """Wrapper class for ctypes.c_size_t to avoid implicit conversion to int.""" 94 | 95 | 96 | @dataclasses.dataclass 97 | class MongoStringDataLayoutStdStringView(ctypes.Structure): 98 | """Structure with a memory layout compatible with that of mongo::StringData. 99 | 100 | It corresponds to the memory layout after mongo::StringData became a thin wrapper over 101 | std::string_view as part of SERVER-82604 in MongoDB 7.3. It is equivalent to the following 102 | C struct: 103 | 104 | .. code-block:: c 105 | 106 | struct { 107 | size_t size; 108 | char* data; 109 | }; 110 | """ 111 | 112 | size: c_size_t 113 | data: c_char_p 114 | 115 | 116 | setattr(MongoStringDataLayoutStdStringView, "_fields_", 117 | [(field.name, field.type) 118 | for field in dataclasses.fields(MongoStringDataLayoutStdStringView)]) 119 | 120 | 121 | @dataclasses.dataclass 122 | class MongoStringDataLayoutPre73(ctypes.Structure): 123 | """Structure with a memory layout compatible with that of mongo::StringData. 124 | 125 | It corresponds to the memory layout prior to mongo::StringData being made a thin wrapper over 126 | std::string_view as part of SERVER-82604 in MongoDB 7.3. It is equivalent to the following 127 | C struct: 128 | 129 | .. code-block:: c 130 | 131 | struct { 132 | char* data; 133 | size_t size; 134 | }; 135 | """ 136 | 137 | data: c_char_p 138 | size: c_size_t 139 | 140 | 141 | setattr(MongoStringDataLayoutPre73, "_fields_", 142 | [(field.name, field.type) for field in dataclasses.fields(MongoStringDataLayoutPre73)]) 143 | 144 | 145 | class MongoStringData(ctypes.Union): 146 | """Object with a memory layout compatible with that of mongo::StringData. 147 | 148 | It is implemented as a ctypes.Union to accommodate the memory layout of mongo::StringData 149 | changing between MongoDB Server versions. It is equivalent to the following C union: 150 | 151 | .. code-block:: c 152 | 153 | union { 154 | struct { 155 | size_t size; 156 | char* data; 157 | } layout_string_view; 158 | 159 | struct { 160 | char* data; 161 | size_t size; 162 | } layout_pre73; 163 | }; 164 | 165 | This class is useful for constructing gdb.Value objects of type mongo::StringData out of 166 | selected portions of a buffer read with gdb.Inferior.read_memory(). These synthetic gdb.Values 167 | can then be formatted by StringDataPrinter like normal. 168 | 169 | .. code-block:: python 170 | 171 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 172 | string_data = MongoStringData.from_pascalstring(self.val["_objdata"], view=objdata) 173 | yield (f"{i}", string_data.to_value()) 174 | """ 175 | 176 | layout_string_view: MongoStringDataLayoutStdStringView 177 | layout_pre73: MongoStringDataLayoutPre73 178 | 179 | # dataclasses.dataclass doesn't appear to be compatible with ctypes.Union. We enumerate 180 | # `MongoStringData._fields_` explicitly instead of relying on the type annotations. 181 | _fields_ = [("layout_string_view", MongoStringDataLayoutStdStringView), 182 | ("layout_pre73", MongoStringDataLayoutPre73)] 183 | 184 | def __init__(self, *, data: int, size: int) -> None: 185 | if size < 0: 186 | raise ValueError("size argument must be a non-negative integer") 187 | 188 | if StringDataPrinter.is_wrapping_std_string_view(): 189 | super().__init__(layout_string_view=MongoStringDataLayoutStdStringView( 190 | data=c_char_p(data), size=c_size_t(size))) 191 | else: 192 | super().__init__( 193 | layout_pre73=MongoStringDataLayoutPre73(data=c_char_p(data), size=c_size_t(size))) 194 | 195 | @classmethod 196 | def from_cstring(cls, val: gdb.Value, /, *, maxsize: int) -> "MongoStringData": 197 | """Read a null-terminated string starting from the beginning of the given buffer.""" 198 | start = int(val) 199 | size = maxsize 200 | 201 | if (end := gdb.selected_inferior().search_memory(start, maxsize, b"\x00")) is not None: 202 | size = end - start 203 | 204 | return cls(data=start, size=size) 205 | 206 | @classmethod 207 | def from_pascalstring(cls, val: gdb.Value, /, *, view: memoryview) -> "MongoStringData": 208 | """Read a length-prefixed string starting from the beginning of the given buffer.""" 209 | fmt = " c_char_p: 216 | """Return the pointer to the first character in the string.""" 217 | return (self.layout_string_view.data 218 | if StringDataPrinter.is_wrapping_std_string_view() else self.layout_pre73.data) 219 | 220 | @property 221 | def size(self) -> c_size_t: 222 | """Return the number of characters in the string.""" 223 | return (self.layout_string_view.size 224 | if StringDataPrinter.is_wrapping_std_string_view() else self.layout_pre73.size) 225 | 226 | def to_value(self) -> gdb.Value: 227 | """Convert the structure to a gdb.Value of type mongo::StringData.""" 228 | typ = gdb.lookup_type("mongo::StringData") 229 | return gdb.Value(memoryview(self), typ) 230 | 231 | 232 | class StringDataPrinter(SupportsDisplayHint, ValueAsPythonStringMixin): 233 | # pylint: disable=missing-function-docstring 234 | """Pretty-printer for mongo::StringData.""" 235 | 236 | def __init__(self, val: gdb.Value, /) -> None: 237 | self.val = val 238 | 239 | @staticmethod 240 | def display_hint() -> typing.Literal["string"]: 241 | return "string" 242 | 243 | def to_string(self) -> typing.Union[gdb.Value, LazyString]: 244 | if StringDataPrinter.is_wrapping_std_string_view(): 245 | return self.val["_sv"] 246 | 247 | return self.val["_data"].lazy_string(length=int(self.val["_size"])) 248 | 249 | @staticmethod 250 | def is_wrapping_std_string_view() -> bool: 251 | # The StringData class was changed to be a thin wrapper over std::string_view as part of 252 | # SERVER-82604 in MongoDB 7.3. 253 | return gdb_lookup_value("mongo::StringData::npos") is not None 254 | 255 | 256 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 257 | """Add the StringDataPrinter to the pretty printer collection given.""" 258 | pretty_printer.add_printer("mongo::StringData", "^mongo::StringData$", StringDataPrinter) 259 | -------------------------------------------------------------------------------- /gdbmongo/thread_name_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2023-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printer for the mongo::(anonymous namespace)::ThreadNameInfo type.""" 17 | 18 | import typing 19 | 20 | import gdb 21 | 22 | from gdbmongo.decorable_printer import DecorationIterator 23 | from gdbmongo.libstdcxxutil import shared_ptr_get 24 | from gdbmongo.printer_protocol import SupportsDisplayHint 25 | from gdbmongo.string_data_printer import (StdStringPrinter, StringDataPrinter, 26 | ValueAsPythonStringMixin) 27 | 28 | 29 | def get_thread_name() -> str: 30 | """Return the full name associated with the selected thread. 31 | 32 | mongo::(anonymous namespace)::ThreadNameInfo is stored a thread-local variable to record the 33 | thread's full name for use by MongoDB's logging subsystem and GDB. This data is useful in the 34 | context of GDB because thread names are otherwise limited to 16 bytes by the Linux kernel. 35 | Furthermore, core dumps do not record the thread names which were made visible to the kernel. 36 | mongo::(anonymous namespace)::ThreadNameInfo is therefore the only memory location where the 37 | thread's name is recorded in a core dump. 38 | """ 39 | try: 40 | # The ThreadNameInfo type replaced the ThreadNameSconce type for representing the storage 41 | # for the thread name as part of SERVER-63852 in MongoDB 6.1 and was then subsequently 42 | # backported to 5.0.12 and 6.0.2. In some versions the ThreadNameInfo instance is managed 43 | # directly as a thread-local variable, and in other versions it is managed as a decoration 44 | # within the ThreadContext object. 45 | thread_info_type = gdb.lookup_type("mongo::(anonymous namespace)::ThreadNameInfo") 46 | except gdb.error as err: 47 | if not err.args[0].startswith("No type named "): 48 | raise 49 | 50 | try: 51 | # The ThreadNameSconce type was introduced for representing the storage for the thread 52 | # name as part of SERVER-52821 in MongoDB 5.0. It is always managed as a decoration 53 | # within the ThreadContext object. Previously in MongoDB 4.4, the thread name was made 54 | # available through a thread-local StringData variable. 55 | thread_sconce_type = gdb.lookup_type("mongo::(anonymous namespace)::ThreadNameSconce") 56 | except gdb.error as err2: 57 | if not err2.args[0].startswith("No type named "): 58 | raise 59 | 60 | thread_name = gdb.parse_and_eval("mongo::for_debuggers::threadName") 61 | return StringDataPrinter(thread_name).string() 62 | else: 63 | return _get_thread_name_from_sconce(thread_sconce_type) 64 | 65 | try: 66 | # The `tls` thread-local variable was introduced to the ThreadNameInfo::forThisThread() 67 | # static function as part of SERVER-66385 in MongoDB 6.1. The ThreadNameInfo instance was 68 | # previously managed as a decoration within the ThreadContext object. 69 | thread_info_pp = gdb.parse_and_eval( 70 | "&'mongo::(anonymous namespace)::ThreadNameInfo::forThisThread()::tls'") 71 | except gdb.error as err: 72 | if not err.args[0].startswith("No symbol "): 73 | raise 74 | 75 | if (thread_context := _get_thread_context()) == 0: 76 | return "" 77 | 78 | for decoration in DecorationIterator(thread_context.dereference()): 79 | if decoration.type == thread_info_type: 80 | thread_info = decoration.address 81 | break 82 | else: 83 | raise ValueError( 84 | "Failed to locate ThreadNameInfo decoration in ThreadContext") from None 85 | else: 86 | # The 'mongo::(anonymous namespace)::ThreadNameInfo::forThisThread()::Tls' struct has a 87 | # trivial definition and its typeinfo can be elided. 88 | # 89 | # struct Tls { 90 | # ThreadNameInfo* info = new ThreadNameInfo; 91 | # }; 92 | # 93 | # (gdb) print 'mongo::(anonymous namespace)::ThreadNameInfo::forThisThread()::tls' 94 | # 'mongo::(anonymous namespace)::ThreadNameInfo::forThisThread()::tls' has unknown type; 95 | # cast it to its declared type 96 | # 97 | # We therefore cast what would be the Tls* to be a ThreadNameInfo** because the Tls::info 98 | # member variable is guaranteed to be stored at byte offset 0 of the struct. 99 | thread_info = thread_info_pp.cast(thread_info_type.pointer().pointer()).dereference() 100 | 101 | return _ThreadNameInfoPrinter(thread_info.dereference()).string() if thread_info != 0 else "" 102 | 103 | 104 | def _get_thread_name_from_sconce(thread_sconce_type: gdb.Type, /) -> str: 105 | """Return the thread name stored within the ThreadNameSconce instance.""" 106 | if (thread_context := _get_thread_context()) == 0: 107 | return "" 108 | 109 | for decoration in DecorationIterator(thread_context.dereference()): 110 | if decoration.type == thread_sconce_type: 111 | thread_sconce = decoration.address 112 | break 113 | else: 114 | raise ValueError("Failed to locate ThreadNameSconce decoration in ThreadContext") 115 | 116 | if (thread_name := thread_sconce["activePtr"]["px"]) == 0: 117 | thread_name = thread_sconce["cachedPtr"]["px"] 118 | 119 | return _ThreadNamePrinter(thread_name.dereference()).string() if thread_name != 0 else "" 120 | 121 | 122 | def _get_thread_context() -> gdb.Value: 123 | """Return the ThreadContext object associated with the current thread.""" 124 | thread_context_handle_p = gdb.parse_and_eval("&mongo::ThreadContext::_handle") 125 | thread_context_handle_type = gdb.lookup_type("mongo::ThreadContext::Handle") 126 | thread_context_handle_p = thread_context_handle_p.cast(thread_context_handle_type.pointer()) 127 | return thread_context_handle_p.dereference()["instance"]["px"] 128 | 129 | 130 | # mongo::(anonymous namespace)::ThreadNameInfo isn't a type which is likely to be printed so we 131 | # don't bother registering it with GDB. 132 | class _ThreadNameInfoPrinter(SupportsDisplayHint, ValueAsPythonStringMixin): 133 | # pylint: disable=missing-function-docstring 134 | """Pretty-printer for mongo::(anonymous namespace)::ThreadNameInfo.""" 135 | 136 | def __init__(self, val: gdb.Value, /) -> None: 137 | self.val = val 138 | 139 | @staticmethod 140 | def display_hint() -> typing.Literal["string"]: 141 | return "string" 142 | 143 | def to_string(self) -> str: 144 | thread_name = shared_ptr_get(self.val["_h"]["_ptr"]).dereference() 145 | return StdStringPrinter(thread_name).string() 146 | 147 | 148 | # mongo::ThreadName isn't a type which is likely to be printed so we don't bother registering it 149 | # with GDB. 150 | class _ThreadNamePrinter(SupportsDisplayHint, ValueAsPythonStringMixin): 151 | # pylint: disable=missing-function-docstring 152 | """Pretty-printer for mongo::ThreadName.""" 153 | 154 | def __init__(self, val: gdb.Value, /) -> None: 155 | self.val = val 156 | 157 | @staticmethod 158 | def display_hint() -> typing.Literal["string"]: 159 | return "string" 160 | 161 | def to_string(self) -> str: 162 | return StdStringPrinter(self.val["_storage"]).string() 163 | -------------------------------------------------------------------------------- /gdbmongo/timestamp_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printer for the mongo::Timestamp type.""" 17 | 18 | import ctypes 19 | import dataclasses 20 | import struct 21 | 22 | import gdb 23 | 24 | from gdbmongo.printer_protocol import SupportsToString 25 | 26 | 27 | # pylint: disable-next=invalid-name 28 | # pylint: disable-next=too-few-public-methods 29 | class c_uint32(ctypes.c_uint32): 30 | """Wrapper class for ctypes.c_uint32 to avoid implicit conversion to int.""" 31 | 32 | 33 | @dataclasses.dataclass 34 | class MongoTimestamp(ctypes.Structure): 35 | """Structure with a memory layout compatible with that of mongo::Timestamp. 36 | 37 | This class is useful for constructing gdb.Value objects of type mongo::Timestamp out of selected 38 | portions of a buffer read with gdb.Inferior.read_memory(). These synthetic gdb.Values can then 39 | be formatted by TimestampPrinter like normal. 40 | 41 | .. code-block:: python 42 | 43 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 44 | timestamp = MongoTimestamp.unpack_from(objdata) 45 | yield (f"{i}", timestamp.to_value()) 46 | """ 47 | 48 | i: c_uint32 49 | secs: c_uint32 50 | 51 | @classmethod 52 | def unpack_from(cls, buffer: memoryview, /) -> "MongoTimestamp": 53 | """Read an 8-byte Timestamp starting from the beginning of the given buffer.""" 54 | fmt = " gdb.Value: 59 | """Convert the structure to a gdb.Value of type mongo::Timestamp.""" 60 | typ = gdb.lookup_type("mongo::Timestamp") 61 | return gdb.Value(memoryview(self), typ) 62 | 63 | 64 | setattr(MongoTimestamp, "_fields_", 65 | [(field.name, field.type) for field in dataclasses.fields(MongoTimestamp)]) 66 | 67 | 68 | # pylint: disable-next=too-few-public-methods 69 | class TimestampPrinter(SupportsToString): 70 | # pylint: disable=missing-function-docstring 71 | """Pretty-printer for mongo::Timestamp.""" 72 | 73 | def __init__(self, val: gdb.Value, /) -> None: 74 | self.val = val 75 | self.time = val["secs"] 76 | self.inc = val["i"] 77 | 78 | def to_string(self) -> str: 79 | return f"Timestamp({self.time}, {self.inc})" 80 | 81 | 82 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 83 | """Add the TimestampPrinter to the pretty printer collection given.""" 84 | pretty_printer.add_printer("mongo::Timestamp", "^mongo::Timestamp$", TimestampPrinter) 85 | -------------------------------------------------------------------------------- /gdbmongo/uuid_printer.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Pretty-printer for the mongo::UUID type.""" 17 | 18 | import ctypes 19 | import dataclasses 20 | import typing 21 | import uuid 22 | 23 | import gdb 24 | 25 | from gdbmongo.printer_protocol import SupportsToString 26 | 27 | 28 | # pylint: disable-next=invalid-name 29 | # pylint: disable-next=too-few-public-methods 30 | class c_uint8(ctypes.c_uint8): 31 | """Wrapper class for ctypes.c_uint8 to avoid implicit conversion to int.""" 32 | 33 | 34 | @dataclasses.dataclass 35 | class MongoUUID(ctypes.Structure): 36 | """Structure with a memory layout compatible with that of mongo::UUID. 37 | 38 | This class is useful for constructing gdb.Value objects of type mongo::UUID out of selected 39 | portions of a buffer read with gdb.Inferior.read_memory(). These synthetic gdb.Values can then 40 | be formatted by UUIDPrinter like normal. 41 | 42 | .. code-block:: python 43 | 44 | objdata = gdb.selected_inferior().read_memory(self.val["_objdata"], objsize) 45 | uuid = MongoUUID.unpack_from(objdata) 46 | yield (f"{i}", uuid.to_value()) 47 | """ 48 | 49 | if typing.TYPE_CHECKING: 50 | uuid: ctypes.Array[c_uint8] 51 | else: 52 | uuid: c_uint8 * 16 53 | 54 | @classmethod 55 | def unpack_from(cls, buffer: memoryview, /) -> "MongoUUID": 56 | """Read a 16-byte UUID starting from the beginning of the given buffer.""" 57 | return cls.from_buffer(buffer) 58 | 59 | def to_value(self) -> gdb.Value: 60 | """Convert the structure to a gdb.Value of type mongo::UUID.""" 61 | typ = gdb.lookup_type("mongo::UUID") 62 | return gdb.Value(memoryview(self), typ) 63 | 64 | 65 | setattr(MongoUUID, "_fields_", 66 | [(field.name, field.type) for field in dataclasses.fields(MongoUUID)]) 67 | 68 | 69 | # pylint: disable-next=too-few-public-methods 70 | class UUIDPrinter(SupportsToString): 71 | # pylint: disable=missing-function-docstring 72 | """Pretty-printer for mongo::UUID.""" 73 | 74 | def __init__(self, val: gdb.Value, /) -> None: 75 | self.val = val 76 | self.uuid = val["_uuid"]["_M_elems"] 77 | 78 | def to_string(self) -> str: 79 | data = bytes([int(self.uuid[i]) for i in range(16)]) 80 | return f'UUID("{uuid.UUID(bytes=data)}")' 81 | 82 | 83 | def add_printers(pretty_printer: gdb.printing.RegexpCollectionPrettyPrinter, /) -> None: 84 | """Add the UUIDPrinter to the pretty printer collection given.""" 85 | pretty_printer.add_printer("mongo::UUID", "^mongo::UUID$", UUIDPrinter) 86 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools >= 45.1.0", 4 | "setuptools_scm[toml] >= 6.3.2", 5 | "wheel >= 0.36.0" 6 | ] 7 | build-backend = "setuptools.build_meta" 8 | 9 | [tool.setuptools_scm] 10 | write_to = "gdbmongo/_version.py" 11 | 12 | [tool.mypy] 13 | mypy_path = "stubs" 14 | pretty = true 15 | python_version = "3.9" 16 | strict = true 17 | warn_unreachable = true 18 | 19 | [tool.pydocstyle] 20 | match = ".*\\.pyi?" 21 | ignore = [ 22 | "D101", 23 | "D102", 24 | "D103", 25 | "D105", 26 | "D106", 27 | "D107", 28 | "D203", 29 | "D205", 30 | "D213", 31 | "D400", 32 | "D415" 33 | ] 34 | 35 | [tool.pylint] 36 | 37 | [tool.pylint.basic] 38 | ignore = "_version.py" 39 | 40 | [tool.pylint.design] 41 | ignored-parents = [ 42 | "gdbmongo.printer_protocol.PrettyPrinterProtocol", 43 | "gdbmongo.printer_protocol.SupportsDisplayHint", 44 | "gdbmongo.printer_protocol.SupportsToString", 45 | "gdbmongo.printer_protocol.SupportsChildren" 46 | ] 47 | 48 | [tool.pylint.similarities] 49 | min-similarity-lines = 6 50 | 51 | [tool.pylint.typecheck] 52 | ignored-modules = [ 53 | "gdb" 54 | ] 55 | 56 | [tool.yapf] 57 | based_on_style = "pep8" 58 | column_limit = 100 59 | split_before_named_assigns = false 60 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = gdbmongo 3 | description = GDB pretty printers and commands for debugging the MongoDB Server 4 | long_description = file: README.rst, CHANGELOG.rst 5 | long_description_content_type = text/x-rst 6 | url = https://github.com/visemet/gdb-mongodb-server 7 | maintainer = Max Hirschhorn 8 | maintainer_email = max.hirschhorn@mongodb.com 9 | license = Apache License, Version 2.0 10 | license_files = 11 | LICENSE 12 | classifiers = 13 | Development Status :: 4 - Beta 14 | Intended Audience :: Developers 15 | License :: OSI Approved :: Apache Software License 16 | Operating System :: POSIX 17 | Programming Language :: Python :: 3 18 | Programming Language :: Python :: 3 :: Only 19 | Programming Language :: Python :: 3.9 20 | Programming Language :: Python :: 3.10 21 | Programming Language :: Python :: 3.11 22 | Topic :: Database 23 | Topic :: Database :: Database Engines/Servers 24 | Topic :: Software Development :: Debuggers 25 | platforms = linux 26 | keywords = mongo, mongodb, gdb 27 | 28 | [options] 29 | zip_safe = False 30 | packages = gdbmongo 31 | install_requires = 32 | python_requires = >=3.9 33 | -------------------------------------------------------------------------------- /stubs/gdb/__init__.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html""" 17 | 18 | from gdb import events as events 19 | from gdb import printing as printing 20 | from gdb._architecture import Architecture as Architecture 21 | from gdb._basic import parse_and_eval as parse_and_eval 22 | from gdb._basic import execute as execute 23 | from gdb._errors import error as error 24 | from gdb._errors import MemoryError as MemoryError 25 | from gdb._errors import GdbError as GdbError 26 | from gdb.events import StopEvent as StopEvent 27 | from gdb._frame import Frame as Frame 28 | from gdb._frame import newest_frame as newest_frame 29 | from gdb._frame import selected_frame as selected_frame 30 | from gdb._inferior import Inferior as Inferior 31 | from gdb._inferior import selected_inferior as selected_inferior 32 | from gdb._inferiorthread import InferiorThread as InferiorThread 33 | from gdb._inferiorthread import selected_thread as selected_thread 34 | from gdb._objfile import Objfile as Objfile 35 | from gdb._objfile import current_objfile as current_objfile 36 | from gdb._progspace import Progspace as Progspace 37 | from gdb._symbol import Symbol as Symbol 38 | from gdb._symbol import lookup_symbol as lookup_symbol 39 | from gdb._type import Field as Field 40 | from gdb._type import Type as Type 41 | from gdb._type import TypeCode 42 | from gdb._type import lookup_type as lookup_type 43 | from gdb._value import Value as Value 44 | 45 | TYPE_CODE_BITSTRING = TypeCode.TYPE_CODE_BITSTRING 46 | TYPE_CODE_PTR = TypeCode.TYPE_CODE_PTR 47 | TYPE_CODE_ARRAY = TypeCode.TYPE_CODE_ARRAY 48 | TYPE_CODE_STRUCT = TypeCode.TYPE_CODE_STRUCT 49 | TYPE_CODE_UNION = TypeCode.TYPE_CODE_UNION 50 | TYPE_CODE_ENUM = TypeCode.TYPE_CODE_ENUM 51 | TYPE_CODE_FLAGS = TypeCode.TYPE_CODE_FLAGS 52 | TYPE_CODE_FUNC = TypeCode.TYPE_CODE_FUNC 53 | TYPE_CODE_INT = TypeCode.TYPE_CODE_INT 54 | TYPE_CODE_FLT = TypeCode.TYPE_CODE_FLT 55 | TYPE_CODE_VOID = TypeCode.TYPE_CODE_VOID 56 | TYPE_CODE_SET = TypeCode.TYPE_CODE_SET 57 | TYPE_CODE_RANGE = TypeCode.TYPE_CODE_RANGE 58 | TYPE_CODE_STRING = TypeCode.TYPE_CODE_STRING 59 | TYPE_CODE_ERROR = TypeCode.TYPE_CODE_ERROR 60 | TYPE_CODE_METHOD = TypeCode.TYPE_CODE_METHOD 61 | TYPE_CODE_METHODPTR = TypeCode.TYPE_CODE_METHODPTR 62 | TYPE_CODE_MEMBERPTR = TypeCode.TYPE_CODE_MEMBERPTR 63 | TYPE_CODE_REF = TypeCode.TYPE_CODE_REF 64 | TYPE_CODE_RVALUE_REF = TypeCode.TYPE_CODE_RVALUE_REF 65 | TYPE_CODE_CHAR = TypeCode.TYPE_CODE_CHAR 66 | TYPE_CODE_BOOL = TypeCode.TYPE_CODE_BOOL 67 | TYPE_CODE_COMPLEX = TypeCode.TYPE_CODE_COMPLEX 68 | TYPE_CODE_TYPEDEF = TypeCode.TYPE_CODE_TYPEDEF 69 | TYPE_CODE_NAMESPACE = TypeCode.TYPE_CODE_NAMESPACE 70 | TYPE_CODE_DECFLOAT = TypeCode.TYPE_CODE_DECFLOAT 71 | TYPE_CODE_INTERNAL_FUNCTION = TypeCode.TYPE_CODE_INTERNAL_FUNCTION 72 | -------------------------------------------------------------------------------- /stubs/gdb/_architecture.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Architectures-In-Python.html""" 17 | 18 | 19 | class Architecture: 20 | 21 | def name(self) -> str: 22 | ... 23 | -------------------------------------------------------------------------------- /stubs/gdb/_basic.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Basic-Python.html""" 17 | 18 | import typing 19 | 20 | from gdb._value import Value 21 | 22 | 23 | def parse_and_eval(expression: str, /) -> Value: 24 | ... 25 | 26 | 27 | @typing.overload 28 | def execute(command: str, /, *, from_tty: bool = False, 29 | to_string: typing.Literal[False] = False) -> None: 30 | ... 31 | 32 | 33 | @typing.overload 34 | def execute(command: str, /, *, from_tty: bool = False, to_string: typing.Literal[True]) -> str: 35 | ... 36 | -------------------------------------------------------------------------------- /stubs/gdb/_errors.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Exception-Handling.htm""" 17 | 18 | 19 | class error(RuntimeError): 20 | ... 21 | 22 | 23 | class MemoryError(error): 24 | ... 25 | 26 | 27 | class GdbError(Exception): 28 | ... 29 | -------------------------------------------------------------------------------- /stubs/gdb/_frame.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2023-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Frames-In-Python.html""" 17 | 18 | import typing 19 | 20 | from gdb._symbol import Symbol 21 | 22 | 23 | class Frame: 24 | 25 | def is_valid(self) -> bool: 26 | ... 27 | 28 | def name(self) -> typing.Optional[str]: 29 | ... 30 | 31 | def pc(self) -> int: 32 | ... 33 | 34 | def function(self) -> typing.Optional[Symbol]: 35 | ... 36 | 37 | def older(self) -> typing.Optional[Frame]: 38 | ... 39 | 40 | def newer(self) -> typing.Optional[Frame]: 41 | ... 42 | 43 | def select(self) -> None: 44 | ... 45 | 46 | def level(self) -> int: 47 | ... 48 | 49 | 50 | def selected_frame() -> Frame: 51 | ... 52 | 53 | 54 | def newest_frame() -> Frame: 55 | ... 56 | -------------------------------------------------------------------------------- /stubs/gdb/_inferior.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Inferiors-In-Python.html""" 17 | 18 | import typing 19 | 20 | from _typeshed import ReadableBuffer 21 | 22 | from gdb._architecture import Architecture 23 | from gdb._inferiorthread import InferiorThread 24 | from gdb._progspace import Progspace 25 | from gdb._value import Value 26 | 27 | 28 | class Inferior: 29 | 30 | @property 31 | def progspace(self) -> Progspace: 32 | ... 33 | 34 | def threads(self) -> typing.Tuple[InferiorThread, ...]: 35 | ... 36 | 37 | def architecture(self) -> Architecture: 38 | ... 39 | 40 | def read_memory(self, address: int | Value, length: int | Value, /) -> memoryview: 41 | ... 42 | 43 | def search_memory(self, address: int | Value, length: int | Value, pattern: ReadableBuffer, 44 | /) -> typing.Optional[int]: 45 | ... 46 | 47 | 48 | def selected_inferior() -> Inferior: 49 | ... 50 | -------------------------------------------------------------------------------- /stubs/gdb/_inferiorthread.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2023-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Threads-In-Python.html""" 17 | 18 | import typing 19 | 20 | from gdb._inferior import Inferior 21 | 22 | 23 | class InferiorThread: 24 | 25 | name: str 26 | 27 | @property 28 | def num(self) -> int: 29 | ... 30 | 31 | @property 32 | def global_num(self) -> int: 33 | ... 34 | 35 | @property 36 | def ptid(self) -> typing.Tuple[int, int, int]: 37 | ... 38 | 39 | @property 40 | def inferior(self) -> Inferior: 41 | ... 42 | 43 | def is_valid(self) -> bool: 44 | ... 45 | 46 | def switch(self) -> None: 47 | ... 48 | 49 | def is_stopped(self) -> bool: 50 | ... 51 | 52 | def is_running(self) -> bool: 53 | ... 54 | 55 | def is_exited(self) -> bool: 56 | ... 57 | 58 | def handle(self) -> bytes: 59 | ... 60 | 61 | 62 | def selected_thread() -> InferiorThread: 63 | ... 64 | -------------------------------------------------------------------------------- /stubs/gdb/_lazy_string.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Lazy-Strings-In-Python.html""" 17 | 18 | import typing 19 | 20 | from gdb._type import Type 21 | from gdb._value import Value 22 | 23 | 24 | class LazyString: 25 | 26 | @property 27 | def address(self) -> int: 28 | ... 29 | 30 | @property 31 | def length(self) -> int: 32 | ... 33 | 34 | @property 35 | def encoding(self) -> typing.Optional[str]: 36 | ... 37 | 38 | @property 39 | def type(self) -> Type: 40 | ... 41 | 42 | def value(self) -> Value: 43 | ... 44 | -------------------------------------------------------------------------------- /stubs/gdb/_objfile.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Objfiles-In-Python.html""" 17 | 18 | 19 | class Objfile: 20 | pass 21 | 22 | 23 | def current_objfile() -> Objfile: 24 | ... 25 | -------------------------------------------------------------------------------- /stubs/gdb/_progspace.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Progspaces-In-Python.html""" 17 | 18 | import typing 19 | 20 | 21 | class Progspace: 22 | 23 | @property 24 | def filename(self) -> typing.Optional[str]: 25 | ... 26 | -------------------------------------------------------------------------------- /stubs/gdb/_symbol.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Symbols-In-Python.html""" 17 | import typing 18 | 19 | from gdb._type import Type 20 | from gdb._value import Value 21 | 22 | 23 | class Symbol: 24 | 25 | @property 26 | def type(self) -> Type: 27 | ... 28 | 29 | def value(self) -> Value: 30 | ... 31 | 32 | 33 | def lookup_symbol(symbol_name: str, /) -> typing.Tuple[typing.Optional[Symbol], bool]: 34 | ... 35 | -------------------------------------------------------------------------------- /stubs/gdb/_type.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html""" 17 | 18 | import enum 19 | import typing 20 | 21 | 22 | class TypeCode(enum.IntEnum): 23 | """https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=gdb/gdbtypes.h;hb=refs/tags/gdb-8.3.1-release#l90""" 24 | 25 | TYPE_CODE_BITSTRING = -1 26 | TYPE_CODE_PTR = 1 27 | TYPE_CODE_ARRAY = 2 28 | TYPE_CODE_STRUCT = 3 29 | TYPE_CODE_UNION = 4 30 | TYPE_CODE_ENUM = 5 31 | TYPE_CODE_FLAGS = 6 32 | TYPE_CODE_FUNC = 7 33 | TYPE_CODE_INT = 8 34 | TYPE_CODE_FLT = 9 35 | TYPE_CODE_VOID = 10 36 | TYPE_CODE_SET = 11 37 | TYPE_CODE_RANGE = 12 38 | TYPE_CODE_STRING = 13 39 | TYPE_CODE_ERROR = 14 40 | TYPE_CODE_METHOD = 15 41 | TYPE_CODE_METHODPTR = 16 42 | TYPE_CODE_MEMBERPTR = 17 43 | TYPE_CODE_REF = 18 44 | TYPE_CODE_RVALUE_REF = 19 45 | TYPE_CODE_CHAR = 20 46 | TYPE_CODE_BOOL = 21 47 | TYPE_CODE_COMPLEX = 22 48 | TYPE_CODE_TYPEDEF = 23 49 | TYPE_CODE_NAMESPACE = 24 50 | TYPE_CODE_DECFLOAT = 25 51 | TYPE_CODE_INTERNAL_FUNCTION = 27 52 | 53 | 54 | class Field: 55 | 56 | @property 57 | def bitpos(self) -> typing.Optional[int]: 58 | ... 59 | 60 | # The `enumval` property is omitted here because it is assumed gdb.Type.fields() will only be 61 | # used for TYPE_CODE_STRUCT C++ types. The `enumval` property is mutually exclusive with the 62 | # `bitpos` property. 63 | # https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=gdb/python/py-type.c;hb=refs/tags/gdb-12.1-release#l184 64 | 65 | @property 66 | def name(self) -> typing.Optional[str]: 67 | ... 68 | 69 | @property 70 | def artificial(self) -> bool: 71 | ... 72 | 73 | @property 74 | def is_base_class(self) -> bool: 75 | ... 76 | 77 | @property 78 | def bitsize(self) -> int: 79 | ... 80 | 81 | @property 82 | def type(self) -> typing.Optional[Type]: 83 | ... 84 | 85 | @property 86 | def parent_type(self) -> Type: 87 | ... 88 | 89 | 90 | class Type: 91 | 92 | @property 93 | def code(self) -> TypeCode: 94 | ... 95 | 96 | @property 97 | def name(self) -> typing.Optional[str]: 98 | ... 99 | 100 | @property 101 | def tag(self) -> typing.Optional[str]: 102 | ... 103 | 104 | def fields(self) -> typing.List[Field]: 105 | ... 106 | 107 | def unqualified(self) -> Type: 108 | ... 109 | 110 | def reference(self) -> Type: 111 | ... 112 | 113 | def pointer(self) -> Type: 114 | ... 115 | 116 | def strip_typedefs(self) -> Type: 117 | ... 118 | 119 | def target(self) -> Type: 120 | ... 121 | 122 | def template_argument(self, n: int, /) -> Type: 123 | ... 124 | 125 | 126 | def lookup_type(typename: str, /) -> Type: 127 | ... 128 | -------------------------------------------------------------------------------- /stubs/gdb/_value.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html""" 17 | 18 | import typing 19 | 20 | from _typeshed import ReadableBuffer 21 | 22 | from gdb._lazy_string import LazyString 23 | from gdb._type import Type 24 | 25 | ConstructibleFrom = bool | int | float | str | Value 26 | 27 | 28 | class Value(typing.SupportsInt, typing.SupportsFloat): 29 | 30 | @typing.overload 31 | def __init__(self, val: ConstructibleFrom, /) -> None: 32 | ... 33 | 34 | @typing.overload 35 | def __init__(self, buf: ReadableBuffer, typ: Type, /) -> None: 36 | ... 37 | 38 | def __bool__(self) -> bool: 39 | ... 40 | 41 | def __int__(self) -> int: 42 | ... 43 | 44 | def __float__(self) -> float: 45 | ... 46 | 47 | def __str__(self) -> str: 48 | ... 49 | 50 | @typing.overload 51 | def __getitem__(self, field: str) -> Value: 52 | ... 53 | 54 | @typing.overload 55 | def __getitem__(self, idx: int) -> Value: 56 | ... 57 | 58 | def __lt__(self, other: object) -> bool: 59 | ... 60 | 61 | def __le__(self, other: object) -> bool: 62 | ... 63 | 64 | def __eq__(self, other: object) -> bool: 65 | ... 66 | 67 | def __ne__(self, other: object) -> bool: 68 | ... 69 | 70 | def __gt__(self, other: object) -> bool: 71 | ... 72 | 73 | def __ge__(self, other: object) -> bool: 74 | ... 75 | 76 | def __add__(self, other: ConstructibleFrom) -> Value: 77 | ... 78 | 79 | def __sub__(self, other: ConstructibleFrom) -> Value: 80 | ... 81 | 82 | @property 83 | def address(self) -> Value: 84 | ... 85 | 86 | @property 87 | def is_optimized_out(self) -> bool: 88 | ... 89 | 90 | @property 91 | def type(self) -> Type: 92 | ... 93 | 94 | @property 95 | def dynamic_type(self) -> Type: 96 | ... 97 | 98 | @property 99 | def is_lazy(self) -> bool: 100 | ... 101 | 102 | def cast(self, typ: Type, /) -> Value: 103 | ... 104 | 105 | def dynamic_cast(self, typ: Type, /) -> Value: 106 | ... 107 | 108 | def reinterpret_cast(self, typ: Type, /) -> Value: 109 | ... 110 | 111 | def dereference(self) -> Value: 112 | ... 113 | 114 | def referenced_value(self) -> Value: 115 | ... 116 | 117 | def string(self, *, encoding: str = "", errors: str = "", length: int = -1) -> str: 118 | ... 119 | 120 | def lazy_string(self, *, encoding: str = "", length: int = -1) -> LazyString: 121 | ... 122 | 123 | def fetch_lazy(self) -> None: 124 | ... 125 | -------------------------------------------------------------------------------- /stubs/gdb/events.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Events-In-Python.html""" 17 | 18 | import typing 19 | 20 | NotifyFunc = typing.TypeVar("NotifyFunc", bound=typing.Callable[..., None]) 21 | 22 | 23 | class EventRegistry(typing.Generic[NotifyFunc]): 24 | 25 | def connect(self, func: NotifyFunc, /) -> None: 26 | ... 27 | 28 | def disconnect(self, func: NotifyFunc, /) -> None: 29 | ... 30 | 31 | 32 | before_prompt: EventRegistry[typing.Callable[[], None]] 33 | 34 | 35 | class StopEvent: 36 | pass 37 | 38 | 39 | stop: EventRegistry[typing.Callable[[StopEvent], None]] 40 | -------------------------------------------------------------------------------- /stubs/gdb/printing.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Pretty-Printing-API.html 17 | https://sourceware.org/gdb/onlinedocs/gdb/Writing-a-Pretty_002dPrinter.html 18 | https://sourceware.org/gdb/onlinedocs/gdb/gdb_002eprinting.html 19 | """ 20 | 21 | import abc 22 | import typing 23 | 24 | from gdb._lazy_string import LazyString 25 | from gdb._objfile import Objfile 26 | from gdb._progspace import Progspace 27 | from gdb._value import ConstructibleFrom, Value 28 | 29 | 30 | class _SupportsDisplayHint(typing.Protocol): 31 | 32 | @abc.abstractmethod 33 | def display_hint(self) -> typing.Literal["string", "array", "map", None]: 34 | raise NotImplementedError 35 | 36 | 37 | class _SupportsToString(typing.Protocol): 38 | 39 | @abc.abstractmethod 40 | def to_string(self) -> str | Value | LazyString | None: 41 | raise NotImplementedError 42 | 43 | 44 | class _SupportsChildren(typing.Protocol): 45 | 46 | @abc.abstractmethod 47 | def children(self) -> typing.Iterator[typing.Tuple[str, ConstructibleFrom]]: 48 | raise NotImplementedError 49 | 50 | 51 | class _PrettyPrinterProtocol(_SupportsToString, _SupportsChildren, typing.Protocol): 52 | 53 | def __init__(self, val: Value, /) -> None: 54 | ... 55 | 56 | 57 | class PrettyPrinter: 58 | 59 | def __init__(self, name: str, 60 | subprinters: typing.Optional[typing.Iterator[SubPrettyPrinter]] = None, /) -> None: 61 | self.name = name 62 | self.subprinters = subprinters 63 | self.enabled: bool = True 64 | 65 | def __call__(self, val: Value, /) -> _SupportsToString | _SupportsChildren | None: 66 | ... 67 | 68 | 69 | class SubPrettyPrinter: 70 | 71 | def __init__(self, name: str, /) -> None: 72 | self.name = name 73 | self.enabled: bool = True 74 | 75 | 76 | class RegexpCollectionPrettyPrinter(PrettyPrinter): 77 | 78 | def __init__(self, name: str, /) -> None: 79 | ... 80 | 81 | def add_printer(self, name: str, regexp: str, 82 | gen_printer: typing.Type[_SupportsToString] | typing.Type[_SupportsChildren], 83 | /) -> None: 84 | ... 85 | 86 | 87 | class FlagEnumerationPrinter(PrettyPrinter): 88 | 89 | def __init__(self, name: str, /) -> None: 90 | ... 91 | 92 | 93 | def register_pretty_printer(obj: Objfile | Progspace | None, 94 | printer: typing.Callable[[Value], 95 | _SupportsToString | _SupportsChildren | None], 96 | /, *, replace: bool = False) -> None: 97 | ... 98 | -------------------------------------------------------------------------------- /stubs/gdb/xmethod.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://sourceware.org/gdb/onlinedocs/gdb/Xmethod-API.html 17 | https://sourceware.org/gdb/onlinedocs/gdb/Xmethods-In-Python.html 18 | https://sourceware.org/gdb/onlinedocs/gdb/Writing-an-Xmethod.html 19 | """ 20 | -------------------------------------------------------------------------------- /stubs/pydocstyle/__init__.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://github.com/PyCQA/pydocstyle""" 17 | -------------------------------------------------------------------------------- /stubs/pydocstyle/cli.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://github.com/PyCQA/pydocstyle""" 17 | 18 | 19 | def run_pydocstyle() -> int: 20 | ... 21 | -------------------------------------------------------------------------------- /stubs/pylint/__init__.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://github.com/PyCQA/pylint""" 17 | -------------------------------------------------------------------------------- /stubs/pylint/lint.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://github.com/PyCQA/pylint""" 17 | 18 | import typing 19 | 20 | 21 | class Linter(typing.Protocol): 22 | 23 | @property 24 | def msg_status(self) -> int: 25 | ... 26 | 27 | 28 | class Run: 29 | 30 | def __init__(self, args: typing.List[str], /, *, exit: bool = True) -> None: 31 | ... 32 | 33 | @property 34 | def linter(self) -> Linter: 35 | ... 36 | -------------------------------------------------------------------------------- /stubs/yapf/__init__.pyi: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """https://github.com/google/yapf""" 17 | 18 | import typing 19 | 20 | 21 | def main(argv: typing.List[str], /) -> int: 22 | ... 23 | -------------------------------------------------------------------------------- /tests/test_detect_toolchain.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Test file for the detect_toolchain.py module.""" 17 | 18 | import pathlib 19 | import shutil 20 | import tarfile 21 | import tempfile 22 | import typing 23 | import urllib.request 24 | 25 | import pytest 26 | 27 | from gdbmongo.detect_toolchain import ToolchainInfo, ToolchainVersionDetector 28 | 29 | 30 | @pytest.mark.parametrize( 31 | ("raw_elf_section", "expected"), 32 | ( 33 | pytest.param(b"\x00GCC: (GNU) 8.5.0\x00", "GCC: (GNU) 8.5.0", id="gcc-simple"), 34 | pytest.param( 35 | # pylint: disable-next=line-too-long 36 | b"\x00GCC: (GNU) 8.5.0\x00MongoDB clang version 7.0.1 (tags/RELEASE_701/final) (based on LLVM 7.0.1)\x00", 37 | "GCC: (GNU) 8.5.0", 38 | id="gcc-with-clang"), 39 | pytest.param(b"\x00GCC: (GNU) 8.2.1 20180905 (Red Hat 8.2.1-3)\x00GCC: (GNU) 11.2.0\x00", 40 | "GCC: (GNU) 11.2.0", id="gcc-with-multiple-gcc"), 41 | pytest.param( 42 | # pylint: disable-next=line-too-long 43 | b"GCC: (GNU) 8.5.0\x00Linker: LLD 7.0.1\x00MongoDB clang version 7.0.1 (tags/RELEASE_701/final) (based on LLVM 7.0.1)\x00\x00", 44 | "GCC: (GNU) 8.5.0", 45 | id="gcc-with-clang-and-lld"), 46 | )) 47 | def test_parse_gcc_version(raw_elf_section: bytes, expected: str) -> None: 48 | """Check the extracted GCC compiler version from a sample ELF .comment section.""" 49 | assert ToolchainVersionDetector.parse_gcc_version(raw_elf_section) == expected 50 | 51 | 52 | @pytest.mark.parametrize( 53 | ("raw_elf_section", "expected"), 54 | ( 55 | pytest.param(b"\x00GCC: (GNU) 8.5.0\x00", None, id="clang-missing"), 56 | pytest.param( 57 | # pylint: disable-next=line-too-long 58 | b"\x00MongoDB clang version 7.0.1 (tags/RELEASE_701/final) (based on LLVM 7.0.1)\x00", 59 | "MongoDB clang version 7.0.1", 60 | id="clang-simple"), 61 | pytest.param( 62 | # pylint: disable-next=line-too-long 63 | b"\x00GCC: (GNU) 8.2.1 20180905 (Red Hat 8.2.1-3)\x00GCC: (GNU) 11.2.0\x00MongoDB clang version 12.0.1 (git@github.com:10gen/toolchain-builder.git c6da1cf7f0b4b60d53566305e59857d3d540dcf7)\x00", 64 | "MongoDB clang version 12.0.1", 65 | id="clang-with-multiple-gcc"), 66 | )) 67 | def test_parse_clang_version(raw_elf_section: bytes, expected: typing.Optional[str]) -> None: 68 | """Check the extracted clang compiler version from a sample ELF .comment section.""" 69 | clang_version = ToolchainVersionDetector.parse_clang_version(raw_elf_section) 70 | 71 | if expected is None: 72 | assert clang_version is None 73 | else: 74 | assert clang_version == expected 75 | 76 | 77 | @pytest.mark.parametrize( 78 | ("url", "expected"), 79 | ( 80 | pytest.param( 81 | # pylint: disable-next=line-too-long 82 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-v6.0/enterprise-rhel-8-64-bit-dynamic-required/b77f5b16fadaa45040b280570693b6396d5d714d/binaries/mongo-mongodb_mongo_v6.0_enterprise_rhel_8_64_bit_dynamic_required_b77f5b16fadaa45040b280570693b6396d5d714d_25_01_31_11_12_59.tgz", 83 | ToolchainInfo("GCC: (GNU) 8.5.0", 84 | pathlib.Path("/opt/mongodbtoolchain/v3/share/gcc-8.5.0/python")), 85 | id="v3-gcc"), 86 | pytest.param( 87 | "https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel80-4.4.6.tgz", 88 | ToolchainInfo("GCC: (GNU) 8.3.0", 89 | pathlib.Path("/opt/mongodbtoolchain/v3/share/gcc-8.5.0/python")), 90 | id="v3-gcc-8.3.0"), 91 | pytest.param( 92 | # pylint: disable-next=line-too-long 93 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-v6.0/ubuntu1804-debug-aubsan-lite-required/b77f5b16fadaa45040b280570693b6396d5d714d/binaries/mongo-mongodb_mongo_v6.0_ubuntu1804_debug_aubsan_lite_required_b77f5b16fadaa45040b280570693b6396d5d714d_25_01_31_11_12_59.tgz", 94 | ToolchainInfo("MongoDB clang version 7.0.1", 95 | pathlib.Path("/opt/mongodbtoolchain/v3/share/gcc-8.5.0/python")), 96 | id="v3-clang"), 97 | pytest.param( 98 | # pylint: disable-next=line-too-long 99 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-v8.0/linux-x86-dynamic-compile/mongodb_mongo_v8.0_011f218eaf84f1afa97c3fe8c9b0f1492069af0d/binaries/mongo-2068.tgz", 100 | ToolchainInfo("GCC: (GNU) 11.3.0", 101 | pathlib.Path("/opt/mongodbtoolchain/v4/share/gcc-11.3.0/python")), 102 | id="v4-gcc"), 103 | pytest.param( 104 | # pylint: disable-next=line-too-long 105 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-v8.0/amazon-linux2-arm64-dynamic-compile/mongodb_mongo_v8.0_011f218eaf84f1afa97c3fe8c9b0f1492069af0d/binaries/mongo-2068.tgz", 106 | ToolchainInfo("GCC: (GNU) 11.3.0", 107 | pathlib.Path("/opt/mongodbtoolchain/v4/share/gcc-11.3.0/python")), 108 | id="v4-gcc-arm64"), 109 | pytest.param( 110 | # pylint: disable-next=line-too-long 111 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-v7.0/linux-debug-aubsan-compile-required/mongodb_mongo_v7.0_f11094fb1ea337ae03434a560eb98470b727e88b/binaries/mongo-1885.tgz", 112 | ToolchainInfo("MongoDB clang version 12.0.1", 113 | pathlib.Path("/opt/mongodbtoolchain/v4/share/gcc-11.3.0/python")), 114 | id="v4-clang"), 115 | pytest.param( 116 | # pylint: disable-next=line-too-long 117 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-v8.0/linux-debug-aubsan-compile-required/mongodb_mongo_v8.0_011f218eaf84f1afa97c3fe8c9b0f1492069af0d/binaries/mongo-2068.tgz", 118 | ToolchainInfo("MongoDB clang version 12.0.1", 119 | pathlib.Path("/opt/mongodbtoolchain/v4/share/gcc-11.3.0/python")), 120 | id="v4-clang-compiler-rt"), 121 | pytest.param( 122 | # pylint: disable-next=line-too-long 123 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-master/linux-x86-dynamic-debug-compile-toolchain-v5/mongodb_mongo_master_d6c9f84e40025a3709bb336ae3628009d2bda8dd/binaries/mongo-69121.tgz", 124 | ToolchainInfo("GCC: (GNU) 14.2.0", 125 | pathlib.Path("/opt/mongodbtoolchain/v5/share/gcc-14.2.0/python")), 126 | id="v5-gcc"), 127 | pytest.param( 128 | # pylint: disable-next=line-too-long 129 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-master/enterprise-rhel-8-arm64-grpc-toolchain-v5/mongodb_mongo_master_d6c9f84e40025a3709bb336ae3628009d2bda8dd/binaries/mongo-69121.tgz", 130 | ToolchainInfo("GCC: (GNU) 14.2.0", 131 | pathlib.Path("/opt/mongodbtoolchain/v5/share/gcc-14.2.0/python")), 132 | id="v5-gcc-arm64"), 133 | pytest.param( 134 | # pylint: disable-next=line-too-long 135 | "https://mciuploads.s3.amazonaws.com/mongodb-mongo-master/linux-debug-aubsan-compile-toolchain-v5/mongodb_mongo_master_d6c9f84e40025a3709bb336ae3628009d2bda8dd/binaries/mongo-69121.tgz", 136 | ToolchainInfo("MongoDB clang version 19.1.0", 137 | pathlib.Path("/opt/mongodbtoolchain/v5/share/gcc-14.2.0/python")), 138 | id="v5-clang"), 139 | )) 140 | def test_detected_toolchain_from_real_executable(url: str, expected: ToolchainInfo) -> None: 141 | """Check the toolchain info for a real mongod executable.""" 142 | with tempfile.NamedTemporaryFile() as output_file: 143 | with urllib.request.urlopen(url) as response: 144 | with tarfile.open(fileobj=response, mode="r|gz") as tarball: 145 | while (tarinfo := tarball.next()) is not None: 146 | if tarinfo.isfile() and pathlib.Path(tarinfo.path).name == "mongod": 147 | tarmember = tarball.extractfile(tarinfo) 148 | assert tarmember is not None 149 | 150 | shutil.copyfileobj(tarmember, output_file) 151 | output_file.flush() 152 | break 153 | else: 154 | pytest.fail("Did not extract a mongod executable from the provided url") 155 | 156 | detector = ToolchainVersionDetector(output_file.name) 157 | assert detector.detect() == expected 158 | -------------------------------------------------------------------------------- /tests/test_formatting.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Test file for checking Python formatting.""" 17 | 18 | import itertools 19 | import os 20 | import pathlib 21 | import typing 22 | 23 | import pytest 24 | 25 | 26 | def find_pyfiles() -> typing.Iterator[pathlib.Path]: 27 | """Return an iterator of the files to format.""" 28 | return itertools.chain( 29 | pathlib.Path("../gdbmongo").rglob("*.py"), 30 | pathlib.Path("../gdbmongo").rglob("*.pyi"), 31 | pathlib.Path("../stubs").rglob("*.pyi"), 32 | pathlib.Path("../tests").rglob("*.py")) 33 | 34 | 35 | def run_yapf(fix: bool) -> bool: 36 | """Return True if YAPF reports no further changes are needed, and return False otherwise. 37 | 38 | This function always returns True when fix == True. 39 | """ 40 | # We import the module here to suppress the PendingDeprecationWarning. 41 | # pylint: disable-next=import-outside-toplevel 42 | import yapf 43 | 44 | ret = yapf.main([ 45 | "", 46 | "--in-place" if fix else "--diff", 47 | "--verbose", 48 | ] + [str(path) for path in find_pyfiles() if path != pathlib.Path("../gdbmongo/_version.py")]) 49 | 50 | return ret == 0 or fix 51 | 52 | 53 | # Adapted from the definition for distutils.util.strtobool() in Python 3.11.1 to accommodate the 54 | # deprecation of the distutils module (PEP 632). 55 | def strtobool(val: str) -> bool: 56 | """Convert a string representation of truth to True or False. 57 | 58 | True values are "y", "yes", "t", "true", "on", and "1". 59 | False values are "n", "no", "f", "false", "off", and "0". 60 | 61 | Raises a ValueError if `val` is any other value. 62 | """ 63 | val = val.lower() 64 | if val in ("y", "yes", "t", "true", "on", "1"): 65 | return True 66 | 67 | if val in ("n", "no", "f", "false", "off", "0"): 68 | return False 69 | 70 | raise ValueError(f"Invalid truth value: {val!r}") 71 | 72 | 73 | @pytest.mark.filterwarnings(r"ignore:lib2to3 package is deprecated.*:PendingDeprecationWarning") 74 | def test_formatting() -> None: 75 | """Check code and tests for Python formatting errors.""" 76 | should_fix = strtobool(os.environ.get("TOX_YAPF_FIX", "0")) 77 | format_ok = run_yapf(should_fix) 78 | assert format_ok, "Changes are needed to address formatting issues; try running `tox -e format`" 79 | -------------------------------------------------------------------------------- /tests/test_interaction.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2023-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Test file for the interaction.py module.""" 17 | 18 | import subprocess 19 | import tempfile 20 | import typing 21 | 22 | FAKE_GDBINIT = """\ 23 | set confirm off 24 | set python print-stack full 25 | 26 | python 27 | import gdbmongo 28 | 29 | # Skip importing the libstdc++ GDB pretty printers. This enables running GDB with an executable file 30 | # but without that executable file needing to be a real MongoDB binary. 31 | def init_mock(): 32 | from unittest.mock import Mock 33 | from gdbmongo import interaction 34 | interaction.resolve_import = Mock(return_value=("", lambda: None)) 35 | 36 | init_mock() 37 | del init_mock 38 | 39 | gdbmongo.register_printers() 40 | end 41 | """ 42 | 43 | 44 | def run_interactive_gdb( 45 | input_commands: str, /, *, 46 | executable: typing.Optional[str] = None) -> subprocess.CompletedProcess[str]: 47 | """Launch a GDB session with the in-development version of the gdbmongo package loaded. 48 | 49 | The input commands are submitted by acting as though a human is typing in a series of commands. 50 | The `quit` command is automatically added as the final command. 51 | 52 | All output and/or errors from running the commands are captured and returned. 53 | """ 54 | assert not input_commands or input_commands[-1] == "\n" 55 | input_commands += "quit\n" 56 | 57 | # Setting PYTHONPATH to the root of the gdb-mongodb-server repository makes it so 58 | # `import gdbmongo` will refer to the in-development version of gdbmongo without needing to 59 | # install the package into the MongoDB toolchain Python to test it. 60 | # 61 | # Setting XDG_CACHE_HOME to any value suppresses the 62 | # "Couldn't determine a path for the index cache directory." warning message. /dev/null is used 63 | # because the index cache directory isn't needed for these Python tests. 64 | env = dict(PYTHONPATH="..", XDG_CACHE_HOME="/dev/null") 65 | 66 | with tempfile.NamedTemporaryFile(mode="wt") as command_file: 67 | command_file.write(FAKE_GDBINIT) 68 | command_file.flush() 69 | 70 | argv = [ 71 | "/opt/mongodbtoolchain/v4/bin/gdb", "--silent", "-nx", "--init-command", 72 | command_file.name 73 | ] 74 | 75 | if executable is not None: 76 | argv.append(executable) 77 | 78 | return subprocess.run(argv, text=True, capture_output=True, check=True, 79 | input=input_commands, env=env) 80 | 81 | 82 | def test_gdb_at_prompt_no_target() -> None: 83 | """Check that no GDB errors are emitted from displaying the prompt when there isn't an 84 | executable file loaded, or a core dump file loaded, or a live process attached. 85 | """ 86 | stderr = run_interactive_gdb("\n" * 10).stderr 87 | assert not stderr, stderr 88 | 89 | 90 | def test_gdb_initial_start_with_executable() -> None: 91 | """Check that no GDB errors are emitted from launching GDB with an executable file.""" 92 | stderr = run_interactive_gdb("", executable="/bin/ls").stderr 93 | assert not stderr, stderr 94 | -------------------------------------------------------------------------------- /tests/test_linting.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Test file for checking Python linting.""" 17 | 18 | import logging 19 | import sys 20 | import unittest.mock 21 | 22 | import mypy.api 23 | import pydocstyle.cli 24 | import pylint.lint 25 | 26 | 27 | def test_linting() -> None: 28 | """Check code and tests for Python linting errors.""" 29 | runner = pylint.lint.Run( 30 | ["--rcfile=../pyproject.toml", "../gdbmongo/", "../stubs/", "../tests/"], exit=False) 31 | lint_ok = runner.linter.msg_status == 0 32 | assert lint_ok, "Changes are needed to address linting issues" 33 | 34 | 35 | def test_typechecking() -> None: 36 | """Check code and tests for Python type errors.""" 37 | (normal_report, error_report, exit_status) = mypy.api.run( 38 | ["--config-file=../pyproject.toml", "../gdbmongo/", "../stubs/", "../tests/"]) 39 | 40 | if normal_report: 41 | print("\nType checking report:\n", file=sys.stdout) 42 | print(normal_report, file=sys.stdout) 43 | 44 | if error_report: 45 | print("\nError report:\n", file=sys.stderr) 46 | print(error_report, file=sys.stderr) 47 | 48 | typecheck_ok = exit_status == 0 49 | assert typecheck_ok, "Changes are needed to address type annotation issues" 50 | 51 | 52 | def test_docstrings() -> None: 53 | """Check docstrings for Python style errors.""" 54 | with unittest.mock.patch( 55 | "sys.argv", 56 | ["", "--config=../pyproject.toml", "../gdbmongo/", "../stubs/", "../tests/"]): 57 | logger = logging.getLogger("pydocstyle.utils") 58 | # pydocstyle automatically configures its logger to level DEBUG. This leads pytest to 59 | # capture and display a large volume of log messages whenever there is a test assertion 60 | # failure. We override logging.Logger.setLevel() on pydocstyle's logger to prevent this. 61 | # Note that pytest automatically captures any messages at level WARNING and above. 62 | with unittest.mock.patch.object(logger, "setLevel"): 63 | exit_code = pydocstyle.cli.run_pydocstyle() 64 | 65 | docstrings_ok = exit_code == 0 66 | assert docstrings_ok, "Changes are needed to address docstring issues" 67 | -------------------------------------------------------------------------------- /tests/test_stdlib_printers.py: -------------------------------------------------------------------------------- 1 | ### 2 | # Copyright 2022-present MongoDB, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | ### 16 | """Test file for the stdlib_printers.py and stdlib_printers_loader.py modules.""" 17 | 18 | import pathlib 19 | import sys 20 | import typing 21 | import unittest.mock 22 | 23 | import pytest 24 | 25 | from gdbmongo.detect_toolchain import ToolchainInfo 26 | import gdbmongo.stdlib_printers 27 | from gdbmongo.stdlib_printers_loader import resolve_import 28 | 29 | 30 | @pytest.fixture 31 | def unload_libstdcxx_printers() -> typing.Generator[None, None, None]: 32 | """Remove the gdb.libstdcxx.v6 package and its submodules from sys.modules.""" 33 | yield 34 | sys.modules.pop("gdb.libstdcxx.v6", None) 35 | sys.modules.pop("gdb.libstdcxx.v6.printers", None) 36 | 37 | 38 | @pytest.mark.parametrize(("toolchain_info", ), ( 39 | pytest.param( 40 | ToolchainInfo("GCC: (GNU) 8.5.0", 41 | pathlib.Path("/opt/mongodbtoolchain/v3/share/gcc-8.5.0/python")), 42 | id="v3/gcc-8.5.0"), 43 | pytest.param( 44 | ToolchainInfo("GCC: (GNU) 11.2.0", 45 | pathlib.Path("/opt/mongodbtoolchain/v4/share/gcc-11.3.0/python")), 46 | id="v4/gcc-11.2.0"), 47 | )) 48 | @pytest.mark.usefixtures("unload_libstdcxx_printers") 49 | @unittest.mock.patch.dict("sys.modules", gdb=unittest.mock.MagicMock()) 50 | def test_can_load_module_from_toolchain(toolchain_info: ToolchainInfo) -> None: 51 | """Check that the gdb.libstdcxx.v6 package can be loaded without error for the corresponding 52 | version of the MongoDB toolchain. 53 | """ 54 | (module, _register_module) = resolve_import(toolchain_info) 55 | assert module.register_libstdcxx_printers is not None 56 | 57 | 58 | @pytest.mark.usefixtures("unload_libstdcxx_printers") 59 | @unittest.mock.patch.dict("sys.modules", gdb=unittest.mock.MagicMock()) 60 | class TestStdlibPrinters: 61 | """Container for test cases so each runs with mocks and fixtures applied.""" 62 | 63 | toolchain_info = ToolchainInfo("GCC: (GNU) 8.5.0", 64 | pathlib.Path("/opt/mongodbtoolchain/v3/share/gcc-8.5.0/python")) 65 | 66 | def test_no_side_effects_from_loading_module(self) -> None: 67 | """Check that calling resolve_import() won't modify sys.modules automatically.""" 68 | current_modules = frozenset(sys.modules.keys()) 69 | resolve_import(self.toolchain_info) 70 | assert current_modules == sys.modules.keys() 71 | 72 | def test_can_import_module_after_registering(self) -> None: 73 | """Check that the gdb.libstdcxx.v6 module is only available to import after the returned 74 | register_module() function has been called. 75 | """ 76 | (_module, register_module) = resolve_import(self.toolchain_info) 77 | assert "gdb.libstdcxx.v6" not in sys.modules 78 | assert "gdb.libstdcxx.v6.printers" not in sys.modules 79 | register_module() 80 | assert "gdb.libstdcxx.v6" in sys.modules 81 | assert "gdb.libstdcxx.v6.printers" not in sys.modules 82 | 83 | def test_can_reference_printer_after_registering(self) -> None: 84 | """Check that pretty printer classes are only available to import after the returned 85 | register_module() function has been called. 86 | """ 87 | (_module, register_module) = resolve_import(self.toolchain_info) 88 | with pytest.raises(ModuleNotFoundError, match=r"No module named 'gdb.libstdcxx'"): 89 | _ = gdbmongo.stdlib_printers.UniquePointerPrinter 90 | register_module() 91 | assert gdbmongo.stdlib_printers.UniquePointerPrinter is not None 92 | 93 | def test_can_list_printer_names_after_registering(self) -> None: 94 | """Check that pretty printer classes are only available to list after the returned 95 | register_module() function has been called. 96 | """ 97 | (_module, register_module) = resolve_import(self.toolchain_info) 98 | with pytest.raises(ModuleNotFoundError, match=r"No module named 'gdb.libstdcxx'"): 99 | dir(gdbmongo.stdlib_printers) 100 | register_module() 101 | assert "UniquePointerPrinter" in dir(gdbmongo.stdlib_printers) 102 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | minversion = 3.24.1 3 | envlist = py39, py310, py311 4 | skip_missing_interpreters = True 5 | isolated_build = True 6 | 7 | [testenv] 8 | changedir = tests 9 | deps = 10 | mypy == 0.940 11 | pydocstyle[toml] == 6.1.1 12 | # Upgrading PyLint beyond version 2.15.0 will be challenged by the changes from 13 | # https://github.com/pylint-dev/pylint/pull/7411 due to how we have written 14 | # "pylint: disable-next" comments one per line. 15 | pylint == 2.15.0 16 | pytest >= 7.0.1 17 | setuptools >= 71.1 18 | # A direct dependency on toml is needed until 19 | # https://github.com/google/yapf/commit/fb0fbb47723612608a7c64cb3835562160ea834c is released. 20 | toml 21 | yapf == 0.32.0 22 | commands = pytest --basetemp="{envtmpdir}" {posargs} 23 | 24 | [testenv:format] 25 | basepython = python 26 | changedir = tests 27 | commands = pytest --basetemp="{envtmpdir}" test_formatting.py {posargs} 28 | setenv = 29 | TOX_YAPF_FIX = 1 30 | --------------------------------------------------------------------------------