Page 1 of 1

Using assembly with C and stack

Posted: Tue Aug 17, 2021 4:23 pm
by leosa99
Hi,

I have the following c code (run in protected mode, all segments well defined):

Code: Select all

extern void _printcool();
extern void _wait();

int kmain()
{
_printcool();
while(1==1){}
return 0;
}

The second assembly code defines both functions:

Code: Select all

[bits 32]
global _printcool
global _wait

_printcool:
mov byte [0xB8000], 'R'
mov byte [0xB8001], 0x52
ret 

_wait:
jmp _wait
I build them using :
nasm -f elf asmfile -o asmfile.o
gcc -ffreestanding -m32 -fno-pic -fno-pie -c kernel.c -o kernel.o
ld --oformat binary -Ttext 0x1000 -melf_i386 asmfile.o kernel.o -o kernel.bin

Then I run my bootloader with this kernel, like before, but it triple fault every time.

The ret is responsible of the triple fault, but I don't understand what should I do, I think the problem comes from the stack, I dont know how to clean it before using ret instruction.

Thank you !

Re: Using assembly with C and stack

Posted: Tue Aug 17, 2021 6:34 pm
by Octocontrabass
leosa99 wrote:gcc -ffreestanding -m32 -fno-pic -fno-pie -c kernel.c -o kernel.o
You should be using a cross-compiler.
leosa99 wrote:The ret is responsible of the triple fault, but I don't understand what should I do, I think the problem comes from the stack, I dont know how to clean it before using ret instruction.
How do you know the RET is responsible for the triple fault?

Re: Using assembly with C and stack

Posted: Wed Aug 18, 2021 3:36 am
by leosa99
I am not using a cross compiler for school reasons, I know the ret is responsible because if I replace it by a jump $, there is no triple fault.

Re: Using assembly with C and stack

Posted: Wed Aug 18, 2021 5:24 am
by leosa99
After using a cross-compiler (target elf i686), the same commands with nasm, gcc and ld. It still produces a triple fault on the ret instruction.

Re: Using assembly with C and stack

Posted: Wed Aug 18, 2021 6:18 am
by iansjack
Single-step your code under a debugger to find out where it is going wrong and what the surrounding code looks like. That should give you a good idea of what the problem is.

My guess would be an invalid stack. There's not much else to go wrong in that code snippet.

As a matter of interest, what value do you set your stack pointer to?

Re: Using assembly with C and stack

Posted: Wed Aug 18, 2021 11:34 am
by Maddie
I think you need to respect the calling convention for your compiler.