File size: 6,091 Bytes
8d4e520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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"(?<![\w])" + option + r"(?![\w])", help_text)
           for option in required):
        parser.error("DynamoRIO does not advertise the required bounded/split-window options")
    output.mkdir(parents=True, exist_ok=False)
    (output / "native").mkdir()
    context = {key: getattr(args, key) for key in ("agent", "task", "task_id", "scope")}
    manifest = dict(context, command=cmd, cwd=str(args.cwd.resolve()),
                    started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),
                    warmup_instructions=WARMUP, sample_instructions=LENGTH,
                    start_to_start_instructions=PERIOD, untraced_gap_instructions=PERIOD-LENGTH,
                    instruction_scope="DynamoRIO process-local counters, not distributed agent total",
                    status="running", samples=[])
    write_json(output / "manifest.json", manifest)
    (output / "drcachesim-help.txt").write_text(help_text)
    returncode = 1
    try:
        with (output / "workload.log").open("w") as log:
            returncode = subprocess.run(cmd, cwd=args.cwd, stdout=log,
                                        stderr=subprocess.STDOUT).returncode
    finally:
        manifest["samples"] = index_windows(output, context)
        manifest.update(returncode=returncode,
                        status="exited" if returncode == 0 else "failed_or_interrupted",
                        finished_utc=datetime.datetime.now(datetime.timezone.utc).isoformat())
        write_json(output / "manifest.json", manifest)
    print(f"Indexed {len(manifest['samples'])} windows in {output}; validate counts before simulation.")
    return returncode if returncode >= 0 else 128 - returncode


if __name__ == "__main__":
    sys.exit(main())