Skip to content

Instantly share code, notes, and snippets.

@Hi-Angel
Last active January 4, 2019 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hi-Angel/6e96e3bfd4ee28c046954debfdea6c8e to your computer and use it in GitHub Desktop.
Save Hi-Angel/6e96e3bfd4ee28c046954debfdea6c8e to your computer and use it in GitHub Desktop.
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
extern "C"
int clock_gettime(clockid_t clk_id, struct timespec *tp) {
using clock_gettime_ptr = int (*)(clockid_t, struct timespec*);
const static clock_gettime_ptr real_clock_gettime
= (clock_gettime_ptr) dlsym(RTLD_NEXT, "clock_gettime");
int ret = real_clock_gettime(clk_id, tp);
if (ret != -1) {
const short AMOUNT_TO_SLOW = 4;
const time_t NSEC_FRAC = 1000000000 / AMOUNT_TO_SLOW;
const long nsec_part = NSEC_FRAC * (tp->tv_sec % AMOUNT_TO_SLOW);
tp->tv_nsec = tp->tv_nsec / AMOUNT_TO_SLOW + nsec_part;
tp->tv_sec = tp->tv_sec / AMOUNT_TO_SLOW;
}
return ret;
}
#[macro_use]
extern crate lazy_static;
extern crate libc;
use libc::{clockid_t, timespec, c_int};
#[no_mangle]
pub extern "C" fn clock_gettime(clk_id: clockid_t, tp: *mut timespec) -> c_int {
type ClockGettimeType = fn(clk_id: clockid_t, tp: *mut timespec) -> c_int;
unsafe {
lazy_static! {
static ref real_clock_gettime: ClockGettimeType = unsafe {
let f = libc::dlsym(libc::RTLD_NEXT, "clock_gettime\0".as_ptr() as *const i8);
std::mem::transmute::<*const libc::c_void, ClockGettimeType>(f)
};
}
let ret = real_clock_gettime(clk_id, tp);
if ret != -1 {
let amount_to_slow = 4;
let nsec_frac = 1000000000 / amount_to_slow;
let nsec_part = nsec_frac * ((*tp).tv_sec % amount_to_slow);
(*tp).tv_nsec = (*tp).tv_nsec / amount_to_slow + nsec_part;
(*tp).tv_sec = (*tp).tv_sec / amount_to_slow;
}
ret
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment