aboutsummaryrefslogtreecommitdiffstats
path: root/idatui/launch.py
blob: 01778f35cf529db31553d11c7980598096da4bc1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""One-shot launcher for the IDA Nexus-backed TUI.

A path first resolves to a registered GUI database; when none matches, IDA Nexus
reuses or starts a managed idalib worker. With no path, a single registered
database is selected automatically.

Usage::

    ida-tui /path/to/binary
    ida-tui                         # attach when exactly one database is registered
"""

from __future__ import annotations

import argparse
import os
import sys


def _load_args(load: dict) -> str:
    """``load`` as IDA switches, for the single-binary path (no project ref).

    The base goes through project._as_addr rather than bare int(): our own CLI
    hands over an int, but a project file writes "0x8000000" as a string and
    int() raises on that. One parser, so the two paths can't disagree about what
    an address looks like.
    """
    from .formats import load_args
    from .project import _as_addr

    return load_args(
        load.get("processor", ""),
        _as_addr(load.get("base", 0)),
        str(load.get("ida_args", "") or ""),
    )


def _log(msg: str) -> None:
    print(f"ida-tui: {msg}", file=sys.stderr)


def _registered_databases() -> tuple[list[dict], list[dict]]:
    """Ready and blocked IDA Nexus registrations, with normalized errors."""
    try:
        from ida_nexus import InstanceState, discover_databases

        ready: list[dict] = []
        blocked: list[dict] = []
        for discovered in discover_databases():
            instance = discovered.instance
            item = {
                "record_id": instance.record_id,
                "backend": instance.backend,
                "pid": instance.pid,
                "exe_path": instance.exe_path,
                "idb_path": instance.idb_path,
            }
            if discovered.state is InstanceState.READY:
                ready.append(item)
            else:
                item["error"] = discovered.detail or "instance is unavailable"
                blocked.append(item)
        return ready, blocked
    except Exception as exc:  # discovery diagnostics belong at the CLI boundary
        return [], [{"error": str(exc)}]


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(
        prog="ida-tui",
        description="Open a registered GUI or managed idalib database in the IDA TUI.",
    )
    p.add_argument(
        "binary",
        nargs="*",
        help="binary to open and analyze (several with --project "
        "creates/extends that project)",
    )
    p.add_argument(
        "--project",
        metavar="FILE",
        help="open a multi-binary project (created from the given "
        "binaries if FILE doesn't exist)",
    )
    p.add_argument(
        "--ttl",
        type=int,
        default=1800,
        help="deprecated compatibility option (IDA Nexus uses leases)",
    )
    p.add_argument(
        "--no-keepalive",
        action="store_true",
        help="deprecated compatibility option (the lease is the heartbeat)",
    )
    p.add_argument(
        "--rpc",
        metavar="PATH",
        help="listen for RPC on this unix socket (puppeteer the TUI)",
    )
    p.add_argument(
        "--trace",
        metavar="FILE",
        help="Tenet execution trace to explore alongside the binary",
    )
    p.add_argument(
        "--idb",
        metavar="FILE",
        help="keep the database here instead of beside the binary (an .i64 path; "
        "the default for a binary in a directory you cannot write)",
    )
    g = p.add_argument_group(
        "loading a headerless blob",
        "An ELF/PE/Mach-O says what it is. A raw firmware dump doesn't, and IDA "
        "falls back to x86 at address 0 — which analyses to nothing. These say "
        "how to read it, and are recorded per binary in a project.",
    )
    g.add_argument(
        "--processor",
        metavar="NAME",
        help="IDA processor: arm, armb (big-endian), mipsb, metapc, …",
    )
    g.add_argument(
        "--base",
        metavar="ADDR",
        help="load address, e.g. 0x8000000 (any base; NOT paragraphs)",
    )
    g.add_argument(
        "--ida-args",
        metavar="STR",
        dest="ida_args",
        help="legacy switches; only IDA Nexus-representable -p/-b/-T are accepted",
    )
    args = p.parse_args(argv)

    load: dict = {}
    if args.processor:
        load["processor"] = args.processor
    if args.base:
        try:
            base = int(args.base, 0)
        except ValueError:
            _log(f"--base must be a number (got {args.base!r})")
            return 2
        if base % 16:
            # -b is in paragraphs, so an unaligned base cannot be expressed and
            # would silently load somewhere else.
            _log(f"--base must be 16-byte aligned (got {base:#x})")
            return 2
        load["base"] = base
    if args.ida_args:
        load["ida_args"] = args.ida_args

    # Where the database goes, for a binary whose own directory cannot hold one
    # (``/bin/ls`` -> ``/bin/ls.i64``). Validated HERE, before anything is staged
    # or imported, so a contradictory invocation costs nothing.
    idb_path = None
    if args.idb:
        from . import idbpath

        if args.project:
            # A project already keeps every database in its sidecar, so the two
            # options mean contradictory things. Refusing beats ignoring one.
            _log(
                "--idb is for a single binary; a project keeps its databases in "
                "its sidecar"
            )
            return 2
        try:
            idb_path = idbpath.ensure_parent(args.idb)
        except OSError as e:
            _log(f"cannot create the directory for --idb {args.idb}: {e}")
            return 2

    project = None
    binary = None
    if args.project:
        from .project import Project, ProjectError

        ppath = os.path.abspath(os.path.expanduser(args.project))
        try:
            if os.path.isfile(ppath):
                project = Project.load(ppath)
                if args.binary:  # extend an existing project, skipping repeats
                    before = len(project.refs)
                    for b in args.binary:
                        project.add(b, load=load or None)
                    added = len(project.refs) - before
                    dupes = len(args.binary) - added
                    if added:
                        project.save()
                        _log(f"added {added} binary(ies) to {ppath}")
                    if dupes:
                        _log(
                            f"{dupes} already in the project (matched by path) "
                            f"— left alone"
                        )
            elif args.binary:
                project = Project.create(ppath, args.binary, load=load or None)
                _log(f"created project {ppath} with {len(project.refs)} binaries")
            else:
                _log(f"no such project: {ppath} (pass binaries to create it)")
                return 2
        except ProjectError as e:
            _log(str(e))
            return 2
        # Everything IDA writes lives in the project's sidecar, so the source
        # tree is never touched and never needs to be writable.
        try:
            project.stage_all(progress=lambda m: _log(m))
        except ProjectError as e:
            _log(str(e))
            return 2
    else:
        ready, blocked = _registered_databases()
        if len(args.binary) > 1:
            _log("give at most one binary, or use --project for several")
            return 2
        if args.binary:
            binary = os.path.abspath(os.path.expanduser(args.binary[0]))
            key = os.path.normcase(os.path.realpath(binary))
            registered = any(
                key == os.path.normcase(os.path.realpath(str(item.get(field) or "")))
                for item in ready
                for field in ("exe_path", "idb_path")
                if item.get(field)
            )
            if not os.path.isfile(binary) and not registered:
                _log(f"no such file or registered database: {binary}")
                return 2
        elif len(ready) == 1:
            item = ready[0]
            binary = str(item.get("exe_path") or item.get("idb_path") or "")
            _log(f"attaching to registered {item.get('backend')} database: {binary}")
        elif not ready:
            detail = f" ({blocked[0].get('error')})" if blocked else ""
            _log(f"no registered IDA Nexus database; pass a binary path{detail}")
            return 2
        else:
            _log("several IDA Nexus databases are registered; pass one of these paths:")
            for item in ready:
                _log(
                    f"  {item.get('exe_path') or item.get('idb_path')} "
                    f"[{item.get('backend')}, {item.get('record_id')}]"
                )
            return 2

    # Hand off to the TUI (imported late so --help works without Textual). Code
    # Mode discovery/opening happens behind its loading overlay.
    try:
        from .app import IdaTui
    except ImportError as e:
        _log(f"TUI dependencies are missing; run `uv sync` ({e})")
        return 1
    # Ask the terminal about graphics support NOW: the query needs a reply from
    # stdin, and once Textual starts it reads stdin on its own thread and would
    # swallow it. Only the ANSWER is wanted here -- the image itself is uploaded
    # later, by the splash, because an image uploaded to the primary screen
    # cannot be placed once Textual has switched to the alternate one. Costs one
    # round trip, and only when attached to a tty.
    try:
        from . import kittygfx

        kittygfx.supported()
    except Exception:  # noqa: BLE001 -- graphics are decoration, never fatal
        pass

    rpc_path = os.path.abspath(os.path.expanduser(args.rpc)) if args.rpc else None
    IdaTui(
        open_path=binary,
        keepalive=not args.no_keepalive,
        rpc_path=rpc_path,
        ttl=args.ttl,
        project=project,
        load_args=_load_args(load),
        trace_path=(
            os.path.abspath(os.path.expanduser(args.trace)) if args.trace else ""
        ),
        idb_path=idb_path,
    ).run()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())