title: Read access violation using lock xcmpchg16b _InterlockedCompareExchange128
body: <p>I'm trying to hook a function with a lock xcmpchg16b. I have tried about 20 different things.</p>
  
  <p>Expected result:</p>
  
  <pre><code>In real func
  In hook func
  </code></pre>
  
  <p>Result in <strong>Debug</strong> build:</p>
  
  <pre><code>Exception thrown at 0x..: 0xC0000005 Access violation reading 0xFFFFFFFFFFFFFFFF
  </code></pre>
  
  <p>I'm not sure why it is trying to read from 0xFFFFFFFFFFFFFFFF, none of the pointers go there.</p>
  
  <p>In a <strong>Release</strong> build, it doesn't crash! But it doesn't hook the function either.</p>
  
  <p>Source:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;Windows.h&gt;
  
  int RealFunc()
  {
      printf("In real func\n");
      return 2;
  }
  
  int HookFunc()
  {
      printf("In hook func\n");
      return 1;
  }
  
  int main()
  {
      DWORD dwOld;
      if (!VirtualProtect(&amp;RealFunc, 0x1000, PAGE_EXECUTE_READWRITE, &amp;dwOld))
      {
          printf("Unable to make mem RWX.\n");
          return 0;
      }
  
      RealFunc();
  
      __declspec(align(16)) PVOID ProcAddress = &amp;RealFunc;
      __declspec(align(16)) LONG64 Restore[2];
  
      Restore[0] = 0x0000000025ff9090;    // nop, nop, jmp [rip + 0]
      Restore[1] = (LONG64)&amp;HookFunc;
  
      _InterlockedCompareExchange128((LONG64*)ProcAddress, Restore[0], Restore[1], Restore);
  
      RealFunc();
  
      system("PAUSE");
      return 0;
  }
  </code></pre>
  
  <p>Here is the function documentation: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/hh972640(v=vs.85).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/windows/desktop/hh972640(v=vs.85).aspx</a></p>