Search code examples
c#returncallstack

How could a thread return to a place different from the one it come from in C#?


How could a thread return to a place different from the one it come from in C#?

I met the following excerpt in the CLR via C# book:

Whenever you obtain a stack trace, you might find that some methods in the actual call stack don’t appear in the stack trace string. There are two reasons for this. First, the stack is really a record of where the thread should return to, not where the thread has come from. Second, the just-in-time (JIT) compiler can inline methods to avoid the overhead of calling and returning from a separate method.

Does the excerpt mean that a thread can return not to the place where it come from or does it mean something else? In the former case, could someone give an example when a thread does not return to where it come from, please? And in the latter case, could someone explain what it means in a foolproof manner, please?

For me the excerpt is confusing, because I am used to the behavior of the return statements in functions - they always return to the caller - the place where the thread come from and I can not imagine a case when they would return to a different place. Does it have to do anything with the async/await syntactic sugar?


Solution

  • The excerpt is making a point about the purpose of the return address being pushed on the stack: it's really the address to return, not the address of the jump's origin.

    Another way to look at it is that calling wouldn't need to pair up with returning: instead of call-return you could use push-jump-return, which would put you to a location you pushed, not to the location from which you jumped.