Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3185 lines
102 KiB

  1. /******************************************************************************
  2. Copyright (c) 2000 Microsoft Corporation
  3. Module Name:
  4. faultrep.cpp
  5. Abstract:
  6. Implements utility functions for fault reporting
  7. Revision History:
  8. created derekm 07/07/00
  9. ******************************************************************************/
  10. /////////////////////////////////////////////////////////////////////////////
  11. // tracing
  12. #include "stdafx.h"
  13. #include "wtsapi32.h"
  14. #include "userenv.h"
  15. #include "frmc.h"
  16. #include "tlhelp32.h"
  17. #include "shimdb.h"
  18. #include "dbgeng.h"
  19. #ifdef THIS_FILE
  20. #undef THIS_FILE
  21. #endif
  22. static char __szTraceSourceFile[] = __FILE__;
  23. #define THIS_FILE __szTraceSourceFile
  24. ///////////////////////////////////////////////////////////////////////////////
  25. // typedefs
  26. typedef BOOL (STDAPICALLTYPE *DUMPWRITE_FN)(HANDLE, DWORD, HANDLE,
  27. MINIDUMP_TYPE,
  28. PMINIDUMP_EXCEPTION_INFORMATION,
  29. PMINIDUMP_USER_STREAM_INFORMATION,
  30. PMINIDUMP_CALLBACK_INFORMATION);
  31. typedef DWORD (WINAPI *pfn_GETMODULEFILENAMEEXW)(HANDLE, HMODULE, LPWSTR, DWORD);
  32. ///////////////////////////////////////////////////////////////////////////////
  33. // globals
  34. ///////////////////////////////////////////////////////////////////////////////
  35. // useful structs
  36. struct SLangCodepage
  37. {
  38. WORD wLanguage;
  39. WORD wCodePage;
  40. };
  41. ///////////////////////////////////////////////////////////////////////////////
  42. // misc utility functions
  43. /*************************************************************
  44. *
  45. * localKill(WTS_USER_SESSION_INFO *SessInfo, LPTHREAD_START_ROUTINE lpKill)
  46. * kills the process for us.
  47. *
  48. *************************************************************/
  49. DWORD LocalKill(HANDLE hProc)
  50. {
  51. USE_TRACING("localKill");
  52. LPTHREAD_START_ROUTINE lpKill = NULL;
  53. HMODULE hKernel = LoadLibraryW(L"kernel32");
  54. if (hKernel)
  55. {
  56. lpKill = (LPTHREAD_START_ROUTINE)GetProcAddress(hKernel, "ExitProcess");
  57. FreeLibrary(hKernel);
  58. }
  59. if (lpKill)
  60. {
  61. HANDLE hKillThrd= CreateRemoteThread(
  62. hProc,
  63. NULL,
  64. NULL,
  65. lpKill,
  66. 0,
  67. 0,
  68. NULL);
  69. if (hKillThrd)
  70. {
  71. CloseHandle(hKillThrd);
  72. return 1;
  73. }
  74. DBG_MSG("CreateRemoteThread failed");
  75. // the fall-through is by design...
  76. }
  77. if(!TerminateProcess( hProc, 0 ))
  78. {
  79. DBG_MSG("TerminateProcess failed");
  80. return 1;
  81. }
  82. return 0;
  83. }
  84. // **************************************************************************
  85. void __cdecl TextLogOut(PCSTR pszFormat, ...)
  86. {
  87. va_list Args;
  88. HANDLE hFaultLog;
  89. SYSTEMTIME st;
  90. WCHAR wszSysDir[MAX_PATH];
  91. DWORD cb, cbWritten;
  92. char szMsg[512];
  93. cb = GetSystemDirectoryW(wszSysDir, sizeofSTRW(wszSysDir));
  94. if (cb == 0 || cb >= sizeofSTRW(wszSysDir))
  95. {
  96. // Couldn't get the system directory.
  97. return;
  98. }
  99. // assume system is on a local drive with a base path of "X:\"
  100. wszSysDir[3] = L'\0';
  101. if (StringCbCatW(wszSysDir, sizeof(wszSysDir), c_wszLogFileName) != S_OK)
  102. {
  103. // Overflow.
  104. return;
  105. }
  106. hFaultLog = CreateFileW(wszSysDir, GENERIC_WRITE,
  107. FILE_SHARE_WRITE | FILE_SHARE_READ,
  108. NULL, OPEN_ALWAYS, 0, NULL);
  109. if (hFaultLog == INVALID_HANDLE_VALUE)
  110. {
  111. return;
  112. }
  113. SetFilePointer(hFaultLog, 0, NULL, FILE_END);
  114. GetSystemTime(&st);
  115. if (StringCbPrintfA(szMsg, sizeof(szMsg),
  116. "%02d-%02d-%04d %02d:%02d:%02d ",
  117. st.wDay, st.wMonth, st.wYear, st.wHour, st.wMinute,
  118. st.wSecond) == S_OK)
  119. {
  120. cb = strlen(szMsg);
  121. } else
  122. {
  123. cb = 0;
  124. }
  125. WriteFile(hFaultLog, szMsg, cb, &cbWritten, NULL);
  126. va_start(Args, pszFormat);
  127. if (StringCbVPrintfA(szMsg, sizeof(szMsg), pszFormat, Args) == S_OK)
  128. {
  129. cb = strlen(szMsg);
  130. } else
  131. {
  132. cb = 0;
  133. }
  134. va_end(Args);
  135. WriteFile(hFaultLog, szMsg, cb, &cbWritten, NULL);
  136. CloseHandle(hFaultLog);
  137. }
  138. // **************************************************************************
  139. HMODULE MySafeLoadLibrary(LPCWSTR wszModule)
  140. {
  141. HMODULE hmod = NULL;
  142. PVOID pvLdrLockCookie = NULL;
  143. ULONG ulLockState = 0;
  144. // make sure that no one else owns the loader lock because we
  145. // could otherwise deadlock
  146. LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY, &ulLockState,
  147. &pvLdrLockCookie);
  148. if (ulLockState == LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED)
  149. {
  150. __try { hmod = LoadLibraryExW(wszModule, NULL, 0); }
  151. __except(EXCEPTION_EXECUTE_HANDLER) { hmod = NULL; }
  152. LdrUnlockLoaderLock(0, pvLdrLockCookie);
  153. }
  154. return hmod;
  155. }
  156. // **************************************************************************
  157. static inline WCHAR itox(DWORD dw)
  158. {
  159. dw &= 0xf;
  160. return (WCHAR)((dw < 10) ? (L'0' + dw) : (L'A' + (dw - 10)));
  161. }
  162. // **************************************************************************
  163. BOOL IsASCII(LPCWSTR wszSrc)
  164. {
  165. const WCHAR *pwsz;
  166. // check and see if we need to hexify the string. This is determined
  167. // by whether the string contains all ASCII characters or not. Since
  168. // an ASCII character is defined as being in the range of 00 -> 7f, just
  169. // 'and' the wchar's value with ~0x7f and see if the result is 0. If it
  170. // is, then the whcar is an ASCII value.
  171. for (pwsz = wszSrc; *pwsz != L'\0'; pwsz++)
  172. {
  173. if ((*pwsz & ~0x7f) != 0)
  174. return FALSE;
  175. }
  176. return TRUE;
  177. }
  178. // **************************************************************************
  179. BOOL IsValidField(LPWSTR wsz)
  180. {
  181. WCHAR *pwsz;
  182. if (wsz == NULL)
  183. return FALSE;
  184. for(pwsz = wsz; *pwsz != L'\0'; pwsz++)
  185. {
  186. if (iswspace(*pwsz) == FALSE)
  187. return TRUE;
  188. }
  189. return FALSE;
  190. }
  191. // **************************************************************************
  192. BOOL TransformForWire(LPCWSTR wszSrc, LPWSTR wszDest, DWORD cchDest)
  193. {
  194. HRESULT hr = NOERROR;
  195. DWORD cch;
  196. USE_TRACING("TransformForWire");
  197. VALIDATEPARM(hr, (wszSrc == NULL || wszDest == NULL || cchDest < 5));
  198. if (FAILED(hr))
  199. goto done;
  200. if (cchDest > 5)
  201. {
  202. // darn! Gotta convert every character to a 4 char hex value cuz this
  203. // is what DW does and we have to match them
  204. for (cch = 0; *wszSrc != L'\0' && cch + 4 < cchDest; cch += 4, wszSrc++)
  205. {
  206. *wszDest++ = itox((*wszSrc & 0xf000) > 12);
  207. *wszDest++ = itox((*wszSrc & 0x0f00) > 8);
  208. *wszDest++ = itox((*wszSrc & 0x00f0) > 4);
  209. *wszDest++ = itox((*wszSrc & 0x000f));
  210. }
  211. // if we don't see this, then we've got too small of a buffer
  212. if (*wszSrc != L'\0' || cch >= cchDest)
  213. {
  214. hr = E_FAIL;
  215. goto done;
  216. }
  217. *wszDest = L'\0';
  218. }
  219. else
  220. {
  221. hr = E_FAIL;
  222. }
  223. done:
  224. return (SUCCEEDED(hr));
  225. }
  226. // ***************************************************************************
  227. LPWSTR MarshallString(LPCWSTR wszSrc, PBYTE pBase, ULONG cbMaxBuf,
  228. PBYTE *ppToWrite, DWORD *pcbWritten)
  229. {
  230. DWORD cb;
  231. PBYTE pwszNormalized;
  232. cb = (wcslen(wszSrc) + 1) * sizeof(WCHAR);
  233. if ((*pcbWritten + cb) > cbMaxBuf)
  234. return NULL;
  235. RtlMoveMemory(*ppToWrite, wszSrc, cb);
  236. // the normalized ptr is the current count
  237. pwszNormalized = (PBYTE)(*ppToWrite - pBase);
  238. // cb is always a mutliple of sizeof(WHCAR) so the pointer addition below
  239. // always produces a result that is 2byte aligned (assuming the input was
  240. // 2byte aligned of course)
  241. *ppToWrite += cb;
  242. *pcbWritten += cb;
  243. return (LPWSTR)pwszNormalized;
  244. }
  245. // **************************************************************************
  246. HRESULT GetVerName(LPWSTR wszModule, LPWSTR wszName, DWORD cchName,
  247. LPWSTR wszVer, DWORD cchVer,
  248. LPWSTR wszCompany, DWORD cchCompany,
  249. BOOL fAcceptUnicodeCP, BOOL fWantActualName)
  250. {
  251. USE_TRACING("GetVerName");
  252. VS_FIXEDFILEINFO *pffi;
  253. SLangCodepage *plc;
  254. HRESULT hr = NOERROR;
  255. WCHAR wszQuery[128], *pwszProp = NULL;
  256. WCHAR *pwszPropVal;
  257. DWORD cbFVI, dwJunk, dwMSWin = 0;
  258. PBYTE pbFVI = NULL;
  259. UINT cb, cbVerInfo, i;
  260. SLangCodepage rglc[] = { { 0, 0 }, // UI language if one exists
  261. { 0x409, 0x4B0 }, // unicode English
  262. { 0x409, 0x4E4 }, // English
  263. { 0x409, 0 }, // English, null codepage
  264. { 0 , 0x4E4 } }; // language neutral.
  265. VALIDATEPARM(hr, (wszModule == NULL || wszName == NULL || cchName == 0));
  266. if (FAILED(hr))
  267. goto done;
  268. if (wszCompany != NULL)
  269. *wszCompany = L'\0';
  270. if (wszVer != NULL)
  271. wcsncpy(wszVer, L"0.0.0.0", cchVer);
  272. if (fWantActualName)
  273. {
  274. *wszName = L'\0';
  275. }
  276. else
  277. {
  278. for(pwszPropVal = wszModule + wcslen(wszModule);
  279. pwszPropVal >= wszModule && *pwszPropVal != L'\\';
  280. pwszPropVal--);
  281. if (*pwszPropVal == L'\\')
  282. pwszPropVal++;
  283. wcsncpy(wszName, pwszPropVal, cchName);
  284. wszName[cchName - 1] = L'\0';
  285. }
  286. // dwJunk is a useful parameter. Gotta pass it in so the function call
  287. // set it to 0. Gee this would make a great (tho non-efficient)
  288. // way to set DWORDs to 0. Much better than saying dwJunk = 0 by itself.
  289. cbFVI = GetFileVersionInfoSizeW(wszModule, &dwJunk);
  290. TESTBOOL(hr, (cbFVI != 0));
  291. if (FAILED(hr))
  292. {
  293. // if it fails, assume the file doesn't have any version info &
  294. // return S_FALSE
  295. hr = S_FALSE;
  296. goto done;
  297. }
  298. // alloca only throws exceptions so gotta catch 'em here...
  299. __try
  300. {
  301. __try { pbFVI = (PBYTE)_alloca(cbFVI); }
  302. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  303. {
  304. pbFVI = NULL;
  305. }
  306. _ASSERT(pbFVI != NULL);
  307. hr = NOERROR;
  308. }
  309. __except(EXCEPTION_EXECUTE_HANDLER)
  310. {
  311. pbFVI = NULL;
  312. }
  313. VALIDATEEXPR(hr, (pbFVI == NULL), E_OUTOFMEMORY);
  314. if (FAILED(hr))
  315. goto done;
  316. cb = cbFVI;
  317. TESTBOOL(hr, GetFileVersionInfoW(wszModule, 0, cbFVI, (LPVOID *)pbFVI));
  318. if (FAILED(hr))
  319. {
  320. // if it fails, assume the file doesn't have any version info &
  321. // return S_FALSE
  322. hr = S_FALSE;
  323. goto done;
  324. }
  325. // determine if it's a MS app or windows componenet
  326. dwMSWin = IsMicrosoftApp(NULL, pbFVI, cbFVI);
  327. // get the real version info- apparently, the string can occasionally
  328. // be out of sync (so says the explorer.exe code that extracts ver info)
  329. if (wszVer != NULL &&
  330. VerQueryValueW(pbFVI, L"\\", (LPVOID *)&pffi, &cb) && cb != 0)
  331. {
  332. WCHAR wszVerTemp[64];
  333. StringCbPrintfW(wszVerTemp, sizeof(wszVerTemp), L"%d.%d.%d.%d",
  334. HIWORD(pffi->dwFileVersionMS),LOWORD(pffi->dwFileVersionMS),
  335. HIWORD(pffi->dwFileVersionLS),LOWORD(pffi->dwFileVersionLS));
  336. StringCbCopyW(wszVer, cchVer, wszVerTemp);
  337. wszVer[cchVer - 1] = L'\0';
  338. }
  339. // try to figure out what the appropriate langage...
  340. TESTBOOL(hr, VerQueryValueW(pbFVI, L"\\VarFileInfo\\Translation",
  341. (LPVOID *)&plc, &cbVerInfo));
  342. if (SUCCEEDED(hr))
  343. {
  344. LANGID langid;
  345. DWORD cLangs, iUni = (DWORD)-1;
  346. UINT uiACP;
  347. langid = GetUserDefaultUILanguage();
  348. cLangs = cbVerInfo / sizeof(SLangCodepage);
  349. uiACP = GetACP();
  350. // see if there's a language that matches the default
  351. for(i = 0; i < cLangs; i++)
  352. {
  353. // not sure what to do if there are multiple code pages for a
  354. // particular language. Just take the first, I guess...
  355. if (langid == plc[i].wLanguage && uiACP == plc[i].wCodePage)
  356. break;
  357. // if we can accept the unicode code page & we encounter a
  358. // launguage with it, then remember it. Note that we only
  359. // remember the first such instance we see or one that matches
  360. // the target language
  361. if (fAcceptUnicodeCP && plc[i].wCodePage == 1200 &&
  362. (iUni == (DWORD)-1 || langid == plc[i].wLanguage))
  363. iUni = i;
  364. }
  365. if (i >= cLangs && iUni != (DWORD)-1)
  366. i = iUni;
  367. if (i < cLangs)
  368. {
  369. rglc[0].wLanguage = plc[i].wLanguage;
  370. rglc[0].wCodePage = plc[i].wCodePage;
  371. }
  372. }
  373. for(i = 0; i < 5; i++)
  374. {
  375. if (rglc[i].wLanguage == 0 && rglc[i].wCodePage == 0)
  376. continue;
  377. StringCbPrintfW(wszQuery, sizeof(wszQuery), L"\\StringFileInfo\\%04x%04x\\FileVersion",
  378. rglc[i].wLanguage, rglc[i].wCodePage);
  379. // Retrieve file description for language and code page 'i'.
  380. TESTBOOL(hr, VerQueryValueW(pbFVI, wszQuery,
  381. (LPVOID *)&pwszPropVal, &cb));
  382. if (SUCCEEDED(hr) && cb != 0)
  383. {
  384. // want to get size of a normal char string & not a unicode
  385. // string cuz we'd have to / sizeof(WCHAR) otherwise
  386. pwszProp = wszQuery + sizeof("\\StringFileInfo\\%04x%04x\\") - 1;
  387. cbVerInfo = sizeof(wszQuery) - (ULONG) (((ULONG_PTR)pwszProp - (ULONG_PTR)wszQuery) * sizeof(WCHAR));
  388. break;
  389. }
  390. }
  391. // if we still didn't find anything, then assume there's no version
  392. // resource. We've already set the defaults above, so we can bail...
  393. if (pwszProp == NULL)
  394. {
  395. hr = NOERROR;
  396. goto done;
  397. }
  398. if (wszCompany != NULL)
  399. {
  400. StringCbCopyW(pwszProp, cbVerInfo, L"CompanyName");
  401. TESTBOOL(hr, VerQueryValueW(pbFVI, wszQuery, (LPVOID *)&pwszPropVal,
  402. &cb));
  403. if (SUCCEEDED(hr) && cb != 0)
  404. {
  405. wcsncpy(wszCompany, pwszPropVal, cchCompany);
  406. wszCompany[cchCompany - 1] = L'\0';
  407. }
  408. }
  409. // So to fix the case where Windows components did not properly update
  410. // the product strings, we have to look for the FileDescription first.
  411. // But since the OCA folks want only the description (convieniently
  412. // when the fWantActualName field is set) then we need to only read
  413. // the ProductName field.
  414. if (fWantActualName)
  415. {
  416. StringCbCopyW(pwszProp, cbVerInfo, L"ProductName");
  417. TESTBOOL(hr, VerQueryValueW(pbFVI, wszQuery, (LPVOID *)&pwszPropVal,
  418. &cb));
  419. if (SUCCEEDED(hr) && cb != 0 && IsValidField(pwszPropVal))
  420. {
  421. wcsncpy(wszName, pwszPropVal, cchName);
  422. wszName[cchName - 1] = L'\0';
  423. goto done;
  424. }
  425. }
  426. else
  427. {
  428. StringCbCopyW(pwszProp, cbVerInfo, L"FileDescription");
  429. TESTBOOL(hr, VerQueryValueW(pbFVI, wszQuery, (LPVOID *)&pwszPropVal,
  430. &cb));
  431. if (SUCCEEDED(hr) && cb != 0 && IsValidField(pwszPropVal))
  432. {
  433. wcsncpy(wszName, pwszPropVal, cchName);
  434. wszName[cchName - 1] = L'\0';
  435. goto done;
  436. }
  437. if ((dwMSWin & APP_WINCOMP) == 0)
  438. {
  439. StringCbCopyW(pwszProp, cbVerInfo, L"ProductName");
  440. TESTBOOL(hr, VerQueryValueW(pbFVI, wszQuery,
  441. (LPVOID *)&pwszPropVal, &cb));
  442. if (SUCCEEDED(hr) && cb != 0 && IsValidField(pwszPropVal))
  443. {
  444. wcsncpy(wszName, pwszPropVal, cchName);
  445. wszName[cchName - 1] = L'\0';
  446. goto done;
  447. }
  448. }
  449. StringCbCopyW(pwszProp, cbVerInfo, L"InternalName");
  450. TESTBOOL(hr, VerQueryValueW(pbFVI, wszQuery,
  451. (LPVOID *)&pwszPropVal, &cb));
  452. if (SUCCEEDED(hr) && cb != 0 && IsValidField(pwszPropVal))
  453. {
  454. wcsncpy(wszName, pwszPropVal, cchName);
  455. wszName[cchName - 1] = L'\0';
  456. goto done;
  457. }
  458. }
  459. // We didn't find a name string but we've defaulted
  460. // the name and we may have other valid data, so
  461. // return success.
  462. hr = S_OK;
  463. done:
  464. return hr;
  465. }
  466. // **************************************************************************
  467. HRESULT
  468. GetErrorSignature(LPWSTR wszAppName, LPWSTR wszModName,
  469. WORD rgAppVer[4], WORD rgModVer[4], UINT64 pvOffset,
  470. BOOL f64Bit, LPWSTR *ppwszErrorSig, ULONG cchErrorSig)
  471. {
  472. ULONG cbNeeded;
  473. HRESULT hr;
  474. LPWSTR pwszFmt;
  475. USE_TRACING("GetErrorSignature");
  476. VALIDATEPARM(hr, (wszAppName == NULL || wszModName == NULL ||
  477. ppwszErrorSig == NULL));
  478. if (FAILED(hr))
  479. goto done;
  480. if (cchErrorSig == 0)
  481. {
  482. // we need to allocate memory
  483. cbNeeded = c_cbManErrorSig + (wcslen(wszModName) + wcslen(wszAppName)) * sizeof(WCHAR);
  484. *ppwszErrorSig = (LPWSTR)MyAlloc(cbNeeded);
  485. VALIDATEEXPR(hr, (*ppwszErrorSig == NULL), E_OUTOFMEMORY);
  486. if (FAILED(hr))
  487. goto done;
  488. cchErrorSig = cbNeeded / sizeof(WCHAR);
  489. }
  490. #ifdef _WIN64
  491. if (f64Bit)
  492. {
  493. pwszFmt = (LPWSTR) c_wszManErrorSig64;
  494. } else
  495. #endif
  496. {
  497. pwszFmt = (LPWSTR) c_wszManErrorSig32;
  498. }
  499. hr = StringCchPrintfW(*ppwszErrorSig, cchErrorSig, pwszFmt,
  500. wszAppName,
  501. rgAppVer[0], rgAppVer[1], rgAppVer[2], rgAppVer[3],
  502. wszModName,
  503. rgModVer[0], rgModVer[1], rgModVer[2], rgModVer[3],
  504. (LPVOID)pvOffset);
  505. done:
  506. return hr;
  507. }
  508. // **************************************************************************
  509. HRESULT BuildManifestURLs(LPWSTR wszAppName, LPWSTR wszModName,
  510. WORD rgAppVer[4], WORD rgModVer[4], UINT64 pvOffset,
  511. BOOL f64Bit, LPWSTR *ppwszS1, LPWSTR *ppwszS2,
  512. LPWSTR *ppwszCP, BYTE **ppb)
  513. {
  514. HRESULT hr = NOERROR;
  515. LPWSTR pwszApp, pwszMod, pwszAppVer=NULL, pwszModVer=NULL;
  516. LPWSTR wszStage1, wszStage2, wszCorpPath;
  517. DWORD cbNeeded, cch;
  518. WCHAR *pwsz;
  519. BYTE *pbBuf = NULL;
  520. USE_TRACING("BuildManifestURLs");
  521. VALIDATEPARM(hr, (wszAppName == NULL || wszModName == NULL ||
  522. ppwszS1 == NULL || ppwszS2 == NULL || ppwszCP == NULL ||
  523. ppb == NULL));
  524. if (FAILED(hr))
  525. goto done;
  526. *ppb = NULL;
  527. *ppwszS1 = NULL;
  528. *ppwszS2 = NULL;
  529. *ppwszCP = NULL;
  530. // hexify the app name if necessary
  531. if (IsASCII(wszAppName))
  532. {
  533. cch = (wcslen(wszAppName) + 1);
  534. __try { pwszApp = (LPWSTR)_alloca(cch * sizeof(WCHAR)); }
  535. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  536. {
  537. pwszApp = NULL;
  538. }
  539. if (pwszApp != NULL)
  540. StringCchCopyW(pwszApp, cch, wszAppName);
  541. else
  542. pwszApp = wszAppName;
  543. }
  544. else
  545. {
  546. cch = (4 * wcslen(wszAppName) + 1);
  547. __try { pwszApp = (LPWSTR)_alloca(cch * sizeof(WCHAR)); }
  548. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  549. {
  550. pwszApp = NULL;
  551. }
  552. if (pwszApp != NULL)
  553. {
  554. if (TransformForWire(wszAppName, pwszApp, cch) == FALSE)
  555. *pwszApp = L'\0';
  556. }
  557. else
  558. {
  559. pwszApp = wszAppName;
  560. }
  561. }
  562. // hexify the module name if necessary
  563. if (IsASCII(wszModName))
  564. {
  565. cch = (wcslen(wszModName) + 1);
  566. __try { pwszMod = (LPWSTR)_alloca(cch * sizeof(WCHAR)); }
  567. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  568. {
  569. pwszMod = NULL;
  570. }
  571. if (pwszMod != NULL)
  572. StringCchCopyW(pwszMod, cch, wszModName);
  573. else
  574. pwszMod = wszModName;
  575. }
  576. else
  577. {
  578. cch = (4 * wcslen(wszModName) + 1);
  579. __try { pwszMod = (LPWSTR)_alloca(cch * sizeof(WCHAR)); }
  580. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  581. {
  582. pwszMod = NULL;
  583. }
  584. if (pwszMod != NULL)
  585. {
  586. if (TransformForWire(wszModName, pwszMod, cch) == FALSE)
  587. *pwszMod = L'\0';
  588. }
  589. else
  590. {
  591. pwszMod = wszModName;
  592. }
  593. }
  594. // truncate the appname & modname as needed to 64 characters
  595. if (63 < wcslen(pwszApp))
  596. {
  597. pwszApp[64] = 0;
  598. ErrorTrace(1, "AppName trunc'd to \'%ls\'", pwszApp);
  599. }
  600. if (63 < wcslen(pwszMod))
  601. {
  602. pwszMod[64] = 0;
  603. ErrorTrace(1, "ModName trunc'd to \'%ls\'", pwszMod);
  604. }
  605. // then print the AppVer & ModVer, again truncating as needed
  606. // This time, our limit is 24 characters
  607. __try { pwszModVer = (LPWSTR)_alloca(50 * sizeof(WCHAR)); }
  608. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  609. {
  610. pwszModVer = NULL;
  611. }
  612. if (pwszModVer)
  613. {
  614. ZeroMemory(pwszModVer, 50 * sizeof(WCHAR));
  615. pwszAppVer = pwszModVer + 25;
  616. StringCchPrintfW(pwszAppVer, 24, L"%d.%d.%d.%d", rgAppVer[0], rgAppVer[1], rgAppVer[2], rgAppVer[3]);
  617. StringCchPrintfW(pwszModVer, 24, L"%d.%d.%d.%d", rgModVer[0], rgModVer[1], rgModVer[2], rgModVer[3]);
  618. }
  619. ErrorTrace(1, "AppName=%ls", pwszApp);
  620. ErrorTrace(1, "AppVer=%ls", pwszAppVer);
  621. ErrorTrace(1, "ModName=%ls", pwszMod);
  622. ErrorTrace(1, "ModVer=%ls", pwszModVer);
  623. // determine how big of a buffer we need & alloc it
  624. #ifdef _WIN64
  625. if (f64Bit)
  626. cbNeeded = c_cbFaultBlob64 + 3 * (wcslen(pwszMod) + wcslen(pwszApp) + wcslen(pwszModVer) + wcslen(pwszAppVer)) * sizeof(WCHAR);
  627. else
  628. #endif
  629. cbNeeded = c_cbFaultBlob32 + 3 * (wcslen(pwszMod) + wcslen(pwszApp) + wcslen(pwszModVer) + wcslen(pwszAppVer)) * sizeof(WCHAR);
  630. pbBuf = (BYTE *)MyAlloc(cbNeeded);
  631. VALIDATEEXPR(hr, (pbBuf == NULL), E_OUTOFMEMORY);
  632. if (FAILED(hr))
  633. goto done;
  634. // write out the actual strings
  635. #ifdef _WIN64
  636. if (f64Bit)
  637. {
  638. ULONG cchLeft = cbNeeded/sizeof(WCHAR);
  639. wszStage1 = (WCHAR *)pbBuf;
  640. hr = StringCchPrintfW(wszStage1, cchLeft, c_wszManFS164,
  641. pwszApp, pwszAppVer,
  642. pwszMod, pwszModVer,
  643. pvOffset);
  644. cch = wcslen(wszStage1);
  645. cchLeft -=cch +1;
  646. wszStage2 = wszStage1 + cch + 1;
  647. hr = StringCchPrintfW(wszStage2, cchLeft, c_wszManFS264,
  648. pwszApp, pwszAppVer,
  649. pwszMod, pwszModVer,
  650. pvOffset);
  651. cch = wcslen(wszStage2);
  652. cchLeft -=cch +1;
  653. wszCorpPath = wszStage2 + cch + 1;
  654. hr = StringCchPrintfW(wszCorpPath, cchLeft, c_wszManFCP64,
  655. pwszApp, pwszAppVer,
  656. pwszMod, pwszModVer,
  657. pvOffset);
  658. cch = wcslen(wszCorpPath);
  659. }
  660. else
  661. #endif
  662. {
  663. ULONG cchLeft = cbNeeded/sizeof(WCHAR);
  664. wszStage1 = (WCHAR *)pbBuf;
  665. hr = StringCchPrintfW(wszStage1, cchLeft, c_wszManFS132,
  666. pwszApp, pwszAppVer,
  667. pwszMod, pwszModVer,
  668. (LPVOID)pvOffset);
  669. cch = wcslen(wszStage1);
  670. cchLeft -=cch +1;
  671. wszStage2 = wszStage1 + cch + 1;
  672. hr = StringCchPrintfW(wszStage2, cchLeft, c_wszManFS232,
  673. pwszApp, pwszAppVer,
  674. pwszMod, pwszModVer,
  675. (LPVOID)pvOffset);
  676. cch = wcslen(wszStage2);
  677. cchLeft -=cch +1;
  678. wszCorpPath = wszStage2 + cch + 1;
  679. hr = StringCchPrintfW(wszCorpPath, cchLeft, c_wszManFCP32,
  680. pwszApp, pwszAppVer,
  681. pwszMod, pwszModVer,
  682. (LPVOID)pvOffset);
  683. cch = wcslen(wszCorpPath);
  684. }
  685. // need to convert all '.'s to '_'s cuz URLs don't like dots.
  686. for (pwsz = wszStage1; *pwsz != L'\0'; pwsz++)
  687. {
  688. if (*pwsz == L'.')
  689. *pwsz = L'_';
  690. }
  691. // ok, on the end of the stage 1 URL is a .htm, and we really don't want to
  692. // convert that '.' to a '_', so back up and reconvert it back to a '.'
  693. pwsz -= 4;
  694. if (*pwsz == L'_')
  695. *pwsz = L'.';
  696. *ppwszS1 = wszStage1;
  697. *ppwszS2 = wszStage2;
  698. *ppwszCP = wszCorpPath;
  699. *ppb = pbBuf;
  700. pbBuf = NULL;
  701. done:
  702. if (pbBuf != NULL)
  703. MyFree(pbBuf);
  704. return hr;
  705. }
  706. // **************************************************************************
  707. HRESULT GetExePath(HANDLE hProc, LPWSTR wszPath, DWORD cchPath)
  708. {
  709. USE_TRACING("GetExePath");
  710. pfn_GETMODULEFILENAMEEXW pfn;
  711. HRESULT hr = NOERROR;
  712. HMODULE hmod = NULL;
  713. DWORD dw;
  714. VALIDATEPARM(hr, (wszPath == NULL || hProc == NULL || cchPath < MAX_PATH));
  715. if (FAILED(hr))
  716. goto done;
  717. hmod = MySafeLoadLibrary(L"psapi.dll");
  718. TESTBOOL(hr, (hmod != NULL));
  719. if (FAILED(hr))
  720. goto done;
  721. pfn = (pfn_GETMODULEFILENAMEEXW)GetProcAddress(hmod, "GetModuleFileNameExW");
  722. TESTBOOL(hr, (pfn != NULL));
  723. if (FAILED(hr))
  724. goto done;
  725. dw = (*pfn)(hProc, NULL, wszPath, cchPath);
  726. if (!dw)
  727. goto done;
  728. wszPath[cchPath-1] = 0;
  729. GetLongPathNameW(wszPath, wszPath, cchPath);
  730. done:
  731. dw = GetLastError();
  732. if (hmod != NULL)
  733. FreeLibrary(hmod);
  734. SetLastError(dw);
  735. return hr;
  736. }
  737. // ***************************************************************************
  738. DWORD GetAppCompatFlag(LPCWSTR wszPath, LPCWSTR wszSysDir, LPWSTR wszBuffer, DWORD BufferChCount)
  739. {
  740. LPWSTR pwszFile, wszSysDirLocal = NULL, pwszDir = NULL;
  741. DWORD dwOpt = (DWORD)-1;
  742. DWORD cchPath, cch;
  743. UINT uiDrive;
  744. if (wszPath == NULL || wszBuffer == NULL || wszSysDir == NULL)
  745. goto done;
  746. // can't be a valid path if it's less than 3 characters long
  747. cchPath = wcslen(wszPath);
  748. if (cchPath < 3)
  749. goto done;
  750. // do we have a UNC path?
  751. if (wszPath[0] == L'\\' && wszPath[1] == L'\\')
  752. {
  753. dwOpt = GRABMI_FILTER_THISFILEONLY;
  754. goto done;
  755. }
  756. // ok, maybe a remote mapped path or system32?
  757. StringCchCopyW(wszBuffer, BufferChCount, wszPath);
  758. for(pwszFile = wszBuffer + cchPath;
  759. *pwszFile != L'\\' && pwszFile > wszBuffer;
  760. pwszFile--);
  761. if (*pwszFile == L'\\')
  762. *pwszFile = L'\0';
  763. else
  764. goto done;
  765. cch = wcslen(wszSysDir) + 1;
  766. __try { wszSysDirLocal = (LPWSTR)_alloca(cch * sizeof(WCHAR)); }
  767. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  768. {
  769. wszSysDirLocal = NULL;
  770. }
  771. if (wszSysDirLocal == NULL)
  772. goto done;
  773. // see if it's in system32 or in any parent folder of it.
  774. StringCchCopyW(wszSysDirLocal, cch, wszSysDir);
  775. pwszDir = wszSysDirLocal + cch;
  776. do
  777. {
  778. if (_wcsicmp(wszBuffer, wszSysDirLocal) == 0)
  779. {
  780. dwOpt = GRABMI_FILTER_SYSTEM;
  781. goto done;
  782. }
  783. for(;
  784. *pwszDir != L'\\' && pwszDir > wszSysDirLocal;
  785. pwszDir--);
  786. if (*pwszDir == L'\\')
  787. *pwszDir = L'\0';
  788. }
  789. while (pwszDir > wszSysDirLocal);
  790. // is the file sitting in the root of a drive?
  791. if (pwszFile <= &wszBuffer[3])
  792. {
  793. dwOpt = GRABMI_FILTER_THISFILEONLY;
  794. goto done;
  795. }
  796. // well, if we've gotten this far, then the path is in the form of
  797. // X:\<something>, so cut off the <something> and find out if we're on
  798. // a mapped drive or not
  799. *pwszFile = L'\\';
  800. wszBuffer[3] = L'\0';
  801. switch(GetDriveTypeW(wszBuffer))
  802. {
  803. case DRIVE_UNKNOWN:
  804. case DRIVE_NO_ROOT_DIR:
  805. goto done;
  806. case DRIVE_REMOTE:
  807. dwOpt = GRABMI_FILTER_THISFILEONLY;
  808. goto done;
  809. }
  810. dwOpt = GRABMI_FILTER_PRIVACY;
  811. done:
  812. return dwOpt;
  813. }
  814. // ***************************************************************************
  815. typedef BOOL (APIENTRY *pfn_SDBGRABMATCHINGINFOW)(LPCWSTR, DWORD, LPCWSTR);
  816. BOOL GetAppCompatData(LPCWSTR wszAppPath, LPCWSTR wszModPath, LPCWSTR wszFile)
  817. {
  818. pfn_SDBGRABMATCHINGINFOW pfn = NULL;
  819. HMODULE hmod = NULL;
  820. LPWSTR pwszPath = NULL, pwszFile = NULL;
  821. WCHAR *pwsz;
  822. DWORD cchSysDir, cchNeed, cchApp = 0, cchMod = 0, cchPath;
  823. DWORD dwModOpt = (DWORD)-1, dwAppOpt = (DWORD)-1;
  824. DWORD dwOpt;
  825. BOOL fRet = FALSE;
  826. HRESULT hr;
  827. USE_TRACING("GetAppCompatData");
  828. VALIDATEPARM(hr, (wszAppPath == NULL || wszFile == NULL ||
  829. wszAppPath[0] == L'\0' || wszFile[0] == L'\0'));
  830. if (FAILED(hr))
  831. {
  832. SetLastError(ERROR_INVALID_PARAMETER);
  833. goto done;
  834. }
  835. // load the apphelp dll.
  836. cchNeed = GetSystemDirectoryW(NULL, 0);
  837. if (cchNeed == 0)
  838. goto done;
  839. if (sizeofSTRW(c_wszAppHelpDll) > sizeofSTRW(c_wszKernel32Dll))
  840. cchNeed += (sizeofSTRW(c_wszAppHelpDll) + 8);
  841. else
  842. cchNeed += (sizeofSTRW(c_wszKernel32Dll) + 8);
  843. __try { pwszPath = (WCHAR *)_alloca(cchNeed * sizeof(WCHAR)); }
  844. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  845. {
  846. pwszPath = NULL;
  847. }
  848. if (pwszPath == NULL)
  849. {
  850. SetLastError(ERROR_OUTOFMEMORY);
  851. goto done;
  852. }
  853. cchPath = cchNeed;
  854. cchSysDir = GetSystemDirectoryW(pwszPath, cchNeed);
  855. if (cchSysDir == 0)
  856. goto done;
  857. cchApp = wcslen(wszAppPath);
  858. if (wszModPath != NULL)
  859. cchMod = wcslen(wszModPath);
  860. cchNeed = MyMax(cchApp, cchMod) + 8;
  861. __try { pwszFile = (WCHAR *)_alloca(cchNeed * sizeof(WCHAR)); }
  862. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  863. {
  864. pwszFile = NULL;
  865. }
  866. if (pwszFile == NULL)
  867. {
  868. SetLastError(ERROR_OUTOFMEMORY);
  869. goto done;
  870. }
  871. // find out the app & module option flag
  872. dwAppOpt = GetAppCompatFlag(wszAppPath, pwszPath, pwszFile, cchNeed);
  873. if (wszModPath != NULL && wszModPath[0] != L'\0' &&
  874. _wcsicmp(wszModPath, wszAppPath) != 0)
  875. {
  876. #if 0
  877. dwModOpt = GetAppCompatFlag(wszModPath, pwszPath, pwszFile, cchNeed);
  878. // no need to grab system data twice. If we're already grabbing
  879. // it for the app, don't grab it for the module. Yes, we may end
  880. // up grabbing the mod twice if it happens to be one of the system
  881. // modules, but that's ok.
  882. if (dwModOpt == GRABMI_FILTER_SYSTEM &&
  883. dwAppOpt == GRABMI_FILTER_SYSTEM)
  884. dwModOpt = GRABMI_FILTER_THISFILEONLY;
  885. #else
  886. dwModOpt = GRABMI_FILTER_THISFILEONLY;
  887. #endif
  888. }
  889. // load the libarary
  890. StringCchCopyW(&pwszPath[cchSysDir], cchPath - cchSysDir, L"\\apphelp.dll");
  891. hmod = MySafeLoadLibrary(pwszPath);
  892. if (hmod == NULL)
  893. goto done;
  894. // if we don't find the function, then just bail...
  895. pfn = (pfn_SDBGRABMATCHINGINFOW)GetProcAddress(hmod, "SdbGrabMatchingInfo");
  896. if (pfn == NULL)
  897. goto done;
  898. // call the function to get the app data
  899. if (dwAppOpt != (DWORD)-1)
  900. {
  901. dwOpt = dwAppOpt;
  902. if (dwModOpt != (DWORD)-1 ||
  903. (dwModOpt != GRABMI_FILTER_SYSTEM &&
  904. dwAppOpt != GRABMI_FILTER_SYSTEM))
  905. dwOpt |= GRABMI_FILTER_NOCLOSE;
  906. DBG_MSG("Grab app data");
  907. __try { fRet = (*pfn)(wszAppPath, dwOpt, wszFile); }
  908. __except(EXCEPTION_EXECUTE_HANDLER) { fRet = FALSE; DBG_MSG("GrabAppData crashed");}
  909. if (fRet == FALSE)
  910. goto done;
  911. }
  912. // call the function to get the mod data
  913. if (dwModOpt != (DWORD)-1)
  914. {
  915. dwOpt = dwModOpt;
  916. if (dwAppOpt != (DWORD)-1)
  917. dwOpt |= GRABMI_FILTER_APPEND;
  918. if (dwAppOpt != GRABMI_FILTER_SYSTEM &&
  919. dwModOpt != GRABMI_FILTER_SYSTEM)
  920. dwOpt |= GRABMI_FILTER_NOCLOSE;
  921. DBG_MSG("Grab module data");
  922. __try { fRet = (*pfn)(wszModPath, dwOpt, wszFile); }
  923. __except(EXCEPTION_EXECUTE_HANDLER) { fRet = FALSE; DBG_MSG("GrabModData crashed");}
  924. if (fRet == FALSE)
  925. goto done;
  926. }
  927. // call the function to get the data for kernel32
  928. if (dwModOpt != GRABMI_FILTER_SYSTEM &&
  929. dwAppOpt != GRABMI_FILTER_SYSTEM)
  930. {
  931. StringCchCopyW(&pwszPath[cchSysDir], cchPath - cchSysDir, L"\\kernel32.dll");
  932. dwOpt = GRABMI_FILTER_THISFILEONLY;
  933. if (dwModOpt != (DWORD)-1 || dwAppOpt != (DWORD)-1)
  934. dwOpt |= GRABMI_FILTER_APPEND;
  935. DBG_MSG("Grab kernel data");
  936. __try { fRet = (*pfn)(pwszPath, dwOpt, wszFile); }
  937. __except(EXCEPTION_EXECUTE_HANDLER) { fRet = FALSE; DBG_MSG("GrabKrnlData crashed");}
  938. if (fRet == FALSE)
  939. goto done;
  940. }
  941. done:
  942. if (fRet == FALSE)
  943. DeleteFileW(wszFile);
  944. if (hmod != NULL)
  945. {
  946. __try { FreeLibrary(hmod); }
  947. __except(EXCEPTION_EXECUTE_HANDLER) { }
  948. }
  949. return fRet;
  950. }
  951. //////////////////////////////////////////////////////////////////////////////
  952. // ThreadStuff
  953. // ***************************************************************************
  954. BOOL FreezeAllThreads(DWORD dwpid, DWORD dwtidFilter, SSuspendThreads *pst)
  955. {
  956. THREADENTRY32 te;
  957. HANDLE hTokenImp = NULL;
  958. HANDLE hsnap = (HANDLE)-1, hth = NULL;
  959. HANDLE *rgh = NULL;
  960. DWORD dwtid = GetCurrentThreadId();
  961. DWORD cThreads = 0, cSlots = 0, dw;
  962. BOOL fContinue = FALSE, fRet = FALSE;
  963. if (pst == NULL)
  964. {
  965. SetLastError(ERROR_INVALID_PARAMETER);
  966. goto done;
  967. }
  968. pst->rghThreads = NULL;
  969. pst->cThreads = 0;
  970. // if we have an impersonation token on this thread, revert it back to
  971. // full access cuz otherwise we could fail in the OpenThread API below.
  972. // Even if we fail, we'll still try all the rest of the stuff below.
  973. if (OpenThreadToken(GetCurrentThread(), TOKEN_READ | TOKEN_IMPERSONATE,
  974. TRUE, &hTokenImp))
  975. RevertToSelf();
  976. hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, dwpid);
  977. if (hsnap == (HANDLE)-1)
  978. goto done;
  979. ZeroMemory(&te, sizeof(te));
  980. te.dwSize = sizeof(te);
  981. fContinue = Thread32First(hsnap, &te);
  982. while(fContinue)
  983. {
  984. // only want to freeze threads in my process (not including the
  985. // currently executing one, of course, since that would bring
  986. // everything to a grinding halt.)
  987. if (te.th32OwnerProcessID == dwpid && te.th32ThreadID != dwtidFilter)
  988. {
  989. hth = OpenThread(THREAD_SUSPEND_RESUME, FALSE, te.th32ThreadID);
  990. if (hth != NULL)
  991. {
  992. if (cSlots == cThreads)
  993. {
  994. HANDLE *rghNew = NULL;
  995. DWORD cNew = (cSlots == 0) ? 8 : cSlots * 2;
  996. rghNew = (HANDLE *)MyAlloc(cNew * sizeof(HANDLE));
  997. if (rghNew == NULL)
  998. {
  999. SetLastError(ERROR_OUTOFMEMORY);
  1000. CloseHandle(hth);
  1001. goto done;
  1002. }
  1003. if (rgh != NULL)
  1004. CopyMemory(rghNew, rgh, cSlots * sizeof(HANDLE));
  1005. MyFree(rgh);
  1006. rgh = rghNew;
  1007. cSlots = cNew;
  1008. }
  1009. // if the suspend fails, then just don't add it to the
  1010. // list...
  1011. if (SuspendThread(hth) == (DWORD)-1)
  1012. CloseHandle(hth);
  1013. else
  1014. rgh[cThreads++] = hth;
  1015. hth = NULL;
  1016. }
  1017. }
  1018. fContinue = Thread32Next(hsnap, &te);
  1019. }
  1020. pst->rghThreads = rgh;
  1021. pst->cThreads = cThreads;
  1022. SetLastError(0);
  1023. fRet = TRUE;
  1024. done:
  1025. dw = GetLastError();
  1026. if (hTokenImp != NULL)
  1027. {
  1028. if (SetThreadToken(NULL, hTokenImp) == FALSE)
  1029. dw = GetLastError();
  1030. CloseHandle(hTokenImp);
  1031. }
  1032. if (fRet == FALSE && rgh != NULL)
  1033. {
  1034. DWORD i;
  1035. for (i = 0; i < cThreads; i++)
  1036. {
  1037. if (rgh[i] != NULL)
  1038. {
  1039. ResumeThread(rgh[i]);
  1040. CloseHandle(rgh[i]);
  1041. }
  1042. }
  1043. MyFree(rgh);
  1044. }
  1045. // MSDN says to use CloseToolhelp32Snapshot() to close the snapshot.
  1046. // the tlhelp32.h header file says to use CloseHandle & doens't provide
  1047. // a CloseToolhelp32Snapshot() function. Hence, I'm using CloseHandle
  1048. // for now.
  1049. if (hsnap != (HANDLE)-1)
  1050. CloseHandle(hsnap);
  1051. SetLastError(dw);
  1052. return fRet;
  1053. }
  1054. // ***************************************************************************
  1055. BOOL ThawAllThreads(SSuspendThreads *pst)
  1056. {
  1057. DWORD i;
  1058. if (pst == NULL)
  1059. {
  1060. SetLastError(ERROR_INVALID_PARAMETER);
  1061. return FALSE;
  1062. }
  1063. if (pst->rghThreads == NULL)
  1064. return TRUE;
  1065. for (i = 0; i < pst->cThreads; i++)
  1066. {
  1067. if (pst->rghThreads[i] != NULL)
  1068. {
  1069. ResumeThread(pst->rghThreads[i]);
  1070. CloseHandle(pst->rghThreads[i]);
  1071. }
  1072. }
  1073. MyFree(pst->rghThreads);
  1074. pst->rghThreads = NULL;
  1075. pst->cThreads = 0;
  1076. SetLastError(0);
  1077. return TRUE;
  1078. }
  1079. //////////////////////////////////////////////////////////////////////////////
  1080. // Minidump
  1081. // ***************************************************************************
  1082. BOOL WINAPI MDCallback(void *pvCallbackParam,
  1083. CONST PMINIDUMP_CALLBACK_INPUT pCallbackInput,
  1084. PMINIDUMP_CALLBACK_OUTPUT pCallbackOutput)
  1085. {
  1086. //USE_TRACING("MDCallback");
  1087. SMDumpOptions *psmdo = (SMDumpOptions *)pvCallbackParam;
  1088. if (pCallbackInput == NULL || pCallbackOutput == NULL || psmdo == NULL)
  1089. return TRUE;
  1090. // what did we get called back for?
  1091. switch(pCallbackInput->CallbackType)
  1092. {
  1093. case ModuleCallback:
  1094. pCallbackOutput->ModuleWriteFlags = psmdo->ulMod;
  1095. // only need to do this extra work if we're getting a minidump
  1096. if ((psmdo->dfOptions & dfCollectSig) != 0)
  1097. {
  1098. MINIDUMP_MODULE_CALLBACK *pmmc = &pCallbackInput->Module;
  1099. LPWSTR pwsz = NULL;
  1100. // err, if we don't have a path, can't do squat, so skip it
  1101. if (pmmc->FullPath != NULL && pmmc->FullPath[0] != L'\0')
  1102. {
  1103. // is it the app?
  1104. if (_wcsicmp(pmmc->FullPath, psmdo->wszAppFullPath) == 0)
  1105. {
  1106. pCallbackOutput->ModuleWriteFlags |= ModuleWriteDataSeg;
  1107. psmdo->rgAppVer[0] = HIWORD(pmmc->VersionInfo.dwFileVersionMS);
  1108. psmdo->rgAppVer[1] = LOWORD(pmmc->VersionInfo.dwFileVersionMS);
  1109. psmdo->rgAppVer[2] = HIWORD(pmmc->VersionInfo.dwFileVersionLS);
  1110. psmdo->rgAppVer[3] = LOWORD(pmmc->VersionInfo.dwFileVersionLS);
  1111. // get a pointer to the end of the modulename string
  1112. for(pwsz = pmmc->FullPath + wcslen(pmmc->FullPath);
  1113. *pwsz != L'\\' && pwsz > pmmc->FullPath;
  1114. pwsz--);
  1115. if (*pwsz == L'\\')
  1116. pwsz++;
  1117. // get the app name, if we can make it fit
  1118. if (wcslen(pwsz) < sizeofSTRW(psmdo->wszApp))
  1119. StringCbCopyW(psmdo->wszApp, sizeof(psmdo->wszApp), pwsz);
  1120. else
  1121. StringCbCopyW(psmdo->wszApp, sizeof(psmdo->wszApp), L"unknown");
  1122. }
  1123. }
  1124. // is it the module?
  1125. if (psmdo->pvFaultAddr >= pmmc->BaseOfImage &&
  1126. psmdo->pvFaultAddr <= pmmc->BaseOfImage + pmmc->SizeOfImage)
  1127. {
  1128. pCallbackOutput->ModuleWriteFlags |= ModuleWriteDataSeg;
  1129. psmdo->rgModVer[0] = HIWORD(pmmc->VersionInfo.dwFileVersionMS);
  1130. psmdo->rgModVer[1] = LOWORD(pmmc->VersionInfo.dwFileVersionMS);
  1131. psmdo->rgModVer[2] = HIWORD(pmmc->VersionInfo.dwFileVersionLS);
  1132. psmdo->rgModVer[3] = LOWORD(pmmc->VersionInfo.dwFileVersionLS);
  1133. if (pwsz == NULL)
  1134. {
  1135. // get a pointer to the end of the modulename string
  1136. for(pwsz = pmmc->FullPath + wcslen(pmmc->FullPath);
  1137. *pwsz != L'\\' && pwsz > pmmc->FullPath;
  1138. pwsz--);
  1139. if (*pwsz == L'\\')
  1140. pwsz++;
  1141. }
  1142. if (pwsz != NULL && wcslen(pwsz) < sizeofSTRW(psmdo->wszMod))
  1143. {
  1144. // get the full path if we can make it fit
  1145. if (wcslen(pmmc->FullPath) < sizeofSTRW(psmdo->wszModFullPath))
  1146. StringCbCopyW(psmdo->wszModFullPath, sizeof(psmdo->wszModFullPath),
  1147. pmmc->FullPath);
  1148. else
  1149. psmdo->wszModFullPath[0] = L'\0';
  1150. // get the module name, if we can make it fit
  1151. if (wcslen(pwsz) < sizeofSTRW(psmdo->wszMod))
  1152. StringCbCopyW(psmdo->wszMod, sizeof(psmdo->wszMod), pwsz);
  1153. else
  1154. StringCbCopyW(psmdo->wszMod, sizeof(psmdo->wszMod), L"unknown");
  1155. psmdo->pvOffset = psmdo->pvFaultAddr - pmmc->BaseOfImage;
  1156. }
  1157. }
  1158. }
  1159. break;
  1160. case ThreadCallback:
  1161. // are we collecting info for a single thread only?
  1162. if ((psmdo->dfOptions & dfFilterThread) != 0)
  1163. {
  1164. if (psmdo->dwThreadID == pCallbackInput->Thread.ThreadId)
  1165. pCallbackOutput->ThreadWriteFlags = psmdo->ulThread;
  1166. else
  1167. pCallbackOutput->ThreadWriteFlags = 0;
  1168. }
  1169. // or are we collecting special info for a single thread?
  1170. else if ((psmdo->dfOptions & dfFilterThreadEx) != 0)
  1171. {
  1172. if (psmdo->dwThreadID == pCallbackInput->Thread.ThreadId)
  1173. pCallbackOutput->ThreadWriteFlags = psmdo->ulThreadEx;
  1174. else
  1175. pCallbackOutput->ThreadWriteFlags = psmdo->ulThread;
  1176. }
  1177. // or maybe we're just getting a generic ol' minidump...
  1178. else
  1179. {
  1180. pCallbackOutput->ThreadWriteFlags = psmdo->ulThread;
  1181. }
  1182. break;
  1183. default:
  1184. break;
  1185. }
  1186. return TRUE;
  1187. }
  1188. // **************************************************************************
  1189. BOOL InternalGenerateMinidumpEx(HANDLE hProc, DWORD dwpid, HANDLE hFile,
  1190. SMDumpOptions *psmdo, LPCWSTR wszPath, BOOL f64bit)
  1191. {
  1192. #ifdef _WIN64
  1193. USE_TRACING("InternalGenerateMinidumpEx64(handle)");
  1194. #else
  1195. USE_TRACING("InternalGenerateMinidumpEx(handle)");
  1196. #endif
  1197. SMDumpOptions smdo;
  1198. HRESULT hr = NULL;
  1199. LPWSTR wszMod = NULL;
  1200. DWORD cch, cchNeed;
  1201. BOOL fRet = FALSE;
  1202. VALIDATEPARM(hr, (hProc == NULL || hFile == NULL ||
  1203. hFile == INVALID_HANDLE_VALUE));
  1204. if (FAILED(hr))
  1205. {
  1206. SetLastError(ERROR_INVALID_PARAMETER);
  1207. return FALSE;
  1208. }
  1209. #ifdef _WIN64
  1210. DBG_MSG(f64bit ? "64 bit fault" : "32 bit fault");
  1211. if (!f64bit)
  1212. {
  1213. cchNeed = GetSystemWow64DirectoryW(NULL, 0);
  1214. }
  1215. else
  1216. #endif
  1217. {
  1218. cchNeed = GetSystemDirectoryW(NULL, 0);
  1219. }
  1220. TESTBOOL(hr, cchNeed != 0);
  1221. if (FAILED(hr))
  1222. return FALSE;
  1223. cchNeed += (sizeofSTRW(c_wszDbgHelpDll) + 8);
  1224. __try { wszMod = (LPWSTR)_alloca(cchNeed * sizeof(WCHAR)); }
  1225. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  1226. {
  1227. wszMod = NULL;
  1228. }
  1229. TESTBOOL(hr, wszMod != NULL);
  1230. if (FAILED(hr))
  1231. {
  1232. SetLastError(ERROR_OUTOFMEMORY);
  1233. goto done;
  1234. }
  1235. #ifdef _WIN64
  1236. if (!f64bit)
  1237. {
  1238. cch = GetSystemWow64DirectoryW(wszMod, cchNeed);
  1239. }
  1240. else
  1241. #endif
  1242. {
  1243. cch = GetSystemDirectoryW(wszMod, cchNeed);
  1244. }
  1245. TESTBOOL(hr, cch != 0);
  1246. if (FAILED(hr))
  1247. return FALSE;
  1248. if (*(wszMod + cch - 1) == L'\\')
  1249. *(wszMod + cch - 1) = L'\0';
  1250. // default is to write everything for everything
  1251. if (psmdo == NULL)
  1252. {
  1253. ZeroMemory(&smdo, sizeof(smdo));
  1254. smdo.ulThread = c_ulThreadWriteDefault;
  1255. smdo.ulMod = c_ulModuleWriteDefault;
  1256. psmdo = &smdo;
  1257. }
  1258. // if we're in the same process, we can't call the minidump APIs directly
  1259. // cuz we'll hang the process.
  1260. #ifdef _WIN64
  1261. if (!f64bit || dwpid == GetCurrentProcessId())
  1262. #else
  1263. if (dwpid == GetCurrentProcessId())
  1264. #endif
  1265. {
  1266. PROCESS_INFORMATION pi;
  1267. STARTUPINFOW si;
  1268. LPWSTR wszCmdLine = NULL, wszExeFile = NULL;
  1269. HANDLE hmem = NULL;
  1270. LPVOID pvmem = NULL;
  1271. DWORD dw;
  1272. DWORD cchShareMemName;
  1273. LPWSTR wszShareMemName = NULL, wszFileName = NULL;
  1274. SECURITY_ATTRIBUTES sa;
  1275. SECURITY_DESCRIPTOR sd;
  1276. VALIDATEPARM(hr, (wszPath == NULL));
  1277. if (FAILED(hr))
  1278. {
  1279. SetLastError(ERROR_INVALID_PARAMETER);
  1280. goto done;
  1281. }
  1282. DBG_MSG("Calling dumprep- same process as us");
  1283. wszFileName = wcsrchr(wszPath, L'\\');
  1284. if (!wszFileName)
  1285. {
  1286. wszFileName = (LPWSTR) wszPath;
  1287. } else
  1288. {
  1289. wszFileName++;
  1290. }
  1291. cchShareMemName = cchNeed = wcslen(wszFileName) + 2;
  1292. __try { wszShareMemName = (LPWSTR)_alloca(cchNeed * sizeof(WCHAR)); }
  1293. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  1294. {
  1295. wszShareMemName = NULL;
  1296. }
  1297. TESTBOOL(hr, wszShareMemName != NULL);
  1298. if (FAILED(hr))
  1299. {
  1300. SetLastError(ERROR_OUTOFMEMORY);
  1301. goto doneProcSpawn;
  1302. }
  1303. StringCchCopyW(wszShareMemName, cchNeed, wszFileName);
  1304. cchNeed = sizeofSTRW(c_wszDRExeMD) + cch + 1;
  1305. __try { wszExeFile = (LPWSTR)_alloca(cchNeed * sizeof(WCHAR)); }
  1306. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  1307. {
  1308. wszExeFile = NULL;
  1309. }
  1310. TESTBOOL(hr, wszExeFile != NULL);
  1311. if (FAILED(hr))
  1312. {
  1313. SetLastError(ERROR_OUTOFMEMORY);
  1314. goto doneProcSpawn;
  1315. }
  1316. StringCchPrintfW(wszExeFile, cchNeed, c_wszDRExeMD, wszMod);
  1317. // 32 is the max size of a 64 bit decimal # & a 32 bit decimal #
  1318. cchNeed = sizeofSTRW(c_wszDRCmdLineMD) + cch + wcslen(wszPath) + 32 + cchShareMemName;
  1319. __try { wszCmdLine = (LPWSTR)_alloca(cchNeed * sizeof(WCHAR)); }
  1320. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  1321. {
  1322. wszCmdLine = NULL;
  1323. }
  1324. TESTBOOL(hr, wszCmdLine != NULL);
  1325. if (FAILED(hr))
  1326. {
  1327. SetLastError(ERROR_OUTOFMEMORY);
  1328. goto doneProcSpawn;
  1329. }
  1330. #define ER_ACCESS_ALL GENERIC_ALL | DELETE | READ_CONTROL | SYNCHRONIZE | SPECIFIC_RIGHTS_ALL
  1331. AllocSD(&sd, ER_ACCESS_ALL, ER_ACCESS_ALL, 0);
  1332. ZeroMemory(&sa, sizeof(sa));
  1333. sa.nLength = sizeof(sa);
  1334. sa.lpSecurityDescriptor = &sd;
  1335. sa.bInheritHandle = TRUE;
  1336. hmem = CreateFileMappingW(INVALID_HANDLE_VALUE, &sa, PAGE_READWRITE,
  1337. 0, sizeof(smdo), wszShareMemName);
  1338. if (sa.lpSecurityDescriptor != NULL)
  1339. FreeSD((SECURITY_DESCRIPTOR *)sa.lpSecurityDescriptor);
  1340. TESTBOOL(hr, hmem != NULL);
  1341. if (FAILED(hr))
  1342. goto doneProcSpawn;
  1343. pvmem = MapViewOfFile(hmem, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 0);
  1344. TESTBOOL(hr, pvmem != NULL);
  1345. if (FAILED(hr))
  1346. goto doneProcSpawn;
  1347. // copy that info into the shared memory
  1348. CopyMemory(pvmem, psmdo, sizeof(smdo));
  1349. ZeroMemory(&pi, sizeof(pi));
  1350. ZeroMemory(&si, sizeof(si));
  1351. si.cb = sizeof(si);
  1352. StringCchPrintfW(wszCmdLine, cchNeed, c_wszDRCmdLineMD, dwpid, wszPath, wszShareMemName);
  1353. if (CreateProcessW(wszExeFile, wszCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
  1354. {
  1355. if (pi.hThread != NULL)
  1356. CloseHandle(pi.hThread);
  1357. if (!pi.hProcess)
  1358. {
  1359. DWORD dwAwShit = GetLastError();
  1360. ErrorTrace(0, "Spawned process died: \'%S\', err=0x%x", wszCmdLine, dwAwShit);
  1361. SetLastError(dwAwShit);
  1362. }
  1363. else
  1364. {
  1365. DWORD dwAwShit = GetLastError();
  1366. ErrorTrace(0, "Spawned process for dumprep: \'%S\', err=0x%x", wszCmdLine, dwAwShit);
  1367. SetLastError(dwAwShit);
  1368. }
  1369. // wait 2m for the dump to be complete
  1370. if (pi.hProcess == NULL)
  1371. DBG_MSG("bad hProc");
  1372. else
  1373. {
  1374. DWORD dwtmp = WaitForSingleObject(pi.hProcess, 120000);
  1375. if (dwtmp == WAIT_OBJECT_0)
  1376. fRet = TRUE;
  1377. else
  1378. {
  1379. ErrorTrace(1, "Wait failed! result=0x%x, hProc=0x%x, err=0x%x", dwtmp, pi.hProcess, GetLastError());
  1380. fRet = FALSE;
  1381. }
  1382. }
  1383. }
  1384. else
  1385. {
  1386. DWORD dwAwShit = GetLastError();
  1387. ErrorTrace(0, "Spawn failed: \'%S\', err=0x%x", wszCmdLine, dwAwShit);
  1388. SetLastError(dwAwShit);
  1389. }
  1390. if (fRet)
  1391. {
  1392. // copy back the results from pvmem -> psmdo
  1393. CopyMemory(psmdo, pvmem, sizeof(smdo));
  1394. DBG_MSG("Dumprep worked right!");
  1395. }
  1396. else
  1397. {
  1398. DWORD dwAwShit = GetLastError();
  1399. ErrorTrace(0, "dumprep failed: err=0x%x", dwAwShit);
  1400. SetLastError(dwAwShit);
  1401. }
  1402. doneProcSpawn:
  1403. dw = GetLastError();
  1404. if (pvmem != NULL)
  1405. UnmapViewOfFile(pvmem);
  1406. if (hmem != NULL)
  1407. CloseHandle(hmem);
  1408. if (pi.hProcess != NULL)
  1409. CloseHandle(pi.hProcess);
  1410. SetLastError(dw);
  1411. }
  1412. else
  1413. {
  1414. MINIDUMP_EXCEPTION_INFORMATION mei, *pmei = NULL;
  1415. MINIDUMP_CALLBACK_INFORMATION mci;
  1416. DUMPWRITE_FN pfn;
  1417. HMODULE hmod = NULL;
  1418. ZeroMemory(&mci, sizeof(mci));
  1419. mci.CallbackRoutine = MDCallback;
  1420. mci.CallbackParam = psmdo;
  1421. // if we got exception paramters in the blob, use 'em...
  1422. if (psmdo->pEP != NULL)
  1423. {
  1424. ZeroMemory(&mei, sizeof(mei));
  1425. mei.ExceptionPointers = (PEXCEPTION_POINTERS)(DWORD_PTR)psmdo->pEP;
  1426. mei.ClientPointers = psmdo->fEPClient;
  1427. mei.ThreadId = psmdo->dwThreadID;
  1428. pmei = &mei;
  1429. }
  1430. StringCchCatNW(wszMod, cchNeed, c_wszDbgHelpDll, cchNeed - wcslen(wszMod));
  1431. hmod = MySafeLoadLibrary(wszMod);
  1432. if (hmod != NULL)
  1433. {
  1434. pfn = (DUMPWRITE_FN)GetProcAddress(hmod, "MiniDumpWriteDump");
  1435. if (pfn != NULL)
  1436. {
  1437. MINIDUMP_TYPE MiniDumpType;
  1438. DWORD dwEC;
  1439. if (psmdo->fIncludeHeap)
  1440. {
  1441. MiniDumpType = (MINIDUMP_TYPE) (MiniDumpWithDataSegs |
  1442. MiniDumpWithProcessThreadData |
  1443. MiniDumpWithHandleData |
  1444. MiniDumpWithPrivateReadWriteMemory |
  1445. MiniDumpWithUnloadedModules);
  1446. } else
  1447. {
  1448. MiniDumpType = (MINIDUMP_TYPE) (MiniDumpWithDataSegs |
  1449. MiniDumpWithUnloadedModules);
  1450. }
  1451. fRet = (pfn)(hProc, dwpid, hFile, MiniDumpType,
  1452. pmei, NULL, &mci);
  1453. if (!fRet)
  1454. {
  1455. ErrorTrace(0, "MiniDumpWriteDump failed: err=0x%x", GetLastError());
  1456. fRet = FALSE;
  1457. }
  1458. else
  1459. {
  1460. ErrorTrace(1, "MiniDumpWriteDump OK: fRet=%d, err=0x%x", fRet, GetLastError());
  1461. fRet = TRUE;
  1462. }
  1463. }
  1464. FreeLibrary(hmod);
  1465. }
  1466. }
  1467. done:
  1468. return fRet;
  1469. }
  1470. // **************************************************************************
  1471. BOOL InternalGenerateMinidump(HANDLE hProc, DWORD dwpid, LPCWSTR wszPath,
  1472. SMDumpOptions *psmdo, BOOL f64bit)
  1473. {
  1474. #ifdef _WIN64
  1475. USE_TRACING("InternalGenerateMinidump64(path)");
  1476. #else
  1477. USE_TRACING("InternalGenerateMinidump(path)");
  1478. #endif
  1479. HRESULT hr = NOERROR;
  1480. HANDLE hFile = INVALID_HANDLE_VALUE;
  1481. BOOL fRet = FALSE;
  1482. DWORD dwDummy=0;
  1483. USHORT usCompress = COMPRESSION_FORMAT_DEFAULT;
  1484. VALIDATEPARM(hr, (hProc == NULL || wszPath == NULL));
  1485. if (FAILED(hr))
  1486. {
  1487. SetLastError(ERROR_INVALID_PARAMETER);
  1488. return FALSE;
  1489. }
  1490. // must share this file open, as it could be opened recursively...
  1491. // hFile = CreateFileW(wszPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0,
  1492. // NULL);
  1493. hFile = CreateFileW(wszPath,
  1494. FILE_READ_DATA | FILE_WRITE_DATA,
  1495. FILE_SHARE_READ | FILE_SHARE_WRITE,
  1496. NULL, CREATE_ALWAYS, 0,
  1497. NULL);
  1498. TESTBOOL(hr, (hFile != INVALID_HANDLE_VALUE));
  1499. if (FAILED(hr))
  1500. {
  1501. ErrorTrace(1, "File create choked on %S", wszPath);
  1502. return FALSE;
  1503. }
  1504. // set the file to use NTFS compression- it is ok if this fails.
  1505. if(!DeviceIoControl(hFile, FSCTL_SET_COMPRESSION, &usCompress,
  1506. sizeof(usCompress), NULL, 0, &dwDummy, FALSE))
  1507. {
  1508. ErrorTrace(0, "Compression failed, err=0x%x", GetLastError());
  1509. }
  1510. fRet = InternalGenerateMinidumpEx(hProc, dwpid, hFile, psmdo, wszPath, f64bit);
  1511. // set the file to use NTFS compression- it is ok if this fails.
  1512. if(DeviceIoControl(hFile, FSCTL_GET_COMPRESSION, &usCompress,
  1513. sizeof(usCompress), NULL, 0, &dwDummy, FALSE))
  1514. {
  1515. ErrorTrace(0, "dmpFile(%S) %s compressed", wszPath, usCompress == COMPRESSION_FORMAT_NONE ? "not":"is");
  1516. }
  1517. else
  1518. {
  1519. ErrorTrace(0, "Compression query failed, err=0x%x for file \'%S\'", GetLastError(), wszPath);
  1520. }
  1521. CloseHandle(hFile);
  1522. return fRet;
  1523. }
  1524. // This generates a triage minidump on the given wszPath and then generates a
  1525. // full minidump on wszPath with c_wszHeapDumpSuffix
  1526. BOOL
  1527. InternalGenFullAndTriageMinidumps(HANDLE hProc, DWORD dwpid, LPCWSTR wszPath,
  1528. HANDLE hFile, SMDumpOptions *psmdo, BOOL f64bit)
  1529. {
  1530. #ifdef _WIN64
  1531. USE_TRACING("InternalGenFullAndTriageMinidumps(path)");
  1532. #else
  1533. USE_TRACING("InternalGenFullAndTriageMinidumps(path)");
  1534. #endif
  1535. HRESULT hr = NOERROR;
  1536. BOOL fRet = FALSE;
  1537. LPWSTR wszFullMinidump = NULL;
  1538. DWORD cch;
  1539. SMDumpOptions smdoFullMini;
  1540. VALIDATEPARM(hr, (hProc == NULL || wszPath == NULL));
  1541. if (FAILED(hr))
  1542. {
  1543. SetLastError(ERROR_INVALID_PARAMETER);
  1544. return FALSE;
  1545. }
  1546. if (hFile)
  1547. {
  1548. fRet = InternalGenerateMinidumpEx(hProc, dwpid, hFile, psmdo, wszPath, f64bit);
  1549. } else
  1550. {
  1551. fRet = InternalGenerateMinidump(hProc, dwpid, wszPath, psmdo, f64bit);
  1552. }
  1553. if (!fRet)
  1554. {
  1555. return fRet;
  1556. }
  1557. cch = wcslen(wszPath) + sizeofSTRW(c_wszHeapDumpSuffix);
  1558. __try { wszFullMinidump = (WCHAR *)_alloca(cch * sizeof(WCHAR)); }
  1559. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  1560. {
  1561. wszFullMinidump = NULL;
  1562. }
  1563. if (wszFullMinidump)
  1564. {
  1565. LPWSTR wszFileExt = NULL;
  1566. ZeroMemory(&smdoFullMini, sizeof(SMDumpOptions));
  1567. memcpy(&smdoFullMini, psmdo, sizeof(SMDumpOptions));
  1568. // Build Dump-with-heap path
  1569. StringCchCopyW(wszFullMinidump, cch, wszPath);
  1570. wszFileExt = wszFullMinidump + wcslen(wszFullMinidump) - sizeofSTRW(c_wszDumpSuffix) + 1;
  1571. if (!wcscmp(wszFileExt, c_wszDumpSuffix))
  1572. {
  1573. *wszFileExt = L'\0';
  1574. }
  1575. StringCchCatW(wszFullMinidump, cch, c_wszHeapDumpSuffix);
  1576. smdoFullMini.fIncludeHeap = TRUE;
  1577. fRet = InternalGenerateMinidump(hProc, dwpid, wszFullMinidump, &smdoFullMini, f64bit);
  1578. }
  1579. return fRet;
  1580. }
  1581. BOOL
  1582. CopyFullAndTriageMiniDumps(
  1583. LPWSTR pwszTriageDumpFrom,
  1584. LPWSTR pwszTriageDumpTo
  1585. )
  1586. {
  1587. BOOL fRet;
  1588. LPWSTR wszFullMinidumpFrom = NULL, wszFullMinidumpTo = NULL;
  1589. DWORD cch;
  1590. fRet = CopyFileW(pwszTriageDumpFrom, pwszTriageDumpTo, FALSE);
  1591. if (fRet)
  1592. {
  1593. LPWSTR wszFileExt;
  1594. cch = wcslen(pwszTriageDumpFrom) + sizeofSTRW(c_wszHeapDumpSuffix);
  1595. __try { wszFullMinidumpFrom = (WCHAR *)_alloca(cch * sizeof(WCHAR)); }
  1596. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  1597. {
  1598. wszFullMinidumpFrom = NULL;
  1599. }
  1600. if (wszFullMinidumpFrom)
  1601. {
  1602. StringCchCopyW(wszFullMinidumpFrom, cch, pwszTriageDumpFrom);
  1603. wszFileExt = wszFullMinidumpFrom + wcslen(wszFullMinidumpFrom) -
  1604. sizeofSTRW(c_wszDumpSuffix) + 1;
  1605. if (!wcscmp(wszFileExt, c_wszDumpSuffix))
  1606. {
  1607. *wszFileExt = L'\0';
  1608. }
  1609. StringCchCatW(wszFullMinidumpFrom, cch, c_wszHeapDumpSuffix);
  1610. }
  1611. cch = wcslen(pwszTriageDumpTo) + sizeofSTRW(c_wszHeapDumpSuffix);
  1612. __try { wszFullMinidumpTo = (WCHAR *)_alloca(cch * sizeof(WCHAR)); }
  1613. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  1614. {
  1615. wszFullMinidumpTo = NULL;
  1616. }
  1617. if (wszFullMinidumpTo)
  1618. {
  1619. StringCchCopyW(wszFullMinidumpTo, cch, pwszTriageDumpTo);
  1620. wszFileExt = wszFullMinidumpTo + wcslen(wszFullMinidumpTo) -
  1621. sizeofSTRW(c_wszDumpSuffix) + 1;
  1622. if (!wcscmp(wszFileExt, c_wszDumpSuffix))
  1623. {
  1624. *wszFileExt = L'\0';
  1625. }
  1626. StringCchCatW(wszFullMinidumpTo, cch, c_wszHeapDumpSuffix);
  1627. if (wszFullMinidumpFrom)
  1628. {
  1629. fRet = CopyFileW(wszFullMinidumpFrom, wszFullMinidumpTo, FALSE);
  1630. }
  1631. }
  1632. }
  1633. return fRet;
  1634. }
  1635. HRESULT
  1636. FindFullMinidump(
  1637. LPWSTR pwszDumpFileList,
  1638. LPWSTR pwszFullMiniDump,
  1639. ULONG cchwszFullMiniDump
  1640. )
  1641. //
  1642. // This Grabs dump file name from pwszDumpFileList and then derives the fullminidump name.
  1643. // The full dump is returned in pwszFullMiniDump.
  1644. //
  1645. {
  1646. LPWSTR wszSrch, wszFiles;
  1647. LPWSTR wszOriginalDump = NULL;
  1648. DWORD cchOriginalDump = 0;
  1649. DWORD cchFile, cch;
  1650. HRESULT Hr;
  1651. HANDLE hFile = INVALID_HANDLE_VALUE;
  1652. if (!pwszFullMiniDump || !pwszDumpFileList)
  1653. {
  1654. return E_INVALIDARG;
  1655. }
  1656. pwszFullMiniDump[0] = L'\0';
  1657. // Look through file list to find minidump file
  1658. wszFiles = pwszDumpFileList;
  1659. while (wszFiles && *wszFiles)
  1660. {
  1661. wszSrch = wcschr(wszFiles, DW_FILESEP);
  1662. if (!wszSrch)
  1663. {
  1664. wszSrch = wszFiles + wcslen(wszFiles);
  1665. }
  1666. // wszSrch now points after end of first file in wszFiles
  1667. if (!wcsncmp(wszSrch - sizeofSTRW(c_wszDumpSuffix) + 1,
  1668. c_wszDumpSuffix, sizeofSTRW(c_wszDumpSuffix) - 1))
  1669. {
  1670. // its the dump file
  1671. cchOriginalDump = (DWORD) wcslen(wszFiles) - wcslen(wszSrch);
  1672. __try { wszOriginalDump = (WCHAR *)_alloca((cchOriginalDump+1) * sizeof(WCHAR)); }
  1673. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  1674. {
  1675. wszOriginalDump = NULL;
  1676. }
  1677. StringCchCopyNW(wszOriginalDump, cchOriginalDump+1,
  1678. wszFiles, cchOriginalDump);
  1679. break;
  1680. }
  1681. wszFiles = wszSrch;
  1682. if (*wszFiles == L'\0')
  1683. {
  1684. break;
  1685. }
  1686. wszFiles++;
  1687. }
  1688. if ((wszOriginalDump == NULL) || (cchOriginalDump == 0))
  1689. {
  1690. return E_INVALIDARG;
  1691. }
  1692. // Now build the full dump file name
  1693. cch = (1 + cchOriginalDump + sizeofSTRW(c_wszHeapDumpSuffix));
  1694. if (cch > cchwszFullMiniDump)
  1695. {
  1696. return E_INVALIDARG;
  1697. }
  1698. StringCchCopyNW(pwszFullMiniDump, cch,
  1699. wszOriginalDump, cchOriginalDump);
  1700. pwszFullMiniDump[cchOriginalDump - sizeofSTRW(c_wszDumpSuffix) + 1] = L'\0';
  1701. StringCchCatW(pwszFullMiniDump, cch, c_wszHeapDumpSuffix);
  1702. // check if the dump exists. although we cannot do much if dump doesn't
  1703. // exist.
  1704. hFile = CreateFileW(pwszFullMiniDump, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0,
  1705. NULL);
  1706. if (hFile != INVALID_HANDLE_VALUE)
  1707. {
  1708. Hr = S_OK;
  1709. CloseHandle( hFile );
  1710. hFile = NULL;
  1711. } else
  1712. {
  1713. Hr = E_FAIL;
  1714. }
  1715. return Hr;
  1716. }
  1717. //////////////////////////////////////////////////////////////////////////////
  1718. // DW manifest mode utils
  1719. // **************************************************************************
  1720. EFaultRepRetVal StartDWManifest(CPFFaultClientCfg &oCfg, SDWManifestBlob &dwmb,
  1721. LPWSTR wszManifestIn, BOOL fAllowSend,
  1722. BOOL fReturnProcessHandle, DWORD dwTimeout)
  1723. {
  1724. USE_TRACING("StartDWManifest");
  1725. OSVERSIONINFOEXW ovi;
  1726. EFaultRepRetVal frrvRet = frrvErrNoDW;
  1727. STARTUPINFOW si;
  1728. HRESULT hr = NOERROR;
  1729. LPCWSTR pwszServer, pwszCorpPath;
  1730. LPCWSTR wszBrand;
  1731. HANDLE hManifest = INVALID_HANDLE_VALUE;
  1732. WCHAR wszManifestTU[MAX_PATH+16], wszDir[MAX_PATH];
  1733. WCHAR wszBuffer[1025], wszBufferApp[MAX_PATH*2];
  1734. LPWSTR pwszMiniDump = NULL;
  1735. DWORD cbToWrite, dw, dwFlags;
  1736. VALIDATEPARM(hr, (dwmb.wszStage2 == NULL ||
  1737. (dwmb.nidTitle == 0 && dwmb.wszTitle == NULL)));
  1738. if (FAILED(hr))
  1739. {
  1740. SetLastError(ERROR_INVALID_PARAMETER);
  1741. goto done;
  1742. }
  1743. // if we get passed a manifest file & we can use it, then do so.
  1744. if (wszManifestIn != NULL && wszManifestIn[0] != L'\0' &&
  1745. wcslen(wszManifestIn) < sizeofSTRW(wszManifestTU))
  1746. {
  1747. StringCbCopyW(wszManifestTU, sizeof(wszManifestTU), wszManifestIn);
  1748. }
  1749. // ok, figure out the temp dir & then generate the filename
  1750. else
  1751. {
  1752. if (!GetTempPathW(sizeofSTRW(wszDir), wszDir) ||
  1753. !GetTempFileNameW(wszDir, L"DWM", 0, wszManifestTU))
  1754. {
  1755. goto done;
  1756. }
  1757. }
  1758. hManifest = CreateFileW(wszManifestTU, GENERIC_WRITE, FILE_SHARE_READ,
  1759. NULL, CREATE_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN,
  1760. NULL);
  1761. TESTBOOL(hr, (hManifest != INVALID_HANDLE_VALUE));
  1762. if (FAILED(hr))
  1763. goto done;
  1764. // write the leading 0xFFFE out to the file
  1765. wszBuffer[0] = 0xFEFF;
  1766. TESTBOOL(hr, WriteFile(hManifest, wszBuffer, sizeof(wszBuffer[0]), &dw,
  1767. NULL));
  1768. if (FAILED(hr))
  1769. goto done;
  1770. // write out the server, LCID, Brand, Flags, & title
  1771. // Server=<server>
  1772. // UI LCID=GetSystemDefaultLCID()
  1773. // Flags=fDWWhister + fDWUserHKLM + headless if necessary
  1774. // Brand=<Brand> ("WINDOWS" by default)
  1775. // TitleName=<title>
  1776. wszBrand = (dwmb.wszBrand != NULL) ? dwmb.wszBrand : c_wszDWBrand;
  1777. // determine what server we're going to send the data to.
  1778. pwszServer = oCfg.get_DefaultServer(NULL, 0);
  1779. if (pwszServer == NULL || *pwszServer == L'\0')
  1780. {
  1781. pwszServer = (oCfg.get_UseInternal() == 1) ? c_wszDWDefServerI :
  1782. c_wszDWDefServerE;
  1783. }
  1784. if (oCfg.get_ShowUI() == eedDisabled)
  1785. {
  1786. DBG_MSG("Headless mode");
  1787. dwFlags = fDwWhistler | fDwHeadless | fDwUseHKLM | fDwAllowSuspend | fDwMiniDumpWithUnloadedModules;
  1788. }
  1789. else
  1790. dwFlags = fDwWhistler | fDwUseHKLM | fDwAllowSuspend | fDwMiniDumpWithUnloadedModules;
  1791. if (fAllowSend == FALSE)
  1792. dwFlags |= fDwNoReporting;
  1793. // if it's a MS app, set the flag that says we can have 'please help Microsoft'
  1794. // text in DW.
  1795. if (dwmb.fIsMSApp == FALSE)
  1796. dwFlags |= fDwUseLitePlea;
  1797. if ((dwmb.dwOptions & emoUseIEforURLs) == emoUseIEforURLs)
  1798. dwFlags |= fDwUseIE;
  1799. if ((dwmb.dwOptions & emoSupressBucketLogs) == emoSupressBucketLogs)
  1800. dwFlags |= fDwSkipBucketLog;
  1801. if ((dwmb.dwOptions & emoNoDefCabLimit) == emoNoDefCabLimit)
  1802. dwFlags |= fDwNoDefaultCabLimit;
  1803. if ((dwmb.dwOptions & emoShowDebugButton) == emoShowDebugButton)
  1804. dwFlags |= fDwManifestDebug;
  1805. // Note that I am assuming that we do NOT have an impersionation token on
  1806. // this thread at this point. Later on, I will simply do a RevertToSelf()
  1807. // to get rid of this. If stuff changes such that an impersonation token
  1808. // is applied to the thread before this function is called, it will need
  1809. // to be saved away here and restored later.
  1810. // This impersonation is to take care of the case where the user is using
  1811. // a different language than system default
  1812. if (dwmb.hToken != NULL)
  1813. {
  1814. DBG_MSG("Impersonating");
  1815. // note that I don't care if this fails... It's necessary to call
  1816. // ImpersonateLoggedOnUser because the token is not an impersonation
  1817. // token and this fn deals with both primary and impersonation tokens
  1818. TESTBOOL(hr, ImpersonateLoggedOnUser(dwmb.hToken));
  1819. hr = NOERROR;
  1820. }
  1821. // This function does not return a byte count
  1822. StringCbPrintfW(wszBuffer, sizeof(wszBuffer), c_wszManMisc, pwszServer,
  1823. GetUserDefaultUILanguage(), dwFlags, wszBrand);
  1824. cbToWrite = wcslen(wszBuffer);
  1825. cbToWrite *= sizeof(WCHAR);
  1826. TESTBOOL(hr, WriteFile(hManifest, wszBuffer, cbToWrite, &dw, NULL));
  1827. if (FAILED(hr))
  1828. goto done;
  1829. // write out the title text
  1830. {
  1831. LPCWSTR wszOut;
  1832. if (dwmb.wszTitle != NULL)
  1833. {
  1834. wszOut = dwmb.wszTitle;
  1835. cbToWrite = wcslen(wszOut);
  1836. }
  1837. else
  1838. {
  1839. wszOut = wszBuffer;
  1840. cbToWrite = LoadStringW(g_hInstance, dwmb.nidTitle, wszBuffer,
  1841. sizeofSTRW(wszBuffer));
  1842. if (cbToWrite == 0)
  1843. {
  1844. SetLastError(ERROR_INVALID_PARAMETER);
  1845. goto done;
  1846. }
  1847. }
  1848. cbToWrite *= sizeof(WCHAR);
  1849. TESTBOOL(hr, WriteFile(hManifest, wszOut, cbToWrite, &dw, NULL));
  1850. if (FAILED(hr))
  1851. goto done;
  1852. }
  1853. // write out dig PID path
  1854. // DigPidRegPath=HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\DigitalProductId
  1855. TESTBOOL(hr, WriteFile(hManifest, c_wszManPID,
  1856. sizeof(c_wszManPID) - sizeof(WCHAR), &dw,
  1857. NULL));
  1858. if (FAILED(hr))
  1859. goto done;
  1860. // write out the registry subpath for policy info
  1861. // RegSubPath==Microsoft\\PCHealth\\ErrorReporting\\DW
  1862. TESTBOOL(hr, WriteFile(hManifest, c_wszManSubPath,
  1863. sizeof(c_wszManSubPath) - sizeof(WCHAR), &dw,
  1864. NULL));
  1865. if (FAILED(hr))
  1866. goto done;
  1867. // write out the error message if we have one
  1868. // ErrorText=<error text read from resource>
  1869. if (dwmb.wszErrMsg != NULL || dwmb.nidErrMsg != 0)
  1870. {
  1871. LPCWSTR wszOut;
  1872. TESTBOOL(hr, WriteFile(hManifest, c_wszManErrText,
  1873. sizeof(c_wszManErrText) - sizeof(WCHAR), &dw,
  1874. NULL));
  1875. if (FAILED(hr))
  1876. goto done;
  1877. if (dwmb.wszErrMsg != NULL)
  1878. {
  1879. wszOut = dwmb.wszErrMsg;
  1880. cbToWrite = wcslen(wszOut);
  1881. }
  1882. else
  1883. {
  1884. wszOut = wszBuffer;
  1885. cbToWrite = LoadStringW(g_hInstance, dwmb.nidErrMsg, wszBuffer,
  1886. sizeofSTRW(wszBuffer));
  1887. if (cbToWrite == 0)
  1888. {
  1889. SetLastError(ERROR_INVALID_PARAMETER);
  1890. goto done;
  1891. }
  1892. }
  1893. cbToWrite *= sizeof(WCHAR);
  1894. TESTBOOL(hr, WriteFile(hManifest, wszOut, cbToWrite, &dw, NULL));
  1895. if (FAILED(hr))
  1896. goto done;
  1897. }
  1898. // write out the header text if we have one
  1899. // HeaderText=<header text read from resource>
  1900. if (dwmb.wszHdr != NULL || dwmb.nidHdr != 0)
  1901. {
  1902. LPCWSTR wszOut;
  1903. TESTBOOL(hr, WriteFile(hManifest, c_wszManHdrText,
  1904. sizeof(c_wszManHdrText) - sizeof(WCHAR), &dw,
  1905. NULL));
  1906. if (FAILED(hr))
  1907. goto done;
  1908. if (dwmb.wszHdr != NULL)
  1909. {
  1910. wszOut = dwmb.wszHdr;
  1911. cbToWrite = wcslen(wszOut);
  1912. }
  1913. else
  1914. {
  1915. wszOut = wszBuffer;
  1916. cbToWrite = LoadStringW(g_hInstance, dwmb.nidHdr, wszBuffer,
  1917. sizeofSTRW(wszBuffer));
  1918. if (cbToWrite == 0)
  1919. {
  1920. SetLastError(ERROR_INVALID_PARAMETER);
  1921. goto done;
  1922. }
  1923. }
  1924. cbToWrite *= sizeof(WCHAR);
  1925. TESTBOOL(hr, WriteFile(hManifest, wszOut, cbToWrite, &dw, NULL));
  1926. if (FAILED(hr))
  1927. goto done;
  1928. }
  1929. // write out the plea text if we have one
  1930. // Plea=<plea text>
  1931. if (dwmb.wszPlea != NULL)
  1932. {
  1933. TESTBOOL(hr, WriteFile(hManifest, c_wszManPleaText,
  1934. sizeof(c_wszManPleaText) - sizeof(WCHAR), &dw,
  1935. NULL));
  1936. if (FAILED(hr))
  1937. goto done;
  1938. cbToWrite = wcslen(dwmb.wszPlea) * sizeof(WCHAR);
  1939. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszPlea, cbToWrite, &dw, NULL));
  1940. if (FAILED(hr))
  1941. goto done;
  1942. }
  1943. // write out the ReportButton text if we have one
  1944. // ReportButton=<button text>
  1945. if (dwmb.wszSendBtn != NULL && dwmb.wszSendBtn[0] != L'\0')
  1946. {
  1947. TESTBOOL(hr, WriteFile(hManifest, c_wszManSendText,
  1948. sizeof(c_wszManSendText) - sizeof(WCHAR), &dw,
  1949. NULL));
  1950. if (FAILED(hr))
  1951. goto done;
  1952. cbToWrite = wcslen(dwmb.wszSendBtn) * sizeof(WCHAR);
  1953. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszSendBtn, cbToWrite, &dw, NULL));
  1954. if (FAILED(hr))
  1955. goto done;
  1956. }
  1957. // write out the NoReportButton text if we have one
  1958. // NoReportButton=<button text>
  1959. if (dwmb.wszNoSendBtn != NULL && dwmb.wszNoSendBtn[0] != L'\0')
  1960. {
  1961. TESTBOOL(hr, WriteFile(hManifest, c_wszManNSendText,
  1962. sizeof(c_wszManNSendText) - sizeof(WCHAR), &dw,
  1963. NULL));
  1964. if (FAILED(hr))
  1965. goto done;
  1966. cbToWrite = wcslen(dwmb.wszNoSendBtn) * sizeof(WCHAR);
  1967. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszNoSendBtn, cbToWrite, &dw, NULL));
  1968. if (FAILED(hr))
  1969. goto done;
  1970. }
  1971. // write out the EventLog text if we have one
  1972. // EventLogSource=<button text>
  1973. if (dwmb.wszEventSrc != NULL && dwmb.wszEventSrc[0] != L'\0')
  1974. {
  1975. TESTBOOL(hr, WriteFile(hManifest, c_wszManEventSrc,
  1976. sizeof(c_wszManEventSrc) - sizeof(WCHAR), &dw,
  1977. NULL));
  1978. if (FAILED(hr))
  1979. goto done;
  1980. cbToWrite = wcslen(dwmb.wszEventSrc) * sizeof(WCHAR);
  1981. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszEventSrc, cbToWrite, &dw, NULL));
  1982. if (FAILED(hr))
  1983. goto done;
  1984. }
  1985. // write out the stage 1 URL if there is one
  1986. // Stage1URL=<stage 1 URL>
  1987. if (dwmb.wszStage1 != NULL && dwmb.wszStage1[0] != L'\0')
  1988. {
  1989. /*
  1990. * We don't look for a "Stage1URL=" string at the beginning of this, like
  1991. * we do for Stage2 (below) . In an ideal world, we should not need to
  1992. * check in either location, but we did find a problem with PnP reporting
  1993. * code, so I do check for it there...
  1994. */
  1995. cbToWrite = wcslen(dwmb.wszStage1) * sizeof(WCHAR);
  1996. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszStage1, cbToWrite, &dw, NULL));
  1997. if (FAILED(hr))
  1998. goto done;
  1999. }
  2000. // write out the stage 2 URL
  2001. // Stage2URL=<stage 2 URL>
  2002. if (dwmb.wszStage2 != NULL && dwmb.wszStage2[0] != L'\0')
  2003. {
  2004. if (wcsncmp(dwmb.wszStage2, c_wszManStageTwo, ARRAYSIZE(c_wszManStageTwo)-1))
  2005. {
  2006. // if the "Stage2URL=" does not exist, add it!
  2007. TESTBOOL(hr, WriteFile(hManifest, c_wszManStageTwo,
  2008. sizeof(c_wszManStageTwo) - sizeof(WCHAR), &dw,
  2009. NULL));
  2010. if (FAILED(hr))
  2011. goto done;
  2012. }
  2013. cbToWrite = wcslen(dwmb.wszStage2) * sizeof(WCHAR);
  2014. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszStage2, cbToWrite, &dw, NULL));
  2015. if (FAILED(hr))
  2016. goto done;
  2017. }
  2018. else if (dwmb.wszErrorSig == NULL || dwmb.wszErrorSig[0] != L'\0')
  2019. {
  2020. // write out the Error Signature for DW if no Stage2
  2021. TESTBOOL(hr, WriteFile(hManifest, c_wszManErrSig,
  2022. sizeof(c_wszManErrSig) - sizeof(WCHAR), &dw,
  2023. NULL));
  2024. if (FAILED(hr))
  2025. goto done;
  2026. }
  2027. // write out error signature
  2028. // ErrorSig=<error signature>
  2029. if (dwmb.wszErrorSig != NULL && dwmb.wszErrorSig[0] != L'\0')
  2030. {
  2031. cbToWrite = wcslen(dwmb.wszErrorSig) * sizeof(WCHAR);
  2032. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszErrorSig, cbToWrite, &dw, NULL));
  2033. if (FAILED(hr))
  2034. goto done;
  2035. }
  2036. // write out files to collect if we have any
  2037. // DataFiles=<list of files to include in cab>
  2038. if (dwmb.wszFileList != NULL && dwmb.wszFileList[0] != L'\0')
  2039. {
  2040. TESTBOOL(hr, WriteFile(hManifest, c_wszManFiles,
  2041. sizeof(c_wszManFiles) - sizeof(WCHAR), &dw,
  2042. NULL));
  2043. if (FAILED(hr))
  2044. goto done;
  2045. cbToWrite = wcslen(dwmb.wszFileList) * sizeof(WCHAR);
  2046. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszFileList, cbToWrite, &dw, NULL));
  2047. if (FAILED(hr))
  2048. goto done;
  2049. }
  2050. // write out dump file with heap info if we have any
  2051. // Heap=<dump file which has heap info>
  2052. if (1)
  2053. {
  2054. __try { pwszMiniDump = (LPWSTR)_alloca((wcslen(dwmb.wszFileList) + 1) * sizeof(WCHAR)); }
  2055. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  2056. {
  2057. pwszMiniDump = NULL;
  2058. }
  2059. if (FindFullMinidump((LPWSTR)dwmb.wszFileList, pwszMiniDump,
  2060. wcslen(dwmb.wszFileList) + 1) == S_OK)
  2061. {
  2062. if (pwszMiniDump != NULL && pwszMiniDump[0] != L'\0')
  2063. {
  2064. TESTBOOL(hr, WriteFile(hManifest, c_wszManHeapDump,
  2065. sizeof(c_wszManHeapDump) - sizeof(WCHAR), &dw,
  2066. NULL));
  2067. if (FAILED(hr))
  2068. goto done;
  2069. cbToWrite = wcslen(pwszMiniDump) * sizeof(WCHAR);
  2070. TESTBOOL(hr, WriteFile(hManifest, pwszMiniDump, cbToWrite, &dw, NULL));
  2071. if (FAILED(hr))
  2072. goto done;
  2073. }
  2074. }
  2075. }
  2076. // write out corporate mode subpath
  2077. // ErrorSubPath=<subpath for the error signature>
  2078. pwszCorpPath = oCfg.get_DumpPath(NULL, 0);
  2079. if (pwszCorpPath != NULL && pwszCorpPath != L'\0' &&
  2080. dwmb.wszCorpPath != NULL && dwmb.wszCorpPath[0] != L'\0')
  2081. {
  2082. TESTBOOL(hr, WriteFile(hManifest, c_wszManCorpPath,
  2083. sizeof(c_wszManCorpPath) - sizeof(WCHAR), &dw,
  2084. NULL));
  2085. if (FAILED(hr))
  2086. goto done;
  2087. cbToWrite = wcslen(dwmb.wszCorpPath) * sizeof(WCHAR);
  2088. TESTBOOL(hr, WriteFile(hManifest, dwmb.wszCorpPath, cbToWrite, &dw, NULL));
  2089. if (FAILED(hr))
  2090. goto done;
  2091. }
  2092. // since we only need then when pulling strings from faultrep.dll, can go
  2093. // ahead and restore ourselves. Note that we assume there was no previous
  2094. // impersonation token on the the thread.
  2095. if (dwmb.hToken != NULL)
  2096. RevertToSelf();
  2097. // write out the final "\r\n"
  2098. wszBuffer[0] = L'\r';
  2099. wszBuffer[1] = L'\n';
  2100. TESTBOOL(hr, WriteFile(hManifest, wszBuffer, 2 * sizeof(wszBuffer[0]), &dw,
  2101. NULL));
  2102. if (FAILED(hr))
  2103. goto done;
  2104. CloseHandle(hManifest);
  2105. hManifest = INVALID_HANDLE_VALUE;
  2106. // create the process
  2107. GetSystemDirectoryW(wszDir, sizeofSTRW(wszDir));
  2108. StringCbPrintfW(wszBufferApp, sizeof(wszBufferApp), c_wszDWExeKH, wszDir);
  2109. StringCbPrintfW(wszBuffer, sizeof(wszBuffer), c_wszDWCmdLineKH, wszManifestTU);
  2110. ZeroMemory(&si, sizeof(si));
  2111. ZeroMemory(&dwmb.pi, sizeof(dwmb.pi));
  2112. si.cb = sizeof(si);
  2113. // check and see if the system is shutting down. If so, CreateProcess is
  2114. // gonna pop up some annoying UI that we can't get rid of, so we don't
  2115. // want to call it if we know it's gonna happen.
  2116. if (GetSystemMetrics(SM_SHUTTINGDOWN))
  2117. {
  2118. DBG_MSG("Shutting down, report not sent");
  2119. goto done;
  2120. }
  2121. // ErrorTrace(1, "Starting DW as: \'%S\' \'%S\'", wszBufferApp, wszBuffer);
  2122. // we're creating the process in the same user context that we're in
  2123. if (dwmb.hToken == NULL)
  2124. {
  2125. si.lpDesktop = L"Winsta0\\Default";
  2126. TESTBOOL(hr, CreateProcessW(wszBufferApp, wszBuffer, NULL, NULL, TRUE,
  2127. CREATE_DEFAULT_ERROR_MODE |
  2128. NORMAL_PRIORITY_CLASS,
  2129. NULL, wszDir, &si, &dwmb.pi));
  2130. if (FAILED(hr))
  2131. goto done;
  2132. }
  2133. // we're creating DW in a different user context. Note that we pretty
  2134. // much have to be running as local system for this to work.
  2135. // Note that the access check that CreateProcessAsUser makes appears to
  2136. // use the process token, so we do not need to remove any impersonation
  2137. // tokens at this point.
  2138. else
  2139. {
  2140. TESTBOOL(hr, CreateProcessAsUserW(dwmb.hToken, wszBufferApp, wszBuffer, NULL,
  2141. NULL, FALSE, NORMAL_PRIORITY_CLASS |
  2142. CREATE_UNICODE_ENVIRONMENT |
  2143. CREATE_DEFAULT_ERROR_MODE,
  2144. dwmb.pvEnv, wszDir, &si, &dwmb.pi));
  2145. if (FAILED(hr))
  2146. {
  2147. ErrorTrace(1, "CreateProcessAsUser failed err=0x%x", GetLastError());
  2148. goto done;
  2149. }
  2150. }
  2151. // don't need the thread handle & we gotta close it, so close it now
  2152. CloseHandle(dwmb.pi.hThread);
  2153. dwmb.pi.hThread = NULL;
  2154. // wait 5 minutes for DW to close. If it doesn't close by then, just
  2155. // return.
  2156. dw = WaitForSingleObject(dwmb.pi.hProcess, dwTimeout);
  2157. if (dw == WAIT_TIMEOUT)
  2158. {
  2159. /* We need to kill this process */
  2160. LocalKill(dwmb.pi.hProcess);
  2161. CloseHandle(dwmb.pi.hProcess);
  2162. DBG_MSG("Timeout error");
  2163. frrvRet = frrvErrTimeout;
  2164. goto done;
  2165. }
  2166. else if (dw == WAIT_FAILED)
  2167. {
  2168. CloseHandle(dwmb.pi.hProcess);
  2169. DWORD dwErr = GetLastError();
  2170. ErrorTrace(0, "Wait failed: err=0x%x", dwErr);
  2171. SetLastError(dwErr);
  2172. goto done;
  2173. }
  2174. TESTBOOL(hr, GetExitCodeProcess(dwmb.pi.hProcess, &dw));
  2175. if (dw == STILL_ACTIVE)
  2176. {
  2177. DBG_MSG("Evil problem: DW process still active!");
  2178. frrvRet = frrvErrTimeout;
  2179. goto done;
  2180. }
  2181. if (!fReturnProcessHandle)
  2182. {
  2183. CloseHandle(dwmb.pi.hProcess);
  2184. dwmb.pi.hProcess = NULL;
  2185. }
  2186. if (dw == 0)
  2187. {
  2188. DBG_MSG("DW returned SUCCESS");
  2189. frrvRet = frrvOk;
  2190. }
  2191. else
  2192. {
  2193. ErrorTrace(0, "DW returned FAILURE (%d)", dw);
  2194. frrvRet = frrvErr;
  2195. }
  2196. done:
  2197. // preserve the error code so that the following calls don't overwrite it
  2198. dw = GetLastError();
  2199. // Note again that we assume there was no previous impersonation token
  2200. // on the the thread before we did the impersonation above.
  2201. if (dwmb.hToken != NULL)
  2202. RevertToSelf();
  2203. if (hManifest != INVALID_HANDLE_VALUE)
  2204. CloseHandle(hManifest);
  2205. if (FAILED(hr) || wszManifestIn == NULL)
  2206. {
  2207. DBG_MSG("Deleting manifest file");
  2208. DeleteFileW(wszManifestTU);
  2209. }
  2210. SetLastError(dw);
  2211. return frrvRet;
  2212. }
  2213. //////////////////////////////////////////////////////////////////////////////
  2214. // Security
  2215. // **************************************************************************
  2216. BOOL CompareUserToProcessUser(PSID psidUser)
  2217. {
  2218. TOKEN_USER *ptuProc = NULL;
  2219. HRESULT hr = NOERROR;
  2220. HANDLE hTokenProc = NULL;
  2221. DWORD cb;
  2222. USE_TRACING("CompareUserToProcessUser");
  2223. // fetch the token for the current process
  2224. TESTBOOL(hr, OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &hTokenProc));
  2225. if (FAILED(hr))
  2226. goto done;
  2227. // check the SID coming in
  2228. TESTBOOL(hr, IsValidSid(psidUser));
  2229. if (FAILED(hr))
  2230. goto done;
  2231. // fetch the sid for the user of the current process
  2232. GetTokenInformation(hTokenProc, TokenUser, NULL, 0, &cb);
  2233. __try { ptuProc = (TOKEN_USER *)_alloca(cb); }
  2234. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  2235. {
  2236. ptuProc = NULL;
  2237. }
  2238. VALIDATEEXPR(hr, (ptuProc == NULL), E_OUTOFMEMORY);
  2239. if (FAILED(hr))
  2240. {
  2241. SetLastError(ERROR_OUTOFMEMORY);
  2242. goto done;
  2243. }
  2244. TESTBOOL(hr, GetTokenInformation(hTokenProc, TokenUser, (LPVOID)ptuProc,
  2245. cb, &cb));
  2246. if (FAILED(hr))
  2247. goto done;
  2248. TESTBOOL(hr, IsValidSid(ptuProc->User.Sid));
  2249. if (FAILED(hr))
  2250. goto done;
  2251. // are they equal?
  2252. VALIDATEEXPR(hr, (EqualSid(ptuProc->User.Sid, psidUser) == FALSE),
  2253. Err2HR(ERROR_ACCESS_DENIED));
  2254. if (FAILED(hr))
  2255. {
  2256. SetLastError(ERROR_ACCESS_DENIED);
  2257. goto done;
  2258. }
  2259. done:
  2260. if (hTokenProc != NULL)
  2261. CloseHandle(hTokenProc);
  2262. return SUCCEEDED(hr);
  2263. }
  2264. // **************************************************************************
  2265. #define ER_WINSTA_ALL WINSTA_ACCESSCLIPBOARD | WINSTA_ACCESSGLOBALATOMS | \
  2266. WINSTA_CREATEDESKTOP | WINSTA_ENUMDESKTOPS | \
  2267. WINSTA_ENUMERATE | WINSTA_EXITWINDOWS | \
  2268. WINSTA_READATTRIBUTES | WINSTA_READSCREEN | \
  2269. WINSTA_WRITEATTRIBUTES
  2270. BOOL DoUserContextsMatch(void)
  2271. {
  2272. HWINSTA hwinsta = NULL;
  2273. HRESULT hr = NOERROR;
  2274. PSID psidUser = NULL;
  2275. DWORD cbNeed = 0, cbGot;
  2276. BOOL fRet = FALSE;
  2277. USE_TRACING("DoUserContextsMatch");
  2278. // well, we pretty much only care about the user attached to WinSta0 since
  2279. // that's where the interactive user'll be at. If we don't have full
  2280. // access to it, we're not going to be able to create DW on it anyway, so
  2281. // just bail if we fail.
  2282. hwinsta = OpenWindowStationW(L"WinSta0", FALSE, ER_WINSTA_ALL);
  2283. TESTBOOL(hr, (hwinsta != NULL));
  2284. if (FAILED(hr))
  2285. goto done;
  2286. fRet = GetUserObjectInformationW(hwinsta, UOI_USER_SID, NULL, 0, &cbNeed);
  2287. TESTBOOL(hr, (cbNeed != 0));
  2288. if (FAILED(hr))
  2289. {
  2290. hr = E_FAIL;
  2291. goto done;
  2292. }
  2293. __try { psidUser = (PSID)_alloca(cbNeed); }
  2294. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  2295. {
  2296. psidUser = NULL;
  2297. }
  2298. VALIDATEEXPR(hr, (psidUser == NULL), E_OUTOFMEMORY);
  2299. if (FAILED(hr))
  2300. {
  2301. SetLastError(ERROR_OUTOFMEMORY);
  2302. goto done;
  2303. }
  2304. TESTBOOL(hr, GetUserObjectInformationW(hwinsta, UOI_USER_SID, psidUser, cbNeed,
  2305. &cbGot));
  2306. if (FAILED(hr))
  2307. goto done;
  2308. TESTBOOL(hr, CompareUserToProcessUser(psidUser));
  2309. if (FAILED(hr))
  2310. goto done;
  2311. done:
  2312. if (hwinsta != NULL)
  2313. CloseWindowStation(hwinsta);
  2314. return SUCCEEDED(hr);
  2315. }
  2316. // ***************************************************************************
  2317. BOOL DoWinstaDesktopMatch(void)
  2318. {
  2319. HWINSTA hwinsta = NULL;
  2320. HRESULT hr = NOERROR;
  2321. LPWSTR wszWinsta = NULL;
  2322. DWORD cbNeed = 0, cbGot;
  2323. BOOL fRet = FALSE;
  2324. USE_TRACING("DoWinstaDesktopMatch");
  2325. hwinsta = GetProcessWindowStation();
  2326. TESTBOOL(hr, (hwinsta != NULL));
  2327. if (FAILED(hr))
  2328. goto done;
  2329. fRet = GetUserObjectInformationW(hwinsta, UOI_NAME, NULL, 0, &cbNeed);
  2330. TESTBOOL(hr, (cbNeed != 0));
  2331. if (FAILED(hr))
  2332. {
  2333. fRet = FALSE;
  2334. goto done;
  2335. }
  2336. cbNeed += sizeof(WCHAR);
  2337. __try { wszWinsta = (LPWSTR)_alloca(cbNeed); }
  2338. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  2339. {
  2340. wszWinsta = NULL;
  2341. }
  2342. TESTBOOL(hr, (wszWinsta != NULL));
  2343. if (FAILED(hr))
  2344. {
  2345. fRet = FALSE;
  2346. goto done;
  2347. }
  2348. cbGot = 0;
  2349. fRet = GetUserObjectInformationW(hwinsta, UOI_NAME, wszWinsta, cbNeed,
  2350. &cbGot);
  2351. TESTBOOL(hr, (fRet != FALSE));
  2352. if (FAILED(hr))
  2353. goto done;
  2354. ErrorTrace(0, "WinSta = %S", wszWinsta);
  2355. // 'Winsta0' should be the interactive window station for a given session
  2356. fRet = (_wcsicmp(wszWinsta, L"WinSta0") == 0);
  2357. done:
  2358. return fRet;
  2359. }
  2360. // ***************************************************************************
  2361. BOOL AmIPrivileged(BOOL fOnlyCheckLS)
  2362. {
  2363. SID_IDENTIFIER_AUTHORITY siaNT = SECURITY_NT_AUTHORITY;
  2364. TOKEN_USER *ptu = NULL, *ptuImp = NULL;
  2365. HANDLE hToken = NULL, hTokenImp = NULL;
  2366. DWORD cb, cbGot, i;
  2367. PSID psid = NULL;
  2368. BOOL fRet = FALSE, fThread;
  2369. // local system has to be the first RID in this array. Otherwise, the
  2370. // loop logic below needs to be changed.
  2371. DWORD rgRIDs[3] = { SECURITY_LOCAL_SYSTEM_RID,
  2372. SECURITY_LOCAL_SERVICE_RID,
  2373. SECURITY_NETWORK_SERVICE_RID };
  2374. // gotta have a token to get the SID
  2375. fThread = OpenThreadToken(GetCurrentThread(),
  2376. TOKEN_READ | TOKEN_IMPERSONATE, TRUE,
  2377. &hTokenImp);
  2378. if (fThread == FALSE && GetLastError() != ERROR_NO_TOKEN)
  2379. goto done;
  2380. // revert back to base user acct so we can fetch the process token &
  2381. // extract all the nifty stuff out of it.
  2382. RevertToSelf();
  2383. fRet = OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &hToken);
  2384. if (fRet == FALSE)
  2385. goto done;
  2386. // figure out the SID
  2387. fRet = GetTokenInformation(hToken, TokenUser, NULL, 0, &cb);
  2388. if (fRet != FALSE && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  2389. {
  2390. fRet = FALSE;
  2391. goto done;
  2392. }
  2393. __try { ptu = (TOKEN_USER *)_alloca(cb); }
  2394. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  2395. {
  2396. ptu = NULL;
  2397. }
  2398. if (ptu == NULL)
  2399. {
  2400. SetLastError(ERROR_OUTOFMEMORY);
  2401. fRet = FALSE;
  2402. goto done;
  2403. }
  2404. fRet = GetTokenInformation(hToken, TokenUser, (LPVOID)ptu, cb, &cbGot);
  2405. if (fRet == FALSE)
  2406. goto done;
  2407. fRet = IsValidSid(ptu->User.Sid);
  2408. if (fRet == FALSE)
  2409. goto done;
  2410. if (fThread)
  2411. {
  2412. // figure out the SID
  2413. fRet = GetTokenInformation(hTokenImp, TokenUser, NULL, 0, &cb);
  2414. if (fRet != FALSE && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  2415. {
  2416. fRet = FALSE;
  2417. goto done;
  2418. }
  2419. __try { ptuImp = (TOKEN_USER *)_alloca(cb); }
  2420. __except(EXCEPTION_STACK_OVERFLOW == GetExceptionCode() ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
  2421. {
  2422. ptuImp = NULL;
  2423. }
  2424. if (ptuImp == NULL)
  2425. {
  2426. SetLastError(ERROR_OUTOFMEMORY);
  2427. fRet = FALSE;
  2428. goto done;
  2429. }
  2430. fRet = GetTokenInformation(hTokenImp, TokenUser, (LPVOID)ptuImp, cb,
  2431. &cbGot);
  2432. if (fRet == FALSE)
  2433. goto done;
  2434. fRet = IsValidSid(ptuImp->User.Sid);
  2435. if (fRet == FALSE)
  2436. goto done;
  2437. }
  2438. // loop thru & check against the SIDs we are interested in
  2439. for (i = 0; i < 3; i++)
  2440. {
  2441. fRet = AllocateAndInitializeSid(&siaNT, 1, rgRIDs[i], 0, 0, 0, 0, 0, 0,
  2442. 0, &psid);
  2443. if (fRet == FALSE)
  2444. goto done;
  2445. fRet = IsValidSid(psid);
  2446. if (fRet == FALSE)
  2447. goto done;
  2448. fRet = EqualSid(psid, ptu->User.Sid);
  2449. if (fRet)
  2450. {
  2451. // set this to false so that the code below will correctly change
  2452. // it to TRUE
  2453. fRet = FALSE;
  2454. goto done;
  2455. }
  2456. if (fThread)
  2457. {
  2458. fRet = EqualSid(psid, ptuImp->User.Sid);
  2459. if (fRet)
  2460. {
  2461. // set this to false so that the code below will correctly
  2462. // change it to TRUE
  2463. fRet = FALSE;
  2464. goto done;
  2465. }
  2466. }
  2467. FreeSid(psid);
  2468. psid = NULL;
  2469. // if we only need to check for local system, can bail now (we've
  2470. // already done it if we've gone thru this loop once)
  2471. if (fOnlyCheckLS)
  2472. break;
  2473. }
  2474. // only way to get here is to fail all the SID checks above. So set the
  2475. // result to TRUE so the code below correclty changes it to FALSE
  2476. fRet = TRUE;
  2477. done:
  2478. if (fThread && hTokenImp != NULL)
  2479. {
  2480. if (SetThreadToken(NULL, hTokenImp) == FALSE)
  2481. fRet = FALSE;
  2482. }
  2483. // if anything failed above, we want to return TRUE (cuz this puts us
  2484. // down the most secure code path), so need to negate the result. Since
  2485. // we set the fallthru case to TRUE, we'll correctly negate it to FALSE
  2486. // here.
  2487. fRet = !fRet;
  2488. // if we had an impersonation token on the thread, put it back in place.
  2489. if (hToken != NULL)
  2490. CloseHandle(hToken);
  2491. if (hTokenImp != NULL)
  2492. CloseHandle(hTokenImp);
  2493. if (fRet == TRUE && GetLastError() == ERROR_SUCCESS)
  2494. SetLastError(ERROR_ACCESS_DENIED);
  2495. if (psid != NULL)
  2496. FreeSid(psid);
  2497. return fRet;
  2498. }
  2499. /*
  2500. * WtsLockCheck-
  2501. * returns TRUE if the session is locked.
  2502. * The session can be marked as "Active", and can still be locked, if FUS
  2503. * is active.
  2504. */
  2505. BOOL WtsLockCheck(DWORD dwSession)
  2506. {
  2507. BOOL bRet = FALSE;
  2508. DWORD dwRetSize;
  2509. WinStationQueryInformationW(
  2510. SERVERNAME_CURRENT,
  2511. dwSession,
  2512. WinStationLockedState,
  2513. &bRet,
  2514. sizeof(bRet),
  2515. &dwRetSize);
  2516. return bRet;
  2517. }
  2518. // **************************************************************************
  2519. BOOL FindAdminSession(DWORD *pdwSession, HANDLE *phToken)
  2520. {
  2521. USE_TRACING("FindAdminSession");
  2522. WINSTATIONUSERTOKEN wsut;
  2523. LOGONIDW *rgSesn = NULL;
  2524. HRESULT hr = NOERROR;
  2525. DWORD i, cSesn, cb;
  2526. ZeroMemory(&wsut, sizeof(wsut));
  2527. VALIDATEPARM(hr, (pdwSession == NULL || phToken == NULL));
  2528. if (FAILED(hr))
  2529. goto done;
  2530. *pdwSession = (DWORD)-1;
  2531. *phToken = NULL;
  2532. TESTBOOL(hr, WinStationEnumerateW(SERVERNAME_CURRENT, &rgSesn, &cSesn));
  2533. if (FAILED(hr))
  2534. goto done;
  2535. wsut.ProcessId = LongToHandle(GetCurrentProcessId());
  2536. wsut.ThreadId = LongToHandle(GetCurrentThreadId());
  2537. for(i = 0; i < cSesn; i++)
  2538. {
  2539. if (rgSesn[i].State != State_Active)
  2540. continue;
  2541. TESTBOOL(hr, WinStationQueryInformationW(SERVERNAME_CURRENT,
  2542. rgSesn[i].SessionId,
  2543. WinStationUserToken,
  2544. &wsut, sizeof(wsut), &cb));
  2545. if (FAILED(hr))
  2546. continue;
  2547. if (wsut.UserToken != NULL)
  2548. {
  2549. if (IsUserAnAdmin(wsut.UserToken) && !WtsLockCheck(rgSesn[i].SessionId))
  2550. break;
  2551. CloseHandle(wsut.UserToken);
  2552. wsut.UserToken = NULL;
  2553. }
  2554. }
  2555. if (i < cSesn)
  2556. {
  2557. hr = NOERROR;
  2558. *pdwSession = rgSesn[i].SessionId;
  2559. *phToken = wsut.UserToken;
  2560. }
  2561. else
  2562. {
  2563. hr = E_FAIL;
  2564. }
  2565. done:
  2566. if (rgSesn != NULL)
  2567. WinStationFreeMemory(rgSesn);
  2568. return SUCCEEDED(hr);
  2569. }
  2570. //////////////////////////////////////////////////////////////////////////////
  2571. // Logging
  2572. // **************************************************************************
  2573. HRESULT LogEvent(LPCWSTR wszSrc, WORD wCat, DWORD dwEventID, WORD cStrs,
  2574. DWORD cbBlob, LPCWSTR *rgwszStrs, LPVOID pvBlob)
  2575. {
  2576. USE_TRACING("LogEvent");
  2577. HRESULT hr = NOERROR;
  2578. HANDLE hLog = NULL;
  2579. WORD wErr = EVENTLOG_ERROR_TYPE;
  2580. VALIDATEPARM(hr, (wszSrc == NULL));
  2581. if (FAILED(hr))
  2582. goto done;
  2583. hLog = RegisterEventSourceW(NULL, wszSrc);
  2584. TESTBOOL(hr, (hLog != NULL));
  2585. if (FAILED(hr))
  2586. goto done;
  2587. if (dwEventID == ER_QUEUEREPORT_LOG)
  2588. wErr = EVENTLOG_INFORMATION_TYPE;
  2589. TESTBOOL(hr, ReportEventW(hLog, wErr, wCat, dwEventID,
  2590. NULL, cStrs, cbBlob, rgwszStrs, pvBlob));
  2591. if (FAILED(hr))
  2592. goto done;
  2593. done:
  2594. if (hLog != NULL)
  2595. DeregisterEventSource(hLog);
  2596. return hr;
  2597. }
  2598. // **************************************************************************
  2599. HRESULT LogHang(LPCWSTR wszApp, WORD *rgAppVer, LPCWSTR wszMod, WORD *rgModVer,
  2600. ULONG64 ulOffset, BOOL f64bit)
  2601. {
  2602. USE_TRACING("LogHang");
  2603. HRESULT hr = NOERROR;
  2604. LPCWSTR rgwsz[5];
  2605. WCHAR wszAppVer[32], wszModVer[32], wszOffset[32];
  2606. char szBlobLog[1024];
  2607. VALIDATEPARM(hr, (wszApp == NULL || rgAppVer == NULL || wszMod == NULL ||
  2608. rgModVer == NULL));
  2609. if (FAILED(hr))
  2610. return hr;
  2611. StringCbPrintfW(wszAppVer, sizeof(wszAppVer), L"%d.%d.%d.%d",
  2612. rgAppVer[0], rgAppVer[1], rgAppVer[2], rgAppVer[3]);
  2613. StringCbPrintfW(wszModVer, sizeof(wszModVer), L"%d.%d.%d.%d",
  2614. rgModVer[0], rgModVer[1], rgModVer[2], rgModVer[3]);
  2615. if (f64bit)
  2616. StringCbPrintfW(wszOffset, sizeof(wszOffset), L"%016I64x", ulOffset);
  2617. else
  2618. StringCbPrintfW(wszOffset, sizeof(wszOffset), L"%08x", (DWORD)ulOffset);
  2619. StringCbPrintfA(szBlobLog, sizeof(szBlobLog),
  2620. "Application Hang %S %S in %S %S at offset %S",
  2621. wszApp, wszAppVer, wszMod, wszModVer, wszOffset);
  2622. rgwsz[0] = wszApp;
  2623. rgwsz[1] = wszAppVer;
  2624. rgwsz[2] = wszMod;
  2625. rgwsz[3] = wszModVer;
  2626. rgwsz[4] = wszOffset;
  2627. return LogEvent(c_wszHangEventSrc, ER_HANG_CATEGORY, ER_HANG_LOG, 5,
  2628. strlen(szBlobLog), rgwsz, szBlobLog);
  2629. }
  2630. // **************************************************************************
  2631. HRESULT LogUser(LPCWSTR wszApp, WORD *rgAppVer, LPCWSTR wszMod, WORD *rgModVer,
  2632. ULONG64 ulOffset, BOOL f64bit, DWORD dwEventID)
  2633. {
  2634. USE_TRACING("LogUser");
  2635. HRESULT hr = NOERROR;
  2636. LPCWSTR rgwsz[5];
  2637. WCHAR wszAppVer[32], wszModVer[32], wszOffset[32];
  2638. char szBlobLog[1024];
  2639. VALIDATEPARM(hr, (wszApp == NULL || rgAppVer == NULL || wszMod == NULL ||
  2640. rgModVer == NULL));
  2641. if (FAILED(hr))
  2642. return hr;
  2643. StringCbPrintfW(wszAppVer, sizeof(wszAppVer), L"%d.%d.%d.%d",
  2644. rgAppVer[0], rgAppVer[1], rgAppVer[2], rgAppVer[3]);
  2645. StringCbPrintfW(wszModVer, sizeof(wszModVer), L"%d.%d.%d.%d",
  2646. rgModVer[0], rgModVer[1], rgModVer[2], rgModVer[3]);
  2647. if (f64bit)
  2648. StringCbPrintfW(wszOffset, sizeof(wszOffset), L"%016I64x", ulOffset);
  2649. else
  2650. StringCbPrintfW(wszOffset, sizeof(wszOffset), L"%08x", (DWORD)ulOffset);
  2651. StringCbPrintfA(szBlobLog, sizeof(szBlobLog),
  2652. "Application Failure %S %S in %S %S at offset %S",
  2653. wszApp, wszAppVer, wszMod, wszModVer, wszOffset);
  2654. rgwsz[0] = wszApp;
  2655. rgwsz[1] = wszAppVer;
  2656. rgwsz[2] = wszMod;
  2657. rgwsz[3] = wszModVer;
  2658. rgwsz[4] = wszOffset;
  2659. return LogEvent(c_wszUserEventSrc, ER_USERFAULT_CATEGORY, dwEventID,
  2660. 5, strlen(szBlobLog), rgwsz, szBlobLog);
  2661. }
  2662. // **************************************************************************
  2663. #ifndef _WIN64
  2664. HRESULT LogKrnl(ULONG ulBCCode, ULONG ulBCP1, ULONG ulBCP2, ULONG ulBCP3,
  2665. ULONG ulBCP4)
  2666. #else
  2667. HRESULT LogKrnl(ULONG ulBCCode, ULONG64 ulBCP1, ULONG64 ulBCP2, ULONG64 ulBCP3,
  2668. ULONG64 ulBCP4)
  2669. #endif
  2670. {
  2671. USE_TRACING("LogKrnl");
  2672. HRESULT hr = NOERROR;
  2673. LPCWSTR rgwsz[5];
  2674. WCHAR wszBCC[32], wszBCP1[32], wszBCP2[32], wszBCP3[32], wszBCP4[32];
  2675. char szBlobLog[1024];
  2676. #ifndef _WIN64
  2677. WCHAR szIntFormat[] = L"%08x";
  2678. #else
  2679. WCHAR szIntFormat[] = L"%016I64x";
  2680. #endif
  2681. StringCbPrintfW(wszBCC, sizeof(wszBCC), szIntFormat, ulBCCode);
  2682. StringCbPrintfW(wszBCP1, sizeof(wszBCP1), szIntFormat, ulBCP1);
  2683. StringCbPrintfW(wszBCP2, sizeof(wszBCP2), szIntFormat, ulBCP2);
  2684. StringCbPrintfW(wszBCP3, sizeof(wszBCP3), szIntFormat, ulBCP3);
  2685. StringCbPrintfW(wszBCP4, sizeof(wszBCP4), szIntFormat, ulBCP4);
  2686. StringCbPrintfA(szBlobLog, sizeof(szBlobLog),
  2687. "System Error Error code %S Parameters %S, %S, %S, %S",
  2688. wszBCC, wszBCP1, wszBCP2, wszBCP3, wszBCP4);
  2689. rgwsz[0] = wszBCC;
  2690. rgwsz[1] = wszBCP1;
  2691. rgwsz[2] = wszBCP2;
  2692. rgwsz[3] = wszBCP3;
  2693. rgwsz[4] = wszBCP4;
  2694. return LogEvent(c_wszKrnlEventSrc, ER_KRNLFAULT_CATEGORY, ER_KRNLCRASH_LOG,
  2695. 5, strlen(szBlobLog), rgwsz, szBlobLog);
  2696. }