如何从Clang的CallExpr中获取函数指针的参数
How to get the arguments of a function pointer from a CallExpr in Clang?
我试图分析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 12
是VarDecl
,而不是像普通函数调用那样的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
来获取函数包含的参数数量的详细信息。
相关文章:
- 具有默认值的引用获取函数
- 如何从"decltype()"获取函数参数的数量<funtion>?
- C++ 获取函数在常量引用中按值返回的结果
- 如何从参数中获取函数签名?
- 获取函数的地址?
- 如何从不同的类中获取函数来调用在 Main 中声明的对象?
- 在 gcc/clang (C++) 中获取函数范围之外的标签地址
- 如何使用 std::invoke_result_t 获取函数的返回类型
- 获取函数中基元类型的指针
- 如何从 lambda 表达式中获取函数指针?
- 如何从核密度估计中获取函数?
- 如何在函数内部使用 zmq(以非阻塞方式)在客户端请求时获取函数的状态?
- 具有获取函数的无限循环
- 使用 decltype(this) 获取函数引用
- 在编译时使用可变参数模板在 c++ 中使用参数类型检查获取函数的参数数
- 如何在C++中接收任何类型的函数参数并获取函数内传递变量的类型?
- 从C 中的PHP扩展中获取函数参数值
- 从返回绑定中获取函数失败
- 从 Rcpp c++ 函数获取 r 函数参数
- 获取函数调用方的地址?