array.asm

URL: http://147.64.242.52/~bennett/class/cmsc3100/spring2026/notes/dynam/code/array.asm
 
%include "CONSTANTS.h"

extern malloc
extern free

section .data

     ; the equivelent to 
     ;   long * a
     arrayAddress: dq 0
     arrayElements: dq 10

     addressMsg: db `The array is at %#Lx\n`,0
     arrayElementFmt: db `A[%d] = %d\n`,0


section .bss

section .text
global main
main:

     ; a =  malloc(sizeof(long) * arraySize)
     mov rdi,arrayElements 
     mov rax, 8
     mul rdi
     mov rdi, rax
     call malloc

     ; save this, we will need it
     mov [arrayAddress], rax

     ; cout << a    just look at the base address of the array.
     mov rdi, addressMsg
     mov rsi, [arrayAddress] 
     call CallPrintf


     ; fill the array with random numbers
     mov rdi, [arrayAddress]
     mov rsi, [arrayElements]
     call FillArray

     ; print the array
     mov rdi, [arrayAddress]
     mov rsi, [arrayElements]
     call PrintArray

     ; free(a)
     mov rdi, [arrayAddress]
     call free

    jmp Exit

;   rdi holds the array address
;   rsi holds the array size
PrintArray:
    push rbp
    mov rbp, rsp

    push r12   ;  the lcv
    push r13   ;  storage for the array size
    push r14   ; storage for the base address of the array

    mov r14, rdi
    mov r13, rsi

    ; i = 0
    mov r12, 0
.top:
    ; while (i < size)
    cmp r12, r13
    je .done

    ; cout array[i]
    mov rdi, arrayElementFmt
    mov rsi, r12
    mov rdx, [r14 + r12 * 8]
    call CallPrintf

    ; ++i
    inc r12
    jmp .top

.done:
    pop r14
    pop r13
    pop r12
    pop rbp

    ret

;   rdi holds the array address
;   rsi holds the array size
FillArray:
   
   push rbp
   mov rbp, rsp

   ; declare a local variable, 
   ;  long tmp
   add rsp, -8 ; reserve space for a random number

   push r12 ; lcv
   push r13 ; array size
   push r14 ; base address

   mov r13, rsi
   mov r14, rdi

   mov r12, 0

.top:
   cmp r12, r13
   je  .done

   ; tmp = rand() % 100
   ; sys_getrandom take 
   ;    318 in rax
   ;    the base address of the buffer in rdi
   ;    the size of the number to generate in rsi
   ;    arguments in rdx
   mov rax, 318   ; sys_getrandom
   ;   the buffer is rbp -8
   mov rdi, rbp
   add rdi, -8
   mov rsi, 8
   mov rdx, 0
   syscall
  
   ; move the value from the buffer to memory
   ; but first mod it by 100
   mov rdx, 0
   mov rax, [rbp - 8]
   mov rbx, 100
   div rbx

   ; a[i] = rand() % 100
   mov [r14 + r12 * 8], rdx

   inc r12
   jmp .top

.done:

   pop r14
   pop r15
   pop r12

   add rsp, 8

   pop rbp
   ret