0

I'm given the following code:

#include <stdio.h>
#include <stdlib.h>

int A(int x, int y);
int B(int x, int y);

int *FP;

int main(int argc, char *argv[], char *env[]){
  int a, b, c;
  printf("enter main\n");
  A(a,b);
  printf("exit main\n");

  return 0;
}

int A(int x, int y)
{
    int d, e, f;
    printf("enter A\n");
    d = 4; e = 5; f = 6;
    B(d,e);
    printf("exit A\n");
}

int B(int x, int y)
{
    int u, v, w;
    printf("enter B\n");
    u = 7; v = 8; w = 9;
    asm("movl %ebp, FP"); // set FP = CPU's %ebp register
    //Write C code to question here
    printf("exit B\n");
}

I'm asked to:

  • In B(), FP points the stack frame link list in stack. Print the stack frame link list.
  • Print in HEX the address and contents of the stack from FP to the stack frame of main().

I'm not sure how to get started and was wondering if I could get some advice/hints. Since FP is already pointing to the stack frame, would it be something like printf("%p", &FP)? All help is much appreciated.

SaschaM78
  • 4,376
  • 4
  • 33
  • 42
chacha
  • 99
  • 1
  • 8
  • One of your colleagues asked [How to work with FP in C?](https://stackoverflow.com/questions/48274130/how-to-work-with-fp-in-c) This question, like that one, is signally lack in critical information, such as the platform and compiler and options in use. Note that if you use GCC, the `-O` option turns on `-fomit-frame-pointer`, which makes analysis with a frame pointer difficult. – Jonathan Leffler Jan 16 '18 at 05:48
  • `int *FP;` needs to be `volatile` if you want that to work reliably, because you modify it with a GNU C Basic `asm` statement, which doesn't declare `FP` as an output operand. Of course, I think your assignment is assuming you will compile in debug mode (`-O0`), because it doesn't use `__attribute__((noinline))` either to stop the functions from inlining. `gcc` defaults to `-O0`, which forces the compiler to assume anything might have been asynchronously modified (e.g. by a debugger) between every C statement. So everything is implicitly `volatile` with `-O0`. – Peter Cordes Jan 16 '18 at 09:27
  • @JonathanLeffler: You could use [`int*FP = __builtin_frame_address(0)`](https://gcc.gnu.org/onlinedocs/gcc/Return-Address.html) to get the frame pointer for the current frame. It forces creation of a stack frame for *that* function even when `-fomit-frame-pointer` is enabled, (like it is by default with optimization enabled). It doesn't block inlining, and there won't be a chain of frame pointers if you didn't use `-fno-omit-frame-pointer`, though! Heh, I also noticed this code has multiple Undefined-Behaviour problems, e.g. no `return` in a non-void function. https://godbolt.org/g/Eo6PWd – Peter Cordes Jan 16 '18 at 09:39

0 Answers0