ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Computer Organization and Assembly Language
    COMP3137
    Progress0 / 73 topics
    Topics
    1. Introduction to Computer Organization2. Assembly Language3. Comparison of Low-Level and High-Level Languages4. Register Types (16-bit): General Purpose and Special Purpose Registers5. Introduction and Usage of RAM6. Processor7. Registers8. System Bus9. Instruction Execution Cycle10. Assembly and Machine Language11. Assembler12. Linker and Link Libraries13. Programmer's View of a Computer System14. RISC and CISC Architecture15. Physical Address Calculation16. Basic Memory Organization17. CPU Organization18. Top Level View of Computer Function and Interconnection19. Assembler Instruction Cycle20. Execute Cycle21. Interrupts22. Interrupt Cycle23. Memory Connection24. Input/Output Connection25. CPU Connection26. MASM27. MIPS28. Defining Data in MASM Assembler29. Elements of Assembly Language30. Integer Constants31. Integer Expressions32. Real Number Constants33. Character Constants34. String Constants35. Reserved Words36. Identifiers37. Directives38. Instructions39. The NOP (No Operation) Instruction40. Adding and Subtracting Integer41. INC and DEC Instructions42. NEG Instruction43. How to Move Integer Number in Register44. Adding and Subtracting Numbers in Registers45. Declaration and Initialization of Variables46. Moving Data from Variable to Register47. Data Definition Statement48. BYTE and SBYTE Data49. WORD and SWORD Data50. Defining DWORD and SDWORD Data51. Knowledge about Different Data Types52. Operations, Array & Loops53. Division and Multiplication in Assembly54. Jumps Based on Specific Flags55. Jumps Based on Equality56. Simple Jump Statements57. Jumps Based on Specific Condition58. Code Examples59. Practice on MASM60. Procedures61. File Operations Procedures62. Labels in Procedures63. Stack64. Runtime Stack65. Conditional Control Flow Directives66. Compound Expressions67. Data Representation & Conversion68. Architecture69. Data Path70. Control Unit71. Critical Path72. General Principles of Pipelining73. Pipelined Y86 Implementations
    COMP3137›Stack
    Computer Organization and Assembly LanguageTopic 63 of 73

    Stack

    8 minread
    1,312words
    Intermediatelevel

    Understanding the Stack in Assembly Language (MASM)

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,312
      Code examples0
      DifficultyIntermediate