-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathida_analyze_bin.py
More file actions
2606 lines (2254 loc) · 90.4 KB
/
ida_analyze_bin.py
File metadata and controls
2606 lines (2254 loc) · 90.4 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
IDA Binary Analysis Script for CS2_VibeSignatures
Analyzes CS2 binary files using IDA Pro MCP and Claude/Codex agents.
Sequentially processes modules and symbols defined in config.yaml.
Usage:
python ida_analyze_bin.py -gamever=14134 [-platform=windows,linux] [-agent=codex]
-gamever: Game version subdirectory name (required)
-oldgamever: Old game version for signature reuse (default: gamever - 1)
-configyaml: Path to config.yaml file (default: config.yaml)
-bindir: Directory containing downloaded binaries (default: bin)
-platform: Platforms to analyze, comma-separated (default: windows,linux)
-agent: Agent to use for analysis: claude or codex (default: claude)
-ida_args: Additional arguments for idalib-mcp (optional)
-debug: Enable debug output
Requirements:
uv sync
uv (for running idalib-mcp)
claude CLI or codex CLI
Output:
bin/14134/engine/CServerSideClient_IsHearingClient.linux.yaml
bin/14134/engine/CServerSideClient_IsHearingClient.windows.yaml
...and more
"""
import argparse
import inspect
import json
import os
import re
from dotenv import load_dotenv
load_dotenv()
import socket
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
try:
import yaml
import asyncio
import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from mcp.types import TextContent
except ImportError as e:
print(f"Error: Missing required dependency: {e.name}")
print("Please install required dependencies with: uv sync")
sys.exit(1)
from ida_skill_preprocessor import (
PREPROCESS_STATUS_ABSENT_OK,
PREPROCESS_STATUS_FAILED,
PREPROCESS_STATUS_SUCCESS,
preprocess_single_skill_via_mcp,
)
from ida_vcall_finder import (
aggregate_vcall_results_for_object,
export_object_xref_details_via_mcp,
)
DEFAULT_CONFIG_FILE = "config.yaml"
DEFAULT_BIN_DIR = "bin"
DEFAULT_PLATFORM = "windows,linux"
DEFAULT_MODULES = "*"
DEFAULT_AGENT = "claude"
DEFAULT_LLM_MODEL = "gpt-4o"
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 13337
MCP_STARTUP_TIMEOUT = 1200 # seconds to wait for MCP server
SKILL_TIMEOUT = 1200 # 10 minutes per skill
ERROR_MARKER_RE = re.compile(
r"(?<![A-Za-z0-9])error(?![A-Za-z0-9])",
re.IGNORECASE,
)
_ARTIFACT_SYMBOL_CATEGORY_CACHE = {}
SURVEY_CURRENT_IDB_PATH_PY_EVAL = (
"import json\n"
"path = ''\n"
"try:\n"
" import idaapi\n"
" path = idaapi.get_path(idaapi.PATH_TYPE_IDB) or ''\n"
"except Exception:\n"
" pass\n"
"if not path:\n"
" try:\n"
" import idc\n"
" path = idc.get_idb_path() or ''\n"
" except Exception:\n"
" pass\n"
"result = json.dumps({'metadata': {'path': path}})\n"
)
def _output_contains_error_marker(*texts: str) -> bool:
merged_output = "\n".join(text for text in texts if text)
return bool(ERROR_MARKER_RE.search(merged_output))
def _parse_tool_json_content(result):
if not result or not getattr(result, "content", None):
return None
item = result.content[0]
raw = getattr(item, "text", None)
if not isinstance(raw, str):
raw = item.text if isinstance(item, TextContent) else str(item)
try:
return json.loads(raw)
except (json.JSONDecodeError, TypeError):
return None
def _resolve_config_path(config_path=DEFAULT_CONFIG_FILE):
path = Path(config_path)
if path.is_absolute():
return path
return Path(__file__).resolve().parent / path
def _load_artifact_symbol_category_map(config_path=DEFAULT_CONFIG_FILE):
resolved_config_path = _resolve_config_path(config_path)
cache_key = os.fspath(resolved_config_path)
cached = _ARTIFACT_SYMBOL_CATEGORY_CACHE.get(cache_key)
if cached is not None:
return cached
category_map = {}
try:
with open(resolved_config_path, "r", encoding="utf-8") as handle:
config_data = yaml.safe_load(handle) or {}
except Exception:
_ARTIFACT_SYMBOL_CATEGORY_CACHE[cache_key] = category_map
return category_map
for module_entry in config_data.get("modules", []):
if not isinstance(module_entry, dict):
continue
for symbol_entry in module_entry.get("symbols", []):
if not isinstance(symbol_entry, dict):
continue
symbol_name = str(symbol_entry.get("name", "")).strip()
category = str(symbol_entry.get("category", "")).strip()
if symbol_name and category and symbol_name not in category_map:
category_map[symbol_name] = category
_ARTIFACT_SYMBOL_CATEGORY_CACHE[cache_key] = category_map
return category_map
def _derive_artifact_symbol_name(artifact_path, platform):
basename = os.path.basename(str(artifact_path or ""))
platform_suffix = f".{platform}.yaml"
if basename.endswith(platform_suffix):
return basename[:-len(platform_suffix)]
if basename.endswith(".yaml"):
return basename[:-5]
return basename
def _lookup_expected_input_artifact_category(
artifact_path,
platform,
config_path=DEFAULT_CONFIG_FILE,
):
symbol_name = _derive_artifact_symbol_name(artifact_path, platform)
if not symbol_name:
return None
category_map = _load_artifact_symbol_category_map(config_path=config_path)
return category_map.get(symbol_name)
def _is_current_module_artifact_path(artifact_path, binary_dir):
"""Return whether artifact addresses can be checked in this binary's IDB."""
if not binary_dir:
return True
try:
artifact_resolved = Path(artifact_path).resolve()
binary_dir_resolved = Path(binary_dir).resolve()
return (
os.path.commonpath(
[os.fspath(artifact_resolved), os.fspath(binary_dir_resolved)]
)
== os.fspath(binary_dir_resolved)
)
except (OSError, ValueError):
return True
def _parse_py_eval_result_json(result):
payload = _parse_tool_json_content(result)
if not isinstance(payload, dict):
return None
result_text = payload.get("result", "")
if not isinstance(result_text, str) or not result_text:
return None
try:
parsed = json.loads(result_text)
except (json.JSONDecodeError, TypeError):
return None
return parsed if isinstance(parsed, dict) else None
async def _inspect_func_va_via_session(session, func_va_text):
py_code = (
"import ida_funcs, ida_segment, idaapi, json\n"
f"raw_func_va = {json.dumps(str(func_va_text))}\n"
"payload = {\n"
" 'has_segment': False,\n"
" 'segment_name': '',\n"
" 'has_function': False,\n"
" 'function_start': '',\n"
" 'is_function_start': False,\n"
"}\n"
"try:\n"
" ea = int(raw_func_va, 0)\n"
"except Exception:\n"
" result = json.dumps(payload)\n"
"else:\n"
" seg = None\n"
" try:\n"
" seg = ida_segment.getseg(ea)\n"
" except Exception:\n"
" try:\n"
" seg = idaapi.getseg(ea)\n"
" except Exception:\n"
" seg = None\n"
" if seg is not None:\n"
" payload['has_segment'] = True\n"
" try:\n"
" payload['segment_name'] = ida_segment.get_segm_name(seg) or ''\n"
" except Exception:\n"
" payload['segment_name'] = ''\n"
" func = ida_funcs.get_func(ea)\n"
" if func is not None:\n"
" func_start = int(func.start_ea)\n"
" payload['has_function'] = True\n"
" payload['function_start'] = hex(func_start)\n"
" payload['is_function_start'] = (func_start == ea)\n"
" result = json.dumps(payload)\n"
)
try:
eval_result = await session.call_tool(
name="py_eval",
arguments={"code": py_code},
)
except Exception:
return None
return _parse_py_eval_result_json(eval_result)
async def validate_expected_input_artifacts_via_session(
session,
expected_inputs,
platform,
binary_dir=None,
debug=False,
config_path=DEFAULT_CONFIG_FILE,
):
invalid_artifacts = []
for artifact_path in expected_inputs or []:
category = _lookup_expected_input_artifact_category(
artifact_path,
platform,
config_path=config_path,
)
if category not in {"func", "vfunc"}:
continue
try:
with open(artifact_path, "r", encoding="utf-8") as handle:
artifact_payload = yaml.safe_load(handle)
except Exception as exc:
invalid_artifacts.append(
f"{artifact_path}: failed to read YAML ({exc})"
)
continue
if not isinstance(artifact_payload, dict):
invalid_artifacts.append(
f"{artifact_path}: invalid YAML payload (expected mapping)"
)
continue
issues = []
raw_func_va = artifact_payload.get("func_va")
func_va_text = str(raw_func_va or "").strip()
should_require_func_va = (category == "func")
should_inspect_func_va = _is_current_module_artifact_path(
artifact_path,
binary_dir,
)
if should_require_func_va and not func_va_text:
issues.append("missing required field func_va")
if category == "func":
func_sig_text = str(artifact_payload.get("func_sig") or "").strip()
if not func_sig_text:
issues.append("missing required field func_sig")
if func_va_text:
try:
int(func_va_text, 0)
except (TypeError, ValueError):
issues.append(f"invalid func_va value {func_va_text!r}")
else:
if should_inspect_func_va:
inspect_payload = await _inspect_func_va_via_session(
session,
func_va_text,
)
if inspect_payload is not None:
has_segment = bool(inspect_payload.get("has_segment"))
segment_name = str(
inspect_payload.get("segment_name", "")
).strip()
if not has_segment:
issues.append(
f"func_va={func_va_text} is not mapped to any segment"
)
elif segment_name != ".text":
issues.append(
f"func_va={func_va_text} resolves to segment {segment_name!r} "
"instead of '.text'"
)
elif not inspect_payload.get("has_function"):
issues.append(
f"func_va={func_va_text} does not resolve to a function"
)
elif not inspect_payload.get("is_function_start"):
function_start = str(
inspect_payload.get("function_start", "")
).strip() or "<unknown>"
issues.append(
f"func_va={func_va_text} resolves inside function "
f"{function_start} instead of a function start"
)
elif debug:
print(
" Warning: unable to inspect expected_input func_va via MCP: "
f"{artifact_path} ({func_va_text})"
)
if issues:
invalid_artifacts.append(f"{artifact_path}: {'; '.join(issues)}")
return invalid_artifacts
def _merge_metadata_path(payload, path_payload):
if not isinstance(path_payload, dict):
return payload
path_metadata = path_payload.get("metadata")
if not isinstance(path_metadata, dict):
return payload
resolved_path = path_metadata.get("path")
if not isinstance(resolved_path, str) or not resolved_path:
return payload
if not isinstance(payload, dict):
return {"metadata": {"path": resolved_path}}
metadata = payload.get("metadata")
merged_payload = dict(payload)
merged_metadata = dict(metadata) if isinstance(metadata, dict) else {}
merged_metadata["path"] = resolved_path
merged_payload["metadata"] = merged_metadata
return merged_payload
async def _survey_current_idb_path_via_py_eval(session):
try:
result = await session.call_tool(
name="py_eval",
arguments={"code": SURVEY_CURRENT_IDB_PATH_PY_EVAL},
)
except Exception:
return None
return _parse_py_eval_result_json(result)
async def survey_binary_via_session(session, detail_level="minimal"):
parsed = None
try:
result = await session.call_tool(
name="survey_binary",
arguments={"detail_level": detail_level},
)
except Exception:
pass
else:
parsed = _parse_tool_json_content(result)
current_idb_path = await _survey_current_idb_path_via_py_eval(session)
if isinstance(current_idb_path, dict):
return _merge_metadata_path(parsed, current_idb_path)
return parsed
async def check_mcp_health(host=DEFAULT_HOST, port=DEFAULT_PORT):
"""
Verify MCP server is alive and responsive via a lightweight py_eval call.
Args:
host: MCP server host
port: MCP server port
Returns:
True if the server responded successfully, False otherwise
"""
server_url = f"http://{host}:{port}/mcp"
try:
async with httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(10.0, read=15.0),
trust_env=False,
) as http_client:
async with streamable_http_client(server_url, http_client=http_client) as (read_stream, write_stream, _):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
await session.call_tool(name="py_eval", arguments={"code": "1"})
return True
except Exception:
return False
async def survey_binary_via_mcp(host=DEFAULT_HOST, port=DEFAULT_PORT, detail_level="minimal"):
"""
Retrieve a compact overview of the binary currently loaded in IDA.
Args:
host: MCP server host
port: MCP server port
detail_level: 'standard' or 'minimal' (use 'minimal' for binaries with >10k functions)
Returns:
Parsed survey dict on success, None otherwise.
Note:
When available, metadata.path is replaced with the current IDB path so callers
can infer targets from the moved .i64 location instead of the original input binary path.
Example result (detail_level='minimal'):
{
"metadata": {
"path": "D:\\CS2_VibeSignatures\\bin\\14141c\\engine\\engine2.dll.i64",
"module": "engine2.dll",
"arch": "64",
"base_address": "0x180000000",
"image_size": "0x95c000",
"md5": "11092707508ae325cfdbcfb5ff200423",
"sha256": "2f48108e724bdb389d0102bc673d762405d39f222d84f4ac56ce86bbe4d61c28"
},
"statistics": {
"total_functions": 15504,
"named_functions": 317,
"library_functions": 248,
"unnamed_functions": 14939,
"total_strings": 14531,
"total_segments": 6
},
"segments": [
{"name": ".text", "start": "0x180001000", "end": "0x180481000", "size": "0x480000", "permissions": "rx"},
{"name": ".idata", "start": "0x180481000", "end": "0x180482bf0", "size": "0x1bf0", "permissions": "r"},
{"name": ".rdata", "start": "0x180482bf0", "end": "0x180604000", "size": "0x181410", "permissions": "r"},
{"name": ".data", "start": "0x180604000", "end": "0x180916000", "size": "0x312000", "permissions": "rw"},
{"name": ".pdata", "start": "0x180916000", "end": "0x180950000", "size": "0x3a000", "permissions": "r"},
{"name": "_RDATA", "start": "0x180950000", "end": "0x180951000", "size": "0x1000", "permissions": "r"}
],
"entrypoints": [
{"addr": "0x1802523d0", "name": "BinaryProperties_GetValue", "ordinal": 1},
{"addr": "0x180400100", "name": "CreateInterface", "ordinal": 2},
{"addr": "0x180219430", "name": "Source2Main", "ordinal": 7},
...
],
"_note": "Binary has 15504 functions; xref analysis was limited to the first 10000 for performance."
}
"""
server_url = f"http://{host}:{port}/mcp"
try:
async with httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(10.0, read=30.0),
trust_env=False,
) as http_client:
async with streamable_http_client(server_url, http_client=http_client) as (read_stream, write_stream, _):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
return await survey_binary_via_session(session, detail_level=detail_level)
except Exception:
return None
async def validate_expected_input_artifacts_via_mcp(
host=DEFAULT_HOST,
port=DEFAULT_PORT,
expected_inputs=None,
platform="",
binary_dir=None,
debug=False,
config_path=DEFAULT_CONFIG_FILE,
):
if not expected_inputs:
return []
server_url = f"http://{host}:{port}/mcp"
try:
async with httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(10.0, read=30.0),
trust_env=False,
) as http_client:
async with streamable_http_client(server_url, http_client=http_client) as (read_stream, write_stream, _):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
return await validate_expected_input_artifacts_via_session(
session,
expected_inputs=expected_inputs,
platform=platform,
binary_dir=binary_dir,
debug=debug,
config_path=config_path,
)
except Exception:
if debug:
print(" Warning: expected_input artifact validation via MCP failed")
return []
def _run_validate_expected_input_artifacts_via_mcp(
*,
host,
port,
expected_inputs,
platform,
binary_dir=None,
debug=False,
config_path=DEFAULT_CONFIG_FILE,
):
return asyncio.run(
validate_expected_input_artifacts_via_mcp(
host=host,
port=port,
expected_inputs=expected_inputs,
platform=platform,
binary_dir=binary_dir,
debug=debug,
config_path=config_path,
)
)
def _run_post_process_expected_outputs_via_mcp(
*,
host,
port,
yaml_items,
debug=False,
):
"""Run post_process for collected expected output YAML mappings."""
if not yaml_items:
return True
return asyncio.run(
post_process_expected_outputs_via_mcp(
host=host,
port=port,
yaml_items=yaml_items,
debug=debug,
)
)
async def post_process_expected_outputs_via_mcp(
host=DEFAULT_HOST,
port=DEFAULT_PORT,
yaml_items=None,
debug=False,
):
"""Connect to IDA MCP and execute post_process actions."""
yaml_items = list(yaml_items or [])
if not yaml_items:
return True
server_url = f"http://{host}:{port}/mcp"
try:
async with httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(10.0, read=120.0),
trust_env=False,
) as http_client:
async with streamable_http_client(server_url, http_client=http_client) as (
read_stream,
write_stream,
_,
):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
return await post_process_expected_outputs_via_session(
session,
yaml_items,
debug=debug,
)
except Exception as exc:
if debug:
print(f" Post-process: MCP connection failed: {exc}")
return False
async def preprocess_single_vcall_object_via_mcp(
host,
port,
output_root,
gamever,
module_name,
platform,
object_name,
debug=False,
):
"""Export xref detail YAMLs for a single vcall_finder object via MCP."""
server_url = f"http://{host}:{port}/mcp"
async with httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(30.0, read=300.0),
trust_env=False,
) as http_client:
async with streamable_http_client(server_url, http_client=http_client) as (read_stream, write_stream, _):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
return await export_object_xref_details_via_mcp(
session,
output_root=output_root,
gamever=gamever,
module_name=module_name,
platform=platform,
object_name=object_name,
debug=debug,
)
def ensure_mcp_available(process, binary_path, host, port, ida_args, debug):
"""
Ensure idalib-mcp is running and responsive. Restart if necessary.
Checks the process status first, then performs a real MCP health check.
If the server is unresponsive, kills the old process and starts a new one.
Args:
process: Current subprocess.Popen object (may be None)
binary_path: Path to binary file for restarting idalib-mcp
host: MCP server host
port: MCP server port
ida_args: Additional arguments for idalib-mcp
debug: Enable debug output
Returns:
Tuple of (new_process, ok) where new_process may be the same object
if no restart was needed, and ok indicates whether MCP is available.
"""
# Step 1: check if the process has already exited
if process is not None and process.poll() is not None:
if debug:
print(f" idalib-mcp process exited with code {process.returncode}")
process = None
# Step 2: if process appears alive, do a real MCP health check
if process is not None:
healthy = asyncio.run(check_mcp_health(host, port))
if healthy:
return process, True
print(" MCP health check failed, restarting idalib-mcp...")
quit_ida_gracefully(process, host, port, debug=debug)
process = None
# Step 3: restart idalib-mcp
print(" Restarting idalib-mcp...")
new_process = start_idalib_mcp(binary_path, host, port, ida_args, debug)
if new_process is None:
return None, False
return new_process, True
async def quit_ida_via_mcp(host=DEFAULT_HOST, port=DEFAULT_PORT):
"""
Gracefully quit IDA using MCP py_eval tool with idc.qexit(0).
Args:
host: MCP server host
port: MCP server port
Returns:
True if successful, False otherwise
"""
server_url = f"http://{host}:{port}/mcp"
try:
async with httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(30.0, read=300.0),
trust_env=False, # Bypass system proxy to avoid 502
) as http_client:
async with streamable_http_client(server_url, http_client=http_client) as (read_stream, write_stream, _):
async with ClientSession(read_stream, write_stream) as session:
await session.initialize()
await session.call_tool(name="py_eval", arguments={"code": "import idc; idc.qexit(0)"})
return True
except Exception:
return False
async def quit_ida_gracefully_async(process, host=DEFAULT_HOST, port=DEFAULT_PORT, debug=False):
"""
Attempt to quit IDA gracefully via MCP, fall back to terminate if needed.
Args:
process: subprocess.Popen object
host: MCP server host
port: MCP server port
"""
if process is None:
return
if process.poll() is not None:
return # Process already exited
if debug:
print(" Quitting IDA gracefully via MCP...")
try:
await asyncio.wait_for(quit_ida_via_mcp(host, port), timeout=5)
except Exception:
pass
try:
await asyncio.to_thread(process.wait, timeout=10)
if debug:
print(" IDA exited gracefully")
return
except subprocess.TimeoutExpired:
if debug:
print(" Warning: IDA did not exit after qexit, forcing kill...")
if process.poll() is None:
try:
process.kill()
await asyncio.to_thread(process.wait, timeout=5)
except Exception:
pass
def quit_ida_gracefully(process, host=DEFAULT_HOST, port=DEFAULT_PORT, debug=False):
"""
Synchronous wrapper around quit_ida_gracefully_async.
Args:
process: subprocess.Popen object
host: MCP server host
port: MCP server port
"""
if process is None:
return
if process.poll() is not None:
return
try:
asyncio.get_running_loop()
except RuntimeError:
asyncio.run(quit_ida_gracefully_async(process, host, port, debug=debug))
return
raise RuntimeError(
"quit_ida_gracefully() cannot run inside an active event loop; "
"use await quit_ida_gracefully_async() instead"
)
def resolve_oldgamever(gamever, bin_dir):
"""
Resolve the best oldgamever by searching for the most recent existing version
directory under bin_dir.
Version ordering (descending):
14141z > 14141y > ... > 14141b > 14141a > 14141 > 14140
Args:
gamever: Current game version string (e.g., "14142", "14141a")
bin_dir: Base binary directory to check for existing version subdirectories
Returns:
Best matching oldgamever string, or None if no candidate directory exists
"""
if not gamever:
return None
# Parse gamever into (base_number, optional_suffix)
if gamever[-1].islower() and gamever[-1].isalpha():
suffix = gamever[-1]
base_str = gamever[:-1]
else:
suffix = None
base_str = gamever
try:
base = int(base_str)
except ValueError:
return None
# Generate candidates in descending version order
candidates = []
if suffix:
# E.g., gamever="14141c" -> try 14141b, 14141a, 14141, 14140z..14140a, 14140
for c in range(ord(suffix) - 1, ord('a') - 1, -1):
candidates.append(f"{base}{chr(c)}")
candidates.append(str(base))
prev_base = base - 1
for c in range(ord('z'), ord('a') - 1, -1):
candidates.append(f"{prev_base}{chr(c)}")
candidates.append(str(prev_base))
else:
# E.g., gamever="14142" -> try 14141z..14141a, 14141, 14140
prev_base = base - 1
for c in range(ord('z'), ord('a') - 1, -1):
candidates.append(f"{prev_base}{chr(c)}")
candidates.append(str(prev_base))
candidates.append(str(prev_base - 1))
# Return the first candidate whose directory exists
for candidate in candidates:
candidate_dir = os.path.join(bin_dir, candidate)
if os.path.isdir(candidate_dir):
return candidate
return None
def parse_vcall_finder_filter(raw_value):
"""
Parse vcall finder selector into normalized filter structure.
Args:
raw_value: Raw selector string from CLI, e.g. "*", "a,b", or None
Returns:
None if selector is not provided; otherwise:
{"all": bool, "names": set[str]}
Raises:
ValueError: If selector is empty or has invalid format.
"""
if raw_value is None:
return None
if not isinstance(raw_value, str):
raise ValueError("selector must be a string")
selector = raw_value.strip()
if not selector:
raise ValueError("selector cannot be empty")
if selector == "*":
return {"all": True, "names": set()}
names = []
for name in selector.split(","):
normalized_name = name.strip()
if not normalized_name:
raise ValueError("selector contains empty object name")
names.append(normalized_name)
if "*" in names:
raise ValueError("'*' cannot be combined with object names")
return {"all": False, "names": set(names)}
def _parse_optional_llm_temperature(raw_value, parser):
if raw_value is None:
return None
raw_text = str(raw_value).strip()
if not raw_text:
return None
try:
return float(raw_text)
except ValueError:
parser.error("Invalid LLM temperature: must be a number")
def _parse_optional_llm_fake_as(raw_value, parser):
if raw_value is None:
return None
normalized_value = str(raw_value).strip().lower()
if not normalized_value:
return None
if normalized_value != "codex":
parser.error("Invalid LLM fake_as: must be 'codex'")
return normalized_value
def _parse_optional_llm_effort(raw_value, parser):
if raw_value is None:
return "medium"
normalized_value = str(raw_value).strip().lower()
if not normalized_value:
return "medium"
valid_efforts = {"none", "minimal", "low", "medium", "high", "xhigh"}
if normalized_value not in valid_efforts:
parser.error(
"Invalid LLM effort: must be one of none, minimal, low, medium, high, xhigh"
)
return normalized_value
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description="Analyze CS2 binary files using IDA Pro MCP and Claude/Codex agents"
)
parser.add_argument(
"-configyaml",
default=DEFAULT_CONFIG_FILE,
help=f"Path to config.yaml file (default: {DEFAULT_CONFIG_FILE})"
)
parser.add_argument(
"-bindir",
default=DEFAULT_BIN_DIR,
help=f"Directory containing downloaded binaries (default: {DEFAULT_BIN_DIR})"
)
parser.add_argument(
"-gamever",
default=os.environ.get("CS2VIBE_GAMEVER"),
required="CS2VIBE_GAMEVER" not in os.environ,
help="Game version subdirectory name (required, or set CS2VIBE_GAMEVER env var)"
)
parser.add_argument(
"-platform",
default=DEFAULT_PLATFORM,
help=f"Platforms to analyze, comma-separated (default: {DEFAULT_PLATFORM})"
)
parser.add_argument(
"-agent",
default=os.environ.get("CS2VIBE_AGENT", DEFAULT_AGENT),
help=f"Agent executable to use for analysis, e.g., claude, claude.cmd, codex, codex.cmd (default: {DEFAULT_AGENT}, or set CS2VIBE_AGENT env var)"
)
parser.add_argument(
"-modules",
default=DEFAULT_MODULES,
help=f"Modules to analyze, comma-separated (default: {DEFAULT_MODULES} for all). E.g., server,engine"
)
parser.add_argument(
"-vcall_finder",
default=None,
help="vcall_finder object selector: '*' for all, or comma-separated object names"
)
parser.add_argument(
"-llm_model",
default=os.environ.get("CS2VIBE_LLM_MODEL", DEFAULT_LLM_MODEL),
help=f"OpenAI-compatible model for preprocessing and vcall_finder workflow (default: {DEFAULT_LLM_MODEL}, or set CS2VIBE_LLM_MODEL env var)"
)
parser.add_argument(
"-llm_apikey",
default=os.environ.get("CS2VIBE_LLM_APIKEY"),
help="OpenAI-compatible API key used by preprocessing and vcall_finder aggregation (or set CS2VIBE_LLM_APIKEY env var)"
)
parser.add_argument(
"-llm_baseurl",
default=os.environ.get("CS2VIBE_LLM_BASEURL"),
help="Optional custom compatible base URL used by preprocessing and vcall_finder aggregation (required when -llm_fake_as=codex; or set CS2VIBE_LLM_BASEURL env var)"
)
parser.add_argument(
"-llm_temperature",
default=os.environ.get("CS2VIBE_LLM_TEMPERATURE"),
help="Optional OpenAI-compatible temperature used by preprocessing and vcall_finder aggregation (or set CS2VIBE_LLM_TEMPERATURE env var)"
)
parser.add_argument(
"-llm_fake_as",
default=os.environ.get("CS2VIBE_LLM_FAKE_AS"),
help="Optional OpenAI-compatible fake_as override (only supports 'codex'; or set CS2VIBE_LLM_FAKE_AS env var)"
)
parser.add_argument(
"-llm_effort",