xref: /aosp_15_r20/external/pigweed/pw_env_setup/py/pw_env_setup/entry_points/arm_gdb.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2023 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Wrapper script to run arm-none-eabi-gdb with Python 3.8."""
15
16import os
17from pathlib import Path
18import shutil
19import signal
20import sys
21import subprocess
22
23
24def main() -> int:
25    """arm-gdb wrapper that sets up the Python environment for gdb"""
26
27    # Find 'arm-none-eabi-gdb' as long as it isn't in the current Python
28    # virtualenv entry point. In other words: not this script.
29    exclude_paths = sys.path
30    venv = os.environ.get('VIRTUAL_ENV')
31    if venv:
32        venv_path = Path(venv).resolve()
33        exclude_paths.append(os.path.join(venv_path, 'Scripts'))
34    arm_gdb_binary = shutil.which(
35        'arm-none-eabi-gdb',
36        path=os.pathsep.join(
37            [
38                path_entry
39                for path_entry in os.environ.get('PATH', '').split(os.pathsep)
40                if str(Path(path_entry).resolve()) not in exclude_paths
41            ]
42        ),
43    )
44    assert arm_gdb_binary
45
46    arm_gdb_path = Path(arm_gdb_binary)
47    arm_install_prefix = arm_gdb_path.parent.parent
48    python_home = arm_install_prefix / 'python/bin/python3'
49    python_path = arm_install_prefix / 'python/lib/python3.8'
50    assert arm_gdb_path.is_file()
51
52    env = os.environ.copy()
53    # Only set Python if it's in the expected location.
54    if python_home.is_file() and python_path.is_dir():
55        env['PYTHONHOME'] = str(python_home)
56        env['PYTHONPATH'] = str(python_path)
57
58    # Ignore Ctrl-C to allow gdb to handle normally
59    signal.signal(signal.SIGINT, signal.SIG_IGN)
60    return subprocess.run(
61        [str(arm_gdb_path)] + sys.argv[1:], env=env, check=False
62    ).returncode
63
64
65if __name__ == '__main__':
66    sys.exit(main())
67