Source code of Windows XP (NT5)
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.

3199 lines
82 KiB

  1. /*++
  2. *
  3. * WOW v1.0
  4. *
  5. * Copyright (c) 1991, Microsoft Corporation
  6. *
  7. * WOW32.C
  8. * WOW32 16-bit API support
  9. *
  10. * History:
  11. * Created 27-Jan-1991 by Jeff Parsons (jeffpar)
  12. * Multi-Tasking 23-May-1991 Matt Felton [mattfe]
  13. * WOW as DLL 06-Dec-1991 Sudeep Bharati (sudeepb)
  14. * Cleanup and rework multi tasking feb 6 (mattfe)
  15. * added notification thread for task creation mar-11 (mattfe)
  16. * added basic exception handling for retail build apr-3 92 mattfe
  17. * use host_ExitThread apr-17 92 daveh
  18. * Hung App Support june-22 82 mattfe
  19. --*/
  20. #include "precomp.h"
  21. #pragma hdrstop
  22. #include "wktbl.h"
  23. #include "wutbl.h"
  24. #include "wgtbl.h"
  25. #include "wstbl.h"
  26. #include "wkbtbl.h"
  27. #include "wshltbl.h"
  28. #include "wmmtbl.h"
  29. #include "wsocktbl.h"
  30. #include "wthtbl.h"
  31. #include "wowit.h"
  32. #include <stdarg.h>
  33. #include <ntcsrdll.h>
  34. #define SHAREWOW_MAIN
  35. #include <sharewow.h>
  36. #include <tsappcmp.h>
  37. /* Function Prototypes */
  38. DWORD W32SysErrorBoxThread2(PTDB pTDB);
  39. VOID StartDebuggerForWow(VOID);
  40. BOOLEAN LoadCriticalStringResources(void);
  41. extern DECLSPEC_IMPORT ULONG *ExpLdt;
  42. #define LDT_DESC_PRESENT 0x8000
  43. #define STD_SELECTOR_BITS 0x7
  44. MODNAME(wow32.c);
  45. #define REGISTRY_BUFFER_SIZE 512
  46. // for logging iloglevel to a file
  47. #ifdef DEBUG
  48. CHAR szLogFile[128];
  49. int fLog;
  50. HANDLE hfLog;
  51. UCHAR gszAssert[256];
  52. #endif
  53. /* iloglevel = 16 MAX the world (all 16 bit kernel internal calls
  54. * iloglevel = 14 All internal WOW kernel Calls
  55. * ilogeveel = 12 All USER GDI call + return Codes
  56. * iloglevel = 5 Returns From Calls
  57. * iloglevel = 3 Calling Parameters
  58. */
  59. INT flOptions; // command line optin
  60. #ifdef DEBUG
  61. INT iLogLevel; // logging level; 0 implies none
  62. INT fDebugWait=0; // Single Step, 0 = No single step
  63. #endif
  64. HANDLE hmodWOW32;
  65. HANDLE hHostInstance;
  66. #ifdef DEBUG
  67. INT fLogFilter = -1; // Logging Code Fiters
  68. WORD fLogTaskFilter = (WORD)-1; // Filter Logging for Specific TaskID
  69. #endif
  70. #ifdef DEBUG
  71. BOOL fSkipLog; // TRUE to temporarily skip certain logging
  72. INT iReqLogLevel; // Current Output LogLevel
  73. INT iCircBuffer = CIRC_BUFFERS-1; // Current Buffer
  74. CHAR achTmp[CIRC_BUFFERS][TMP_LINE_LEN] = {" "}; // Circular Buffer
  75. CHAR *pachTmp = &achTmp[0][0];
  76. WORD awfLogFunctionFilter[FILTER_FUNCTION_MAX] = {0xffff,0,0,0,0,0,0,0,0,0}; // Specific Filter API Array
  77. PWORD pawfLogFunctionFilter = awfLogFunctionFilter;
  78. INT iLogFuncFiltIndex; // Index Into Specific Array for Debugger Extensions
  79. #endif
  80. #ifdef DEBUG_MEMLEAK
  81. CRITICAL_SECTION csMemLeak;
  82. #endif
  83. UINT iW32ExecTaskId = (UINT)-1; // Base Task ID of Task Being Exec'd
  84. UINT nWOWTasks; // # of WOW tasks running
  85. BOOL fBoot = TRUE; // TRUE During the Boot Process
  86. HANDLE ghevWaitCreatorThread = (HANDLE)-1; // Used to Syncronize creation of a new thread
  87. BOOL fWowMode; // Flag used to determine wow mode.
  88. // currently defaults to FALSE (real mode wow)
  89. // This is used by the memory access macros
  90. // to properly form linear addresses.
  91. // When running on an x86 box, it will be
  92. // initialized to the mode the first wow
  93. // bop call is made in. This flag can go
  94. // away when we no longer want to run real
  95. // mode wow. (Daveh 7/25/91)
  96. HANDLE hSharedTaskMemory;
  97. DWORD dwSharedProcessOffset;
  98. HANDLE hWOWHeap;
  99. HANDLE ghProcess; // WOW Process Handle
  100. PFNWOWHANDLERSOUT pfnOut;
  101. PTD * pptdWOA;
  102. PTD gptdShell;
  103. DWORD fThunkStrRtns; // used as a BOOL
  104. BOOL gfDebugExceptions; // set to 1 in debugger to
  105. // enable debugging of W32Exception
  106. BOOL gfIgnoreInputAssertGiven;
  107. DWORD dwSharedWowTimeout;
  108. WORD gwKrnl386CodeSeg1; // code segs of krnl386.exe
  109. WORD gwKrnl386CodeSeg2;
  110. WORD gwKrnl386CodeSeg3;
  111. WORD gwKrnl386DataSeg1;
  112. #ifndef _X86_
  113. PUCHAR IntelMemoryBase; // Start of emulated CPU's memory
  114. #endif
  115. DWORD gpsi = 0;
  116. DWORD gpfn16GetProcModule;
  117. /* for WinFax Lite install hack -- see wow32fax.c */
  118. char szWINFAX[] = "WINFAX";
  119. char szModem[] = "modem";
  120. char szINSTALL[] = "INSTALL";
  121. char szWINFAXCOMx[80];
  122. BOOL gbWinFaxHack = FALSE;
  123. #define TOOLONGLIMIT _MAX_PATH
  124. #define WARNINGMSGLENGTH 255
  125. PSZ aszCriticalStrings[CRITICAL_STRING_COUNT];
  126. char szEmbedding[] = "embedding";
  127. char szDevices[] = "devices";
  128. char szBoot[] = "boot";
  129. char szShell[] = "shell";
  130. char szServerKey[] = "protocol\\StdFileEditing\\server";
  131. char szPicture[] = "picture";
  132. char szPostscript[] = "postscript";
  133. char szZapfDingbats[] = "ZAPFDINGBATS";
  134. char szZapf_Dingbats[] = "ZAPF DINGBATS";
  135. char szSymbol[] = "SYMBOL";
  136. char szTmsRmn[] = "TMS RMN";
  137. char szHelv[] = "HELV";
  138. char szMavisCourier[]= "MAVIS BEACON COURIER FP";
  139. char szWinDotIni[] = "win.ini";
  140. char szSystemDotIni[] = "system.ini";
  141. char szExplorerDotExe[] = "Explorer.exe";
  142. char szDrWtsn32[] = "drwtsn32";
  143. PSTR pszWinIniFullPath;
  144. PSTR pszWindowsDirectory;
  145. PSTR pszSystemDirectory;
  146. BOOL gbDBCSEnable = FALSE;
  147. #ifdef FE_SB
  148. char szSystemMincho[] = {(char) 0xbc, (char) 0xbd, (char) 0xc3, (char) 0xd1,
  149. (char) 0x96, (char) 0xbe, (char) 0x92, (char) 0xa9,
  150. (char) 0 };
  151. char szMsMincho[] = { (char) 0x82, (char) 0x6c, (char) 0x82, (char) 0x72,
  152. (char) 0x20, (char) 0x96, (char) 0xbe, (char) 0x92,
  153. (char) 0xa9, (char) 0};
  154. #endif
  155. extern BOOL GdiReserveHandles(VOID);
  156. extern CRITICAL_SECTION VdmLoadCritSec;
  157. extern LIST_ENTRY TimerList;
  158. extern PVOID GdiQueryTable();
  159. extern PVOID gpGdiHandleInfo;
  160. #if defined (_X86_)
  161. extern PVOID WowpLockPrefixTable;
  162. IMAGE_LOAD_CONFIG_DIRECTORY _load_config_used = {
  163. 0, // Reserved
  164. 0, // Reserved
  165. 0, // Reserved
  166. 0, // Reserved
  167. 0, // GlobalFlagsClear
  168. 0, // GlobalFlagsSet
  169. 0, // CriticalSectionTimeout (milliseconds)
  170. 0, // DeCommitFreeBlockThreshold
  171. 0, // DeCommitTotalFreeThreshold
  172. (LONG) &WowpLockPrefixTable, // LockPrefixTable, defined in FASTWOW.ASM
  173. 0, 0, 0, 0, 0, 0, 0 // Reserved
  174. };
  175. #endif
  176. PVOID pfnGetVersionExA; // Used with Version Lie hack. Function pointer to GetVersionExA
  177. // See WK32GetProcAddress32W in wkgthunk.c
  178. PVOID pfnCreateDirectoryA; // Used with GtCompCreateDirectoryA in wkgthunk.c
  179. PVOID pfnLoadLibraryA; // Used with GtCompLoadLibraryA in wkgthunk.c
  180. BOOLEAN
  181. W32DllInitialize(
  182. IN PVOID DllHandle,
  183. IN ULONG Reason,
  184. IN PCONTEXT Context OPTIONAL
  185. )
  186. /*++
  187. Routine Description: DllMain function called during ntvdm's
  188. LoadLibrary("wow32")
  189. Arguments:
  190. DllHandle - set global hmodWOW32
  191. Reason - Attach or Detach
  192. Context - Not Used
  193. Return Value:
  194. STATUS_SUCCESS
  195. --*/
  196. {
  197. HMODULE hKrnl32dll;
  198. UNREFERENCED_PARAMETER(Context);
  199. hmodWOW32 = DllHandle;
  200. switch ( Reason ) {
  201. case DLL_PROCESS_ATTACH:
  202. if (!CreateSmallHeap()) {
  203. return FALSE;
  204. }
  205. if ((hWOWHeap = HeapCreate (0,
  206. INITIAL_WOW_HEAP_SIZE,
  207. GROW_HEAP_AS_NEEDED)) == NULL)
  208. return FALSE;
  209. // initialize hook stubs data.
  210. W32InitHookState(hmodWOW32);
  211. // initialize the thunk table offsets. do it here so the debug process
  212. // gets them.
  213. InitThunkTableOffsets();
  214. //
  215. // initialization for named pipe handling in file thunks
  216. //
  217. InitializeCriticalSection(&VdmLoadCritSec);
  218. //
  219. // Load Critical Error Strings
  220. //
  221. if (!LoadCriticalStringResources()) {
  222. MessageBox(NULL, "The Win16 subsystem could not load critical string resources from wow32.dll, terminating.",
  223. "Win16 subsystem load failure", MB_ICONEXCLAMATION | MB_OK);
  224. return FALSE;
  225. }
  226. //
  227. // setup the GDI table for handle conversion
  228. //
  229. gpGdiHandleInfo = GdiQueryTable();
  230. W32EWExecer();
  231. InitializeListHead(&TimerList);
  232. if (IsTerminalServer()) {
  233. //
  234. // Load tsappcmp.dll
  235. //
  236. HANDLE dllHandle = LoadLibrary (TEXT("tsappcmp.dll"));
  237. if (dllHandle) {
  238. gpfnTermsrvCORIniFile = (PTERMSRVCORINIFILE) GetProcAddress(
  239. dllHandle,
  240. "TermsrvCORIniFile"
  241. );
  242. ASSERT(gpfnTermsrvCORIniFile != NULL);
  243. }
  244. }
  245. //
  246. // WHISTLER RAID BUG 366613
  247. // Used for redirecting WK32GetProcAddress32W call on GetVersionExA
  248. //
  249. hKrnl32dll = GetModuleHandle("Kernel32.dll");
  250. if(hKrnl32dll)
  251. {
  252. pfnGetVersionExA = GetProcAddress(hKrnl32dll, "GetVersionExA");
  253. pfnCreateDirectoryA = GetProcAddress(hKrnl32dll, "CreateDirectoryA");
  254. pfnLoadLibraryA = GetProcAddress(hKrnl32dll, "LoadLibraryA");
  255. }
  256. break;
  257. case DLL_THREAD_ATTACH:
  258. IsDebuggerAttached(); // Yes, this routine has side-effects.
  259. break;
  260. case DLL_THREAD_DETACH:
  261. break;
  262. case DLL_PROCESS_DETACH:
  263. /*
  264. * Tell base he can nolonger callback to us.
  265. */
  266. RegisterWowBaseHandlers(NULL);
  267. DeleteCriticalSection(&VdmLoadCritSec);
  268. HeapDestroy (hWOWHeap);
  269. break;
  270. default:
  271. break;
  272. }
  273. return TRUE;
  274. }
  275. BOOLEAN
  276. LoadCriticalStringResources(
  277. void
  278. )
  279. /*++
  280. Routine Description: Loads strings we want around even if we can't allocate
  281. memory. Called during wow32 DLL load.
  282. Arguments:
  283. none
  284. Return Value:
  285. TRUE if all strings loaded and aszCriticalStrings initialized.
  286. --*/
  287. {
  288. int i, n;
  289. PSZ psz, pszStringBuffer;
  290. DWORD cbTotal;
  291. DWORD cbUsed;
  292. DWORD cbStrLen;
  293. DWORD rgdwStringOffset[CRITICAL_STRING_COUNT];
  294. //
  295. // Allocate too much memory for strings (maximum possible) at first,
  296. // reallocate to the real size when we're done loading strings.
  297. //
  298. cbTotal = CRITICAL_STRING_COUNT * CCH_MAX_STRING_RESOURCE;
  299. psz = pszStringBuffer = malloc_w(cbTotal);
  300. if ( ! psz ) {
  301. return FALSE;
  302. }
  303. cbUsed = 0;
  304. for ( n = 0; n < CRITICAL_STRING_COUNT; n++ ) {
  305. //
  306. // LoadString return value doesn't count null terminator.
  307. //
  308. cbStrLen = LoadString(hmodWOW32, n, psz, CCH_MAX_STRING_RESOURCE);
  309. if ( ! cbStrLen ) {
  310. return FALSE;
  311. }
  312. rgdwStringOffset[n] = cbUsed;
  313. psz += cbStrLen + 1;
  314. cbUsed += cbStrLen + 1;
  315. }
  316. // Now, alloc a smaller buffer of the correct size
  317. // Note: HeapRealloc(IN_PLACE) won't work because allocations are
  318. // page-sorted by size -- meaning that changing the size will cause
  319. // the memory to move to a new page.
  320. psz = malloc_w(cbUsed);
  321. // copy the strings into the smaller buffer
  322. // if we can't alloc the smaller buffer, just go with the big one
  323. if (psz) {
  324. RtlCopyMemory(psz, pszStringBuffer, cbUsed);
  325. free_w(pszStringBuffer);
  326. pszStringBuffer = psz;
  327. }
  328. // save the offsets in the critical string array
  329. for (i = 0; i < n; i++) {
  330. aszCriticalStrings[i] = pszStringBuffer + rgdwStringOffset[i];
  331. }
  332. return TRUE;
  333. }
  334. //***************************************************************************
  335. // Continues ExitWindowsExec api call after logoff and subsequent logon
  336. // Uses Events to synchronize across all wow vdms
  337. //
  338. //***************************************************************************
  339. BOOL W32EWExecer(VOID)
  340. {
  341. STARTUPINFO StartupInfo;
  342. PROCESS_INFORMATION ProcessInformation;
  343. BOOL CreateProcessStatus;
  344. BYTE abT[REGISTRY_BUFFER_SIZE];
  345. if (W32EWExecData(EWEXEC_QUERY, (LPSTR)abT, sizeof(abT))) {
  346. HANDLE hevT;
  347. if (hevT = CreateEvent(NULL, TRUE, FALSE, WOWSZ_EWEXECEVENT)) {
  348. if (GetLastError() == 0) {
  349. W32EWExecData(EWEXEC_DEL, (LPSTR)NULL, 0);
  350. LOGDEBUG(0, ("WOW:Execing dos app - %s\r\n", abT));
  351. RtlZeroMemory((PVOID)&StartupInfo, (DWORD)sizeof(StartupInfo));
  352. StartupInfo.cb = sizeof(StartupInfo);
  353. StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
  354. StartupInfo.wShowWindow = SW_NORMAL;
  355. CreateProcessStatus = CreateProcess(
  356. NULL,
  357. abT,
  358. NULL, // security
  359. NULL, // security
  360. FALSE, // inherit handles
  361. CREATE_NEW_CONSOLE | CREATE_DEFAULT_ERROR_MODE,
  362. NULL, // environment strings
  363. NULL, // current directory
  364. &StartupInfo,
  365. &ProcessInformation
  366. );
  367. if (CreateProcessStatus) {
  368. WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
  369. CloseHandle( ProcessInformation.hProcess );
  370. CloseHandle( ProcessInformation.hThread );
  371. }
  372. SetEvent(hevT);
  373. }
  374. else {
  375. WaitForSingleObject(hevT, INFINITE);
  376. }
  377. CloseHandle(hevT);
  378. }
  379. }
  380. return 0;
  381. }
  382. //***************************************************************************
  383. // W32EWExecData -
  384. // sets/resets the 'commandline', ie input to ExitWindowssExec api in the
  385. // registry - 'WOW' key 'EWExec' value
  386. //
  387. //***************************************************************************
  388. BOOL W32EWExecData(DWORD fnid, LPSTR lpData, DWORD cb)
  389. {
  390. BOOL bRet = FALSE;
  391. BYTE abT[REGISTRY_BUFFER_SIZE];
  392. switch (fnid) {
  393. case EWEXEC_SET:
  394. bRet = WriteProfileString(WOWSZ_EWEXECVALUE,
  395. WOWSZ_EWEXECVALUE,
  396. lpData);
  397. break;
  398. case EWEXEC_DEL:
  399. bRet = WriteProfileString(WOWSZ_EWEXECVALUE,
  400. NULL, NULL);
  401. break;
  402. case EWEXEC_QUERY:
  403. if (bRet = GetProfileString(WOWSZ_EWEXECVALUE,
  404. WOWSZ_EWEXECVALUE,
  405. "", abT, sizeof(abT))) {
  406. strcpy(lpData, abT);
  407. }
  408. break;
  409. default:
  410. WOW32ASSERT(FALSE);
  411. break;
  412. }
  413. return !!bRet;
  414. }
  415. /* W32Init - Initialize WOW support
  416. *
  417. * ENTRY
  418. *
  419. * EXIT
  420. * TRUE if successful, FALSE if not
  421. */
  422. BOOL W32Init(BOOL fMEoW)
  423. {
  424. HKEY WowKey;
  425. #ifdef DEBUG
  426. CHAR WOWCmdLine[REGISTRY_BUFFER_SIZE];
  427. PCHAR pWOWCmdLine;
  428. ULONG WOWCmdLineSize = REGISTRY_BUFFER_SIZE;
  429. #endif
  430. DWORD cb;
  431. DWORD dwType;
  432. PTD ptd;
  433. PFNWOWHANDLERSIN pfnIn;
  434. LPVOID lpSharedTaskMemory;
  435. LANGID LangID;
  436. UNREFERENCED_PARAMETER(fMEoW);
  437. #ifndef _X86_
  438. //
  439. // This is the one and only call to Sim32GetVDMPointer in WOW32.
  440. // All other cases should use WOWGetVDMPointer. This one is necessary
  441. // to set up the base memory address used by GetRModeVDMPointerMacro.
  442. // (There's also a call in GetPModeVDMPointerAssert, but that's in
  443. // the checked build only and only as a fallback mechanism.)
  444. //
  445. IntelMemoryBase = Sim32GetVDMPointer(0,0,0);
  446. #endif
  447. fWowMode = ((getMSW() & MSW_PE) ? TRUE : FALSE);
  448. // Boost the HourGlass
  449. ShowStartGlass(10000);
  450. LangID = GetSystemDefaultLangID();
  451. if (PRIMARYLANGID(LangID) == LANG_JAPANESE ||
  452. PRIMARYLANGID(LangID) == LANG_KOREAN ||
  453. PRIMARYLANGID(LangID) == LANG_CHINESE ) {
  454. gbDBCSEnable = TRUE;
  455. }
  456. //
  457. // Set up a global WindowsDirectory to be used by other WOW functions.
  458. //
  459. {
  460. char szBuf[ MAX_PATH ];
  461. int cb;
  462. GetSystemDirectory(szBuf, sizeof szBuf);
  463. GetShortPathName(szBuf, szBuf, sizeof szBuf);
  464. cb = strlen(szBuf) + 1;
  465. pszSystemDirectory = malloc_w_or_die(cb);
  466. RtlCopyMemory(pszSystemDirectory, szBuf, cb);
  467. if(!GetWindowsDirectory(szBuf, sizeof szBuf) ) {
  468. WOW32ASSERTMSG(FALSE, "WOW32: couldnt get windows directory, terminating.\n");
  469. WOWStartupFailed(); // never returns.
  470. }
  471. GetShortPathName(szBuf, szBuf, sizeof szBuf);
  472. cb = strlen(szBuf) + 1;
  473. pszWindowsDirectory = malloc_w_or_die(cb);
  474. RtlCopyMemory(pszWindowsDirectory, szBuf, cb);
  475. pszWinIniFullPath = malloc_w_or_die(cb + 8); // "\win.ini"
  476. RtlCopyMemory(pszWinIniFullPath, szBuf, cb);
  477. pszWinIniFullPath[ cb - 1 ] = '\\';
  478. RtlCopyMemory(pszWinIniFullPath + cb, szWinDotIni, 8);
  479. }
  480. // Give USER32 our entry points
  481. RtlZeroMemory(&pfnIn, sizeof(pfnIn));
  482. pfnIn.pfnLocalAlloc = W32LocalAlloc;
  483. pfnIn.pfnLocalReAlloc = W32LocalReAlloc;
  484. pfnIn.pfnLocalLock = W32LocalLock;
  485. pfnIn.pfnLocalUnlock = W32LocalUnlock;
  486. pfnIn.pfnLocalSize = W32LocalSize;
  487. pfnIn.pfnLocalFree = W32LocalFree;
  488. pfnIn.pfnGetExpWinVer = W32GetExpWinVer;
  489. pfnIn.pfn16GlobalAlloc = W32GlobalAlloc16;
  490. pfnIn.pfn16GlobalFree = W32GlobalFree16;
  491. pfnIn.pfnEmptyCB = W32EmptyClipboard;
  492. pfnIn.pfnFindResourceEx = W32FindResource;
  493. pfnIn.pfnLoadResource = W32LoadResource;
  494. pfnIn.pfnFreeResource = W32FreeResource;
  495. pfnIn.pfnLockResource = W32LockResource;
  496. pfnIn.pfnUnlockResource = W32UnlockResource;
  497. pfnIn.pfnSizeofResource = W32SizeofResource;
  498. pfnIn.pfnWowWndProcEx = (PFNWOWWNDPROCEX)W32Win16WndProcEx;
  499. pfnIn.pfnWowDlgProcEx = (PFNWOWDLGPROCEX)W32Win16DlgProcEx;
  500. pfnIn.pfnWowEditNextWord = W32EditNextWord;
  501. pfnIn.pfnWowCBStoreHandle = WU32ICBStoreHandle;
  502. pfnIn.pfnGetProcModule16 = WOWGetProcModule16;
  503. pfnIn.pfnWowMsgBoxIndirectCallback = WowMsgBoxIndirectCallback;
  504. pfnIn.pfnWowIlstrsmp = WOWlstrcmp16;
  505. pfnIn.pfnWOWTellWOWThehDlg = WOWTellWOWThehDlg;
  506. pfnIn.pfnWowTask16SchedNotify = NULL;
  507. gpsi = UserRegisterWowHandlers(&pfnIn, &pfnOut);
  508. RegisterWowBaseHandlers(W32DDEFreeGlobalMem32);
  509. // Prepare us to be in the shared memory process list
  510. lpSharedTaskMemory = LOCKSHAREWOW();
  511. WOW32ASSERTMSG(lpSharedTaskMemory, "WOW32: Could not access shared memory object\n");
  512. if ( lpSharedTaskMemory ) {
  513. UNLOCKSHAREWOW();
  514. }
  515. CleanseSharedList();
  516. AddProcessSharedList();
  517. // Allocate a Temporary TD for the first thread
  518. ptd = CURRENTPTD() = malloc_w_or_die(sizeof(TD));
  519. RtlZeroMemory(ptd, sizeof(*ptd));
  520. InitializeCriticalSection(&ptd->csTD);
  521. // Create Global Wait Event - Used During Task Creation To Syncronize with New Thread
  522. if (!(ghevWaitCreatorThread = CreateEvent(NULL, FALSE, FALSE, NULL))) {
  523. LOGDEBUG(0,(" W32INIT ERROR: event creation failure\n"));
  524. return FALSE;
  525. }
  526. if (RegOpenKeyEx ( HKEY_LOCAL_MACHINE,
  527. "SYSTEM\\CurrentControlSet\\Control\\WOW",
  528. 0,
  529. KEY_QUERY_VALUE,
  530. &WowKey
  531. ) != 0){
  532. LOGDEBUG(0,(" W32INIT ERROR: Registry Opening failed\n"));
  533. return FALSE;
  534. }
  535. //
  536. // If present, read the SharedWowTimeout value and convert
  537. // from seconds to milliseconds, which is what SetTimer
  538. // uses. Maximum interval for SetTimer is 0x7fffffff.
  539. // No need to enforce a minimum, as SetTimer treats a
  540. // zero timeout as a one millsecond timeout.
  541. //
  542. cb = sizeof(dwSharedWowTimeout);
  543. if ( ! RegQueryValueEx(WowKey,
  544. "SharedWowTimeout",
  545. NULL,
  546. &dwType,
  547. (LPBYTE) &dwSharedWowTimeout,
  548. &cb) && REG_DWORD == dwType) {
  549. //
  550. // Prevent overflow in the conversion to millseconds below.
  551. // This caps the timeout to 2,147,483 seconds, or 24.8 days.
  552. //
  553. dwSharedWowTimeout = min( dwSharedWowTimeout,
  554. (0x7fffffff / 1000) );
  555. } else {
  556. //
  557. // Didn't find SharedWowTimeout value or it's the wrong type.
  558. //
  559. dwSharedWowTimeout = 1 * 60 * 60; // 1 hour in seconds
  560. }
  561. dwSharedWowTimeout *= 1000;
  562. //
  563. // If present (it usually isn't) read ThunkNLS value entry.
  564. //
  565. cb = sizeof(fThunkStrRtns);
  566. if (RegQueryValueEx(WowKey,
  567. "ThunkNLS",
  568. NULL,
  569. &dwType,
  570. (LPBYTE) &fThunkStrRtns,
  571. &cb) || dwType != REG_DWORD) {
  572. //
  573. // Didn't find the registry value or it's the wrong type,
  574. // so we use the default behavior which is to thunk outside the
  575. // US.
  576. //
  577. fThunkStrRtns = GetSystemDefaultLCID() !=
  578. MAKELCID(
  579. MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  580. SORT_DEFAULT
  581. );
  582. } else {
  583. //
  584. // We did find a ThunkNLS value in the registry, warn on debug builds
  585. // to save testers and developers who turn it on for one bug but forget
  586. // to turn it back off.
  587. //
  588. #ifdef DEBUG
  589. OutputDebugString("WOW Warning: ThunkNLS registry value overriding default NLS tranlation.\n");
  590. #endif
  591. }
  592. #ifdef DEBUG
  593. if (RegQueryValueEx (WowKey,
  594. "wowcmdline",
  595. NULL,
  596. &dwType,
  597. (LPBYTE)&WOWCmdLine,
  598. &WOWCmdLineSize) != 0){
  599. RegCloseKey (WowKey);
  600. LOGDEBUG(0,(" W32INIT ERROR: WOWCMDLINE not found in registry\n"));
  601. return FALSE;
  602. }
  603. pWOWCmdLine = (PCHAR)((PBYTE)WOWCmdLine + WOWCmdLineSize + 1);
  604. WOWCmdLineSize = REGISTRY_BUFFER_SIZE - WOWCmdLineSize -1;
  605. if (WOWCmdLineSize < (REGISTRY_BUFFER_SIZE / 2)){
  606. LOGDEBUG(0,(" W32INIT ERROR: Registry Buffer too small\n"));
  607. return FALSE;
  608. }
  609. if (ExpandEnvironmentStrings ((LPCSTR)WOWCmdLine, (LPSTR)pWOWCmdLine, WOWCmdLineSize) >
  610. WOWCmdLineSize) {
  611. LOGDEBUG(0,(" W32INIT ERROR: Registry Buffer too small\n"));
  612. return FALSE;
  613. }
  614. // Find Debug Info
  615. while (*pWOWCmdLine) {
  616. if (*pWOWCmdLine == '-' || *pWOWCmdLine == '/') {
  617. // c = (char)tolower(*++pWOWCmdLine);
  618. switch(*++pWOWCmdLine) {
  619. case 'd':
  620. case 'D':
  621. flOptions |= OPT_DEBUG;
  622. break;
  623. case 'n':
  624. case 'N':
  625. flOptions |= OPT_BREAKONNEWTASK;
  626. break;
  627. case 'l':
  628. case 'L':
  629. iLogLevel = atoi(++pWOWCmdLine);
  630. break;
  631. default:
  632. break;
  633. }
  634. }
  635. pWOWCmdLine++;
  636. }
  637. if (iLogLevel > 0) {
  638. if (!(flOptions & OPT_DEBUG))
  639. if (!(OPENLOG()))
  640. iLogLevel = 0;
  641. }
  642. else
  643. iLogLevel = 0;
  644. #endif
  645. //
  646. // Initialize list of known DLLs used by WK32WowIsKnownDLL
  647. // from the registry.
  648. //
  649. WK32InitWowIsKnownDLL(WowKey);
  650. RegCloseKey (WowKey);
  651. //
  652. // Initialize param mapping cache
  653. //
  654. //
  655. InitParamMap();
  656. //
  657. // Set our GDI batching limit from win.ini. This is useful for SGA and
  658. // other performance measurements which require each API to do its own
  659. // work. To set the batching size to 1, which is most common, put the
  660. // following in win.ini:
  661. //
  662. // [WOW]
  663. // BatchLimit=1
  664. //
  665. // or using ini:
  666. //
  667. // ini WOW.BatchLimit = 1
  668. //
  669. // Note that this code only changes the batch limit if the above
  670. // line is in win.ini, otherwise we use default batching. It's
  671. // important that this code be in the free build to be useful.
  672. //
  673. {
  674. extern DWORD dwWOWBatchLimit; // declared in wkman.c
  675. dwWOWBatchLimit = GetProfileInt("WOW", // section
  676. "BatchLimit", // key
  677. 0 // default if not found
  678. );
  679. }
  680. ghProcess = NtCurrentProcess();
  681. #ifdef DEBUG
  682. #ifdef i386
  683. if (IsDebuggerAttached()) {
  684. if (GetProfileInt("WOWDebug", "debugbreaks", 0))
  685. *pNtVDMState |= VDM_BREAK_DEBUGGER;
  686. if (GetProfileInt("WOWDebug", "exceptions", 0))
  687. *pNtVDMState |= VDM_BREAK_EXCEPTIONS;
  688. }
  689. #endif
  690. if (IsDebuggerAttached() && (flOptions & OPT_BREAKONNEWTASK)) {
  691. OutputDebugString("\nW32Init - Initialization Complete, Set any Breakpoints Now, type g to continue\n\n");
  692. DbgBreakPoint();
  693. }
  694. #endif
  695. // Initialize ClipBoard formats structure.
  696. InitCBFormats ();
  697. // This is to initialize the InquireVisRgn for FileMaker Pro 2.0
  698. // InquireVisRgn is an undocumented API Win 3.1 API.
  699. InitVisRgn();
  700. // HUNG APP SUPPORT
  701. if (!WK32InitializeHungAppSupport()) {
  702. LOGDEBUG(LOG_ALWAYS, ("W32INIT Error: InitializeHungAppSupport Failed"));
  703. return FALSE;
  704. }
  705. SetPriorityClass(ghProcess, NORMAL_PRIORITY_CLASS);
  706. #ifdef DEBUG_MEMLEAK
  707. // for memory leak support
  708. InitializeCriticalSection(&csMemLeak);
  709. #endif
  710. // 9x Special Path Map Initialization
  711. // i.e. c:\winnt\startm~1 will be c:\documents and settings\all users\start menu
  712. W32Init9xSpecialPath();
  713. return TRUE;
  714. }
  715. /* Thunk Dispatch Table
  716. *
  717. * see fastwow.h for instructions on how to create a new thunk table
  718. *
  719. */
  720. #ifdef DEBUG_OR_WOWPROFILE
  721. PA32 awThunkTables[] = {
  722. {W32TAB(aw32WOW, "All ", cAPIThunks)}
  723. };
  724. #endif
  725. #ifdef DEBUG_OR_WOWPROFILE // define symbols for API profiling only (debugger extension)
  726. INT iThunkTableMax = NUMEL(awThunkTables);
  727. PPA32 pawThunkTables = awThunkTables;
  728. #endif // WOWPROFILE
  729. /* WOW32UnimplementedAPI - Error Thunk is Not Implemented
  730. *
  731. * Stub thunk table entry for all unimplemented APIs on
  732. * the checked build, and on the free build NOPAPI and
  733. * LOCALAPI entries point here as well.
  734. *
  735. * ENTRY
  736. *
  737. * EXIT
  738. *
  739. */
  740. ULONG FASTCALL WOW32UnimplementedAPI(PVDMFRAME pFrame)
  741. {
  742. #ifdef DEBUG
  743. INT iFun;
  744. iFun = pFrame->wCallID;
  745. LOGDEBUG(2,("WOW32: Warning! %s: Function %i %s is not implemented.\n",
  746. GetModName(iFun),
  747. GetOrdinal(iFun),
  748. aw32WOW[iFun].lpszW32
  749. ));
  750. //
  751. // After complaining once about each API, patch the thunk table so
  752. // future calls to the API will (mostly) silently slip by in WOW32NopAPI.
  753. //
  754. aw32WOW[iFun].lpfnW32 = WOW32NopAPI;
  755. #else
  756. UNREFERENCED_PARAMETER(pFrame);
  757. #endif
  758. return FALSE;
  759. }
  760. #ifdef DEBUG
  761. /* WOW32Unimplemented95API - Error Thunk is Not Implemented
  762. *
  763. * Stub thunk table entry for Win95 unimplemented APIs on
  764. * the checked build, and for now on the free build as well.
  765. *
  766. * ENTRY
  767. *
  768. * EXIT
  769. *
  770. */
  771. ULONG FASTCALL WOW32Unimplemented95API(PVDMFRAME pFrame)
  772. {
  773. INT iFun;
  774. iFun = pFrame->wCallID;
  775. WOW32ASSERTMSGF (FALSE, ("New-for-Win95/NT5 %s API %s #%i not implemented, contact DaveHart.\n",
  776. GetModName(iFun),
  777. aw32WOW[iFun].lpszW32,
  778. GetOrdinal(iFun)
  779. ));
  780. //
  781. // After complaining once about each API, patch the thunk table so
  782. // future calls to the API will silently slip by.
  783. //
  784. aw32WOW[iFun].lpfnW32 = NOPAPI;
  785. return FALSE;
  786. }
  787. /* WOW32NopAPI - Thunk to do nothing - checked build only.
  788. *
  789. * All Function tables point here for APIs which should do nothing.
  790. *
  791. * ENTRY
  792. *
  793. * EXIT
  794. *
  795. */
  796. ULONG FASTCALL WOW32NopAPI(PVDMFRAME pFrame)
  797. {
  798. INT iFun;
  799. iFun = pFrame->wCallID;
  800. LOGDEBUG(4,("%s: Function %i %s is NOP'd\n", GetModName(iFun), GetOrdinal(iFun), aw32WOW[iFun].lpszW32));
  801. return FALSE;
  802. }
  803. /* WOW32LocalAPI - ERROR Should Have Been Handled in 16 BIT
  804. * Checked build only
  805. *
  806. * All Function tables point here for Local API Error Messages
  807. *
  808. * ENTRY
  809. * Module startup registers:
  810. *
  811. * EXIT
  812. *
  813. *
  814. */
  815. ULONG FASTCALL WOW32LocalAPI(PVDMFRAME pFrame)
  816. {
  817. INT iFun;
  818. iFun = pFrame->wCallID;
  819. WOW32ASSERTMSGF (FALSE, ("Error - %s: Function %i %s should be handled by 16-bit code\n",
  820. GetModName(iFun),
  821. GetOrdinal(iFun),
  822. aw32WOW[iFun].lpszW32
  823. ));
  824. return FALSE;
  825. }
  826. #endif // DEBUG
  827. LPFNW32 FASTCALL W32PatchCodeWithLpfnw32(PVDMFRAME pFrame , LPFNW32 lpfnW32 )
  828. {
  829. VPVOID vpCode;
  830. LPBYTE lpCode;
  831. #ifdef DEBUG
  832. INT iFun = pFrame->wCallID;
  833. #endif
  834. #ifdef DEBUG_OR_WOWPROFILE
  835. //
  836. // On checked builds do not patch calls to the 4 special
  837. // thunks above, since many entries will point to each one,
  838. // the routines could not easily distinguish which 16-bit
  839. // entrypoint was called.
  840. //
  841. if (flOptions & OPT_DONTPATCHCODE ||
  842. lpfnW32 == UNIMPLEMENTEDAPI ||
  843. lpfnW32 == UNIMPLEMENTED95API ||
  844. lpfnW32 == NOPAPI ||
  845. lpfnW32 == LOCALAPI ) {
  846. goto Done;
  847. }
  848. #endif
  849. //
  850. // just return the thunk function if called in real mode
  851. //
  852. if (!fWowMode) {
  853. goto Done;
  854. }
  855. // the thunk looks like so.
  856. //
  857. // push HI_WCALLID (3bytes) - 0th byte is opcode.
  858. // push 0xfnid (3bytes)
  859. // call wow16call (5bytes)
  860. // ThunksCSIP:
  861. //
  862. // point to the 1st word (the hiword)
  863. vpCode = (DWORD)pFrame->wThunkCSIP - (0x5 + 0x3 + 0x2);
  864. WOW32ASSERT(HI_WCALLID == 0); // we need to revisit wow32.c if this
  865. // value is changed to a non-zero value
  866. WOW32ASSERT(HIWORD(iFun) == HI_WCALLID);
  867. GETVDMPTR(vpCode, 0x2 + 0x3, lpCode);
  868. WOW32ASSERT(lpCode != NULL);
  869. WOW32ASSERT(*(PWORD16)(lpCode) == HIWORD(iFun));
  870. WOW32ASSERT(*(PWORD16)(lpCode+0x3) == LOWORD(iFun));
  871. *((PWORD16)lpCode) = HIWORD((DWORD)lpfnW32);
  872. lpCode += 0x3; // seek to the 2nd word (the loword)
  873. *((PWORD16)lpCode) = LOWORD((DWORD)lpfnW32);
  874. FLUSHVDMCODEPTR(vpCode, 0x2 + 0x3, lpCode);
  875. FREEVDMPTR(lpCode);
  876. Done:
  877. return lpfnW32;
  878. }
  879. /* W32Dispatch - Recipient of all WOW16 API calls (sort of)
  880. *
  881. * "sort of" means that the word "all" above hasn't been true since 8/93:
  882. * 1. Most calls to the 16-bit kernel are handled by krnl386.exe on the
  883. * 16-bit side (this has always been true).
  884. * 2. There are several User API's that are thunked on the 16-bit side by
  885. * User32.dll code on x86 platforms.
  886. * 3. A FEW (only MulDiv?) GDI API's are thunked by GDI.exe in 16-bit land.
  887. * 4. On CHECKED x86 builds & ALL RISC builds, all API's not subject to the
  888. * above exceptions are dispatched through this function.
  889. * 5. On x86 FREE platforms, API calls are dispatched from fastwow.asm
  890. * - That's about it -- until we change it again, in which case this note
  891. * could be terribly misleading. cmjones 10/08/97
  892. *
  893. * Having said that:
  894. * This routine dispatches to the relavant WOW thunk routine via
  895. * jump tables wktbl.c wutbl.c wgtbl.c based on a function id on the 16 bit
  896. * stack.
  897. *
  898. * In debug versions it also calls routines to log parameters.
  899. *
  900. * ENTRY
  901. * None (x86 registers contain parameters)
  902. *
  903. * EXIT
  904. * None (x86 registers/memory updated appropriately)
  905. */
  906. VOID W32Dispatch()
  907. {
  908. INT iFun;
  909. ULONG ulReturn;
  910. DWORD dwThunkCSIP;
  911. VPVOID vpCurrentStack;
  912. register PTD ptd;
  913. register PVDMFRAME pFrame;
  914. #ifdef DEBUG_OR_WOWPROFILE
  915. INT iFunT;
  916. #endif
  917. #ifdef WOWPROFILE
  918. DWORD dwTics;
  919. #endif
  920. //
  921. // WARNING: DO NOT ADD ANYTHING TO THIS FUNCTION UNLESS YOU ADD THE SAME
  922. // STUFF TO i386/FastWOW.asm. i386/FastWOW.ASM is used for speedy
  923. // thunk dispatching on retail builds.
  924. //
  925. try {
  926. //
  927. // if we get here then even if we're going to be fastbopping
  928. // then the faststack stuff must not be enabled yet. that's why
  929. // there's no #if FASTBOPPING for this fetching of the vdmstack
  930. //
  931. vpCurrentStack = VDMSTACK(); // Get 16 bit ss:sp
  932. // Use WOWGetVDMPointer here since we can get called in RealMode on
  933. // Errors
  934. pFrame = WOWGetVDMPointer(vpCurrentStack, sizeof(VDMFRAME), fWowMode);
  935. ptd = CURRENTPTD(); // Setup Task Pointer
  936. ptd->vpStack = vpCurrentStack; // Save 16 bit ss:sp
  937. // ssync 16-bit & 32-bit common dialog structs (see wcommdlg.c)
  938. if(ptd->CommDlgTd) {
  939. dwThunkCSIP = (DWORD)(pFrame->wThunkCSIP);
  940. Ssync_WOW_CommDlg_Structs(ptd->CommDlgTd, w16to32, dwThunkCSIP);
  941. }
  942. WOW32ASSERT( FIELD_OFFSET(TD,vpStack) == 0 );
  943. LOGARGS(3,pFrame); // Perform Function Logging
  944. iFun = pFrame->wCallID;
  945. #ifdef DEBUG_OR_WOWPROFILE
  946. iFunT = ISFUNCID(iFun) ? iFun : GetFuncId(iFun) ;
  947. #endif
  948. if (ISFUNCID(iFun)) {
  949. #ifdef DEBUG
  950. if (cAPIThunks && iFunT >= cAPIThunks) {
  951. LOGDEBUG(LOG_ALWAYS,("W32Dispatch: Task %04x thunked to function %d, cAPIThunks = %d.\n",
  952. pFrame->wTDB, iFunT, cAPIThunks));
  953. WOW32ASSERT(FALSE);
  954. }
  955. #endif
  956. iFun = (INT)aw32WOW[iFun].lpfnW32;
  957. if ( ! HIWORD(iFun)) {
  958. #ifdef WOWPROFILE // For API profiling only (debugger extension)
  959. dwTics = GetWOWTicDiff(0L);
  960. #endif // WOWPROFILE
  961. ulReturn = InterpretThunk(pFrame, iFun);
  962. goto AfterApiCall;
  963. } else {
  964. W32PatchCodeWithLpfnw32(pFrame, (LPFNW32)iFun);
  965. }
  966. }
  967. #ifdef WOWPROFILE // For API profiling only (debugger extension)
  968. dwTics = GetWOWTicDiff(0L);
  969. #endif // WOWPROFILE
  970. //
  971. // WARNING: DO NOT ADD ANYTHING TO THIS FUNCTION UNLESS YOU ADD THE SAME
  972. // STUFF TO i386/FastWOW.asm. i386/FastWOW.ASM is used for speedy
  973. // thunk dispatching on retail builds.
  974. //
  975. ulReturn = (*((LPFNW32)iFun))(pFrame); // Dispatch to Thunk
  976. AfterApiCall:
  977. // ssync 16-bit & 32-bit common dialog structs (see wcommdlg.c)
  978. if(ptd->CommDlgTd) {
  979. Ssync_WOW_CommDlg_Structs(ptd->CommDlgTd, w32to16, dwThunkCSIP);
  980. }
  981. #ifdef WOWPROFILE // For API profiling only (debugger extension)
  982. dwTics = GetWOWTicDiff(dwTics);
  983. iFun = iFunT;
  984. // add time ellapsed for call to total
  985. aw32WOW[iFun].cTics += dwTics;
  986. aw32WOW[iFun].cCalls++; // inc # times this API called
  987. #endif // WOWPROFILE
  988. FREEVDMPTR(pFrame); // Set the 16-bit return code
  989. GETFRAMEPTR(ptd->vpStack, pFrame);
  990. LOGRETURN(5,pFrame,ulReturn); // Log return Values
  991. pFrame->wAX = LOW(ulReturn); // Pass Back Return Value form thunk
  992. pFrame->wDX = HIW(ulReturn);
  993. #ifdef DEBUG
  994. // If OPT_DEBUGRETURN is set, diddle the RetID as approp.
  995. if (flOptions & OPT_DEBUGRETURN) {
  996. if (pFrame->wRetID == RET_RETURN) {
  997. pFrame->wRetID = RET_DEBUGRETURN;
  998. flOptions &= ~OPT_DEBUGRETURN;
  999. }
  1000. }
  1001. // Put the current logging level where 16-bit code can get it
  1002. // Use ROMBIOS Hard DISK information as a safe address
  1003. *(PBYTE)GetVDMAddr(0x0040,0x0042) = (BYTE)(iLogLevel/10+'0');
  1004. *(PBYTE)GetVDMAddr(0x0040,0x0043) = (BYTE)(iLogLevel%10+'0');
  1005. #endif // DEBUG
  1006. FREEVDMPTR(pFrame);
  1007. SETVDMSTACK(ptd->vpStack);
  1008. } except (W32Exception(GetExceptionCode(), GetExceptionInformation())) {
  1009. }
  1010. //
  1011. // WARNING: DO NOT ADD ANYTHING TO THIS FUNCTION UNLESS YOU ADD THE SAME
  1012. // STUFF TO i386/FastWOW.asm. i386/FastWOW.ASM is used for speedy
  1013. // thunk dispatching on retail builds.
  1014. //
  1015. }
  1016. #if NO_W32TRYCALL
  1017. INT
  1018. W32FilterException(
  1019. INT ExceptionCode,
  1020. PEXCEPTION_POINTERS ExceptionInformation
  1021. )
  1022. /* W32FilterException - Filter WOW32 thread exceptions
  1023. *
  1024. * ENTRY
  1025. *
  1026. * ExceptionCode - Indicate type of exception
  1027. *
  1028. * ExceptionInformation - Supplies a pointer to ExceptionInformation
  1029. * structure.
  1030. *
  1031. * EXIT
  1032. *
  1033. * return exception disposition value.
  1034. */
  1035. {
  1036. extern BOOLEAN IsW32WorkerException(VOID);
  1037. extern VOID W32SetExceptionContext(PCONTEXT);
  1038. INT Disposition = EXCEPTION_CONTINUE_SEARCH;
  1039. if ((ExceptionCode != EXCEPTION_WOW32_ASSERTION) &&
  1040. IsW32WorkerException()) {
  1041. Disposition = W32Exception(ExceptionCode, ExceptionInformation);
  1042. if (Disposition == EXCEPTION_EXECUTE_HANDLER) {
  1043. //
  1044. // if this is the exception we want to handle, change its
  1045. // context to the point where we can safely fail the api and
  1046. // return exception disposition as continue execution.
  1047. //
  1048. W32SetExceptionContext(ExceptionInformation->ContextRecord);
  1049. Disposition = EXCEPTION_CONTINUE_EXECUTION;
  1050. }
  1051. }
  1052. return(Disposition);
  1053. }
  1054. #endif // NO_W32TRYCALL
  1055. /* W32Exception - Handle WOW32 thread exceptions
  1056. *
  1057. * ENTRY
  1058. * None (x86 registers contain parameters)
  1059. *
  1060. * EXIT
  1061. * None (x86 registers/memory updated appropriately)
  1062. *
  1063. */
  1064. INT W32Exception(DWORD dwException, PEXCEPTION_POINTERS pexi)
  1065. {
  1066. PTD ptd;
  1067. PVDMFRAME pFrame;
  1068. DWORD dwButtonPushed;
  1069. char szTask[9];
  1070. HMODULE hModule;
  1071. char szModule[_MAX_PATH + 1];
  1072. PSZ pszModuleFilePart;
  1073. PSZ pszErrorFormatString;
  1074. char szErrorMessage[TOOLONGLIMIT + 4*WARNINGMSGLENGTH];
  1075. char szDialogText[TOOLONGLIMIT + 4*WARNINGMSGLENGTH];
  1076. PTDB pTDB;
  1077. NTSTATUS Status;
  1078. HANDLE DebugPort;
  1079. PRTL_CRITICAL_SECTION PebLockPointer;
  1080. CHAR AeDebuggerCmdLine[256];
  1081. CHAR AeAutoDebugString[8];
  1082. BOOL AeAutoDebug;
  1083. WORD wDebugButton;
  1084. if (!gfDebugExceptions) {
  1085. //
  1086. // If the process is being debugged, just let the exception happen
  1087. // so that the debugger can see it. This way the debugger can ignore
  1088. // all first chance exceptions.
  1089. //
  1090. DebugPort = (HANDLE)NULL;
  1091. Status = NtQueryInformationProcess(
  1092. GetCurrentProcess(),
  1093. ProcessDebugPort,
  1094. (PVOID)&DebugPort,
  1095. sizeof(DebugPort),
  1096. NULL
  1097. );
  1098. if ( NT_SUCCESS(Status) && DebugPort) {
  1099. //
  1100. // Process is being debugged.
  1101. // Return a code that specifies that the exception
  1102. // processing is to continue
  1103. //
  1104. return EXCEPTION_CONTINUE_SEARCH;
  1105. }
  1106. }
  1107. //
  1108. // NtClose can raise exceptions if NtGlobalFlag is set for it.
  1109. // We want to ignore these exceptions if we're not being debugged,
  1110. // since the errors will be returned from the APIs and we generally
  1111. // don't have control over what handles the app closes. (Well, that's
  1112. // not true for file I/O, but it is true for RegCloseKey.)
  1113. //
  1114. if (STATUS_INVALID_HANDLE == dwException ||
  1115. STATUS_HANDLE_NOT_CLOSABLE == dwException) {
  1116. return EXCEPTION_CONTINUE_EXECUTION;
  1117. }
  1118. //
  1119. // See if a debugger has been programmed in. If so, use the
  1120. // debugger specified. If not then there is no AE Cancel support
  1121. // DEVL systems will default the debugger command line. Retail
  1122. // systems will not.
  1123. //
  1124. // The above paragraph was copied from the system exception
  1125. // popup in base. It is no longer true. On retail systems,
  1126. // AeDebug.Auto is set to 1 and AeDebug.Debugger is
  1127. // "drwtsn32 -p %ld -e %ld -g".
  1128. //
  1129. // This means if we support AeDebug for stress, customers don't see
  1130. // our exception popup and misalignment handling -- instead they get
  1131. // a nearly-useless drwtsn32.log and popup.
  1132. //
  1133. // SO, we check for this situation and act as if no debugger was
  1134. // enabled.
  1135. //
  1136. wDebugButton = 0;
  1137. AeAutoDebug = FALSE;
  1138. //
  1139. // If we are holding the PebLock, then the createprocess will fail
  1140. // because a new thread will also need this lock. Avoid this by peeking
  1141. // inside the PebLock and looking to see if we own it. If we do, then just allow
  1142. // a regular popup.
  1143. //
  1144. PebLockPointer = NtCurrentPeb()->FastPebLock;
  1145. if ( PebLockPointer->OwningThread != NtCurrentTeb()->ClientId.UniqueThread ) {
  1146. try {
  1147. if ( GetProfileString(
  1148. "AeDebug",
  1149. "Debugger",
  1150. NULL,
  1151. AeDebuggerCmdLine,
  1152. sizeof(AeDebuggerCmdLine)-1
  1153. ) ) {
  1154. wDebugButton = SEB_CANCEL;
  1155. if ( GetProfileString(
  1156. "AeDebug",
  1157. "Auto",
  1158. "0",
  1159. AeAutoDebugString,
  1160. sizeof(AeAutoDebugString)-1
  1161. ) ) {
  1162. if ( !WOW32_strcmp(AeAutoDebugString,"1") ) {
  1163. AeAutoDebug = TRUE;
  1164. }
  1165. }
  1166. }
  1167. } except (EXCEPTION_EXECUTE_HANDLER) {
  1168. wDebugButton = 0;
  1169. AeAutoDebug = FALSE;
  1170. }
  1171. }
  1172. //
  1173. // See comment above about drwtsn32
  1174. //
  1175. if (AeAutoDebug &&
  1176. !WOW32_strnicmp(AeDebuggerCmdLine, szDrWtsn32, (sizeof szDrWtsn32) - 1)) {
  1177. wDebugButton = 0;
  1178. AeAutoDebug = FALSE;
  1179. }
  1180. ptd = CURRENTPTD();
  1181. GETFRAMEPTR(ptd->vpStack, pFrame);
  1182. pTDB = (PVOID)SEGPTR(ptd->htask16,0);
  1183. //
  1184. // Get a zero-terminated copy of the Win16 task name.
  1185. //
  1186. RtlZeroMemory(szTask, sizeof(szTask));
  1187. RtlCopyMemory(szTask, pTDB->TDB_ModName, sizeof(szTask)-1);
  1188. //
  1189. // Translate exception address to module name in szModule.
  1190. //
  1191. strcpy(szModule, CRITSTR(TheWin16Subsystem));
  1192. RtlPcToFileHeader(pexi->ExceptionRecord->ExceptionAddress, (PVOID *)&hModule);
  1193. GetModuleFileName(hModule, szModule, sizeof(szModule));
  1194. pszModuleFilePart = WOW32_strrchr(szModule, '\\');
  1195. if (pszModuleFilePart) {
  1196. pszModuleFilePart++;
  1197. } else {
  1198. pszModuleFilePart = szModule;
  1199. }
  1200. //
  1201. // Format error message into szErrorMessage
  1202. //
  1203. switch (dwException) {
  1204. case EXCEPTION_ACCESS_VIOLATION:
  1205. pszErrorFormatString = CRITSTR(CausedAV);
  1206. break;
  1207. case EXCEPTION_STACK_OVERFLOW:
  1208. pszErrorFormatString = CRITSTR(CausedStackOverflow);
  1209. break;
  1210. case EXCEPTION_DATATYPE_MISALIGNMENT:
  1211. pszErrorFormatString = CRITSTR(CausedAlignmentFault);
  1212. break;
  1213. case EXCEPTION_ILLEGAL_INSTRUCTION:
  1214. case EXCEPTION_PRIV_INSTRUCTION:
  1215. pszErrorFormatString = CRITSTR(CausedIllegalInstr);
  1216. break;
  1217. case EXCEPTION_IN_PAGE_ERROR:
  1218. pszErrorFormatString = CRITSTR(CausedInPageError);
  1219. break;
  1220. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  1221. pszErrorFormatString = CRITSTR(CausedIntDivideZero);
  1222. break;
  1223. case EXCEPTION_FLT_DENORMAL_OPERAND:
  1224. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  1225. case EXCEPTION_FLT_INEXACT_RESULT:
  1226. case EXCEPTION_FLT_INVALID_OPERATION:
  1227. case EXCEPTION_FLT_OVERFLOW:
  1228. case EXCEPTION_FLT_STACK_CHECK:
  1229. case EXCEPTION_FLT_UNDERFLOW:
  1230. pszErrorFormatString = CRITSTR(CausedFloatException);
  1231. break;
  1232. default:
  1233. pszErrorFormatString = CRITSTR(CausedException);
  1234. }
  1235. wsprintf(szErrorMessage,
  1236. pszErrorFormatString,
  1237. szTask,
  1238. pszModuleFilePart,
  1239. pexi->ExceptionRecord->ExceptionAddress,
  1240. dwException
  1241. );
  1242. LOGDEBUG(LOG_ALWAYS, ("W32Exception:\n%s\n",szErrorMessage));
  1243. //
  1244. // Format dialog text into szDialogText and display.
  1245. //
  1246. if (AeAutoDebug) {
  1247. dwButtonPushed = 2;
  1248. } else {
  1249. if (wDebugButton == SEB_CANCEL) {
  1250. wsprintf(szDialogText,
  1251. "%s\n%s\n%s\n%s\n",
  1252. szErrorMessage,
  1253. CRITSTR(ChooseClose),
  1254. CRITSTR(ChooseCancel),
  1255. (dwException == EXCEPTION_DATATYPE_MISALIGNMENT)
  1256. ? CRITSTR(ChooseIgnoreAlignment)
  1257. : CRITSTR(ChooseIgnore)
  1258. );
  1259. } else {
  1260. wsprintf(szDialogText,
  1261. "%s\n%s\n%s\n",
  1262. szErrorMessage,
  1263. CRITSTR(ChooseClose),
  1264. (dwException == EXCEPTION_DATATYPE_MISALIGNMENT)
  1265. ? CRITSTR(ChooseIgnoreAlignment)
  1266. : CRITSTR(ChooseIgnore)
  1267. );
  1268. }
  1269. dwButtonPushed = WOWSysErrorBox(
  1270. CRITSTR(ApplicationError),
  1271. szDialogText,
  1272. SEB_CLOSE,
  1273. wDebugButton,
  1274. SEB_IGNORE | SEB_DEFBUTTON
  1275. );
  1276. }
  1277. //
  1278. // If CANCEL is chosen Launch Debugger.
  1279. //
  1280. if (dwButtonPushed == 2) {
  1281. BOOL b;
  1282. STARTUPINFO StartupInfo;
  1283. PROCESS_INFORMATION ProcessInformation;
  1284. CHAR CmdLine[256];
  1285. NTSTATUS Status;
  1286. HANDLE EventHandle;
  1287. SECURITY_ATTRIBUTES sa;
  1288. sa.nLength = sizeof(sa);
  1289. sa.lpSecurityDescriptor = NULL;
  1290. sa.bInheritHandle = TRUE;
  1291. EventHandle = CreateEvent(&sa,TRUE,FALSE,NULL);
  1292. RtlZeroMemory(&StartupInfo,sizeof(StartupInfo));
  1293. sprintf(CmdLine,AeDebuggerCmdLine,GetCurrentProcessId(),EventHandle);
  1294. StartupInfo.cb = sizeof(StartupInfo);
  1295. StartupInfo.lpDesktop = "Winsta0\\Default";
  1296. CsrIdentifyAlertableThread();
  1297. b = CreateProcess(
  1298. NULL,
  1299. CmdLine,
  1300. NULL,
  1301. NULL,
  1302. TRUE,
  1303. 0,
  1304. NULL,
  1305. NULL,
  1306. &StartupInfo,
  1307. &ProcessInformation
  1308. );
  1309. if ( b && EventHandle) {
  1310. //
  1311. // Do an alertable wait on the event
  1312. //
  1313. Status = NtWaitForSingleObject(
  1314. EventHandle,
  1315. TRUE,
  1316. NULL
  1317. );
  1318. return EXCEPTION_CONTINUE_SEARCH;
  1319. } else {
  1320. LOGDEBUG(0, ("W32Exception unable to start debugger.\n"));
  1321. goto KillTask;
  1322. }
  1323. }
  1324. //
  1325. // If IGNORE is chosen and it's an EXCEPTION_DATATYPE_MISALIGNMENT,
  1326. // turn on software emulation of misaligned access and restart the
  1327. // faulting instruction. Otherwise, just fail the API and continue.
  1328. //
  1329. if (dwButtonPushed == 3) {
  1330. if (dwException == EXCEPTION_DATATYPE_MISALIGNMENT) {
  1331. SetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT);
  1332. LOGDEBUG(0, ("W32Exception disabling alignment fault exceptions at user's request.\n"));
  1333. return EXCEPTION_CONTINUE_EXECUTION;
  1334. }
  1335. LOGDEBUG(0, ("W32Exception ignoring at user's request via EXCEPTION_EXECUTE_HANDLER\n"));
  1336. return EXCEPTION_EXECUTE_HANDLER;
  1337. }
  1338. //
  1339. // If user typed CLOSE or Any of the above fail,
  1340. // force just the task to die.
  1341. //
  1342. KillTask:
  1343. LOGDEBUG(0, ("W32Exception killing task via RET_FORCETASKEXIT\n"));
  1344. GETFRAMEPTR(ptd->vpStack, pFrame);
  1345. pFrame->wRetID = RET_FORCETASKEXIT;
  1346. return EXCEPTION_EXECUTE_HANDLER;
  1347. }
  1348. #ifdef DEBUG
  1349. VOID StartDebuggerForWow(VOID)
  1350. /*++
  1351. Routine Description:
  1352. This routine checks to see if there's a debugger attached to WOW. If not,
  1353. it attempts to spawn one with a command to attach to WOW. If the system
  1354. was booted with /DEBUG in boot.ini (kernel debugger enabled), we'll run
  1355. "ntsd -d" otherwise we'll run "ntsd".
  1356. Arguments:
  1357. None.
  1358. Return Value:
  1359. None.
  1360. --*/
  1361. {
  1362. BOOL fKernelDebuggerEnabled, b;
  1363. NTSTATUS Status;
  1364. SYSTEM_KERNEL_DEBUGGER_INFORMATION KernelDebuggerInformation;
  1365. ULONG ulReturnLength;
  1366. SECURITY_ATTRIBUTES sa;
  1367. STARTUPINFO StartupInfo;
  1368. PROCESS_INFORMATION ProcessInformation;
  1369. CHAR szCmdLine[256];
  1370. HANDLE hEvent;
  1371. //
  1372. // Are we being run under a debugger ?
  1373. //
  1374. if (IsDebuggerAttached()) {
  1375. //
  1376. // No need to start one.
  1377. //
  1378. return;
  1379. }
  1380. //
  1381. // Is the kernel debugger enabled?
  1382. //
  1383. Status = NtQuerySystemInformation(
  1384. SystemKernelDebuggerInformation,
  1385. &KernelDebuggerInformation,
  1386. sizeof(KernelDebuggerInformation),
  1387. &ulReturnLength
  1388. );
  1389. if (NT_SUCCESS(Status) &&
  1390. (ulReturnLength >= sizeof(KernelDebuggerInformation))) {
  1391. fKernelDebuggerEnabled = KernelDebuggerInformation.KernelDebuggerEnabled;
  1392. } else {
  1393. fKernelDebuggerEnabled = FALSE;
  1394. LOGDEBUG(0,("StartDebuggerForWow: NtQuerySystemInformation(kdinfo) returns 0x%8.8x, return length 0x%08x.\n",
  1395. Status, ulReturnLength));
  1396. }
  1397. //
  1398. // Create an event for NTSD to signal once it has fully connected
  1399. // and is ready for the exception. We force the handle to be inherited.
  1400. //
  1401. sa.nLength = sizeof(sa);
  1402. sa.lpSecurityDescriptor = NULL;
  1403. sa.bInheritHandle = TRUE;
  1404. hEvent = CreateEvent(&sa, TRUE, FALSE, NULL);
  1405. //
  1406. // Build debugger command line.
  1407. //
  1408. wsprintf(szCmdLine, "ntsd %s -p %lu -e %lu -x -g -G",
  1409. fKernelDebuggerEnabled ? "-d" : "",
  1410. GetCurrentProcessId(),
  1411. hEvent
  1412. );
  1413. RtlZeroMemory(&StartupInfo,sizeof(StartupInfo));
  1414. StartupInfo.cb = sizeof(StartupInfo);
  1415. b = CreateProcess(
  1416. NULL,
  1417. szCmdLine,
  1418. NULL,
  1419. NULL,
  1420. TRUE, // fInheritHandles
  1421. CREATE_DEFAULT_ERROR_MODE,
  1422. NULL,
  1423. NULL,
  1424. &StartupInfo,
  1425. &ProcessInformation
  1426. );
  1427. if (b) {
  1428. CloseHandle(ProcessInformation.hProcess);
  1429. CloseHandle(ProcessInformation.hThread);
  1430. if (hEvent) {
  1431. //
  1432. // Wait for debugger to initialize.
  1433. //
  1434. WaitForSingleObject(hEvent, INFINITE);
  1435. }
  1436. }
  1437. CloseHandle(hEvent);
  1438. return;
  1439. }
  1440. #endif // DEBUG
  1441. BOOL IsDebuggerAttached(VOID)
  1442. /*++
  1443. Routine Description:
  1444. Checks to see if there's a debugger attached to WOW. If there is,
  1445. this routine also turns on a bit in the 16-bit kernel's DS so it
  1446. can do its part to report debug events.
  1447. Arguments:
  1448. None.
  1449. Return Value:
  1450. FALSE - no debugger attached or NtQueryInformationProcess fails.
  1451. TRUE - debugger is definitely attached.
  1452. --*/
  1453. {
  1454. NTSTATUS Status;
  1455. HANDLE MyDebugPort;
  1456. LPBYTE lpDebugWOW;
  1457. static BOOL fDebuggerAttached = FALSE;
  1458. static BOOL fKernel16Notified = FALSE;
  1459. //
  1460. // Don't bother checking if we already have been told that
  1461. // there is a debugger attached, since debuggers cannot detach.
  1462. //
  1463. if (!fDebuggerAttached) {
  1464. //
  1465. // Query our ProcessDebugPort, if it is nonzero we have
  1466. // a debugger attached.
  1467. //
  1468. Status = NtQueryInformationProcess(
  1469. NtCurrentProcess(),
  1470. ProcessDebugPort,
  1471. (PVOID)&MyDebugPort,
  1472. sizeof(MyDebugPort),
  1473. NULL
  1474. );
  1475. fDebuggerAttached = NT_SUCCESS(Status) && (MyDebugPort != NULL);
  1476. }
  1477. //
  1478. // If we have a debugger attached share that information
  1479. // with the 16-bit kernel.
  1480. //
  1481. if (!fKernel16Notified && fDebuggerAttached && vpDebugWOW != 0) {
  1482. GETVDMPTR(vpDebugWOW, 1, lpDebugWOW);
  1483. *lpDebugWOW |= 1;
  1484. FREEVDMPTR(lpDebugWOW);
  1485. DBGNotifyDebugged( TRUE );
  1486. fKernel16Notified = TRUE;
  1487. }
  1488. return fDebuggerAttached;
  1489. }
  1490. void *
  1491. WOWGetVDMPointer(
  1492. VPVOID Address,
  1493. DWORD Count,
  1494. BOOL ProtectedMode
  1495. )
  1496. /*++
  1497. Routine Description:
  1498. This routine converts a 16/16 address to a linear address.
  1499. WARNING NOTE - This routine has been optimized so protect mode LDT lookup
  1500. falls stright through.
  1501. Arguments:
  1502. Address -- specifies the address in seg:offset format
  1503. Size -- specifies the size of the region to be accessed.
  1504. ProtectedMode -- true if the address is a protected mode address
  1505. Return Value:
  1506. The pointer.
  1507. --*/
  1508. {
  1509. if (ProtectedMode) {
  1510. return GetPModeVDMPointer(Address, Count);
  1511. } else {
  1512. return GetRModeVDMPointer(Address);
  1513. }
  1514. }
  1515. PVOID FASTCALL
  1516. GetPModeVDMPointerAssert(
  1517. DWORD Address
  1518. #ifdef DEBUG
  1519. , DWORD Count
  1520. #endif
  1521. )
  1522. /*++
  1523. Routine Description:
  1524. Convert a 16:16 protected mode address to the equivalent flat pointer.
  1525. Arguments:
  1526. Address -- specifies the address in selector:offset format
  1527. Return Value:
  1528. The pointer.
  1529. --*/
  1530. {
  1531. #ifdef DEBUG
  1532. void *vp;
  1533. #endif
  1534. // what to do if this assert fires?? Currently "nothing" seems to work OK.
  1535. WOW32WARNMSG((ExpLdt),("WOW::GetPModeVDMPointerAssert: ExpLdt == NULL\n"));
  1536. //
  1537. // Check to see if the descriptor is marked present
  1538. // We assume here that ExpLdt is DWORD ALIGNED to avoid a slower
  1539. // unaligned access on risc.
  1540. //
  1541. if (!((ExpLdt)[(Address >> 18) | 1] & LDT_DESC_PRESENT)) {
  1542. PARM16 Parm16;
  1543. ULONG ul;
  1544. if ((HIWORD(Address) & STD_SELECTOR_BITS) == STD_SELECTOR_BITS) {
  1545. // We've determined that the selector is valid and not
  1546. // present. So we call over to kernel16 to have it load
  1547. // the selector into a segment register. This forces a
  1548. // segment fault, and the segment should be brought in.
  1549. // Note that CallBack16 also calls this routine, so we could
  1550. // theoretically get into an infinite recursion loop here.
  1551. // This could only happen if selectors like the 16-bit stack
  1552. // were not present, which would mean we are hosed anyway.
  1553. // Such a loop should terminate with a stack fault eventually.
  1554. Parm16.WndProc.lParam = (LONG) Address;
  1555. CallBack16(RET_FORCESEGMENTFAULT, &Parm16, 0, &ul);
  1556. } else {
  1557. // We come here if the address can't be resolved. A null
  1558. // selector is special-cased to allow for a null 16:16
  1559. // pointer to be passed.
  1560. if (HIWORD(Address)) {
  1561. LOGDEBUG(LOG_ALWAYS,("WOW::GetVDMPointer: *** Invalid 16:16 address %04x:%04x\n",
  1562. HIWORD(Address), LOWORD(Address)));
  1563. // If we get here, then we are about to return a bogus
  1564. // flat pointer.
  1565. // I would prefer to eventually assert this, but it
  1566. // appears to be overactive for winfax lite.
  1567. //WOW32ASSERT(FALSE);
  1568. }
  1569. }
  1570. }
  1571. #ifdef DEBUG
  1572. if (vp = GetPModeVDMPointerMacro(Address, Count)) {
  1573. #ifdef _X86_
  1574. //
  1575. // Check the selector limit on x86 only and return NULL if
  1576. // the limit is too small.
  1577. //
  1578. if (SelectorLimit &&
  1579. (Address & 0xFFFF) + Count > SelectorLimit[Address >> 19] + 1)
  1580. {
  1581. WOW32ASSERTMSGF (FALSE, ("WOW32 limit check assertion: %04x:%04x size %x is beyond limit %x.\n",
  1582. Address >> 16,
  1583. Address & 0xFFFF,
  1584. Count,
  1585. SelectorLimit[Address >> 19]
  1586. ));
  1587. return vp;
  1588. }
  1589. #endif
  1590. #if 0 // this code is a paranoid check, only useful when debugging GetPModeVDMPointer.
  1591. if (vp != Sim32GetVDMPointer(Address, Count, TRUE)) {
  1592. LOGDEBUG(LOG_ALWAYS,
  1593. ("GetPModeVDMPointer: GetPModeVDMPointerMacro(%x) returns %x, Sim32 returns %x!\n",
  1594. Address, vp, Sim32GetVDMPointer(Address, Count, TRUE)));
  1595. vp = Sim32GetVDMPointer(Address, Count, TRUE);
  1596. }
  1597. #endif
  1598. return vp;
  1599. } else {
  1600. return NULL;
  1601. }
  1602. #else
  1603. return GetPModeVDMPointerMacro(Address, 0); // No limit check on free build.
  1604. #endif // DEBUG
  1605. }
  1606. ULONG FASTCALL WK32WOWGetFastAddress( PVDMFRAME pFrame )
  1607. {
  1608. #if FASTBOPPING
  1609. return (ULONG)WOWBopEntry;
  1610. #else
  1611. return 0;
  1612. #endif
  1613. }
  1614. ULONG FASTCALL WK32WOWGetFastCbRetAddress( PVDMFRAME pFrame )
  1615. {
  1616. #if FASTBOPPING
  1617. return (ULONG)FastWOWCallbackRet;
  1618. #else
  1619. return( 0L );
  1620. #endif
  1621. }
  1622. ULONG FASTCALL WK32WOWGetTableOffsets( PVDMFRAME pFrame )
  1623. {
  1624. PWOWGETTABLEOFFSETS16 parg16;
  1625. PTABLEOFFSETS pto16;
  1626. GETARGPTR(pFrame, sizeof(PDWORD16), parg16);
  1627. GETVDMPTR(parg16->vpThunkTableOffsets, sizeof(TABLEOFFSETS), pto16);
  1628. RtlCopyMemory(pto16, &tableoffsets, sizeof(TABLEOFFSETS));
  1629. FLUSHVDMPTR(parg16->vpThunkTableOffsets, sizeof(TABLEOFFSETS), pto16);
  1630. FREEVDMPTR(pto16);
  1631. FREEARGPTR(parg16);
  1632. #if FASTBOPPING
  1633. fKernelCSIPFixed = TRUE;
  1634. #endif
  1635. return 1;
  1636. }
  1637. ULONG FASTCALL WK32WOWGetFlatAddressArray( PVDMFRAME pFrame )
  1638. {
  1639. #if FASTBOPPING
  1640. return (ULONG)FlatAddress;
  1641. #else
  1642. return 0;
  1643. #endif
  1644. }
  1645. #ifdef DEBUG
  1646. /*
  1647. * DoAssert - do an assertion. called after the expression has been evaluted
  1648. *
  1649. * Input:
  1650. *
  1651. *
  1652. * Note if the requested log level is not what we want we don't output
  1653. * but we always output to the circular buffer - just in case.
  1654. *
  1655. *
  1656. */
  1657. int DoAssert(PSZ szAssert, PSZ szModule, UINT line, UINT loglevel)
  1658. {
  1659. INT savefloptions;
  1660. //
  1661. // Start a debugger for WOW if there isn't already one.
  1662. //
  1663. // Until now StartDebuggerForWow was started by
  1664. // the exception filter, which meant asserts on a
  1665. // checked build got the debugger but the user didn't see
  1666. // the assertion text on the debugger screen because
  1667. // logprintf was called before the debugger attached.
  1668. // -- DaveHart 31-Jan-95
  1669. //
  1670. StartDebuggerForWow();
  1671. savefloptions = flOptions;
  1672. flOptions |= OPT_DEBUG; // *always* print the message
  1673. //
  1674. // szAssert is NULL for bare-bones WOW32ASSERT()
  1675. //
  1676. if (szAssert == NULL) {
  1677. LOGDEBUG(loglevel, ("WOW32 assertion failure: %s line %d\n", szModule, line));
  1678. } else {
  1679. LOGDEBUG(loglevel, ("%s", szAssert));
  1680. }
  1681. flOptions = savefloptions;
  1682. if (IsDebuggerAttached()) {
  1683. DbgBreakPoint();
  1684. } else {
  1685. DWORD dw = SetErrorMode(0);
  1686. RaiseException(EXCEPTION_WOW32_ASSERTION, 0, 0, NULL);
  1687. SetErrorMode(dw);
  1688. }
  1689. return 0;
  1690. }
  1691. /*
  1692. * sprintf_gszAssert
  1693. *
  1694. * Used by WOW32ASSERTMSGF to format the assertion text into
  1695. * a global buffer, gszAssert. There is probably a better way.
  1696. *
  1697. * DaveHart 15-Jun-95.
  1698. *
  1699. */
  1700. int _cdecl sprintf_gszAssert(PSZ pszFmt, ...)
  1701. {
  1702. va_list VarArgs;
  1703. va_start(VarArgs, pszFmt);
  1704. return vsprintf(gszAssert, pszFmt, VarArgs);
  1705. }
  1706. /*
  1707. * logprintf - format log print routine
  1708. *
  1709. * Input:
  1710. * iReqLogLevel - Requested Logging Level
  1711. *
  1712. * Note if the requested log level is not what we want we don't output
  1713. * but we always output to the circular buffer - just in case.
  1714. *
  1715. *
  1716. */
  1717. VOID logprintf(PSZ pszFmt, ...)
  1718. {
  1719. DWORD lpBytesWritten;
  1720. int len;
  1721. char text[1024];
  1722. va_list arglist;
  1723. va_start(arglist, pszFmt);
  1724. len = vsprintf(text, pszFmt, arglist);
  1725. // fLog states (set by !wow32.logfile debugger extension):
  1726. // 0 -> no logging;
  1727. // 1 -> log to file
  1728. // 2 -> create log file
  1729. // 3 -> close log file
  1730. if(fLog > 1) {
  1731. if(fLog == 2) {
  1732. if((hfLog = CreateFile(szLogFile,
  1733. GENERIC_WRITE,
  1734. FILE_SHARE_WRITE,
  1735. NULL,
  1736. CREATE_ALWAYS,
  1737. FILE_ATTRIBUTE_NORMAL,
  1738. NULL)) != INVALID_HANDLE_VALUE) {
  1739. fLog = 1;
  1740. }
  1741. else {
  1742. hfLog = NULL;
  1743. fLog = 0;
  1744. OutputDebugString("Couldn't open log file!\n");
  1745. }
  1746. }
  1747. else {
  1748. FlushFileBuffers(hfLog);
  1749. CloseHandle(hfLog);
  1750. hfLog = NULL;
  1751. fLog = 0;
  1752. }
  1753. }
  1754. if ( len > TMP_LINE_LEN-1 ) {
  1755. text[TMP_LINE_LEN-2] = '\n';
  1756. text[TMP_LINE_LEN-1] = '\0'; /* Truncate to 128 */
  1757. }
  1758. IFLOG(iReqLogLevel) {
  1759. // write to file?
  1760. if (fLog) {
  1761. WriteFile(hfLog, text, len, &lpBytesWritten, NULL);
  1762. }
  1763. // write to terminal?
  1764. else if (flOptions & OPT_DEBUG) {
  1765. OutputDebugString(text);
  1766. }
  1767. }
  1768. strcpy(&achTmp[iCircBuffer][0], text);
  1769. if (--iCircBuffer < 0 ) {
  1770. iCircBuffer = CIRC_BUFFERS-1;
  1771. }
  1772. }
  1773. /*
  1774. * checkloging - Some Functions we don't want to log
  1775. *
  1776. * Entry
  1777. * fLogFilter = Filter for Specific Modules - Kernel, User, GDI etc.
  1778. * fLogTaskFilter = Filter for specific TaskID
  1779. *
  1780. * Exit: TRUE - OK to LOG Event
  1781. * FALSE - Don't Log Event
  1782. *
  1783. */
  1784. BOOL checkloging(register PVDMFRAME pFrame)
  1785. {
  1786. INT i;
  1787. BOOL bReturn;
  1788. INT iFun = GetFuncId(pFrame->wCallID);
  1789. PTABLEOFFSETS pto = &tableoffsets;
  1790. // Filter on Specific Call IDs
  1791. if (awfLogFunctionFilter[0] != 0xffff) {
  1792. INT nOrdinal;
  1793. nOrdinal = GetOrdinal(iFun);
  1794. bReturn = FALSE;
  1795. for (i=0; i < FILTER_FUNCTION_MAX ; i++) {
  1796. if (awfLogFunctionFilter[i] == nOrdinal) {
  1797. bReturn = TRUE;
  1798. break;
  1799. }
  1800. }
  1801. } else {
  1802. bReturn = TRUE;
  1803. }
  1804. // Do not LOG Internal Kernel Calls below level 20
  1805. if (iLogLevel < 20 ) {
  1806. if((iFun == FUN_WOWOUTPUTDEBUGSTRING) ||
  1807. ((iFun < pto->user) && (iFun >= FUN_WOWINITTASK)))
  1808. bReturn = FALSE;
  1809. }
  1810. // LOG Only Specific TaskID
  1811. if (fLogTaskFilter != 0xffff) {
  1812. if (fLogTaskFilter != pFrame->wTDB) {
  1813. bReturn = FALSE;
  1814. }
  1815. }
  1816. // LOG Filter On Modules USER/GDI/Kernel etc.
  1817. switch (ModFromCallID(iFun)) {
  1818. case MOD_KERNEL:
  1819. if ((fLogFilter & FILTER_KERNEL) == 0 )
  1820. bReturn = FALSE;
  1821. break;
  1822. case MOD_USER:
  1823. if ((fLogFilter & FILTER_USER) == 0 )
  1824. bReturn = FALSE;
  1825. break;
  1826. case MOD_GDI:
  1827. if ((fLogFilter & FILTER_GDI) == 0 )
  1828. bReturn = FALSE;
  1829. break;
  1830. case MOD_KEYBOARD:
  1831. if ((fLogFilter & FILTER_KEYBOARD) == 0 )
  1832. bReturn = FALSE;
  1833. break;
  1834. case MOD_SOUND:
  1835. if ((fLogFilter & FILTER_SOUND) == 0 )
  1836. bReturn = FALSE;
  1837. break;
  1838. case MOD_MMEDIA:
  1839. if ((fLogFilter & FILTER_MMEDIA) == 0 )
  1840. bReturn = FALSE;
  1841. break;
  1842. case MOD_WINSOCK:
  1843. if ((fLogFilter & FILTER_WINSOCK) == 0 )
  1844. bReturn = FALSE;
  1845. break;
  1846. case MOD_COMMDLG:
  1847. if ((fLogFilter & FILTER_COMMDLG) == 0 ) {
  1848. bReturn = FALSE;
  1849. }
  1850. break;
  1851. #ifdef FE_IME
  1852. case MOD_WINNLS:
  1853. if ((fLogFilter & FILTER_WINNLS) == 0 )
  1854. bReturn = FALSE;
  1855. break;
  1856. #endif // FE_IME
  1857. #ifdef FE_SB
  1858. case MOD_WIFEMAN:
  1859. if ((fLogFilter & FILTER_WIFEMAN) == 0 )
  1860. bReturn = FALSE;
  1861. break;
  1862. #endif
  1863. default:
  1864. break;
  1865. }
  1866. return (bReturn);
  1867. }
  1868. /*
  1869. * Argument Logging For Tracing API Calls
  1870. *
  1871. *
  1872. */
  1873. VOID logargs(INT iLog, register PVDMFRAME pFrame)
  1874. {
  1875. register PBYTE pbArgs;
  1876. INT iFun;
  1877. INT cbArgs;
  1878. if (checkloging(pFrame)) {
  1879. iFun = GetFuncId(pFrame->wCallID);
  1880. cbArgs = aw32WOW[iFun].cbArgs; // Get Number of Parameters
  1881. if ((fLogFilter & FILTER_VERBOSE) == 0 ) {
  1882. LOGDEBUG(iLog,("%s(", aw32WOW[iFun].lpszW32));
  1883. } else {
  1884. LOGDEBUG(iLog,("%04X %08X %04X %s:%s(",pFrame->wTDB, pFrame->vpCSIP,pFrame->wAppDS, GetModName(iFun), aw32WOW[iFun].lpszW32));
  1885. }
  1886. GETARGPTR(pFrame, cbArgs, pbArgs);
  1887. pbArgs += cbArgs;
  1888. //
  1889. // Log the function arguments a word at a time.
  1890. // The first iteration of the while loop is unrolled so
  1891. // that the main loop doesn't have to figure out whether
  1892. // or not to print a comma.
  1893. //
  1894. if (cbArgs > 0) {
  1895. pbArgs -= sizeof(WORD);
  1896. cbArgs -= sizeof(WORD);
  1897. LOGDEBUG(iLog,("%04x", *(PWORD16)pbArgs));
  1898. while (cbArgs > 0) {
  1899. pbArgs -= sizeof(WORD);
  1900. cbArgs -= sizeof(WORD);
  1901. LOGDEBUG(iLog,(",%04x", *(PWORD16)pbArgs));
  1902. }
  1903. }
  1904. FREEARGPTR(pbArgs);
  1905. LOGDEBUG(iLog,(")\n"));
  1906. if (fDebugWait != 0) {
  1907. DbgPrint("WOWSingle Step\n");
  1908. DbgBreakPoint();
  1909. }
  1910. }
  1911. }
  1912. /*
  1913. * logreturn - Log Return Values From Call
  1914. *
  1915. * Entry
  1916. *
  1917. * Exit - None
  1918. */
  1919. VOID logreturn(INT iLog, register PVDMFRAME pFrame, ULONG ulReturn)
  1920. {
  1921. INT iFun;
  1922. if (checkloging(pFrame)) {
  1923. iFun = GetFuncId(pFrame->wCallID);
  1924. if ((fLogFilter & FILTER_VERBOSE) == 0 ) {
  1925. LOGDEBUG(iLog,("%s: %lx\n", aw32WOW[iFun].lpszW32, ulReturn));
  1926. } else {
  1927. LOGDEBUG(iLog,("%04X %08X %04X %s:%s: %lx\n", pFrame->wTDB, pFrame->vpCSIP, pFrame->wAppDS, GetModName(iFun), aw32WOW[iFun].lpszW32, ulReturn));
  1928. }
  1929. }
  1930. }
  1931. #endif // DEBUG
  1932. PVOID FASTCALL malloc_w (ULONG size)
  1933. {
  1934. PVOID pv;
  1935. pv = HeapAlloc(hWOWHeap, 0, size + TAILCHECK);
  1936. WOW32ASSERTMSG(pv, "WOW32: malloc_w failing, returning NULL\n");
  1937. #ifdef DEBUG_MEMLEAK
  1938. WOW32DebugMemLeak(pv, size, ML_MALLOC_W);
  1939. #endif
  1940. return pv;
  1941. }
  1942. DWORD FASTCALL size_w (PVOID pv)
  1943. {
  1944. DWORD dwSize;
  1945. dwSize = HeapSize(hWOWHeap, 0, pv) - TAILCHECK;
  1946. return(dwSize);
  1947. }
  1948. PVOID FASTCALL malloc_w_zero (ULONG size)
  1949. {
  1950. PVOID pv;
  1951. pv = HeapAlloc(hWOWHeap, HEAP_ZERO_MEMORY, size + TAILCHECK);
  1952. WOW32ASSERTMSG(pv, "WOW32: malloc_w_zero failing, returning NULL\n");
  1953. #ifdef DEBUG_MEMLEAK
  1954. WOW32DebugMemLeak(pv, size, ML_MALLOC_W_ZERO);
  1955. #endif
  1956. return pv;
  1957. }
  1958. VOID FASTCALL free_w (PVOID p)
  1959. {
  1960. #ifdef DEBUG_MEMLEAK
  1961. WOW32DebugFreeMem(p);
  1962. #endif
  1963. HeapFree(hWOWHeap, 0, (LPSTR)(p));
  1964. }
  1965. //
  1966. // malloc_w_or_die is for use by *initialization* code only, when we
  1967. // can't get WOW going because, for example, we can't allocate a buffer
  1968. // to hold the known DLL list.
  1969. //
  1970. // malloc_w_or_die should not be used by API or message thunks or worker
  1971. // routines called by API or message thunks.
  1972. //
  1973. PVOID FASTCALL malloc_w_or_die(ULONG size)
  1974. {
  1975. PVOID pv;
  1976. if (!(pv = malloc_w(size))) {
  1977. WOW32ASSERTMSG(pv, "WOW32: malloc_w_or_die failing, terminating.\n");
  1978. WOWStartupFailed(); // never returns.
  1979. }
  1980. return pv;
  1981. }
  1982. LPSTR malloc_w_strcpy_vp16to32(VPVOID vpstr16, BOOL bMulti, INT cMax)
  1983. {
  1984. return(ThunkStr16toStr32(NULL, vpstr16, cMax, bMulti));
  1985. }
  1986. LPSTR ThunkStr16toStr32(LPSTR pdst32, VPVOID vpsrc16, INT cChars, BOOL bMulti)
  1987. /*++
  1988. Thunks a 16-bit string to a 32-bit ANSI string.
  1989. bMulti == TRUE means we are thunking a multi-string which is a list of NULL
  1990. *separated* strings that *terminate* with a double NULL.
  1991. Notes: If the original 32-bit buffer is too small to contain the new string,
  1992. it will be free'd and a new 32-bit buffer will be allocated. If a new
  1993. 32-bit buffer can't be allocated, the ptr to the original 32-bit
  1994. buffer is returned with no changes to the contents.
  1995. Returns: ptr to the original 32-bit buffer
  1996. OR ptr to a new 32-bit buffer if the original buffer was too small
  1997. OR NULL if psrc is NULL.
  1998. --*/
  1999. {
  2000. PVOID pbuf32;
  2001. LPSTR psrc16;
  2002. INT buf16size, iLen;
  2003. INT buf32size = 0;
  2004. GETPSZPTR(vpsrc16, psrc16);
  2005. if(!psrc16) {
  2006. // the app doesn't want a buffer for this anymore
  2007. // (this is primarily for comdlg support)
  2008. if(pdst32) {
  2009. free_w(pdst32);
  2010. }
  2011. return(NULL);
  2012. }
  2013. if(bMulti) {
  2014. iLen = Multi_strlen(psrc16) + 1;
  2015. } else {
  2016. iLen = (INT)(strlen(psrc16) + 1);
  2017. }
  2018. buf16size = max(cChars, iLen);
  2019. if(pdst32) {
  2020. buf32size = (INT)size_w(pdst32);
  2021. }
  2022. // if 32-bit buffer is too small, NULL, or invalid -- alloc a bigger buffer
  2023. if((buf32size < buf16size) || (!pdst32) || (buf32size == 0xFFFFFFFF)) {
  2024. if(pbuf32 = malloc_w(buf16size)) {
  2025. // now copy to the new 32-bit buffer
  2026. if(bMulti) {
  2027. Multi_strcpy(pbuf32, psrc16);
  2028. } else {
  2029. strcpy(pbuf32, psrc16);
  2030. }
  2031. // get rid of the old buffer
  2032. if(pdst32) {
  2033. free_w(pdst32);
  2034. }
  2035. pdst32 = pbuf32;
  2036. }
  2037. else {
  2038. WOW32ASSERTMSG(0, "WOW32: ThunkStr16toStr32: malloc_w failed!\n");
  2039. }
  2040. }
  2041. // else just use the original 32-bit buffer (99% of the time)
  2042. else if(pdst32) {
  2043. if(bMulti) {
  2044. Multi_strcpy(pdst32, psrc16);
  2045. } else {
  2046. strcpy(pdst32, psrc16);
  2047. }
  2048. }
  2049. FREEPSZPTR(psrc16);
  2050. return(pdst32);
  2051. }
  2052. //
  2053. // WOWStartupFailed puts up a fatal error box and terminates WOW.
  2054. //
  2055. PVOID WOWStartupFailed(VOID)
  2056. {
  2057. char szCaption[256];
  2058. char szMsgBoxText[1024];
  2059. LoadString(hmodWOW32, iszStartupFailed, szMsgBoxText, sizeof szMsgBoxText);
  2060. LoadString(hmodWOW32, iszSystemError, szCaption, sizeof szCaption);
  2061. MessageBox(GetDesktopWindow(),
  2062. szMsgBoxText,
  2063. szCaption,
  2064. MB_SETFOREGROUND | MB_TASKMODAL | MB_ICONSTOP | MB_OK | MB_DEFBUTTON1);
  2065. ExitVDM(WOWVDM, ALL_TASKS); // Tell Win32 All Tasks are gone.
  2066. ExitProcess(EXIT_FAILURE);
  2067. return (PVOID)NULL;
  2068. }
  2069. #ifdef FIX_318197_NOW
  2070. char*
  2071. WOW32_strchr(
  2072. const char* psz,
  2073. int c
  2074. )
  2075. {
  2076. if (gbDBCSEnable) {
  2077. unsigned int cc;
  2078. for (; (cc = *psz); psz++) {
  2079. if (IsDBCSLeadByte((BYTE)cc)) {
  2080. if (*++psz == '\0') {
  2081. return NULL;
  2082. }
  2083. if ((unsigned int)c == ((cc << 8) | *psz) ) { // DBCS match
  2084. return (char*)(psz - 1);
  2085. }
  2086. }
  2087. else if ((unsigned int)c == cc) {
  2088. return (char*)psz; // SBCS match
  2089. }
  2090. }
  2091. if ((unsigned int)c == cc) { // NULL match
  2092. return (char*)psz;
  2093. }
  2094. return NULL;
  2095. }
  2096. else {
  2097. return strchr(psz, c);
  2098. }
  2099. }
  2100. char*
  2101. WOW32_strrchr(
  2102. const char* psz,
  2103. int c
  2104. )
  2105. {
  2106. if (gbDBCSEnable) {
  2107. char* r = NULL;
  2108. unsigned int cc;
  2109. do {
  2110. cc = *psz;
  2111. if (IsDBCSLeadByte((BYTE)cc)) {
  2112. if (*++psz) {
  2113. if ((unsigned int)c == ((cc << 8) | *psz) ) { // DBCS match
  2114. r = (char*)(psz - 1);
  2115. }
  2116. }
  2117. else if (!r) {
  2118. // return pointer to '\0'
  2119. r = (char*)psz;
  2120. }
  2121. }
  2122. else if ((unsigned int)c == cc) {
  2123. r = (char*)psz; // SBCS match
  2124. }
  2125. } while (*psz++);
  2126. return r;
  2127. }
  2128. else {
  2129. return strrchr(psz, c);
  2130. }
  2131. }
  2132. char*
  2133. WOW32_strstr(
  2134. const char* str1,
  2135. const char* str2
  2136. )
  2137. {
  2138. if (gbDBCSEnable) {
  2139. char *cp, *endp;
  2140. char *s1, *s2;
  2141. cp = (char*)str1;
  2142. endp = (char*)str1 + strlen(str1) - strlen(str2);
  2143. while (*cp && (cp <= endp)) {
  2144. s1 = cp;
  2145. s2 = (char*)str2;
  2146. while ( *s1 && *s2 && (*s1 == *s2) ) {
  2147. s1++;
  2148. s2++;
  2149. }
  2150. if (!(*s2)) {
  2151. return cp; // success!
  2152. }
  2153. cp = CharNext(cp);
  2154. }
  2155. return NULL;
  2156. }
  2157. else {
  2158. return strstr(str1, str2);
  2159. }
  2160. }
  2161. int
  2162. WOW32_strncmp(
  2163. const char* str1,
  2164. const char* str2,
  2165. size_t n
  2166. )
  2167. {
  2168. if (gbDBCSEnable) {
  2169. int retval;
  2170. if (n == 0) {
  2171. return 0;
  2172. }
  2173. retval = CompareStringA( GetThreadLocale(),
  2174. LOCALE_USE_CP_ACP,
  2175. str1,
  2176. n,
  2177. str2,
  2178. n );
  2179. if (retval == 0) {
  2180. //
  2181. // The caller is not expecting failure. Try the system
  2182. // default locale id.
  2183. //
  2184. retval = CompareStringA( GetSystemDefaultLCID(),
  2185. LOCALE_USE_CP_ACP,
  2186. str1,
  2187. n,
  2188. str2,
  2189. n );
  2190. }
  2191. if (retval == 0) {
  2192. if (str1 && str2) {
  2193. //
  2194. // The caller is not expecting failure. We've never had a
  2195. // failure indicator before. We'll do a best guess by calling
  2196. // the C runtimes to do a non-locale sensitive compare.
  2197. //
  2198. return strncmp(str1, str2, n);
  2199. }
  2200. else if (str1) {
  2201. return 1;
  2202. }
  2203. else if (str2) {
  2204. return -1;
  2205. }
  2206. else {
  2207. return 0;
  2208. }
  2209. }
  2210. return retval - 2;
  2211. }
  2212. else {
  2213. return strncmp(str1, str2, n);
  2214. }
  2215. }
  2216. int
  2217. WOW32_strnicmp(
  2218. const char* str1,
  2219. const char* str2,
  2220. size_t n
  2221. )
  2222. {
  2223. if (gbDBCSEnable) {
  2224. int retval;
  2225. if (n == 0) {
  2226. return 0;
  2227. }
  2228. retval = CompareStringA( GetThreadLocale(),
  2229. LOCALE_USE_CP_ACP | NORM_IGNORECASE,
  2230. str1,
  2231. n,
  2232. str2,
  2233. n );
  2234. if (retval == 0) {
  2235. //
  2236. // The caller is not expecting failure. Try the system
  2237. // default locale id.
  2238. //
  2239. retval = CompareStringA( GetSystemDefaultLCID(),
  2240. LOCALE_USE_CP_ACP | NORM_IGNORECASE,
  2241. str1,
  2242. n,
  2243. str2,
  2244. n );
  2245. }
  2246. if (retval == 0) {
  2247. if (str1 && str2) {
  2248. //
  2249. // The caller is not expecting failure. We've never had a
  2250. // failure indicator before. We'll do a best guess by calling
  2251. // the C runtimes to do a non-locale sensitive compare.
  2252. //
  2253. return _strnicmp(str1, str2, n);
  2254. }
  2255. else if (str1) {
  2256. return 1;
  2257. }
  2258. else if (str2) {
  2259. return -1;
  2260. }
  2261. else {
  2262. return 0;
  2263. }
  2264. }
  2265. return retval - 2;
  2266. }
  2267. else {
  2268. return _strnicmp(str1, str2, n);
  2269. }
  2270. }
  2271. #endif
  2272. //****************************************************************************
  2273. #ifdef DEBUG_OR_WOWPROFILE
  2274. DWORD GetWOWTicDiff(DWORD dwPrevCount) {
  2275. /*
  2276. * Returns difference between a previous Tick count & the current tick count
  2277. *
  2278. * NOTE: Tick counts are in unspecified units (PerfFreq is in MHz)
  2279. */
  2280. DWORD dwDiff;
  2281. LARGE_INTEGER PerfCount, PerfFreq;
  2282. NtQueryPerformanceCounter(&PerfCount, &PerfFreq);
  2283. /* if ticks carried into high dword (assuming carry was only one) */
  2284. if( dwPrevCount > PerfCount.LowPart ) {
  2285. /* (0xFFFFFFFF - (dwPrevCount - LowPart)) + 1L caused compiler to
  2286. optimize in an arithmetic overflow, so we do it in two steps
  2287. to fool Mr. compiler
  2288. */
  2289. dwDiff = (dwPrevCount - PerfCount.LowPart) - 1L;
  2290. dwDiff = ((DWORD)0xFFFFFFFF) - dwDiff;
  2291. }
  2292. else {
  2293. dwDiff = PerfCount.LowPart - dwPrevCount;
  2294. }
  2295. return(dwDiff);
  2296. }
  2297. INT GetFuncId(DWORD iFun)
  2298. {
  2299. INT i;
  2300. static DWORD dwLastInput = -1;
  2301. static DWORD dwLastOutput = -1;
  2302. if (iFun == dwLastInput) {
  2303. iFun = dwLastOutput;
  2304. } else {
  2305. dwLastInput = iFun;
  2306. if (!ISFUNCID(iFun)) {
  2307. for (i = 0; i < cAPIThunks; i++) {
  2308. if (aw32WOW[i].lpfnW32 == (LPFNW32)iFun) {
  2309. iFun = i;
  2310. break;
  2311. }
  2312. }
  2313. }
  2314. dwLastOutput = iFun;
  2315. }
  2316. return iFun;
  2317. }
  2318. #endif // DEBUG_OR_WOWPROFILE
  2319. // for debugging memory leaks
  2320. #ifdef DEBUG_MEMLEAK
  2321. LPMEMLEAK lpMemLeakStart = NULL;
  2322. ULONG ulalloc_Count = 1L;
  2323. DWORD dwAllocFlags = 0;
  2324. VOID WOW32DebugMemLeak(PVOID lp, ULONG size, DWORD fHow)
  2325. {
  2326. PVOID pvCallersAddress, pvCallersCaller;
  2327. LPMEMLEAK lpml;
  2328. HGLOBAL h32 = NULL; // lp from ML_GLOBALTYPE's are really HGLOBAL's
  2329. if(lp) {
  2330. // if we are tracking this type
  2331. if(dwAllocFlags & fHow) {
  2332. // allocate a tracking node
  2333. if(lpml = GlobalAlloc(GPTR, sizeof(MEMLEAK))) {
  2334. lpml->lp = lp;
  2335. lpml->size = size;
  2336. lpml->fHow = fHow;
  2337. lpml->Count = ulalloc_Count++; // save when originally alloc'd
  2338. RtlGetCallersAddress(&pvCallersAddress, &pvCallersCaller);
  2339. lpml->CallersAddress = pvCallersCaller;
  2340. EnterCriticalSection(&csMemLeak);
  2341. lpml->lpmlNext = lpMemLeakStart;
  2342. lpMemLeakStart = lpml;
  2343. LeaveCriticalSection(&csMemLeak);
  2344. }
  2345. WOW32WARNMSG(lpml,"WOW32DebugMemLeak: can't alloc node\n");
  2346. }
  2347. // add "EnD" signature for heap tail corruption checking
  2348. if(fHow & ML_GLOBALTYPE) {
  2349. h32 = (HGLOBAL)lp;
  2350. lp = GlobalLock(h32);
  2351. }
  2352. if(lp) {
  2353. ((CHAR *)(lp))[size++] = 'E';
  2354. ((CHAR *)(lp))[size++] = 'n';
  2355. ((CHAR *)(lp))[size++] = 'D';
  2356. ((CHAR *)(lp))[size++] = '\0';
  2357. if(h32) {
  2358. GlobalUnlock(h32);
  2359. }
  2360. }
  2361. }
  2362. }
  2363. VOID WOW32DebugReMemLeak(PVOID lpNew, PVOID lpOrig, ULONG size, DWORD fHow)
  2364. {
  2365. PVOID pvCallersAddress, pvCallersCaller;
  2366. HGLOBAL h32 = NULL; // lp from ML_GLOBALTYPE's are really HGLOBAL's
  2367. LPMEMLEAK lpml = lpMemLeakStart;
  2368. if(lpNew) {
  2369. if(dwAllocFlags & fHow) {
  2370. // look for original ptr in the list
  2371. while(lpml) {
  2372. if(lpml->lp == lpOrig) {
  2373. break;
  2374. }
  2375. lpml = lpml->lpmlNext;
  2376. }
  2377. WOW32WARNMSG(lpml,
  2378. "WOW32DebugReMemLeak: can't find original node\n");
  2379. // if we found the original ptr
  2380. if(lpml) {
  2381. // update our struct with new ptr if necessary
  2382. if(lpNew != lpOrig) {
  2383. lpml->lp = lpNew;
  2384. }
  2385. lpml->size = size;
  2386. lpml->fHow |= fHow;
  2387. RtlGetCallersAddress(&pvCallersAddress, &pvCallersCaller);
  2388. lpml->CallersAddress = pvCallersCaller;
  2389. ulalloc_Count++;
  2390. }
  2391. }
  2392. // for heap tail corruption checking
  2393. if(fHow & ML_GLOBALTYPE) {
  2394. h32 = (HGLOBAL)lpNew;
  2395. lpNew = GlobalLock(h32);
  2396. }
  2397. if(lpNew) {
  2398. ((CHAR *)(lpNew))[size++] = 'E';
  2399. ((CHAR *)(lpNew))[size++] = 'n';
  2400. ((CHAR *)(lpNew))[size++] = 'D';
  2401. ((CHAR *)(lpNew))[size++] = '\0';
  2402. if(h32) {
  2403. GlobalUnlock(h32);
  2404. }
  2405. }
  2406. }
  2407. }
  2408. VOID WOW32DebugFreeMem(PVOID lp)
  2409. {
  2410. LPMEMLEAK lpmlPrev;
  2411. LPMEMLEAK lpml = lpMemLeakStart;
  2412. if(lp && dwAllocFlags) {
  2413. while(lpml) {
  2414. lpmlPrev = lpml;
  2415. if(lpml->lp == lp) {
  2416. WOW32DebugCorruptionCheck(lp, lpml->size);
  2417. EnterCriticalSection(&csMemLeak);
  2418. if(lpml == lpMemLeakStart) {
  2419. lpMemLeakStart = lpml->lpmlNext;
  2420. }
  2421. else {
  2422. lpmlPrev->lpmlNext = lpml->lpmlNext;
  2423. }
  2424. GlobalFree(lpml); // free the LPMEMLEAK node
  2425. LeaveCriticalSection(&csMemLeak);
  2426. break;
  2427. }
  2428. else {
  2429. lpml = lpml->lpmlNext;
  2430. }
  2431. }
  2432. WOW32WARNMSG((lpml), "WOW32DebugFreeMem: can't find node\n");
  2433. }
  2434. }
  2435. VOID WOW32DebugCorruptionCheck(PVOID lp, DWORD size)
  2436. {
  2437. if(lp && size) {
  2438. if(!((((CHAR *)(lp))[size++] == 'E') &&
  2439. (((CHAR *)(lp))[size++] == 'n') &&
  2440. (((CHAR *)(lp))[size++] == 'D') &&
  2441. (((CHAR *)(lp))[size++] == '\0')) ) {
  2442. WOW32ASSERTMSG(FALSE,"WOW32DebugCorruptionCheck: Corrupt tail!!\n");
  2443. }
  2444. }
  2445. }
  2446. DWORD WOW32DebugGetMemSize(PVOID lp)
  2447. {
  2448. LPMEMLEAK lpml = lpMemLeakStart;
  2449. while(lpml) {
  2450. if(lpml->lp == lp) {
  2451. return(lpml->size);
  2452. }
  2453. lpml = lpml->lpmlNext;
  2454. }
  2455. return(0);
  2456. }
  2457. // NOTE: this is called ONLY IF built with DEBUG_MEMLEAK
  2458. HGLOBAL WOW32DebugGlobalAlloc(UINT flags, DWORD dwSize)
  2459. {
  2460. HGLOBAL h32;
  2461. h32 = GlobalAlloc(flags, dwSize + TAILCHECK);
  2462. WOW32DebugMemLeak((PVOID)h32, dwSize, ML_GLOBALALLOC);
  2463. return(h32);
  2464. }
  2465. // NOTE: this is called ONLY IF built with DEBUG_MEMLEAK
  2466. HGLOBAL WOW32DebugGlobalReAlloc(HGLOBAL h32, DWORD dwSize, UINT flags)
  2467. {
  2468. HGLOBAL h32New;
  2469. PVOID lp32Orig;
  2470. // get the original pointer & check the memory for tail corruption
  2471. lp32Orig = (PVOID)GlobalLock(h32);
  2472. WOW32DebugCorruptionCheck(lp32Orig, WOW32DebugGetMemSize((PVOID)h32));
  2473. GlobalUnlock(h32);
  2474. h32New = GlobalReAlloc(h32, dwSize + TAILCHECK, flags);
  2475. // fix our memory list to account for the realloc
  2476. WOW32DebugReMemLeak((PVOID)h32New,
  2477. (PVOID)h32,
  2478. dwSize + TAILCHECK,
  2479. ML_GLOBALREALLOC);
  2480. return(h32New);
  2481. }
  2482. // NOTE: this is called ONLY IF built with DEBUG_MEMLEAK
  2483. HGLOBAL WOW32DebugGlobalFree(HGLOBAL h32)
  2484. {
  2485. WOW32DebugFreeMem((PVOID)h32);
  2486. h32 = GlobalFree(h32);
  2487. if(h32) {
  2488. LOGDEBUG(0, ("WOW32DebugFreeMem: Lock count not 0!\n"));
  2489. }
  2490. else {
  2491. if(GetLastError() != NO_ERROR) {
  2492. LOGDEBUG(0, ("WOW32DebugFreeMem: GlobalFree failed!\n"));
  2493. }
  2494. }
  2495. return(h32);
  2496. }
  2497. #endif // DEBUG_MEMLEAK