So I am still kind of a beginner in NASM x64. I am writing a rock paper scissors program and I decided that instead of getting a random number I should just get the last digit of milliseconds. I already know how to get the time in seconds:
section .text:
global _start
_start:
mov rax, 201
xor rdx, rdx ; if rdx is empty, the time value will go to rax
syscall
; exit
mov rax, 60
mov rdi, 0
syscall
I've tested it out and it works. How can I do the exact same thing, but rax will hold the value in milliseconds? (I am not saying multiply by 1000, I want the real value)
I have looked for a really long time: went through the syscall table, searched it up, look at a university's course plan. I even asked an AI. So I'm at my last resort asking you guys. Any help would be greatly appreciated.
CodePudding user response:
There is the gettimeofday
system call which gives you microseconds, or clock_gettime
that gives you nanoseconds. They are a little more work to call, since they return the time in a buffer rather than in a register, but you can allocate a temporary buffer on the stack. If you specifically care about getting milliseconds, then divide by 1000 or 1000000 accordingly.
If you're going to go to the trouble to make a system call, though, why not do it right and call getrandom(2)
for some more truly random bytes?
Untested example of getrandom
:
sub rsp, 16 ; make some stack space, maintain alignment
mov rdi, rsp ; point rdi at our stack buffer
mov esi, 1 ; read one byte
xor edx, edx ; no flags needed
mov eax, 318 ; see https://chromium.googlesource.com/chromiumos/docs/ /HEAD/constants/syscalls.md#x86_64-64_bit
syscall
; check for errors here; left as an exercise
movzx eax, byte [rsp] ; load the byte from stack into eax, zero the high bits
add rsp, 16 ; clean up the stack