array.asm

URL: https://mirkwood.cs.edinboro.edu/~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:

     mov rdi,arrayElements 
     mov rax, 8
     mul rdi
     mov rdi, rax
     call malloc

     mov [arrayAddress], rax

     mov rdi, addressMsg
     mov rsi, [arrayAddress] 
     call CallPrintf


     mov rdi, [arrayAddress]
     mov rsi, [arrayElements]
     call FillArray

     mov rdi, [arrayAddress]
     mov rsi, [arrayElements]
     call PrintArray

     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
    push r13
    push r14

    mov r14, rdi
    mov r13, rsi

    mov r12, 0
.top:
    cmp r12, r13
    je .done

    mov rdi, arrayElementFmt
    mov rsi, r12
    mov rdx, [r14 + r12 * 8]
    call CallPrintf

    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

   mov [r14 + r12 * 8], rdx

   inc r12
   jmp .top

.done:

   pop r14
   pop r15
   pop r12

   add rsp, 8

   pop rbp
   ret