Skip to content

gettimeofday example in tutorial uses wrong structure def #1657

Closed
@brson

Description

@brson

This is the gettimeofday example from the tutorial, with the addition that it prints the result

use std;
type timeval = {mutable tv_sec: u32,
                mutable tv_usec: u32};

#[nolink]
native mod libc {
    fn gettimeofday(tv: *timeval, tz: *()) -> i32;
}

fn unix_time() -> u64 unsafe {
    let x = {mutable tv_sec: 0u32, mutable tv_usec: 0u32};
    libc::gettimeofday(ptr::addr_of(x), ptr::null());
    ret (x.tv_sec as u64) * 1000_000_u64 + (x.tv_usec as u64);
}

fn main() {
    std::io::println(#fmt("%u", unix_time()));
}

It crashes, because timeval is defined incorrectly and gettimeofday ends up overwriting other parts of the stack. On 64-bit linux I show both fields of timeval having 8 bytes.

Probably we should add time_t and suseconds_t to core::ctypes

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions