프로시저 정의와 호출
CALL과 RET 명령어로 직접 프로시저(함수)를 정의하고 호출하며 스택 프레임 설정을 이해합니다.
프로시저 정의와 호출은(는) CoddyKit의 무료 Assembly Language & x86 Low-Level Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Assembly Language & x86 Low-Level Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Assembly Language & x86 Low-Level Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What are Procedures?
In assembly, a procedure (often called a function or subroutine) is a block of code designed to perform a specific task. They help organize your program and avoid repeating code.
Think of them like functions in high-level languages like C++ or Python. They allow you to break down complex problems into smaller, manageable parts, making your code modular and easier to read.
Calling a Procedure with CALL
To execute a procedure, we use the CALL instruction. When CALL is executed, two important things happen:
- The address of the instruction immediately after
CALLis pushed onto the stack. This is known as the return address. - The CPU then jumps to the starting address of the procedure you specified.
This mechanism ensures that the program knows exactly where to resume execution once the procedure has completed its work.
Returning from a Procedure with RET
Once a procedure has finished its assigned task, it needs to return control to the code that called it. This is achieved using the RET instruction.
When RET is executed:
- The CPU pops the return address from the top of the stack.
- The CPU then jumps to this popped address, effectively resuming execution at the instruction immediately following the original
CALL.
Together, CALL and RET form the fundamental pair for managing program flow between different procedures.
Your First Procedure Call
Let's look at a simple assembly program that demonstrates a basic procedure call and return. We'll define a procedure named print_hello and call it from our program's entry point, _start.
This example uses Linux system calls for output and program exit.
section .data
msg db "Hello from proc!", 0xA
len equ $ - msg
section .text
global _start
_start:
call print_hello
; Exit program (sys_exit)
mov eax, 1 ; System call number for sys_exit
xor ebx, ebx ; Exit code 0
int 0x80
print_hello:
; Print "Hello from proc!" (sys_write)
mov eax, 4 ; System call number for sys_write
mov ebx, 1 ; File descriptor for stdout
mov ecx, msg ; Address of string to write
mov edx, len ; Length of string
int 0x80
ret
Understanding the Output
When you run the previous code, it will print "Hello from proc!" to your console. Here's a step-by-step breakdown of what happened:
- The
_startroutine executedcall print_hello. - The address of the instruction
mov eax, 1(which is right aftercall print_hello) was pushed onto the stack. - The CPU jumped to the
print_helloprocedure. print_helloexecuted its instructions to print the message.retpopped the saved return address from the stack and jumped back to the_startroutine._startthen executed the system call to exit the program.
What are Stack Frames?
When a procedure is called, it often needs its own private workspace on the stack to manage its data. This dedicated region on the stack is called a stack frame.
A stack frame typically holds several key pieces of information for a procedure:
- The return address (pushed by the
CALLinstruction). - Saved register values (e.g., the caller's base pointer).
- Local variables specific to that procedure.
- Arguments passed to the procedure (we'll cover this in the next lesson!).
Setting Up the Base Pointer (EBP)
The base pointer register (`EBP` in 32-bit, `RBP` in 64-bit) is a crucial tool for managing stack frames. It provides a stable reference point within the current stack frame, making it easy to access local variables and arguments.
A common setup sequence at the very beginning of a procedure is:
push ebp: This saves the caller's current `EBP` value onto the stack, so it can be restored later.mov ebp, esp: This sets `EBP` to the current value of the stack pointer (`ESP`), establishing the base of the new stack frame.
Allocating Local Variables
After setting up `EBP`, a procedure can allocate space for its own local variables on the stack. This is typically done by simply decrementing the stack pointer (`ESP`).
sub esp, NHere, `N` represents the total number of bytes required for all local variables. For example, sub esp, 4 allocates enough space for one 32-bit integer.
These local variables can then be accessed efficiently relative to `EBP` (e.g., [ebp-4], [ebp-8], etc.).
Tearing Down the Stack Frame
Before a procedure returns, its stack frame must be properly dismantled to restore the stack to its original state. This involves deallocating local variables and restoring the caller's base pointer.
The LEAVE instruction is a convenient way to perform these two actions in one step:
mov esp, ebp: This deallocates any local variables by moving `ESP` back to where `EBP` points (the base of the frame).pop ebp: This restores the caller's `EBP` value, which was saved at the beginning of the procedure.
After LEAVE, the stack is correctly positioned for the RET instruction to pop the return address.
Procedure with a Stack Frame
This example demonstrates a complete procedure that sets up a proper stack frame, allocates space for a hypothetical local variable, and then correctly tears down the frame before returning.
Notice how `push ebp`, `mov ebp, esp`, `sub esp, 4`, `leave`, and `ret` work together.
section .data
msg db "Procedure with frame!", 0xA
len equ $ - msg
section .text
global _start
_start:
call my_framed_proc
; Exit program
mov eax, 1
xor ebx, ebx
int 0x80
my_framed_proc:
push ebp ; 1. Save caller's EBP
mov ebp, esp ; 2. Set EBP for new frame
sub esp, 4 ; 3. Allocate 4 bytes for a local variable
; mov dword [ebp-4], 123 ; Example: store a local value
; Print message (for demonstration)
mov eax, 4
mov ebx, 1
mov ecx, msg
mov edx, len
int 0x80
leave ; 4. Deallocate locals, restore EBP
ret ; 5. Return to caller
Procedure Call Flow Check
Consider the following x86 assembly snippet:
call my_function
mov eax, 1
my_function:
ret
What specific address is pushed onto the stack by the call my_function instruction?
Defining & Calling Procedures Recap
We've covered the essential concepts of defining and calling procedures in x86 assembly. Here are the key takeaways from this lesson:
- The
CALLinstruction pushes the return address onto the stack and transfers control to a procedure. - The
RETinstruction pops the return address from the stack and transfers control back to the caller. - Stack frames, managed primarily with the
EBP/RBPregister, provide a dedicated and organized workspace on the stack for a procedure's local variables and saved registers. - A typical stack frame setup involves
push ebp,mov ebp, esp, and allocating local variables withsub esp, N. - Tearing down the stack frame is done using the
LEAVEinstruction (or manually withmov esp, ebpandpop ebp) beforeRET.
Next, we'll build on this by learning how to pass arguments to procedures and retrieve return values.
AI 튜터와 함께 Assembly을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 48
자주 묻는 질문
“프로시저 정의와 호출” 강의는 무료인가요?
네 — “프로시저 정의와 호출” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Assembly Language & x86 Low-Level Systems Programming 강의 전체를 잠금 해제할 수 있습니다. Assembly Language & x86 Low-Level Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“프로시저 정의와 호출”에서 뭘 배우나요?
CALL과 RET 명령어로 직접 프로시저(함수)를 정의하고 호출하며 스택 프레임 설정을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Assembly Language & x86 Low-Level Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Assembly Language & x86 Low-Level Systems Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Assembly Language & x86 Low-Level Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“프로시저 정의와 호출” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Assembly Language & x86 Low-Level Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Assembly Language & x86 Low-Level Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 호출 스택 기초
- 프로시저 정의와 호출
- 인수와 반환 값 전달
- 스택 프레임과 지역 변수