如何从Clang的CallExpr中获取函数指针的参数

How to get the arguments of a function pointer from a CallExpr in Clang?

本文关键字:获取 函数 指针 参数 CallExpr Clang      更新时间:2023-10-16

我试图分析c++源代码与其中的函数调用。我能够使用下面的源代码分析正常的函数调用,以获得它们的参数,其中ce是CallExpr对象:

1.  if(ce != NULL) {            
2.      QualType q = ce->getType();
3.      const Type *t = q.getTypePtrOrNull();
4.
5.      if (t != NULL) {
6.          llvm::errs() << "TYPE: " << t->isFunctionPointerType() << " " << q.getAsString() << " " << t->isPointerType() << "n";
7.      } else {
8.          llvm::errs() << "FUNCTION CE HAS NO TYPE?n";
9.      }
10.
11.
12.     const Decl* D = ce ->getCalleeDecl();
13.     while(D->getPreviousDecl() != NULL) 
14.         D = D->getPreviousDecl();
15.         
16.     llvm::errs() << "Kind:  " << D->getDeclKindName() << "n";
17.     
18.     FunctionDecl* fd = (FunctionDecl*) llvm::dyn_cast<FunctionDecl>(D);
19.     for(int x = 0; x< fd ->getNumParams(); x++) {
20.         if(fd ->getParamDecl(x)->getType()->isAnyPointerType()) {
21.             // Do Stuff Here
22.         } 
23.     }
24. }

上述源代码的问题出现在第18行,当我尝试将Decl从CallExpr类型转换为FunctionDecl时,如果CallExpr来自函数指针调用,则会导致fd变为NULL

我尝试通过打印第16行中的类型来调试。对于函数指针,它指定Decl on 12VarDecl,而不是像普通函数调用那样的FunctionDecl。

我也尝试使用isFunctionPointerType(),但这是返回false。

下面是导致段错误的一段源代码:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    void* (*mp)(size_t size);
    void *mpp;
    mp = &malloc;
    mpp = mp(30);
    free(mpp);
    return (0);
}

是否有一种方法使用clang来检测CallExpr是否为函数指针调用?如果有,如何获得参数列表?

我使用clang 3.1

谢谢

使用getDirectCallee()功能(我不确定它是否在clang 3.1中可用)FunctionDecl *func = ce->getDirectCallee();

if (func != NULL){
    for(int i = 0; i < func->getNumParams(); i++){
        if(func->getParamDecl(i)->getType()->isFunctionPointerType()){
            // Do stuff here
        }
    }
}

您应该从指针声明中获得函数原型,之后您将能够获得有关返回类型和参数类型的信息:

clang::CallExpr* expr;
...
auto decl = expr->getCalleeDecl();
if (decl != nullptr) {
    if (decl->getKind() == clang::Decl::Var) {
        clang::VarDecl *varDecl = clang::dyn_cast<clang::VarDecl>(decl);
        if(varDecl->getType()->isFunctionPointerType() == true) {
            const clang::PointerType *pt = varDecl->getType()->getAs<clang::PointerType>();
            const clang::FunctionProtoType *ft = pt->getPointeeType()->getAs<clang::FunctionProtoType>();
            if (ft != nullptr) {
                std::string retTypeName = ft->getReturnType().getAsString();
                ...
                auto paramsCount = funcType->getNumParams();
                for (size_t i = 0; i < paramsCount; ++i) {
                    clang::QualType paramType = funcType->getParamType(i);
                    std::string paramTypeName = paramType.getAsString();
                    ...
                }
            }
        }
    }
}

可能您也可以使用getArg(position)来获取特定的参数,在此之前您应该使用getNumArgs来获取函数包含的参数数量的详细信息。