Fix compilation.
[reactos.git] / reactos / subsystems / mvdm / ntvdm / dos / dem.c
1 /*
2 * COPYRIGHT: GPL - See COPYING in the top level directory
3 * PROJECT: ReactOS Virtual DOS Machine
4 * FILE: dem.c
5 * PURPOSE: DOS 32-bit Emulation Support Library -
6 * This library is used by the built-in NTVDM DOS32 and by
7 * the NT 16-bit DOS in Windows (via BOPs). It also exposes
8 * exported functions that can be used by VDDs.
9 * PROGRAMMERS: Aleksandar Andrejevic <theflash AT sdf DOT lonestar DOT org>
10 * Hermes Belusca-Maito (hermes.belusca@sfr.fr)
11 */
12
13 /* INCLUDES *******************************************************************/
14
15 #define NDEBUG
16
17 #include "ntvdm.h"
18 #include "emulator.h"
19 #include "utils.h"
20
21 #include "dem.h"
22 #include "dos/dos32krnl/device.h"
23 #include "dos/dos32krnl/process.h"
24 #include "cpu/bop.h"
25
26 #include "bios/bios.h"
27 #include "mouse32.h"
28
29 /* PRIVATE VARIABLES **********************************************************/
30
31 /**/extern BYTE CurrentDrive;/**/
32
33 /* PRIVATE FUNCTIONS **********************************************************/
34
35 static VOID WINAPI DosSystemBop(LPWORD Stack)
36 {
37 /* Get the Function Number and skip it */
38 BYTE FuncNum = *(PBYTE)SEG_OFF_TO_PTR(getCS(), getIP());
39 setIP(getIP() + 1);
40
41 switch (FuncNum)
42 {
43 case 0x11: // Load the DOS kernel
44 {
45 BOOLEAN Success = FALSE;
46 HANDLE hDosKernel;
47 ULONG ulDosKernelSize = 0;
48
49 DPRINT1("You are loading Windows NT DOS!\n");
50
51 /* Open the DOS kernel file */
52 hDosKernel = FileOpen("ntdos.sys", &ulDosKernelSize);
53
54 /* If we failed, bail out */
55 if (hDosKernel == NULL) goto Quit;
56
57 /*
58 * Attempt to load the DOS kernel into memory.
59 * The segment where to load the DOS kernel is defined
60 * by the DOS BIOS and is found in DI:0000 .
61 */
62 Success = FileLoadByHandle(hDosKernel,
63 REAL_TO_PHYS(TO_LINEAR(getDI(), 0x0000)),
64 ulDosKernelSize,
65 &ulDosKernelSize);
66
67 DPRINT1("Windows NT DOS loading %s at %04X:%04X, size 0x%X ; GetLastError() = %u\n",
68 (Success ? "succeeded" : "failed"),
69 getDI(), 0x0000,
70 ulDosKernelSize,
71 GetLastError());
72
73 /* Close the DOS kernel file */
74 FileClose(hDosKernel);
75
76 Quit:
77 if (!Success)
78 {
79 /* We failed everything, stop the VDM */
80 EmulatorTerminate();
81 }
82
83 break;
84 }
85
86 /* Call 32-bit Driver Strategy Routine */
87 case BOP_DRV_STRATEGY:
88 {
89 DeviceStrategyBop();
90 break;
91 }
92
93 /* Call 32-bit Driver Interrupt Routine */
94 case BOP_DRV_INTERRUPT:
95 {
96 DeviceInterruptBop();
97 break;
98 }
99
100 default:
101 {
102 DPRINT1("Unknown DOS System BOP Function: 0x%02X\n", FuncNum);
103 // setCF(1); // Disable, otherwise we enter an infinite loop
104 break;
105 }
106 }
107 }
108
109 static VOID WINAPI DosCmdInterpreterBop(LPWORD Stack)
110 {
111 /* Get the Function Number and skip it */
112 BYTE FuncNum = *(PBYTE)SEG_OFF_TO_PTR(getCS(), getIP());
113 setIP(getIP() + 1);
114
115 switch (FuncNum)
116 {
117 case 0x08: // Launch external command
118 {
119 BOOL Result;
120 DWORD dwExitCode;
121
122 LPSTR Command = (LPSTR)SEG_OFF_TO_PTR(getDS(), getSI());
123 CHAR CmdLine[sizeof("cmd.exe /c ") + DOS_CMDLINE_LENGTH + 1] = "";
124 LPSTR CmdLinePtr;
125 ULONG CmdLineLen;
126 STARTUPINFOA StartupInfo;
127 PROCESS_INFORMATION ProcessInformation;
128
129 /* Spawn a user-defined 32-bit command preprocessor */
130
131 // FIXME: Use COMSPEC env var!!
132 CmdLinePtr = CmdLine;
133 strcpy(CmdLinePtr, "cmd.exe /c ");
134 CmdLinePtr += strlen(CmdLinePtr);
135
136 /* Build a Win32-compatible command-line */
137 CmdLineLen = min(strlen(Command), sizeof(CmdLine) - strlen(CmdLinePtr) - 1);
138 RtlCopyMemory(CmdLinePtr, Command, CmdLineLen);
139 CmdLinePtr[CmdLineLen] = '\0';
140
141 /* Remove any trailing return carriage character and NULL-terminate the command line */
142 while (*CmdLinePtr && *CmdLinePtr != '\r' && *CmdLinePtr != '\n') CmdLinePtr++;
143 *CmdLinePtr = '\0';
144
145 DPRINT1("CMD Run Command '%s' ('%s')\n", Command, CmdLine);
146
147 RtlZeroMemory(&StartupInfo, sizeof(StartupInfo));
148 RtlZeroMemory(&ProcessInformation, sizeof(ProcessInformation));
149
150 StartupInfo.cb = sizeof(StartupInfo);
151
152 VidBiosDetachFromConsole();
153
154 Result = CreateProcessA(NULL,
155 CmdLine,
156 NULL,
157 NULL,
158 TRUE,
159 0,
160 NULL,
161 NULL,
162 &StartupInfo,
163 &ProcessInformation);
164 if (Result)
165 {
166 DPRINT1("Command '%s' ('%s') launched successfully\n", Command, CmdLine);
167
168 /* Wait for process termination */
169 WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
170
171 /* Get the exit code */
172 GetExitCodeProcess(ProcessInformation.hProcess, &dwExitCode);
173
174 /* Close handles */
175 CloseHandle(ProcessInformation.hThread);
176 CloseHandle(ProcessInformation.hProcess);
177 }
178 else
179 {
180 DPRINT1("Failed when launched command '%s' ('%s')\n", Command, CmdLine);
181 dwExitCode = GetLastError();
182 }
183
184 VidBiosAttachToConsole();
185
186 setAL((UCHAR)dwExitCode);
187
188 break;
189 }
190
191 default:
192 {
193 DPRINT1("Unknown DOS CMD Interpreter BOP Function: 0x%02X\n", FuncNum);
194 // setCF(1); // Disable, otherwise we enter an infinite loop
195 break;
196 }
197 }
198 }
199
200 #ifndef STANDALONE
201 static DWORD
202 WINAPI
203 CommandThreadProc(LPVOID Parameter)
204 {
205 BOOLEAN First = TRUE;
206 DWORD Result;
207 VDM_COMMAND_INFO CommandInfo;
208 CHAR CmdLine[MAX_PATH];
209 CHAR AppName[MAX_PATH];
210 CHAR PifFile[MAX_PATH];
211 CHAR Desktop[MAX_PATH];
212 CHAR Title[MAX_PATH];
213 ULONG EnvSize = 256;
214 PVOID Env = RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, EnvSize);
215
216 UNREFERENCED_PARAMETER(Parameter);
217 ASSERT(Env);
218
219 do
220 {
221 /* Clear the structure */
222 RtlZeroMemory(&CommandInfo, sizeof(CommandInfo));
223
224 /* Initialize the structure members */
225 CommandInfo.TaskId = SessionId;
226 CommandInfo.VDMState = VDM_FLAG_DOS;
227 CommandInfo.CmdLine = CmdLine;
228 CommandInfo.CmdLen = sizeof(CmdLine);
229 CommandInfo.AppName = AppName;
230 CommandInfo.AppLen = sizeof(AppName);
231 CommandInfo.PifFile = PifFile;
232 CommandInfo.PifLen = sizeof(PifFile);
233 CommandInfo.Desktop = Desktop;
234 CommandInfo.DesktopLen = sizeof(Desktop);
235 CommandInfo.Title = Title;
236 CommandInfo.TitleLen = sizeof(Title);
237 CommandInfo.Env = Env;
238 CommandInfo.EnvLen = EnvSize;
239
240 if (First) CommandInfo.VDMState |= VDM_FLAG_FIRST_TASK;
241
242 Command:
243 if (!GetNextVDMCommand(&CommandInfo))
244 {
245 if (CommandInfo.EnvLen > EnvSize)
246 {
247 /* Expand the environment size */
248 EnvSize = CommandInfo.EnvLen;
249 CommandInfo.Env = Env = RtlReAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY, Env, EnvSize);
250
251 /* Repeat the request */
252 CommandInfo.VDMState |= VDM_FLAG_RETRY;
253 goto Command;
254 }
255
256 break;
257 }
258
259 /* Start the process from the command line */
260 DPRINT1("Starting '%s' ('%.*s')...\n",
261 AppName,
262 CommandInfo.CmdLen >= 2 ? CommandInfo.CmdLen - 2 /* Display the command line without the terminating 0d 0a */
263 : CommandInfo.CmdLen,
264 CmdLine);
265 Result = DosStartProcess(AppName, CmdLine, Env);
266 if (Result != ERROR_SUCCESS)
267 {
268 DisplayMessage(L"Could not start '%S'. Error: %u", AppName, Result);
269 // break;
270 continue;
271 }
272
273 First = FALSE;
274 }
275 while (AcceptCommands);
276
277 RtlFreeHeap(RtlGetProcessHeap(), 0, Env);
278 return 0;
279 }
280 #endif
281
282 /* PUBLIC FUNCTIONS ***********************************************************/
283
284 //
285 // This function (equivalent of the DOS bootsector) is called by the bootstrap
286 // loader *BEFORE* jumping at 0000:7C00. What we should do is to write at 0000:7C00
287 // a BOP call that calls DosInitialize back. Then the bootstrap loader jumps at
288 // 0000:7C00, our BOP gets called and then we can initialize the 32-bit part of the DOS.
289 //
290
291 /* 16-bit bootstrap code at 0000:7C00 */
292 /* Of course, this is not in real bootsector format, because we don't care */
293 static BYTE Bootsector1[] =
294 {
295 LOBYTE(EMULATOR_BOP), HIBYTE(EMULATOR_BOP), BOP_LOAD_DOS, // Call DOS Loading
296 };
297 /* This portion of code is run if we failed to load the DOS */
298 static BYTE Bootsector2[] =
299 {
300 0xEA, // jmp far ptr
301 0x5B, 0xE0, 0x00, 0xF0, // F000:E05B /** HACK! What to do instead?? **/
302 };
303
304 static VOID WINAPI DosInitialize(LPWORD Stack);
305
306 VOID DosBootsectorInitialize(VOID)
307 {
308 /* We write the bootsector at 0000:7C00 */
309 ULONG_PTR Address = (ULONG_PTR)SEG_OFF_TO_PTR(0x0000, 0x7C00);
310 CHAR DosKernelFileName[] = ""; // No DOS file name, therefore we'll load DOS32
311
312 DPRINT("DosBootsectorInitialize\n");
313
314 /* Write the "bootsector" */
315 RtlCopyMemory((PVOID)Address, Bootsector1, sizeof(Bootsector1));
316 Address += sizeof(Bootsector1);
317 RtlCopyMemory((PVOID)Address, DosKernelFileName, sizeof(DosKernelFileName));
318 Address += sizeof(DosKernelFileName);
319 RtlCopyMemory((PVOID)Address, Bootsector2, sizeof(Bootsector2));
320
321 /* Register the DOS Loading BOP */
322 RegisterBop(BOP_LOAD_DOS, DosInitialize);
323 }
324
325
326 //
327 // This function is called by the DOS bootsector. We finish to load
328 // the DOS, then we jump to 0070:0000.
329 //
330
331 /* 16-bit startup code at 0070:0000 */
332 static BYTE Startup[] =
333 {
334 LOBYTE(EMULATOR_BOP), HIBYTE(EMULATOR_BOP), BOP_START_DOS, // Call DOS Start
335 };
336
337 static VOID WINAPI DosStart(LPWORD Stack);
338
339 static VOID WINAPI DosInitialize(LPWORD Stack)
340 {
341 BOOLEAN Success = FALSE;
342
343 /* Get the DOS kernel file name (NULL-terminated) */
344 // FIXME: Isn't it possible to use some DS:SI instead??
345 LPCSTR DosKernelFileName = (LPCSTR)SEG_OFF_TO_PTR(getCS(), getIP());
346 setIP(getIP() + strlen(DosKernelFileName) + 1); // Skip it
347
348 DPRINT("DosInitialize('%s')\n", DosKernelFileName);
349
350 /* Register the DOS BOPs */
351 RegisterBop(BOP_DOS, DosSystemBop );
352 RegisterBop(BOP_CMD, DosCmdInterpreterBop);
353
354 if (DosKernelFileName && DosKernelFileName[0] != '\0')
355 {
356 HANDLE hDosBios;
357 ULONG ulDosBiosSize = 0;
358
359 /* Open the DOS BIOS file */
360 hDosBios = FileOpen(DosKernelFileName, &ulDosBiosSize);
361
362 /* If we failed, bail out */
363 if (hDosBios == NULL) goto QuitCustom;
364
365 /* Attempt to load the DOS BIOS into memory */
366 Success = FileLoadByHandle(hDosBios,
367 REAL_TO_PHYS(TO_LINEAR(0x0070, 0x0000)),
368 ulDosBiosSize,
369 &ulDosBiosSize);
370
371 DPRINT1("DOS BIOS loading %s at %04X:%04X, size 0x%X ; GetLastError() = %u\n",
372 (Success ? "succeeded" : "failed"),
373 0x0070, 0x0000,
374 ulDosBiosSize,
375 GetLastError());
376
377 /* Close the DOS BIOS file */
378 FileClose(hDosBios);
379
380 if (!Success) goto QuitCustom;
381
382 /* Position execution pointers and return */
383 setCS(0x0070);
384 setIP(0x0000);
385
386 /* Return control */
387 QuitCustom:
388 if (!Success)
389 DisplayMessage(L"Custom DOS '%S' loading failed, what to do??", DosKernelFileName);
390 }
391 else
392 {
393 Success = DosBIOSInitialize();
394 // Success &= DosKRNLInitialize();
395
396 if (!Success) goto Quit32;
397
398 /* Write the "bootsector" */
399 RtlCopyMemory(SEG_OFF_TO_PTR(0x0070, 0x0000), Startup, sizeof(Startup));
400
401 /* Register the DOS Starting BOP */
402 RegisterBop(BOP_START_DOS, DosStart);
403
404 /* Position execution pointers and return */
405 setCS(0x0070);
406 setIP(0x0000);
407
408 /* Return control */
409 Quit32:
410 if (!Success)
411 DisplayMessage(L"DOS32 loading failed, what to do??");
412 }
413
414 if (Success)
415 {
416 /*
417 * We succeeded, deregister the DOS Loading BOP
418 * so that no app will be able to call us back.
419 */
420 RegisterBop(BOP_LOAD_DOS, NULL);
421 }
422 }
423
424 static VOID WINAPI DosStart(LPWORD Stack)
425 {
426 #ifdef STANDALONE
427 DWORD Result;
428 CHAR ApplicationName[MAX_PATH];
429 CHAR CommandLine[DOS_CMDLINE_LENGTH];
430 #endif
431
432 DPRINT("DosStart\n");
433
434 /*
435 * We succeeded, deregister the DOS Starting BOP
436 * so that no app will be able to call us back.
437 */
438 RegisterBop(BOP_START_DOS, NULL);
439
440 /* Load the mouse driver */
441 DosMouseInitialize();
442
443 #ifndef STANDALONE
444
445 /* Create the GetNextVDMCommand thread */
446 CommandThread = CreateThread(NULL, 0, &CommandThreadProc, NULL, 0, NULL);
447 if (CommandThread == NULL)
448 {
449 wprintf(L"FATAL: Failed to create the command processing thread: %d\n", GetLastError());
450 goto Quit;
451 }
452
453 /* Wait for the command thread to exit */
454 WaitForSingleObject(CommandThread, INFINITE);
455
456 /* Close the thread handle */
457 CloseHandle(CommandThread);
458
459 #else
460
461 if (NtVdmArgc >= 2)
462 {
463 WideCharToMultiByte(CP_ACP, 0, NtVdmArgv[1], -1, ApplicationName, sizeof(ApplicationName), NULL, NULL);
464
465 if (NtVdmArgc >= 3)
466 WideCharToMultiByte(CP_ACP, 0, NtVdmArgv[2], -1, CommandLine, sizeof(CommandLine), NULL, NULL);
467 else
468 strcpy(CommandLine, "");
469 }
470 else
471 {
472 DisplayMessage(L"Invalid DOS command line\n");
473 goto Quit;
474 }
475
476 /* Start the process from the command line */
477 DPRINT1("Starting '%s' ('%s')...\n", ApplicationName, CommandLine);
478 Result = DosStartProcess(ApplicationName, CommandLine,
479 SEG_OFF_TO_PTR(SYSTEM_ENV_BLOCK, 0));
480 if (Result != ERROR_SUCCESS)
481 {
482 DisplayMessage(L"Could not start '%S'. Error: %u", ApplicationName, Result);
483 goto Quit;
484 }
485
486 #endif
487
488 Quit:
489 /* Stop the VDM */
490 EmulatorTerminate();
491 }
492
493 /* PUBLIC EXPORTED APIS *******************************************************/
494
495 // demLFNCleanup
496 // demLFNGetCurrentDirectory
497
498 // demGetFileTimeByHandle_WOW
499 // demWOWLFNAllocateSearchHandle
500 // demWOWLFNCloseSearchHandle
501 // demWOWLFNEntry
502 // demWOWLFNGetSearchHandle
503 // demWOWLFNInit
504
505 DWORD
506 WINAPI
507 demClientErrorEx(IN HANDLE FileHandle,
508 IN CHAR Unknown,
509 IN BOOL Flag)
510 {
511 UNIMPLEMENTED;
512 return GetLastError();
513 }
514
515 DWORD
516 WINAPI
517 demFileDelete(IN LPCSTR FileName)
518 {
519 if (DeleteFileA(FileName)) SetLastError(ERROR_SUCCESS);
520
521 return GetLastError();
522 }
523
524 DWORD
525 WINAPI
526 demFileFindFirst(OUT PVOID lpFindFileData,
527 IN LPCSTR FileName,
528 IN WORD AttribMask)
529 {
530 BOOLEAN Success = TRUE;
531 WIN32_FIND_DATAA FindData;
532 PDOS_FIND_FILE_BLOCK FindFileBlock = (PDOS_FIND_FILE_BLOCK)lpFindFileData;
533
534 /* Fill the block */
535 FindFileBlock->DriveLetter = CurrentDrive + 'A';
536 FindFileBlock->AttribMask = AttribMask;
537 FindFileBlock->SearchHandle = FindFirstFileA(FileName, &FindData);
538 if (FindFileBlock->SearchHandle == INVALID_HANDLE_VALUE) return GetLastError();
539
540 do
541 {
542 /* Check the attributes */
543 if (!((FindData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN |
544 FILE_ATTRIBUTE_SYSTEM |
545 FILE_ATTRIBUTE_DIRECTORY))
546 & ~AttribMask))
547 {
548 break;
549 }
550 }
551 while ((Success = FindNextFileA(FindFileBlock->SearchHandle, &FindData)));
552
553 if (!Success) return GetLastError();
554
555 FindFileBlock->Attributes = LOBYTE(FindData.dwFileAttributes);
556 FileTimeToDosDateTime(&FindData.ftLastWriteTime,
557 &FindFileBlock->FileDate,
558 &FindFileBlock->FileTime);
559 FindFileBlock->FileSize = FindData.nFileSizeHigh ? 0xFFFFFFFF
560 : FindData.nFileSizeLow;
561 strcpy(FindFileBlock->FileName, FindData.cAlternateFileName);
562
563 return ERROR_SUCCESS;
564 }
565
566 DWORD
567 WINAPI
568 demFileFindNext(OUT PVOID lpFindFileData)
569 {
570 WIN32_FIND_DATAA FindData;
571 PDOS_FIND_FILE_BLOCK FindFileBlock = (PDOS_FIND_FILE_BLOCK)lpFindFileData;
572
573 do
574 {
575 if (!FindNextFileA(FindFileBlock->SearchHandle, &FindData))
576 return GetLastError();
577
578 /* Update the block */
579 FindFileBlock->Attributes = LOBYTE(FindData.dwFileAttributes);
580 FileTimeToDosDateTime(&FindData.ftLastWriteTime,
581 &FindFileBlock->FileDate,
582 &FindFileBlock->FileTime);
583 FindFileBlock->FileSize = FindData.nFileSizeHigh ? 0xFFFFFFFF
584 : FindData.nFileSizeLow;
585 strcpy(FindFileBlock->FileName, FindData.cAlternateFileName);
586 }
587 while((FindData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN |
588 FILE_ATTRIBUTE_SYSTEM |
589 FILE_ATTRIBUTE_DIRECTORY))
590 & ~FindFileBlock->AttribMask);
591
592 return ERROR_SUCCESS;
593 }
594
595 UCHAR
596 WINAPI
597 demGetPhysicalDriveType(IN UCHAR DriveNumber)
598 {
599 UNIMPLEMENTED;
600 return DOSDEVICE_DRIVE_UNKNOWN;
601 }
602
603 BOOL
604 WINAPI
605 demIsShortPathName(IN LPCSTR Path,
606 IN BOOL Unknown)
607 {
608 UNIMPLEMENTED;
609 return FALSE;
610 }
611
612 DWORD
613 WINAPI
614 demSetCurrentDirectoryGetDrive(IN LPCSTR CurrentDirectory,
615 OUT PUCHAR DriveNumber)
616 {
617 UNIMPLEMENTED;
618 return ERROR_SUCCESS;
619 }
620
621 /* EOF */