【问题标题】:Identifying the start and end of functions in a C program识别 C 程序中函数的开始和结束
【发布时间】:2012-12-13 11:39:55
【问题描述】:

我目前正在用 C 进行编程,以根据函数中的行数来查找程序中函数的复杂性。我将不得不打开一个现有的 C 文件并继续计算。我知道可能有一些内置工具可以找到它。但我仍然希望它手动编程。是否有任何特定方法可以在 C 文件中查找各种函数的开始和结束?

【问题讨论】:

  • 您使用什么语言编写分析器?因为它只是一个解析问题,不同的语言和环境有不同的工具。
  • 不是真的,至少在没有实现 C 解析器的至少一部分的情况下不会。好消息是,如果您并不真正关心函数的内容或函数声明在语义上是否有效,那么使用 LexYacc 之类的工具非常容易。
  • 顺便说一句,行数是衡量函数复杂性的一个非常的糟糕指标。我可以创建一个非常长的函数来做一些非常简单和快速的事情,或者一个包含高级循环的单行函数需要很多时间。您可能可以使用 LLVM 之类的东西来解析代码,然后提取关于复杂性的更可靠的统计数据,而不仅仅是行数。
  • @DimaRudnik 我正在用 C 编程。

标签: c


【解决方案1】:
  1. 通过 C 预处理器运行它。通过这种方式,您可以剥离 cmets、展开宏、包含 #includes 等。除非您想要用户可读的代码的复杂性,否则这将产生更真实的结果。

  2. 删除固定字符串。 "" 之间的任何内容,注意转义引号 \" 不会关闭字符串。

  3. 扫描文件。首先{ 增加函数计数并开始扫描函数体。观察深度。 { 增加深度,} 减少,随着深度达到 0 另一个 } 是函数的结尾。下一个{ 将是一个新功能,但是当您扫描外部时,如果在到达下一个{EOF 之前遇到; - 取消在最后一块上收集的任何数据。那不是一个函数,它是一个结构、一个联合或类似的东西。

【讨论】:

  • 谢谢!第三点很清楚。但是,我不明白第二点。删除它们有什么帮助?还有,如何运行预处理器?
  • @Gomathi: Parse void a() { printf("{{{\"{\"{"); } 至于预处理器,取决于你的 C 编译器。对于 GCC,stackoverflow.com/questions/3916979/gcc-preprocessor
【解决方案2】:

我建议采用 2-pass 方法。

第 1 步:删除 cmets 中的任何左大括号或右大括号(以及预处理器指令中的可选大括号)。

第 2 步:计算左大括号和右大括号,只要它们匹配(#open == #close),函数就会结束。下一个大括号表示新函数的开始。

这种方法不是万无一失的。如果代码包含违反良好编程习惯的预处理器语句,它可能会失败。如果您遇到此类代码,您可能希望在代码通过预处理器阶段后对其运行您的工具。

【讨论】:

    【解决方案3】:

    我终于找到了一个很好的方法!
    doxygen 已经做了很多事情来很好地处理函数和其他事情。
    生成 doxygen conf,如 doxygen -g doxygen_conf
    用你喜欢的编辑器打开 conf 文件并设置GENERATE_XML = YES。您可能还想设置 RECURSIVE = YES 和项目所需的其他内容,然后运行 ​​doxygen。也设置INPUT = [PATH_TO_PROJECT_BASE]。 在你的 doxygen 构建目录中,你会找到 html/ 和 xml/。

    cd80@cd80 ~/lab/VulnVizOnLinux/linux-5.4.109 » cd build_doc
    cd80@cd80 ~/lab/VulnVizOnLinux/linux-5.4.109/build_doc » ls
    ExtractFunctions.ipynb  html  xml
    cd80@cd80 ~/lab/VulnVizOnLinux/linux-5.4.109/build_doc » 
    

    (忽略 ExtractFunctions.ipynb,这是我的)
    cd 到 xml 并打开任何 xml 文件并分析一段时间。
    以下是我的做法。

    import os
    import xml.etree.ElementTree as ET
    
    base_path = '/home/cd80/lab/VulnVizOnLinux/linux-5.4.109/'
    open_files = {}
    doc = ET.parse('/home/cd80/lab/VulnVizOnLinux/linux-5.4.109/build_doc/xml/4_2kernel_2module-plts_8c.xml')
    root = doc.getroot()
    
    for func in root.findall(".//memberdef/[@kind='function']"):
        name = func.find('./name').text
        location = func.find('./location')
        if 'bodyend' not in location.keys():
            continue # this memberdef is not a definition of function
        bodystart = int(location.attrib.get('bodystart'))
        bodyend = int(location.attrib.get('bodyend'))
        file_path = location.attrib.get('file')
        file_path = os.path.join(base_path, file_path)
        
        if file_path not in open_files.keys():
            with open(file_path, 'rb') as f:
                code = f.read().decode('utf-8')
            open_files[file_path] = code
        else:
            code = open_files[file_path]
        
        func_def = '\n'.join(code.split("\n")[bodystart-1:bodyend])
        print(func_def)
        print('='*30)
    

    结果:

    static struct plt_entry __get_adrp_add_pair(u64 dst, u64 pc,
                            enum aarch64_insn_register reg)
    {
        u32 adrp, add;
    
        adrp = aarch64_insn_gen_adr(pc, dst, reg, AARCH64_INSN_ADR_TYPE_ADRP);
        add = aarch64_insn_gen_add_sub_imm(reg, reg, dst % SZ_4K,
                           AARCH64_INSN_VARIANT_64BIT,
                           AARCH64_INSN_ADSB_ADD);
    
        return (struct plt_entry){ cpu_to_le32(adrp), cpu_to_le32(add) };
    }
    ==============================
    struct plt_entry get_plt_entry(u64 dst, void *pc)
    {
        struct plt_entry plt;
        static u32 br;
    
        if (!br)
            br = aarch64_insn_gen_branch_reg(AARCH64_INSN_REG_16,
                             AARCH64_INSN_BRANCH_NOLINK);
    
        plt = __get_adrp_add_pair(dst, (u64)pc, AARCH64_INSN_REG_16);
        plt.br = cpu_to_le32(br);
    
        return plt;
    }
    ==============================
    bool plt_entries_equal(const struct plt_entry *a, const struct plt_entry *b)
    {
        u64 p, q;
    
        /*
         * Check whether both entries refer to the same target:
         * do the cheapest checks first.
         * If the 'add' or 'br' opcodes are different, then the target
         * cannot be the same.
         */
        if (a->add != b->add || a->br != b->br)
            return false;
    
        p = ALIGN_DOWN((u64)a, SZ_4K);
        q = ALIGN_DOWN((u64)b, SZ_4K);
    
        /*
         * If the 'adrp' opcodes are the same then we just need to check
         * that they refer to the same 4k region.
         */
        if (a->adrp == b->adrp && p == q)
            return true;
    
        return (p + aarch64_insn_adrp_get_offset(le32_to_cpu(a->adrp))) ==
               (q + aarch64_insn_adrp_get_offset(le32_to_cpu(b->adrp)));
    }
    ==============================
    static bool in_init(const struct module *mod, void *loc)
    {
        return (u64)loc - (u64)mod->init_layout.base < mod->init_layout.size;
    }
    ==============================
    u64 module_emit_plt_entry(struct module *mod, Elf64_Shdr *sechdrs,
                  void *loc, const Elf64_Rela *rela,
                  Elf64_Sym *sym)
    {
        struct mod_plt_sec *pltsec = !in_init(mod, loc) ? &mod->arch.core :
                                  &mod->arch.init;
        struct plt_entry *plt = (struct plt_entry *)sechdrs[pltsec->plt_shndx].sh_addr;
        int i = pltsec->plt_num_entries;
        int j = i - 1;
        u64 val = sym->st_value + rela->r_addend;
    
        if (is_forbidden_offset_for_adrp(&plt[i].adrp))
            i++;
    
        plt[i] = get_plt_entry(val, &plt[i]);
    
        /*
         * Check if the entry we just created is a duplicate. Given that the
         * relocations are sorted, this will be the last entry we allocated.
         * (if one exists).
         */
        if (j >= 0 && plt_entries_equal(plt + i, plt + j))
            return (u64)&plt[j];
    
        pltsec->plt_num_entries += i - j;
        if (WARN_ON(pltsec->plt_num_entries > pltsec->plt_max_entries))
            return 0;
    
        return (u64)&plt[i];
    }
    ==============================
    static int cmp_rela(const void *a, const void *b)
    {
        const Elf64_Rela *x = a, *y = b;
        int i;
    
        /* sort by type, symbol index and addend */
        i = cmp_3way(ELF64_R_TYPE(x->r_info), ELF64_R_TYPE(y->r_info));
        if (i == 0)
            i = cmp_3way(ELF64_R_SYM(x->r_info), ELF64_R_SYM(y->r_info));
        if (i == 0)
            i = cmp_3way(x->r_addend, y->r_addend);
        return i;
    }
    ==============================
    static bool duplicate_rel(const Elf64_Rela *rela, int num)
    {
        /*
         * Entries are sorted by type, symbol index and addend. That means
         * that, if a duplicate entry exists, it must be in the preceding
         * slot.
         */
        return num > 0 && cmp_rela(rela + num, rela + num - 1) == 0;
    }
    ==============================
    static unsigned int count_plts(Elf64_Sym *syms, Elf64_Rela *rela, int num,
                       Elf64_Word dstidx, Elf_Shdr *dstsec)
    {
        unsigned int ret = 0;
        Elf64_Sym *s;
        int i;
    
        for (i = 0; i < num; i++) {
            u64 min_align;
    
            switch (ELF64_R_TYPE(rela[i].r_info)) {
            case R_AARCH64_JUMP26:
            case R_AARCH64_CALL26:
                if (!IS_ENABLED(CONFIG_RANDOMIZE_BASE))
                    break;
    
                /*
                 * We only have to consider branch targets that resolve
                 * to symbols that are defined in a different section.
                 * This is not simply a heuristic, it is a fundamental
                 * limitation, since there is no guaranteed way to emit
                 * PLT entries sufficiently close to the branch if the
                 * section size exceeds the range of a branch
                 * instruction. So ignore relocations against defined
                 * symbols if they live in the same section as the
                 * relocation target.
                 */
                s = syms + ELF64_R_SYM(rela[i].r_info);
                if (s->st_shndx == dstidx)
                    break;
    
                /*
                 * Jump relocations with non-zero addends against
                 * undefined symbols are supported by the ELF spec, but
                 * do not occur in practice (e.g., 'jump n bytes past
                 * the entry point of undefined function symbol f').
                 * So we need to support them, but there is no need to
                 * take them into consideration when trying to optimize
                 * this code. So let's only check for duplicates when
                 * the addend is zero: this allows us to record the PLT
                 * entry address in the symbol table itself, rather than
                 * having to search the list for duplicates each time we
                 * emit one.
                 */
                if (rela[i].r_addend != 0 || !duplicate_rel(rela, i))
                    ret++;
                break;
            case R_AARCH64_ADR_PREL_PG_HI21_NC:
            case R_AARCH64_ADR_PREL_PG_HI21:
                if (!IS_ENABLED(CONFIG_ARM64_ERRATUM_843419) ||
                    !cpus_have_const_cap(ARM64_WORKAROUND_843419))
                    break;
    
                /*
                 * Determine the minimal safe alignment for this ADRP
                 * instruction: the section alignment at which it is
                 * guaranteed not to appear at a vulnerable offset.
                 *
                 * This comes down to finding the least significant zero
                 * bit in bits [11:3] of the section offset, and
                 * increasing the section's alignment so that the
                 * resulting address of this instruction is guaranteed
                 * to equal the offset in that particular bit (as well
                 * as all less signficant bits). This ensures that the
                 * address modulo 4 KB != 0xfff8 or 0xfffc (which would
                 * have all ones in bits [11:3])
                 */
                min_align = 2ULL << ffz(rela[i].r_offset | 0x7);
    
                /*
                 * Allocate veneer space for each ADRP that may appear
                 * at a vulnerable offset nonetheless. At relocation
                 * time, some of these will remain unused since some
                 * ADRP instructions can be patched to ADR instructions
                 * instead.
                 */
                if (min_align > SZ_4K)
                    ret++;
                else
                    dstsec->sh_addralign = max(dstsec->sh_addralign,
                                   min_align);
                break;
            }
        }
    
        if (IS_ENABLED(CONFIG_ARM64_ERRATUM_843419) &&
            cpus_have_const_cap(ARM64_WORKAROUND_843419))
            /*
             * Add some slack so we can skip PLT slots that may trigger
             * the erratum due to the placement of the ADRP instruction.
             */
            ret += DIV_ROUND_UP(ret, (SZ_4K / sizeof(struct plt_entry)));
    
        return ret;
    }
    ==============================
    int module_frob_arch_sections(Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
                      char *secstrings, struct module *mod)
    {
        unsigned long core_plts = 0;
        unsigned long init_plts = 0;
        Elf64_Sym *syms = NULL;
        Elf_Shdr *pltsec, *tramp = NULL;
        int i;
    
        /*
         * Find the empty .plt section so we can expand it to store the PLT
         * entries. Record the symtab address as well.
         */
        for (i = 0; i < ehdr->e_shnum; i++) {
            if (!strcmp(secstrings + sechdrs[i].sh_name, ".plt"))
                mod->arch.core.plt_shndx = i;
            else if (!strcmp(secstrings + sechdrs[i].sh_name, ".init.plt"))
                mod->arch.init.plt_shndx = i;
            else if (!strcmp(secstrings + sechdrs[i].sh_name,
                     ".text.ftrace_trampoline"))
                tramp = sechdrs + i;
            else if (sechdrs[i].sh_type == SHT_SYMTAB)
                syms = (Elf64_Sym *)sechdrs[i].sh_addr;
        }
    
        if (!mod->arch.core.plt_shndx || !mod->arch.init.plt_shndx) {
            pr_err("%s: module PLT section(s) missing\n", mod->name);
            return -ENOEXEC;
        }
        if (!syms) {
            pr_err("%s: module symtab section missing\n", mod->name);
            return -ENOEXEC;
        }
    
        for (i = 0; i < ehdr->e_shnum; i++) {
            Elf64_Rela *rels = (void *)ehdr + sechdrs[i].sh_offset;
            int numrels = sechdrs[i].sh_size / sizeof(Elf64_Rela);
            Elf64_Shdr *dstsec = sechdrs + sechdrs[i].sh_info;
    
            if (sechdrs[i].sh_type != SHT_RELA)
                continue;
    
            /* ignore relocations that operate on non-exec sections */
            if (!(dstsec->sh_flags & SHF_EXECINSTR))
                continue;
    
            /* sort by type, symbol index and addend */
            sort(rels, numrels, sizeof(Elf64_Rela), cmp_rela, NULL);
    
            if (!str_has_prefix(secstrings + dstsec->sh_name, ".init"))
                core_plts += count_plts(syms, rels, numrels,
                            sechdrs[i].sh_info, dstsec);
            else
                init_plts += count_plts(syms, rels, numrels,
                            sechdrs[i].sh_info, dstsec);
        }
    
        pltsec = sechdrs + mod->arch.core.plt_shndx;
        pltsec->sh_type = SHT_NOBITS;
        pltsec->sh_flags = SHF_EXECINSTR | SHF_ALLOC;
        pltsec->sh_addralign = L1_CACHE_BYTES;
        pltsec->sh_size = (core_plts  + 1) * sizeof(struct plt_entry);
        mod->arch.core.plt_num_entries = 0;
        mod->arch.core.plt_max_entries = core_plts;
    
        pltsec = sechdrs + mod->arch.init.plt_shndx;
        pltsec->sh_type = SHT_NOBITS;
        pltsec->sh_flags = SHF_EXECINSTR | SHF_ALLOC;
        pltsec->sh_addralign = L1_CACHE_BYTES;
        pltsec->sh_size = (init_plts + 1) * sizeof(struct plt_entry);
        mod->arch.init.plt_num_entries = 0;
        mod->arch.init.plt_max_entries = init_plts;
    
        if (tramp) {
            tramp->sh_type = SHT_NOBITS;
            tramp->sh_flags = SHF_EXECINSTR | SHF_ALLOC;
            tramp->sh_addralign = __alignof__(struct plt_entry);
            tramp->sh_size = sizeof(struct plt_entry);
        }
    
        return 0;
    }
    ==============================
    

    很脏,但按我想要的方式工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-30
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2014-12-14
      • 2012-10-06
      • 1970-01-01
      相关资源
      最近更新 更多