어셈블리에서 C 호출
표준 호출 규칙을 준수하며 어셈블리 코드 안에서 C 함수를 호출하는 방법을 이해합니다.
어셈블리에서 C 호출은(는) 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개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Bridge Assembly & C
Why would you want to combine C and Assembly code? It's a powerful technique in low-level and system programming!
- Assembly: Great for performance-critical tasks, direct hardware access, and understanding system internals.
- C: Offers high-level structure, portability, and access to vast libraries.
By calling C functions from Assembly, you can leverage C's complex logic and libraries while retaining Assembly's low-level control for specific tasks.
The Calling Contract
When one function calls another, they need to agree on a set of rules. This 'contract' is known as a calling convention.
It defines crucial aspects of how functions interact:
- How arguments are passed (e.g., on the stack, in registers).
- The order in which arguments are passed.
- Which function is responsible for cleaning up the stack after the call.
- How return values are transmitted back to the caller.
Without these conventions, your assembly code wouldn't know how to prepare data for a C function, or how to interpret its results.
Common `cdecl` Convention
The cdecl (C declaration) calling convention is very common, especially for 32-bit x86 systems (like Linux).
Let's look at its key characteristics:
- Argument Order: Arguments are pushed onto the stack from right to left.
- Stack Cleanup: The caller (your assembly code) is responsible for cleaning up the stack after the function returns.
- Return Values: Integer return values are typically placed in the EAX register.
Understanding cdecl is fundamental for successful interaction between your assembly and C code.
`cdecl` Argument Passing
With 32-bit cdecl, arguments are pushed onto the stack in reverse order. This means the last argument is pushed first, and the first argument is pushed last.
For a C function like my_func(arg1, arg2, arg3);, the assembly call would involve:
push dword arg3_valuepush dword arg2_valuepush dword arg1_valuecall my_func
This ensures that arg1 is at the 'top' of the arguments on the stack, just below the return address pushed by call.
Caller Cleans Up the Stack
One of the defining features of cdecl is that the caller (your assembly code) is responsible for removing the arguments from the stack after the C function returns.
This is typically done by adjusting the stack pointer (ESP) using the ADD ESP, N instruction, where N is the total size of the arguments pushed (e.g., 4 bytes per argument on 32-bit systems).
This cleanup mechanism allows C functions to accept a variable number of arguments (like printf) because the caller knows exactly how many arguments it pushed.
Handling Return Values
When a C function returns a value using cdecl, it places that value in a specific register for the caller to retrieve.
- For integer types (like
int,char,short), the return value is typically stored in the EAX register (on 32-bit x86). - For larger or floating-point types, other registers or memory locations might be used, but EAX is the most common for simple integer returns.
After the CALL instruction returns, you can simply access the EAX register to get the result from your C function.
Declaring External C Functions
Before your assembly code can call a C function, you need to tell the assembler that the function exists but is defined elsewhere. This is done using the extern directive.
Example: extern printf
This directive informs the assembler that printf is an external symbol. During the linking phase, the linker (e.g., gcc) will resolve this symbol to the actual C function's address, allowing your assembly program to execute it.
Example: Basic C Function Call
Let's call a simple C function that takes no arguments and returns nothing. We'll use 32-bit x86 assembly.
First, compile the C code (c_funcs.c):
#include <stdio.h>
#include <stdlib.h>
void greet_c() {
printf("Hello from C's greet_c()!\n");
}
// Placeholder for next example
int add_c(int a, int b) {
return a + b;
}
Now, try running this assembly code:
extern greet_c
extern exit
section .text
global _start
_start:
call greet_c ; Call the C function
; Exit the program
push dword 0 ; Exit status 0
call exit
Example: C with Args & Return
Now, let's call a C function that takes arguments and returns a value. Remember the cdecl rules for 32-bit x86:
- Arguments pushed right-to-left.
- Caller cleans the stack.
- Return value in EAX.
Add the add_c function to your c_funcs.c file (from the previous scene).
Then, run this assembly code:
extern add_c
extern exit
extern printf
section .data
format_str db "Result from C: %d", 0xA, 0
section .text
global _start
_start:
; Call add_c(10, 20)
; Arguments pushed right-to-left on 32-bit stack
push dword 20 ; Push b
push dword 10 ; Push a
call add_c ; Call the C function
; EAX now holds the return value (30)
; Clean up the stack (2 arguments * 4 bytes each = 8 bytes)
add esp, 8
; Now print the result using C's printf
; For 32-bit cdecl, printf args are pushed right-to-left
push eax ; Push result from add_c (in EAX)
push dword format_str ; Push format string address
call printf
add esp, 8 ; Clean up printf's arguments
; Exit the program
push dword 0 ; Exit status 0
call exit
Check Your Knowledge
Consider a C function int calculate(int x, int y, int z); that you want to call from 32-bit x86 assembly using the cdecl calling convention.
Which sequence of assembly instructions correctly prepares the stack and calls calculate with arguments x=5, y=10, z=15, and correctly cleans up the stack?
Recap: Calling C from Assembly
You've successfully learned how to integrate C functions into your assembly programs!
- Calling Conventions: These are crucial rules for function interaction.
cdecl(32-bit): Arguments are pushed onto the stack from right-to-left.- Caller Cleanup: The assembly code (caller) is responsible for removing arguments from the stack using
ADD ESP, N. - Return Values: Integer results from C functions are typically found in the EAX register.
externDirective: Use this to declare C functions to your assembler.
This skill allows you to combine the performance and low-level control of assembly with the rich features and libraries of C!
자주 묻는 질문
“어셈블리에서 C 호출” 강의는 무료인가요?
네 — “어셈블리에서 C 호출” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Assembly Language & x86 Low-Level Systems Programming 강의 전체를 잠금 해제할 수 있습니다. Assembly Language & x86 Low-Level Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“어셈블리에서 C 호출”에서 뭘 배우나요?
표준 호출 규칙을 준수하며 어셈블리 코드 안에서 C 함수를 호출하는 방법을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 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번째 강의입니다.
“어셈블리에서 C 호출” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Assembly Language & x86 Low-Level Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Assembly Language & x86 Low-Level Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.