Reputation: 51
I am writing a LLVM module pass that will get the third argument in pthread_create
. According to the man page the function prototype of pthread_create
is
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
For example my target C source is as following.
void *pthread_task(void *args) {
sleep(4);
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t tid;
pthread_create(&tid, NULL, pthread_task, NULL);
pthread_join(tid, NULL);
return 0;
}
I would like to have the output "pthread_task". I was able to access the right function and list all arguments. However, since the third parameter is a function pointer, I don't know how to access the function which it points to.
Also I attach how I implement my module pass as following.
namespace {
~ int32_t indexOfPthreadCreate(CallGraphNode *node) {
~ for (int32_t i = 0; i < node -> size(); i++) {
~ Function *f = (*node)[i] -> getFunction();
~ if (f && f -> getName().compare("pthread_create") == 0) {
+ for (auto &A: f->args()) {
// I would like to access the third parameter of pthread_create here.
+ A.print(errs());
+ }
+ return i;
+ }
}
~ return -1;
}
struct PthreadScopeDetectPass : public ModulePass {
static char ID;
PthreadScopeDetectPass() : ModulePass(ID) { }
bool runOnModule(Module &M) override {
CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
uint32_t nSCC = 0;
for (scc_iterator<CallGraph *> iterSCC = scc_begin(&CG); !iterSCC.isAtEnd(); ++iterSCC) {
auto nodes = *iterSCC;
for (CallGraphNode *node: nodes) {
Function *currFunc = node -> getFunction();
~ int32_t target_i = indexOfPthreadCreate(node);
~ if (target_i > 0 && currFunc) {
+ insertTimer(currFunc);
}
}
}
return true;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
AU.addRequired<CallGraphWrapperPass>();
}
};
}
Upvotes: 1
Views: 1320
Reputation: 51
Thanks for @arnt's comment. I already solve the issue. Here's how I solve it.
~ int32_t indexOfPthreadCreate(CallGraphNode *node) {
~ for (int32_t i = 0; i < node -> size(); i++) {
~ Function *f = (*node)[i] -> getFunction();
~ if (f && f -> getName().compare("pthread_create") == 0) {
+ for (auto &inst: instructions(f)) {
~ if (inst.getOpcode() == 56) {
~ CallInst *ci = dyn_cast<CallInst>(&inst);
~ if (ci && ci->getCalledFunction()->getName().compare("pthread_create") == 0) {
~ Function *pthread_task = dyn_cast<Function>(ci->getArgOperand(2));
~_ errs() << "pthread is going to execute " << pthread_task->getName() << "function \n";
}
+ }
+ A.print(errs());
+ }
+ return i;
+ }
}
~ return -1;
}
Upvotes: 1