7 #define helloPassLog(M) DBG(errs() << "HelloPass: " << M << "\n")
8 #define MSG "Hello world!"
9 #define ERROR_FAILURE 1
13 class HelloPass
: public ModulePass
{
19 HelloPass() : ModulePass(ID
) { }
22 virtual bool runOnModule(Module
&M
) {
24 Function
* printfFunction
= NULL
;
25 Function
* mainFunction
= NULL
;
27 mainFunction
= M
.getFunction("main");
28 if (NULL
== mainFunction
)
30 helloPassLog("Info: main() not found. Skipping instrumentation.");
34 /* Prepare the string arguments for printf */
35 std::string printFuncName
= "printf" ;
36 const std::string msg
= MSG
;
37 const std::string fmt
= "%s\n";
38 Constant
* strConstMsg
= NULL
;
39 Constant
* strConstFmt
= NULL
;
40 std::vector
<Value
*> args(0);
41 Instruction
*I
= NULL
;
43 PassUtil::getStringGlobalVariable(M
, fmt
, ".fmtStr", "", &strConstFmt
, false);
44 PassUtil::getStringGlobalVariable(M
, msg
, ".helloworld", "", &strConstMsg
, false);
46 if (NULL
== strConstFmt
|| NULL
== strConstMsg
)
48 helloPassLog("Error: Prepared string contants point to NULL");
49 exitOnError(ERROR_FAILURE
);
52 args
.push_back(strConstFmt
);
53 args
.push_back(strConstMsg
);
55 /* Look for printf declaration */
56 std::vector
<TYPECONST Type
*> functionTyArgs
;
57 FunctionType
* printfFuncType
;
59 functionTyArgs
.push_back(PointerType::get(IntegerType::get(M
.getContext(), 8), 0));
61 printfFuncType
= PassUtil::getFunctionType(IntegerType::get(M
.getContext(), 32), functionTyArgs
, true);
62 if (NULL
== printfFuncType
)
64 helloPassLog("Error: Couldn't make function-type for printf.");
65 exitOnError(ERROR_FAILURE
);
68 printfFunction
= (Function
*) M
.getOrInsertFunction(printFuncName
, printfFuncType
);
69 if (NULL
== printfFunction
)
71 helloPassLog("Error: Couldnt find printf function declaration.");
72 exitOnError(ERROR_FAILURE
);
75 /* Insert call instruction in main() to call printf */
76 I
= mainFunction
->getBasicBlockList().begin()->begin();
81 helloPassLog("Warning: args to printf is empty.");
84 helloPassLog("Info: Inserting printf call instruction");
86 CallInst
* callInst
= PassUtil::createCallInstruction(printfFunction
, args
, "", I
);
88 if (NULL
== callInst
)
90 helloPassLog("Error: callInstr is null.");
91 exitOnError(ERROR_FAILURE
);
94 helloPassLog("Info: Inserting call instruction successful.");
103 void exitOnError(int errCode
)
105 helloPassLog("Aborting instrumentation.");
113 char HelloPass::ID
= 0;
114 RegisterPass
<HelloPass
> HP("hello", "Hello Pass", false, false);