"""DIS-Bench evaluator: pass / reach / sfunc of generated inputs. This is the evaluator used to produce every number in the paper (experiments/results/*.json). For each attempt it 1. executes the generator code in a separate process (1 s CPU-time alarm, 100 MB address-space limit, file writes captured in memory), 2. collects every candidate byte buffer the code produces: the return value of generate_buf(), return values of other zero-/one-argument functions, files written by the code, and printed output, 3. runs the instrumented target on each buffer (inputs are truncated to 10,000 bytes by SeedRunner) and checks pass : the target branch (src_site_id, to_take) is covered, reach : the conditional statement src_site_id is executed (either direction), sfunc : some branch inside the function enclosing the target is executed, 4. repeats steps 1-3 up to N_repeat (default 10) times for non-deterministic generators; an attempt passes as soon as one repetition passes. Paths default to the Docker image layout and can be overridden with the environment variables DIS_TARGETS, DIS_INST_SRC_MATCH and DIS_COV_UTILS_PARENT (the directory that contains the cov_utils package). Batch re-evaluation of a generator tree (/------/------------/generator.py): python3 eval.py --generators_dir /experiments/generators --model qwen-3.5-27b \ --thinking false --method claude --prog all --output_dir /tmp/results """ import argparse import io import json import os import pickle import resource import signal import sys import multiprocessing as mp from collections import defaultdict from typing import Dict, Optional, Tuple try: from tqdm import tqdm except ImportError: # tqdm is optional def tqdm(it, **kw): return it mp.set_start_method('spawn', force=True) INSTRU_BIN_DIR = os.environ.get('DIS_TARGETS', '/targets') INSTRU_SOURCE_MATCH_DIR = os.environ.get('DIS_INST_SRC_MATCH', '/inst_src_match') COV_UTILS_PARENT = os.environ.get('DIS_COV_UTILS_PARENT', '/') sys.path.insert(0, COV_UTILS_PARENT) from cov_utils import SeedRunner # noqa: E402 def raise_fd_limit(): """cov_utils' forkserver uses fixed, high file descriptors; raise the soft RLIMIT_NOFILE so that the forkserver can start inside containers.""" soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) if hard > soft: resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard)) raise_fd_limit() # The 37 DIS-Bench entry programs: prog -> [package, command-line arguments] ('@@' = input file) prog_mp = { 'bloaty_fuzz_target': ['bloaty', ['@@']], 'exiv2': ['exiv2', ['@@']], 'ffmpeg': ['ffmpeg', ['-y', '-i', '@@', '-c:v', 'mpeg4', '-c:a', 'copy', '-f', 'mp4', '/dev/null']], 'freetype2_ftfuzzer': ['freetype2', ['@@']], 'harfbuzz_hb-shape-fuzzer': ['harfbuzz', ['@@']], 'imginfo': ['jasper', ['-f', '@@']], 'infotocap': ['ncurses', ['-o', '/dev/null', '@@']], 'jhead': ['jhead', ['@@']], 'jq': ['jq', ['.', '@@']], 'lcms_cms_transform_fuzzer': ['lcms', ['@@']], 'libjpeg_turbo_fuzzer': ['libjpeg', ['@@']], 'libpcap_fuzz_both': ['libpcap', ['@@']], 'libpng_read_fuzzer': ['libpng', ['@@']], 'libxml2_xml': ['libxml2', ['@@']], 'lua': ['lua', ['@@']], 'mbedtls_fuzz_dtlsclient': ['mbedtls', ['@@']], 'mruby_fuzzer': ['mruby', ['@@']], 'mujs': ['mujs', ['@@']], 'nm-new': ['binutils', ['-A', '-a', '-l', '-S', '-s', '--special-syms', '--synthetic', '--with-symbol-versions', '-D', '@@']], 'objdump': ['binutils', ['-S', '@@']], 'openh264_decoder_fuzzer': ['openh264', ['@@']], 'openthread_ot-ip6-send-fuzzer': ['openthread', ['@@']], 'pdftotext': ['xpdf', ['@@', '/dev/null']], 'php_php-fuzz-parser': ['php', ['@@']], 'proj4_proj_crs_to_crs_fuzzer': ['proj4', ['@@']], 're2_fuzzer': ['re2', ['@@']], 'readelf': ['binutils', ['-a', '@@']], 'size': ['binutils', ['@@']], 'sndfile_fuzzer': ['libsndfile', ['@@']], 'sqlite3_ossfuzz': ['sqlite3', ['@@']], 'stb_stbi_read_fuzzer': ['stb', ['@@']], 'strip-new': ['binutils', ['@@']], 'tcpdump': ['tcpdump', ['-e', '-vv', '-nr', '@@']], 'tiff2ps': ['libtiff', ['@@']], 'tiffsplit': ['libtiff', ['@@']], 'vorbis_decode_fuzzer': ['vorbis', ['@@']], 'woff2_convert_woff2ttf_fuzzer': ['woff2', ['@@']], } def _exec_and_generate_worker(python_code, time_limit, memory_limit_mb, result_dict, key): """Worker to execute python_code and extract all possible buffers.""" import resource import builtins import types import inspect class TimeoutError(Exception): pass def timeout_handler(signum, frame): raise TimeoutError('Execution timed out') def to_bytes(val): """Convert value to bytes if possible.""" if isinstance(val, (bytes, bytearray)): return bytes(val) if isinstance(val, str): return val.encode('utf-8') return None def get_all_functions(local_ns): """Get all functions defined in the namespace.""" functions = [] for name, obj in local_ns.items(): if isinstance(obj, types.FunctionType) and not name.startswith('_'): functions.append((name, obj)) return functions def get_required_args(func): """Get the number of required arguments for a function.""" try: sig = inspect.signature(func) required = sum(1 for p in sig.parameters.values() if p.default == inspect.Parameter.empty and p.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.POSITIONAL_ONLY)) return required except Exception: return 0 try: # Set memory limit try: memory_limit_bytes = memory_limit_mb * 1024 * 1024 resource.setrlimit(resource.RLIMIT_AS, (memory_limit_bytes, memory_limit_bytes)) except Exception: pass # Set signal-based timeout signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(time_limit) # Storage for captured buffers from all methods all_buffers = [] # Setup file write hooks FIRST (before any execution) written_files = {} captured_stdout = [] original_open = builtins.open original_print = builtins.print def hooked_open(filename, mode='r', *args, **kwargs): # Handle BytesIO/StringIO if isinstance(filename, (io.BytesIO, io.StringIO)): return original_open(filename, mode, *args, **kwargs) # Normalize filename fname = None if isinstance(filename, str): fname = filename # For write modes, capture the content if fname and ('w' in mode or 'a' in mode): if 'b' in mode: # Binary mode buffer = io.BytesIO() class CaptureBinaryFile: def __init__(self): self.closed = False self.name = fname def write(self, data): buffer.write(data) return len(data) def writelines(self, lines): for line in lines: buffer.write(line) def read(self): return buffer.getvalue() def close(self): if not self.closed: written_files[fname] = buffer.getvalue() self.closed = True def __enter__(self): return self def __exit__(self, *args): self.close() return CaptureBinaryFile() else: # Text mode buffer = io.StringIO() class CaptureTextFile: def __init__(self): self.closed = False self.name = fname def write(self, data): buffer.write(data) return len(data) def writelines(self, lines): for line in lines: buffer.write(line) def read(self): return buffer.getvalue() def close(self): if not self.closed: written_files[fname] = buffer.getvalue().encode('utf-8') self.closed = True def __enter__(self): return self def __exit__(self, *args): self.close() return CaptureTextFile() return original_open(filename, mode, *args, **kwargs) def hooked_print(*args, **kwargs): output = ' '.join(str(arg) for arg in args) captured_stdout.append(output.encode('utf-8')) # Apply hooks BEFORE execution builtins.open = hooked_open builtins.print = hooked_print try: # Execute code with hooks in place local_ns = {} exec(python_code, local_ns, local_ns) # Method 1: Try generate_buf first if 'generate_buf' in local_ns: try: buf = local_ns['generate_buf']() buf_bytes = to_bytes(buf) if buf_bytes: all_buffers.append(buf_bytes) except Exception: pass # Method 2: Find all functions and try calling them # Functions may write to files during execution functions = get_all_functions(local_ns) for func_name, func_obj in functions: if func_name == 'generate_buf': continue # Already tried try: num_required = get_required_args(func_obj) if num_required == 0: result = func_obj() buf_bytes = to_bytes(result) if buf_bytes: all_buffers.append(buf_bytes) elif num_required == 1: # Function likely takes a filename argument # Call with a dummy filename to trigger file write result = func_obj('/tmp/buffer.bin') buf_bytes = to_bytes(result) if buf_bytes: all_buffers.append(buf_bytes) except Exception: pass finally: # Restore original functions builtins.open = original_open builtins.print = original_print # Collect all captured buffers # From file writes for fname, content in written_files.items(): if content: all_buffers.append(content) # From stdout for content in captured_stdout: if content: all_buffers.append(content) signal.alarm(0) # Return ALL available buffers if all_buffers: result_dict[key] = (True, all_buffers, None, 'success') return # No buffer found result_dict[key] = (False, [], 'no buffer found', 'missing_function') except TimeoutError: result_dict[key] = (False, [], 'timeout', 'timeout') except MemoryError: result_dict[key] = (False, [], 'memory_limit_exceeded', 'memory_exceeded') except SyntaxError as e: result_dict[key] = (False, [], f'syntax_error: {str(e)}', 'syntax_error') except NameError as e: result_dict[key] = (False, [], f'name_error: {str(e)}', 'name_error') except ImportError as e: result_dict[key] = (False, [], f'import_error: {str(e)}', 'import_error') except TypeError as e: result_dict[key] = (False, [], f'type_error: {str(e)}', 'type_error') except ValueError as e: result_dict[key] = (False, [], f'value_error: {str(e)}', 'value_error') except Exception as e: result_dict[key] = (False, [], str(e), 'runtime_error') def exec_and_generate_with_limits(python_code, time_limit=1, memory_limit=100): """Execute python_code and extract ALL possible buffers. Returns: tuple: (success, buffers_list, error_msg, execution_status) buffers_list: list of all extracted buffers execution_status is one of: 'success', 'timeout', 'memory_exceeded', 'syntax_error', 'name_error', 'import_error', 'type_error', 'value_error', 'runtime_error', 'missing_function', 'invalid_type', 'no_result' """ with mp.Manager() as manager: result_dict = manager.dict() key = 'result' p = mp.Process(target=_exec_and_generate_worker, args=(python_code, time_limit, memory_limit, result_dict, key)) p.start() p.join(timeout=time_limit + 1) if p.is_alive(): # Try SIGTERM first p.terminate() p.join(timeout=0.5) if p.is_alive(): # Force kill with SIGKILL try: os.kill(p.pid, signal.SIGKILL) except: pass p.join(timeout=0.5) return (False, [], 'timeout', 'timeout') if key in result_dict: return result_dict[key] return (False, [], 'no_result', 'no_result') def load_if_info(prog: str) -> Tuple[dict, dict, list]: """Load if_info from pkl file for a program.""" pkl_path = os.path.join(INSTRU_SOURCE_MATCH_DIR, f'{prog}.pkl') if not os.path.exists(pkl_path): return None, None, None with open(pkl_path, 'rb') as f: br_mp, if_site_id_mp, if_info = pickle.load(f) return br_mp, if_site_id_mp, if_info def get_func_name_for_site(if_info: list, src_site_id: int) -> Optional[str]: """ Get the function name for a given src_site_id from if_info. if_info is a list where index = src_site_id. Each element is a tuple: (full_if_stmt, cond_stmt, then_stmt, else_stmt, func_name) Each of these is (text, (file, start_line, start_col, end_line, end_col)) or None. """ if if_info is None or src_site_id >= len(if_info): return None info_tuple = if_info[src_site_id] if info_tuple is None or len(info_tuple) < 5: return None func_name = info_tuple[4] return func_name def build_site_to_func_map(if_info: list) -> Dict[int, str]: """Build a mapping from src_site_id to function name.""" site_to_func = {} if if_info is None: return site_to_func for src_site_id, info_tuple in enumerate(if_info): if info_tuple is not None and len(info_tuple) >= 5: func_name = info_tuple[4] if func_name is not None: site_to_func[src_site_id] = func_name return site_to_func def verify_res_repeat_rnr(python_code, prog, src_site_id, to_take, N_repeat, rnr=None, if_info=None, site_to_func=None): """ Verify if python_code can generate buffers that cover the target branch. Tests ALL extracted buffers for each attempt. Returns a dict with: - pass: True if the target branch (src_site_id, to_take) was covered - reach: True if the conditional statement was executed (either direction) - sfunc: True if the function containing the target branch was entered - error: error message if any - exec_status: execution status of the code """ result = { 'pass': False, 'reach': False, 'sfunc': False, 'error': None, 'exec_status': 'unknown' } if rnr is None: binary = os.path.join(INSTRU_BIN_DIR, prog) if prog not in prog_mp: result['error'] = 'prog not in prog_mp' result['exec_status'] = 'invalid_prog' return result _, args = prog_mp[prog] exe_arg = [binary] + args pkl_path = os.path.join(INSTRU_SOURCE_MATCH_DIR, f'{prog}.pkl') if not os.path.exists(pkl_path): result['error'] = 'pkl file not found' result['exec_status'] = 'missing_pkl' return result with open(pkl_path, 'rb') as f: br_mp, _, if_info = pickle.load(f) try: rnr = SeedRunner(binary, exe_arg, br_mp=br_mp) except Exception as e: result['error'] = f'Failed to create SeedRunner: {e}' result['exec_status'] = 'seedrunner_error' return result site_to_func = build_site_to_func_map(if_info) should_end = True else: should_end = False target_func_name = get_func_name_for_site(if_info, src_site_id) if if_info else None try: for attempt in range(N_repeat): # Execute code and generate ALL possible buffers success, buffers, error, exec_status = exec_and_generate_with_limits(python_code, time_limit=1, memory_limit=100) result['exec_status'] = exec_status if not success: if result['error'] is None: result['error'] = error continue # Test ALL extracted buffers for buf in buffers: if prog == 'libxml2_xml': buf = b'\x06\x00\x00\x00a.xml\x5c\x0a' + buf + b'\x0a\x5c\x0a' try: _, _ = rnr.run_with_seed(buf) src_path = rnr.get_source_path() # Check pass: target branch covered if (src_site_id, to_take) in src_path: result['pass'] = True result['reach'] = True # pass implies reach result['sfunc'] = True # pass implies sfunc result['exec_status'] = 'success' return result # Check reach: either direction of the target branch site if (src_site_id, 0) in src_path or (src_site_id, 1) in src_path: result['reach'] = True result['sfunc'] = True # reach implies sfunc # Check sfunc: any branch in the target function was covered if target_func_name is not None: for (site_id, taken) in src_path: site_func = site_to_func.get(site_id) if site_func == target_func_name: result['sfunc'] = True break except Exception as e: if result['error'] is None: result['error'] = str(e) continue # If we got some results from this attempt, update status if result['reach'] or result['sfunc']: result['exec_status'] = 'success' return result finally: if should_end and rnr is not None: try: rnr.end() except: pass def verify_multiple(prog, python_codes, branches, N_repeat=10, verbose=False): """Evaluate several generators of one program with a single SeedRunner. python_codes[i] is evaluated against branches[i] = (src_site_id, to_take); returns a list of result dicts (see verify_res_repeat_rnr).""" assert len(python_codes) == len(branches) binary = os.path.join(INSTRU_BIN_DIR, prog) _, args = prog_mp[prog] br_mp, _, if_info = load_if_info(prog) rnr = SeedRunner(binary, [binary] + args, br_mp=br_mp) site_to_func = build_site_to_func_map(if_info) out = [] try: for code, (sid, tt) in tqdm(list(zip(python_codes, branches)), desc=prog, disable=not verbose): if code is None: out.append({'pass': False, 'reach': False, 'sfunc': False, 'error': 'generator.py not found', 'exec_status': 'missing_generator'}) continue out.append(verify_res_repeat_rnr(code, prog, sid, tt, N_repeat, rnr=rnr, if_info=if_info, site_to_func=site_to_func)) finally: try: rnr.end() except Exception: pass return out def parse_attempt_dirname(dirname): """------------ (explicit '---' delimiter, so model names containing '.' or '-' are parsed correctly).""" parts = dirname.split('---') if len(parts) != 5: return None model, prog, sid, tt, try_id = parts try: return model, prog, int(sid), int(tt), int(try_id) except ValueError: return None def evaluate_generator_tree(generators_dir, model, thinking, method, prog, N_repeat=10, verbose=True): """Evaluate every attempt of (model, thinking, method, prog) found under generators_dir. Attempt directories without generator.py are not present in the released tree; pass dataset-derived attempt lists to verify_multiple() to score them as 'missing_generator'.""" run_dir = os.path.join(generators_dir, f"{model}---{'thinking' if thinking else 'nothinking'}---{method}") attempts = [] for d in sorted(os.listdir(run_dir)): parsed = parse_attempt_dirname(d) if parsed is None or parsed[1] != prog: continue attempts.append((parsed, os.path.join(run_dir, d, 'generator.py'))) codes = [open(p).read() if os.path.exists(p) else None for _, p in attempts] res = verify_multiple(prog, codes, [(a[2], a[3]) for a, _ in attempts], N_repeat, verbose) results = [] for (m, pg, sid, tt, try_id), path in attempts: r = res[len(results)] results.append({'model': model, 'thinking': thinking, 'method': method, 'prog': pg, 'src_site_id': sid, 'to_take': tt, 'try_id': try_id, 'generator_exists': os.path.exists(path), **r}) return results def main(): ap = argparse.ArgumentParser(description='Re-evaluate a DIS-Bench generator tree (pass / reach / sfunc).') ap.add_argument('--generators_dir', required=True) ap.add_argument('--model', required=True) ap.add_argument('--thinking', choices=['true', 'false'], required=True) ap.add_argument('--method', required=True, help='rag, miniswe, openhands, claude, rag_fo, rag_lc or rag_dense') ap.add_argument('--prog', default='all', help='a program name, or "all"') ap.add_argument('--N_repeat', type=int, default=10) ap.add_argument('--output_dir', required=True) a = ap.parse_args() thinking = a.thinking == 'true' os.makedirs(a.output_dir, exist_ok=True) progs = sorted(prog_mp) if a.prog == 'all' else [a.prog] for prog in progs: results = evaluate_generator_tree(a.generators_dir, a.model, thinking, a.method, prog, a.N_repeat) if not results: continue out = os.path.join(a.output_dir, f"{a.method}_{a.model}_{'thinking' if thinking else 'nothinking'}_{prog}.json") with open(out, 'w') as f: json.dump({'results': results}, f, indent=1) print(f'{prog}: {sum(r["pass"] for r in results)}/{len(results)} pass -> {out}') if __name__ == '__main__': main()