0% found this document useful (0 votes)
3 views16 pages

Procedure_Call_Assembly_Explanation (2)

Uploaded by

tjdabral2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views16 pages

Procedure_Call_Assembly_Explanation (2)

Uploaded by

tjdabral2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

LEC4 RUN TIME STACK

Yes, the runtime stack is just a smart system of filling and emptying
memory — like a controlled version of putting things on a shelf and
then taking them off in reverse order.

But Here’s What Makes It Powerful:

It's not just filling and emptying — it's how and why it does it that
makes it essential:

🔁 Every Function Call = Stack Fills

 CALL myProc → pushes the return address


 PUSH EBP → saves the base pointer
 MOV EBP, ESP → marks the start of a new stack frame
 PUSH arg1, arg2… → saves arguments
 PUSH reg → temporarily saves registers
 SUB ESP, x → makes space for local variables

📦 That’s the filling part.

↩️Every Return = Stack Empties

 MOV ESP, EBP → removes local variable space


 POP EBP → restores previous frame
 RET → pops return address → jumps back

🧹 That’s the emptying part.

🧩 Why This Matters:

It’s not just memory being added and removed. It’s organised memory:

 Temporary values get a safe spot.


 Procedures don’t mess with each other’s data.
 Control always goes back exactly where it came from.
 If used wrong, crashes or vulnerabilities happen.

SUMMARY

When your program begins running, the operating system quietly sets
up a special memory area called the runtime stack — kind of like a
blank notebook, ready to take notes. At first, it's empty, and the ESP
register points to the top of it. Now, the moment your code calls a
procedure or function using something like CALL myFunction, the
runtime stack jumps into action. The first thing it does is save the
return address — the memory location the program needs to go back
to after the function finishes — by pushing it onto the stack. Then,
when the function starts, it creates its own stack frame by saving the
old base pointer with PUSH EBP, then copying ESP into EBP with MOV
EBP, ESP. This stack frame becomes the function’s private workspace,
where it stores any parameters, local variables, or temporarily
saved registers. This whole process is repeated every time another
function is called — each one stacking on top of the last, like a pile of
books. Once the function completes its task, it cleans up: it resets ESP,
restores the old EBP, and uses RET to pop the return address and
return to where it was originally called. All of this happens smoothly,
and the calling code continues like nothing happened, because the
runtime stack handled all the temporary memory and flow control
behind the scenes. Without the runtime stack, your program would have
no way to jump into a function, remember where it came from, or pass
data safely. It plays a silent but critical role in managing function calls,
parameters, return addresses, local memory, and even security —
showing up exactly when needed, doing its job, and then clearing out
quietly until the next call.
✅ Week 4: Runtime Stack
This is where you learn the foundation — what the stack is, how PUSH
and POP work, how memory grows downward, and how values are
temporarily stored.

🧠 Focus here:

 What a stack is
 How ESP, EBP work
 Stack frames
 Why stack matters for function calls, parameter passing, and
temporary storage

✅ Week 6: Procedure Calls


This is where you use the runtime stack in real situations — like how
CALL/RET instructions work, how parameters are passed, stack frames
are built, and what happens when one function calls another (nested
calls).

🧠 Focus here:

 CALL → pushes Return Address (RA)


 PUSH EBP + MOV EBP, ESP → create stack frame
 Access parameters ([EBP+8]), locals ([EBP-4])
 RET → pops RA and jumps back
 Register preservation
 Stack-based vulnerabilities (e.g., smashing)

🔗 So what’s the relationship?

📚 Lecture 6 is basically Lecture 4 applied in real life.


Week 4 teaches you how the engine works.
Week 6 shows you how to drive the car.

🔁 Lecture 5: Story – How FLAGS Fit into the Bigger Picture

When your program runs and executes instructions like ADD, SUB, CMP,
or TEST, it doesn’t just blindly move on — it leaves behind clues in
something called the FLAGS register. This tiny but powerful register
holds flags like CF (Carry Flag), OF (Overflow Flag), ZF (Zero Flag),
and SF (Sign Flag) — each telling you something about the result of the
last instruction. For example, if you subtract two numbers and the result
is zero, the ZF is set. If the result is negative, the SF is set. If you overflow
the signed range, the OF is set. These flags become the eyes and brain
of the CPU — and your key tool to write decisions in assembly. You
don’t get if, else, or while directly like in C. Instead, you use these
flags with jump instructions like JE (Jump if Equal), JL (Jump if Less),
or JA (Jump if Above) — and each of these checks one or more flags to
decide whether to jump. If ZF is set, you might jump to the “equal” case.
If CF is clear and ZF is clear, you might jump to a “greater than” case for
unsigned numbers. That’s why different flags apply to signed vs
unsigned comparisons. You also learn about instructions like XOR
(great for encryption and clearing registers), TEST (non-destructive
AND for checking bits), and how to convert binary digits to ASCII using
OR, AND, and clever bit masking. All of this ties directly into what you
learned about the runtime stack and procedure calls — because
when you're deep in a function or loop, these flags are how your
program makes decisions, branches, loops, or ends. Without them,
your program wouldn’t know if subtraction gave 0, or if an overflow
happened — and you’d have no control flow at all. So, in the big picture,
FLAGS are like post-it notes left behind after every operation, telling
your code what just happened, and what to do next — silently guiding
the jump, loop, or return.

What Are the Core Topics in Lecture 5?

These are the must-know topics — the ones that’ll make


everything easier when writing and understanding
assembly, especially for branching, loops, and decisions:

🔘 1. Flags You Must Know

These are set automatically by CPU after instructions like


ADD, SUB, CMP, TEST.

Flag Means if Set When It's Useful


ZF (Zero Used in JE, JZ
Result = 0
Flag) (jump if equal)
SF (Sign
Result is negative Used in JL, JS
Flag)
CF (Carry Borrow or overflow
Used in JB, JAE
Flag) (unsigned)
OF
Signed overflow
(Overflow Used in JG, JL
occurred
Flag)
✅ Practice tip: After SUB or CMP, print the flags using
DumpRegs or use conditional jumps (JE, JG, JB) and see what
happens.

🔁 2. Jump Instructions Based on Flags

Use Jump
Meaning
With Instruction
Jump if equal /
ZF JE, JZ
zero
JA, JB, JAE, For unsigned
CF, ZF
JBE comparisons
OF, SF, JG, JL, JGE, For signed
ZF JLE comparisons
✅ Practice tip: Write small programs using CMP + jumps to
simulate if/else logic.

🔣 3. ASCII and Bitwise Tricks

 OR al, 30h → Converts 0-9 to ASCII '0'-'9'


 AND al, 0Fh → Converts ASCII back to binary
 XOR eax, eax → Clears register (sets to 0)
✅ Practice tip: Try converting numbers to characters and
back (e.g., for printing digits).

🧪 4. TEST Instruction

 Does a bitwise AND but doesn’t change the values.


 Sets flags only → used for checking if bits are set.

asm
CopyEdit
TEST AL, 01h ; Checks if least significant bit is 1
JNZ OddLabel ; Jump if not zero (bit was 1)

✅ Practice tip: Use it to detect specific bits, like checking if


a number is even or odd.

🧠 5. XOR for Simple Encryption

 XOR AL, key → Encrypt


 XOR AL, key again → Decrypt

✅ Practice tip: Try writing a mini Caesar-style XOR cipher


that encrypts and decrypts a message.

🔁 6. Loops That Use Flags

 LOOP, LOOPZ, LOOPNZ, JECXZ


 Combine ECX and ZF for fancy loops

✅ Practice tip: Build string scanning or number-checking


loops using ECX and LOOPZ.
LEC 6 Journey of a Procedure Call in
Assembly
When a program starts running, it uses registers like EAX, EBX, and
others to process data, while ESP and EBP keep track of where we are in
the stack. Now, when the main program wants to call another procedure
(say myProc), it uses the CALL instruction. This saves the return
address (the next line in main) onto the stack and jumps to the
procedure. As soon as myProc begins, it creates its own working area
called a stack frame by pushing the old base pointer (EBP) and setting
the new base using MOV EBP, ESP. It can then allocate local space or
push arguments as needed. This setup ensures that everything myProc
does stays within its own section of memory. Inside the procedure, we
use [EBP+8], [EBP+12] and so on to read parameters, and any
variables we need are managed using stack space. Once the job is done,
myProc cleans up — it restores the stack by resetting ESP to EBP and
popping the old EBP back. Finally, it executes RET, which pops the
return address from the stack and puts it back into EIP so the program
can jump right back to where it left off in main. Throughout this whole
process, things like the Carry Flag (CF) and Overflow Flag (OF) help
track any issues in arithmetic operations, and conventions like
PUSH/POP and RET make sure the program’s flow is smooth and error-
free. If these steps are skipped or broken, we risk bugs or even security
issues like stack smashing attacks, where someone overwrites the
return address to hijack the program. To make things easier, tools like
Irvine32 provide shortcuts using USES, LOCAL, ENTER, and LEAVE to
handle all this boilerplate safely. Altogether, this journey shows exactly
how assembly language controls the entire life cycle of a function call —
manually and with precision.

1. Program Starts Running (main)

* Registers like EAX, EBX, ECX, EDX are ready to use.


* Stack pointer (ESP) and base pointer (EBP) point to the current stack
frame of `main`.
* Your code is executing line by line, in control.

2. You Call a Procedure (CALL instruction)

CALL myProc

* This does two things:


1. PUSH EIP: Saves the address of the next instruction (return point)
onto the stack.
2. Jumps to myProc: Sets EIP to the address of the procedure.
✅ Why? So after the function finishes, we can jump back and keep going.
3. Procedure Starts: Stack Frame is Created

PUSH EBP ; Save old base pointer


MOV EBP, ESP ; Set new base (starting point for this
function)
SUB ESP, X ; Reserve space for LOCAL variables
PUSH arguments ; Save incoming values or registers

✅ Why? This isolates the function’s workspace. Each function gets its
own 'slice' of the stack.

4. The Procedure Does Its Job

* Access input parameters from:


* [EBP+8], [EBP+12] → these are arguments
* Use local variables stored via:
* LOCAL myVar:DWORD
* Perform logic, update registers, call other procedures if needed.
✅ Why? This is where the function does its actual computation or task.

5. Cleanup: Stack Frame is Destroyed

MOV ESP, EBP ; Reset the stack pointer


POP EBP ; Restore the previous base pointer
RET ; Pop return address into EIP
LEAVE ; Same as MOV ESP, EBP + POP EBP
RET n ; Return and remove arguments

✅ Why? To undo all the setup and cleanly return control.


6. Return to Caller (main resumes)

* EIP now points to the instruction right after the CALL


* ESP and EBP are restored
* main continues like nothing happened

7. Behind the Scenes: Key Things That Help

Feature Role in the Flow

EIP Holds current line of code being


executed

ESP (Stack Ptr) Grows downward, tracks top of


stack

EBP (Base Ptr) Marks the bottom of current stack


frame

Flags (CF/OF) Track math issues


(overflow/borrow)

PUSH/POP Move data in/out of the stack

RET 12 Return + auto-pop 12 bytes of


args

RA (Return Addr) Pushed during CALL, popped on


RET
Security Warning: Stack Smashing

* If an attacker overwrites the RA on the stack, they can redirect EIP and
hijack the program.
* That’s how buffer overflow exploits happen.

Summary Flowchart
[main starts]

[CALL myProc]

[Push EIP (return address)]

[Jump to myProc]

[myProc pushes EBP, sets up stack frame]

[myProc does logic – access args, local vars]

[Clean up – POP EBP, RET]

[Return address restored into EIP]

[main resumes after CALL]

Extra Tools from Irvine32 (used in labs)

* WriteString, ReadString: Use EDX, EAX, ECX


* USES: Automatically saves/restores registers
* LOCAL: Reserves space for local variables
* ENTER/LEAVE: Stack frame setup/teardown made easy
🧠 Lecture 7 – Story: Clean, Organised Procedure Calls (Like a Pro)

By now you know how the runtime stack manages function calls using
CALL and RET. But as your code grows, repeating all the PUSH, POP, and
register saving becomes messy. That’s where Assembly macros and calling
conventions come in — to automate and clean up the mess. It starts with
declaring procedures properly using PROTO (like a blueprint), and defining
them with PROC. Inside a PROC, you can use the USES keyword to
automatically save and restore registers. Instead of writing PUSH EAX,
PUSH EBX, then popping them later, you just write PROC USES EAX
EBX, and it’ll handle all that for you. If your function needs space for local
variables, you use LOCAL, which reserves memory by adjusting ESP. When
the procedure is called, instead of using plain CALL, you can now use
INVOKE. It’s like a super version of CALL that also pushes the
arguments for you — but only if you’ve defined the prototype using
PROTO. It’s cleaner, safer, and avoids mismatching parameter order.

To manage all this properly, macros like ENTER and LEAVE are used.
ENTER sets up the stack frame (just like PUSH EBP, MOV EBP, ESP, SUB
ESP, n), while LEAVE tears it down (MOV ESP, EBP, POP EBP). Then
RET n returns and also cleans up parameters if needed. This is especially
useful when using the stdcall calling convention (used in C++), where the
called function cleans the stack, unlike cdecl (used in C) where the caller
does the cleanup.In big projects, you’ll separate each procedure into its
own .asm file, keeping your main function clean. All these .asm files are
linked together at compile time. That’s how you make modular, reusable,
low-level code just like in high-level languages — but with full control. In
short, Lecture 7 teaches you how to use procedures properly and cleanly
with macros, calling conventions, and stack discipline — so your assembly
code becomes maintainable, scalable, and professional.
🧠 Lecture 8: Story – From Bit Twiddling to String
Mastery
In low-level assembly, there’s no shortcut — if you want to multiply,
divide, or handle strings, you need to know how the CPU moves and
manipulates bits. That’s where Lecture 8 steps in. It starts with shift
operations — SHL, SHR, SAR, and ROL, ROR — which move bits left or
right. These are the building blocks of fast multiplication (using SHL)
and division (using SHR). For signed numbers, you use arithmetic shift
(SAR) so the sign bit is preserved. Logical shift (SHR) is for unsigned
data. Rotation instructions like ROL and ROR let you move bits around
without losing them, perfect for tasks like reading individual bits (e.g.,
flags or hardware control bits). Once you master that, you move on to
multiplication and division. Even though CPUs have MUL and DIV,
Lecture 8 shows how early CPUs used clever combinations of shifts and
adds to simulate multiplication — a skill still useful on RISC or
embedded systems. Then you dive into how numbers are stored:
EDX:EAX is used to hold 64-bit results for division or multiplication,
where EAX gets the quotient and EDX the remainder.

The lecture then shifts focus to memory manipulation, especially with


arrays and strings. You learn to use MOVSx, STOSx, LODSx, SCASx, and
CMPSx to copy, scan, and compare data in memory — without writing
complex loops. These instructions auto-increment ESI and EDI for you,
while REP, REPE, and REPNE add loop-like behavior. For example, you
can copy an entire array with REP MOVSD, or compare strings with REP
CMPSD. You also explore real-world uses, like searching strings, trimming
characters, and converting binary numbers into ASCII (or vice versa). These
skills are critical when writing input/output routines, parsing memory, or
processing data without any library support — just raw assembly.In the end,
Lecture 8 brings everything together showing that bit-level operations,
loops, memory addressing, and math are all interconnected. It’s not just
about low-level instructions — it’s about understanding the machine, and
building fast, precise code that can read, transform, and control data like a
boss.
🔥 What You’ll Be Doing (Mapped to Content)
🎯 Task 💡 Relevant Topics
Input UserID & ReadString, string buffer, checking length → Lecture 8, conditional jumps → Lecture
password 5
Check UserID format ASCII check S, then numeric range using AtoI → Lecture 8 (char processing)
Encrypt Password XOR loop or hashing → Lecture 5 (XOR)
Read File ReadFromFile, OpenInputFile → File I/O week 11
Parse File Content Split buffer using CMP, JZ, INC EDI, etc. → Lecture 8
Compare Strings Use Str_Compare or byte-by-byte → Lecture 8
Update/Create File WriteToFile, use string building → File I/O + Lecture 8 string ops
Use Procedures Each major task = separate procedure → Lecture 6 & 7
Optional: Use STRUCT Hold UserID, password, name → Lecture 9

🧪 How to Get Each Grade (and What Lecture Helps)


🎓 Grade 🔧 What You Need 📘 Focus Lectures
Reads file, prompts user, Lecture 4 (stack), 5 (CMP, jumps), 8
Pass
compares ID/pass (strings), File I/O
Encrypts password w/ multi-byte Add: Lecture 5 (XOR), 6–7 (clean
Credit
XOR, writes file procedures)
Distincti Menu: Login or Create User + Add: Lecture 9 (STRUCTs), File I/O write
on Structs modes
High
Hash algorithm (not XOR), Add: Hashing (Lecture 10 or external),
Distincti
optional user add/update File ops, extra features
on

📝 What You Should Practice Immediately


 ✅ Reading and writing a file using Irvine32 routines
 ✅ Breaking program into procedures: InputID, InputPassword,
Encrypt, Compare, WriteToFile
 ✅ Parsing a string with : delimiter using CMP, JZ, INC, LOOP
 ✅ Using XOR for encryption
 ✅ Creating and accessing a structure (UserData STRUCT)
 ✅ Using INVOKE with parameters (Lecture 7 style)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy