From e837f3a4fa9a11350cca0ce8e147787c3b4f6fdb Mon Sep 17 00:00:00 2001 From: "yu.dongliang" <18588496441@163.com> Date: Wed, 28 Aug 2024 16:56:16 +0800 Subject: [PATCH] support argc & argv in main() for x64, support fopen(), fclose(), ... --- examples/fopen.c | 26 ++++++++++++++++++++++++++ examples/main_argv.c | 11 +++++++++++ lib/_start.o | Bin 840 -> 864 bytes lib/_start.s | 13 ++++++++++++- 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 examples/fopen.c create mode 100644 examples/main_argv.c diff --git a/examples/fopen.c b/examples/fopen.c new file mode 100644 index 0000000..62be9a5 --- /dev/null +++ b/examples/fopen.c @@ -0,0 +1,26 @@ +/*#include +#include +*/ +void* fopen(const char* path, const char* mode); +int fclose(void* fp); +int fscanf(void* fp, const char* fmt, ...); + +int printf(const char* fmt, ...); + +int main() +{ + void* fp = fopen("1.txt", "r"); + if (!fp) { + printf("fp: %p\n", fp); + return -1; + } + + char* s[64]; + + int n = fscanf(fp, "%s", s); + + printf("s: %s, n: %d\n", s, n); + + fclose(fp); + return 0; +} diff --git a/examples/main_argv.c b/examples/main_argv.c new file mode 100644 index 0000000..fe50ca8 --- /dev/null +++ b/examples/main_argv.c @@ -0,0 +1,11 @@ + +int printf(const char* fmt, ...); + +int main(int argc, char** argv, char** envp) +{ + int i; + for (i = 0; i < argc; i++) + printf("%s\n", argv[i]); + + return 0; +} diff --git a/lib/_start.o b/lib/_start.o index bca4a4de7cf737a07cbc8749bcd766dd51737ce1..38dbb233c43dc0328307640a799c60ef3200f718 100644 GIT binary patch delta 113 zcmX@X_JD1IhEW0|0~|PjSq=;w4D1XZozFa)k8yZ(e)8zH@@PK9;nDiP^ovKgjmks^ zqlqOgjM5W-u4gouypqv;vH~;5}VA6mvCV&`|cQV;Cy#Pux*>MU$4KxJmkp}=$0vC1w diff --git a/lib/_start.s b/lib/_start.s index a5ba655..2df9e03 100644 --- a/lib/_start.s +++ b/lib/_start.s @@ -2,8 +2,19 @@ .global _start, main _start: + mov %rsp, %rsi + add $8, %rsi # argv + mov %rsi, %rdx +1: + mov (%rdx), %rdi + add $8, %rdx # envp + test %rdi, %rdi + jnz 1b + + mov (%rsp), %rdi # argc + call main mov %rax, %rdi mov $60, %rax syscall -.fill 7, 1, 0 +.fill 5, 1, 0 -- 2.25.1