// Image load callback - inserts the probes.
void ImgLoad(IMG img, void *v)
{
    // Called every time a new image is loaded

    if ( (IMG_Name(img).find("libncurses.so") != string::npos) ||
         (IMG_Name(img).find("LIBNCURSES.SO") != string::npos) ||
         (IMG_Name(img).find("LIBNCURSES.so") != string::npos) )
    {
        RTN rtngetch = RTN_FindByName(img, "getch");
        if (RTN_Valid(rtngetch) && RTN_IsSafeForProbedReplacement(rtngetch))
        {
            OutFile << CurrentTime() << "Inserting probe for getch at " << RTN_Address(rtngetch) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtngetch, AFUNPTR(mygetch)));
            fptrgetch = (int (*)())fptr;
        }

        RTN rtnmvgetch = RTN_FindByName(img, "mvgetch");
        if (RTN_Valid(rtnmvgetch) && RTN_IsSafeForProbedReplacement(rtnmvgetch))
        {
            OutFile << CurrentTime() << "Inserting probe for mvgetch at " << RTN_Address(rtnmvgetch) << endl;
            OutFile.flush();
            AFUNPTR fptr = (RTN_ReplaceProbed(rtnmvgetch, AFUNPTR(mymvgetch)));
            fptrmvgetch = (int (*)(int, int))fptr;
        }
    }
    // finished instrumentation
}
VOID ImageLoad(IMG img, VOID *v)
{
    
    printf ("ImageLoad %s\n", IMG_Name(img).c_str());
    for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
    {
        for (RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn))
        {
             if (strcmp(RTN_Name(rtn).c_str(), "_dl_debug_state") == 0)
             {
                 printf ("  RTN %s at %p\n", RTN_Name(rtn).c_str(),  reinterpret_cast<void *>(RTN_Address(rtn)));
                 printf ("    ** found _dl_debug_state\n");
                 dl_debug_state_Addr = RTN_Address(rtn);
                 justFoundDlDebugState = TRUE;
             }
             else if (justFoundDlDebugState)
             {
                 printf ("  RTN %s at %p\n", RTN_Name(rtn).c_str(),  reinterpret_cast<void *>(RTN_Address(rtn)));
                 dl_debug_state_AddrEnd =  RTN_Address(rtn);
                 justFoundDlDebugState = FALSE;
                 printf ("    ** _dl_debug_state from %p to %p\n", reinterpret_cast<void *>(dl_debug_state_Addr), reinterpret_cast<void *>(dl_debug_state_AddrEnd));
             }
        }
    }
}
Exemplo n.º 3
0
VOID Image(IMG img, void *v)
{
    RTN rtn = RTN_FindByName(img, "ReplacedXmmRegs");
    if (RTN_Valid(rtn))
    {
        PROTO proto = PROTO_Allocate(PIN_PARG(int), CALLINGSTD_DEFAULT, "ReplacedXmmRegs", PIN_PARG_END());
        RTN_ReplaceSignature(rtn, AFUNPTR(REPLACE_ReplacedXmmRegs),
                             IARG_PROTOTYPE, proto,
                             (KnobUseIargConstContext)?IARG_CONST_CONTEXT:IARG_CONTEXT,
                             IARG_THREAD_ID,
                             IARG_ORIG_FUNCPTR,
                             IARG_END);
        PROTO_Free(proto);
        printf ("TOOL found and replaced ReplacedXmmRegs\n");
        fflush (stdout);

        RTN rtn = RTN_FindByName(img, "ExecutedAtFunc");
        if (RTN_Valid(rtn))
        {
            executeAtAddr = RTN_Address(rtn);
            printf ("TOOL found ExecutedAtFunc for later PIN_ExecuteAt\n");
            fflush (stdout);
        }

        rtn = RTN_FindByName(img, "DumpXmmRegsAtException");
        if (RTN_Valid(rtn))
        {
            dumpXmmRegsAtExceptionAddr = RTN_Address(rtn);
            printf ("TOOL found DumpXmmRegsAtException for later Exception\n");
            fflush (stdout);
        }
    }
}
/*****************************************************************************
 函 数 名  : traceBack
 功能描述  : 回溯已经调用的函数栈,解析当前函数调用的信息
 输入参数  : const char* cfuncName
             ADDRINT funcAddr
             ADDRINT funcBP
 输出参数  : 无
 返 回 值  :
 调用函数  :
 被调函数  :

 修改历史      :
  1.日    期   : 2012年5月16日
    作    者   : @zhi
    修改内容   : 新生成函数

*****************************************************************************/
VOID traceBack( ADDRINT funcCurSP, ADDRINT funcUpperBP )
{
    if(g_backTraceFlg)
    {
#if 1
        string funcName;
        std::stack<FuncItem>tmpFuncs;
        ADDRINT tmpAddr;
        ADDRINT funcAddr;
        //待运行函数入栈,后面的插入直接是从该函数开始
        //tmpFuncs.push(FuncItem(funcName, funcAddr, funcBP-1));
        tmpAddr = *((ADDRINT *)funcCurSP);
        funcName = RTN_FindNameByAddress(tmpAddr);
        //获取不到函数名
        if("" == funcName)
        {
            funcName  = "[unknown]";
        }
        PIN_LockClient();
        funcAddr = RTN_Address(RTN_FindByAddress(tmpAddr));
        PIN_UnlockClient();
        ADDRINT funcBP = funcUpperBP;

        while(0 != funcBP)
        {
            tmpFuncs.push(FuncItem(funcName, funcAddr, funcBP));

            tmpAddr = *((ADDRINT *)funcBP + 1);
            funcName = RTN_FindNameByAddress(tmpAddr);
            //获取不到函数名
            if("" == funcName)
            {
                funcName  = "[unknown]";
            }
            PIN_LockClient();
            funcAddr = RTN_Address(RTN_FindByAddress(tmpAddr));
            PIN_UnlockClient();

            funcBP = *(ADDRINT*) funcBP;
        }

#endif

#if 1
        tmpAddr =0;
        while(!tmpFuncs.empty())
        {
            funcPackage(tmpFuncs.top().funcName.c_str(),
                tmpFuncs.top().funcAddr, tmpAddr);

            tmpAddr = tmpFuncs.top().upperFuncBP;
            tmpFuncs.pop();
        }
#endif
        g_backTraceFlg = false;
    }
}
Exemplo n.º 5
0
VOID Image(IMG img, VOID *)
{
    RTN rtn = RTN_FindByName(img, NAME("NotTraced"));
    if (RTN_Valid(rtn))
        AddrNotTraced = RTN_Address(rtn);

    rtn = RTN_FindByName(img, NAME("IsTraced"));
    if (RTN_Valid(rtn))
        AddrIsTraced = RTN_Address(rtn);
}
// Pin calls this function every time a new img is loaded
VOID ImageLoad(IMG img, VOID *v)
{
    if (!IMG_IsMainExecutable(img))
        return;

    printf("%s loaded\n", IMG_Name(img).c_str());
    fflush(stdout);

    ADDRINT imageBase = IMG_LowAddress(img);
    WINDOWS::PIMAGE_DATA_DIRECTORY pExpDir = GetExportDirectory(imageBase);
    if ((pExpDir == 0) || (pExpDir->Size == 0))
    {
        // Failure: Executable image lacks export directory.
        printf("ERROR: No export directory in executable image\n");
        fflush(stdout);
        exit(3);
    }
    ADDRINT exportBase = imageBase + pExpDir->VirtualAddress;

    // First check that bytes in export directory range do not belong to a RTN
    for (ADDRINT addr = exportBase; addr < exportBase + pExpDir->Size; ++addr)
    {
        if (RTN_FindByAddress(addr) != RTN_Invalid())
        {
            // Test failure. Byte in export directory belongs to a RTN.
            printf("ERROR: Data from export directory included in RTN\n");
            fflush(stdout);
            exit(1);
        }
    }

    // Second check RTN size. RTN range should not overlap with export directory range.
    for (SEC sec = IMG_SecHead(img); sec != SEC_Invalid(); sec = SEC_Next(sec))
    {
        for (RTN rtn = SEC_RtnHead(sec); rtn != RTN_Invalid(); rtn = RTN_Next(rtn))
        {
            if (((RTN_Address(rtn) <= exportBase) && (RTN_Address(rtn) + RTN_Size(rtn) > exportBase)) ||
                ((RTN_Address(rtn) > exportBase) && (exportBase + pExpDir->Size > RTN_Address(rtn))))
            {
                // Test failure. RTN overlaps with export directory.
                printf("ERROR: RTN overlaps with export directory\n");
                fflush(stdout);
                exit(2);
            }
        }
    }

    return;
}
Exemplo n.º 7
0
static VOID Image(IMG img, VOID *v)
{
    RTN rtn = RTN_FindByName(img, watch_rtn);

    if (!RTN_Valid(rtn))
    {
        return;
    }
    printf("Instrumenting %s at %p\n", watch_rtn, reinterpret_cast<void *>(RTN_Address(rtn)));
    RTN_Open(rtn);
    INS ins = RTN_InsHeadOnly(rtn);
    ASSERTX (INS_Valid(ins));
    // version_reg is used to select the version, use the first
    // argument of watch_rtn to set it
    INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(select_version),
                   IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                   IARG_REG_VALUE, version_reg,
                   IARG_RETURN_REGS, version_reg,
                   IARG_END);
    // Note that the version instrumentation will occur before any
    // instrumentation done on this ins from Trace or Instruction 
    // instrumentation time callbacks
    INS_InsertVersionCase(ins, version_reg, 10, VERSION_1, IARG_END);
    INS_InsertVersionCase(ins, version_reg, 20, VERSION_2, IARG_END);
    RTN_Close(rtn);
}
Exemplo n.º 8
0
VOID Routine(RTN rtn, VOID *v)
{
	RTN_Open(rtn);
	RTN_NAME * rn = new RTN_NAME;
    if (KnobOnly){
        if(IMG_IsMainExecutable(SEC_Img(RTN_Sec(rtn))) \
                /*&& std::strcmp(IMG_Name(SEC_Img(RTN_Sec(rtn))).c_str(),"/usr/lib/libSystem.B.dylib")!=0 \*/
                || std::strcmp(IMG_Name(SEC_Img(RTN_Sec(rtn))).c_str(),"/usr/lib/system/libsystem_malloc.dylib")==0)
        {
            funcList.push_back(RTN_Name(rtn));
            cerr << "Getting "<< RTN_Name(rtn) <<endl ;
            //RTN_Close(rtn);
            //return ;
        }
    }

    if(KnobOnly && find (funcList.begin(), funcList.end(), RTN_Name(rtn)) == funcList.end()){
        cerr << "excluding : " << RTN_Name(rtn) ;
        cerr << IMG_Name(SEC_Img(RTN_Sec(rtn))) << endl;
        RTN_Close(rtn);
        return;
    }
    // The RTN goes away when the image is unloaded, so save it now
    // because we need it in the fin
    rn->_name = RTN_Name(rtn);
    rn->_image = IMG_Name(SEC_Img(RTN_Sec(rtn))).c_str();
    rn->_address = RTN_Address(rtn);
	//_address = RTN_Address(rtn);

    // Insert a call at the entry point of a routine to increment the call count
	RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)print, IARG_PTR, rn,IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_END);
	RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)ret,IARG_PTR,rn,IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
	//INS_InsertCall(RTN_InsTail(rtn), IPOINT_BEFORE, (AFUNPTR)ret, IARG_END);
	RTN_Close(rtn);
}
static VOID Ins(INS ins, VOID *v)
{
    RTN rtn = INS_Rtn(ins);
    
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        return;
    }

    if (INS_Address(ins) == RTN_Address(rtn)) 
    {
        INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(Emit),
                       IARG_PTR, "Ins instrumentation", IARG_CALL_ORDER, CALL_ORDER_FIRST+3, IARG_END);
        printf("Ins Instrumenting %s\n", watch_rtn, reinterpret_cast<void *>(RTN_Address(rtn)));
    }
}
Exemplo n.º 10
0
VOID Image(IMG img, VOID *v)
{
    RTN mmapRtn = RTN_FindByName(img, FUNC_PREFIX "mmap");
    if (RTN_Valid(mmapRtn))
    {
        RTN_Open(mmapRtn);
        RTN_InsertCall(mmapRtn, IPOINT_BEFORE, AFUNPTR(MmapArgs), IARG_RETURN_IP, IARG_G_ARG0_CALLEE, IARG_G_ARG1_CALLEE, IARG_G_ARG2_CALLEE, IARG_G_ARG3_CALLEE, IARG_G_ARG4_CALLEE, IARG_G_ARG5_CALLEE, IARG_END);
        RTN_Close(mmapRtn);
    }
    RTN foobarRtn = RTN_FindByName(img, FUNC_PREFIX "foobar");
    if (RTN_Valid(foobarRtn))
    {
        foobarAddress = RTN_Address(foobarRtn);
        
        RTN_Open(foobarRtn);
        RTN_InsertCall(foobarRtn, IPOINT_BEFORE, AFUNPTR(FoobarArgs), IARG_G_ARG0_CALLEE, IARG_G_ARG1_CALLEE, IARG_END);
        RTN_Close(foobarRtn);
    }

    RTN bazRtn = RTN_FindByName(img, FUNC_PREFIX "baz");
    if (RTN_Valid(bazRtn))
    {
        RTN_Open(bazRtn);
        RTN_InsertCall(bazRtn, IPOINT_BEFORE, AFUNPTR(BazArg), IARG_FUNCARG_ENTRYPOINT_REFERENCE, 0, IARG_FUNCARG_ENTRYPOINT_REFERENCE, 1, IARG_FUNCARG_ENTRYPOINT_REFERENCE, 2, IARG_END);
        RTN_Close(bazRtn);
    }

}
static VOID Trace(TRACE trace, VOID *v)
{
    RTN rtn = TRACE_Rtn(trace);
    
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        return;
    }

    if (TRACE_Address(trace) == RTN_Address(rtn)) 
    {
        // Pin does not support issuing an RTN_ReplaceSignature from the TRACE instrumentation callback
        // This will cause Pin to terminate with an error

        PROTO proto_watch_rtn 
            = PROTO_Allocate(PIN_PARG(void), CALLINGSTD_DEFAULT, "watch_rtn", PIN_PARG(int), PIN_PARG_END());

        RTN_ReplaceSignature(rtn, AFUNPTR(WatchRtnReplacement),
            IARG_PROTOTYPE, proto_watch_rtn,
            IARG_CONST_CONTEXT,
            IARG_THREAD_ID,
            IARG_ORIG_FUNCPTR,
            IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
            IARG_END);
    }
/*****************************************************************************
 函 数 名  : rtn
 功能描述  : Pin calls this function every time a new rtn is executed
 输入参数  : RTN rtn
             VOID * v
 输出参数  : 无
 返 回 值  :
 调用函数  :
 被调函数  :

 修改历史      :
  1.日    期   : 2012年5月16日
    作    者   : @zhi
    修改内容   : 新生成函数

*****************************************************************************/
VOID rtn(RTN rtn, VOID * v)
{
    //干掉系统的动态连接库, 即IMG为/lib/*
    if(EXCEPT_SEC == IMG_Name(SEC_Img(RTN_Sec(rtn)))
            .substr(0, EXCEPT_SEC.size()))
    {
        return;
    }

    RTN_Open(rtn);

    if ( g_backTraceFlg )
    {
        //第一次进入,回溯已调用的函数(附加到进程模式)
        //, 参数为待执行函数的函数名,函数起始地址,函数EBP(函数初始未压栈)
        RTN_InsertCall(rtn, IPOINT_BEFORE,
                       (AFUNPTR)traceBack,
                       //IARG_PTR, RTN_Name(rtn).c_str(),
                       //IARG_ADDRINT, RTN_Address(rtn),
                       IARG_REG_VALUE, REG_STACK_PTR,
                       IARG_REG_VALUE, REG_EBP, IARG_END);
    }
    RTN_InsertCall(rtn, IPOINT_BEFORE,
                   (AFUNPTR)funcPackage,
                   IARG_PTR, RTN_Name(rtn).c_str(),
                   IARG_ADDRINT, RTN_Address(rtn),
                   IARG_REG_VALUE, REG_EBP,
                   //IARG_REG_VALUE, REG_STACK_PTR, IARG_END);
                   IARG_END);
    RTN_Close(rtn);
}
Exemplo n.º 13
0
// Pin calls this function every time a new rtn is executed
VOID Routine(RTN rtn, VOID *v)
{
    
    // Allocate a counter for this routine
    RTN_COUNT * rc = new RTN_COUNT;

    // The RTN goes away when the image is unloaded, so save it now
    // because we need it in the fini
    rc->_name = RTN_Name(rtn);
    rc->_image = StripPath(IMG_Name(SEC_Img(RTN_Sec(rtn))).c_str());
    rc->_address = RTN_Address(rtn);
    rc->_icount = 0;
    rc->_rtnCount = 0;

    // Add to list of routines
    rc->_next = RtnList;
    RtnList = rc;
            
    RTN_Open(rtn);
            
    // Insert a call at the entry point of a routine to increment the call count
    RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)docount, IARG_PTR, &(rc->_rtnCount), IARG_END);
    
    // For each instruction of the routine
    for (INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins))
    {
        // Insert a call to docount to increment the instruction counter for this rtn
        INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)docount, IARG_PTR, &(rc->_icount), IARG_END);
    }

    
    RTN_Close(rtn);
}
Exemplo n.º 14
0
static VOID Trace(TRACE trace, VOID *v)
{
    RTN rtn = TRACE_Rtn(trace);
    
    ADDRINT version = TRACE_Version(trace);
    // If we are not in watch_rtn, switch back to base version
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        if (version != VERSION_BASE)
            BBL_SetTargetVersion(TRACE_BblHead(trace), VERSION_BASE);
        return;
    }

    if (TRACE_Address(trace) == RTN_Address(rtn)) {
        INS ins = BBL_InsHead(TRACE_BblHead(trace));
        if (version == VERSION_BASE) 
        {
            // version_reg is used to select the version, use the first
            // argument of watch_rtn to set it
            INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(select_version),
                           IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
                           IARG_RETURN_REGS, version_reg,
                           IARG_END);
            // IF we are in the base version, decide if we should go to the
            // other versions
            // Note that the version instrumentation will occur before any
            // following instrumentation done on this ins
            INS_InsertVersionCase(ins, version_reg, 10, VERSION_1, IARG_END);
            INS_InsertVersionCase(ins, version_reg, 20, VERSION_2, IARG_END);
            printf ("Instrumentation at %p\n", reinterpret_cast<void *>(INS_Address(ins)));
        }
    }

    INS ins = BBL_InsHead(TRACE_BblHead(trace));
    for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl)) 
    {
        // Instrumentation depends on version
        // These instrumentations occur after the preceeding version instrumentation
        // (i.e. the instrumentation inserted by the above INS_InsertVersionCase calls
        switch(version) {
          case VERSION_BASE:
            INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "version base", IARG_END);
            break;
          case VERSION_1:
            INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "version 1", IARG_END);
            break;
          case VERSION_2:
            INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "version 2", IARG_END);
            break;
          default:
            assert(0);
            break;
        }
    }
}
Exemplo n.º 15
0
void DoReplacementFunc( IMG img, char * funcName)
{
    RTN rtnToReplace;
    printf ("Image %s\n", IMG_Name(img).c_str());

    for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
    {     
        for (RTN rtn = SEC_RtnHead(sec); RTN_Valid(rtn); rtn = RTN_Next(rtn))
        {
           printf ("  Rtn: %s  %s\n", RTN_Name(rtn).c_str(), funcName);
           if (strstr( RTN_Name(rtn).c_str(), funcName))
           {
               //printf ("    found\n");
               foundFunc = true;
               rtnToReplace = rtn;
               break;
           }
        }
        if (foundFunc)
        {
            break;
        }
    }
    if (!foundFunc)
    {
        return;
    }

    printf ( "Found %s %x\n", funcName, RTN_Address(rtnToReplace));
    // commented out so that absence of pdb file will not cause failure
    if (RTN_IsSafeForProbedReplacement(rtnToReplace))
    {  
        printf ( "RTN_ReplaceSignatureProbed on %s\n", funcName);
        foundFunc = true;
        
        PROTO protoOfStdCallFunction1ToBeReplacedByPin 
            = PROTO_Allocate( PIN_PARG(void *), 
                              CALLINGSTD_STDCALL,
                              "protoOfStdCallFunction1ToBeReplacedByPin", 
                              PIN_PARG(char), 
                              PIN_PARG(int),
                              PIN_PARG(char), 
                              PIN_PARG(int),
                              PIN_PARG_END() );
        
        RTN_ReplaceSignatureProbed(rtnToReplace, AFUNPTR(ReplacementFunc),
            IARG_PROTOTYPE, protoOfStdCallFunction1ToBeReplacedByPin,
            IARG_ORIG_FUNCPTR,
            IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
            IARG_FUNCARG_ENTRYPOINT_VALUE, 1,
            IARG_FUNCARG_ENTRYPOINT_VALUE, 2,
            IARG_FUNCARG_ENTRYPOINT_VALUE, 3,
            IARG_END);
        PROTO_Free( protoOfStdCallFunction1ToBeReplacedByPin );
    }    
}
Exemplo n.º 16
0
// - Get initial entropy
// - Get PE section data 
// - Add filtered library
void imageLoadCallback(IMG img,void *){

	Section item;
	static int va_hooked = 0;

	//get the initial entropy of the PE
	//we have to consder only the main executable and avìvoid the libraries
	if(IMG_IsMainExecutable(img)){
		
		ProcInfo *proc_info = ProcInfo::getInstance();
		//get the  address of the first instruction
		proc_info->setFirstINSaddress(IMG_Entry(img));
		//get the program name
		proc_info->setProcName(IMG_Name(img));
		//get the initial entropy
		MYINFO("----------------------------------------------");
		float initial_entropy = proc_info->GetEntropy();
		proc_info->setInitialEntropy(initial_entropy);
		MYINFO("----------------------------------------------");
		//retrieve the section of the PE
		for( SEC sec= IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec) ){
			item.name = SEC_Name(sec);
			item.begin = SEC_Address(sec);
			item.end = item.begin + SEC_Size(sec);
			proc_info->insertSection(item);
		}
		//DEBUG
		proc_info->PrintSections();
	}
	//build the filtered libtrary list
	FilterHandler *filterH = FilterHandler::getInstance();
	ADDRINT startAddr = IMG_LowAddress(img);
	ADDRINT endAddr = IMG_HighAddress(img);
	const string name = IMG_Name(img); 

	if(!IMG_IsMainExecutable(img) && filterH->isKnownLibrary(name)){	

		/* searching for VirtualAlloc */ 
		RTN rtn = RTN_FindByName( img, "VirtualAlloc");
		if(rtn != RTN_Invalid()){
			MYINFO("BECCATO LA VIRTUAL ALLOC\n");
			ADDRINT va_address = RTN_Address(rtn);
			MYINFO("Address of VirtualAlloc: %08x\n" , va_address);

			RTN_Open(rtn); 	
			RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)VirtualAllocHook , IARG_G_ARG0_CALLEE , IARG_G_ARG1_CALLEE , IARG_G_RESULT0, IARG_END);
			RTN_Close(rtn);
		
		}

		filterH->addLibrary(name,startAddr,endAddr);

	}
}
static VOID Trace(TRACE trace, VOID *v)
{
    RTN rtn = TRACE_Rtn(trace);
    
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        return;
    }

    if (TRACE_Address(trace) == RTN_Address(rtn)) 
    {        
        TRACE_InsertCall(trace, IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "Trace instrumentation", IARG_CALL_ORDER, CALL_ORDER_FIRST+2, IARG_END);
        BBL_InsertCall(TRACE_BblHead(trace), IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "Trace_BBL instrumentation", IARG_CALL_ORDER, CALL_ORDER_FIRST+2, IARG_END);
        INS_InsertCall(BBL_InsHead(TRACE_BblHead(trace)), IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "Trace_INS instrumentation", IARG_CALL_ORDER, CALL_ORDER_FIRST+2, IARG_END);
        printf("Trace Instrumenting %s\n", watch_rtn, reinterpret_cast<void *>(RTN_Address(rtn)));
    }
}
Exemplo n.º 18
0
static void InstrumentRtn(RTN rtn, VOID *)
{
	ADDRINT a = RTN_Address(rtn);
	IMG img = IMG_FindByAddress(a);

	if (IMG_Valid(img) &&
	    IMG_IsMainExecutable(img)) {
		RTN_Open(rtn);
		RTN_InsertCall(rtn, IPOINT_BEFORE, AFUNPTR(FunctionHook), IARG_ADDRINT, a, IARG_END);
		RTN_Close(rtn);
	}
}
static VOID Rtn(RTN rtn, VOID *v)
{
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        return;
    }
    printf("Rtn Instrumenting %s\n", watch_rtn, reinterpret_cast<void *>(RTN_Address(rtn)));
    RTN_Open(rtn);

    RTN_InsertCall(rtn, IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "RTN instrumentation", IARG_CALL_ORDER, CALL_ORDER_FIRST+1, IARG_END);
    RTN_Close(rtn);
}
Exemplo n.º 20
0
static void 
I_ImageLoad(IMG img, void *v) 
{
  static bool main_rtn_instrumented = false;

  if( !main_rtn_instrumented ) {
    RTN rtn = RTN_FindByName(img, "main");
    if( rtn == RTN_Invalid() ) {
      rtn = RTN_FindByName(img, "__libc_start_main");      
    }
    // Instrument main
    if( rtn != RTN_Invalid() ) {
      main_rtn_instrumented = true;
      RTN_Open(rtn);
      RTN_InsertCall(rtn, IPOINT_BEFORE,
		     (AFUNPTR)A_EnterMainImage,
		     IARG_INST_PTR,
		     IARG_ADDRINT, RTN_Address(rtn),
		     IARG_REG_VALUE, REG_STACK_PTR,
		     IARG_END);
      RTN_Close(rtn);
    }
  }

  for( SYM sym = IMG_RegsymHead(img); SYM_Valid(sym); sym = SYM_Next(sym) ) {
    if( strstr(SYM_Name(sym).c_str(), "MAID_register_address" ) ) {
      RTN rtn;
      rtn = RTN_FindByName(img, SYM_Name(sym).c_str());
      ASSERTX(RTN_Valid(rtn));

      RTN_Open(rtn);
      RTN_InsertCall(rtn, IPOINT_BEFORE,
                     (AFUNPTR)A_RegisterAddr,
                     IARG_G_ARG0_CALLEE,
                     IARG_END);
      RTN_Close(rtn);
    } else if( strstr(SYM_Name(sym).c_str(), "MAID_unregister_address" ) ) {
      RTN rtn;
      rtn = RTN_FindByName(img, SYM_Name(sym).c_str());
      ASSERTX(RTN_Valid(rtn));
      RTN_Open(rtn);
      RTN_InsertCall(rtn, IPOINT_BEFORE,
		     (AFUNPTR)A_UnregisterAddr,
		     IARG_G_ARG0_CALLEE,
		     IARG_END);
      RTN_Close(rtn);
    }
  }

}
Exemplo n.º 21
0
//scan the image and try to hook all the function specified above
void HookFunctions::hookDispatcher(IMG img){
	//for each function that we want to hook or replace
	for (std::map<string,int>::iterator item = this->functionsMap.begin(); item != this->functionsMap.end(); ++item){
		//get the pointer to the specified function
		const char * func_name = item->first.c_str();
		RTN rtn = RTN_FindByName(img, func_name);
		//if we found a valid routine
		if(rtn != RTN_Invalid()){		
			ADDRINT va_address = RTN_Address(rtn);
			MYINFO("Inside %s Address of %s: %08x" ,IMG_Name(img).c_str(),func_name, va_address);
			RTN_Open(rtn); 	
			int index = item->second;
			//decide what to do based on the function hooked
			//Different arguments are passed to the hooking routine based on the function
			switch(index){
				case(VIRTUALALLOC_INDEX):
					RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)VirtualAllocHook , IARG_FUNCARG_ENTRYPOINT_VALUE,1 , IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
					break;
				case(RTLALLOCATEHEAP_INDEX):
					//need to be IPOINT_AFTER because the allocated address is returned as return value
					RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)RtlAllocateHeapHook , IARG_FUNCARG_ENTRYPOINT_VALUE,2, IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
					break;
				case(ISDEBUGGERPRESENT_INDEX):
					RTN_Replace(rtn, AFUNPTR(IsDebuggerPresentHook));
					break;
				case(RTLREALLOCATEHEAP_INDEX):
					//IPOINT_BEFORE because the address to be realloc is passed as an input paramenter
					RTN_InsertCall(rtn,IPOINT_BEFORE,(AFUNPTR)RtlReAllocateHeapHook, IARG_FUNCARG_ENTRYPOINT_VALUE,2 , IARG_FUNCARG_ENTRYPOINT_VALUE,3, IARG_END);
					break;
				case(MAPVIEWOFFILE_INDEX):
					//need to be IPOINT_AFTER because the allocated address is returned as return value
					RTN_InsertCall(rtn,IPOINT_AFTER,(AFUNPTR)MapViewOfFileHookAfter,IARG_FUNCARG_ENTRYPOINT_VALUE,1,IARG_FUNCARG_ENTRYPOINT_VALUE,2,IARG_FUNCARG_ENTRYPOINT_VALUE,3, IARG_FUNCARG_ENTRYPOINT_VALUE,4,IARG_FUNCRET_EXITPOINT_VALUE,  IARG_END);
					break;
				case(VIRTUALFREE_INDEX):
					RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)VirtualFreeHook , IARG_FUNCARG_ENTRYPOINT_VALUE,0, IARG_END);
					break;
				case(VIRTUALQUERY_INDEX):
					//IPOINT_AFTER because we have to check if the query is on a whitelisted address
					RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)VirtualQueryHook, IARG_FUNCARG_ENTRYPOINT_VALUE, 0, IARG_FUNCARG_ENTRYPOINT_VALUE, 1, IARG_FUNCRET_EXITPOINT_REFERENCE, IARG_END);
					break;
				case(VIRTUALQUERYEX_INDEX):
					//IPOINT_AFTER because we have to check if the query is on a whitelisted address
					RTN_InsertCall(rtn, IPOINT_AFTER, (AFUNPTR)VirtualQueryExHook, IARG_FUNCARG_ENTRYPOINT_VALUE, 0,  IARG_FUNCARG_ENTRYPOINT_VALUE, 1, IARG_FUNCARG_ENTRYPOINT_VALUE, 2, IARG_FUNCRET_EXITPOINT_REFERENCE, IARG_END);
					break;
				}			
			RTN_Close(rtn);
		}
	}
}
Exemplo n.º 22
0
// -------------------------------------------------------------
// Get function address by branch target address
// -------------------------------------------------------------
ADDRINT Target2FunAddr(ADDRINT target) {
    PIN_LockClient();
    
    ADDRINT funAddr;
    
    const RTN rtn = RTN_FindByAddress(target);

    if ( RTN_Valid(rtn) ) 
         funAddr = RTN_Address(rtn);
    else funAddr = target;

    PIN_UnlockClient();

    return funAddr;
}
static VOID Image(IMG img, VOID *v)
{
    RTN rtn = RTN_FindByName(img, watch_rtn);

    if (!RTN_Valid(rtn))
    {
        return;
    }
    printf("Image Instrumenting %s\n", watch_rtn, reinterpret_cast<void *>(RTN_Address(rtn)));
    RTN_Open(rtn);
    
    RTN_InsertCall(rtn, IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "IMG instrumentation", IARG_CALL_ORDER, CALL_ORDER_FIRST, IARG_END);
    RTN_Close(rtn);
    
}
static VOID Trace(TRACE trace, VOID *v)
{
    RTN rtn = TRACE_Rtn(trace);
    
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        return;
    }

    if (TRACE_Address(trace) == RTN_Address(rtn)) 
    {        
        TRACE_InsertCall(trace, IPOINT_BEFORE, AFUNPTR(Emit),
                             IARG_PTR, "Trace instrumentation", IARG_CALL_ORDER, CALL_ORDER_FIRST+3, IARG_END);
        printf("Trace Instrumenting %s\n", watch_rtn);
    }
}
Exemplo n.º 25
0
static VOID ImageLoadCallback(IMG img, VOID *v)
{
    if (threadFunction == 0)
    {
        if (KnobVerbose)
            cerr << "Looking for doNothing in " << IMG_Name(img) << "\n";

        RTN rtn = RTN_FindByName (img, "doNothing");

        if (RTN_Valid(rtn))
        {
            threadFunction = RTN_Address(rtn);
            if (KnobVerbose)
                cerr << "'doNothing' at " << hex << threadFunction << dec << "\n";
        }            
    }
}
Exemplo n.º 26
0
static VOID OnImage(IMG img, VOID *)
{
    RTN rtn = RTN_FindByName(img, "PIN_TEST_FOO");
    if (RTN_Valid(rtn))
    {
        RTN_Open(rtn);
        RTN_InsertCall(rtn, IPOINT_BEFORE, AFUNPTR(OnFoo), IARG_CONTEXT, IARG_THREAD_ID, IARG_END);
        RTN_Close(rtn);
    }

    rtn = RTN_FindByName(img, "PIN_TEST_BAR");
    if (RTN_Valid(rtn))
    {
        BarAddr = RTN_Address(rtn);
        FoundBar = TRUE;
    }
}
static VOID Trace(TRACE trace, VOID *v)
{
    RTN rtn = TRACE_Rtn(trace);
    
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        return;
    }

    if (TRACE_Address(trace) == RTN_Address(rtn)) 
    {
        // Pin does not support issuing an RTN_Replace from the TRACE instrumentation callback
        // This will cause Pin to terminate with an error

        RTN_Replace(rtn, AFUNPTR(WatchRtnReplacement));
    }

}
static VOID Instruction(INS ins, VOID *v)
{
    RTN rtn = INS_Rtn(ins);
    
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        return;
    }

    if (INS_Address(ins) == RTN_Address(rtn)) 
    {
        // Pin does not support issuing an RTN_Replace from the INS instrumentation callback
        // This will cause Pin to terminate with an error


        RTN_Replace(rtn, AFUNPTR(WatchRtnReplacement));
    }

}
Exemplo n.º 29
0
static VOID Trace(TRACE trace, VOID *v)
{
    RTN rtn = TRACE_Rtn(trace);
    
    if (!RTN_Valid(rtn) || RTN_Name(rtn) != watch_rtn)
    {
        return;
    }

    if (TRACE_Address(trace) == RTN_Address(rtn)) 
    {
        // Pin does not support issuing an RTN_InsertCall from the TRACE instrumentation callback
        // This will cause Pin to terminate with an error
        RTN_Open(rtn);
        RTN_InsertCall(rtn, IPOINT_BEFORE, AFUNPTR(Emit),
                       IARG_PTR, "Ins instrumentation1", IARG_END);
        RTN_Close(rtn);
    }
}
Exemplo n.º 30
0
/*!
 * Test SafeCopy in the image instrumentation callback
 */
VOID ImageLoad(IMG img, VOID *v)
{
#if defined(TARGET_WINDOWS)
    // Pin on Windows inserts a probe that intercepts APCs at KiApcUserDispatcher
    RTN rtn = RTN_FindByName(img, "KiUserApcDispatcher");
    if (RTN_Valid(rtn))
    {
        probeAddr = (VOID *)RTN_Address(rtn);
    }
#endif

    static BOOL first = TRUE;
    if (first)
    {
        first = FALSE;
        out << "Test SafeCopy in the image instrumentation callback." << endl << flush;
        SafeCopyTest();
    }
}