title: WinAPI: Is it needed to call FlushInstructionCache on an executable memory-mapped file?
body: <p>I have written a short program to read a windows obj file and find the .text section and run the code in it. To do this I make the following Windows API function calls (<a href="https://gist.github.com/Fsmv/ffb290c99a35795dbcfa7eba05616c20" rel="noreferrer">Full code [gist.github.com]</a>, for those interested):</p>
  
  <pre><code>HANDLE FileHandle = CreateFile("lib.obj",
                                 GENERIC_READ | GENERIC_EXECUTE,
                                 FILE_SHARE_READ, 0,
                                 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  
  HANDLE MappingHandle = CreateFileMapping(FileHandle, 0, PAGE_EXECUTE_READ, 0, 0, 0);
  
  void *Address = MapViewOfFile(MappingHandle, FILE_MAP_EXECUTE | FILE_MAP_READ,
                                0, 0, 0);
  </code></pre>
  
  <p>I then find the .text section in the file and cast the pointer to the code to a function pointer in C++ and simply call the function. This actually appeared to work for me.</p>
  
  <p><strong>Have I made a mistake not calling FlushInstructonCache on the range of virtual memory mapped to the file?</strong></p>
  
  <p>I ask this because I was recently reading the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa366887(v=vs.85).aspx" rel="noreferrer">VirtualAlloc</a> documentation and it notes at the bottom:</p>
  
  <blockquote>
    <p>When creating a region that will be executable, the calling program bears responsibility for ensuring cache coherency via an appropriate call to <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms679350(v=vs.85).aspx" rel="noreferrer">FlushInstructionCache</a> once the code has been set in place. Otherwise attempts to execute code out of the newly executable region may produce unpredictable results.</p>
  </blockquote>
  
  <p>Is it possible that my code will cause the CPU to execute old instructions in the instruction cache?</p>
  
  <p>There is no such note on the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa366761(v=vs.85).aspx" rel="noreferrer">MapViewOfFile</a> or <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa366537(v=vs.85).aspx" rel="noreferrer">CreateFileMapping</a> pages.</p>