From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.197 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795391967; b=DmKGkF1vCfiZvITTz6wjoA07Z0T3knMJZDZ36g07zV/zn61q2FXtdGLjljuQeC0MRISU ojLz39EpQQXFCQJ9CLik8nlcNvwbYPU4MZHwfd3uf5M+zEWPD5h80h2fGUP4Nupzs4VPm ol+FlcvQ8dhkDO9W443sFhkXjC0t+bK9wmSpMOiQE67WlaKeezbYYg4MfekEicK15Szc9 v1wlihJEHA1oWZ7I25aG8cbWE/NMKjPiwbwBxHrFD7VJZWwujJ3/vGseHRmmlamhV/Fj6 oTzdCZvJEUyg706vAlnq08aL05WC1zcU25CnpB4QlOtjf/YQ5GQ0+l+x2lPI6hmtTpw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795391967; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=6YYhm9IxKJacmBRPk1BwBojwdCvDw+zld1+t11skAg0=; b=KXDmVrrUuT+nDmcvbowU4uqb+oOi+LmU6yS2UcWw1lDMtiuO9PxmhkhvSoE+u4hPu3PV rZGiap5PkbDonQOW0EOh3UEI3F/a25/wbKzr0NQ3HUy+9C3h0gVaYe2Se/Lla+LLykjrU EUqvQaDwin0V9l7fqFeUWhLtmSR7uZSSvMV51wLcDgSIACtRyvtdOIwJ638/mhvxP6+wR kD9KRgN9Ec/gDt9dv5rxjG2wOQyfbwunuLG2FwVseQR42nsZGG/84lLcrBJCmW6UjHnVB DLh+Tw++J723uSFlrGyrq6JNoPhOJcSRhcEYbp9pSZdJmu4r4E9KqShcwkadKB2fv2Q== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=lMjtMZth; arc=none smtp.remote-ip=74.125.82.197 Received: from mail-dy1-f197.google.com (mail-dy1-f197.google.com [74.125.82.197]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 31E3B606A69C for ; Sun, 22 Nov 2026 23:59:26 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 31E3B606A69C Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--irogers.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=lMjtMZth Received: by mail-dy1-f197.google.com with SMTP id 5a478bee46e88-30bcb065bfdso3111266eec.0 for ; Sun, 22 Nov 2026 15:59:26 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795391965; x=1795996765; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=6YYhm9IxKJacmBRPk1BwBojwdCvDw+zld1+t11skAg0=; b=lMjtMZthZUXpKfPu5kZBCNp7gCDCM6UH/QcNlg9HxpmrR6mKVVBMNgQz2treNcuJXs Ld1fELdksbMZfOmGDYHRDv4YIwHxhdR3DxL4m0rSJdJF7kdNtxNOOsi24GUXXZ8WLFld 5dA9UXX+mPu/9toRKZKIBQJUe5wzI6aWLvXx0Vam3k7GbMhTlZkcekzMl7WR4P8yAyRI FZHLcwVTLLOyNaHvB2691/eUnlZqoyPlLbrdzYJ1gQjrVOsuZHigVUOn1VCGUmTTHDsq w2g2qLFgFRDEnzyQSBKOw60U+UluUX0I+QKYDb4Fx0/a9wWJBYRZXlEr5Mkb8AauB2x5 INCw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795391965; x=1795996765; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=6YYhm9IxKJacmBRPk1BwBojwdCvDw+zld1+t11skAg0=; b=hRr48EyeHqNzC/1ZyQ4QlBMHma/cBLLlF7tqa/Vdmf+V/G6Yuf0IsaSYvUfiAqF9Yh Kqw1KiTEX0IoaJ9B+qIxVpT8SybMCvYnjO3JYRf+purieOV0h+HHg7I+EIJmNTCoTzPX qCOR1N/QDSnJlpv/KP5pRKPQMCb4JzW5T8+DXiPY/kjznVPxRWn8x9GxnkTpGRRPEckk q2XDjebaMAquKS35/ZntoAuiz7U/2gCaJ2j3pB6MfopZPLky2slDhW2+RJ2oDrRrvEZE ITbPNNcNOWn/RoAUO0lDpzbwm+rhybSlnoLA2X7aRxW+M5OKR68OrJMmWuyiHSGpuJV/ CuRA== X-Forwarded-Encrypted: i=1; AL+hErG7gfAdY/e4o5nP2E0WWxrjrjncf5UBjFa5xv3//zYycTKJRlnYebNv9IOVj/UTZn14mgI=@vger.kernel.org X-Gm-Message-State: APuU4Z9XlmEpw9lN8KHIxORcmBCcTNKjrN28D5oXaXU8qTLfoo2teIGV /Il+k4/wD/iAWir+NedAwltk3hZOuAsEySJ0237tzbm3pGjxmztIpgtyqzLOJNASEGE/hrng31U QYOLric8Bgg== X-Received: from dybqo16.prod.google.com ([2002:a05:7301:6790:b0:36a:de0:d28a]) (user=irogers job=prod-delivery.src-stubby-dispatcher) by 2002:a05:7300:6da7:b0:384:5885:2f81 with SMTP id 5a478bee46e88-3856c0c7c05mr14446912eec.5.1795391964567; Sun, 22 Nov 2026 15:59:24 -0800 (PST) Date: Sun, 22 Nov 2026 15:57:57 -0800 In-Reply-To: <20261122235757.3456048-1-irogers@google.com> X-Mailing-List: bpf@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261122235757.3456048-1-irogers@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261122235757.3456048-12-irogers@google.com> Subject: [RFC PATCH v1 11/11] scripts: Add eh_frame_min.py .eh_frame coverage and size analyzer From: Ian Rogers To: linux-kernel@vger.kernel.org, linux-trace-kernel@vger.kernel.org, linux-arch@vger.kernel.org Cc: jpoimboe@kernel.org, rostedt@goodmis.org, peterz@infradead.org, mingo@redhat.com, tglx@kernel.org, bp@alien8.de, dave.hansen@linux.intel.com, x86@kernel.org, catalin.marinas@arm.com, will@kernel.org, mark.rutland@arm.com, linux-arm-kernel@lists.infradead.org, pjw@kernel.org, palmer@dabbelt.com, aou@eecs.berkeley.edu, alex@ghiti.fr, linux-riscv@lists.infradead.org, acme@kernel.org, namhyung@kernel.org, linux-perf-users@vger.kernel.org, mhiramat@kernel.org, ast@kernel.org, daniel@iogearbox.net, andrii@kernel.org, bpf@vger.kernel.org, nathan@kernel.org, nsc@kernel.org, linux-kbuild@vger.kernel.org, ojeda@kernel.org, rust-for-linux@vger.kernel.org, ardb@kernel.org, linux-efi@vger.kernel.org, maz@kernel.org, oupton@kernel.org, kvmarm@lists.linux.dev, shuah@kernel.org, linux-kselftest@vger.kernel.org, indu.bhagat@oracle.com, jremus@linux.ibm.com, wnliu@google.com, dylanbhatch@google.com, Ian Rogers Content-Type: text/plain; charset="UTF-8" Add an optional standalone developer inspection script (scripts/eh_frame_min.py, not invoked by Kbuild) to analyze ELF32/ELF64 relocatable objects (.o, .ko), vmlinux images, user-space executables, and shared libraries across x86_64, i386, arm64, arm, and riscv. It reports .text / .eh_frame / .eh_frame_hdr / .sframe / .orc_unwind section sizes, simulated minified .eh_frame savings, Minimal DWARF FDE coverage (and breakdown of any unsupported opcodes), kept FP/RA vs. ignored GPR register rules, maximum DW_CFA_remember_state depth, and top DWARF CFA opcode counts. Example usage: $ ./scripts/eh_frame_min.py vmlinux $ ./scripts/eh_frame_min.py mm/vmscan.o kernel/fork.o $ ./scripts/eh_frame_min.py /bin/bash /lib/x86_64-linux-gnu/libc.so.6 $ ./scripts/eh_frame_min.py --minify /tmp/eh_frame.min mm/vmscan.o Signed-off-by: Ian Rogers --- scripts/eh_frame_min.py | 938 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 938 insertions(+) create mode 100755 scripts/eh_frame_min.py diff --git a/scripts/eh_frame_min.py b/scripts/eh_frame_min.py new file mode 100755 index 000000000000..6a64563a7c40 --- /dev/null +++ b/scripts/eh_frame_min.py @@ -0,0 +1,938 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +""" +Offline ELF .eh_frame / Minimal DWARF CFA coverage and size analyzer. + +Note: This script is a standalone developer/benchmarking inspection tool and +is NOT invoked during Kbuild (which uses the standalone C host tool in +scripts/min_eh_frame.c when CONFIG_UNWINDER_DWARF_CFI_MINIFY=y). + +It parses ELF32/ELF64 relocatable objects (.o, .ko), vmlinux images, user +executables, and shared libraries across x86_64, i386, arm64, arm, and riscv, +reporting: + - .text, .eh_frame, .eh_frame_hdr, .sframe, and .orc_unwind section sizes + - Simulated minified .eh_frame + .eh_frame_hdr sizes and byte savings + - Minimal DWARF CFA FDE coverage (supported vs. unsupported FDEs & reasons) + - Kept FP/RA register rules vs. ignored general-purpose register spill ops + - Maximum DW_CFA_remember_state nesting depth and top DWARF CFA opcodes + +Example usage (from the kernel tree root, invoke via ./scripts/eh_frame_min*): + 1. Analyze a built vmlinux image (with or without build-time minification): + $ eh_frame_min.py vmlinux + + 2. Compare multiple kernel objects, loadable modules, or cross-arch builds: + $ eh_frame_min.py mm/vmscan.o kernel/fork.o fs/ext4/inode.o + $ eh_frame_min.py build_arm64/vmlinux build_riscv/vmlinux + + 3. Analyze existing user-space binaries and shared libraries: + $ eh_frame_min.py /bin/bash /lib/x86_64-linux-gnu/libc.so.6 + + 4. Emit a standalone minified .eh_frame section blob for differential tests: + $ eh_frame_min.py --minify /tmp/eh_frame.min mm/vmscan.o + +Example output: + === build_arm64/vmlinux (arm64) === + .text size : 18,500,228 B + Original .eh_frame : 2,294,092 B (1 CIEs, 69,765 FDEs) + Original .eh_frame_hdr : 558,132 B (combined: 2,852,224 B) + Minified .eh_frame : 2,285,920 B (1 CIEs, -0.4% vs .eh_frame) + Minified + .eh_frame_hdr: 2,844,052 B (-0.3% combined) + FDE bytecode payload : 1,108,067 B -> 953,348 B (avg 13.7 B/FDE) + .sframe section : 2,938,460 B + Minimal DWARF coverage : 69,765 / 69,765 FDEs (100.00%) + Register ops kept/skip : 125,630 kept (FP/RA), 0 ignored (other GPRs/args) + Max remember_state depth: 1 +""" + +import argparse +import os +import struct +import sys +from collections import Counter + +# DWARF register numbers per ELF e_machine (drap = transient stack-realign scratch regs) +ARCH_REGS = { + 62: {"name": "x86_64", "sp": 7, "fp": 6, "ra": 16, "drap": {1, 2, 5, 10, 13}}, # EM_X86_64 + 3: {"name": "i386", "sp": 4, "fp": 5, "ra": 8, "drap": {1, 2}}, # EM_386 + 40: {"name": "arm", "sp": 13, "fp": 11, "ra": 14, "drap": set()}, # EM_ARM + 183: {"name": "arm64", "sp": 31, "fp": 29, "ra": 30, "drap": set()}, # EM_AARCH64 + 243: {"name": "riscv", "sp": 2, "fp": 8, "ra": 1, "drap": set()}, # EM_RISCV +} + +DW_CFA_nop = 0x00 +DW_CFA_set_loc = 0x01 +DW_CFA_advance_loc1 = 0x02 +DW_CFA_advance_loc2 = 0x03 +DW_CFA_advance_loc4 = 0x04 +DW_CFA_offset_extended = 0x05 +DW_CFA_restore_extended = 0x06 +DW_CFA_undefined = 0x07 +DW_CFA_same_value = 0x08 +DW_CFA_register = 0x09 +DW_CFA_remember_state = 0x0a +DW_CFA_restore_state = 0x0b +DW_CFA_def_cfa = 0x0c +DW_CFA_def_cfa_register = 0x0d +DW_CFA_def_cfa_offset = 0x0e +DW_CFA_def_cfa_expression = 0x0f +DW_CFA_expression = 0x10 +DW_CFA_offset_extended_sf = 0x11 +DW_CFA_def_cfa_sf = 0x12 +DW_CFA_def_cfa_offset_sf = 0x13 +DW_CFA_val_offset = 0x14 +DW_CFA_val_offset_sf = 0x15 +DW_CFA_val_expression = 0x16 +DW_CFA_AARCH64_negate_ra_state = 0x2d +DW_CFA_GNU_args_size = 0x2e +DW_CFA_GNU_negative_offset_extended = 0x2f + +OPCODE_NAMES = { + 0x00: "DW_CFA_nop", + 0x01: "DW_CFA_set_loc", + 0x02: "DW_CFA_advance_loc1", + 0x03: "DW_CFA_advance_loc2", + 0x04: "DW_CFA_advance_loc4", + 0x05: "DW_CFA_offset_extended", + 0x06: "DW_CFA_restore_extended", + 0x07: "DW_CFA_undefined", + 0x08: "DW_CFA_same_value", + 0x09: "DW_CFA_register", + 0x0a: "DW_CFA_remember_state", + 0x0b: "DW_CFA_restore_state", + 0x0c: "DW_CFA_def_cfa", + 0x0d: "DW_CFA_def_cfa_register", + 0x0e: "DW_CFA_def_cfa_offset", + 0x0f: "DW_CFA_def_cfa_expression", + 0x10: "DW_CFA_expression", + 0x11: "DW_CFA_offset_extended_sf", + 0x12: "DW_CFA_def_cfa_sf", + 0x13: "DW_CFA_def_cfa_offset_sf", + 0x14: "DW_CFA_val_offset", + 0x15: "DW_CFA_val_offset_sf", + 0x16: "DW_CFA_val_expression", + 0x2d: "DW_CFA_negate_ra_state/window_save", + 0x2e: "DW_CFA_GNU_args_size", + 0x2f: "DW_CFA_GNU_negative_offset_extended", +} + +DW_EH_PE_omit = 0xff +DW_EH_PE_absptr = 0x00 +DW_EH_PE_uleb128 = 0x01 +DW_EH_PE_udata2 = 0x02 +DW_EH_PE_udata4 = 0x03 +DW_EH_PE_udata8 = 0x04 +DW_EH_PE_sleb128 = 0x09 +DW_EH_PE_sdata2 = 0x0a +DW_EH_PE_sdata4 = 0x0b +DW_EH_PE_sdata8 = 0x0c +DW_EH_PE_pcrel = 0x10 +DW_EH_PE_indirect = 0x80 + + +def read_uleb128(buf, pos, end): + val = 0 + shift = 0 + while pos < end: + b = buf[pos] + pos += 1 + val |= (b & 0x7f) << shift + if not (b & 0x80): + return val, pos + shift += 7 + if shift > 63: + raise ValueError("ULEB128 overflow") + raise ValueError("Truncated ULEB128") + + +def read_sleb128(buf, pos, end): + val = 0 + shift = 0 + while pos < end: + b = buf[pos] + pos += 1 + val |= (b & 0x7f) << shift + shift += 7 + if not (b & 0x80): + if b & 0x40: + val |= -(1 << shift) + return val, pos + if shift > 63: + raise ValueError("SLEB128 overflow") + raise ValueError("Truncated SLEB128") + + +def encode_uleb128(val): + if val < 0: + raise ValueError("Negative ULEB128") + out = bytearray() + while True: + b = val & 0x7f + val >>= 7 + if val: + b |= 0x80 + out.append(b) + if not val: + break + return bytes(out) + + +def encode_sleb128(val): + out = bytearray() + more = True + while more: + b = val & 0x7f + val >>= 7 + if (val == 0 and not (b & 0x40)) or (val == -1 and (b & 0x40)): + more = False + else: + b |= 0x80 + out.append(b) + return bytes(out) + + +def encoded_ptr_size(enc, addr_size): + if enc == DW_EH_PE_omit: + return 0 + fmt = enc & 0x0f + if fmt == DW_EH_PE_absptr: + return addr_size + if fmt in (DW_EH_PE_udata2, DW_EH_PE_sdata2): + return 2 + if fmt in (DW_EH_PE_udata4, DW_EH_PE_sdata4): + return 4 + if fmt in (DW_EH_PE_udata8, DW_EH_PE_sdata8): + return 8 + return None + + +def read_encoded_ptr(buf, pos, end, enc, addr_size, sec_vaddr): + if enc == DW_EH_PE_omit: + return 0, pos + orig_pos = pos + fmt = enc & 0x0f + if fmt == DW_EH_PE_absptr: + fmt_str = "= e_shnum: + raise ValueError("ELF has invalid section header counts") + + shdrs = [] + for i in range(e_shnum): + off = e_shoff + i * e_shentsize + shdrs.append(struct.unpack_from(sh_fmt, data, off)) + + shstr_off = shdrs[e_shstrndx][4] + shstr_sz = shdrs[e_shstrndx][5] + shstrtab = data[shstr_off : shstr_off + shstr_sz] + + for sh in shdrs: + sh_name_idx = sh[0] + sh_type = sh[1] + sh_addr = sh[3] + sh_offset = sh[4] + sh_size = sh[5] + end_idx = shstrtab.find(b"\x00", sh_name_idx) + name = shstrtab[sh_name_idx:end_idx].decode("utf-8", errors="replace") + # SHT_NOBITS == 8 + sec_bytes = b"" if sh_type == 8 else data[sh_offset : sh_offset + sh_size] + if name in sections: + # Accumulate sizes for multi-section objects (e.g. .text.*) + prev_addr, prev_sz, prev_b = sections[name] + sections[name] = (prev_addr, prev_sz + sh_size, prev_b) + else: + sections[name] = (sh_addr, sh_size, sec_bytes) + + return e_machine, addr_size, sections + + +def parse_cie(buf, entry_off, body_off, entry_end, addr_size, sec_vaddr): + pos = body_off + version = buf[pos] + pos += 1 + nul = buf.find(b"\x00", pos, entry_end) + if nul < 0: + raise ValueError("Unterminated CIE augmentation string") + aug = buf[pos:nul].decode("ascii", errors="replace") + pos = nul + 1 + + if version == 4: + addr_size = buf[pos] + seg_size = buf[pos + 1] + pos += 2 + if seg_size != 0: + raise ValueError("Non-zero segment selector size") + + code_align, pos = read_uleb128(buf, pos, entry_end) + data_align, pos = read_sleb128(buf, pos, entry_end) + if version == 1: + ra_reg = buf[pos] + pos += 1 + else: + ra_reg, pos = read_uleb128(buf, pos, entry_end) + + fde_enc = DW_EH_PE_absptr + lsda_enc = DW_EH_PE_omit + has_z = False + is_signal = False + has_indirect = False + + if aug.startswith("z"): + has_z = True + aug_len, pos = read_uleb128(buf, pos, entry_end) + aug_end = pos + aug_len + ap = pos + for ch in aug[1:]: + if ch == "L": + lsda_enc = buf[ap] + if lsda_enc != DW_EH_PE_omit and (lsda_enc & DW_EH_PE_indirect): + has_indirect = True + ap += 1 + elif ch == "P": + p_enc = buf[ap] + ap += 1 + if p_enc & DW_EH_PE_indirect: + has_indirect = True + _, ap = read_encoded_ptr(buf, ap, aug_end, p_enc & ~DW_EH_PE_indirect, addr_size, sec_vaddr) + elif ch == "R": + fde_enc = buf[ap] + if fde_enc & DW_EH_PE_indirect: + has_indirect = True + ap += 1 + elif ch == "S": + is_signal = True + elif ch == "B": + # BTI / PAC key on arm64 + pass + else: + raise ValueError(f"Unknown CIE augmentation '{ch}' in '{aug}'") + pos = aug_end + elif aug != "": + raise ValueError(f"Unsupported non-z CIE augmentation '{aug}'") + + return { + "offset": entry_off, + "version": version, + "aug": aug, + "addr_size": addr_size, + "code_align": code_align, + "data_align": data_align, + "ra_reg": ra_reg, + "fde_enc": fde_enc, + "lsda_enc": lsda_enc, + "has_z": has_z, + "is_signal": is_signal, + "has_indirect_fde": bool(fde_enc & DW_EH_PE_indirect), + "insns": bytes(buf[pos:entry_end]), + } + + +def decode_and_minify_insns(insns, cie, arch, init_row=None, is_cie=False): + """ + Decode CFI instructions, validate against Minimal DWARF subset, and emit + minified instructions keeping only PC advances and {CFA(SP|FP), FP, RA}. + """ + sp_reg = arch["sp"] + fp_reg = arch["fp"] + ra_reg = cie["ra_reg"] + tracked_regs = {fp_reg, ra_reg} + + pos = 0 + end = len(insns) + op_counts = Counter() + ignored_reg_ops = 0 + kept_reg_ops = 0 + max_state_depth = 0 + reasons = [] + + if init_row is None: + row = { + "cfa_reg": None, + "cfa_off": 0, + "fp": ("same", 0), + "ra": ("same", 0), + "ra_signed": False, + } + else: + row = dict(init_row) + + cie_base_row = dict(row) + state_stack = [] + + # Stream of abstract events: ("adv", delta_units) or ("op", raw_bytes, new_row_snapshot) + events = [] + pending_adv = 0 + + def emit_op(raw_bytes): + nonlocal pending_adv + if pending_adv > 0 and not is_cie: + events.append(("adv", pending_adv)) + pending_adv = 0 + events.append(("op", raw_bytes)) + + while pos < end: + op = insns[pos] + pos += 1 + hi = op & 0xc0 + lo = op & 0x3f + + if hi == 0x40: + op_counts["DW_CFA_advance_loc"] += 1 + pending_adv += lo + continue + if hi == 0x80: + op_counts["DW_CFA_offset"] += 1 + reg = lo + uoff, pos = read_uleb128(insns, pos, end) + off = uoff * cie["data_align"] + if reg in tracked_regs: + kept_reg_ops += 1 + key = "fp" if reg == fp_reg else "ra" + if row[key] != ("off", off): + row[key] = ("off", off) + emit_op(bytes([0x80 | reg]) + encode_uleb128(uoff)) + else: + ignored_reg_ops += 1 + continue + if hi == 0xc0: + op_counts["DW_CFA_restore"] += 1 + reg = lo + if reg in tracked_regs: + kept_reg_ops += 1 + key = "fp" if reg == fp_reg else "ra" + if row[key] != cie_base_row[key]: + row[key] = cie_base_row[key] + emit_op(bytes([0xc0 | reg])) + else: + ignored_reg_ops += 1 + continue + + name = OPCODE_NAMES.get(op, f"DW_CFA_unknown_0x{op:02x}") + op_counts[name] += 1 + + if op == DW_CFA_nop: + continue + elif op == DW_CFA_advance_loc1: + pending_adv += insns[pos] + pos += 1 + elif op == DW_CFA_advance_loc2: + pending_adv += struct.unpack_from(" 4: + reasons.append(f"remember_state depth={len(state_stack)} > 4") + elif op == DW_CFA_restore_state: + if not state_stack: + reasons.append("unmatched restore_state") + else: + saved_row, rem_idx = state_stack.pop() + if saved_row != row: + row = saved_row + emit_op(bytes([DW_CFA_restore_state])) + else: + # Nothing in {CFA, FP, RA} changed inside remember/restore! + # If remember_state is only followed by adv, elide the pair. + elided = False + if rem_idx < len(events) and events[rem_idx] == ("op", bytes([DW_CFA_remember_state])): + if all(ev[0] == "adv" for ev in events[rem_idx + 1:]): + extra_adv = sum(ev[1] for ev in events[rem_idx + 1:]) + del events[rem_idx:] + pending_adv += extra_adv + elided = True + if not elided: + emit_op(bytes([DW_CFA_restore_state])) + elif op == DW_CFA_GNU_args_size: + _, pos = read_uleb128(insns, pos, end) + ignored_reg_ops += 1 + elif op == DW_CFA_AARCH64_negate_ra_state and arch["name"] == "arm64": + row["ra_signed"] = not row["ra_signed"] + emit_op(bytes([DW_CFA_AARCH64_negate_ra_state])) + elif op == DW_CFA_def_cfa_expression: + expr_len, pos = read_uleb128(insns, pos, end) + expr = insns[pos : pos + expr_len] + pos += expr_len + # Fixed DRAP / sigframe pattern: DW_OP_breg(FP|SP) , DW_OP_deref + if (len(expr) >= 3 and expr[-1] == 0x06 and + expr[0] in (0x70 + fp_reg, 0x70 + sp_reg)): + soff, epos = read_sleb128(expr, 1, len(expr) - 1) + if epos == len(expr) - 1: + kind = "fp_indirect" if expr[0] == (0x70 + fp_reg) else "sp_indirect" + row["cfa_reg"] = (kind,) + row["cfa_off"] = soff + emit_op(bytes([DW_CFA_def_cfa_expression]) + encode_uleb128(len(expr)) + expr) + continue + reasons.append(name) + elif op in (DW_CFA_expression, DW_CFA_val_expression): + reg, pos = read_uleb128(insns, pos, end) + expr_len, pos = read_uleb128(insns, pos, end) + expr = insns[pos : pos + expr_len] + pos += expr_len + if reg == sp_reg: + if (op == DW_CFA_expression and len(expr) >= 2 and + expr[0] == (0x70 + sp_reg) and row["cfa_reg"] == ("sp_indirect",)): + soff, epos = read_sleb128(expr, 1, len(expr)) + if epos == len(expr) and soff == row["cfa_off"]: + ignored_reg_ops += 1 + continue + reasons.append(f"{name} r{reg}") + continue + if reg not in tracked_regs: + ignored_reg_ops += 1 + continue + # Fixed DRAP / sigframe save pattern: DW_CFA_expression(FP|RA, DW_OP_breg(FP|SP) ) + if (op == DW_CFA_expression and len(expr) >= 2 and + expr[0] in (0x70 + fp_reg, 0x70 + sp_reg)): + soff, epos = read_sleb128(expr, 1, len(expr)) + if epos == len(expr) and (reg == fp_reg or expr[0] == (0x70 + sp_reg)): + kept_reg_ops += 1 + rule = "fp_off" if expr[0] == (0x70 + fp_reg) else "sp_off" + row["fp" if reg == fp_reg else "ra"] = (rule, soff) + emit_op(bytes([DW_CFA_expression]) + encode_uleb128(reg) + + encode_uleb128(len(expr)) + expr) + continue + reasons.append(f"{name} r{reg}") + elif op == DW_CFA_register: + r1, pos = read_uleb128(insns, pos, end) + r2, pos = read_uleb128(insns, pos, end) + if r1 in tracked_regs or r1 == sp_reg: + reasons.append(f"DW_CFA_register r{r1}->r{r2}") + else: + ignored_reg_ops += 1 + elif op == DW_CFA_val_offset: + r1, pos = read_uleb128(insns, pos, end) + _, pos = read_uleb128(insns, pos, end) + if r1 in tracked_regs or r1 == sp_reg: + reasons.append(f"DW_CFA_val_offset r{r1}") + else: + ignored_reg_ops += 1 + elif op == DW_CFA_val_offset_sf: + r1, pos = read_uleb128(insns, pos, end) + _, pos = read_sleb128(insns, pos, end) + if r1 in tracked_regs or r1 == sp_reg: + reasons.append(f"DW_CFA_val_offset_sf r{r1}") + else: + ignored_reg_ops += 1 + elif op == DW_CFA_set_loc: + _, pos = read_encoded_ptr(insns, pos, end, cie["fde_enc"], cie["addr_size"], 0) + reasons.append("DW_CFA_set_loc") + else: + reasons.append(name) + break + + # Coalesce consecutive ("adv", d) events and drop trailing ("adv", d) + while events and events[-1][0] == "adv": + events.pop() + + min_bytes = bytearray() + acc_adv = 0 + for kind, payload in events: + if kind == "adv": + acc_adv += payload + else: + if acc_adv > 0: + if acc_adv <= 0x3f: + min_bytes.append(0x40 | acc_adv) + elif acc_adv <= 0xff: + min_bytes.extend([DW_CFA_advance_loc1, acc_adv]) + elif acc_adv <= 0xffff: + min_bytes.append(DW_CFA_advance_loc2) + min_bytes.extend(struct.pack(" {total_min_insn_bytes:,d} B " + f"(avg {total_min_insn_bytes / max(supported_fdes, 1):.1f} B/FDE)") + if sframe_size: + print(f" .sframe section : {sframe_size:10,d} B") + if orc_size: + print(f" .orc_unwind + _ip : {orc_size:10,d} B") + print(f" Minimal DWARF coverage : {supported_fdes:,d} / {total_fdes:,d} FDEs ({pct_cov:.2f}%)") + print(f" Register ops kept/skip : {total_kept_ops:,d} kept (FP/RA), {total_ignored_ops:,d} ignored (other GPRs/args)") + print(f" Max remember_state depth: {max_depth_seen}") + if unsupported_breakdown: + print(" Unsupported FDE reasons :") + for r, cnt in unsupported_breakdown.most_common(): + print(f" - {r}: {cnt}") + print(" Top DWARF CFA opcodes :") + for op_name, cnt in total_op_counts.most_common(10): + print(f" - {op_name:34s}: {cnt:8,d}") + print() + + +def main(): + epilog = ( + "Examples:\n" + " %(prog)s vmlinux\n" + " %(prog)s mm/vmscan.o kernel/fork.o\n" + " %(prog)s /bin/bash /lib/x86_64-linux-gnu/libc.so.6\n" + " %(prog)s --minify /tmp/eh_frame.min mm/vmscan.o\n" + ) + ap = argparse.ArgumentParser( + description="Analyze ELF .eh_frame coverage and size for Minimal DWARF CFI", + epilog=epilog, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + ap.add_argument("files", nargs="+", help="ELF files (.o, .ko, vmlinux, DSO, executable) to analyze") + ap.add_argument("--minify", metavar="OUT", help="Write minified .eh_frame binary for the first file") + args = ap.parse_args() + + for idx, path in enumerate(args.files): + out_p = args.minify if idx == 0 else None + analyze_elf(path, out_min_path=out_p) + + +if __name__ == "__main__": + main() -- 2.56.1.750.gf70dc682cf-goog