修改C语言中的时间函数

3

为了完成一项与计算机安全相关的任务,我需要修改时间函数以返回特定日期。我需要时间函数返回2016年1月1日至2018年6月15日之间的日期。然后,我使用以下命令来重载和挂钩时间函数:

gcc -Wall -fPIC -shared -o newtime.so newtime.c -ldl
export LD_PRELOAD=$PWD/newtime.so

这是我修改过的时间函数版本:
#define _GNU_SOURCE

#include <dlfcn.h>
#include <time.h>

time_t time (time_t *t)
{
    long int seconds = 1485907200;
    time_t modifiedTime = (time_t) seconds;
    return modifiedTime;
}

每当我运行这个实现时,它都会说返回的日期是1969年12月31日19:00:00。我是只是格式化Linux纪元后的时间不正确还是犯了更严重的错误?我已经尝试使用常规int而不是long int,但仍然遇到相同的问题。对于我的错误的一些见解将非常有帮助。
2个回答

2
您没有实现time()的全部功能。 您正在干涉的代码可能使用了您尚未实现的功能。
根据C标准(链接)

7.27.2.4 The time function (note the bolded part):

Synopsis

     #include <time.h>
     time_t time(time_t *timer);

Description

The time function determines the current calendar time. The encoding of the value is unspecified.

Returns

The time function returns the implementation's best approximation to the current calendar time. The value (time_t)(-1) is returned if the calendar time is not available. If timer is not a null pointer, the return value is also assigned to the object it points to.

一个基于您的代码的完整实现:
time_t time (time_t *t)
{
    long int seconds = 1485907200;
    time_t modifiedTime = (time_t) seconds;

    if ( t )
    {
        *t = modifiedTime;
    }

    return modifiedTime;
}

谢谢,那真的解决了我的问题。我也理解了。我没有传递一个空值,所以它默认为时间实现。 - Colin Null

0

实际上,您提供的代码没有问题。我使用以下基本程序进行了测试:

#include <stdio.h>
#include <time.h>

int main(void)
{
    printf("%ld\n", (long) time(NULL));
}

所以我只需要运行LD_PRELOAD=./newtime.so ./test,就可以得到预期的结果。

然而,date命令不会调用time函数。它调用的是int clock_gettime(clockid_t clk_id, struct timespec *tp)。因此,如果您想覆盖这种情况,最好重新实现它们两个。

可能一个简单的实现如下(它在date中运行良好):

int clock_gettime(clockid_t clk_id, struct timespec *tp)
{
    if(tp) {
        tp->tv_sec = 1485907200;
        tp->tv_nsec = 0;
    }
    return 0;
}

如果你得到的日期与你的预期不同,可能与你的时区有关。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接