0

Im having a hard time trying to figure out what of the to following options is the second line of code doing and why.

  1. Substracting 1xsizeof(t_stackFrame) to the memory direction of baseStack
  2. Subtracting 1 to the memory direction of baseStack
  3. Subtracting 1xsizeof(t_stackFrame*) (equals to 8 bytes in x64) to the memory direction of baseStack

Here's the code:

static void* initializeStackFrame(void* entryPoint, void* baseStack) {
      t_stackFrame* frame = (t_stackFrame*)baseStack - 1;
      frame->gs = 0x001;
      frame->fs = 0x002;
      frame->r15 = 0x003;
      frame->r14 = 0x004;
      frame->r13 = 0x005;
      frame->r12 = 0x006;
      frame->r11 = 0x007;
      frame->r10 = 0x008;
      frame->r9 = 0x009;
      frame->r8 = 0x00A;
      frame->rsi = 0x00B;
      frame->rdi = 0x00C;
      frame->rbp = 0x00D;
      frame->rdx = 0x00E;
      frame->rcx = 0x00F;
      frame->rbx = 0x010;
      frame->rax = 0x011;
      frame->rip = (uint64_t)entryPoint;
      frame->cs = 0x008;
      frame->eflags = 0x202;
      frame->rsp = (uint64_t) & (frame->base);
      frame->ss = 0x000;
      frame->base = 0x000;

      return (void*)(frame);
}
FRANCISCO BERNAD
  • 473
  • 4
  • 15
  • 1
    take a look at this answer [https://stackoverflow.com/a/394774/4249714](https://stackoverflow.com/a/394774/4249714) – sebastian Aug 22 '20 at 15:49

1 Answers1

1

Pointer arithmetic is defined in terms of the pointed-to type. This code ...

    t_stackFrame* frame = (t_stackFrame*)baseStack - 1;

...

  1. converts the value of baseStack from type void * to type t_stackFrame * (because casts have higher precedence than subtractions or assignments), then
  2. treating the result as a pointer into an array of t_stackFrames, computes a pointer to the (start of) the element immediately preceding the one to which the original pointer points, and finally
  3. assigns the result to variable frame.

That's more or less you alternative (1).

John Bollinger
  • 160,171
  • 8
  • 81
  • 157