2

I am having hard times to figure out what's happening.

Here is what I see in the gdb session when dive deeper into a printfn from the stdio.h on Linux:

#1 0x00007ffff7ddb81f in __printf (format=) at ./st
dio-common/printf.c:33

488 (gdb) p $rbp

489 $39 = (void *) 0x7ffff798fff8

So far so good.

Let's step into the next call (which is the __vfprintf_internal) and see what the %rbp will be then:

(gdb) p $rbp

504 $41 = (void *) 0x7ffff7f95780 <IO_2_1_stdout

The difference between both values is 6313864 bytes. How is that possible? What is happening?!

P.S. I explicitly use -fno-omit-frame-pointer to ensure the %rbp preservation.

Zazaeil
  • 3,900
  • 2
  • 14
  • 31

1 Answers1

6

You might be compiling with -fno-omit-frame-pointer, but it looks like the libc was not. So rbp could have been used as a general purpose register inside the glibc.

fuz
  • 88,405
  • 25
  • 200
  • 352
  • How do you do context-switching then? `%rbp` is to be preserved across threads. – Zazaeil Oct 18 '22 at 10:56
  • @Zazaeil You need to save `rbp` on context switch just like any other register. Whether `rbp` is used as a frame pointer or not doesn't matter for that. – fuz Oct 18 '22 at 11:35
  • @Zazaeil: Function calls aren't context switches. If you were doing a context switch, the kernel would save/restore all the registers. Or in user-space with fibers or something, it would just look like a normal function call, with all the call-preserved registers (including RBP) unmodified on return. – Peter Cordes Oct 18 '22 at 11:35
  • @PeterCordes I am actually doing my own userspace fibers with pretty regular `pusq %rbp` & `popq %rbp` (not counting other callee/caller-safe registers). It works well with nested functions but not with `printfn` when I pass some pattern like `printfn("%ith number", 0)`, however `printfn("0th number")` will work as expected. That's were my question comes: I though `printfn` falls with a `segmentation fault` due to broken `rbp`. – Zazaeil Oct 18 '22 at 11:56
  • Shall I update the question with my context switching routine though? – Zazaeil Oct 18 '22 at 11:57
  • 1
    @Zazaeil If that is your question... why didn't you ask it in the first place? Try not to fall prey to the [XY problem](https://xyproblem.info). It's more likely a stack alignment issue. – fuz Oct 18 '22 at 12:01
  • Please post your context switching problem as a separate question as it's really a whole 'nother thing. – fuz Oct 18 '22 at 12:02