title: Virtual Memory Handling
body: <p>I'm working on a PE Loader, just like windows loader</p>
  
  <p>my target is an executable not DLL,i tried first loadlibrary but faced reallocation problems,got some code to fix it, but it didn't work with all targets (some exe's needs to be loaded at the same BaseAdress to work probably</p>
  
  <p>so i got to the point, i've to implement my loader to ensure the BaseAddress issue and no need for reallocation</p>
  
  <p>I'm forcing my application to load at a high addr(0x10000000),while using VirtualAlloc to allocate memory for headers &amp; sections for the target app</p>
  
  <p>i use VirtualQuery to see the state of the address i want to allocate, if not free i use UnMapViewOfFile if Page type MEM_MAPPED else VirtualFree(MEM_RELEASE)</p>
  
  <p>The problem is that if the memory pages are MEM_MAPPED &amp; MEM_COMMIT (always page file backed pages) all methods fails with error code 0x57 ERROR_INVALID_PARAMETER</p>
  
  <p>looking for solutions/ideas   here's the code :</p>
  
  <pre><code>MylpAddr = (DWORD)lpAddr ;
  MemInfo.RegionSize = 0 ;
  NtUnmapViewOfSection=       (NTUNMAPVIEWOFSECTION)GetProcAddress(LoadLibrary(TEXT("ntdll.dll")), "NtUnmapViewOfSection");
  NtProtectVirtualMemory=     (NTPROTECTVIRTUALMEMORY)GetProcAddress(LoadLibrary(TEXT("ntdll.dll")), "NtProtectVirtualMemory");
  NtUnlockVirtualMemory=      (NTUNLOCKVIRTUALMEMORY)GetProcAddress(LoadLibrary(TEXT("ntdll.dll")), "NtUnlockVirtualMemory");
  GetSystemInfo(&amp;siSysInfo);
  szPage = siSysInfo.dwPageSize ;
  
  i = VirtualQuery( (LPCVOID)MylpAddr , &amp;MemInfo , 0x20 ) ;
  if (!i) return NULL ;
  
  if ( !(MemInfo.State &amp; MEM_FREE) )
  {
      if ( MemInfo.Type &amp; MEM_MAPPED )
      {
          hProc = GetCurrentProcess() ;
          szPage = MemInfo.RegionSize ;
          i = NtUnlockVirtualMemory(hProc , (PVOID *)MemInfo.AllocationBase , (PULONG)szPage , LOCK_VM_IN_WORKING_SET | LOCK_VM_IN_RAM );
          i = NtProtectVirtualMemory(hProc , (PVOID *)MemInfo.AllocationBase , (PULONG)szPage , PAGE_READWRITE , &amp;OldProt ) ;
          i = NtUnmapViewOfSection( hProc , (LPVOID)MemInfo.AllocationBase );
          i = UnmapViewOfFile( (LPVOID)MemInfo.AllocationBase );
          if (!i) i =1 ;
      }
      else
      {
          j = VirtualUnlock(MemInfo.BaseAddress , MemInfo.RegionSize);
          i = VirtualFree( (LPVOID)MemInfo.AllocationBase , NULL , MEM_RELEASE ) ;
      }
      if (!i) return NULL ;
  
  }
  
  MylpAddr = (DWORD)VirtualAlloc( lpAddr , dwSize , AllocType , ProtFlags );
  </code></pre>