ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP3137Stack
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP3137

    Computer Organization and Assembly Language

    Progress0 / 73 done
    Topics73
    1Introduction to Computer Organization2Assembly Language3Comparison of Low-Level and High-Level Languages
    4General Purpose and Special Purpose Registers5Introduction and Usage of RAM6Processor7Registers8System Bus9Instruction Execution Cycle10Assembly and Machine Language11Assembler12Linker and Link Libraries13Programmer's View of a Computer System14RISC and CISC Architecture15Physical Address Calculation16Basic Memory Organization17CPU Organization18Top Level View of Computer Function and Interconnection19Assembler Instruction Cycle20Execute Cycle21Interrupts22Interrupt Cycle23Memory Connection24Input/Output Connection25CPU Connection26MASM27MIPS28Defining Data in MASM Assembler29Elements of Assembly Language30Integer Constants31Integer Expressions32Real Number Constants33Character Constants34String Constants35Reserved Words36Identifiers37Directives38Instructions39The NOP (No Operation) Instruction40Adding and Subtracting Integer41INC and DEC Instructions42NEG Instruction43How to Move Integer Number in Register44Adding and Subtracting Numbers in Registers45Declaration and Initialization of Variables46Moving Data from Variable to Register47Data Definition Statement48BYTE and SBYTE Data49WORD and SWORD Data50Defining DWORD and SDWORD Data51Knowledge about Different Data Types52Operations, Array & Loops53Division and Multiplication in Assembly54Jumps Based on Specific Flags55Jumps Based on Equality56Simple Jump Statements57Jumps Based on Specific Condition58Code Examples59Practice on MASM60Procedures61File Operations Procedures62Labels in Procedures63Stack64Runtime Stack65Conditional Control Flow Directives66Compound Expressions67Data Representation & Conversion68Architecture69Data Path70Control Unit71Critical Path72General Principles of Pipelining73Pipelined Y86 Implementations
    8 min read
    Topic 63 of 73
    Topic Study Note Illustration
    63

    Stack

    Visual Reference Stack (Abstract Data Type) Wikipedia In assembly language programming, especially in the context of MASM (Microsoft Macro Assembler), the stack is a fundamental part of...

    Understanding the Stack in Assembly Language (MASM)

    Stack (abstract data type)
    Visual ReferenceStack (Abstract Data Type)
    Wikipedia

    In assembly language programming, especially in the context of MASM (Microsoft Macro Assembler), the stack is a fundamental part of the memory organization. It is used for managing function calls, storing temporary data, and handling interrupt or exception information.

    The stack operates on the Last-In, First-Out (LIFO) principle, meaning that the last value pushed onto the stack is the first one that will be popped off. The stack grows downwards in memory, and it is manipulated using special instructions like PUSH, POP, and others.

    What is the Stack?

    The stack is a special region of memory used for storing temporary data such as:

    1. Function Call Information: Parameters, return addresses, and saved registers.
    2. Local Variables: Temporary variables used within procedures.
    3. Return Addresses: When a function is called, the address to return to after the function finishes is pushed onto the stack.
    4. Interrupt Context: When interrupts occur, the processor saves important register values on the stack.

    Key Operations on the Stack

    There are two primary operations used to manipulate the stack in MASM:

    • PUSH: This instruction pushes a value onto the stack.
    • POP: This instruction pops a value from the stack.

    Additionally, there are other instructions and concepts related to the stack:

    • Stack Pointer (SP): The stack pointer (SP) is a register that points to the top of the stack. It is automatically adjusted when data is pushed to or popped from the stack.
    • Stack Frame: The portion of the stack used by a particular procedure during its execution.

    PUSH and POP Instructions

    PUSH Instruction

    The PUSH instruction adds data to the stack. It decreases the SP (stack pointer) by the size of the data being pushed (typically 2 bytes for a word, 4 bytes for a double word), and then stores the data at the new location pointed to by SP.

    Example of PUSH:
    mov ax, 1234h    ; Load AX with a value
    push ax          ; Push the value of AX onto the stack
    

    POP Instruction

    The POP instruction retrieves data from the stack. It first loads the value at the current location pointed to by SP into the specified register or memory location, and then increments the SP to point to the next item on the stack.

    Example of POP:
    pop ax           ; Pop the value from the stack into AX
    

    Stack and Procedure Calls

    When a procedure (or function) is called, the stack plays an important role in saving the current state, including the return address, so the program can continue executing after the procedure finishes.

    Function Call and Return

    • Call Instruction: The CALL instruction pushes the return address (the address of the next instruction) onto the stack and then jumps to the procedure.
    • Return Instruction: The RET instruction pops the return address from the stack and jumps back to the calling procedure.
    Example of Function Call and Return:
    ; Procedure that calls another procedure
    main:
        ; Call the Procedure1
        call Procedure1
    
        ; Execution returns here after Procedure1 finishes
        mov ax, 4Ch
        int 21h           ; Exit the program
    
    ; Procedure1
    Procedure1 proc
        ; Save registers or temporary data if needed
        push ax           ; Push AX onto the stack (save its value)
        
        ; Code for the procedure
        mov ax, 1234h     ; Do some operations
        ; Perform tasks here...
    
        pop ax            ; Pop the value back into AX (restore it)
    
        ret               ; Return to the calling function (main)
    Procedure1 endp
    

    Explanation:

    • call Procedure1: When Procedure1 is called, the return address (the address of the instruction after call Procedure1) is pushed onto the stack.
    • ret: The ret instruction pops the return address from the stack and jumps to that address.

    Stack and Local Variables

    In many cases, local variables are stored on the stack. When a procedure is called, a "stack frame" is created, which holds local variables, saved registers, and return addresses. This allows each function call to have its own isolated data, even if multiple functions are called in a nested manner.

    Example: Using the Stack for Local Variables

    .model small
    .stack 100h
    
    .data
        msg db 'Stack example finished.$', 0
    
    .code
    main:
        mov ax, @data    ; Initialize data segment
        mov ds, ax
    
        ; Call the procedure
        call StackExample
    
        ; Exit program
        mov ah, 4Ch
        int 21h
    
    StackExample proc
        ; Push registers and create space for local variables
        push ax
        push bx
    
        ; Local variables on the stack
        mov ax, 5
        mov bx, 10
        add ax, bx          ; ax = 5 + 10 = 15
    
        ; Clean up stack before returning
        pop bx
        pop ax
    
        ret
    StackExample endp
    end main
    

    Explanation:

    • Push registers (push ax, push bx): Before using registers for calculations, we push their current values onto the stack to preserve them.
    • Local variables (ax, bx): We can treat registers like local variables by storing their values temporarily on the stack.
    • Pop registers (pop bx, pop ax): After the procedure finishes its execution, we restore the values of registers from the stack, cleaning up the stack.

    Using the Stack for Nested Calls

    The stack allows procedures to be nested. Each call to a procedure pushes a new return address and local data onto the stack. This makes it possible to have multiple function calls that can return to the correct place in the program.

    Example: Nested Function Calls Using the Stack

    .model small
    .stack 100h
    
    .data
        msg db 'Finished calling procedures.$', 0
    
    .code
    main:
        mov ax, @data       ; Initialize data segment
        mov ds, ax
    
        ; Call the first procedure
        call OuterProcedure
    
        ; Exit program
        mov ah, 4Ch
        int 21h
    
    OuterProcedure proc
        ; Save state of registers
        push ax
        push bx
    
        ; Call the inner procedure
        call InnerProcedure
    
        ; Restore state of registers
        pop bx
        pop ax
    
        ret
    OuterProcedure endp
    
    InnerProcedure proc
        ; Example function that just prints something
        mov ax, 1234h   ; Set some value for AX
        ; Normally you'd do something with AX here, but just return for this example
    
        ret
    InnerProcedure endp
    
    end main
    

    Explanation:

    • When OuterProcedure calls InnerProcedure, the return address of OuterProcedure is pushed onto the stack. The stack pointer is adjusted accordingly.
    • When InnerProcedure finishes, it returns to OuterProcedure by popping the return address from the stack.
    • After InnerProcedure returns, the execution returns to OuterProcedure, which restores any saved register values before returning to the main program.

    Stack Pointer (SP) and Stack Frame

    • The Stack Pointer (SP) register points to the top of the stack. Each time you push data, SP is decremented, and each time you pop data, SP is incremented.
    • A stack frame is the portion of the stack used by a procedure to store:
      • The return address (pushed when the function is called).
      • Saved registers (if any, pushed to preserve their state).
      • Local variables (temporary data created by the procedure).

    The stack frame ensures that even with nested function calls, the return address and local data for each procedure are kept separate and can be restored correctly.

    Stack Overflow

    A stack overflow occurs when the stack exceeds its limit, often due to too many nested function calls or allocating too much space for local variables. This can cause the program to crash or behave unexpectedly. To avoid this, the size of the stack must be carefully managed, and recursion should be used cautiously.

    Summary

    • The stack is an essential memory structure in assembly programming for managing function calls, local variables, and return addresses.
    • The PUSH instruction saves data to the stack, and the POP instruction retrieves it.
    • The CALL instruction pushes the return address onto the stack, and RET pops it, returning control to the calling function.
    • The stack allows for nested function calls, preserving each procedure's state.
    • Managing the stack properly is essential to avoid stack overflows and ensure correct program behavior.
    ← Previous topic 62
    Labels in Procedures
    Next topic 64 →
    Runtime Stack

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Computer Organization and Assembly Language