zwj0571 zwj0571 - 1 year ago 98
Linux Question

How To hook time function

EveryOne. I have a project which call some func to get time such as

time_t t = time(NULL);

#ifndef _WIN32
timespec ts;
if( -1 == clock_gettime(CLOCK_MONOTONIC,&ts) )
return uint64( ( ((uint64)ts.tv_sec*1000 + (uint64)ts.tv_nsec/1000000) - m_uBaseTime ) * ms_dTimeRatio ) ;
return uint64( ( uint64(uTime.QuadPart/CFrequency::Instance().Get().QuadPart) - m_uBaseTime ) * ms_dTimeRatio );


what I wana is to hook all this time func, without change the code exist. when it calls time(NULL) or other func, it returns the time i faked.

Answer Source

The usual way that this sort of thing is done is with the --wrap option to the linker. It works like this:

  1. Write your replacement function, but instead of naming it time(...), name it __wrap_time(...);
  2. In your replacement function, if you need to call the original time() function, actually call __real_time();
  3. When linking the program, add the following option: --wrap=time. This will make the linker link any other module's call to time() to __wrap_time(), and yet still allow the original time() function to be called via __real_time().


// Need this to satisfy the compiler
extern time_t __real_time(time_t *seconds);

time_t __wrap_time(time_t *seconds) {
    if (seconds==NULL) {
        return 0;
    } // if
    return __real_time(seconds)
} // __wrap_time(seconds)