每个人。我有一个项目调用一些函数来获取时间,例如
time_t t = time(NULL);
#ifndef _WIN32
timespec ts;
if( -1 == clock_gettime(CLOCK_MONOTONIC,&ts) )
GenErrnoErr()
return uint64( ( ((uint64)ts.tv_sec*1000 + (uint64)ts.tv_nsec/1000000) - m_uBaseTime ) * ms_dTimeRatio ) ;
#else
LARGE_INTEGER uTime;
QueryPerformanceCounter(&uTime);
return uint64( ( uint64(uTime.QuadPart/CFrequency::Instance().Get().QuadPart) - m_uBaseTime ) * ms_dTimeRatio );
#endif
`
我想要的是一直 Hook func,而不更改现有代码。当它调用 time(NULL) 或其他函数时,它返回我伪造的时间。
最佳答案
完成这种事情的通常方法是使用链接器的 --wrap
选项。它是这样工作的:
- 编写替换函数,但不要将其命名为
time(...)
,而是将其命名为__wrap_time(...)
; - 在你的替换函数中,如果你需要调用原来的
time()
函数,实际调用__real_time()
; - 链接程序时,添加以下选项:
--wrap=time
。这将使链接器将任何其他模块对time()
的调用链接到__wrap_time()
,但仍允许原始的time()
函数通过__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)
关于c++ - 如何 Hook 时间功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39929748/