You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不借助dex的情况下用Python统计smali文件的方法与字段数量?

解决Smali文件方法与字段统计偏差问题

原代码统计结果与实际值存在差异的核心原因是未处理注释行和行首空白字符,以下是修正后的实现方案:

问题分析

  • 原代码直接判断行首是否为.field/.method,但Smali注释(以#开头)中若包含这些字符串会被误统计
  • 部分Smali文件可能因格式问题,.field/.method前存在空格或制表符,导致原代码漏统计

修正后的Python代码

def count_smali_methods(smali_path):
    count = 0
    with open(smali_path, 'r', encoding='utf-8') as f:
        is_valid_class = False
        for line in f:
            stripped_line = line.strip()
            # 跳过空行和注释行
            if not stripped_line or stripped_line.startswith('#'):
                continue
            # 验证是否为合法类Smali文件
            if stripped_line.startswith('.class'):
                is_valid_class = True
                continue
            if not is_valid_class:
                continue
            # 统计方法
            if stripped_line.startswith('.method'):
                count += 1
    if not is_valid_class:
        print(f'Warning: Not a valid class smali file: {smali_path}')
        return 0
    return count

def count_smali_fields(smali_path):
    count = 0
    with open(smali_path, 'r', encoding='utf-8') as f:
        is_valid_class = False
        for line in f:
            stripped_line = line.strip()
            # 跳过空行和注释行
            if not stripped_line or stripped_line.startswith('#'):
                continue
            # 验证是否为合法类Smali文件
            if stripped_line.startswith('.class'):
                is_valid_class = True
                continue
            if not is_valid_class:
                continue
            # 统计字段
            if stripped_line.startswith('.field'):
                count += 1
    if not is_valid_class:
        print(f'Warning: Not a valid class smali file: {smali_path}')
        return 0
    return count

关键优化点

  • 对每行先执行strip()处理,消除行首行尾空白字符,避免因格式问题漏统计
  • 跳过空行和以#开头的注释行,防止注释中的.field/.method被误算
  • 调整为逐行遍历的读取逻辑,代码更简洁且规避原循环中可能的漏读问题

内容的提问来源于stack exchange,提问作者lhq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:35:16