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.

4007 lines
124 KiB

  1. /*++
  2. Copyright (c) 1990 Microsoft Corporation
  3. Module Name:
  4. vdm.c
  5. Abstract:
  6. This module implements Win32 APIs for VDMs
  7. Author:
  8. Sudeepb Bharati (sudeepb) 04-Sep-1991
  9. Revision History:
  10. --*/
  11. #include "basedll.h"
  12. #include "apcompat.h"
  13. #pragma hdrstop
  14. BOOL
  15. APIENTRY
  16. GetBinaryTypeA(
  17. IN LPCSTR lpApplicationName,
  18. OUT LPDWORD lpBinaryType
  19. )
  20. /*++
  21. Routine Description: ANSI version of GetBinaryTypeW.
  22. This API returns the binary type of lpApplicationName.
  23. Arguments:
  24. lpApplicationName - Full pathname of the binary
  25. lpBinaryType - pointer where binary type will be returned.
  26. Return Value:
  27. TRUE - if SUCCESS; lpBinaryType has following
  28. SCS_64BIT_BINARY - Win64 Binary
  29. SCS_32BIT_BINARY - Win32 Binary
  30. SCS_DOS_BINARY - DOS Binary
  31. SCS_WOW_BINARY - Windows 3.X Binary
  32. SCS_PIF_BINARY - PIF file
  33. SCS_POSIX_BINARY - POSIX Binary
  34. SCS_OS216_BINARY - OS/2 Binary
  35. FALSE - if file not found or of unknown type. More info with GetLastError
  36. --*/
  37. {
  38. NTSTATUS Status;
  39. PUNICODE_STRING CommandLine;
  40. ANSI_STRING AnsiString;
  41. UNICODE_STRING DynamicCommandLine;
  42. BOOLEAN bReturn = FALSE;
  43. CommandLine = &NtCurrentTeb()->StaticUnicodeString;
  44. RtlInitAnsiString(&AnsiString,lpApplicationName);
  45. if ( (ULONG)AnsiString.Length<<1 < (ULONG)NtCurrentTeb()->StaticUnicodeString.MaximumLength ) {
  46. DynamicCommandLine.Buffer = NULL;
  47. Status = RtlAnsiStringToUnicodeString(CommandLine,&AnsiString,FALSE);
  48. if ( !NT_SUCCESS(Status) ) {
  49. BaseSetLastNTError(Status);
  50. return FALSE;
  51. }
  52. }
  53. else {
  54. Status = RtlAnsiStringToUnicodeString(&DynamicCommandLine,&AnsiString,TRUE);
  55. if ( !NT_SUCCESS(Status) ) {
  56. BaseSetLastNTError(Status);
  57. return FALSE;
  58. }
  59. }
  60. bReturn = (BOOLEAN)GetBinaryTypeW(
  61. DynamicCommandLine.Buffer ? DynamicCommandLine.Buffer : CommandLine->Buffer,
  62. lpBinaryType);
  63. RtlFreeUnicodeString(&DynamicCommandLine);
  64. return((BOOL)bReturn);
  65. }
  66. BOOL
  67. WINAPI
  68. GetBinaryTypeW(
  69. IN LPCWSTR lpApplicationName,
  70. OUT LPDWORD lpBinaryType
  71. )
  72. /*++
  73. Routine Description: Unicode version.
  74. This API returns the binary type of lpApplicationName.
  75. Arguments:
  76. lpApplicationName - Full pathname of the binary
  77. lpBinaryType - pointer where binary type will be returned.
  78. Return Value:
  79. TRUE - if SUCCESS; lpBinaryType has following
  80. SCS_64BIT_BINARY - Win64 Binary
  81. SCS_32BIT_BINARY - Win32 Binary
  82. SCS_DOS_BINARY - DOS Binary
  83. SCS_WOW_BINARY - Windows 3.X Binary
  84. SCS_PIF_BINARY - PIF file
  85. SCS_POSIX_BINARY - POSIX Binary
  86. SCS_OS216_BINARY - OS/2 Binary
  87. FALSE - if file not found or of unknown type. More info with GetLastError
  88. --*/
  89. {
  90. NTSTATUS Status;
  91. UNICODE_STRING PathName;
  92. RTL_RELATIVE_NAME RelativeName;
  93. BOOLEAN TranslationStatus;
  94. OBJECT_ATTRIBUTES Obja;
  95. PVOID FreeBuffer = NULL;
  96. HANDLE FileHandle, SectionHandle=NULL;
  97. IO_STATUS_BLOCK IoStatusBlock;
  98. LONG fBinaryType = SCS_THIS_PLATFORM_BINARY;
  99. BOOLEAN bReturn = FALSE;
  100. SECTION_IMAGE_INFORMATION ImageInformation;
  101. try {
  102. //
  103. // Translate to an NT name.
  104. //
  105. TranslationStatus = RtlDosPathNameToNtPathName_U(
  106. // DynamicCommandLine.Buffer ? DynamicCommandLine.Buffer : CommandLine->Buffer,
  107. lpApplicationName,
  108. &PathName,
  109. NULL,
  110. &RelativeName
  111. );
  112. if ( !TranslationStatus ) {
  113. BaseSetLastNTError(STATUS_OBJECT_NAME_INVALID);
  114. goto GBTtryexit;
  115. }
  116. FreeBuffer = PathName.Buffer;
  117. if ( RelativeName.RelativeName.Length ) {
  118. PathName = *(PUNICODE_STRING)&RelativeName.RelativeName;
  119. }
  120. else {
  121. RelativeName.ContainingDirectory = NULL;
  122. }
  123. InitializeObjectAttributes(
  124. &Obja,
  125. &PathName,
  126. OBJ_CASE_INSENSITIVE,
  127. RelativeName.ContainingDirectory,
  128. NULL
  129. );
  130. //
  131. // Open the file for execute access
  132. //
  133. Status = NtOpenFile(
  134. &FileHandle,
  135. SYNCHRONIZE | FILE_EXECUTE,
  136. &Obja,
  137. &IoStatusBlock,
  138. FILE_SHARE_READ | FILE_SHARE_DELETE,
  139. FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE
  140. );
  141. if (!NT_SUCCESS(Status) ) {
  142. BaseSetLastNTError(Status);
  143. goto GBTtryexit;
  144. }
  145. //
  146. // Create a section object backed by the file
  147. //
  148. Status = NtCreateSection(
  149. &SectionHandle,
  150. SECTION_ALL_ACCESS,
  151. NULL,
  152. NULL,
  153. PAGE_EXECUTE,
  154. SEC_IMAGE,
  155. FileHandle
  156. );
  157. NtClose(FileHandle);
  158. if (!NT_SUCCESS(Status) ) {
  159. SectionHandle = NULL;
  160. switch (Status) {
  161. case STATUS_INVALID_IMAGE_NE_FORMAT:
  162. #if defined(i386) && defined(OS2_SUPPORT_ENABLED)
  163. fBinaryType = SCS_OS216_BINARY;
  164. break;
  165. #endif
  166. case STATUS_INVALID_IMAGE_PROTECT:
  167. fBinaryType = SCS_DOS_BINARY;
  168. break;
  169. case STATUS_INVALID_IMAGE_WIN_16:
  170. fBinaryType = SCS_WOW_BINARY;
  171. break;
  172. case STATUS_INVALID_IMAGE_NOT_MZ:
  173. fBinaryType = BaseIsDosApplication(&PathName, Status);
  174. if (!fBinaryType){
  175. BaseSetLastNTError(Status);
  176. goto GBTtryexit;
  177. }
  178. fBinaryType = (fBinaryType == BINARY_TYPE_DOS_PIF) ?
  179. SCS_PIF_BINARY : SCS_DOS_BINARY;
  180. break;
  181. case STATUS_INVALID_IMAGE_WIN_32:
  182. fBinaryType = SCS_32BIT_BINARY;
  183. break;
  184. case STATUS_INVALID_IMAGE_WIN_64:
  185. fBinaryType = SCS_64BIT_BINARY;
  186. break;
  187. default:
  188. BaseSetLastNTError(Status);
  189. goto GBTtryexit;
  190. }
  191. }
  192. else {
  193. //
  194. // Query the section
  195. //
  196. Status = NtQuerySection(
  197. SectionHandle,
  198. SectionImageInformation,
  199. &ImageInformation,
  200. sizeof( ImageInformation ),
  201. NULL
  202. );
  203. if (!NT_SUCCESS( Status )) {
  204. BaseSetLastNTError(Status);
  205. goto GBTtryexit;
  206. }
  207. if (ImageInformation.ImageCharacteristics & IMAGE_FILE_DLL) {
  208. SetLastError(ERROR_BAD_EXE_FORMAT);
  209. goto GBTtryexit;
  210. }
  211. if (ImageInformation.Machine !=
  212. RtlImageNtHeader(NtCurrentPeb()->ImageBaseAddress)->FileHeader.Machine) {
  213. #ifdef MIPS
  214. if ( ImageInformation.Machine == IMAGE_FILE_MACHINE_R3000 ||
  215. ImageInformation.Machine == IMAGE_FILE_MACHINE_R4000 ) {
  216. ;
  217. }
  218. else {
  219. SetLastError(ERROR_BAD_EXE_FORMAT);
  220. goto GBTtryexit;
  221. }
  222. #else
  223. switch ( ImageInformation.Machine ) {
  224. case IMAGE_FILE_MACHINE_I386:
  225. fBinaryType = SCS_32BIT_BINARY;
  226. break;
  227. #if defined(BUILD_WOW6432)
  228. //
  229. // GetBinaryType (64-bit image) from an application running on win64
  230. // will fall to here since the 64-bit kernel allows creation of 32-bit/64-bit
  231. // image sections.
  232. //
  233. case IMAGE_FILE_MACHINE_IA64:
  234. case IMAGE_FILE_MACHINE_AMD64:
  235. fBinaryType = SCS_64BIT_BINARY;
  236. break;
  237. #endif
  238. default:
  239. SetLastError(ERROR_BAD_EXE_FORMAT);
  240. goto GBTtryexit;
  241. }
  242. #endif // MIPS
  243. }
  244. else if ( ImageInformation.SubSystemType != IMAGE_SUBSYSTEM_WINDOWS_GUI &&
  245. ImageInformation.SubSystemType != IMAGE_SUBSYSTEM_WINDOWS_CUI ) {
  246. if ( ImageInformation.SubSystemType == IMAGE_SUBSYSTEM_POSIX_CUI ) {
  247. fBinaryType = SCS_POSIX_BINARY;
  248. }
  249. }
  250. }
  251. *lpBinaryType = fBinaryType;
  252. bReturn = TRUE;
  253. GBTtryexit:;
  254. }
  255. finally {
  256. if (SectionHandle)
  257. NtClose(SectionHandle);
  258. if (FreeBuffer)
  259. RtlFreeHeap(RtlProcessHeap(), 0,FreeBuffer);
  260. }
  261. return bReturn;
  262. }
  263. VOID
  264. APIENTRY
  265. VDMOperationStarted
  266. (
  267. BOOL IsWowCaller
  268. )
  269. /*++
  270. Routine Description:
  271. This routine is used by MVDM to tell base that it has hooked
  272. ctrl-c handler with console. If the cmd window is killed
  273. before VDM could hook ctrl-c, then we wont get a chance to
  274. cleanup our data structures. The absence of this call tells
  275. base that it has to clean up the resources next time a
  276. call is made to create a VDM.
  277. Arguments:
  278. IsWowCaller - TRUE if the caller is WOWVDM
  279. Return Value:
  280. None
  281. --*/
  282. {
  283. BaseUpdateVDMEntry(UPDATE_VDM_HOOKED_CTRLC,
  284. NULL,
  285. 0,
  286. IsWowCaller);
  287. return;
  288. }
  289. BOOL
  290. APIENTRY
  291. GetNextVDMCommand(
  292. PVDMINFO lpVDMInfo
  293. )
  294. /*++
  295. Routine Description:
  296. This routine is used by MVDM to get a new command to execute. The
  297. VDM is blocked untill a DOS/WOW binary is encountered.
  298. Arguments:
  299. lpVDMInfo - pointer to VDMINFO where new DOS command and other
  300. enviornment information is returned.
  301. if lpVDMInfo is NULL, then the caller is
  302. asking whether its the first VDM in the system.
  303. Return Value:
  304. TRUE - The operation was successful. lpVDMInfo is filled in.
  305. FALSE/NULL - The operation failed.
  306. --*/
  307. {
  308. NTSTATUS Status;
  309. BASE_API_MSG m;
  310. PBASE_GET_NEXT_VDM_COMMAND_MSG a = &m.u.GetNextVDMCommand;
  311. PBASE_EXIT_VDM_MSG c = &m.u.ExitVDM;
  312. PBASE_IS_FIRST_VDM_MSG d = &m.u.IsFirstVDM;
  313. PBASE_SET_REENTER_COUNT_MSG e = &m.u.SetReenterCount;
  314. PCSR_CAPTURE_HEADER CaptureBuffer;
  315. ULONG Len,nPointers;
  316. USHORT VDMStateSave;
  317. // Special case to query the first VDM In the system.
  318. if(lpVDMInfo == NULL){
  319. Status = CsrClientCallServer(
  320. (PCSR_API_MSG)&m,
  321. NULL,
  322. CSR_MAKE_API_NUMBER(BASESRV_SERVERDLL_INDEX,
  323. BasepIsFirstVDM
  324. ),
  325. sizeof( *d )
  326. );
  327. if (NT_SUCCESS(Status)) {
  328. return(d->FirstVDM);
  329. }
  330. else {
  331. BaseSetLastNTError(Status);
  332. return FALSE;
  333. }
  334. }
  335. // Special case to increment/decrement the re-enterancy count
  336. if (lpVDMInfo->VDMState == INCREMENT_REENTER_COUNT ||
  337. lpVDMInfo->VDMState == DECREMENT_REENTER_COUNT) {
  338. e->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  339. e->fIncDec = lpVDMInfo->VDMState;
  340. Status = CsrClientCallServer(
  341. (PCSR_API_MSG)&m,
  342. NULL,
  343. CSR_MAKE_API_NUMBER( BASESRV_SERVERDLL_INDEX,
  344. BasepSetReenterCount
  345. ),
  346. sizeof( *e )
  347. );
  348. if (NT_SUCCESS(Status)) {
  349. return TRUE;
  350. }
  351. else {
  352. BaseSetLastNTError(Status);
  353. return FALSE;
  354. }
  355. }
  356. VDMStateSave = lpVDMInfo->VDMState;
  357. // console handle is always passed on in this case
  358. // wow is differentiated by a parameter a->VDMState
  359. // a->VDMState & ASKING_FOR_WOW_BINARY indicates wow
  360. a->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  361. if (lpVDMInfo->VDMState & ASKING_FOR_PIF) {
  362. a->iTask = lpVDMInfo->iTask;
  363. }
  364. else {
  365. a->iTask = 0;
  366. }
  367. a->AppLen = lpVDMInfo->AppLen;
  368. a->PifLen = lpVDMInfo->PifLen;
  369. a->CmdLen = lpVDMInfo->CmdSize;
  370. a->EnvLen = lpVDMInfo->EnviornmentSize;
  371. a->ExitCode = lpVDMInfo->ErrorCode;
  372. a->VDMState = VDMStateSave;
  373. a->WaitObjectForVDM = 0;
  374. a->DesktopLen = lpVDMInfo->DesktopLen;
  375. a->TitleLen = lpVDMInfo->TitleLen;
  376. a->ReservedLen = lpVDMInfo->ReservedLen;
  377. a->CurDirectoryLen = lpVDMInfo->CurDirectoryLen;
  378. // Find the total space for capture buffer
  379. // startup info
  380. Len = ROUND_UP(sizeof(STARTUPINFOA),4);
  381. nPointers = 1;
  382. if (lpVDMInfo->CmdSize) {
  383. Len += ROUND_UP(a->CmdLen,4);
  384. nPointers++;
  385. }
  386. if (lpVDMInfo->AppLen) {
  387. Len +=ROUND_UP(a->AppLen,4);
  388. nPointers++;
  389. }
  390. if (lpVDMInfo->PifLen) {
  391. Len +=ROUND_UP(a->PifLen,4);
  392. nPointers++;
  393. }
  394. if (lpVDMInfo->Enviornment) {
  395. nPointers++;
  396. Len+= (lpVDMInfo->EnviornmentSize) ?
  397. ROUND_UP(lpVDMInfo->EnviornmentSize, 4) : 4;
  398. }
  399. if (lpVDMInfo->CurDirectoryLen == 0)
  400. a->CurDirectory = NULL;
  401. else{
  402. Len += ROUND_UP(lpVDMInfo->CurDirectoryLen,4);
  403. nPointers++;
  404. }
  405. if (lpVDMInfo->DesktopLen == 0)
  406. a->Desktop = NULL;
  407. else {
  408. Len += ROUND_UP(lpVDMInfo->DesktopLen,4);
  409. nPointers++;
  410. }
  411. if (lpVDMInfo->TitleLen == 0)
  412. a->Title = NULL;
  413. else {
  414. Len += ROUND_UP(lpVDMInfo->TitleLen,4);
  415. nPointers++;
  416. }
  417. if (lpVDMInfo->ReservedLen == 0)
  418. a->Reserved = NULL;
  419. else {
  420. Len += ROUND_UP(lpVDMInfo->ReservedLen,4);
  421. nPointers++;
  422. }
  423. CaptureBuffer = CsrAllocateCaptureBuffer(nPointers, Len);
  424. if (CaptureBuffer == NULL) {
  425. BaseSetLastNTError( STATUS_NO_MEMORY );
  426. return FALSE;
  427. }
  428. if (lpVDMInfo->CmdLine) {
  429. CsrAllocateMessagePointer( CaptureBuffer,
  430. lpVDMInfo->CmdSize,
  431. (PVOID *)&a->CmdLine
  432. );
  433. }
  434. else {
  435. a->CmdLine = NULL;
  436. }
  437. if (lpVDMInfo->AppLen) {
  438. CsrAllocateMessagePointer( CaptureBuffer,
  439. lpVDMInfo->AppLen,
  440. (PVOID *)&a->AppName
  441. );
  442. }
  443. else {
  444. a->AppName = NULL;
  445. }
  446. if (lpVDMInfo->PifLen) {
  447. CsrAllocateMessagePointer( CaptureBuffer,
  448. lpVDMInfo->PifLen,
  449. (PVOID *)&a->PifFile
  450. );
  451. }
  452. else {
  453. a->PifFile = NULL;
  454. }
  455. if (lpVDMInfo->EnviornmentSize) {
  456. CsrAllocateMessagePointer( CaptureBuffer,
  457. lpVDMInfo->EnviornmentSize,
  458. (PVOID *)&a->Env
  459. );
  460. }
  461. else {
  462. a->Env = NULL;
  463. }
  464. if (lpVDMInfo->CurDirectoryLen)
  465. CsrAllocateMessagePointer( CaptureBuffer,
  466. lpVDMInfo->CurDirectoryLen,
  467. (PVOID *)&a->CurDirectory
  468. );
  469. else
  470. a->CurDirectory = NULL;
  471. CsrAllocateMessagePointer( CaptureBuffer,
  472. sizeof(STARTUPINFOA),
  473. (PVOID *)&a->StartupInfo
  474. );
  475. if (lpVDMInfo->DesktopLen)
  476. CsrAllocateMessagePointer( CaptureBuffer,
  477. lpVDMInfo->DesktopLen,
  478. (PVOID *)&a->Desktop
  479. );
  480. else
  481. a->Desktop = NULL;
  482. if (lpVDMInfo->TitleLen)
  483. CsrAllocateMessagePointer( CaptureBuffer,
  484. lpVDMInfo->TitleLen,
  485. (PVOID *)&a->Title
  486. );
  487. else
  488. a->Title = NULL;
  489. if (lpVDMInfo->ReservedLen)
  490. CsrAllocateMessagePointer( CaptureBuffer,
  491. lpVDMInfo->ReservedLen,
  492. (PVOID *)&a->Reserved
  493. );
  494. else
  495. a->Reserved = NULL;
  496. retry:
  497. Status = CsrClientCallServer(
  498. (PCSR_API_MSG)&m,
  499. CaptureBuffer,
  500. CSR_MAKE_API_NUMBER( BASESRV_SERVERDLL_INDEX,
  501. BasepGetNextVDMCommand
  502. ),
  503. sizeof( *a )
  504. );
  505. if (a->WaitObjectForVDM) {
  506. Status = NtWaitForSingleObject(a->WaitObjectForVDM,FALSE,NULL);
  507. if (Status != STATUS_SUCCESS){
  508. BaseSetLastNTError(Status);
  509. return FALSE;
  510. }
  511. else {
  512. a->VDMState |= ASKING_FOR_SECOND_TIME;
  513. a->ExitCode = 0;
  514. goto retry;
  515. }
  516. }
  517. if (NT_SUCCESS(Status)) {
  518. Status = (NTSTATUS)m.ReturnValue;
  519. }
  520. if (!NT_SUCCESS( Status )) {
  521. if (Status == STATUS_INVALID_PARAMETER) {
  522. //This means one of the buffer size is less than required.
  523. lpVDMInfo->CmdSize = a->CmdLen;
  524. lpVDMInfo->AppLen = a->AppLen;
  525. lpVDMInfo->PifLen = a->PifLen;
  526. lpVDMInfo->EnviornmentSize = a->EnvLen;
  527. lpVDMInfo->CurDirectoryLen = a->CurDirectoryLen;
  528. lpVDMInfo->DesktopLen = a->DesktopLen;
  529. lpVDMInfo->TitleLen = a->TitleLen;
  530. lpVDMInfo->ReservedLen = a->ReservedLen;
  531. }
  532. else {
  533. lpVDMInfo->CmdSize = 0;
  534. lpVDMInfo->AppLen = 0;
  535. lpVDMInfo->PifLen = 0;
  536. lpVDMInfo->EnviornmentSize = 0;
  537. lpVDMInfo->CurDirectoryLen = 0;
  538. lpVDMInfo->DesktopLen = 0;
  539. lpVDMInfo->TitleLen = 0;
  540. lpVDMInfo->ReservedLen = 0;
  541. }
  542. CsrFreeCaptureBuffer( CaptureBuffer );
  543. BaseSetLastNTError(Status);
  544. return FALSE;
  545. }
  546. try {
  547. if (lpVDMInfo->CmdSize)
  548. RtlMoveMemory(lpVDMInfo->CmdLine,
  549. a->CmdLine,
  550. a->CmdLen);
  551. if (lpVDMInfo->AppLen)
  552. RtlMoveMemory(lpVDMInfo->AppName,
  553. a->AppName,
  554. a->AppLen);
  555. if (lpVDMInfo->PifLen)
  556. RtlMoveMemory(lpVDMInfo->PifFile,
  557. a->PifFile,
  558. a->PifLen);
  559. if (lpVDMInfo->Enviornment)
  560. RtlMoveMemory(lpVDMInfo->Enviornment,
  561. a->Env,
  562. a->EnvLen);
  563. if (lpVDMInfo->CurDirectoryLen)
  564. RtlMoveMemory(lpVDMInfo->CurDirectory,
  565. a->CurDirectory,
  566. a->CurDirectoryLen);
  567. if (a->VDMState & STARTUP_INFO_RETURNED)
  568. RtlMoveMemory(&lpVDMInfo->StartupInfo,
  569. a->StartupInfo,
  570. sizeof(STARTUPINFOA));
  571. if (lpVDMInfo->DesktopLen){
  572. RtlMoveMemory(lpVDMInfo->Desktop,
  573. a->Desktop,
  574. a->DesktopLen);
  575. lpVDMInfo->StartupInfo.lpDesktop = lpVDMInfo->Desktop;
  576. }
  577. if (lpVDMInfo->TitleLen){
  578. RtlMoveMemory(lpVDMInfo->Title,
  579. a->Title,
  580. a->TitleLen);
  581. lpVDMInfo->StartupInfo.lpTitle = lpVDMInfo->Title;
  582. }
  583. if (lpVDMInfo->ReservedLen){
  584. RtlMoveMemory(lpVDMInfo->Reserved,
  585. a->Reserved,
  586. a->ReservedLen);
  587. lpVDMInfo->StartupInfo.lpReserved = lpVDMInfo->Reserved;
  588. }
  589. lpVDMInfo->CmdSize = a->CmdLen;
  590. lpVDMInfo->AppLen = a->AppLen;
  591. lpVDMInfo->PifLen = a->PifLen;
  592. lpVDMInfo->EnviornmentSize = a->EnvLen;
  593. if (a->VDMState & STARTUP_INFO_RETURNED)
  594. lpVDMInfo->VDMState = STARTUP_INFO_RETURNED;
  595. else
  596. lpVDMInfo->VDMState = 0;
  597. lpVDMInfo->CurDrive = a->CurrentDrive;
  598. lpVDMInfo->StdIn = a->StdIn;
  599. lpVDMInfo->StdOut = a->StdOut;
  600. lpVDMInfo->StdErr = a->StdErr;
  601. lpVDMInfo->iTask = a->iTask;
  602. lpVDMInfo->CodePage = a->CodePage;
  603. lpVDMInfo->CurDirectoryLen = a->CurDirectoryLen;
  604. lpVDMInfo->DesktopLen = a->DesktopLen;
  605. lpVDMInfo->TitleLen = a->TitleLen;
  606. lpVDMInfo->ReservedLen = a->ReservedLen;
  607. lpVDMInfo->dwCreationFlags = a->dwCreationFlags;
  608. lpVDMInfo->fComingFromBat = a->fComingFromBat;
  609. CsrFreeCaptureBuffer( CaptureBuffer );
  610. return TRUE;
  611. }
  612. except ( EXCEPTION_EXECUTE_HANDLER ) {
  613. BaseSetLastNTError(GetExceptionCode());
  614. CsrFreeCaptureBuffer( CaptureBuffer );
  615. return FALSE;
  616. }
  617. }
  618. VOID
  619. APIENTRY
  620. ExitVDM(
  621. BOOL IsWowCaller,
  622. ULONG iWowTask
  623. )
  624. /*++
  625. Routine Description:
  626. This routine is used by MVDM to exit.
  627. Arguments:
  628. IsWowCaller - TRUE if the caller is WOWVDM.
  629. FALSE if the caller is DOSVDM
  630. This parameter is obsolete as basesrv knows about the kind
  631. of vdm that is calling us
  632. iWowTask - if IsWowCaller == FALSE then Dont Care
  633. - if IsWowCaller == TRUE && iWowTask != -1 kill iWowTask task
  634. - if IsWowCaller == TRUE && iWowTask == -1 kill all wow task
  635. Return Value:
  636. None
  637. --*/
  638. {
  639. NTSTATUS Status;
  640. BASE_API_MSG m;
  641. PBASE_EXIT_VDM_MSG c = &m.u.ExitVDM;
  642. c->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  643. if (IsWowCaller) {
  644. c->iWowTask = iWowTask;
  645. }
  646. else {
  647. c->iWowTask = 0;
  648. }
  649. // this parameter means
  650. c->WaitObjectForVDM =0;
  651. Status = CsrClientCallServer(
  652. (PCSR_API_MSG)&m,
  653. NULL,
  654. CSR_MAKE_API_NUMBER( BASESRV_SERVERDLL_INDEX,
  655. BasepExitVDM
  656. ),
  657. sizeof( *c )
  658. );
  659. if (NT_SUCCESS(Status) && c->WaitObjectForVDM) {
  660. NtClose (c->WaitObjectForVDM);
  661. }
  662. return;
  663. }
  664. /*++
  665. Routine Description:
  666. Set new VDM current directories
  667. Arguments:
  668. cchCurDir - length of buffer in bytes
  669. lpszCurDir - buffer to return the current director of NTVDM
  670. Return Value:
  671. TRUE if function succeed
  672. FALSE if function failed, GetLastError() has the error code
  673. --*/
  674. BOOL
  675. APIENTRY
  676. SetVDMCurrentDirectories(
  677. IN ULONG cchCurDirs,
  678. IN LPSTR lpszzCurDirs
  679. )
  680. {
  681. NTSTATUS Status;
  682. PCSR_CAPTURE_HEADER CaptureBuffer;
  683. BASE_API_MSG m;
  684. PBASE_GET_SET_VDM_CUR_DIRS_MSG a = &m.u.GetSetVDMCurDirs;
  685. a->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  686. // caller must have a valid console(WOW will fail)
  687. if (a->ConsoleHandle == (HANDLE) -1) {
  688. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  689. return FALSE;
  690. }
  691. if (cchCurDirs && lpszzCurDirs) {
  692. // get capture buffer, one pointer in the message
  693. CaptureBuffer = CsrAllocateCaptureBuffer(1, cchCurDirs);
  694. if (CaptureBuffer == NULL) {
  695. BaseSetLastNTError( STATUS_NO_MEMORY );
  696. return FALSE;
  697. }
  698. CsrAllocateMessagePointer( CaptureBuffer,
  699. cchCurDirs,
  700. (PVOID *)&a->lpszzCurDirs
  701. );
  702. a->cchCurDirs = cchCurDirs;
  703. try {
  704. RtlMoveMemory(a->lpszzCurDirs, lpszzCurDirs, cchCurDirs);
  705. }
  706. except (EXCEPTION_EXECUTE_HANDLER) {
  707. BaseSetLastNTError(GetExceptionCode());
  708. CsrFreeCaptureBuffer(CaptureBuffer);
  709. return FALSE;
  710. }
  711. Status = CsrClientCallServer(
  712. (PCSR_API_MSG)&m,
  713. CaptureBuffer,
  714. CSR_MAKE_API_NUMBER(BASESRV_SERVERDLL_INDEX,
  715. BasepSetVDMCurDirs
  716. ),
  717. sizeof( *a )
  718. );
  719. CsrFreeCaptureBuffer(CaptureBuffer);
  720. if (!NT_SUCCESS(Status) || !NT_SUCCESS((NTSTATUS)m.ReturnValue)) {
  721. BaseSetLastNTError(Status);
  722. return FALSE;
  723. }
  724. }
  725. return TRUE;
  726. }
  727. /*++
  728. Routine Description:
  729. To return current directory of NTVDM.
  730. This allows the parent process(CMD.EXE in most cases) to keep track the
  731. current directory after each VDM execution.
  732. NOTE: this function doesn't apply to wow
  733. Arguments:
  734. cchCurDir - length of buffer in bytes
  735. lpszCurDir - buffer to return the current director of NTVDM
  736. Note: We don't require the process id to the running VDM because
  737. current directories are global to every VDMs under a single NTVDM
  738. control -- each console handle has its own current directories
  739. Return Value:
  740. ULONG - (1). number of bytes written to the given buffer if succeed
  741. (2). lentgh of the current directory including NULL
  742. if the provided buffer is not large enough
  743. (3). 0 then GetLastError() has the error code
  744. --*/
  745. ULONG
  746. APIENTRY
  747. GetVDMCurrentDirectories(
  748. IN ULONG cchCurDirs,
  749. IN LPSTR lpszzCurDirs
  750. )
  751. {
  752. NTSTATUS Status;
  753. PCSR_CAPTURE_HEADER CaptureBuffer;
  754. BASE_API_MSG m;
  755. PBASE_GET_SET_VDM_CUR_DIRS_MSG a = &m.u.GetSetVDMCurDirs;
  756. a->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  757. if (a->ConsoleHandle == (HANDLE) -1) {
  758. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  759. return 0L;
  760. }
  761. if (cchCurDirs && lpszzCurDirs) {
  762. CaptureBuffer = CsrAllocateCaptureBuffer(1, cchCurDirs);
  763. if (CaptureBuffer == NULL) {
  764. BaseSetLastNTError( STATUS_NO_MEMORY );
  765. return FALSE;
  766. }
  767. CsrAllocateMessagePointer( CaptureBuffer,
  768. cchCurDirs,
  769. (PVOID *)&a->lpszzCurDirs
  770. );
  771. a->cchCurDirs = cchCurDirs;
  772. }
  773. else {
  774. a->cchCurDirs = 0;
  775. a->lpszzCurDirs = NULL;
  776. CaptureBuffer = NULL;
  777. }
  778. m.ReturnValue = 0xffffffff;
  779. Status = CsrClientCallServer(
  780. (PCSR_API_MSG)&m,
  781. CaptureBuffer,
  782. CSR_MAKE_API_NUMBER(BASESRV_SERVERDLL_INDEX,
  783. BasepGetVDMCurDirs
  784. ),
  785. sizeof( *a )
  786. );
  787. if (m.ReturnValue == 0xffffffff) {
  788. a->cchCurDirs = 0;
  789. }
  790. if (NT_SUCCESS(Status)) {
  791. Status = m.ReturnValue;
  792. }
  793. if (NT_SUCCESS(Status)) {
  794. try {
  795. RtlMoveMemory(lpszzCurDirs, a->lpszzCurDirs, a->cchCurDirs);
  796. }
  797. except(EXCEPTION_EXECUTE_HANDLER) {
  798. Status = GetExceptionCode();
  799. a->cchCurDirs = 0;
  800. }
  801. }
  802. else {
  803. BaseSetLastNTError(Status);
  804. }
  805. if (CaptureBuffer) {
  806. CsrFreeCaptureBuffer(CaptureBuffer);
  807. }
  808. return a->cchCurDirs;
  809. }
  810. VOID
  811. APIENTRY
  812. CmdBatNotification(
  813. IN ULONG fBeginEnd
  814. )
  815. /*++
  816. Routine Description:
  817. This API lets base know about .bat processing from cmd. This is
  818. required by VDM, so that it can decided correctly when to put
  819. command.com prompt on TSRs. If the command came from .bat file
  820. then VDM should'nt put its prompt. This is important for
  821. ventura publisher and civilization apps.
  822. Arguments:
  823. fBeginEnd - CMD_BAT_OPERATION_STARTING -> .BAT processing is starting
  824. CMD_BAT_OPERATION_TERMINATING -> .BAT processing is ending
  825. Return Value:
  826. None
  827. --*/
  828. {
  829. #if defined(BUILD_WOW6432)
  830. // 32-bit cmd.exe calls this in WOW64, but there is no VDM support, so
  831. // no need for a WOW64 thunk for it.
  832. UNREFERENCED_PARAMETER(fBeginEnd);
  833. #else
  834. BASE_API_MSG m;
  835. PBASE_BAT_NOTIFICATION_MSG a = &m.u.BatNotification;
  836. a->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  837. if (a->ConsoleHandle == (HANDLE) -1)
  838. return;
  839. a->fBeginEnd = fBeginEnd;
  840. CsrClientCallServer((PCSR_API_MSG)&m,
  841. NULL,
  842. CSR_MAKE_API_NUMBER(BASESRV_SERVERDLL_INDEX,
  843. BasepBatNotification
  844. ),
  845. sizeof( *a )
  846. );
  847. #endif
  848. return;
  849. }
  850. NTSTATUS
  851. APIENTRY
  852. RegisterWowExec(
  853. IN HANDLE hwndWowExec
  854. )
  855. /*++
  856. Routine Description:
  857. This API gives basesrv the window handle for the shared WowExec so
  858. it can send WM_WOWEXECSTARTAPP messages to WowExec. This
  859. saves having a thread in WOW dedicated to GetNextVDMCommand.
  860. Arguments:
  861. hwndWowExec - Win32 window handle for WowExec in shared WOW VDM.
  862. Separate WOW VDMs don't register their WowExec handle
  863. because they never get commands from base.
  864. NULL is passed to de-register any given wowexec
  865. Return Value:
  866. If hwndWowExec != NULL then returns success if wow had been registered successfully
  867. if hwndWowExec == NULL then returns success if no tasks are pending to be executed
  868. --*/
  869. {
  870. BASE_API_MSG m;
  871. PBASE_REGISTER_WOWEXEC_MSG a = &m.u.RegisterWowExec;
  872. NTSTATUS Status;
  873. a->hwndWowExec = hwndWowExec;
  874. a->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  875. Status = CsrClientCallServer((PCSR_API_MSG)&m,
  876. NULL,
  877. CSR_MAKE_API_NUMBER(BASESRV_SERVERDLL_INDEX,
  878. BasepRegisterWowExec
  879. ),
  880. sizeof( *a )
  881. );
  882. return Status;
  883. }
  884. /*++
  885. Routine Description:
  886. This routine is used to close standard IO handles before returning to the
  887. caller
  888. Arguments:
  889. pVDMInfo - VDM Info record containing stdio handles
  890. Return Value:
  891. None
  892. --*/
  893. VOID
  894. BaseCloseStandardHandle(
  895. IN PVDMINFO pVDMInfo
  896. )
  897. {
  898. if (pVDMInfo->StdIn)
  899. NtClose (pVDMInfo->StdIn);
  900. if (pVDMInfo->StdOut)
  901. NtClose (pVDMInfo->StdOut);
  902. if (pVDMInfo->StdErr)
  903. NtClose (pVDMInfo->StdErr);
  904. pVDMInfo->StdIn = 0;
  905. pVDMInfo->StdOut = 0;
  906. pVDMInfo->StdErr = 0;
  907. }
  908. #ifdef OLD_CFG_BASED
  909. BOOL
  910. BaseGetVDMKeyword(
  911. PCHAR KeywordLine,
  912. PCONFIG_KEYWORD *pKeywordLine,
  913. PCHAR KeywordSize,
  914. PULONG VdmSize
  915. )
  916. {
  917. NTSTATUS Status;
  918. PCONFIG_FILE ConfigFile;
  919. PCONFIG_SECTION Section;
  920. STRING SectionName, KeywordName;
  921. PCONFIG_KEYWORD pKeywordSize;
  922. //
  923. // Retrieve the VDM configuration information from the config file
  924. //
  925. Status = RtlOpenConfigFile( NULL, &ConfigFile );
  926. if (!NT_SUCCESS( Status )) {
  927. return FALSE;
  928. }
  929. //
  930. // Find WOW section of config file
  931. //
  932. RtlInitString( &SectionName, "WOW" );
  933. Section = RtlLocateSectionConfigFile( ConfigFile, &SectionName );
  934. if (Section == NULL) {
  935. RtlCloseConfigFile( ConfigFile );
  936. return FALSE;
  937. }
  938. //
  939. // Get command line
  940. //
  941. RtlInitString( &KeywordName, KeywordLine );
  942. *pKeywordLine = RtlLocateKeywordConfigFile( Section, &KeywordName );
  943. if (*pKeywordLine == NULL) {
  944. RtlCloseConfigFile( ConfigFile );
  945. return FALSE;
  946. }
  947. //
  948. // Get Vdm size
  949. //
  950. RtlInitString( &KeywordName, KeywordSize );
  951. pKeywordSize = RtlLocateKeywordConfigFile( Section, &KeywordName );
  952. if (pKeywordSize == NULL) {
  953. *VdmSize = 1024L * 1024L * 16L;
  954. } else {
  955. Status = RtlCharToInteger( pKeywordSize->Value.Buffer, 0, VdmSize );
  956. if (!NT_SUCCESS( Status )) {
  957. *VdmSize = 1024L * 1024L * 16L;
  958. } else {
  959. *VdmSize *= 1024L * 1024L; // convert to MB
  960. }
  961. }
  962. return TRUE;
  963. }
  964. #endif
  965. BOOL
  966. BaseGetVDMKeyword(
  967. LPWSTR KeywordLine,
  968. LPSTR KeywordLineValue,
  969. LPDWORD KeywordLineSize,
  970. LPWSTR KeywordSize,
  971. LPDWORD VdmSize
  972. )
  973. {
  974. NTSTATUS NtStatus;
  975. UNICODE_STRING UnicodeString,UnicodeTemp;
  976. UNICODE_STRING KeyName;
  977. ANSI_STRING AnsiString;
  978. LPWSTR UnicodeBuffer,Temp;
  979. OBJECT_ATTRIBUTES ObjectAttributes;
  980. HANDLE hKey = NULL;
  981. PKEY_VALUE_FULL_INFORMATION pKeyValueInformation;
  982. //
  983. // Allocate Work buffer
  984. //
  985. UnicodeBuffer = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( VDM_TAG ), FULL_INFO_BUFFER_SIZE);
  986. if (!UnicodeBuffer) {
  987. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  988. return(FALSE);
  989. }
  990. // Open the WOW key
  991. RtlInitUnicodeString (&KeyName, WOW_ROOT);
  992. InitializeObjectAttributes(&ObjectAttributes,
  993. &KeyName,
  994. OBJ_CASE_INSENSITIVE,
  995. NULL,
  996. NULL
  997. );
  998. NtStatus = NtOpenKey(&hKey, KEY_READ, &ObjectAttributes);
  999. if (NtStatus == STATUS_OBJECT_NAME_NOT_FOUND) {
  1000. BaseSetLastNTError(NtStatus);
  1001. return FALSE;
  1002. }
  1003. if (!GetVDMConfigValue(hKey,KeywordLine,UnicodeBuffer)) {
  1004. NtClose (hKey);
  1005. RtlFreeHeap(RtlProcessHeap(), 0, UnicodeBuffer);
  1006. return(FALSE);
  1007. }
  1008. //
  1009. // Now convert back to ANSI for the caller after doing all the substitution
  1010. //
  1011. pKeyValueInformation = (PVOID)UnicodeBuffer;
  1012. Temp = (LPWSTR)((PBYTE) pKeyValueInformation + pKeyValueInformation->DataOffset);
  1013. RtlInitUnicodeString( &UnicodeString, Temp );
  1014. UnicodeTemp.Buffer = (LPWSTR)KeywordLineValue;
  1015. UnicodeTemp.Length = 0;
  1016. UnicodeTemp.MaximumLength = MAX_VDM_CFG_LINE;
  1017. NtStatus = RtlExpandEnvironmentStrings_U (NULL,&UnicodeString, &UnicodeTemp, NULL);
  1018. if (!NT_SUCCESS( NtStatus )){
  1019. NtClose (hKey);
  1020. RtlFreeHeap(RtlProcessHeap(), 0, UnicodeBuffer);
  1021. return FALSE;
  1022. }
  1023. wcscpy(UnicodeString.Buffer,UnicodeTemp.Buffer);
  1024. UnicodeString.Length = UnicodeTemp.Length;
  1025. //
  1026. // Set up an ANSI_STRING that points to the user's buffer
  1027. //
  1028. AnsiString.MaximumLength = (USHORT) *KeywordLineSize;
  1029. AnsiString.Length = 0;
  1030. AnsiString.Buffer = KeywordLineValue;
  1031. RtlUnicodeStringToAnsiString(&AnsiString, &UnicodeString, FALSE);
  1032. *KeywordLineSize = AnsiString.Length;
  1033. // Always set the VDMSize to 16Mb. (This is for reservation only)
  1034. // Actual commit is done by SAS_INIT.
  1035. //
  1036. // jarbats
  1037. // for meow subsystem we need more than 16mb reserved for
  1038. // loading win32 pe exes
  1039. // VDMSize is set to 32Mb.
  1040. *VdmSize = 32L; //default value is 32
  1041. *VdmSize *= 1024L * 1024L; // convert From MB
  1042. NtClose (hKey);
  1043. RtlFreeHeap(RtlProcessHeap(), 0, UnicodeBuffer);
  1044. return(TRUE);
  1045. }
  1046. BOOL
  1047. GetVDMConfigValue(
  1048. HANDLE hKey,
  1049. LPWSTR Keyword,
  1050. LPWSTR UnicodeBuffer
  1051. )
  1052. {
  1053. NTSTATUS NtStatus;
  1054. UNICODE_STRING ValueName;
  1055. PKEY_VALUE_FULL_INFORMATION pKeyValueInformation = (PVOID) UnicodeBuffer;
  1056. ULONG ValueLength;
  1057. RtlInitUnicodeString(&ValueName, Keyword);
  1058. NtStatus = NtQueryValueKey(hKey,
  1059. &ValueName,
  1060. KeyValueFullInformation,
  1061. pKeyValueInformation,
  1062. FULL_INFO_BUFFER_SIZE,
  1063. &ValueLength);
  1064. if (NT_SUCCESS(NtStatus))
  1065. return TRUE;
  1066. else {
  1067. BaseSetLastNTError (NtStatus);
  1068. return FALSE;
  1069. }
  1070. }
  1071. NTSTATUS
  1072. BaseCheckVDMp(
  1073. IN ULONG BinaryType,
  1074. IN PCWCH lpApplicationName,
  1075. IN PCWCH lpCommandLine,
  1076. IN PCWCH lpCurrentDirectory,
  1077. IN ANSI_STRING *pAnsiStringEnv,
  1078. IN PBASE_API_MSG m,
  1079. IN OUT PULONG iTask,
  1080. IN DWORD dwCreationFlags,
  1081. LPSTARTUPINFOW lpStartupInfo
  1082. )
  1083. /*++
  1084. Routine Description:
  1085. This routine calls the windows server to find out if the VDM for the
  1086. current session is already present. If so, a new process is'nt created
  1087. instead the DOS binary is dispatched to the existing VDM. Otherwise,
  1088. a new VDM process is created. This routine also passes the app name
  1089. and command line to the server in DOS int21/0ah style which is later
  1090. passed by the server to the VDM.
  1091. Arguments:
  1092. BinaryType - DOS/WOW binary
  1093. lpApplicationName -- pointer to the full path name of the executable.
  1094. lpCommandLine -- command line
  1095. lpCurrentDirectory - Current directory
  1096. lpEnvironment, - Envirinment strings
  1097. m - pointer to the base api message.
  1098. iTask - taskid for win16 apps, and no-console dos apps
  1099. dwCreationFlags - creation flags as passed to createprocess
  1100. lpStartupInfo =- pointer to startupinfo as passed to createprocess
  1101. Return Value:
  1102. OEM vs. ANSI:
  1103. The command line, Application Name, title are converted to OEM strings,
  1104. suitable for the VDM. All other strings are returned as ANSI.
  1105. returns nt status code of the last operation
  1106. STATUS_ACCESS_DENIED -- Operation failed (desktop access denied)
  1107. STATUS_SUCCESS -- Operation sucseeded
  1108. --*/
  1109. {
  1110. NTSTATUS Status = STATUS_UNSUCCESSFUL;
  1111. PPEB Peb;
  1112. PBASE_CHECKVDM_MSG b= (PBASE_CHECKVDM_MSG)&m->u.CheckVDM;
  1113. PCSR_CAPTURE_HEADER CaptureBuffer;
  1114. ANSI_STRING AnsiStringCurrentDir,AnsiStringDesktop;
  1115. ANSI_STRING AnsiStringReserved, AnsiStringPif;
  1116. OEM_STRING OemStringCmd, OemStringAppName, OemStringTitle;
  1117. UNICODE_STRING UnicodeString;
  1118. PCHAR pch, Buffer = NULL;
  1119. ULONG Len;
  1120. ULONG bufPointers;
  1121. LPWSTR wsBuffer;
  1122. LPWSTR wsAppName;
  1123. LPWSTR wsPifName;
  1124. LPWSTR wsCmdLine;
  1125. LPWSTR wsPif=(PWSTR)".\0p\0i\0f\0\0"; // L".pif"
  1126. LPWSTR wsSharedWowPif=L"wowexec.pif";
  1127. PWCHAR pwch;
  1128. BOOLEAN bNewConsole;
  1129. DWORD dw, dwTotal, Length;
  1130. WCHAR wchBuffer[MAX_PATH + 1];
  1131. ULONG BinarySubType;
  1132. LPWSTR lpAllocatedReserved = NULL;
  1133. DWORD HandleFlags;
  1134. // does a trivial test of the environment
  1135. if (!ARGUMENT_PRESENT(pAnsiStringEnv) ||
  1136. pAnsiStringEnv->Length > MAXIMUM_VDM_ENVIORNMENT) {
  1137. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  1138. return STATUS_INVALID_PARAMETER;
  1139. }
  1140. wsCmdLine = wsAppName = NULL;
  1141. OemStringCmd.Buffer = NULL;
  1142. OemStringAppName.Buffer = NULL;
  1143. AnsiStringCurrentDir.Buffer = NULL;
  1144. AnsiStringDesktop.Buffer = NULL;
  1145. AnsiStringPif.Buffer = NULL;
  1146. OemStringTitle.Buffer = NULL;
  1147. AnsiStringReserved.Buffer = NULL;
  1148. wsBuffer = NULL;
  1149. wsPifName = NULL;
  1150. BinarySubType = BinaryType & BINARY_SUBTYPE_MASK;
  1151. BinaryType = BinaryType & ~BINARY_SUBTYPE_MASK;
  1152. bNewConsole = !NtCurrentPeb()->ProcessParameters->ConsoleHandle ||
  1153. (dwCreationFlags & CREATE_NEW_CONSOLE);
  1154. try {
  1155. if (BinaryType == BINARY_TYPE_DOS) {
  1156. Peb = NtCurrentPeb();
  1157. if (lpStartupInfo && lpStartupInfo->dwFlags & STARTF_USESTDHANDLES) {
  1158. b->StdIn = lpStartupInfo->hStdInput;
  1159. b->StdOut = lpStartupInfo->hStdOutput;
  1160. b->StdErr = lpStartupInfo->hStdError;
  1161. }
  1162. else {
  1163. b->StdIn = Peb->ProcessParameters->StandardInput;
  1164. b->StdOut = Peb->ProcessParameters->StandardOutput;
  1165. b->StdErr = Peb->ProcessParameters->StandardError;
  1166. //
  1167. // Verify that the standard handles ntvdm process will inherit
  1168. // from the calling process are real handles. They are not
  1169. // handles if the calling process was created with
  1170. // STARTF_USEHOTKEY | STARTF_HASSHELLDATA.
  1171. // Note that CreateProcess clears STARTF_USESTANDHANDLES
  1172. // if either STARTF_USEHOTKEY or STARTF_HASSHELLDATA is set.
  1173. //
  1174. if (Peb->ProcessParameters->WindowFlags &
  1175. (STARTF_USEHOTKEY | STARTF_HASSHELLDATA)) {
  1176. if (b->StdIn && !CONSOLE_HANDLE(b->StdIn) &&
  1177. !GetHandleInformation(b->StdIn, &HandleFlags))
  1178. b->StdIn = 0;
  1179. if (b->StdOut && !CONSOLE_HANDLE(b->StdOut) &&
  1180. !GetHandleInformation(b->StdOut, &HandleFlags)) {
  1181. if (b->StdErr == b->StdOut)
  1182. b->StdErr = 0;
  1183. b->StdOut = 0;
  1184. }
  1185. if (b->StdErr && b->StdErr != b->StdOut &&
  1186. !CONSOLE_HANDLE(b->StdErr) &&
  1187. !GetHandleInformation(b->StdErr, &HandleFlags))
  1188. b->StdErr = 0;
  1189. }
  1190. }
  1191. if (CONSOLE_HANDLE((b->StdIn)))
  1192. b->StdIn = 0;
  1193. if (CONSOLE_HANDLE((b->StdOut)))
  1194. b->StdOut = 0;
  1195. if (CONSOLE_HANDLE((b->StdErr)))
  1196. b->StdErr = 0;
  1197. }
  1198. if (BinaryType == BINARY_TYPE_SEPWOW) {
  1199. bNewConsole = TRUE;
  1200. }
  1201. //
  1202. // Convert Unicode Application Name to Oem short name
  1203. //
  1204. // skiping leading white space
  1205. while(*lpApplicationName == (WCHAR)' ' || *lpApplicationName == (WCHAR)'\t' ) {
  1206. lpApplicationName++;
  1207. }
  1208. // space for short AppName
  1209. Len = wcslen(lpApplicationName);
  1210. dwTotal = Len + 1 + MAX_PATH;
  1211. wsAppName = RtlAllocateHeap(RtlProcessHeap(),
  1212. MAKE_TAG(VDM_TAG),
  1213. dwTotal * sizeof(WCHAR)
  1214. );
  1215. if (wsAppName == NULL) {
  1216. Status = STATUS_NO_MEMORY;
  1217. goto BCVTryExit;
  1218. }
  1219. dw = GetShortPathNameW(lpApplicationName, wsAppName, dwTotal);
  1220. // If getting the short name is impossible, stop right here.
  1221. // We can not execute a 16bits biranry if we can not find
  1222. // its appropriate short name alias. Sorry HPFS, Sorry NFS
  1223. if (0 == dw || dw > dwTotal) {
  1224. Status = STATUS_OBJECT_PATH_INVALID;
  1225. goto BCVTryExit;
  1226. }
  1227. RtlInitUnicodeString(&UnicodeString, wsAppName);
  1228. Status = RtlUnicodeStringToOemString(&OemStringAppName,
  1229. &UnicodeString,
  1230. TRUE
  1231. );
  1232. if (!NT_SUCCESS(Status) ){
  1233. goto BCVTryExit;
  1234. }
  1235. //
  1236. // Find len of basename excluding extension,
  1237. // for CommandTail max len check.
  1238. //
  1239. dw = OemStringAppName.Length;
  1240. pch = OemStringAppName.Buffer;
  1241. Length = 1; // start at one for space between cmdname & cmdtail
  1242. while (dw-- && *pch != '.') {
  1243. if (*pch == '\\') {
  1244. Length = 1;
  1245. }
  1246. else {
  1247. Length++;
  1248. }
  1249. pch++;
  1250. }
  1251. //
  1252. // Find the beg of the command tail to pass as the CmdLine
  1253. //
  1254. Len = wcslen(lpApplicationName);
  1255. if (L'"' == lpCommandLine[0]) {
  1256. //
  1257. // Application name is quoted, skip the quoted text
  1258. // to get command tail.
  1259. //
  1260. pwch = (LPWSTR)&lpCommandLine[1];
  1261. while (*pwch && L'"' != *pwch++) {
  1262. ;
  1263. }
  1264. } else if (Len <= wcslen(lpCommandLine) &&
  1265. 0 == _wcsnicmp(lpApplicationName, lpCommandLine, Len)) {
  1266. //
  1267. // Application path is also on the command line, skip past
  1268. // that to reach the command tail instead of looking for
  1269. // the first white space.
  1270. //
  1271. pwch = (LPWSTR)lpCommandLine + Len;
  1272. } else {
  1273. //
  1274. // We assume first token is exename (argv[0]).
  1275. //
  1276. pwch = (LPWSTR)lpCommandLine;
  1277. // skip leading white characters
  1278. while (*pwch != UNICODE_NULL &&
  1279. (*pwch == (WCHAR) ' ' || *pwch == (WCHAR) '\t')) {
  1280. pwch++;
  1281. }
  1282. // skip first token
  1283. if (*pwch == (WCHAR) '\"') { // quotes as delimiter
  1284. pwch++;
  1285. while (*pwch && *pwch++ != '\"') {
  1286. ;
  1287. }
  1288. }
  1289. else { // white space as delimiter
  1290. while (*pwch && *pwch != ' ' && *pwch != '\t') {
  1291. pwch++;
  1292. }
  1293. }
  1294. }
  1295. //
  1296. // pwch points past the application name, now skip any trailing
  1297. // whitespace.
  1298. //
  1299. while (*pwch && (L' ' == *pwch || L'\t' == *pwch)) {
  1300. pwch++;
  1301. }
  1302. wsCmdLine = pwch;
  1303. dw = wcslen(wsCmdLine);
  1304. // convert to oem
  1305. UnicodeString.Length = (USHORT)(dw * sizeof(WCHAR));
  1306. UnicodeString.MaximumLength = UnicodeString.Length + sizeof(WCHAR);
  1307. UnicodeString.Buffer = wsCmdLine;
  1308. Status = RtlUnicodeStringToOemString(
  1309. &OemStringCmd,
  1310. &UnicodeString,
  1311. TRUE);
  1312. if (!NT_SUCCESS(Status) ){
  1313. goto BCVTryExit;
  1314. }
  1315. //
  1316. // check len of command line for dos compatibility
  1317. //
  1318. if (OemStringCmd.Length >= MAXIMUM_VDM_COMMAND_LENGTH - Length) {
  1319. Status = STATUS_INVALID_PARAMETER;
  1320. goto BCVTryExit;
  1321. }
  1322. //
  1323. // Search for matching pif file. Search order is AppName dir,
  1324. // followed by win32 default search path. For the shared wow, pif
  1325. // is wowexec.pif if it exists.
  1326. //
  1327. wsBuffer = RtlAllocateHeap(RtlProcessHeap(),MAKE_TAG( VDM_TAG ),MAX_PATH*sizeof(WCHAR));
  1328. if (!wsBuffer) {
  1329. Status = STATUS_NO_MEMORY;
  1330. goto BCVTryExit;
  1331. }
  1332. wsPifName = RtlAllocateHeap(RtlProcessHeap(),MAKE_TAG( VDM_TAG ),MAX_PATH*sizeof(WCHAR));
  1333. if (!wsPifName) {
  1334. Status = STATUS_NO_MEMORY;
  1335. goto BCVTryExit;
  1336. }
  1337. if (BinaryType == BINARY_TYPE_WIN16) {
  1338. wcscpy(wsBuffer, wsSharedWowPif);
  1339. Len = 0;
  1340. }
  1341. else {
  1342. // start with fully qualified app name
  1343. wcscpy(wsBuffer, lpApplicationName);
  1344. // strip extension if any
  1345. pwch = wcsrchr(wsBuffer, (WCHAR)'.');
  1346. // dos application must have an extention
  1347. if (pwch == NULL) {
  1348. Status = STATUS_INVALID_PARAMETER;
  1349. goto BCVTryExit;
  1350. }
  1351. wcscpy(pwch, wsPif);
  1352. Len = GetFileAttributesW(wsBuffer);
  1353. if (Len == (DWORD)(-1) || (Len & FILE_ATTRIBUTE_DIRECTORY)) {
  1354. Len = 0;
  1355. }
  1356. else {
  1357. Len = wcslen(wsBuffer) + 1;
  1358. wcsncpy(wsPifName, wsBuffer, Len);
  1359. }
  1360. }
  1361. if (!Len) { // try basename
  1362. // find beg of basename
  1363. pwch = wcsrchr(wsBuffer, (WCHAR)'\\');
  1364. if (!pwch ) {
  1365. pwch = wcsrchr(wsBuffer, (WCHAR)':');
  1366. }
  1367. // move basename to beg of wsBuffer
  1368. if (pwch++) {
  1369. while (*pwch != UNICODE_NULL &&
  1370. *pwch != (WCHAR)' ' && *pwch != (WCHAR)'\t' )
  1371. {
  1372. wsBuffer[Len++] = *pwch++;
  1373. }
  1374. wsBuffer[Len] = UNICODE_NULL;
  1375. }
  1376. if (Len) {
  1377. Len = SearchPathW(
  1378. NULL,
  1379. wsBuffer,
  1380. wsPif, // L".pif"
  1381. MAX_PATH,
  1382. wsPifName,
  1383. NULL
  1384. );
  1385. if (Len >= MAX_PATH) {
  1386. Status = STATUS_NO_MEMORY;
  1387. goto BCVTryExit;
  1388. }
  1389. }
  1390. }
  1391. if (!Len)
  1392. *wsPifName = UNICODE_NULL;
  1393. if (!ARGUMENT_PRESENT( lpCurrentDirectory )) {
  1394. dw = RtlGetCurrentDirectory_U(sizeof (wchBuffer), wchBuffer);
  1395. wchBuffer[dw / sizeof(WCHAR)] = UNICODE_NULL;
  1396. dw = GetShortPathNameW(wchBuffer,
  1397. wchBuffer,
  1398. sizeof(wchBuffer) / sizeof(WCHAR)
  1399. );
  1400. if (dw > sizeof(wchBuffer) / sizeof(WCHAR))
  1401. goto BCVTryExit;
  1402. else if (dw == 0) {
  1403. RtlInitUnicodeString(&UnicodeString, wchBuffer);
  1404. dw = UnicodeString.Length / sizeof(WCHAR);
  1405. }
  1406. else {
  1407. UnicodeString.Length = (USHORT)(dw * sizeof(WCHAR));
  1408. UnicodeString.Buffer = wchBuffer;
  1409. UnicodeString.MaximumLength = (USHORT)sizeof(wchBuffer);
  1410. }
  1411. // DOS limit of 64 includes the final NULL but not the leading
  1412. // drive and slash. So here we should be checking the ansi length
  1413. // of current directory + 1 (for NULL) - 3 (for c:\).
  1414. if ( dw - 2 <= MAXIMUM_VDM_CURRENT_DIR ) {
  1415. Status = RtlUnicodeStringToAnsiString(
  1416. &AnsiStringCurrentDir,
  1417. &UnicodeString,
  1418. TRUE
  1419. );
  1420. }
  1421. else {
  1422. Status = STATUS_INVALID_PARAMETER;
  1423. }
  1424. if ( !NT_SUCCESS(Status) ) {
  1425. goto BCVTryExit;
  1426. }
  1427. }
  1428. else {
  1429. // first get a full path name
  1430. dw = GetFullPathNameW(lpCurrentDirectory,
  1431. sizeof(wchBuffer) / sizeof(WCHAR),
  1432. wchBuffer,
  1433. NULL);
  1434. if (0 != dw && dw <= sizeof(wchBuffer) / sizeof(WCHAR)) {
  1435. dw = GetShortPathNameW(wchBuffer,
  1436. wchBuffer,
  1437. sizeof(wchBuffer) / sizeof(WCHAR));
  1438. }
  1439. if (dw > sizeof(wchBuffer) / sizeof(WCHAR))
  1440. goto BCVTryExit;
  1441. if (dw != 0) {
  1442. UnicodeString.Buffer = wchBuffer;
  1443. UnicodeString.Length = (USHORT)(dw * sizeof(WCHAR));
  1444. UnicodeString.MaximumLength = sizeof(wchBuffer);
  1445. }
  1446. else
  1447. RtlInitUnicodeString(&UnicodeString, lpCurrentDirectory);
  1448. Status = RtlUnicodeStringToAnsiString(
  1449. &AnsiStringCurrentDir,
  1450. &UnicodeString,
  1451. TRUE);
  1452. if ( !NT_SUCCESS(Status) ){
  1453. goto BCVTryExit;
  1454. }
  1455. // DOS limit of 64 includes the final NULL but not the leading
  1456. // drive and slash. So here we should be checking the ansi length
  1457. // of current directory + 1 (for NULL) - 3 (for c:\).
  1458. if((AnsiStringCurrentDir.Length - 2) > MAXIMUM_VDM_CURRENT_DIR) {
  1459. Status = STATUS_INVALID_PARAMETER;
  1460. goto BCVTryExit;
  1461. }
  1462. }
  1463. // NT allows applications to use UNC name as their current directory.
  1464. // while NTVDM can't do that. We will end up a weird drive number
  1465. // like '\' - 'a') here ????????????????????????????????
  1466. //
  1467. // Place Current Drive
  1468. if(AnsiStringCurrentDir.Buffer[0] <= 'Z')
  1469. b->CurDrive = AnsiStringCurrentDir.Buffer[0] - 'A';
  1470. else
  1471. b->CurDrive = AnsiStringCurrentDir.Buffer[0] - 'a';
  1472. //
  1473. // Hotkey info in NT traditionally is specified in the
  1474. // startupinfo.lpReserved field, but Win95 added a
  1475. // duplicate mechanism. If the Win95 method was used,
  1476. // map it to the NT method here so the rest of the
  1477. // VDM code only has to deal with one method.
  1478. //
  1479. // If the caller was specified a hotkey
  1480. // in lpReserved as well as using STARTF_USEHOTKEY,
  1481. // the STARTF_USEHOTKEY hotkey will take precedence.
  1482. //
  1483. if (lpStartupInfo && lpStartupInfo->dwFlags & STARTF_USEHOTKEY) {
  1484. DWORD cbAlloc = sizeof(WCHAR) *
  1485. (20 + // "hotkey.4294967295 " (MAXULONG)
  1486. (lpStartupInfo->lpReserved // length of prev lpReserved
  1487. ? wcslen(lpStartupInfo->lpReserved)
  1488. : 0
  1489. ) +
  1490. 1 // NULL terminator
  1491. );
  1492. lpAllocatedReserved = RtlAllocateHeap(RtlProcessHeap(),
  1493. MAKE_TAG( VDM_TAG ),
  1494. cbAlloc
  1495. );
  1496. if (lpAllocatedReserved) {
  1497. swprintf(lpAllocatedReserved,
  1498. L"hotkey.%u %s",
  1499. HandleToUlong(lpStartupInfo->hStdInput),
  1500. lpStartupInfo->lpReserved ? lpStartupInfo->lpReserved : L""
  1501. );
  1502. lpStartupInfo->dwFlags &= ~STARTF_USEHOTKEY;
  1503. lpStartupInfo->hStdInput = 0;
  1504. lpStartupInfo->lpReserved = lpAllocatedReserved;
  1505. }
  1506. }
  1507. //
  1508. // Allocate Capture Buffer
  1509. //
  1510. //
  1511. bufPointers = 2; // CmdLine, AppName
  1512. //
  1513. // CmdLine for capture buffer, 3 for 0xd,0xa and NULL
  1514. //
  1515. Len = ROUND_UP((OemStringCmd.Length + 3),4);
  1516. // AppName, 1 for NULL
  1517. Len += ROUND_UP((OemStringAppName.Length + 1),4);
  1518. // Env
  1519. if (pAnsiStringEnv->Length) {
  1520. bufPointers++;
  1521. Len += ROUND_UP(pAnsiStringEnv->Length, 4);
  1522. }
  1523. // CurrentDir
  1524. if (AnsiStringCurrentDir.Length){
  1525. bufPointers++;
  1526. Len += ROUND_UP((AnsiStringCurrentDir.Length +1),4); // 1 for NULL
  1527. }
  1528. // pif file name, 1 for NULL
  1529. if (wsPifName && *wsPifName != UNICODE_NULL) {
  1530. bufPointers++;
  1531. RtlInitUnicodeString(&UnicodeString,wsPifName);
  1532. Status = RtlUnicodeStringToAnsiString(&AnsiStringPif,
  1533. &UnicodeString,
  1534. TRUE
  1535. );
  1536. if ( !NT_SUCCESS(Status) ){
  1537. goto BCVTryExit;
  1538. }
  1539. Len += ROUND_UP((AnsiStringPif.Length+1),4);
  1540. }
  1541. //
  1542. // startupinfo space
  1543. //
  1544. if (lpStartupInfo) {
  1545. Len += ROUND_UP(sizeof(STARTUPINFOA),4);
  1546. bufPointers++;
  1547. if (lpStartupInfo->lpDesktop) {
  1548. bufPointers++;
  1549. RtlInitUnicodeString(&UnicodeString,lpStartupInfo->lpDesktop);
  1550. Status = RtlUnicodeStringToAnsiString(
  1551. &AnsiStringDesktop,
  1552. &UnicodeString,
  1553. TRUE);
  1554. if ( !NT_SUCCESS(Status) ){
  1555. goto BCVTryExit;
  1556. }
  1557. Len += ROUND_UP((AnsiStringDesktop.Length+1),4);
  1558. }
  1559. if (lpStartupInfo->lpTitle) {
  1560. bufPointers++;
  1561. RtlInitUnicodeString(&UnicodeString,lpStartupInfo->lpTitle);
  1562. Status = RtlUnicodeStringToOemString(
  1563. &OemStringTitle,
  1564. &UnicodeString,
  1565. TRUE);
  1566. if ( !NT_SUCCESS(Status) ){
  1567. goto BCVTryExit;
  1568. }
  1569. Len += ROUND_UP((OemStringTitle.Length+1),4);
  1570. }
  1571. if (lpStartupInfo->lpReserved) {
  1572. bufPointers++;
  1573. RtlInitUnicodeString(&UnicodeString,lpStartupInfo->lpReserved);
  1574. Status = RtlUnicodeStringToAnsiString(
  1575. &AnsiStringReserved,
  1576. &UnicodeString,
  1577. TRUE);
  1578. if ( !NT_SUCCESS(Status) ){
  1579. goto BCVTryExit;
  1580. }
  1581. Len += ROUND_UP((AnsiStringReserved.Length+1),4);
  1582. }
  1583. }
  1584. // capture message buffer
  1585. CaptureBuffer = CsrAllocateCaptureBuffer(bufPointers, Len);
  1586. if (CaptureBuffer == NULL) {
  1587. Status = STATUS_NO_MEMORY;
  1588. goto BCVTryExit;
  1589. }
  1590. // Allocate CmdLine pointer
  1591. CsrAllocateMessagePointer( CaptureBuffer,
  1592. ROUND_UP((OemStringCmd.Length + 3),4),
  1593. (PVOID *)&b->CmdLine
  1594. );
  1595. // Copy Command Line
  1596. RtlMoveMemory (b->CmdLine, OemStringCmd.Buffer, OemStringCmd.Length);
  1597. b->CmdLine[OemStringCmd.Length] = 0xd;
  1598. b->CmdLine[OemStringCmd.Length+1] = 0xa;
  1599. b->CmdLine[OemStringCmd.Length+2] = 0;
  1600. b->CmdLen = (USHORT)(OemStringCmd.Length + 3);
  1601. // Allocate AppName pointer
  1602. CsrAllocateMessagePointer( CaptureBuffer,
  1603. ROUND_UP((OemStringAppName.Length + 1),4),
  1604. (PVOID *)&b->AppName
  1605. );
  1606. // Copy AppName
  1607. RtlMoveMemory (b->AppName,
  1608. OemStringAppName.Buffer,
  1609. OemStringAppName.Length
  1610. );
  1611. b->AppName[OemStringAppName.Length] = 0;
  1612. b->AppLen = OemStringAppName.Length + 1;
  1613. // Allocate PifFile pointer, Copy PifFile name
  1614. if(AnsiStringPif.Buffer) {
  1615. CsrAllocateMessagePointer( CaptureBuffer,
  1616. ROUND_UP((AnsiStringPif.Length + 1),4),
  1617. (PVOID *)&b->PifFile
  1618. );
  1619. RtlMoveMemory(b->PifFile,
  1620. AnsiStringPif.Buffer,
  1621. AnsiStringPif.Length);
  1622. b->PifFile[AnsiStringPif.Length] = 0;
  1623. b->PifLen = AnsiStringPif.Length + 1;
  1624. }
  1625. else {
  1626. b->PifLen = 0;
  1627. b->PifFile = NULL;
  1628. }
  1629. // Allocate Env pointer, Copy Env strings
  1630. if(pAnsiStringEnv->Length) {
  1631. CsrAllocateMessagePointer( CaptureBuffer,
  1632. ROUND_UP((pAnsiStringEnv->Length),4),
  1633. (PVOID *)&b->Env
  1634. );
  1635. RtlMoveMemory(b->Env,
  1636. pAnsiStringEnv->Buffer,
  1637. pAnsiStringEnv->Length);
  1638. b->EnvLen = pAnsiStringEnv->Length;
  1639. }
  1640. else {
  1641. b->EnvLen = 0;
  1642. b->Env = NULL;
  1643. }
  1644. if(AnsiStringCurrentDir.Length) {
  1645. // Allocate Curdir pointer
  1646. CsrAllocateMessagePointer( CaptureBuffer,
  1647. ROUND_UP((AnsiStringCurrentDir.Length + 1),4),
  1648. (PVOID *)&b->CurDirectory
  1649. );
  1650. // copy cur directory
  1651. RtlMoveMemory (b->CurDirectory,
  1652. AnsiStringCurrentDir.Buffer,
  1653. AnsiStringCurrentDir.Length+1);
  1654. b->CurDirectoryLen = AnsiStringCurrentDir.Length+1;
  1655. }
  1656. else {
  1657. b->CurDirectory = NULL;
  1658. b->CurDirectoryLen = 0;
  1659. }
  1660. // Allocate startupinfo pointer
  1661. if (lpStartupInfo) {
  1662. CsrAllocateMessagePointer( CaptureBuffer,
  1663. ROUND_UP(sizeof(STARTUPINFOA),4),
  1664. (PVOID *)&b->StartupInfo
  1665. );
  1666. // Copy startupinfo
  1667. b->StartupInfo->dwX = lpStartupInfo->dwX;
  1668. b->StartupInfo->dwY = lpStartupInfo->dwY;
  1669. b->StartupInfo->dwXSize = lpStartupInfo->dwXSize;
  1670. b->StartupInfo->dwYSize = lpStartupInfo->dwYSize;
  1671. b->StartupInfo->dwXCountChars= lpStartupInfo->dwXCountChars;
  1672. b->StartupInfo->dwYCountChars= lpStartupInfo->dwYCountChars;
  1673. b->StartupInfo->dwFillAttribute=lpStartupInfo->dwFillAttribute;
  1674. b->StartupInfo->dwFlags = lpStartupInfo->dwFlags;
  1675. b->StartupInfo->wShowWindow = lpStartupInfo->wShowWindow;
  1676. b->StartupInfo->cb = sizeof(STARTUPINFOA);
  1677. }
  1678. else {
  1679. b->StartupInfo = NULL;
  1680. }
  1681. // Allocate pointer for Desktop info if needed
  1682. if (AnsiStringDesktop.Buffer) {
  1683. CsrAllocateMessagePointer( CaptureBuffer,
  1684. ROUND_UP((AnsiStringDesktop.Length + 1),4),
  1685. (PVOID *)&b->Desktop
  1686. );
  1687. // Copy desktop string
  1688. RtlMoveMemory (b->Desktop,
  1689. AnsiStringDesktop.Buffer,
  1690. AnsiStringDesktop.Length+1);
  1691. b->DesktopLen =AnsiStringDesktop.Length+1;
  1692. }
  1693. else {
  1694. b->Desktop = NULL;
  1695. b->DesktopLen =0;
  1696. }
  1697. // Allocate pointer for Title info if needed
  1698. if (OemStringTitle.Buffer) {
  1699. CsrAllocateMessagePointer( CaptureBuffer,
  1700. ROUND_UP((OemStringTitle.Length + 1),4),
  1701. (PVOID *)&b->Title
  1702. );
  1703. // Copy title string
  1704. RtlMoveMemory (b->Title,
  1705. OemStringTitle.Buffer,
  1706. OemStringTitle.Length+1);
  1707. b->TitleLen = OemStringTitle.Length+1;
  1708. }
  1709. else {
  1710. b->Title = NULL;
  1711. b->TitleLen = 0;
  1712. }
  1713. // Allocate pointer for Reserved field if needed
  1714. if (AnsiStringReserved.Buffer) {
  1715. CsrAllocateMessagePointer( CaptureBuffer,
  1716. ROUND_UP((AnsiStringReserved.Length + 1),4),
  1717. (PVOID *)&b->Reserved
  1718. );
  1719. // Copy reserved string
  1720. RtlMoveMemory (b->Reserved,
  1721. AnsiStringReserved.Buffer,
  1722. AnsiStringReserved.Length+1);
  1723. b->ReservedLen = AnsiStringReserved.Length+1;
  1724. }
  1725. else {
  1726. b->Reserved = NULL;
  1727. b->ReservedLen = 0;
  1728. }
  1729. // VadimB: this code is of no consequence to our marvelous new
  1730. // architecture for tracking shared wows.
  1731. // Reason: the checkvdm command is executed within the context of
  1732. // a parent process thus at this point ConsoleHandle is of any
  1733. // interest only to DOS apps.
  1734. if (BinaryType == BINARY_TYPE_WIN16)
  1735. b->ConsoleHandle = (HANDLE)-1;
  1736. else if (bNewConsole)
  1737. b->ConsoleHandle = 0;
  1738. else
  1739. b->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  1740. b->VDMState = FALSE;
  1741. b->BinaryType = BinaryType;
  1742. b->CodePage = (ULONG) GetConsoleCP ();
  1743. b->dwCreationFlags = dwCreationFlags;
  1744. Status = CsrClientCallServer(
  1745. (PCSR_API_MSG)m,
  1746. CaptureBuffer,
  1747. CSR_MAKE_API_NUMBER( BASESRV_SERVERDLL_INDEX,
  1748. BasepCheckVDM
  1749. ),
  1750. sizeof( *b )
  1751. );
  1752. // if desktop access is denied, then we try again with the
  1753. // current default desktop
  1754. //
  1755. if ((STATUS_ACCESS_DENIED == Status) && (0 == b->DesktopLen)) {
  1756. CsrFreeCaptureBuffer(CaptureBuffer);
  1757. goto BCVTryExit;
  1758. }
  1759. CsrFreeCaptureBuffer(CaptureBuffer);
  1760. if (!NT_SUCCESS(Status) || !NT_SUCCESS((NTSTATUS)m->ReturnValue)) {
  1761. Status = (NTSTATUS)m->ReturnValue;
  1762. goto BCVTryExit;
  1763. }
  1764. // VadimB: This iTask could be :
  1765. // (*) If not wow task - then dos task id (items below are not
  1766. // relevant for this case)
  1767. // (*) Shared wow exists and ready - this is a wow task id
  1768. // that is unique across all the shared wows
  1769. *iTask = b->iTask;
  1770. Status = STATUS_SUCCESS;
  1771. BCVTryExit:;
  1772. BaseSetLastNTError(Status);
  1773. }
  1774. finally {
  1775. if(Buffer != NULL)
  1776. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)Buffer);
  1777. if(wsBuffer != NULL)
  1778. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)wsBuffer);
  1779. if(wsPifName != NULL)
  1780. RtlFreeHeap(RtlProcessHeap(), 0, (PVOID)wsPifName);
  1781. if(OemStringCmd.Buffer != NULL)
  1782. RtlFreeOemString(&OemStringCmd);
  1783. if(OemStringAppName.Buffer != NULL)
  1784. RtlFreeOemString(&OemStringAppName);
  1785. if(AnsiStringPif.Buffer != NULL)
  1786. RtlFreeAnsiString(&AnsiStringPif);
  1787. if(AnsiStringCurrentDir.Buffer != NULL)
  1788. RtlFreeAnsiString(&AnsiStringCurrentDir);
  1789. if(AnsiStringDesktop.Buffer != NULL)
  1790. RtlFreeAnsiString(&AnsiStringDesktop);
  1791. if(OemStringTitle.Buffer != NULL)
  1792. RtlFreeAnsiString(&OemStringTitle);
  1793. if(AnsiStringReserved.Buffer != NULL)
  1794. RtlFreeAnsiString(&AnsiStringReserved);
  1795. if (wsAppName != NULL)
  1796. RtlFreeHeap(RtlProcessHeap(), 0, wsAppName);
  1797. if (lpAllocatedReserved != NULL)
  1798. RtlFreeHeap(RtlProcessHeap(), 0, lpAllocatedReserved);
  1799. }
  1800. return Status;
  1801. }
  1802. /*
  1803. jarbats
  1804. Some apps send startupinfo with bad desktop name
  1805. as a result, basecheckvdm will fail with because
  1806. access to the desktop can't be obtained
  1807. in that case we attempt again with the parents desktop
  1808. */
  1809. BOOL
  1810. BaseCheckVDM(
  1811. IN ULONG BinaryType,
  1812. IN PCWCH lpApplicationName,
  1813. IN PCWCH lpCommandLine,
  1814. IN PCWCH lpCurrentDirectory,
  1815. IN ANSI_STRING *pAnsiStringEnv,
  1816. IN PBASE_API_MSG m,
  1817. IN OUT PULONG iTask,
  1818. IN DWORD dwCreationFlags,
  1819. LPSTARTUPINFOW lpStartupInfo
  1820. ) {
  1821. NTSTATUS Status;
  1822. LPWSTR lpDesktopOld;
  1823. Status = BaseCheckVDMp(
  1824. BinaryType,
  1825. lpApplicationName,
  1826. lpCommandLine,
  1827. lpCurrentDirectory,
  1828. pAnsiStringEnv,
  1829. m,
  1830. iTask,
  1831. dwCreationFlags,
  1832. lpStartupInfo
  1833. );
  1834. if ( Status == STATUS_ACCESS_DENIED ) {
  1835. lpDesktopOld = lpStartupInfo->lpDesktop;
  1836. lpStartupInfo->lpDesktop =
  1837. (LPWSTR)((PRTL_USER_PROCESS_PARAMETERS)NtCurrentPeb()->
  1838. ProcessParameters)->DesktopInfo.Buffer;
  1839. Status = BaseCheckVDMp(
  1840. BinaryType,
  1841. lpApplicationName,
  1842. lpCommandLine,
  1843. lpCurrentDirectory,
  1844. pAnsiStringEnv,
  1845. m,
  1846. iTask,
  1847. dwCreationFlags,
  1848. lpStartupInfo
  1849. );
  1850. if (!NT_SUCCESS(Status)) {
  1851. lpStartupInfo->lpDesktop = lpDesktopOld;
  1852. }
  1853. }
  1854. return NT_SUCCESS(Status);
  1855. }
  1856. BOOL
  1857. BaseUpdateVDMEntry(
  1858. IN ULONG UpdateIndex,
  1859. IN OUT HANDLE *WaitHandle,
  1860. IN ULONG IndexInfo,
  1861. IN ULONG BinaryType
  1862. )
  1863. {
  1864. NTSTATUS Status;
  1865. BASE_API_MSG m;
  1866. PBASE_UPDATE_VDM_ENTRY_MSG c = &m.u.UpdateVDMEntry;
  1867. switch (UpdateIndex) {
  1868. case UPDATE_VDM_UNDO_CREATION:
  1869. c->iTask = HandleToUlong(*WaitHandle);
  1870. c->VDMCreationState = (USHORT)IndexInfo;
  1871. break;
  1872. case UPDATE_VDM_PROCESS_HANDLE:
  1873. c->VDMProcessHandle = *WaitHandle; // Actually this is VDM handle
  1874. c->iTask = IndexInfo;
  1875. break;
  1876. }
  1877. // VadimB: this ConsoleHandle is of no consequence to the
  1878. // shared wow tracking mechanism
  1879. if(BinaryType == BINARY_TYPE_WIN16)
  1880. c->ConsoleHandle = (HANDLE)-1;
  1881. else if (c->iTask)
  1882. c->ConsoleHandle = 0;
  1883. else
  1884. c->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  1885. c->EntryIndex = (WORD)UpdateIndex;
  1886. c->BinaryType = BinaryType;
  1887. Status = CsrClientCallServer(
  1888. (PCSR_API_MSG)&m,
  1889. NULL,
  1890. CSR_MAKE_API_NUMBER( BASESRV_SERVERDLL_INDEX,
  1891. BasepUpdateVDMEntry
  1892. ),
  1893. sizeof( *c )
  1894. );
  1895. if (!NT_SUCCESS(Status) || !NT_SUCCESS((NTSTATUS)m.ReturnValue)) {
  1896. BaseSetLastNTError((NTSTATUS)m.ReturnValue);
  1897. return FALSE;
  1898. }
  1899. switch (UpdateIndex) {
  1900. case UPDATE_VDM_UNDO_CREATION:
  1901. break;
  1902. case UPDATE_VDM_PROCESS_HANDLE:
  1903. *WaitHandle = c->WaitObjectForParent;
  1904. break;
  1905. }
  1906. return TRUE;
  1907. }
  1908. ULONG
  1909. BaseIsDosApplication(
  1910. IN PUNICODE_STRING PathName,
  1911. IN NTSTATUS Status
  1912. )
  1913. /*++
  1914. Routine Description:
  1915. Determines if app is a ".com" or a ".pif" type of app
  1916. by looking at the extension, and the Status from NtCreateSection
  1917. for PAGE_EXECUTE.
  1918. Arguments:
  1919. PathName -- Supplies a pointer to the path string
  1920. Status -- Status code from CreateSection call
  1921. bNewConsole -- Pif can exec only from a new console
  1922. Return Value:
  1923. file is a com\pif dos application
  1924. SCS_DOS_BINARY - ".com", may also be a .exe extension
  1925. SCS_PIF_BINARY - ".pif"
  1926. 0 -- file is not a dos application, may be a .bat or .cmd file
  1927. --*/
  1928. {
  1929. UNICODE_STRING String;
  1930. // check for .com extension
  1931. String.Length = BaseDotComSuffixName.Length;
  1932. String.Buffer = &(PathName->Buffer[(PathName->Length - String.Length) /
  1933. sizeof(WCHAR)]);
  1934. if (RtlEqualUnicodeString(&String, &BaseDotComSuffixName, TRUE))
  1935. return BINARY_TYPE_DOS_COM;
  1936. // check for .pif extension
  1937. String.Length = BaseDotPifSuffixName.Length;
  1938. String.Buffer = &(PathName->Buffer[(PathName->Length - String.Length) /
  1939. sizeof(WCHAR)]);
  1940. if (RtlEqualUnicodeString(&String, &BaseDotPifSuffixName, TRUE))
  1941. return BINARY_TYPE_DOS_PIF;
  1942. // check for .exe extension
  1943. String.Length = BaseDotExeSuffixName.Length;
  1944. String.Buffer = &(PathName->Buffer[(PathName->Length - String.Length) /
  1945. sizeof(WCHAR)]);
  1946. if (RtlEqualUnicodeString(&String, &BaseDotExeSuffixName, TRUE))
  1947. return BINARY_TYPE_DOS_EXE;
  1948. return 0;
  1949. }
  1950. BOOL
  1951. BaseGetVdmConfigInfo(
  1952. IN LPCWSTR CommandLine,
  1953. IN ULONG DosSeqId,
  1954. IN ULONG BinaryType,
  1955. IN PUNICODE_STRING CmdLineString,
  1956. IN OUT PULONG VdmSize
  1957. )
  1958. /*++
  1959. Routine Description:
  1960. This routine locates the VDM configuration information for Wow vdms in
  1961. the system configuration file. It also reconstructs the commandline so
  1962. that we can start the VDM. The new command line is composed from the
  1963. information in the configuration file + the old command line.
  1964. Arguments:
  1965. CommandLine -- pointer to a string pointer that is used to pass the
  1966. command line string
  1967. DosSeqId - new console session id. This parameter is also valid for
  1968. shared wow as it is passed to ntvdm as -i parameter. Another
  1969. parameter to identify shared wow is passed to ntvdm as
  1970. '-ws' where 'w' stands for wow app, 's' stands for separate
  1971. In response to this 's' parameter ntvdm launches a
  1972. separate wow (one-time shot). By default, ntvdm starts a shared
  1973. wow.
  1974. VdmSize --entry:
  1975. If set to 1 construct command line for MEOW
  1976. return: the size in bytes of the VDM to be created
  1977. BinaryType - dos, sharedwow, sepwow
  1978. Return Value:
  1979. TRUE -- VDM configuration information was available
  1980. FALSE -- VDM configuration information was not available
  1981. Notes:
  1982. --*/
  1983. {
  1984. NTSTATUS Status;
  1985. BOOL bRet;
  1986. DWORD dw;
  1987. ANSI_STRING AnsiString;
  1988. LPSTR NewCmdLine=NULL;
  1989. PCH pSrc, pDst, pch;
  1990. ULONG Len;
  1991. char CmdLine[MAX_VDM_CFG_LINE];
  1992. BOOL bMeow =(1 == *VdmSize);
  1993. CmdLineString->Buffer = NULL;
  1994. Len = MAX_VDM_CFG_LINE;
  1995. if (BinaryType == BINARY_TYPE_DOS) {
  1996. bRet = BaseGetVDMKeyword(CMDLINE, CmdLine, &Len, DOSSIZE, VdmSize);
  1997. }
  1998. else {
  1999. bRet = BaseGetVDMKeyword(WOWCMDLINE, CmdLine, &Len, WOWSIZE, VdmSize);
  2000. }
  2001. if (!bRet) {
  2002. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2003. return FALSE;
  2004. }
  2005. //
  2006. // Allocate memory to replace the CommandLine
  2007. // extra space is needed for long->short name conversion,
  2008. // separate wow, and extension.
  2009. //
  2010. NewCmdLine = RtlAllocateHeap(RtlProcessHeap(),
  2011. MAKE_TAG( VDM_TAG ),
  2012. MAX_PATH + MAX_VDM_CFG_LINE
  2013. );
  2014. if (!NewCmdLine) {
  2015. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2016. return FALSE;
  2017. }
  2018. //
  2019. // Copy over the cmdline checking for special args
  2020. // and locating the beg of wowkernel
  2021. //
  2022. pSrc = CmdLine;
  2023. pDst = NewCmdLine;
  2024. //
  2025. // first token must be "\\%SystemRoot%\\system32\\ntvdm", search
  2026. // for the tail of the pathname to traverse possible long file name
  2027. // safely.
  2028. //
  2029. pch = strstr(pSrc, "\\system32\\ntvdm");
  2030. if (!pch) {
  2031. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  2032. return FALSE;
  2033. }
  2034. // mov pch to trailing space in "ntvdm "
  2035. while (*pch && *pch != ' ') {
  2036. pch++;
  2037. }
  2038. //
  2039. // copy first token (ntvdm path name), surrounded by quotes for
  2040. // possible long file name
  2041. //
  2042. *pDst++ = '\"';
  2043. while (pSrc < pch) {
  2044. *pDst++ = *pSrc++;
  2045. }
  2046. *pDst++ = '\"';
  2047. //
  2048. // Add -f arg, so ntvdm knows it wasn't invoked directly
  2049. //
  2050. *pDst++ = ' ';
  2051. *pDst++ = '-';
  2052. *pDst++ = 'f';
  2053. //
  2054. // Add DosSeqId for new console
  2055. //
  2056. if (DosSeqId) {
  2057. sprintf(pDst, " -i%lx", DosSeqId);
  2058. pDst += strlen(pDst);
  2059. }
  2060. //
  2061. // Copy over everything up to the " -a " (exclusive)
  2062. // CAVEAT: we assume -a is last
  2063. //
  2064. pch = strstr(pSrc, " -a ");
  2065. if (pch) {
  2066. while (pSrc < pch) {
  2067. *pDst++ = *pSrc++;
  2068. }
  2069. }
  2070. else {
  2071. while (*pSrc) {
  2072. *pDst++ = *pSrc++;
  2073. }
  2074. }
  2075. *pDst = '\0';
  2076. //
  2077. // for wow -a is mandatory to specify win16 krnl, and is expected
  2078. // to be the last cmdline parameter
  2079. //
  2080. if (BinaryType != BINARY_TYPE_DOS) { // shared wow, sep wow
  2081. PCH pWowKernel;
  2082. if (!*pSrc) {
  2083. BaseSetLastNTError(STATUS_INVALID_PARAMETER);
  2084. return FALSE;
  2085. }
  2086. //
  2087. // Add -w to tell ntvdm its wow (mandatory)
  2088. //
  2089. *pDst++ = ' ';
  2090. *pDst++ = '-';
  2091. *pDst++ = 'w';
  2092. //
  2093. // identify that this wow is a separate wow by -ws
  2094. //
  2095. if (BINARY_TYPE_SEPWOW == BinaryType) {
  2096. *pDst++ = 's';
  2097. }
  2098. //
  2099. // identify that this wow is a MEOW process by -wsm
  2100. //
  2101. if (bMeow) {
  2102. *pDst++ = 'm';
  2103. }
  2104. //
  2105. // copy over the " -a WowKernelPathname" argument
  2106. // and locate beg of WowKernelPathname in destination
  2107. //
  2108. pWowKernel = pDst;
  2109. while (*pSrc) {
  2110. *pDst++ = *pSrc++;
  2111. }
  2112. pWowKernel += 4; // find beg of WowKernelPathaname
  2113. while (*pWowKernel == ' ') {
  2114. pWowKernel++;
  2115. }
  2116. //
  2117. // If meow process, change krnl386 to mekr386
  2118. //
  2119. if (bMeow) {
  2120. pch=strrchr(pWowKernel,'\\');
  2121. strcpy(pch+1,"mekr386.exe");
  2122. }
  2123. else {
  2124. //
  2125. // Append file extension to destination
  2126. //
  2127. strcpy(pDst, ".exe");
  2128. }
  2129. //
  2130. // convert wowkernel to short name
  2131. //
  2132. Len = MAX_PATH + MAX_VDM_CFG_LINE - (ULONG)((ULONG_PTR)pWowKernel - (ULONG_PTR)NewCmdLine) -1;
  2133. dw = GetShortPathNameA(pWowKernel, pWowKernel, Len);
  2134. if (dw > Len) {
  2135. RtlFreeHeap(RtlProcessHeap(), 0, NewCmdLine);
  2136. return FALSE;
  2137. }
  2138. }
  2139. RtlInitAnsiString(&AnsiString, NewCmdLine);
  2140. Status = RtlAnsiStringToUnicodeString(CmdLineString, &AnsiString, TRUE);
  2141. if (!NT_SUCCESS(Status)) {
  2142. BaseSetLastNTError(Status);
  2143. RtlFreeHeap(RtlProcessHeap(), 0, NewCmdLine);
  2144. CmdLineString->Buffer = NULL;
  2145. return FALSE;
  2146. }
  2147. RtlFreeHeap(RtlProcessHeap(), 0, NewCmdLine);
  2148. return TRUE;
  2149. }
  2150. BOOL
  2151. BaseCheckForVDM(
  2152. IN HANDLE hProcess,
  2153. OUT LPDWORD lpExitCode
  2154. )
  2155. {
  2156. NTSTATUS Status;
  2157. EVENT_BASIC_INFORMATION ebi;
  2158. BASE_API_MSG m;
  2159. PBASE_GET_VDM_EXIT_CODE_MSG a = &m.u.GetVDMExitCode;
  2160. Status = NtQueryEvent (
  2161. hProcess,
  2162. EventBasicInformation,
  2163. &ebi,
  2164. sizeof(ebi),
  2165. NULL);
  2166. if(!NT_SUCCESS(Status))
  2167. return FALSE;
  2168. a->ConsoleHandle = NtCurrentPeb()->ProcessParameters->ConsoleHandle;
  2169. a->hParent = hProcess;
  2170. Status = CsrClientCallServer(
  2171. (PCSR_API_MSG)&m,
  2172. NULL,
  2173. CSR_MAKE_API_NUMBER( BASESRV_SERVERDLL_INDEX,
  2174. BasepGetVDMExitCode),
  2175. sizeof( *a )
  2176. );
  2177. if (!NT_SUCCESS(Status)) {
  2178. return FALSE;
  2179. }
  2180. *lpExitCode = (DWORD)a->ExitCode;
  2181. return TRUE;
  2182. }
  2183. DWORD
  2184. APIENTRY
  2185. GetShortPathNameA(
  2186. IN LPCSTR lpszLongPath,
  2187. IN LPSTR lpShortPath,
  2188. IN DWORD cchBuffer
  2189. )
  2190. {
  2191. UNICODE_STRING UString, UStringRet;
  2192. ANSI_STRING AString;
  2193. NTSTATUS Status;
  2194. WCHAR TempPathW[MAX_PATH];
  2195. LPWSTR lpShortPathW = NULL;
  2196. DWORD ReturnValue;
  2197. DWORD ReturnValueW;
  2198. if (lpszLongPath == NULL) {
  2199. SetLastError(ERROR_INVALID_PARAMETER);
  2200. return 0;
  2201. }
  2202. // We have to initialize it before the "try" statement
  2203. AString.Buffer = NULL;
  2204. UString.Buffer = NULL;
  2205. ReturnValue = 0;
  2206. ReturnValueW = 0;
  2207. try {
  2208. if (!Basep8BitStringToDynamicUnicodeString(&UString, lpszLongPath )) {
  2209. goto gspTryExit;
  2210. }
  2211. // we have to get the real converted path in order to find out
  2212. // the required length. An UNICODE char does not necessarily convert
  2213. // to one ANSI char(A DBCS is basically TWO ANSI char!!!!!).
  2214. // First, we use the buffer allocated from the stack. If the buffer
  2215. // is too small, we then allocate it from heap.
  2216. // A check of (lpShortPathW && TempPathW != lpShortPathW) will reveal
  2217. // if we have allocated a buffer from heap and need to release it.
  2218. lpShortPathW = TempPathW;
  2219. ReturnValueW = GetShortPathNameW(UString.Buffer, lpShortPathW, sizeof(TempPathW) / sizeof(WCHAR));
  2220. if (ReturnValueW >= sizeof(TempPathW) / sizeof(WCHAR))
  2221. {
  2222. // the stack-based buffer is too small. Allocate a new buffer
  2223. // from heap.
  2224. lpShortPathW = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( VDM_TAG ),
  2225. ReturnValueW * sizeof(WCHAR)
  2226. );
  2227. if (lpShortPathW) {
  2228. ReturnValueW = GetShortPathNameW(UString.Buffer, lpShortPathW, ReturnValueW);
  2229. }
  2230. else {
  2231. ReturnValueW = 0;
  2232. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2233. }
  2234. }
  2235. if (ReturnValueW)
  2236. {
  2237. // we are here because we have something interesting left to do.
  2238. // Convert the UNICODE path name to ANSI(or OEM).
  2239. UString.MaximumLength = (USHORT)((ReturnValueW + 1) * sizeof(WCHAR));
  2240. UStringRet.Buffer = lpShortPathW;
  2241. UStringRet.Length = (USHORT)(ReturnValueW * sizeof(WCHAR));
  2242. Status = BasepUnicodeStringTo8BitString(&AString,
  2243. &UStringRet,
  2244. TRUE
  2245. );
  2246. if (!NT_SUCCESS(Status))
  2247. {
  2248. BaseSetLastNTError(Status);
  2249. ReturnValue=0;
  2250. goto gspTryExit;
  2251. }
  2252. // now AString.Length contains the size of the converted path
  2253. // name. If the caller provides enough buffer, copy the
  2254. // path name.
  2255. ReturnValue = AString.Length;
  2256. if (ARGUMENT_PRESENT(lpShortPath) && cchBuffer > ReturnValue)
  2257. {
  2258. RtlMoveMemory(lpShortPath, AString.Buffer, ReturnValue);
  2259. // terminate the string with NULL char
  2260. lpShortPath[ReturnValue] = '\0';
  2261. }
  2262. else
  2263. {
  2264. // either the caller does not provide a buffer or
  2265. // the provided buffer is too small return the required size,
  2266. // including the terminated null char
  2267. ReturnValue++;
  2268. }
  2269. }
  2270. gspTryExit:;
  2271. }
  2272. finally {
  2273. if (UString.Buffer)
  2274. RtlFreeUnicodeString(&UString);
  2275. if (AString.Buffer)
  2276. RtlFreeAnsiString(&AString);
  2277. if (lpShortPathW && lpShortPathW != TempPathW)
  2278. RtlFreeHeap(RtlProcessHeap(), 0, lpShortPathW);
  2279. }
  2280. return ReturnValue;
  2281. }
  2282. /****
  2283. GetShortPathName
  2284. Description:
  2285. This function converts the given path name to its short form if
  2286. needed. The conversion may not be necessary and in that case,
  2287. this function simply copies down the given name to the return buffer.
  2288. The caller can have the return buffer set equal to the given path name
  2289. address.
  2290. Parameters:
  2291. lpszLongPath - Points to a NULL terminated string.
  2292. lpszShortPath - Buffer address to return the short name.
  2293. cchBuffer - Buffer size in char of lpszShortPath.
  2294. Return Value
  2295. If the GetShortPathName function succeeds, the return value is the length,
  2296. in characters, of the string copied to lpszShortPath,
  2297. not including the terminating
  2298. null character.
  2299. If the lpszShortPath is too small, the return value is
  2300. the size of the buffer, in
  2301. characters, required to hold the path.
  2302. If the function fails, the return value is zero. To get
  2303. extended error information, use
  2304. the GetLastError function.
  2305. Remarks:
  2306. The "short name" can be longer than its "long name". lpszLongPath doesn't
  2307. have to be a fully qualified path name or a long path name.
  2308. ****/
  2309. DWORD
  2310. APIENTRY
  2311. GetShortPathNameW(
  2312. IN LPCWSTR lpszLongPath,
  2313. IN LPWSTR lpszShortPath,
  2314. IN DWORD cchBuffer
  2315. )
  2316. {
  2317. LPCWSTR pcs;
  2318. LPWSTR pSrcCopy, pSrc, pFirst, pLast, pDst;
  2319. WCHAR wch;
  2320. HANDLE FindHandle;
  2321. WIN32_FIND_DATAW FindData;
  2322. LPWSTR Buffer;
  2323. DWORD ReturnLen=0, Length;
  2324. UINT PrevErrorMode;
  2325. if (!ARGUMENT_PRESENT(lpszLongPath)) {
  2326. SetLastError(ERROR_INVALID_PARAMETER);
  2327. return 0;
  2328. }
  2329. //
  2330. // override the error mode since we will be touching the media.
  2331. // This is to prevent file system's pop-up when the given path does not
  2332. // exist or the media is not available.
  2333. // we are doing this because we can not depend on the caller's current
  2334. // error mode. NOTE: the old error mode must be restored.
  2335. PrevErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
  2336. try {
  2337. Buffer = NULL;
  2338. pSrcCopy = NULL;
  2339. // first, make sure the given path exist
  2340. if (0xFFFFFFFF == GetFileAttributesW(lpszLongPath))
  2341. {
  2342. //
  2343. // (bjm - 3/17/99)
  2344. // This behavior (failing if the file does not exist) is new (to NT) with NT 5.
  2345. // (It's the Win9x behavior.)
  2346. // Give an exception to Norton AntiVirus Uninstall.
  2347. // If we fail this call, there will be a registry value left behind in VDD that'll cause
  2348. // undeserved ugly messages for a user. Norton AV Uninstall counts on NT 4 behavior
  2349. // which did not care if the file existed to do this conversion. This was changed in
  2350. // NT 5.0 to match Win9x behavior.
  2351. //
  2352. if ( !NtCurrentPeb() || !APPCOMPATFLAG(KACF_OLDGETSHORTPATHNAME) )
  2353. {
  2354. // last error has been set by GetFileAttributes
  2355. ReturnLen = 0;
  2356. goto gsnTryExit;
  2357. }
  2358. }
  2359. pcs = SkipPathTypeIndicator_U(lpszLongPath);
  2360. if (!pcs || *pcs == UNICODE_NULL || !FindLFNorSFN_U((LPWSTR)pcs, &pFirst, &pLast, TRUE))
  2361. {
  2362. // nothing to convert, copy down the source string
  2363. // to the buffer if necessary
  2364. ReturnLen = wcslen(lpszLongPath);
  2365. if (cchBuffer > ReturnLen && ARGUMENT_PRESENT(lpszShortPath))
  2366. {
  2367. if (lpszShortPath != lpszLongPath)
  2368. RtlMoveMemory(lpszShortPath, lpszLongPath,
  2369. (ReturnLen + 1) * sizeof(WCHAR)
  2370. );
  2371. }
  2372. else {
  2373. // the caller does not provide enough buffer, return
  2374. // necessary string length plus the terminated null char
  2375. ReturnLen++;
  2376. }
  2377. goto gsnTryExit;
  2378. }
  2379. // conversions are necessary, make a local copy of the string
  2380. // because we have to party on it.
  2381. ASSERT(!pSrcCopy);
  2382. // get the source string length
  2383. Length = wcslen(lpszLongPath) + 1;
  2384. pSrcCopy = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( VDM_TAG ),
  2385. Length * sizeof(WCHAR)
  2386. );
  2387. if (!pSrcCopy) {
  2388. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2389. goto gsnTryExit;
  2390. }
  2391. wcsncpy(pSrcCopy, lpszLongPath, Length);
  2392. // pFirst points to the first char of the very first LFN in the path
  2393. // pLast points to the char right after the last char of the very
  2394. // first LFN in the path. *pLast could be UNICODE_NULL
  2395. pFirst = pSrcCopy + (pFirst - lpszLongPath);
  2396. pLast = pSrcCopy + (pLast - lpszLongPath);
  2397. //
  2398. // We allow lpszShortPath be overlapped with lpszLongPath so
  2399. // allocate a local buffer.
  2400. pDst = lpszShortPath;
  2401. if (cchBuffer > 0 && ARGUMENT_PRESENT(lpszShortPath) &&
  2402. (lpszShortPath >= lpszLongPath &&lpszShortPath < lpszLongPath + Length ||
  2403. lpszShortPath < lpszLongPath && lpszShortPath + cchBuffer >= lpszLongPath))
  2404. {
  2405. ASSERT(!Buffer);
  2406. Buffer = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( VDM_TAG ),
  2407. cchBuffer * sizeof(WCHAR));
  2408. if (!Buffer){
  2409. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2410. goto gsnTryExit;
  2411. }
  2412. pDst = Buffer;
  2413. }
  2414. pSrc = pSrcCopy;
  2415. ReturnLen = 0;
  2416. do {
  2417. // there are three pointers involve in the conversion loop:
  2418. // pSrc, pFirst and pLast. Their relationship
  2419. // is:
  2420. //
  2421. // "c:\long~1.1\\foo.bar\\long~2.2\\bar"
  2422. // ^ ^ ^ ^
  2423. // | | | |
  2424. // | pSrc pFirst pLast
  2425. // pSrcCopy
  2426. //
  2427. // pSrcCopy always points to the very first char of the entire
  2428. // path.
  2429. //
  2430. // chars between pSrc(included) and pFirst(not included)
  2431. // do not need conversion so we simply copy them.
  2432. // chars between pFirst(included) and pLast(not included)
  2433. // need conversion.
  2434. //
  2435. Length = (ULONG)(pFirst - pSrc);
  2436. if (Length) {
  2437. ReturnLen += Length;
  2438. if (cchBuffer > ReturnLen && ARGUMENT_PRESENT(lpszShortPath)) {
  2439. RtlMoveMemory(pDst, pSrc, Length * sizeof(WCHAR));
  2440. pDst += Length;
  2441. }
  2442. }
  2443. wch = *pLast;
  2444. *pLast = UNICODE_NULL;
  2445. FindHandle = FindFirstFileW(pSrcCopy, &FindData);
  2446. *pLast = wch;
  2447. if (INVALID_HANDLE_VALUE != FindHandle) {
  2448. FindClose(FindHandle);
  2449. // if no short name could be found, copy the original name.
  2450. // the origian name starts with pFirst(included) and ends
  2451. // with pLast(excluded).
  2452. if (!(Length = wcslen(FindData.cAlternateFileName)))
  2453. Length = (ULONG)(pLast - pFirst);
  2454. else
  2455. pFirst = FindData.cAlternateFileName;
  2456. ReturnLen += Length;
  2457. if (cchBuffer > ReturnLen && ARGUMENT_PRESENT(lpszShortPath))
  2458. {
  2459. RtlMoveMemory(pDst, pFirst, Length * sizeof(WCHAR));
  2460. pDst += Length;
  2461. }
  2462. }
  2463. else {
  2464. // part of the path does not exist, fail the function
  2465. //
  2466. ReturnLen = 0;
  2467. break;
  2468. }
  2469. // move to next path name
  2470. pSrc = pLast;
  2471. if (*pLast == UNICODE_NULL)
  2472. break;
  2473. }while (FindLFNorSFN_U(pSrc, &pFirst, &pLast, TRUE));
  2474. // if ReturnLen == 0, we fail somewhere inside while loop.
  2475. if (ReturnLen) {
  2476. // (*pSrc == UNICODE_NULL) means the last pathname is a LFN which
  2477. // has been dealt with. otherwise, the substring pointed by
  2478. // pSrc is a legal short path name and we have to copy it
  2479. //Length could be zero
  2480. Length = wcslen(pSrc);
  2481. ReturnLen += Length;
  2482. if (cchBuffer > ReturnLen && ARGUMENT_PRESENT(lpszShortPath))
  2483. {
  2484. //include the terminated null char
  2485. RtlMoveMemory(pDst, pSrc, (Length + 1)* sizeof(WCHAR));
  2486. if (Buffer)
  2487. RtlMoveMemory(lpszShortPath, Buffer, (ReturnLen + 1) * sizeof(WCHAR));
  2488. }
  2489. else
  2490. // not enough buffer, the return value counts the terminated NULL
  2491. ReturnLen++;
  2492. }
  2493. gsnTryExit:;
  2494. }
  2495. finally {
  2496. if (Buffer)
  2497. RtlFreeHeap(RtlProcessHeap(), 0, Buffer);
  2498. if (pSrcCopy)
  2499. RtlFreeHeap(RtlProcessHeap(), 0, pSrcCopy);
  2500. // restore the error mode
  2501. SetErrorMode(PrevErrorMode);
  2502. }
  2503. return ReturnLen;
  2504. }
  2505. /**
  2506. function to create VDM environment for the new executable.
  2507. Input: lpEnvironmen = optinal environment strings prototype in UNICODE.
  2508. If it is NULL, this function use the environment
  2509. block attached to the process
  2510. pAStringEnv = pointer to a ANSI_STRING to receive the
  2511. new environment strings.
  2512. pUStringEnv = pointer to a UNICODE_STRING to receive the
  2513. new environment strings.
  2514. Output: FALSE if the creattion failed.
  2515. TRUE creation successful, pAStringEnv has been setup.
  2516. This function was provided so that BaseCheckVdm can have correct
  2517. environment(includes the newly create NTVDM process). This was done
  2518. because before command.com gets the next command, users can have
  2519. tons of things specified in config.sys and autoexec.bat which
  2520. may rely on current directory of each drive.
  2521. **/
  2522. BOOL BaseCreateVDMEnvironment(
  2523. PWCHAR lpEnvironment,
  2524. ANSI_STRING * pAStringEnv,
  2525. UNICODE_STRING *pUStringEnv
  2526. )
  2527. {
  2528. WCHAR *pEnv, *pDst, *EnvStrings=NULL,* pTmp, *pNewEnv=NULL;
  2529. DWORD cchEnv, dw, Length, dwRemain;
  2530. NTSTATUS Status;
  2531. UINT NameType;
  2532. BOOL bRet = FALSE;
  2533. SIZE_T EnvSize;
  2534. if (!ARGUMENT_PRESENT(pAStringEnv) || !ARGUMENT_PRESENT(pUStringEnv)){
  2535. SetLastError(ERROR_INVALID_PARAMETER);
  2536. return FALSE;
  2537. }
  2538. try {
  2539. // the environment strings are shared by every thread of the same
  2540. // process. Since we have no idea of what the caller process
  2541. // is, we have to grab the entire environment to our local buffer in one
  2542. // shot then we can walk through the strings.
  2543. // Note that if another thread makes call to RtlSetEnvironmentVariable
  2544. // then we are out of sync. It is a problem of process structure and
  2545. // I don't want to think about it now.
  2546. // The funny thing is that we have to assume the environment
  2547. // is a block of strings(otherwise, how can we do it?)t, nothing more and
  2548. // nothing less. If someday and somebody dares to change it, he will be
  2549. // the one to blame. If the caller(CreateProcess)
  2550. // provides the environment, we assume it is safe to walk through it.
  2551. //
  2552. if (lpEnvironment == NULL) {
  2553. // create a new environment and inherit the current process env
  2554. Status = RtlCreateEnvironment(TRUE, (PVOID *)&EnvStrings);
  2555. if (!NT_SUCCESS(Status))
  2556. goto bveTryExit;
  2557. }
  2558. else
  2559. EnvStrings = lpEnvironment;
  2560. if (EnvStrings == NULL) {
  2561. SetLastError(ERROR_BAD_ENVIRONMENT);
  2562. goto bveTryExit;
  2563. }
  2564. // figure out how long the environment is
  2565. // why can Rtl just provides such a function for us?
  2566. //
  2567. cchEnv = 0;
  2568. pEnv = EnvStrings;
  2569. // environment is double-null terminated
  2570. while (!(*pEnv++ == UNICODE_NULL && *pEnv == UNICODE_NULL))
  2571. cchEnv++;
  2572. // count the last two NULLs
  2573. cchEnv += 2;
  2574. // we don't want to change the original environment, so
  2575. // make a local buffer for it.
  2576. EnvSize = (cchEnv + MAX_PATH) * sizeof(WCHAR);
  2577. Status = NtAllocateVirtualMemory( NtCurrentProcess(),
  2578. &pNewEnv,
  2579. 0,
  2580. &EnvSize,
  2581. MEM_COMMIT,
  2582. PAGE_READWRITE
  2583. );
  2584. if (!NT_SUCCESS(Status) ) {
  2585. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2586. pNewEnv = NULL;
  2587. goto bveTryExit;
  2588. }
  2589. // give the last two for null
  2590. dwRemain = MAX_PATH - 2;
  2591. // now walk through the environment string
  2592. pEnv = EnvStrings;
  2593. // the new environmet will be
  2594. pDst = pNewEnv;
  2595. while (*pEnv != UNICODE_NULL) {
  2596. // current directory environment has the form as:
  2597. // "=d:=d:\pathname" where d: is the drive designator.
  2598. if (pEnv[0] == L'=')
  2599. {
  2600. if ((pEnv[1] >= L'A' && pEnv[1] <= L'Z' || pEnv[1] >= L'a' && pEnv[1] <= L'z') &&
  2601. pEnv[2] == L':' && pEnv[3] == L'=' && wcslen(pEnv) >= 7)
  2602. {
  2603. // hack hack!!!!
  2604. // if the path points to the root directory,
  2605. // bypass the conversion. Dos or Wow keeps current directory
  2606. // for every valid drive. If we do the conversion for
  2607. // every current directory, it could take several
  2608. // seconds on removable drives, especially, on
  2609. // floppy drives.
  2610. if (pEnv[7] == UNICODE_NULL &&
  2611. (pEnv[6] == L'\\' || pEnv[6] == L'/') &&
  2612. pEnv[5] == L':' &&
  2613. (pEnv[4] >= L'A' && pEnv[4] <= L'Z' ||
  2614. pEnv[4] >= L'a' && pEnv[4] <= L'z'))
  2615. {
  2616. NameType = ENV_NAME_TYPE_NO_PATH;
  2617. }
  2618. else
  2619. {
  2620. // copy "=N:=", where N is the drive letter
  2621. *pDst++ = *pEnv++;*pDst++ = *pEnv++;
  2622. *pDst++ = *pEnv++;*pDst++ = *pEnv++;
  2623. NameType = ENV_NAME_TYPE_SINGLE_PATH;
  2624. }
  2625. }
  2626. else {
  2627. // a weird environment was detected.
  2628. // treat it as no path
  2629. NameType = ENV_NAME_TYPE_NO_PATH;
  2630. }
  2631. }
  2632. else {
  2633. pTmp = pEnv;
  2634. // copy down the name and the '='
  2635. while (*pEnv != UNICODE_NULL && (*pDst++ = *pEnv++) != L'=')
  2636. ;
  2637. NameType = BaseGetEnvNameType_U(pTmp, (DWORD)(pEnv - pTmp) - 1);
  2638. }
  2639. if (NameType == ENV_NAME_TYPE_NO_PATH) {
  2640. while ((*pDst++ = *pEnv++) != UNICODE_NULL)
  2641. ;
  2642. }
  2643. else if (NameType == ENV_NAME_TYPE_SINGLE_PATH) {
  2644. Length = wcslen(pEnv) + 1;
  2645. dw = GetShortPathNameW(pEnv, pDst, Length + dwRemain);
  2646. // if the conversion failed, we simply pass down the original
  2647. // one no matter what the reason is. This is done because we
  2648. // are doing the environment strings.
  2649. if (dw == 0 || dw >= Length + dwRemain){
  2650. RtlMoveMemory(pDst, pEnv, Length * sizeof(WCHAR));
  2651. dw = Length - 1;
  2652. }
  2653. pDst += dw + 1;
  2654. pEnv += Length;
  2655. if (dw > Length)
  2656. dwRemain -= dw - Length;
  2657. }
  2658. else {
  2659. // multiple path name found.
  2660. // the character ';' is used for seperator
  2661. pTmp = pEnv;
  2662. while(*pEnv != UNICODE_NULL) {
  2663. if (*pEnv == L';') {
  2664. // length not include the ';'
  2665. Length = (DWORD)(pEnv - pTmp);
  2666. if (Length > 0) {
  2667. *pEnv = UNICODE_NULL;
  2668. dw = GetShortPathNameW(pTmp, pDst, Length + 1 + dwRemain);
  2669. // again, if the conversion failed, use the original one
  2670. if (dw == 0 || dw > Length + dwRemain) {
  2671. RtlMoveMemory(pDst, pTmp, Length * sizeof(WCHAR));
  2672. dw = Length;
  2673. }
  2674. pDst += dw;
  2675. *pDst++ = *pEnv++ = L';';
  2676. if (dw > Length)
  2677. dwRemain -= dw - Length;
  2678. }
  2679. // skip all consecutive ';'
  2680. while (*pEnv == L';')
  2681. *pDst++ = *pEnv++;
  2682. pTmp = pEnv;
  2683. }
  2684. else
  2685. pEnv++;
  2686. }
  2687. // convert the last one
  2688. if ((Length = (DWORD)(pEnv - pTmp)) != 0) {
  2689. dw = GetShortPathNameW(pTmp, pDst, Length+1 + dwRemain);
  2690. if (dw == 0 || dw > Length) {
  2691. RtlMoveMemory(pDst, pTmp, Length * sizeof(WCHAR));
  2692. dw = Length;
  2693. }
  2694. pDst += dw;
  2695. if (dw > Length)
  2696. dwRemain -= dw - Length;
  2697. }
  2698. *pDst++ = *pEnv++;
  2699. }
  2700. }
  2701. *pDst++ = UNICODE_NULL;
  2702. cchEnv = (ULONG)((ULONG_PTR)pDst - (ULONG_PTR)pNewEnv);
  2703. pUStringEnv->MaximumLength = pUStringEnv->Length = (USHORT)cchEnv;
  2704. pUStringEnv->Buffer = pNewEnv;
  2705. Status = RtlUnicodeStringToAnsiString(pAStringEnv,
  2706. pUStringEnv,
  2707. TRUE
  2708. );
  2709. if (!NT_SUCCESS(Status)) {
  2710. BaseSetLastNTError(Status);
  2711. } else {
  2712. pNewEnv = NULL;
  2713. bRet = TRUE;
  2714. }
  2715. bveTryExit:;
  2716. }
  2717. finally {
  2718. if (lpEnvironment == NULL && EnvStrings != NULL) {
  2719. RtlDestroyEnvironment(EnvStrings);
  2720. }
  2721. if (pNewEnv != NULL) {
  2722. pUStringEnv->Length = pUStringEnv->MaximumLength = 0;
  2723. pUStringEnv->Buffer = NULL;
  2724. pAStringEnv->Length = pAStringEnv->MaximumLength = 0;
  2725. pAStringEnv->Buffer = NULL;
  2726. Status = NtFreeVirtualMemory (NtCurrentProcess(),
  2727. &pNewEnv,
  2728. &EnvSize,
  2729. MEM_DECOMMIT);
  2730. ASSERT (NT_SUCCESS (Status));
  2731. }
  2732. }
  2733. return bRet;
  2734. }
  2735. /**
  2736. Destroy the environment block created by BaseCreateVDMEnvironment
  2737. Input: ANSI_STRING * pAnsiStringVDMEnv
  2738. Environment block in ANSI, should be freed via
  2739. RtlFreeAnsiString
  2740. UNICODE_STRING * pUnicodeStringEnv
  2741. Environment block in UNICODE. The Buffer should
  2742. be freed with RtlFreeHeap.
  2743. Output: should always be TRUE.
  2744. **/
  2745. BOOL
  2746. BaseDestroyVDMEnvironment(
  2747. ANSI_STRING *pAStringEnv,
  2748. UNICODE_STRING *pUStringEnv
  2749. )
  2750. {
  2751. if (pAStringEnv->Buffer)
  2752. RtlFreeAnsiString(pAStringEnv);
  2753. if (pUStringEnv->Buffer) {
  2754. NTSTATUS Status;
  2755. SIZE_T RegionSize;
  2756. //
  2757. // Free the specified environment variable block.
  2758. //
  2759. RegionSize = 0;
  2760. Status = NtFreeVirtualMemory( NtCurrentProcess(),
  2761. &pUStringEnv->Buffer,
  2762. &RegionSize,
  2763. MEM_RELEASE
  2764. );
  2765. }
  2766. return TRUE;
  2767. }
  2768. /**
  2769. This function returns the name type of the given environment variable name
  2770. The name type has three possibilities. Each one represents if the
  2771. given name can have pathnames as its value.
  2772. ENV_NAME_TYPE_NO_PATH: no pathname can be its value
  2773. ENV_NAME_TYPE_SINGLE_PATH: single pathname
  2774. ENV_NAME_MULTIPLE_PATH: multiple path
  2775. SIDE NOTE:
  2776. Currently, nt can not installed on a long path and it seems
  2777. that systemroot and windir are never be in long path.
  2778. **/
  2779. UINT
  2780. BaseGetEnvNameType_U(WCHAR * Name, DWORD NameLength)
  2781. {
  2782. // so far we only take care of five predefined names:
  2783. // PATH
  2784. // WINDIR and
  2785. // SYSTEMROOT.
  2786. // TEMP
  2787. // TMP
  2788. //
  2789. static ENV_INFO EnvInfoTable[STD_ENV_NAME_COUNT] = {
  2790. {ENV_NAME_TYPE_MULTIPLE_PATH, ENV_NAME_PATH_LEN, ENV_NAME_PATH},
  2791. {ENV_NAME_TYPE_SINGLE_PATH, ENV_NAME_WINDIR_LEN, ENV_NAME_WINDIR},
  2792. {ENV_NAME_TYPE_SINGLE_PATH, ENV_NAME_SYSTEMROOT_LEN, ENV_NAME_SYSTEMROOT},
  2793. {ENV_NAME_TYPE_MULTIPLE_PATH, ENV_NAME_TEMP_LEN, ENV_NAME_TEMP},
  2794. {ENV_NAME_TYPE_MULTIPLE_PATH, ENV_NAME_TMP_LEN, ENV_NAME_TMP}
  2795. };
  2796. UINT NameType;
  2797. int i;
  2798. NameType = ENV_NAME_TYPE_NO_PATH;
  2799. for (i = 0; i < STD_ENV_NAME_COUNT; i++) {
  2800. if (EnvInfoTable[i].NameLength == NameLength &&
  2801. !_wcsnicmp(EnvInfoTable[i].Name, Name, NameLength)) {
  2802. NameType = EnvInfoTable[i].NameType;
  2803. break;
  2804. }
  2805. }
  2806. return NameType;
  2807. }
  2808. DWORD
  2809. APIENTRY
  2810. GetLongPathNameA(
  2811. IN LPCSTR lpszShortPath,
  2812. IN LPSTR lpLongPath,
  2813. IN DWORD cchBuffer
  2814. )
  2815. {
  2816. UNICODE_STRING UString, UStringRet;
  2817. ANSI_STRING AString;
  2818. NTSTATUS Status;
  2819. LPWSTR lpLongPathW = NULL;
  2820. WCHAR TempPathW[MAX_PATH];
  2821. DWORD ReturnValue, ReturnValueW;
  2822. if (lpszShortPath == NULL) {
  2823. SetLastError(ERROR_INVALID_PARAMETER);
  2824. return 0;
  2825. }
  2826. AString.Buffer = NULL;
  2827. UString.Buffer = NULL;
  2828. ReturnValue = 0;
  2829. ReturnValueW = 0;
  2830. try {
  2831. if (!Basep8BitStringToDynamicUnicodeString(&UString, lpszShortPath )) {
  2832. goto glpTryExit;
  2833. }
  2834. // we have to get the real converted path in order to find out
  2835. // the required length. An UNICODE char does not necessarily convert
  2836. // to one ANSI char(A DBCS is basically TWO ANSI char!!!!!).
  2837. // First, we use the buffer allocated from the stack. If the buffer
  2838. // is too small, we then allocate it from heap.
  2839. // A check of (lpLongPathW && TempPathW != lpLongPathW) will reveal
  2840. // if we have allocated a buffer from heap and need to release it.
  2841. lpLongPathW = TempPathW;
  2842. ReturnValueW = GetLongPathNameW(UString.Buffer, lpLongPathW, sizeof(TempPathW) / sizeof(WCHAR));
  2843. if (ReturnValueW >= sizeof(TempPathW) / sizeof(WCHAR))
  2844. {
  2845. // the stack-based buffer is too small. Allocate a new buffer
  2846. // from heap.
  2847. lpLongPathW = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( VDM_TAG ),
  2848. ReturnValueW * sizeof(WCHAR)
  2849. );
  2850. if (lpLongPathW) {
  2851. ReturnValueW = GetLongPathNameW(UString.Buffer, lpLongPathW, ReturnValueW);
  2852. }
  2853. else {
  2854. ReturnValueW = 0;
  2855. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2856. }
  2857. }
  2858. if (ReturnValueW)
  2859. {
  2860. // we are here because we have something interesting left to do.
  2861. // Convert the UNICODE path name to ANSI(or OEM).
  2862. UString.MaximumLength = (USHORT)((ReturnValueW + 1) * sizeof(WCHAR));
  2863. UStringRet.Buffer = lpLongPathW;
  2864. UStringRet.Length = (USHORT)(ReturnValueW * sizeof(WCHAR));
  2865. Status = BasepUnicodeStringTo8BitString(&AString,
  2866. &UStringRet,
  2867. TRUE
  2868. );
  2869. if (!NT_SUCCESS(Status))
  2870. {
  2871. BaseSetLastNTError(Status);
  2872. ReturnValue=0;
  2873. goto glpTryExit;
  2874. }
  2875. // now AString.Length contains the size of the converted path
  2876. // name. If the caller provides enough buffer, copy the
  2877. // path name.
  2878. ReturnValue = AString.Length;
  2879. if (ARGUMENT_PRESENT(lpLongPath) && cchBuffer > ReturnValue)
  2880. {
  2881. RtlMoveMemory(lpLongPath, AString.Buffer, ReturnValue);
  2882. // terminate the buffer with NULL char.
  2883. lpLongPath[ReturnValue] = '\0';
  2884. }
  2885. else
  2886. {
  2887. // either the caller does not provide a buffer or
  2888. // the provided buffer is too small, return the required size,
  2889. // including the terminated null char.
  2890. ReturnValue++;
  2891. }
  2892. }
  2893. glpTryExit:;
  2894. }
  2895. finally {
  2896. if (UString.Buffer)
  2897. RtlFreeUnicodeString(&UString);
  2898. if (AString.Buffer)
  2899. RtlFreeAnsiString(&AString);
  2900. if (lpLongPathW && lpLongPathW != TempPathW)
  2901. RtlFreeHeap(RtlProcessHeap(), 0, lpLongPathW);
  2902. }
  2903. return ReturnValue;
  2904. }
  2905. DWORD
  2906. APIENTRY
  2907. GetLongPathNameW(
  2908. IN LPCWSTR lpszShortPath,
  2909. IN LPWSTR lpszLongPath,
  2910. IN DWORD cchBuffer
  2911. )
  2912. {
  2913. LPCWSTR pcs;
  2914. DWORD ReturnLen, Length;
  2915. LPWSTR pSrc, pSrcCopy, pFirst, pLast, Buffer, pDst;
  2916. WCHAR wch;
  2917. HANDLE FindHandle;
  2918. WIN32_FIND_DATAW FindData;
  2919. UINT PrevErrorMode;
  2920. if (!ARGUMENT_PRESENT(lpszShortPath)) {
  2921. SetLastError(ERROR_INVALID_PARAMETER);
  2922. return 0;
  2923. }
  2924. //
  2925. // override the error mode since we will be touching the media.
  2926. // This is to prevent file system's pop-up when the given path does not
  2927. // exist or the media is not available.
  2928. // we are doing this because we can not depend on the caller's current
  2929. // error mode. NOTE: the old error mode must be restored.
  2930. PrevErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
  2931. try {
  2932. Buffer = NULL;
  2933. pSrcCopy = NULL;
  2934. // first make sure the given path exist.
  2935. //
  2936. if (0xFFFFFFFF == GetFileAttributesW(lpszShortPath))
  2937. {
  2938. // last error has been set by GetFileAttributes
  2939. ReturnLen = 0;
  2940. goto glnTryExit;
  2941. }
  2942. pcs = SkipPathTypeIndicator_U(lpszShortPath);
  2943. if (!pcs || *pcs == UNICODE_NULL || !FindLFNorSFN_U((LPWSTR)pcs, &pFirst, &pLast, FALSE))
  2944. {
  2945. // The path is ok and does not need conversion at all.
  2946. // Check if we need to do copy
  2947. ReturnLen = wcslen(lpszShortPath);
  2948. if (cchBuffer > ReturnLen && ARGUMENT_PRESENT(lpszLongPath))
  2949. {
  2950. if (lpszLongPath != lpszShortPath)
  2951. RtlMoveMemory(lpszLongPath, lpszShortPath,
  2952. (ReturnLen + 1)* sizeof(WCHAR)
  2953. );
  2954. }
  2955. else {
  2956. // No buffer or buffer too small, the return size
  2957. // has to count the terminated NULL char
  2958. ReturnLen++;
  2959. }
  2960. goto glnTryExit;
  2961. }
  2962. // conversions are necessary, make a local copy of the string
  2963. // because we have to party on it.
  2964. ASSERT(!pSrcCopy);
  2965. Length = wcslen(lpszShortPath) + 1;
  2966. pSrcCopy = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( VDM_TAG ),
  2967. Length * sizeof(WCHAR)
  2968. );
  2969. if (!pSrcCopy) {
  2970. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2971. goto glnTryExit;
  2972. }
  2973. RtlMoveMemory(pSrcCopy, lpszShortPath, Length * sizeof(WCHAR));
  2974. // pFirst points to the first char of the very first SFN in the path
  2975. // pLast points to the char right after the last char of the very
  2976. // first SFN in the path. *pLast could be UNICODE_NULL
  2977. pFirst = pSrcCopy + (pFirst - lpszShortPath);
  2978. pLast = pSrcCopy + (pLast - lpszShortPath);
  2979. //
  2980. // We allow lpszShortPath be overlapped with lpszLongPath so
  2981. // allocate a local buffer if necessary:
  2982. // (1) the caller does provide a legitimate buffer and
  2983. // (2) the buffer overlaps with lpszShortName
  2984. pDst = lpszLongPath;
  2985. if (cchBuffer && ARGUMENT_PRESENT(lpszLongPath) &&
  2986. (lpszLongPath >= lpszShortPath && lpszLongPath < lpszShortPath + Length ||
  2987. lpszLongPath < lpszShortPath && lpszLongPath + cchBuffer >= lpszShortPath))
  2988. {
  2989. ASSERT(!Buffer);
  2990. Buffer = RtlAllocateHeap(RtlProcessHeap(), MAKE_TAG( VDM_TAG ),
  2991. cchBuffer * sizeof(WCHAR));
  2992. if (!Buffer){
  2993. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2994. goto glnTryExit;
  2995. }
  2996. pDst = Buffer;
  2997. }
  2998. pSrc = pSrcCopy;
  2999. ReturnLen = 0;
  3000. do {
  3001. // there are three pointers involve in the conversion loop:
  3002. // pSrc, pFirst and pLast. Their relationship
  3003. // is:
  3004. //
  3005. // "c:\long~1.1\\foo.bar\\long~2.2\\bar"
  3006. // ^ ^ ^ ^
  3007. // | | | |
  3008. // | pSrc pFirst pLast
  3009. // pSrcCopy
  3010. //
  3011. // pSrcCopy always points to the very first char of the entire
  3012. // path.
  3013. //
  3014. // chars between pSrc(included) and pFirst(not included)
  3015. // do not need conversion so we simply copy them.
  3016. // chars between pFirst(included) and pLast(not included)
  3017. // need conversion.
  3018. //
  3019. Length = (ULONG)(pFirst - pSrc);
  3020. ReturnLen += Length;
  3021. if (Length && cchBuffer > ReturnLen && ARGUMENT_PRESENT(lpszShortPath))
  3022. {
  3023. RtlMoveMemory(pDst, pSrc, Length * sizeof(WCHAR));
  3024. pDst += Length;
  3025. }
  3026. // now try to convert the name, chars between pFirst and (pLast - 1)
  3027. wch = *pLast;
  3028. *pLast = UNICODE_NULL;
  3029. FindHandle = FindFirstFileW(pSrcCopy, &FindData);
  3030. *pLast = wch;
  3031. if (FindHandle != INVALID_HANDLE_VALUE){
  3032. FindClose(FindHandle);
  3033. // if no long name, copy the original name
  3034. // starts with pFirst(included) and ends with pLast(excluded)
  3035. if (!(Length = wcslen(FindData.cFileName)))
  3036. Length = (ULONG)(pLast - pFirst);
  3037. else
  3038. pFirst = FindData.cFileName;
  3039. ReturnLen += Length;
  3040. if (cchBuffer > ReturnLen && ARGUMENT_PRESENT(lpszLongPath))
  3041. {
  3042. RtlMoveMemory(pDst, pFirst, Length * sizeof(WCHAR));
  3043. pDst += Length;
  3044. }
  3045. }
  3046. else {
  3047. // invalid path, reset the length, mark the error and
  3048. // bail out of the loop. We will be copying the source
  3049. // to destination later.
  3050. //
  3051. ReturnLen = 0;
  3052. break;
  3053. }
  3054. pSrc = pLast;
  3055. if (*pSrc == UNICODE_NULL)
  3056. break;
  3057. } while (FindLFNorSFN_U(pSrc, &pFirst, &pLast, FALSE));
  3058. if (ReturnLen) {
  3059. //copy the rest of the path from pSrc. This may only contain
  3060. //a single NULL char
  3061. Length = wcslen(pSrc);
  3062. ReturnLen += Length;
  3063. if (cchBuffer > ReturnLen && ARGUMENT_PRESENT(lpszLongPath))
  3064. {
  3065. RtlMoveMemory(pDst, pSrc, (Length + 1) * sizeof(WCHAR));
  3066. if (Buffer)
  3067. RtlMoveMemory(lpszLongPath, Buffer, (ReturnLen + 1) * sizeof(WCHAR));
  3068. }
  3069. else
  3070. ReturnLen++;
  3071. }
  3072. glnTryExit:
  3073. ;
  3074. }
  3075. finally {
  3076. if (pSrcCopy)
  3077. RtlFreeHeap(RtlProcessHeap(), 0, pSrcCopy);
  3078. if (Buffer)
  3079. RtlFreeHeap(RtlProcessHeap(), 0, Buffer);
  3080. }
  3081. // restore error mode.
  3082. SetErrorMode(PrevErrorMode);
  3083. return ReturnLen;
  3084. }
  3085. /**
  3086. Search for SFN(Short File Name) or LFN(Long File Name) in the
  3087. given path depends on FindLFN.
  3088. Input: LPWSTR Path
  3089. The given path name. Does not have to be fully qualified.
  3090. However, path type separaters are not allowed.
  3091. LPWSTR* ppFirst
  3092. To return the pointer points to the first char
  3093. of the name found.
  3094. LPWSTR* ppLast
  3095. To return the pointer points the char right after
  3096. the last char of the name found.
  3097. BOOL FindLFN
  3098. TRUE to search for LFN, otherwise, search for SFN
  3099. Output:
  3100. TRUE
  3101. if the target file name type is found, ppFirst and
  3102. ppLast are filled with pointers.
  3103. FALSE
  3104. if the target file name type not found.
  3105. Remark: "\\." and "\\.." are special cases. When encountered, they
  3106. are ignored and the function continue to search
  3107. **/
  3108. BOOL
  3109. FindLFNorSFN_U(
  3110. LPWSTR Path,
  3111. LPWSTR* ppFirst,
  3112. LPWSTR* ppLast,
  3113. BOOL FindLFN
  3114. )
  3115. {
  3116. LPWSTR pFirst, pLast;
  3117. BOOL TargetFound;
  3118. ASSERT(Path);
  3119. pFirst = Path;
  3120. TargetFound = FALSE;
  3121. while(TRUE) {
  3122. //skip over leading path separator
  3123. // it is legal to have multiple path separators in between
  3124. // name such as "foobar\\\\\\multiplepathchar"
  3125. while (*pFirst != UNICODE_NULL && (*pFirst == L'\\' || *pFirst == L'/'))
  3126. pFirst++;
  3127. if (*pFirst == UNICODE_NULL)
  3128. break;
  3129. pLast = pFirst + 1;
  3130. while (*pLast != UNICODE_NULL && *pLast != L'\\' && *pLast != L'/')
  3131. pLast++;
  3132. if (FindLFN)
  3133. TargetFound = !IsShortName_U(pFirst, (int)(pLast - pFirst));
  3134. else
  3135. TargetFound = !IsLongName_U(pFirst, (int)(pLast - pFirst));
  3136. if (TargetFound) {
  3137. if(ppFirst && ppLast) {
  3138. *ppFirst = pFirst;
  3139. // pLast point to the last char of the path/file name
  3140. *ppLast = pLast;
  3141. }
  3142. break;
  3143. }
  3144. if (*pLast == UNICODE_NULL)
  3145. break;
  3146. pFirst = pLast + 1;
  3147. }
  3148. return TargetFound;
  3149. }
  3150. LPCWSTR
  3151. SkipPathTypeIndicator_U(
  3152. LPCWSTR Path
  3153. )
  3154. {
  3155. RTL_PATH_TYPE RtlPathType;
  3156. LPCWSTR pFirst;
  3157. DWORD Count;
  3158. RtlPathType = RtlDetermineDosPathNameType_U(Path);
  3159. switch (RtlPathType) {
  3160. // form: "\\server_name\share_name\rest_of_the_path"
  3161. case RtlPathTypeUncAbsolute:
  3162. case RtlPathTypeLocalDevice:
  3163. pFirst = Path + 2;
  3164. Count = 2;
  3165. // guard for UNICODE_NULL is necessary because
  3166. // RtlDetermineDosPathNameType_U doesn't really
  3167. // verify an UNC name.
  3168. while (Count && *pFirst != UNICODE_NULL) {
  3169. if (*pFirst == L'\\' || *pFirst == L'/')
  3170. Count--;
  3171. pFirst++;
  3172. }
  3173. break;
  3174. // form: "\\."
  3175. case RtlPathTypeRootLocalDevice:
  3176. pFirst = NULL;
  3177. break;
  3178. // form: "D:\rest_of_the_path"
  3179. case RtlPathTypeDriveAbsolute:
  3180. pFirst = Path + 3;
  3181. break;
  3182. // form: "D:rest_of_the_path"
  3183. case RtlPathTypeDriveRelative:
  3184. pFirst = Path + 2;
  3185. break;
  3186. // form: "\rest_of_the_path"
  3187. case RtlPathTypeRooted:
  3188. pFirst = Path + 1;
  3189. break;
  3190. // form: "rest_of_the_path"
  3191. case RtlPathTypeRelative:
  3192. pFirst = Path;
  3193. break;
  3194. default:
  3195. pFirst = NULL;
  3196. break;
  3197. }
  3198. return pFirst;
  3199. }
  3200. /**
  3201. This function determines if the given name is a valid short name.
  3202. This function only does "obvious" testing since there are not precise
  3203. ways to cover all the file systems(each file system has its own
  3204. file name domain(for example, FAT allows all extended chars and space char
  3205. while NTFS **may** not).
  3206. The main purpose is to help the caller decide if a long to short name
  3207. conversion is necessary. When in doubt, this function simply tells the
  3208. caller that the given name is NOT a short name so that caller would
  3209. do whatever it takes to convert the name.
  3210. This function applies strict rules in deciding if the given name
  3211. is a valid short name. For example, a name containing any extended chars
  3212. is treated as invalid; a name with embedded space chars is also treated
  3213. as invalid.
  3214. A name is a valid short name if ALL the following conditions are met:
  3215. (1). total length <= 13.
  3216. (2). 0 < base name length <= 8.
  3217. (3). extention name length <= 3.
  3218. (4). only one '.' is allowed and must not be the first char.
  3219. (5). every char must be legal defined by the IllegalMask array.
  3220. null path, "." and ".." are treated valid.
  3221. Input: LPCWSTR Name - points to the name to be checked. It does not
  3222. have to be NULL terminated.
  3223. int Length - Length of the name, not including teminated NULL char.
  3224. output: TRUE - if the given name is a short file name.
  3225. FALSE - if the given name is not a short file name
  3226. **/
  3227. // bit set -> char is illegal
  3228. DWORD IllegalMask[] =
  3229. {
  3230. // code 0x00 - 0x1F --> all illegal
  3231. 0xFFFFFFFF,
  3232. // code 0x20 - 0x3f --> 0x20,0x22,0x2A-0x2C,0x2F and 0x3A-0x3F are illegal
  3233. 0xFC009C05,
  3234. // code 0x40 - 0x5F --> 0x5B-0x5D are illegal
  3235. 0x38000000,
  3236. // code 0x60 - 0x7F --> 0x7C is illegal
  3237. 0x10000000
  3238. };
  3239. BOOL
  3240. IsShortName_U(
  3241. LPCWSTR Name,
  3242. int Length
  3243. )
  3244. {
  3245. int Index;
  3246. BOOL ExtensionFound;
  3247. DWORD dwStatus;
  3248. UNICODE_STRING UnicodeName;
  3249. ANSI_STRING AnsiString;
  3250. UCHAR AnsiBuffer[MAX_PATH];
  3251. UCHAR Char;
  3252. ASSERT(Name);
  3253. // total length must less than 13(8.3 = 8 + 1 + 3 = 12)
  3254. if (Length > 12)
  3255. return FALSE;
  3256. // "" or "." or ".."
  3257. if (!Length)
  3258. return TRUE;
  3259. if (L'.' == *Name)
  3260. {
  3261. // "." or ".."
  3262. if (1 == Length || (2 == Length && L'.' == Name[1]))
  3263. return TRUE;
  3264. else
  3265. // '.' can not be the first char(base name length is 0)
  3266. return FALSE;
  3267. }
  3268. UnicodeName.Buffer = (LPWSTR)Name;
  3269. UnicodeName.Length =
  3270. UnicodeName.MaximumLength = (USHORT)(Length * sizeof(WCHAR));
  3271. AnsiString.Buffer = AnsiBuffer;
  3272. AnsiString.Length = 0;
  3273. AnsiString.MaximumLength = MAX_PATH; // make a dangerous assumption
  3274. dwStatus = BasepUnicodeStringTo8BitString(&AnsiString,
  3275. &UnicodeName,
  3276. FALSE);
  3277. if (! NT_SUCCESS(dwStatus)) {
  3278. return(FALSE);
  3279. }
  3280. // all trivial cases are tested, now we have to walk through the name
  3281. ExtensionFound = FALSE;
  3282. for (Index = 0; Index < AnsiString.Length; Index++)
  3283. {
  3284. Char = AnsiString.Buffer[Index];
  3285. // Skip over and Dbcs characters
  3286. if (IsDBCSLeadByte(Char)) {
  3287. //
  3288. // 1) if we're looking at base part ( !ExtensionPresent ) and the 8th byte
  3289. // is in the dbcs leading byte range, it's error ( Index == 7 ). If the
  3290. // length of base part is more than 8 ( Index > 7 ), it's definitely error.
  3291. //
  3292. // 2) if the last byte ( Index == DbcsName.Length - 1 ) is in the dbcs leading
  3293. // byte range, it's error
  3294. //
  3295. if ((!ExtensionFound && (Index >= 7)) ||
  3296. (Index == AnsiString.Length - 1)) {
  3297. return FALSE;
  3298. }
  3299. Index += 1;
  3300. continue;
  3301. }
  3302. // make sure the char is legal
  3303. if (Char > 0x7F || IllegalMask[Char / 32] & (1 << (Char % 32)))
  3304. return FALSE;
  3305. if ('.' == Char)
  3306. {
  3307. // (1) can have only one '.'
  3308. // (2) can not have more than 3 chars following.
  3309. if (ExtensionFound || Length - (Index + 1) > 3)
  3310. {
  3311. return FALSE;
  3312. }
  3313. ExtensionFound = TRUE;
  3314. }
  3315. // base length > 8 chars
  3316. if (Index >= 8 && !ExtensionFound)
  3317. return FALSE;
  3318. }
  3319. return TRUE;
  3320. }
  3321. /**
  3322. This function determines if the given name is a valid long name.
  3323. This function only does "obvious" testing since there are not precise
  3324. ways to cover all the file systems(each file system has its own
  3325. file name domain(for example, FAT allows all extended chars and space char
  3326. while NTFS **may** not)
  3327. This function helps the caller to determine if a short to long name
  3328. conversion is necessary. When in doubt, this function simply tells the
  3329. caller that the given name is NOT a long name so that caller would
  3330. do whatever it takes to convert the name.
  3331. A name is a valid long name if one of the following conditions is met:
  3332. (1). total length >= 13.
  3333. (2). 0 == base name length || base name length > 8.
  3334. (3). extention name length > 3.
  3335. (4). '.' is the first char.
  3336. (5). muitlple '.'
  3337. null path, "." and ".." are treat as valid long name.
  3338. Input: LPCWSTR Name - points to the name to be checked. It does not
  3339. have to be NULL terminated.
  3340. int Length - Length of the name, not including teminated NULL char.
  3341. output: TRUE - if the given name is a long file name.
  3342. FALSE - if the given name is not a long file name
  3343. **/
  3344. BOOL
  3345. IsLongName_U(
  3346. LPCWSTR Name,
  3347. int Length
  3348. )
  3349. {
  3350. int Index;
  3351. BOOL ExtensionFound;
  3352. // (1) NULL path
  3353. // (2) total length > 12
  3354. // (3) . is the first char (cover "." and "..")
  3355. if (!Length || Length > 12 || L'.' == *Name)
  3356. return TRUE;
  3357. ExtensionFound = FALSE;
  3358. for (Index = 0; Index < Length; Index++)
  3359. {
  3360. if (L'.' == Name[Index])
  3361. {
  3362. // multiple . or extension longer than 3
  3363. if (ExtensionFound || Length - (Index + 1) > 3)
  3364. return TRUE;
  3365. ExtensionFound = TRUE;
  3366. }
  3367. // base length longer than 8
  3368. if (Index >= 8 && !ExtensionFound)
  3369. return TRUE;
  3370. }
  3371. return FALSE;
  3372. }