title: Anti dll Injection with API Hooking "Access Violation writing location 0x0000000000"
body: <p>I'm using the JMP instruction tecnique for try make a Anti-Dll Injection with detour when <em>LdrLoadDll</em> api is called inside my program. I found a Delphi code that works perfectly, but this VC++ 2013 version for this code, crashes with a </p>
  
  <blockquote>
    <p>"Access Violation writing location 0x0000000000"</p>
  </blockquote>
  
  <p>with showed below.</p>
  
  <p>So, how I can solve this trouble? Someone can help me please?</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>Delphi version:</strong></p>
  
  <pre><code>procedure hook(target, newfunc:pointer); 
  var 
    jmpto:dword; 
      OldProtect: Cardinal; // old protect in memory 
  begin 
    jmpto:=dword(newfunc)-dword(target)-5; 
    VirtualProtect(target, 5, PAGE_EXECUTE_READWRITE, @OldProtect); 
    pbyte(target)^:=$e9; 
    pdword(dword(target)+1)^:=jmpto; 
  end; 
  
  procedure myLdrLoadDll(PathToFile:PAnsiChar; Flags:variant; ModuleFileName:PAnsiChar; var ModuleHandle:THandle); 
  begin 
    MessageBox(0, 'I have blocked your attempt to inject a dll file!!', 'WARNING!', MB_OK); 
    ModuleHandle:=0; 
  end; 
  
  procedure Main; 
  begin 
  Hook(GetProcAddress(GetModuleHandle('ntdll.dll'), 'LdrLoadDll'), @myLdrLoadDll); 
  end; 
  
  begin 
  end.
  </code></pre>
  
  <p><strong><em>Trying translate for VC++ 2013 version:</em></strong></p>
  
  <pre><code> BOOL TrampolineAPI(HMODULE hModule, LPCWSTR DllName, LPCSTR ProcName, DWORD dwReplaced)
      {
          DWORD dwReturn;
          DWORD dwOldProtect;
          DWORD dwAddressToHook = (DWORD)GetProcAddress(GetModuleHandle(DllName), ProcName);
          BYTE *pbTargetCode = (BYTE *)dwAddressToHook;
          BYTE *pbReplaced = (BYTE *)dwReplaced;
          VirtualProtect((LPVOID)dwAddressToHook, 5, PAGE_EXECUTE_READWRITE, &amp;dwOldProtect);
          *pbTargetCode++ = 0xE9;   // My trouble is here
          *((signed int*)(pbTargetCode)) = pbReplaced - (pbTargetCode + 4);
          VirtualProtect((LPVOID)dwAddressToHook, 5, PAGE_EXECUTE, &amp;dwOldProtect);
          dwReturn = dwAddressToHook + 5;
          FlushInstructionCache(GetCurrentProcess(), NULL, NULL);
          return TRUE;
      }
  
      void WINAPI Replaced(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType)
      {
          printf("Invasion!!");
      }
  
  
  
      int _tmain(int argc, _TCHAR* argv[])
      {
  
          while (true)
          {
   TrampolineAPI(GetModuleHandle(0), (LPCWSTR)"ntdll.DLL","LdrLoadDLL"(DWORD)Replaced);
  
  
          }
  
  
          return 0;
      }
  </code></pre>