title: Pointlessly trying to compare rsp across a call without using registers
body: <p>I would like to write a small thunk which will call an underlying function and then compare the value of <code>rsp</code> before and after the call. Critically, this code shouldn't clobber any registers.</p>
  
  <p>The obvious implementation is to simply <code>push rsp</code> before the call, and then compare after. The problem is that <code>push rsp</code> itself subtracts 8 from the stack, so you should actually compare the saved value of <code>rsp</code> with the value after the call <em>plus 8</em>.</p>
  
  <p>Here's one way to do it:</p>
  
  <pre><code>foo_thunk:
  push rsp              ; save the value of rsp
  call foo              ; call the underlying function
  add rsp, 8            ; adjust rsp by 8, popping the saved value
  cmp rsp, [rsp - 8]    
  jne bad_rsp           ; bad foo!
  ret
  </code></pre>
  
  <p>The problem is this accesses a value <code>[rsp - 8]</code> which is above <code>rsp</code> - i.e., not <em>on</em> the stack but the nebulous region <em>above</em> the stack. This should be where you have a red-zone, but it isn't when you don't.</p>
  
  <p>What are the alternatives? Performance and code-size is important.</p>