support argc & argv in main() for x64, support fopen(), fclose(), ...
authoryu.dongliang <18588496441@163.com>
Wed, 28 Aug 2024 08:56:16 +0000 (16:56 +0800)
committeryu.dongliang <18588496441@163.com>
Wed, 28 Aug 2024 08:56:16 +0000 (16:56 +0800)
examples/fopen.c [new file with mode: 0644]
examples/main_argv.c [new file with mode: 0644]
lib/_start.o
lib/_start.s

diff --git a/examples/fopen.c b/examples/fopen.c
new file mode 100644 (file)
index 0000000..62be9a5
--- /dev/null
@@ -0,0 +1,26 @@
+/*#include<stdio.h>
+#include<stdint.h>
+*/
+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 (file)
index 0000000..fe50ca8
--- /dev/null
@@ -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;
+}
index bca4a4de7cf737a07cbc8749bcd766dd51737ce1..38dbb233c43dc0328307640a799c60ef3200f718 100644 (file)
Binary files a/lib/_start.o and b/lib/_start.o differ
index a5ba6559513fd7f45c729c77194fc211162a07d5..2df9e0344a28a9afbde7d4bc9f566a6a706df137 100644 (file)
@@ -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