From b8a6996906808619f65d36372228f633b8aa4d5b Mon Sep 17 00:00:00 2001
From: "SND\\kernelnet_cp"
 <SND\kernelnet_cp@9b283d60-5439-405e-af05-b73fd8c4d996>
Date: Tue, 16 Oct 2012 05:57:48 +0000
Subject: [PATCH] [0.2.x] added : attachProcess routine

git-svn-id: https://pykd.svn.codeplex.com/svn@80240 9b283d60-5439-405e-af05-b73fd8c4d996
---
 pykd/dbgengine.h    |  1 +
 pykd/pymod.cpp      |  2 ++
 pykd/win/dbgeng.cpp | 34 ++++++++++++++++++++++++++++++++++
 3 files changed, 37 insertions(+)

diff --git a/pykd/dbgengine.h b/pykd/dbgengine.h
index 9d14f4f..3fab1e8 100644
--- a/pykd/dbgengine.h
+++ b/pykd/dbgengine.h
@@ -7,6 +7,7 @@ namespace pykd {
 
 // manage debug target
 ULONG startProcess( const std::wstring  &processName );
+ULONG attachProcess( ULONG pid );
 void detachProcess( ULONG processId = -1);
 void terminateProcess( ULONG processId = -1);
 
diff --git a/pykd/pymod.cpp b/pykd/pymod.cpp
index 03ec690..edc0c5b 100644
--- a/pykd/pymod.cpp
+++ b/pykd/pymod.cpp
@@ -70,6 +70,8 @@ BOOST_PYTHON_MODULE( pykd )
 
     python::def( "startProcess", &startProcess,
         "Start process for debugging"); 
+    python::def( "attachProcess", &attachProcess,
+        "Attach debugger to a exsisting process" );
     python::def( "detachProcess", &detachProcess, 
         "Stop process debugging"); 
     python::def( "killProcess", &terminateProcess,
diff --git a/pykd/win/dbgeng.cpp b/pykd/win/dbgeng.cpp
index 58d9bed..b09ecf2 100644
--- a/pykd/win/dbgeng.cpp
+++ b/pykd/win/dbgeng.cpp
@@ -51,6 +51,40 @@ ULONG startProcess( const std::wstring  &processName )
 
 ///////////////////////////////////////////////////////////////////////////////////
 
+ULONG attachProcess( ULONG pid )
+{
+    PyThread_StateRestore pyThreadRestore( g_dbgEng->pystate );
+
+    HRESULT     hres;
+
+    ULONG       opt;
+    hres = g_dbgEng->control->GetEngineOptions( &opt );
+    if ( FAILED( hres ) )
+        throw DbgException( "IDebugControl::GetEngineOptions failed" );
+
+    opt |= DEBUG_ENGOPT_INITIAL_BREAK;
+    hres = g_dbgEng->control->SetEngineOptions( opt );
+    if ( FAILED( hres ) )
+        throw DbgException( "IDebugControl::SetEngineOptions failed" );
+    
+    hres = g_dbgEng->client->AttachProcess( 0, pid, 0 );
+    if ( FAILED( hres ) )
+        throw DbgException( "IDebugClient::AttachProcess failed" );
+
+    hres = g_dbgEng->control->WaitForEvent(DEBUG_WAIT_DEFAULT, INFINITE);
+    if ( FAILED( hres ) )
+        throw DbgException( "IDebugControl::WaitForEvent failed" );
+
+    ULONG processId = -1;
+    hres = g_dbgEng->system->GetCurrentProcessId( &processId );
+    if ( FAILED( hres ) )
+        throw DbgException( "IDebugSystemObjects::GetCurrentProcessId failed" );
+
+    return processId;
+}
+
+///////////////////////////////////////////////////////////////////////////////////
+
 void detachProcess( ULONG processId )
 {
     PyThread_StateRestore pyThreadRestore( g_dbgEng->pystate );