Question

I am trying to seed my random number generator with current system time. How can I access the system time using NASM? (I am using linux)

Was it helpful?

Solution

%define RTCaddress  0x70
%define RTCdata     0x71

;Get time and date from RTC

.l1:    mov al,10           ;Get RTC register A
    out RTCaddress,al
    in al,RTCdata
    test al,0x80            ;Is update in progress?
    jne .l1             ; yes, wait

    mov al,0            ;Get seconds (00 to 59)
    out RTCaddress,al
    in al,RTCdata
    mov [RTCtimeSecond],al

    mov al,0x02         ;Get minutes (00 to 59)
    out RTCaddress,al
    in al,RTCdata
    mov [RTCtimeMinute],al

    mov al,0x04         ;Get hours (see notes)
    out RTCaddress,al
    in al,RTCdata
    mov [RTCtimeHour],al

    mov al,0x07         ;Get day of month (01 to 31)
    out RTCaddress,al
    in al,RTCdata
    mov [RTCtimeDay],al

    mov al,0x08         ;Get month (01 to 12)
    out RTCaddress,al
    in al,RTCdata
    mov [RTCtimeMonth],al

    mov al,0x09         ;Get year (00 to 99)
    out RTCaddress,al
    in al,RTCdata
    mov [RTCtimeYear],al

    ret

This uses NASM, and is from here.

OTHER TIPS

Using linux:

mov eax, 13
push eax
mov ebx, esp
int 0x80
pop eax

Will pop the current unix time into eax (just replace the last instruction if you want it popped into another register).

This is a system call to sys_time (system call number 13), and it returns the time into the memory location in ebx, which is the top of the stack.

I'd say, depending on what platform you're on, you'll have to use an OS function.

On windows, try GetSystemTime. On linux, try gettimeofday - see related question here.

With NASM, if you are targeting Linux x86-64, you can simply do the following:

mov rax, 201
xor rdi, rdi        
syscall

201 corresponds to the 64-bit system call number for sys_time (as listed here). Register rdi is set to 0 so the return value after performing the system call is stored in rax, but you could also make it point to a memory location of your choosing. The result is expressed in seconds since the Epoch.

More information about this system call can be found in the time man page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top