Created
July 16, 2019 20:03
-
-
Save NateSeymour/0b3f789ab8b72e8cc1c683dfc06d0b68 to your computer and use it in GitHub Desktop.
Random number generator in x86 MacOS assembly (AT&T) syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The most awesome, awe inspiring random number generator ever | |
# Error codes: | |
# 0x0 - Could not open file | |
# 0x1 - No bytes read from file | |
.bss | |
.data | |
output: .asciz "Random number: %i \n" | |
path: .asciz "/dev/random" | |
fd_is: .asciz "The File descriptor is: %i \n" | |
end_message: .asciz "I hope you enjoyed the most awe inspiring random number generator ever\n" | |
error_message: .asciz "Error code: %i\nExiting..." | |
.lcomm buffer, 4 | |
.lcomm fd, 4 | |
.text | |
.globl _main | |
_main: | |
# First open the file? | |
# int open(const char *path, int flags, ...) | |
subl $0x04, %esp # Pad the stack | |
pushl $0x0 # This is the flag for O_RDONLY | |
pushl $path # Then add the path | |
call _open # Make the call to open | |
movl %eax, fd # Put the file descriptor into the fd variable | |
addl $0xC, %esp | |
# Check for errors | |
cmpl $0x0, fd | |
movl $0x0, %eax | |
jl error | |
# Ok now we have to read from the file | |
# ssize_t read(int fd, void *buf, size_t nbytes); | |
pushl $0x4 # We want to read 4 bytes | |
pushl $buffer # Provide the buffer | |
pushl fd # And our file descriptor | |
call _read # Read the file :) | |
addl $0xC, %esp | |
# Check for errors | |
cmpl $0x0, %eax | |
movl $0x1, %eax | |
je error | |
# Ok, now because we want a number between 0-15, we need to do some arithmetic :) | |
movl buffer, %eax | |
and $0xF, %eax # 00001111 | |
movl %eax, buffer | |
# Now we need to display what we read | |
pushl $0x4 | |
pushl buffer | |
pushl $output | |
call _printf | |
addl $0x4, %esp | |
# Let's close the file | |
# int close(int fd); | |
pushl fd # Push the file descriptor onto the stack | |
call _close # Close that bitch | |
addl $0x4, %esp | |
# Display a nice message and leave | |
pushl $end_message # Put our message on da stack | |
call _printf # Print the message | |
# Goodbye :) | |
call _exit | |
nop | |
error: | |
subl $0x4, %esp | |
pushl %eax | |
pushl $error_message | |
call _printf | |
call _exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment