c++ - 如何 Hook 时间功能

标签 c++ linux windows api

每个人。我有一个项目调用一些函数来获取时间,例如

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 选项。它是这样工作的:

  1. 编写替换函数,但不要将其命名为time(...),而是将其命名为__wrap_time(...)
  2. 在你的替换函数中,如果你需要调用原来的time()函数,实际调用__real_time();
  3. 链接程序时,添加以下选项:--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/

相关文章:

c++ - 单击按钮时将当前位置/订单保存在 QTabWidget 中 - 用户设置

c++ - 如何分配和访问 3D、4D、5D 数组?

linux - awk 在 centOS 7 上就位

c - 如何使用 getpwuid_r() 正确设置缓冲区和 bufsize?

c++ - 是否可以在不复制非常大的 std::vector 的情况下执行 Rcpp::wrap

c++ - linux上的系统时间变化检测

windows - 安装 fugitive.vim 插件后,Vim 在 Cygwin 下启动非常慢

php - 寻找用于 windows 的 SMTP 服务器

linux - 我多早可以在 arm linux 内核中调用 kalloc?

c - Frama-c 镁 : Unable to execute WP plugin on Windows