如何在LLVM中遍历GlobalVariable名称的每个字符?

时间:2018-04-10 07:44:32

标签: llvm

我编写了一个获取GlobalVariable名称的每个字符并进行XOR操作的演示。这是我演示代码的一部分(函数入口块已经创建,gvar是GlobalVariable,len是GlobalVariable长度):

BasicBlock *preHeaderBB=builder.GetInsertBlock();
                                    ConstantInt* string_length = ConstantInt::get(mod->getContext(), APInt(32, len));
                                    BasicBlock* for_body = BasicBlock::Create(mod->getContext(), "for-body", fdecode);

                                    builder.CreateBr(for_body);
                                    builder.SetInsertPoint(for_body);
                                    PHINode *variable = builder.CreatePHI(Type::getInt32Ty(mod->getContext()), 2, "i");
                                    Value *startValue = builder.getInt32(0);
                                    Value *endValue = builder.getInt32(len);
                                    variable->addIncoming(startValue, preHeaderBB);

                                    LoadInst *Load=builder.CreateLoad(gvar);
                                    Load->setAlignment(8);
                                    Value* indexList[2] = {ConstantInt::get(startValue->getType(), 0), startValue};
                                    ConstantInt* const_key = ConstantInt::get(mod->getContext(), APInt(8, key));
                                    Value *GEP=builder.CreateGEP(gvar,ArrayRef<Value*>(indexList, 2),"arrayIdx");
                                    LoadInst *loadElement=builder.CreateLoad(GEP);
                                    loadElement->setAlignment(1);
                                    Value *Xor = builder.CreateXor(loadElement,const_key,"xor");
                                    StoreInst *Store = builder.CreateStore(Xor, loadElement);

                                    Value *stepValue = builder.getInt32(1);
                                    Value *nextValue = builder.CreateAdd(startValue, stepValue, "next-value");
                                    Value *endCondition = builder.CreateICmpULT(startValue, endValue, "end-condition");
                                    endCondition = builder.CreateICmpNE(endCondition, builder.getInt32(0), "loop-condion");
                                    BasicBlock *loopEndBB = builder.GetInsertBlock();
                                    builder.CreateCondBr(endCondition, loopEndBB, entry);
                                    variable->addIncoming(nextValue, loopEndBB);
                                    builder.SetInsertPoint(entry);

我使用LoadInst来获取GloablVariable名称的每个字符,但它出现了错误。我在哪里可以改进这段代码。谢谢。

1 个答案:

答案 0 :(得分:0)

在LLVM的SSA表格IR中,GV的名称仅仅是&#34;别名&#34;对于变量,可能出现在SymbolTable中,具体取决于LinkageType。没有任何&#34;加载变量的名称&#34;,因为名称本身就是变量。您正在创建的GEP指令实际上是GV表示的任何值的索引,而不是名称。所以这里的根本错误。您需要编写一些代码来解析二进制格式和运行时,并从SymbolTable中检索名称,前提是GV的LinkageType不是PrivateLinkageInternalLinkage和二进制文件没被剥夺