/******************************************************* * File: StructEx.m * Date: Oct. 31, 2021 * Author: DSS * Computer: KUNET suns * Execute: StructEx1 * Purpose: to demonstrate the use of structs as allocated on the stack. * It illustrates how components of the structs are referenced * efficiently and demonstrates offsets via an index search * * This program will define a struct stored in the stack * read in its fields and print them out. * * It uses minimal code, optimizing several things *******************************************************/ define(name,0) # 20 char string define(age,20) # 32-bit int define(level,24) # char representing class '1'=fr '2'=so, etc. define(student,32) .global main main: push %rbp # keep stack aligned subq $student,%rsp # Make room for a student # Make room for 10 ints on the stack loop: # Prompt for name leaq getName(%rip), %rdi # load format string to proper register call printf # print it # Read the name # leaq fmt_in(%rip), %rdi # load format string movq %rsp, %rdi addq $name, %rdi # Offset to name call gets # Read the name # Prompt for age leaq getAge(%rip), %rdi # load format string for age prompt call printf # print it # Read it leaq int_in(%rip), %rdi # load format string for int movq %rsp, %rsi addq $age, %rsi # Offset to name call scanf # Prompt for level leaq getClass(%rip), %rdi # load format string for age prompt call printf # print it # Read it leaq char_in(%rip), %rdi # load format string for int movq %rsp, %rsi addq $level, %rsi # Offset to level movq %rsi, %rdx # What's going on? Four arguments? # Comment previous line to find out call scanf print: # Print the struct leaq output(%rip),%rdi movq %rsp, %rsi # Struct starts at stack pointer addq $name, %rsi # Offset to name; adrs to register movq 0x14(%rsi),%rdx # Load age... 20 bytes past %rsp movq 0x18(%rsi), %rcx # Level is 24 bytes past %rsp call printf # Note level's value is loaded done: addq $student, %rsp # Deallocate the array (not critical) pop %rbp ret .data getName: .asciz "Enter Name: " getAge: .asciz "Enter Age: " getClass: .asciz "Enter Class 1)Frosh 2)Soph 3)Jr 4)Sr >" int_in: .asciz "%d" char_in: .asciz "%c%c" output: .asciz "Name: %s Age: %d Class: %c\n"