Returns ThreadID of main thread If the process was started by standard ConEmuC/ConEmuHk functions, this function is called with (bUseCurrentAsMain==true) from DllMain. Otherwise we must enumerate **all** processes in system, there is no way to enumerate only current process threads unfortunately. Also, enumerating threads may cause noticeable lags, but we can't do anything with that... However, t
| 64 | /// do anything with that... However, this is rare situation, and in most |
| 65 | /// cases main thread ID is initialized with (bUseCurrentAsMain==true). |
| 66 | DWORD GetMainThreadId(bool bUseCurrentAsMain) |
| 67 | { |
| 68 | // Найти ID основной нити |
| 69 | if (!gnHookMainThreadId) |
| 70 | { |
| 71 | if (bUseCurrentAsMain) |
| 72 | { |
| 73 | // Only one thread is expected at the moment |
| 74 | gnHookMainThreadId = GetCurrentThreadId(); |
| 75 | } |
| 76 | else |
| 77 | { |
| 78 | const DWORD dwPID = GetCurrentProcessId(); |
| 79 | |
| 80 | #ifdef FORCE_GETMAINTHREAD_PRINTF |
| 81 | wchar_t szInfo[160] = L"", szTail[32] = L""; |
| 82 | msprintf(szInfo, countof(szInfo), L"\x1B[1;31;40m" L"*** [PID=%u %s] GetMainThreadId is using CreateToolhelp32Snapshot", dwPID, gsExeName); |
| 83 | wcscpy_c(szTail, L"\x1B[1;31;40m" L" ***" L"\x1B[0m" L"\n"); |
| 84 | WriteProcessed2(szInfo, LODWORD(wcslen(szInfo)), nullptr, wps_Error); |
| 85 | #endif |
| 86 | |
| 87 | // Unfortunately, dwPID is ignored in TH32CS_SNAPTHREAD |
| 88 | MToolHelpThread snapshot(dwPID); |
| 89 | THREADENTRY32 thread = {}; |
| 90 | // Don't stop enumeration on first thread, populate gStartedThreads |
| 91 | while (snapshot.Next(thread)) |
| 92 | { |
| 93 | if (thread.th32OwnerProcessID == dwPID) |
| 94 | { |
| 95 | DWORD nTID = thread.th32ThreadID; |
| 96 | |
| 97 | if (!gnHookMainThreadId) |
| 98 | gnHookMainThreadId = nTID; |
| 99 | |
| 100 | if (!gStartedThreads.Get(nTID, nullptr)) |
| 101 | gStartedThreads.Set(nTID, FALSE); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | #ifdef FORCE_GETMAINTHREAD_PRINTF |
| 106 | WriteProcessed2(szTail, LODWORD(wcslen(szTail)), nullptr, wps_Error); |
| 107 | #endif |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | #ifdef _DEBUG |
| 112 | char szInfo[100]; |
| 113 | msprintf(szInfo, countof(szInfo), "GetMainThreadId()=%u, TID=%u\n", gnHookMainThreadId, GetCurrentThreadId()); |
| 114 | //OutputDebugStringA(szInfo); |
| 115 | #endif |
| 116 | |
| 117 | _ASSERTE(gnHookMainThreadId!=0); |
| 118 | return gnHookMainThreadId; |
| 119 | } |
| 120 | |
| 121 | |
| 122 | // The problem was in third-party hooking application on cygwin ssh. |