#!/usr/bin/env python3 """Collect native periodic drmemtrace windows without full-execution tracing.""" import argparse import datetime import json import os from pathlib import Path import re import shlex import subprocess import sys WARMUP = 500_000_000 LENGTH = 10_000_000 PERIOD = 1_000_000_000 def command(drrun, output, workload): return [str(drrun), "-t", "drcachesim", "-offline", "-split_windows", "-trace_after_instrs", str(WARMUP), "-trace_for_instrs", str(LENGTH), "-retrace_every_instrs", str(PERIOD - LENGTH), "-outdir", str(output / "native"), "--", *workload] def write_json(path, value): temporary = path.with_suffix(".json.tmp") temporary.write_text(json.dumps(value, indent=2) + "\n") temporary.replace(path) def index_windows(output, context): """Keep native layout/module metadata intact; expose named sample directories.""" samples = [] for window in sorted((output / "native").glob("*/raw/window.*")): match = re.fullmatch(r"window\.(\d+)", window.name) if not match or not window.is_dir(): continue index = int(match[1]) start = WARMUP + index * PERIOD # Include process-relative path to avoid conflating different processes. relative = window.relative_to(output / "native") destination = output / "samples" / relative.parent / ( f"sample_{index:04d}_instr_{start}_{start + LENGTH}") destination.mkdir(parents=True, exist_ok=True) link = destination / "window" if not link.is_symlink(): link.symlink_to(os.path.relpath(window, destination), target_is_directory=True) record = dict(context, window_id=index, requested_start_inclusive=start, requested_end_exclusive=start + LENGTH, requested_instruction_count=LENGTH, actual_instruction_count=None, range_accuracy="nominal; DynamoRIO thresholds are approximate", validation="unvalidated; may be partial or metadata-only", native_window=str(relative), native_process_directory=str(relative.parent), sample_directory=str(destination.relative_to(output))) write_json(destination / "metadata.json", record) samples.append(record) return samples def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--drrun", type=Path, default=( Path(os.environ["DYNAMORIO_HOME"]) / "bin64/drrun" if "DYNAMORIO_HOME" in os.environ else None)) parser.add_argument("--output", type=Path, required=True, help="New output directory; existing directories are rejected") parser.add_argument("--agent", required=True) parser.add_argument("--task", required=True) parser.add_argument("--task-id", required=True, help="Episode ID, or explicit workload batch identifier") parser.add_argument("--scope", required=True, help="What this process measures, e.g. agent-client or task-worker") parser.add_argument("--cwd", type=Path, default=Path.cwd()) parser.add_argument("--dry-run", action="store_true") parser.add_argument("workload", nargs=argparse.REMAINDER) args = parser.parse_args(argv) workload = args.workload[1:] if args.workload[:1] == ["--"] else args.workload if not workload or args.drrun is None: parser.error("provide --drrun (or DYNAMORIO_HOME) and a command after --") output = args.output.resolve() cmd = command(args.drrun.resolve(), output, workload) print(shlex.join(cmd), flush=True) if args.dry_run: return 0 if not args.cwd.is_dir(): parser.error("--cwd must be an existing workload directory") # Check capabilities before launching the workload; never fall back to full tracing. help_result = subprocess.run([str(args.drrun.resolve()), "-t", "drcachesim", "-help"], capture_output=True, text=True, timeout=30) help_text = help_result.stdout + help_result.stderr required = ["trace_after_instrs", "trace_for_instrs", "retrace_every_instrs", "split_windows"] if any(not re.search(r"(?= 0 else 128 - returncode if __name__ == "__main__": sys.exit(main())