0

I have inserted the following asm code in my C++ code. I am using a VC++ compiler.

char c;
curr_stack_return_addr = s.AddrFrame.Offset; //I am doing a stack walk
    __asm{  
            push bx
            mov eax, curr_stack_return_addr  
            mov bl, BYTE PTR [eax - 1]
            mov c,bl
            pop bx

     }

I get the correct value in c for my functions but it crashes when it reaches system functions on stack. I get no compiler errors. What did I do wrong?

Resolved: I forgot to check for end of stack! The return address in last frame is 0. Thanks everyone.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Bruce
  • 33,927
  • 76
  • 174
  • 262
  • When does it crash ? How do you know you got correct value in c – Madhur Ahuja Dec 31 '10 at 10:26
  • 1
    Try removing the line, " mov bl, BYTE PTR [eax - 1]". I am not experienced with Assembly but I suspect you maybe addressing incorrect memory here. Your fix may revolve around this. – Shamim Hafiz - MSFT Dec 31 '10 at 10:26
  • 2
    Please, do a stack walk with StackWalk64, unless you have multi-threading + performance critical considerations. – Yakov Galka Dec 31 '10 at 10:45
  • 1
    you don't need to `push bx`, and even if you did `push ebx` would be more efficient. Unlike GNU C inline asm, MSVC inline asm saves any registers you use. (see also [this comparison of GNU C inline asm vs. MSVC style](http://stackoverflow.com/questions/3323445/what-is-the-difference-between-asm-and-asm/35959859#35959859). Actually, I don't understand why you need inline asm for this at all. I could see using it to get the current value of `esp` or something, but you could and should do this with pure C by casting to a pointer-to-struct or to `char*`. – Peter Cordes Aug 07 '16 at 16:16

2 Answers2

4

I see two problems here:

  1. push bl and pop bl don't exist. You can only push and pop word or dwords. The compiler warns by the way.

  2. How do you know that eax points to a legal address?

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
3

You have no way of knowing the value of eax when your program enters the asm block.

Eugene Smith
  • 9,126
  • 6
  • 36
  • 40