ida-pro反编译小技巧之InitializeListHead宏
ida-pro decompile InitializeListHead
ida-pro反编译小技巧之InitializeListHead宏
缘由
在用ida-pro进行windows驱动文件反编译的时候,经常遇到这样的情况:
qword_1C00E7F40 = (__int64)&qword_1C00E7F38;
qword_1C00E7F38 = (__int64)&qword_1C00E7F38;搞windows 驱动开发的人员,应该会想到一个数据结构:
typedef struct _LIST_ENTRY { // C:\Program Files (x86)\Windows Kits\10\Include\10.0.28000.0\shared\ntdef.h
struct _LIST_ENTRY *Flink;
struct _LIST_ENTRY *Blink;
} LIST_ENTRY, *PLIST_ENTRY, *RESTRICTED_POINTER PRLIST_ENTRY;如果手动把qword_1C00E7F38处的变量定义为LIST_ENTRY,ida-pro会自动显示下面的反编译结果:
stru_1C00E7F38.Blink = &stru_1C00E7F38;
stru_1C00E7F38.Flink = &stru_1C00E7F38;如果幸运的话,有符号文件,ida-pro会自动识别并显示上面的结果。
如果你是个细致或讲究的人,你还会发现,这不就是InitializeListHead吗?
FORCEINLINE
VOID
InitializeListHead(
_Out_ PLIST_ENTRY ListHead
)
// C:\Program Files (x86)\Windows Kits\10\Include\10.0.28000.0\km\wdm.h
{
ListHead->Flink = ListHead->Blink = ListHead;
return;
}但是,如何才能显示InitializeListHead这样的形式呢?
解决脚本
苦思冥想了好长时间,终于在AI的帮助下,经过多次调教,得出如下脚本:
# -*- coding: utf-8 -*-
"""
ida_hexrays_initlisthead.py — InitializeListHead 宏展开自动还原
功能:
把
ndisGlobalNetBufferPoolList.Blink = &ndisGlobalNetBufferPoolList;
ndisGlobalNetBufferPoolList.Flink = &ndisGlobalNetBufferPoolList;
变成
InitializeListHead(&ndisGlobalNetBufferPoolList);
原理:
使用 open_pseudocode / refresh_pseudocode 钩子,在反编译窗口打开或 F5 刷新时,
对已完全返回的 cfunc 做 ctree 修改,然后调用 vu.refresh_ctext() 更新显示。
refresh_ctext() 只刷新文本显示,不会重新触发反编译,因此不会产生循环。
NOTE: 不能在 maturity(CMAT_FINAL) 内修改 ctree——IDA 在该回调返回后
仍会做最终序列化,修改会破坏内部一致性,导致 decompile() 返回 None。
对于批处理场景,提供 process_cfunc(cfunc) 辅助函数直接调用。
加载:
import importlib.util, sys
spec = importlib.util.spec_from_file_location(
"ida_hexrays_initlisthead",
r"<路径>\\ida_hexrays_initlisthead.py")
mod = importlib.util.module_from_spec(spec)
sys.modules["ida_hexrays_initlisthead"] = mod
spec.loader.exec_module(mod)
"""
import traceback
import idaapi
import ida_hexrays
import ida_typeinf
# ── LIST_ENTRY 字段偏移 ───────────────────────────────────────────────────────
def _list_entry_offsets():
tif = ida_typeinf.tinfo_t()
if tif.get_named_type(None, "LIST_ENTRY"):
udt = ida_typeinf.udt_type_data_t()
if tif.get_udt_details(udt):
d = {m.name: m.offset // 8 for m in udt}
return d.get("Flink", 0), d.get("Blink", 8)
return 0, 8
_FLINK_OFF, _BLINK_OFF = _list_entry_offsets()
# ── 表达式指纹 ────────────────────────────────────────────────────────────────
class _EK:
@classmethod
def key(cls, e):
op = e.op
if op == ida_hexrays.cot_num: return "n%d" % e.numval()
if op == ida_hexrays.cot_var: return "v%d" % e.v.idx
if op == ida_hexrays.cot_obj: return "g%x" % e.obj_ea
if op == ida_hexrays.cot_ref: return "r:" + cls.key(e.x)
if op == ida_hexrays.cot_ptr: return "p:" + cls.key(e.x)
if op == ida_hexrays.cot_cast: return cls.key(e.x)
if op == ida_hexrays.cot_memref: return "mr%d:%s" % (e.m, cls.key(e.x))
if op == ida_hexrays.cot_memptr: return "mp%d:%s" % (e.m, cls.key(e.x))
if op == ida_hexrays.cot_add: return "add:%s:%s" % (cls.key(e.x), cls.key(e.y))
return "op%d" % op
@classmethod
def eq(cls, a, b): return cls.key(a) == cls.key(b)
# ── 模式匹配 ─────────────────────────────────────────────────────────────────
def _strip_cast(e):
while e.op == ida_hexrays.cot_cast: e = e.x
return e
def _match_field_asg(expr, field_off):
if expr.op != ida_hexrays.cot_asg: return None
lhs = expr.x
if lhs.op in (ida_hexrays.cot_memref, ida_hexrays.cot_memptr) and lhs.m == field_off:
return lhs.x, expr.y
return None
def _rhs_is_addr_of(rhs, base):
e = _strip_cast(rhs)
if e.op == ida_hexrays.cot_ref: return _EK.eq(e.x, base)
return _EK.eq(e, base)
def _try_match(s1, s2):
if s1.op != ida_hexrays.cit_expr or s2.op != ida_hexrays.cit_expr: return None
for off_a, off_b in ((_BLINK_OFF, _FLINK_OFF), (_FLINK_OFF, _BLINK_OFF)):
m1 = _match_field_asg(s1.cexpr, off_a)
m2 = _match_field_asg(s2.cexpr, off_b)
if m1 is None or m2 is None: continue
base1, rhs1 = m1; base2, rhs2 = m2
if not _EK.eq(base1, base2): continue
if _rhs_is_addr_of(rhs1, base1) and _rhs_is_addr_of(rhs2, base2): return base1
return None
# ── 构造 InitializeListHead(&base) ───────────────────────────────────────────
def _build_call(base_expr):
void_t = ida_typeinf.tinfo_t()
void_t.create_simple_type(ida_typeinf.BTF_VOID)
# ptr_t.create_ptr(x) 意为"让 ptr_t 成为指向 x 的指针类型"
# 务必是 ptr_t.create_ptr(base_expr.type),而非反过来调用
ptr_t = ida_typeinf.tinfo_t()
ptr_t.create_ptr(base_expr.type)
inner = ida_hexrays.cexpr_t(); inner.assign(base_expr)
ref = ida_hexrays.cexpr_t()
ref.op = ida_hexrays.cot_ref; ref.type = ptr_t; ref.x = inner
inner.thisown = False
fn = ida_hexrays.cexpr_t()
fn.op = ida_hexrays.cot_helper; fn.helper = "InitializeListHead"
fn.type = void_t
args = ida_hexrays.carglist_t()
ca = ida_hexrays.carg_t(); ca.assign(ref); args.push_back(ca); ca.thisown = False
call = ida_hexrays.cexpr_t()
call.op = ida_hexrays.cot_call; call.x = fn; fn.thisown = False
call.a = args; call.type = void_t
return call
# ── 处理单个 block ────────────────────────────────────────────────────────────
def _process_block(block):
stmts = list(block)
to_del = []
count = 0
i = 0
while i < len(stmts) - 1:
base = _try_match(stmts[i], stmts[i + 1])
if base is not None:
try:
call = _build_call(base)
stmts[i].cexpr.swap(call)
to_del.append(stmts[i + 1])
count += 1; i += 2; continue
except Exception as ex:
print("[InitListHead] replace error @ %d: %s" % (i, ex))
i += 1
for s in to_del:
it = block.find(s)
if it != block.end(): block.erase(it)
return count
# ── ctree 访问器 ──────────────────────────────────────────────────────────────
class _Visitor(ida_hexrays.ctree_visitor_t):
def __init__(self):
ida_hexrays.ctree_visitor_t.__init__(self, ida_hexrays.CV_FAST)
self.count = 0
def visit_insn(self, insn):
if insn.op == ida_hexrays.cit_block:
self.count += _process_block(insn.cblock)
return 0
# ── 公开 API:处理已反编译好的 cfunc ─────────────────────────────────────────
def process_cfunc(cfunc):
"""
对已完成反编译的 cfunc 应用 InitializeListHead 模式替换。
必须在 decompile() 完全返回之后调用,返回替换次数。
"""
ea = cfunc.entry_ea
v = _Visitor()
v.apply_to(cfunc.body, None)
if v.count:
print("[InitListHead] %#x %s: %d place(s) replaced" % (
ea, idaapi.get_func_name(ea), v.count))
return v.count
# ── Hex-Rays UI 钩子 ──────────────────────────────────────────────────────────
#
# 为什么用 open_pseudocode / refresh_pseudocode 而不是 maturity(CMAT_FINAL):
# maturity 回调在 IDA 内部反编译流水线中间触发;CMAT_FINAL 之后 IDA 仍然
# 会对 cfunc 做最终序列化/验证,此时 ctree 已被修改,导致 decompile() 返回 None。
# open_pseudocode / refresh_pseudocode 在 decompile() 完全返回、调用方拿到
# cfunc 之后才触发,此时修改 ctree 是安全的。
# refresh_ctext() 只刷新文本渲染,不重新运行反编译器,不会产生循环。
#
class _Hook(ida_hexrays.Hexrays_Hooks):
# ── 首次打开反编译窗口 ──────────────────────────────────────────────────
def open_pseudocode(self, vu):
try:
cnt = process_cfunc(vu.cfunc)
if cnt:
vu.refresh_ctext()
except Exception:
traceback.print_exc()
return 0
# ── F5 重新反编译(ctree 已全新生成,直接处理)─────────────────────────
def refresh_pseudocode(self, vu):
try:
cnt = process_cfunc(vu.cfunc)
if cnt:
vu.refresh_ctext()
except Exception:
traceback.print_exc()
return 0
# ── 安装 / 卸载 ───────────────────────────────────────────────────────────────
_ATTR = "_initlisthead_hook"
def install():
if not ida_hexrays.init_hexrays_plugin():
print("[InitListHead] Hex-Rays not available.")
return
uninstall()
h = _Hook(); h.hook()
setattr(idaapi, _ATTR, h)
print("[InitListHead] installed (FLINK_OFF=%d, BLINK_OFF=%d)" % (_FLINK_OFF, _BLINK_OFF))
print("[InitListHead] - open_pseudocode / refresh_pseudocode hooks active")
print("[InitListHead] - call process_cfunc(cfunc) for batch use")
def uninstall():
old = getattr(idaapi, _ATTR, None)
if old is not None:
old.unhook(); delattr(idaapi, _ATTR)
print("[InitListHead] uninstalled.")
if __name__ == "__main__":
install()不当之处,敬请指正。
作者信息
made by correy
made at 2026/3/6