0

I try to combine NASM code and c code. So, I wrote a function in asm file, and in the next step I connect asm file to the c file. I look at the example here

Linking C with NASM

But I get the error "segmentation fault error". Ordinary I used exit syscall and it's worked without error, but now I should use "ret" and when I move the address of path in register ecx I get this error. I looked at this article

Nasm segmentation fault on RET in _start

But I should use ret operation. Well, maybe you can adjust me...

Nasm code

global get_ostype

section .data
ostype: db "/proc/sys/kernel/ostype",0      ;path to ostype

section .bss
buf resb 1024
descriptor resb 4
len equ 1024

section .text
get_ostype:

open_file:
    mov eax, 5
    mov ebx, ostype    ;open file by path ostype
    mov ecx, 0
    int 80h
    mov [descriptor], eax

read_file:
    mov eax, 3  ;read text
    mov ebx, [descriptor];  
    mov ecx, buf    ;read to variable buf
    mov edx, len    ;size of bug
    int 80h     ;interrupt

close_file:
    mov eax, 6
    mov ebx, [descriptor]
    int 80h

mov eax, 0  ;return 0

ret

C code

#include <stdio.h>

int get_ostype();

int main()
{
  printf("%d\n", get_ostype());
  return 0;
}

When I comment "mov ebx, ostype" file is compiled. I tried to return 0, after this, I will try to return a string with file content (maybe it's important info). For compile i use commands

nasm -f elf32 get_ostype.asm&&gcc -Wall -m32 main.c get_ostype.o&&./a.out
OKIS
  • 55
  • 1
  • 7
  • 1
    Why do you show so many commented assembly instructions? If you want to show different versions of your code, I suggest to show both versions as separate code blocks. Do I understand correct that your assembly code function is supposed to return an `int` value 0? Did you check the calling conventions? (I didn't.) There should be a specification which registers you have to use for what data and which registers must not be changed (or must be saved and restored) in your assembly code function. Your code changes `ebx`. Check if this is OK. – Bodo Mar 22 '21 at 12:51
  • @Bodo I changed my code. Return value from function is 0. So, look above. – OKIS Mar 22 '21 at 13:15
  • 2
    @Bodo is right, `ebx` has to be saved and restored by your function. You can't avoid using it altogether, so the easiest fix is to `push ebx` at the start of your function and `pop ebx` just before returning. – Nate Eldredge Mar 22 '21 at 13:33
  • The thing about `ret` versus exit system call is not applicable here. If your assembly code was in the `_start` function, which is called directly by the OS, then it can't return. But here it is a function that was called from C, so returning with `ret` is correct. – Nate Eldredge Mar 22 '21 at 13:34
  • @NateEldredge Thank you. – OKIS Mar 22 '21 at 19:29

0 Answers0