c2d863d952af890e7b6e0f2f63c493d97edbd9e5
[reactos.git] / subsystems / ntvdm / dos.c
1 /*
2 * COPYRIGHT: GPL - See COPYING in the top level directory
3 * PROJECT: ReactOS Virtual DOS Machine
4 * FILE: dos.c
5 * PURPOSE: VDM DOS Kernel
6 * PROGRAMMERS: Aleksandar Andrejevic <theflash AT sdf DOT lonestar DOT org>
7 */
8
9 /* INCLUDES *******************************************************************/
10
11 #define NDEBUG
12
13 #include "dos.h"
14 #include "bios.h"
15 #include "emulator.h"
16
17 /* PRIVATE VARIABLES **********************************************************/
18
19 static WORD CurrentPsp = SYSTEM_PSP;
20 static WORD DosLastError = 0;
21 static DWORD DiskTransferArea;
22 static BYTE CurrentDrive;
23 static CHAR LastDrive = 'E';
24 static CHAR CurrentDirectories[NUM_DRIVES][DOS_DIR_LENGTH];
25 static HANDLE DosSystemFileTable[DOS_SFT_SIZE];
26 static WORD DosSftRefCount[DOS_SFT_SIZE];
27 static BYTE DosAllocStrategy = DOS_ALLOC_BEST_FIT;
28 static BOOLEAN DosUmbLinked = FALSE;
29
30 /* PRIVATE FUNCTIONS **********************************************************/
31
32 /* Taken from base/shell/cmd/console.c */
33 static BOOL IsConsoleHandle(HANDLE hHandle)
34 {
35 DWORD dwMode;
36
37 /* Check whether the handle may be that of a console... */
38 if ((GetFileType(hHandle) & FILE_TYPE_CHAR) == 0) return FALSE;
39
40 /*
41 * It may be. Perform another test... The idea comes from the
42 * MSDN description of the WriteConsole API:
43 *
44 * "WriteConsole fails if it is used with a standard handle
45 * that is redirected to a file. If an application processes
46 * multilingual output that can be redirected, determine whether
47 * the output handle is a console handle (one method is to call
48 * the GetConsoleMode function and check whether it succeeds).
49 * If the handle is a console handle, call WriteConsole. If the
50 * handle is not a console handle, the output is redirected and
51 * you should call WriteFile to perform the I/O."
52 */
53 return GetConsoleMode(hHandle, &dwMode);
54 }
55
56 static VOID DosCombineFreeBlocks(WORD StartBlock)
57 {
58 PDOS_MCB CurrentMcb = SEGMENT_TO_MCB(StartBlock), NextMcb;
59
60 /* If this is the last block or it's not free, quit */
61 if (CurrentMcb->BlockType == 'Z' || CurrentMcb->OwnerPsp != 0) return;
62
63 while (TRUE)
64 {
65 /* Get a pointer to the next MCB */
66 NextMcb = SEGMENT_TO_MCB(StartBlock + CurrentMcb->Size + 1);
67
68 /* Check if the next MCB is free */
69 if (NextMcb->OwnerPsp == 0)
70 {
71 /* Combine them */
72 CurrentMcb->Size += NextMcb->Size + 1;
73 CurrentMcb->BlockType = NextMcb->BlockType;
74 NextMcb->BlockType = 'I';
75 }
76 else
77 {
78 /* No more adjoining free blocks */
79 break;
80 }
81 }
82 }
83
84 static WORD DosCopyEnvironmentBlock(WORD SourceSegment, LPCSTR ProgramName)
85 {
86 PCHAR Ptr, SourceBuffer, DestBuffer = NULL;
87 ULONG TotalSize = 0;
88 WORD DestSegment;
89
90 Ptr = SourceBuffer = (PCHAR)((ULONG_PTR)BaseAddress + TO_LINEAR(SourceSegment, 0));
91
92 /* Calculate the size of the environment block */
93 while (*Ptr)
94 {
95 TotalSize += strlen(Ptr) + 1;
96 Ptr += strlen(Ptr) + 1;
97 }
98 TotalSize++;
99
100 /* Add the string buffer size */
101 TotalSize += strlen(ProgramName) + 1;
102
103 /* Allocate the memory for the environment block */
104 DestSegment = DosAllocateMemory((WORD)((TotalSize + 0x0F) >> 4), NULL);
105 if (!DestSegment) return 0;
106
107 Ptr = SourceBuffer;
108
109 DestBuffer = (PCHAR)((ULONG_PTR)BaseAddress + TO_LINEAR(DestSegment, 0));
110 while (*Ptr)
111 {
112 /* Copy the string */
113 strcpy(DestBuffer, Ptr);
114
115 /* Advance to the next string */
116 DestBuffer += strlen(Ptr);
117 Ptr += strlen(Ptr) + 1;
118
119 /* Put a zero after the string */
120 *(DestBuffer++) = 0;
121 }
122
123 /* Set the final zero */
124 *(DestBuffer++) = 0;
125
126 /* Copy the program name after the environment block */
127 strcpy(DestBuffer, ProgramName);
128
129 return DestSegment;
130 }
131
132 static VOID DosChangeMemoryOwner(WORD Segment, WORD NewOwner)
133 {
134 PDOS_MCB Mcb = SEGMENT_TO_MCB(Segment - 1);
135
136 /* Just set the owner */
137 Mcb->OwnerPsp = NewOwner;
138 }
139
140 static WORD DosOpenHandle(HANDLE Handle)
141 {
142 BYTE i;
143 WORD DosHandle;
144 PDOS_PSP PspBlock;
145 LPBYTE HandleTable;
146
147 /* The system PSP has no handle table */
148 if (CurrentPsp == SYSTEM_PSP) return INVALID_DOS_HANDLE;
149
150 /* Get a pointer to the handle table */
151 PspBlock = SEGMENT_TO_PSP(CurrentPsp);
152 HandleTable = (LPBYTE)FAR_POINTER(PspBlock->HandleTablePtr);
153
154 /* Find a free entry in the JFT */
155 for (DosHandle = 0; DosHandle < PspBlock->HandleTableSize; DosHandle++)
156 {
157 if (HandleTable[DosHandle] == 0xFF) break;
158 }
159
160 /* If there are no free entries, fail */
161 if (DosHandle == PspBlock->HandleTableSize) return INVALID_DOS_HANDLE;
162
163 /* Check if the handle is already in the SFT */
164 for (i = 0; i < DOS_SFT_SIZE; i++)
165 {
166 /* Check if this is the same handle */
167 if (DosSystemFileTable[i] != Handle) continue;
168
169 /* Already in the table, reference it */
170 DosSftRefCount[i]++;
171
172 /* Set the JFT entry to that SFT index */
173 HandleTable[DosHandle] = i;
174
175 /* Return the new handle */
176 return DosHandle;
177 }
178
179 /* Add the handle to the SFT */
180 for (i = 0; i < DOS_SFT_SIZE; i++)
181 {
182 /* Make sure this is an empty table entry */
183 if (DosSystemFileTable[i] != INVALID_HANDLE_VALUE) continue;
184
185 /* Initialize the empty table entry */
186 DosSystemFileTable[i] = Handle;
187 DosSftRefCount[i] = 1;
188
189 /* Set the JFT entry to that SFT index */
190 HandleTable[DosHandle] = i;
191
192 /* Return the new handle */
193 return DosHandle;
194 }
195
196 /* The SFT is full */
197 return INVALID_DOS_HANDLE;
198 }
199
200 static HANDLE DosGetRealHandle(WORD DosHandle)
201 {
202 PDOS_PSP PspBlock;
203 LPBYTE HandleTable;
204
205 /* The system PSP has no handle table */
206 if (CurrentPsp == SYSTEM_PSP) return INVALID_HANDLE_VALUE;
207
208 /* Get a pointer to the handle table */
209 PspBlock = SEGMENT_TO_PSP(CurrentPsp);
210 HandleTable = (LPBYTE)FAR_POINTER(PspBlock->HandleTablePtr);
211
212 /* Make sure the handle is open */
213 if (HandleTable[DosHandle] == 0xFF) return INVALID_HANDLE_VALUE;
214
215 /* Return the Win32 handle */
216 return DosSystemFileTable[HandleTable[DosHandle]];
217 }
218
219 static VOID DosCopyHandleTable(LPBYTE DestinationTable)
220 {
221 INT i;
222 PDOS_PSP PspBlock;
223 LPBYTE SourceTable;
224
225 /* Clear the table first */
226 for (i = 0; i < 20; i++) DestinationTable[i] = 0xFF;
227
228 /* Check if this is the initial process */
229 if (CurrentPsp == SYSTEM_PSP)
230 {
231 /* Set up the standard I/O devices */
232 for (i = 0; i <= 2; i++)
233 {
234 /* Set the index in the SFT */
235 DestinationTable[i] = (BYTE)i;
236
237 /* Increase the reference count */
238 DosSftRefCount[i]++;
239 }
240
241 /* Done */
242 return;
243 }
244
245 /* Get the parent PSP block and handle table */
246 PspBlock = SEGMENT_TO_PSP(CurrentPsp);
247 SourceTable = (LPBYTE)FAR_POINTER(PspBlock->HandleTablePtr);
248
249 /* Copy the first 20 handles into the new table */
250 for (i = 0; i < 20; i++)
251 {
252 DestinationTable[i] = SourceTable[i];
253
254 /* Increase the reference count */
255 DosSftRefCount[SourceTable[i]]++;
256 }
257 }
258
259 /* PUBLIC FUNCTIONS ***********************************************************/
260
261 WORD DosAllocateMemory(WORD Size, WORD *MaxAvailable)
262 {
263 WORD Result = 0, Segment = FIRST_MCB_SEGMENT, MaxSize = 0;
264 PDOS_MCB CurrentMcb, NextMcb;
265 BOOLEAN SearchUmb = FALSE;
266
267 DPRINT("DosAllocateMemory: Size 0x%04X\n", Size);
268
269 if (DosUmbLinked && (DosAllocStrategy & (DOS_ALLOC_HIGH | DOS_ALLOC_HIGH_LOW)))
270 {
271 /* Search UMB first */
272 Segment = UMB_START_SEGMENT;
273 SearchUmb = TRUE;
274 }
275
276 while (TRUE)
277 {
278 /* Get a pointer to the MCB */
279 CurrentMcb = SEGMENT_TO_MCB(Segment);
280
281 /* Make sure it's valid */
282 if (CurrentMcb->BlockType != 'M' && CurrentMcb->BlockType != 'Z')
283 {
284 DPRINT("The DOS memory arena is corrupted!\n");
285 DosLastError = ERROR_ARENA_TRASHED;
286 return 0;
287 }
288
289 /* Only check free blocks */
290 if (CurrentMcb->OwnerPsp != 0) goto Next;
291
292 /* Combine this free block with adjoining free blocks */
293 DosCombineFreeBlocks(Segment);
294
295 /* Update the maximum block size */
296 if (CurrentMcb->Size > MaxSize) MaxSize = CurrentMcb->Size;
297
298 /* Check if this block is big enough */
299 if (CurrentMcb->Size < Size) goto Next;
300
301 switch (DosAllocStrategy & 0x3F)
302 {
303 case DOS_ALLOC_FIRST_FIT:
304 {
305 /* For first fit, stop immediately */
306 Result = Segment;
307 goto Done;
308 }
309
310 case DOS_ALLOC_BEST_FIT:
311 {
312 /* For best fit, update the smallest block found so far */
313 if ((Result == 0) || (CurrentMcb->Size < SEGMENT_TO_MCB(Result)->Size))
314 {
315 Result = Segment;
316 }
317
318 break;
319 }
320
321 case DOS_ALLOC_LAST_FIT:
322 {
323 /* For last fit, make the current block the result, but keep searching */
324 Result = Segment;
325 break;
326 }
327 }
328
329 Next:
330 /* If this was the last MCB in the chain, quit */
331 if (CurrentMcb->BlockType == 'Z')
332 {
333 /* Check if nothing was found while searching through UMBs */
334 if ((Result == 0) && SearchUmb && (DosAllocStrategy & DOS_ALLOC_HIGH_LOW))
335 {
336 /* Search low memory */
337 Segment = FIRST_MCB_SEGMENT;
338 continue;
339 }
340
341 break;
342 }
343
344 /* Otherwise, update the segment and continue */
345 Segment += CurrentMcb->Size + 1;
346 }
347
348 Done:
349
350 /* If we didn't find a free block, return 0 */
351 if (Result == 0)
352 {
353 DosLastError = ERROR_NOT_ENOUGH_MEMORY;
354 if (MaxAvailable) *MaxAvailable = MaxSize;
355 return 0;
356 }
357
358 /* Get a pointer to the MCB */
359 CurrentMcb = SEGMENT_TO_MCB(Result);
360
361 /* Check if the block is larger than requested */
362 if (CurrentMcb->Size > Size)
363 {
364 /* It is, split it into two blocks */
365 NextMcb = SEGMENT_TO_MCB(Result + Size + 1);
366
367 /* Initialize the new MCB structure */
368 NextMcb->BlockType = CurrentMcb->BlockType;
369 NextMcb->Size = CurrentMcb->Size - Size - 1;
370 NextMcb->OwnerPsp = 0;
371
372 /* Update the current block */
373 CurrentMcb->BlockType = 'M';
374 CurrentMcb->Size = Size;
375 }
376
377 /* Take ownership of the block */
378 CurrentMcb->OwnerPsp = CurrentPsp;
379
380 /* Return the segment of the data portion of the block */
381 return Result + 1;
382 }
383
384 BOOLEAN DosResizeMemory(WORD BlockData, WORD NewSize, WORD *MaxAvailable)
385 {
386 BOOLEAN Success = TRUE;
387 WORD Segment = BlockData - 1, ReturnSize = 0, NextSegment;
388 PDOS_MCB Mcb = SEGMENT_TO_MCB(Segment), NextMcb;
389
390 DPRINT("DosResizeMemory: BlockData 0x%04X, NewSize 0x%04X\n",
391 BlockData,
392 NewSize);
393
394 /* Make sure this is a valid, allocated block */
395 if ((Mcb->BlockType != 'M' && Mcb->BlockType != 'Z') || Mcb->OwnerPsp == 0)
396 {
397 Success = FALSE;
398 DosLastError = ERROR_INVALID_HANDLE;
399 goto Done;
400 }
401
402 ReturnSize = Mcb->Size;
403
404 /* Check if we need to expand or contract the block */
405 if (NewSize > Mcb->Size)
406 {
407 /* We can't expand the last block */
408 if (Mcb->BlockType != 'M')
409 {
410 Success = FALSE;
411 goto Done;
412 }
413
414 /* Get the pointer and segment of the next MCB */
415 NextSegment = Segment + Mcb->Size + 1;
416 NextMcb = SEGMENT_TO_MCB(NextSegment);
417
418 /* Make sure the next segment is free */
419 if (NextMcb->OwnerPsp != 0)
420 {
421 DPRINT("Cannot expand memory block: next segment is not free!\n");
422 DosLastError = ERROR_NOT_ENOUGH_MEMORY;
423 Success = FALSE;
424 goto Done;
425 }
426
427 /* Combine this free block with adjoining free blocks */
428 DosCombineFreeBlocks(NextSegment);
429
430 /* Set the maximum possible size of the block */
431 ReturnSize += NextMcb->Size + 1;
432
433 /* Maximize the current block */
434 Mcb->Size = ReturnSize;
435 Mcb->BlockType = NextMcb->BlockType;
436
437 /* Invalidate the next block */
438 NextMcb->BlockType = 'I';
439
440 /* Check if the block is larger than requested */
441 if (Mcb->Size > NewSize)
442 {
443 DPRINT("Block too large, reducing size from 0x%04X to 0x%04X\n",
444 Mcb->Size,
445 NewSize);
446
447 /* It is, split it into two blocks */
448 NextMcb = SEGMENT_TO_MCB(Segment + NewSize + 1);
449
450 /* Initialize the new MCB structure */
451 NextMcb->BlockType = Mcb->BlockType;
452 NextMcb->Size = Mcb->Size - NewSize - 1;
453 NextMcb->OwnerPsp = 0;
454
455 /* Update the current block */
456 Mcb->BlockType = 'M';
457 Mcb->Size = NewSize;
458 }
459 }
460 else if (NewSize < Mcb->Size)
461 {
462 DPRINT("Shrinking block from 0x%04X to 0x%04X\n",
463 Mcb->Size,
464 NewSize);
465
466 /* Just split the block */
467 NextMcb = SEGMENT_TO_MCB(Segment + NewSize + 1);
468 NextMcb->BlockType = Mcb->BlockType;
469 NextMcb->Size = Mcb->Size - NewSize - 1;
470 NextMcb->OwnerPsp = 0;
471
472 /* Update the MCB */
473 Mcb->BlockType = 'M';
474 Mcb->Size = NewSize;
475 }
476
477 Done:
478 /* Check if the operation failed */
479 if (!Success)
480 {
481 DPRINT("DosResizeMemory FAILED. Maximum available: 0x%04X\n",
482 ReturnSize);
483
484 /* Return the maximum possible size */
485 if (MaxAvailable) *MaxAvailable = ReturnSize;
486 }
487
488 return Success;
489 }
490
491 BOOLEAN DosFreeMemory(WORD BlockData)
492 {
493 PDOS_MCB Mcb = SEGMENT_TO_MCB(BlockData - 1);
494
495 DPRINT("DosFreeMemory: BlockData 0x%04X\n", BlockData);
496
497 /* Make sure the MCB is valid */
498 if (Mcb->BlockType != 'M' && Mcb->BlockType != 'Z')
499 {
500 DPRINT("MCB block type '%c' not valid!\n", Mcb->BlockType);
501 return FALSE;
502 }
503
504 /* Mark the block as free */
505 Mcb->OwnerPsp = 0;
506
507 return TRUE;
508 }
509
510 BOOLEAN DosLinkUmb(VOID)
511 {
512 DWORD Segment = FIRST_MCB_SEGMENT;
513 PDOS_MCB Mcb = SEGMENT_TO_MCB(Segment);
514
515 DPRINT("Linking UMB\n");
516
517 /* Check if UMBs are already linked */
518 if (DosUmbLinked) return FALSE;
519
520 /* Find the last block */
521 while ((Mcb->BlockType == 'M') && (Segment <= 0xFFFF))
522 {
523 Segment += Mcb->Size + 1;
524 Mcb = SEGMENT_TO_MCB(Segment);
525 }
526
527 /* Make sure it's valid */
528 if (Mcb->BlockType != 'Z') return FALSE;
529
530 /* Connect the MCB with the UMB chain */
531 Mcb->BlockType = 'M';
532
533 DosUmbLinked = TRUE;
534 return TRUE;
535 }
536
537 BOOLEAN DosUnlinkUmb(VOID)
538 {
539 DWORD Segment = FIRST_MCB_SEGMENT;
540 PDOS_MCB Mcb = SEGMENT_TO_MCB(Segment);
541
542 DPRINT("Unlinking UMB\n");
543
544 /* Check if UMBs are already unlinked */
545 if (!DosUmbLinked) return FALSE;
546
547 /* Find the block preceding the MCB that links it with the UMB chain */
548 while (Segment <= 0xFFFF)
549 {
550 if ((Segment + Mcb->Size) == (FIRST_MCB_SEGMENT + USER_MEMORY_SIZE))
551 {
552 /* This is the last non-UMB segment */
553 break;
554 }
555
556 /* Advance to the next MCB */
557 Segment += Mcb->Size + 1;
558 Mcb = SEGMENT_TO_MCB(Segment);
559 }
560
561 /* Mark the MCB as the last MCB */
562 Mcb->BlockType = 'Z';
563
564 DosUmbLinked = FALSE;
565 return TRUE;
566 }
567
568 WORD DosCreateFile(LPWORD Handle, LPCSTR FilePath, WORD Attributes)
569 {
570 HANDLE FileHandle;
571 WORD DosHandle;
572
573 DPRINT("DosCreateFile: FilePath \"%s\", Attributes 0x%04X\n",
574 FilePath,
575 Attributes);
576
577 /* Create the file */
578 FileHandle = CreateFileA(FilePath,
579 GENERIC_READ | GENERIC_WRITE,
580 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
581 NULL,
582 CREATE_ALWAYS,
583 Attributes,
584 NULL);
585
586 if (FileHandle == INVALID_HANDLE_VALUE)
587 {
588 /* Return the error code */
589 return (WORD)GetLastError();
590 }
591
592 /* Open the DOS handle */
593 DosHandle = DosOpenHandle(FileHandle);
594
595 if (DosHandle == INVALID_DOS_HANDLE)
596 {
597 /* Close the handle */
598 CloseHandle(FileHandle);
599
600 /* Return the error code */
601 return ERROR_TOO_MANY_OPEN_FILES;
602 }
603
604 /* It was successful */
605 *Handle = DosHandle;
606 return ERROR_SUCCESS;
607 }
608
609 WORD DosOpenFile(LPWORD Handle, LPCSTR FilePath, BYTE AccessMode)
610 {
611 HANDLE FileHandle;
612 ACCESS_MASK Access = 0;
613 WORD DosHandle;
614
615 DPRINT("DosOpenFile: FilePath \"%s\", AccessMode 0x%04X\n",
616 FilePath,
617 AccessMode);
618
619 /* Parse the access mode */
620 switch (AccessMode & 3)
621 {
622 case 0:
623 {
624 /* Read-only */
625 Access = GENERIC_READ;
626 break;
627 }
628
629 case 1:
630 {
631 /* Write only */
632 Access = GENERIC_WRITE;
633 break;
634 }
635
636 case 2:
637 {
638 /* Read and write */
639 Access = GENERIC_READ | GENERIC_WRITE;
640 break;
641 }
642
643 default:
644 {
645 /* Invalid */
646 return ERROR_INVALID_PARAMETER;
647 }
648 }
649
650 /* Open the file */
651 FileHandle = CreateFileA(FilePath,
652 Access,
653 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
654 NULL,
655 OPEN_EXISTING,
656 FILE_ATTRIBUTE_NORMAL,
657 NULL);
658
659 if (FileHandle == INVALID_HANDLE_VALUE)
660 {
661 /* Return the error code */
662 return (WORD)GetLastError();
663 }
664
665 /* Open the DOS handle */
666 DosHandle = DosOpenHandle(FileHandle);
667
668 if (DosHandle == INVALID_DOS_HANDLE)
669 {
670 /* Close the handle */
671 CloseHandle(FileHandle);
672
673 /* Return the error code */
674 return ERROR_TOO_MANY_OPEN_FILES;
675 }
676
677 /* It was successful */
678 *Handle = DosHandle;
679 return ERROR_SUCCESS;
680 }
681
682 WORD DosReadFile(WORD FileHandle, LPVOID Buffer, WORD Count, LPWORD BytesRead)
683 {
684 WORD Result = ERROR_SUCCESS;
685 DWORD BytesRead32 = 0;
686 HANDLE Handle = DosGetRealHandle(FileHandle);
687
688 DPRINT("DosReadFile: FileHandle 0x%04X, Count 0x%04X\n", FileHandle, Count);
689
690 /* Make sure the handle is valid */
691 if (Handle == INVALID_HANDLE_VALUE) return ERROR_INVALID_HANDLE;
692
693 /* Read the file */
694 if (!ReadFile(Handle, Buffer, Count, &BytesRead32, NULL))
695 {
696 /* Store the error code */
697 Result = (WORD)GetLastError();
698 }
699
700 /* The number of bytes read is always 16-bit */
701 *BytesRead = LOWORD(BytesRead32);
702
703 /* Return the error code */
704 return Result;
705 }
706
707 WORD DosWriteFile(WORD FileHandle, LPVOID Buffer, WORD Count, LPWORD BytesWritten)
708 {
709 WORD Result = ERROR_SUCCESS;
710 DWORD BytesWritten32 = 0;
711 HANDLE Handle = DosGetRealHandle(FileHandle);
712 WORD i;
713
714 DPRINT("DosWriteFile: FileHandle 0x%04X, Count 0x%04X\n",
715 FileHandle,
716 Count);
717
718 /* Make sure the handle is valid */
719 if (Handle == INVALID_HANDLE_VALUE) return ERROR_INVALID_HANDLE;
720
721 if (IsConsoleHandle(Handle))
722 {
723 for (i = 0; i < Count; i++)
724 {
725 /* Call the BIOS to print the character */
726 BiosPrintCharacter(((LPBYTE)Buffer)[i], DOS_CHAR_ATTRIBUTE, Bda->VideoPage);
727 BytesWritten32++;
728 }
729 }
730 else
731 {
732 /* Write the file */
733 if (!WriteFile(Handle, Buffer, Count, &BytesWritten32, NULL))
734 {
735 /* Store the error code */
736 Result = (WORD)GetLastError();
737 }
738 }
739
740 /* The number of bytes written is always 16-bit */
741 *BytesWritten = LOWORD(BytesWritten32);
742
743 /* Return the error code */
744 return Result;
745 }
746
747 WORD DosSeekFile(WORD FileHandle, LONG Offset, BYTE Origin, LPDWORD NewOffset)
748 {
749 WORD Result = ERROR_SUCCESS;
750 DWORD FilePointer;
751 HANDLE Handle = DosGetRealHandle(FileHandle);
752
753 DPRINT("DosSeekFile: FileHandle 0x%04X, Offset 0x%08X, Origin 0x%02X\n",
754 FileHandle,
755 Offset,
756 Origin);
757
758 /* Make sure the handle is valid */
759 if (Handle == INVALID_HANDLE_VALUE) return ERROR_INVALID_HANDLE;
760
761 /* Check if the origin is valid */
762 if (Origin != FILE_BEGIN && Origin != FILE_CURRENT && Origin != FILE_END)
763 {
764 return ERROR_INVALID_FUNCTION;
765 }
766
767 /* Move the file pointer */
768 FilePointer = SetFilePointer(Handle, Offset, NULL, Origin);
769
770 /* Check if there's a possibility the operation failed */
771 if (FilePointer == INVALID_SET_FILE_POINTER)
772 {
773 /* Get the real error code */
774 Result = (WORD)GetLastError();
775 }
776
777 if (Result != ERROR_SUCCESS)
778 {
779 /* The operation did fail */
780 return Result;
781 }
782
783 /* Return the file pointer, if requested */
784 if (NewOffset) *NewOffset = FilePointer;
785
786 /* Return success */
787 return ERROR_SUCCESS;
788 }
789
790 BOOLEAN DosDuplicateHandle(WORD OldHandle, WORD NewHandle)
791 {
792 BYTE SftIndex;
793 PDOS_PSP PspBlock;
794 LPBYTE HandleTable;
795
796 DPRINT("DosDuplicateHandle: OldHandle 0x%04X, NewHandle 0x%04X\n",
797 OldHandle,
798 NewHandle);
799
800 /* The system PSP has no handle table */
801 if (CurrentPsp == SYSTEM_PSP) return FALSE;
802
803 /* Get a pointer to the handle table */
804 PspBlock = SEGMENT_TO_PSP(CurrentPsp);
805 HandleTable = (LPBYTE)FAR_POINTER(PspBlock->HandleTablePtr);
806
807 /* Make sure the old handle is open */
808 if (HandleTable[OldHandle] == 0xFF) return FALSE;
809
810 /* Check if the new handle is open */
811 if (HandleTable[NewHandle] != 0xFF)
812 {
813 /* Close it */
814 DosCloseHandle(NewHandle);
815 }
816
817 /* Increment the reference count of the SFT entry */
818 SftIndex = HandleTable[OldHandle];
819 DosSftRefCount[SftIndex]++;
820
821 /* Make the new handle point to that SFT entry */
822 HandleTable[NewHandle] = SftIndex;
823
824 /* Return success */
825 return TRUE;
826 }
827
828 BOOLEAN DosCloseHandle(WORD DosHandle)
829 {
830 BYTE SftIndex;
831 PDOS_PSP PspBlock;
832 LPBYTE HandleTable;
833
834 DPRINT("DosCloseHandle: DosHandle 0x%04X\n", DosHandle);
835
836 /* The system PSP has no handle table */
837 if (CurrentPsp == SYSTEM_PSP) return FALSE;
838
839 /* Get a pointer to the handle table */
840 PspBlock = SEGMENT_TO_PSP(CurrentPsp);
841 HandleTable = (LPBYTE)FAR_POINTER(PspBlock->HandleTablePtr);
842
843 /* Make sure the handle is open */
844 if (HandleTable[DosHandle] == 0xFF) return FALSE;
845
846 /* Decrement the reference count of the SFT entry */
847 SftIndex = HandleTable[DosHandle];
848 DosSftRefCount[SftIndex]--;
849
850 /* Check if the reference count fell to zero */
851 if (!DosSftRefCount[SftIndex])
852 {
853 /* Close the file, it's no longer needed */
854 CloseHandle(DosSystemFileTable[SftIndex]);
855
856 /* Clear the handle */
857 DosSystemFileTable[SftIndex] = INVALID_HANDLE_VALUE;
858 }
859
860 /* Clear the entry in the JFT */
861 HandleTable[DosHandle] = 0xFF;
862
863 return TRUE;
864 }
865
866 BOOLEAN DosChangeDrive(BYTE Drive)
867 {
868 WCHAR DirectoryPath[DOS_CMDLINE_LENGTH];
869
870 /* Make sure the drive exists */
871 if (Drive > (LastDrive - 'A')) return FALSE;
872
873 /* Find the path to the new current directory */
874 swprintf(DirectoryPath, L"%c\\%S", Drive + 'A', CurrentDirectories[Drive]);
875
876 /* Change the current directory of the process */
877 if (!SetCurrentDirectory(DirectoryPath)) return FALSE;
878
879 /* Set the current drive */
880 CurrentDrive = Drive;
881
882 /* Return success */
883 return TRUE;
884 }
885
886 BOOLEAN DosChangeDirectory(LPSTR Directory)
887 {
888 BYTE DriveNumber;
889 DWORD Attributes;
890 LPSTR Path;
891
892 /* Make sure the directory path is not too long */
893 if (strlen(Directory) >= DOS_DIR_LENGTH)
894 {
895 DosLastError = ERROR_PATH_NOT_FOUND;
896 return FALSE;
897 }
898
899 /* Get the drive number */
900 DriveNumber = Directory[0] - 'A';
901
902 /* Make sure the drive exists */
903 if (DriveNumber > (LastDrive - 'A'))
904 {
905 DosLastError = ERROR_PATH_NOT_FOUND;
906 return FALSE;
907 }
908
909 /* Get the file attributes */
910 Attributes = GetFileAttributesA(Directory);
911
912 /* Make sure the path exists and is a directory */
913 if ((Attributes == INVALID_FILE_ATTRIBUTES)
914 || !(Attributes & FILE_ATTRIBUTE_DIRECTORY))
915 {
916 DosLastError = ERROR_PATH_NOT_FOUND;
917 return FALSE;
918 }
919
920 /* Check if this is the current drive */
921 if (DriveNumber == CurrentDrive)
922 {
923 /* Change the directory */
924 if (!SetCurrentDirectoryA(Directory))
925 {
926 DosLastError = LOWORD(GetLastError());
927 return FALSE;
928 }
929 }
930
931 /* Get the directory part of the path */
932 Path = strchr(Directory, '\\');
933 if (Path != NULL)
934 {
935 /* Skip the backslash */
936 Path++;
937 }
938
939 /* Set the directory for the drive */
940 if (Path != NULL) strcpy(CurrentDirectories[DriveNumber], Path);
941 else strcpy(CurrentDirectories[DriveNumber], "");
942
943 /* Return success */
944 return TRUE;
945 }
946
947 VOID DosInitializePsp(WORD PspSegment, LPCSTR CommandLine, WORD ProgramSize, WORD Environment)
948 {
949 PDOS_PSP PspBlock = SEGMENT_TO_PSP(PspSegment);
950 LPDWORD IntVecTable = (LPDWORD)((ULONG_PTR)BaseAddress);
951
952 ZeroMemory(PspBlock, sizeof(DOS_PSP));
953
954 /* Set the exit interrupt */
955 PspBlock->Exit[0] = 0xCD; // int 0x20
956 PspBlock->Exit[1] = 0x20;
957
958 /* Set the number of the last paragraph */
959 PspBlock->LastParagraph = PspSegment + ProgramSize - 1;
960
961 /* Save the interrupt vectors */
962 PspBlock->TerminateAddress = IntVecTable[0x22];
963 PspBlock->BreakAddress = IntVecTable[0x23];
964 PspBlock->CriticalAddress = IntVecTable[0x24];
965
966 /* Set the parent PSP */
967 PspBlock->ParentPsp = CurrentPsp;
968
969 /* Copy the parent handle table */
970 DosCopyHandleTable(PspBlock->HandleTable);
971
972 /* Set the environment block */
973 PspBlock->EnvBlock = Environment;
974
975 /* Set the handle table pointers to the internal handle table */
976 PspBlock->HandleTableSize = 20;
977 PspBlock->HandleTablePtr = MAKELONG(0x18, PspSegment);
978
979 /* Set the DOS version */
980 PspBlock->DosVersion = DOS_VERSION;
981
982 /* Set the far call opcodes */
983 PspBlock->FarCall[0] = 0xCD; // int 0x21
984 PspBlock->FarCall[1] = 0x21;
985 PspBlock->FarCall[2] = 0xCB; // retf
986
987 /* Set the command line */
988 PspBlock->CommandLineSize = (BYTE)min(strlen(CommandLine), DOS_CMDLINE_LENGTH - 1);
989 RtlCopyMemory(PspBlock->CommandLine, CommandLine, PspBlock->CommandLineSize);
990 PspBlock->CommandLine[PspBlock->CommandLineSize] = '\r';
991 }
992
993 BOOLEAN DosCreateProcess(LPCSTR CommandLine, WORD EnvBlock)
994 {
995 BOOLEAN Success = FALSE, AllocatedEnvBlock = FALSE;
996 HANDLE FileHandle = INVALID_HANDLE_VALUE, FileMapping = NULL;
997 LPBYTE Address = NULL;
998 LPSTR ProgramFilePath, Parameters[256];
999 CHAR CommandLineCopy[DOS_CMDLINE_LENGTH];
1000 INT ParamCount = 0;
1001 WORD Segment = 0;
1002 WORD MaxAllocSize;
1003 DWORD i, FileSize, ExeSize;
1004 PIMAGE_DOS_HEADER Header;
1005 PDWORD RelocationTable;
1006 PWORD RelocWord;
1007
1008 DPRINT("DosCreateProcess: CommandLine \"%s\", EnvBlock 0x%04X\n",
1009 CommandLine,
1010 EnvBlock);
1011
1012 /* Save a copy of the command line */
1013 strcpy(CommandLineCopy, CommandLine);
1014
1015 // FIXME: Improve parsing (especially: "some_path\with spaces\program.exe" options)
1016
1017 /* Get the file name of the executable */
1018 ProgramFilePath = strtok(CommandLineCopy, " \t");
1019
1020 /* Load the parameters in the local array */
1021 while ((ParamCount < sizeof(Parameters)/sizeof(Parameters[0]))
1022 && ((Parameters[ParamCount] = strtok(NULL, " \t")) != NULL))
1023 {
1024 ParamCount++;
1025 }
1026
1027 /* Open a handle to the executable */
1028 FileHandle = CreateFileA(ProgramFilePath,
1029 GENERIC_READ,
1030 0,
1031 NULL,
1032 OPEN_EXISTING,
1033 FILE_ATTRIBUTE_NORMAL,
1034 NULL);
1035 if (FileHandle == INVALID_HANDLE_VALUE) goto Cleanup;
1036
1037 /* Get the file size */
1038 FileSize = GetFileSize(FileHandle, NULL);
1039
1040 /* Create a mapping object for the file */
1041 FileMapping = CreateFileMapping(FileHandle,
1042 NULL,
1043 PAGE_READONLY,
1044 0,
1045 0,
1046 NULL);
1047 if (FileMapping == NULL) goto Cleanup;
1048
1049 /* Map the file into memory */
1050 Address = (LPBYTE)MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 0);
1051 if (Address == NULL) goto Cleanup;
1052
1053 /* Did we get an environment segment? */
1054 if (!EnvBlock)
1055 {
1056 /* Set a flag to know if the environment block was allocated here */
1057 AllocatedEnvBlock = TRUE;
1058
1059 /* No, copy the one from the parent */
1060 EnvBlock = DosCopyEnvironmentBlock((CurrentPsp != SYSTEM_PSP)
1061 ? SEGMENT_TO_PSP(CurrentPsp)->EnvBlock
1062 : SYSTEM_ENV_BLOCK,
1063 ProgramFilePath);
1064 }
1065
1066 /* Check if this is an EXE file or a COM file */
1067 if (Address[0] == 'M' && Address[1] == 'Z')
1068 {
1069 /* EXE file */
1070
1071 /* Get the MZ header */
1072 Header = (PIMAGE_DOS_HEADER)Address;
1073
1074 /* Get the base size of the file, in paragraphs (rounded up) */
1075 ExeSize = (((Header->e_cp - 1) * 512) + Header->e_cblp + 0x0F) >> 4;
1076
1077 /* Add the PSP size, in paragraphs */
1078 ExeSize += sizeof(DOS_PSP) >> 4;
1079
1080 /* Add the maximum size that should be allocated */
1081 ExeSize += Header->e_maxalloc;
1082
1083 /* Make sure it does not pass 0xFFFF */
1084 if (ExeSize > 0xFFFF) ExeSize = 0xFFFF;
1085
1086 /* Reduce the size one by one until the allocation is successful */
1087 for (i = Header->e_maxalloc; i >= Header->e_minalloc; i--, ExeSize--)
1088 {
1089 /* Try to allocate that much memory */
1090 Segment = DosAllocateMemory((WORD)ExeSize, NULL);
1091 if (Segment != 0) break;
1092 }
1093
1094 /* Check if at least the lowest allocation was successful */
1095 if (Segment == 0) goto Cleanup;
1096
1097 /* Initialize the PSP */
1098 DosInitializePsp(Segment,
1099 CommandLine,
1100 (WORD)ExeSize,
1101 EnvBlock);
1102
1103 /* The process owns its own memory */
1104 DosChangeMemoryOwner(Segment, Segment);
1105 DosChangeMemoryOwner(EnvBlock, Segment);
1106
1107 /* Copy the program to Segment:0100 */
1108 RtlCopyMemory((PVOID)((ULONG_PTR)BaseAddress
1109 + TO_LINEAR(Segment, 0x100)),
1110 Address + (Header->e_cparhdr << 4),
1111 min(FileSize - (Header->e_cparhdr << 4),
1112 (ExeSize << 4) - sizeof(DOS_PSP)));
1113
1114 /* Get the relocation table */
1115 RelocationTable = (PDWORD)(Address + Header->e_lfarlc);
1116
1117 /* Perform relocations */
1118 for (i = 0; i < Header->e_crlc; i++)
1119 {
1120 /* Get a pointer to the word that needs to be patched */
1121 RelocWord = (PWORD)((ULONG_PTR)BaseAddress
1122 + TO_LINEAR(Segment + HIWORD(RelocationTable[i]),
1123 0x100 + LOWORD(RelocationTable[i])));
1124
1125 /* Add the number of the EXE segment to it */
1126 *RelocWord += Segment + (sizeof(DOS_PSP) >> 4);
1127 }
1128
1129 /* Set the initial segment registers */
1130 EmulatorSetRegister(EMULATOR_REG_DS, Segment);
1131 EmulatorSetRegister(EMULATOR_REG_ES, Segment);
1132
1133 /* Set the stack to the location from the header */
1134 EmulatorSetStack(Segment + (sizeof(DOS_PSP) >> 4) + Header->e_ss,
1135 Header->e_sp);
1136
1137 /* Execute */
1138 CurrentPsp = Segment;
1139 DiskTransferArea = MAKELONG(0x80, Segment);
1140 EmulatorExecute(Segment + Header->e_cs + (sizeof(DOS_PSP) >> 4),
1141 Header->e_ip);
1142
1143 Success = TRUE;
1144 }
1145 else
1146 {
1147 /* COM file */
1148
1149 /* Find the maximum amount of memory that can be allocated */
1150 DosAllocateMemory(0xFFFF, &MaxAllocSize);
1151
1152 /* Make sure it's enough for the whole program and the PSP */
1153 if (((DWORD)MaxAllocSize << 4) < (FileSize + sizeof(DOS_PSP))) goto Cleanup;
1154
1155 /* Allocate all of it */
1156 Segment = DosAllocateMemory(MaxAllocSize, NULL);
1157 if (Segment == 0) goto Cleanup;
1158
1159 /* The process owns its own memory */
1160 DosChangeMemoryOwner(Segment, Segment);
1161 DosChangeMemoryOwner(EnvBlock, Segment);
1162
1163 /* Copy the program to Segment:0100 */
1164 RtlCopyMemory((PVOID)((ULONG_PTR)BaseAddress
1165 + TO_LINEAR(Segment, 0x100)),
1166 Address,
1167 FileSize);
1168
1169 /* Initialize the PSP */
1170 DosInitializePsp(Segment,
1171 CommandLine,
1172 (WORD)((FileSize + sizeof(DOS_PSP)) >> 4),
1173 EnvBlock);
1174
1175 /* Set the initial segment registers */
1176 EmulatorSetRegister(EMULATOR_REG_DS, Segment);
1177 EmulatorSetRegister(EMULATOR_REG_ES, Segment);
1178
1179 /* Set the stack to the last word of the segment */
1180 EmulatorSetStack(Segment, 0xFFFE);
1181
1182 /* Execute */
1183 CurrentPsp = Segment;
1184 DiskTransferArea = MAKELONG(0x80, Segment);
1185 EmulatorExecute(Segment, 0x100);
1186
1187 Success = TRUE;
1188 }
1189
1190 Cleanup:
1191 if (!Success)
1192 {
1193 /* It was not successful, cleanup the DOS memory */
1194 if (AllocatedEnvBlock) DosFreeMemory(EnvBlock);
1195 if (Segment) DosFreeMemory(Segment);
1196 }
1197
1198 /* Unmap the file*/
1199 if (Address != NULL) UnmapViewOfFile(Address);
1200
1201 /* Close the file mapping object */
1202 if (FileMapping != NULL) CloseHandle(FileMapping);
1203
1204 /* Close the file handle */
1205 if (FileHandle != INVALID_HANDLE_VALUE) CloseHandle(FileHandle);
1206
1207 return Success;
1208 }
1209
1210 VOID DosTerminateProcess(WORD Psp, BYTE ReturnCode)
1211 {
1212 WORD i;
1213 WORD McbSegment = FIRST_MCB_SEGMENT;
1214 PDOS_MCB CurrentMcb;
1215 LPDWORD IntVecTable = (LPDWORD)((ULONG_PTR)BaseAddress);
1216 PDOS_PSP PspBlock = SEGMENT_TO_PSP(Psp);
1217
1218 DPRINT("DosTerminateProcess: Psp 0x%04X, ReturnCode 0x%02X\n",
1219 Psp,
1220 ReturnCode);
1221
1222 /* Check if this PSP is it's own parent */
1223 if (PspBlock->ParentPsp == Psp) goto Done;
1224
1225 for (i = 0; i < PspBlock->HandleTableSize; i++)
1226 {
1227 /* Close the handle */
1228 DosCloseHandle(i);
1229 }
1230
1231 /* Free the memory used by the process */
1232 while (TRUE)
1233 {
1234 /* Get a pointer to the MCB */
1235 CurrentMcb = SEGMENT_TO_MCB(McbSegment);
1236
1237 /* Make sure the MCB is valid */
1238 if (CurrentMcb->BlockType != 'M' && CurrentMcb->BlockType !='Z') break;
1239
1240 /* If this block was allocated by the process, free it */
1241 if (CurrentMcb->OwnerPsp == Psp) DosFreeMemory(McbSegment + 1);
1242
1243 /* If this was the last block, quit */
1244 if (CurrentMcb->BlockType == 'Z') break;
1245
1246 /* Update the segment and continue */
1247 McbSegment += CurrentMcb->Size + 1;
1248 }
1249
1250 Done:
1251 /* Restore the interrupt vectors */
1252 IntVecTable[0x22] = PspBlock->TerminateAddress;
1253 IntVecTable[0x23] = PspBlock->BreakAddress;
1254 IntVecTable[0x24] = PspBlock->CriticalAddress;
1255
1256 /* Update the current PSP */
1257 if (Psp == CurrentPsp)
1258 {
1259 CurrentPsp = PspBlock->ParentPsp;
1260 if (CurrentPsp == SYSTEM_PSP) VdmRunning = FALSE;
1261 }
1262
1263 /* Return control to the parent process */
1264 EmulatorExecute(HIWORD(PspBlock->TerminateAddress),
1265 LOWORD(PspBlock->TerminateAddress));
1266 }
1267
1268 CHAR DosReadCharacter(VOID)
1269 {
1270 CHAR Character = '\0';
1271 WORD BytesRead;
1272
1273 if (IsConsoleHandle(DosGetRealHandle(DOS_INPUT_HANDLE)))
1274 {
1275 /* Call the BIOS */
1276 Character = LOBYTE(BiosGetCharacter());
1277 }
1278 else
1279 {
1280 /* Use the file reading function */
1281 DosReadFile(DOS_INPUT_HANDLE, &Character, sizeof(CHAR), &BytesRead);
1282 }
1283
1284 return Character;
1285 }
1286
1287 VOID DosPrintCharacter(CHAR Character)
1288 {
1289 WORD BytesWritten;
1290
1291 /* Use the file writing function */
1292 DosWriteFile(DOS_OUTPUT_HANDLE, &Character, sizeof(CHAR), &BytesWritten);
1293 }
1294
1295 BOOLEAN DosHandleIoctl(BYTE ControlCode, WORD FileHandle)
1296 {
1297 HANDLE Handle = DosGetRealHandle(FileHandle);
1298
1299 if (Handle == INVALID_HANDLE_VALUE)
1300 {
1301 /* Doesn't exist */
1302 DosLastError = ERROR_FILE_NOT_FOUND;
1303 return FALSE;
1304 }
1305
1306 switch (ControlCode)
1307 {
1308 /* Get Device Information */
1309 case 0x00:
1310 {
1311 WORD InfoWord = 0;
1312
1313 if (Handle == DosSystemFileTable[0])
1314 {
1315 /* Console input */
1316 InfoWord |= 1 << 0;
1317 }
1318 else if (Handle == DosSystemFileTable[1])
1319 {
1320 /* Console output */
1321 InfoWord |= 1 << 1;
1322 }
1323
1324 /* It is a character device */
1325 InfoWord |= 1 << 7;
1326
1327 /* Return the device information word */
1328 EmulatorSetRegister(EMULATOR_REG_DX, InfoWord);
1329
1330 return TRUE;
1331 }
1332
1333 /* Unsupported control code */
1334 default:
1335 {
1336 DPRINT1("Unsupported IOCTL: 0x%02X\n", ControlCode);
1337
1338 DosLastError = ERROR_INVALID_PARAMETER;
1339 return FALSE;
1340 }
1341 }
1342 }
1343
1344 VOID DosInt20h(LPWORD Stack)
1345 {
1346 /* This is the exit interrupt */
1347 DosTerminateProcess(Stack[STACK_CS], 0);
1348 }
1349
1350 VOID DosInt21h(LPWORD Stack)
1351 {
1352 INT i;
1353 CHAR Character;
1354 SYSTEMTIME SystemTime;
1355 PCHAR String;
1356 PDOS_INPUT_BUFFER InputBuffer;
1357 DWORD Eax = EmulatorGetRegister(EMULATOR_REG_AX);
1358 DWORD Ecx = EmulatorGetRegister(EMULATOR_REG_CX);
1359 DWORD Edx = EmulatorGetRegister(EMULATOR_REG_DX);
1360 DWORD Ebx = EmulatorGetRegister(EMULATOR_REG_BX);
1361 WORD DataSegment = (WORD)EmulatorGetRegister(EMULATOR_REG_DS);
1362 WORD ExtSegment = (WORD)EmulatorGetRegister(EMULATOR_REG_ES);
1363
1364 /* Check the value in the AH register */
1365 switch (HIBYTE(Eax))
1366 {
1367 /* Terminate Program */
1368 case 0x00:
1369 {
1370 DosTerminateProcess(Stack[STACK_CS], 0);
1371 break;
1372 }
1373
1374 /* Read Character And Echo */
1375 case 0x01:
1376 {
1377 Character = DosReadCharacter();
1378 DosPrintCharacter(Character);
1379
1380 if (!EmulatorGetFlag(EMULATOR_FLAG_CF))
1381 {
1382 EmulatorSetRegister(EMULATOR_REG_AX, (Eax & 0xFFFFFF00) | Character);
1383 }
1384
1385 break;
1386 }
1387
1388 /* Print Character */
1389 case 0x02:
1390 {
1391 DosPrintCharacter(LOBYTE(Edx));
1392 break;
1393 }
1394
1395 /* Read Character Without Echo */
1396 case 0x07:
1397 case 0x08:
1398 {
1399 Character = DosReadCharacter();
1400
1401 if (!EmulatorGetFlag(EMULATOR_FLAG_CF))
1402 {
1403 EmulatorSetRegister(EMULATOR_REG_AX, (Eax & 0xFFFFFF00) | Character);
1404 }
1405
1406 break;
1407 }
1408
1409 /* Print String */
1410 case 0x09:
1411 {
1412 String = (PCHAR)((ULONG_PTR)BaseAddress
1413 + TO_LINEAR(DataSegment, LOWORD(Edx)));
1414
1415 while ((*String) != '$')
1416 {
1417 DosPrintCharacter(*String);
1418 String++;
1419 }
1420
1421 break;
1422 }
1423
1424 /* Read Buffered Input */
1425 case 0x0A:
1426 {
1427 DPRINT1("FIXME: This function is still not adapted to the new system!\n");
1428
1429 InputBuffer = (PDOS_INPUT_BUFFER)((ULONG_PTR)BaseAddress
1430 + TO_LINEAR(DataSegment,
1431 LOWORD(Edx)));
1432
1433 InputBuffer->Length = 0;
1434 for (i = 0; i < InputBuffer->MaxLength; i ++)
1435 {
1436 Character = DosReadCharacter();
1437 DosPrintCharacter(Character);
1438 InputBuffer->Buffer[InputBuffer->Length] = Character;
1439 if (Character == '\r') break;
1440 InputBuffer->Length++;
1441 }
1442
1443 break;
1444 }
1445
1446 /* Set Default Drive */
1447 case 0x0E:
1448 {
1449 DosChangeDrive(LOBYTE(Edx));
1450 EmulatorSetRegister(EMULATOR_REG_AX,
1451 (Eax & 0xFFFFFF00) | (LastDrive - 'A' + 1));
1452
1453 break;
1454 }
1455
1456 /* Get Default Drive */
1457 case 0x19:
1458 {
1459 EmulatorSetRegister(EMULATOR_REG_AX,
1460 (Eax & 0xFFFFFF00) | CurrentDrive);
1461
1462 break;
1463 }
1464
1465 /* Set Disk Transfer Area */
1466 case 0x1A:
1467 {
1468 DiskTransferArea = MAKELONG(LOWORD(Edx), DataSegment);
1469 break;
1470 }
1471
1472 /* Set Interrupt Vector */
1473 case 0x25:
1474 {
1475 DWORD FarPointer = MAKELONG(LOWORD(Edx), DataSegment);
1476
1477 /* Write the new far pointer to the IDT */
1478 ((PDWORD)BaseAddress)[LOBYTE(Eax)] = FarPointer;
1479
1480 break;
1481 }
1482
1483 /* Get system date */
1484 case 0x2A:
1485 {
1486 GetLocalTime(&SystemTime);
1487 EmulatorSetRegister(EMULATOR_REG_CX,
1488 (Ecx & 0xFFFF0000) | SystemTime.wYear);
1489 EmulatorSetRegister(EMULATOR_REG_DX,
1490 (Edx & 0xFFFF0000)
1491 | (SystemTime.wMonth << 8)
1492 | SystemTime.wDay);
1493 EmulatorSetRegister(EMULATOR_REG_AX,
1494 (Eax & 0xFFFFFF00) | SystemTime.wDayOfWeek);
1495 break;
1496 }
1497
1498 /* Set system date */
1499 case 0x2B:
1500 {
1501 GetLocalTime(&SystemTime);
1502 SystemTime.wYear = LOWORD(Ecx);
1503 SystemTime.wMonth = HIBYTE(Edx);
1504 SystemTime.wDay = LOBYTE(Edx);
1505
1506 if (SetLocalTime(&SystemTime))
1507 {
1508 /* Return success */
1509 EmulatorSetRegister(EMULATOR_REG_AX, Eax & 0xFFFFFF00);
1510 }
1511 else
1512 {
1513 /* Return failure */
1514 EmulatorSetRegister(EMULATOR_REG_AX, Eax | 0xFF);
1515 }
1516
1517 break;
1518 }
1519
1520 /* Get system time */
1521 case 0x2C:
1522 {
1523 GetLocalTime(&SystemTime);
1524 EmulatorSetRegister(EMULATOR_REG_CX,
1525 (Ecx & 0xFFFF0000)
1526 | (SystemTime.wHour << 8)
1527 | SystemTime.wMinute);
1528 EmulatorSetRegister(EMULATOR_REG_DX,
1529 (Edx & 0xFFFF0000)
1530 | (SystemTime.wSecond << 8)
1531 | (SystemTime.wMilliseconds / 10));
1532 break;
1533 }
1534
1535 /* Set system time */
1536 case 0x2D:
1537 {
1538 GetLocalTime(&SystemTime);
1539 SystemTime.wHour = HIBYTE(Ecx);
1540 SystemTime.wMinute = LOBYTE(Ecx);
1541 SystemTime.wSecond = HIBYTE(Edx);
1542 SystemTime.wMilliseconds = LOBYTE(Edx) * 10;
1543
1544 if (SetLocalTime(&SystemTime))
1545 {
1546 /* Return success */
1547 EmulatorSetRegister(EMULATOR_REG_AX, Eax & 0xFFFFFF00);
1548 }
1549 else
1550 {
1551 /* Return failure */
1552 EmulatorSetRegister(EMULATOR_REG_AX, Eax | 0xFF);
1553 }
1554
1555 break;
1556 }
1557
1558 /* Get Disk Transfer Area */
1559 case 0x2F:
1560 {
1561 EmulatorSetRegister(EMULATOR_REG_ES, HIWORD(DiskTransferArea));
1562 EmulatorSetRegister(EMULATOR_REG_BX, LOWORD(DiskTransferArea));
1563
1564 break;
1565 }
1566
1567 /* Get DOS Version */
1568 case 0x30:
1569 {
1570 PDOS_PSP PspBlock = SEGMENT_TO_PSP(CurrentPsp);
1571
1572 EmulatorSetRegister(EMULATOR_REG_AX, PspBlock->DosVersion);
1573 break;
1574 }
1575
1576 /* Get Interrupt Vector */
1577 case 0x35:
1578 {
1579 DWORD FarPointer = ((PDWORD)BaseAddress)[LOBYTE(Eax)];
1580
1581 /* Read the address from the IDT into ES:BX */
1582 EmulatorSetRegister(EMULATOR_REG_ES, HIWORD(FarPointer));
1583 EmulatorSetRegister(EMULATOR_REG_BX, LOWORD(FarPointer));
1584
1585 break;
1586 }
1587
1588 /* Create Directory */
1589 case 0x39:
1590 {
1591 String = (PCHAR)((ULONG_PTR)BaseAddress
1592 + TO_LINEAR(DataSegment, LOWORD(Edx)));
1593
1594 if (CreateDirectoryA(String, NULL))
1595 {
1596 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1597 }
1598 else
1599 {
1600 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1601 EmulatorSetRegister(EMULATOR_REG_AX,
1602 (Eax & 0xFFFF0000) | LOWORD(GetLastError()));
1603 }
1604
1605 break;
1606 }
1607
1608 /* Remove Directory */
1609 case 0x3A:
1610 {
1611 String = (PCHAR)((ULONG_PTR)BaseAddress
1612 + TO_LINEAR(DataSegment, LOWORD(Edx)));
1613
1614 if (RemoveDirectoryA(String))
1615 {
1616 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1617 }
1618 else
1619 {
1620 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1621 EmulatorSetRegister(EMULATOR_REG_AX,
1622 (Eax & 0xFFFF0000) | LOWORD(GetLastError()));
1623 }
1624
1625
1626 break;
1627 }
1628
1629 /* Set Current Directory */
1630 case 0x3B:
1631 {
1632 String = (PCHAR)((ULONG_PTR)BaseAddress
1633 + TO_LINEAR(DataSegment, LOWORD(Edx)));
1634
1635 if (DosChangeDirectory(String))
1636 {
1637 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1638 }
1639 else
1640 {
1641 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1642 EmulatorSetRegister(EMULATOR_REG_AX,
1643 (Eax & 0xFFFF0000) | DosLastError);
1644 }
1645
1646 break;
1647 }
1648
1649 /* Create File */
1650 case 0x3C:
1651 {
1652 WORD FileHandle;
1653 WORD ErrorCode = DosCreateFile(&FileHandle,
1654 (LPCSTR)(ULONG_PTR)BaseAddress
1655 + TO_LINEAR(DataSegment, LOWORD(Edx)),
1656 LOWORD(Ecx));
1657
1658 if (ErrorCode == 0)
1659 {
1660 /* Clear CF */
1661 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1662
1663 /* Return the handle in AX */
1664 EmulatorSetRegister(EMULATOR_REG_AX,
1665 (Eax & 0xFFFF0000) | FileHandle);
1666 }
1667 else
1668 {
1669 /* Set CF */
1670 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1671
1672 /* Return the error code in AX */
1673 EmulatorSetRegister(EMULATOR_REG_AX,
1674 (Eax & 0xFFFF0000) | ErrorCode);
1675 }
1676
1677 break;
1678 }
1679
1680 /* Open File */
1681 case 0x3D:
1682 {
1683 WORD FileHandle;
1684 WORD ErrorCode = DosOpenFile(&FileHandle,
1685 (LPCSTR)(ULONG_PTR)BaseAddress
1686 + TO_LINEAR(DataSegment, LOWORD(Edx)),
1687 LOBYTE(Eax));
1688
1689 if (ErrorCode == 0)
1690 {
1691 /* Clear CF */
1692 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1693
1694 /* Return the handle in AX */
1695 EmulatorSetRegister(EMULATOR_REG_AX,
1696 (Eax & 0xFFFF0000) | FileHandle);
1697 }
1698 else
1699 {
1700 /* Set CF */
1701 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1702
1703 /* Return the error code in AX */
1704 EmulatorSetRegister(EMULATOR_REG_AX,
1705 (Eax & 0xFFFF0000) | ErrorCode);
1706 }
1707
1708 break;
1709 }
1710
1711 /* Close File */
1712 case 0x3E:
1713 {
1714 if (DosCloseHandle(LOWORD(Ebx)))
1715 {
1716 /* Clear CF */
1717 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1718 }
1719 else
1720 {
1721 /* Set CF */
1722 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1723
1724 /* Return the error code in AX */
1725 EmulatorSetRegister(EMULATOR_REG_AX,
1726 (Eax & 0xFFFF0000) | ERROR_INVALID_HANDLE);
1727 }
1728
1729 break;
1730 }
1731
1732 /* Read File */
1733 case 0x3F:
1734 {
1735 WORD Handle = LOWORD(Ebx);
1736 LPBYTE Buffer = (LPBYTE)((ULONG_PTR)BaseAddress + TO_LINEAR(DataSegment, LOWORD(Edx)));
1737 WORD Count = LOWORD(Ecx);
1738 WORD BytesRead = 0;
1739 WORD ErrorCode = ERROR_SUCCESS;
1740
1741 if (IsConsoleHandle(DosGetRealHandle(Handle)))
1742 {
1743 while (Stack[STACK_COUNTER] < Count)
1744 {
1745 /* Read a character from the BIOS */
1746 Buffer[Stack[STACK_COUNTER]] = LOBYTE(BiosGetCharacter()); // FIXME: Security checks!
1747
1748 /* Stop if the BOP needs to be repeated */
1749 if (EmulatorGetFlag(EMULATOR_FLAG_CF)) break;
1750
1751 /* Increment the counter */
1752 Stack[STACK_COUNTER]++;
1753 }
1754
1755 if (Stack[STACK_COUNTER] < Count) ErrorCode = ERROR_NOT_READY;
1756 else BytesRead = Count;
1757 }
1758 else
1759 {
1760 /* Use the file reading function */
1761 ErrorCode = DosReadFile(Handle, Buffer, Count, &BytesRead);
1762 }
1763
1764 if (ErrorCode == 0)
1765 {
1766 /* Clear CF */
1767 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1768
1769 /* Return the number of bytes read in AX */
1770 EmulatorSetRegister(EMULATOR_REG_AX,
1771 (Eax & 0xFFFF0000) | BytesRead);
1772 }
1773 else if (ErrorCode != ERROR_NOT_READY)
1774 {
1775 /* Set CF */
1776 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1777
1778 /* Return the error code in AX */
1779 EmulatorSetRegister(EMULATOR_REG_AX,
1780 (Eax & 0xFFFF0000) | ErrorCode);
1781 }
1782 break;
1783 }
1784
1785 /* Write File */
1786 case 0x40:
1787 {
1788 WORD BytesWritten = 0;
1789 WORD ErrorCode = DosWriteFile(LOWORD(Ebx),
1790 (LPVOID)((ULONG_PTR)BaseAddress
1791 + TO_LINEAR(DataSegment, LOWORD(Edx))),
1792 LOWORD(Ecx),
1793 &BytesWritten);
1794
1795 if (ErrorCode == 0)
1796 {
1797 /* Clear CF */
1798 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1799
1800 /* Return the number of bytes written in AX */
1801 EmulatorSetRegister(EMULATOR_REG_AX,
1802 (Eax & 0xFFFF0000) | BytesWritten);
1803 }
1804 else
1805 {
1806 /* Set CF */
1807 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1808
1809 /* Return the error code in AX */
1810 EmulatorSetRegister(EMULATOR_REG_AX,
1811 (Eax & 0xFFFF0000) | ErrorCode);
1812 }
1813
1814 break;
1815 }
1816
1817 /* Delete File */
1818 case 0x41:
1819 {
1820 LPSTR FileName = (LPSTR)((ULONG_PTR)BaseAddress + TO_LINEAR(DataSegment, Edx));
1821
1822 /* Call the API function */
1823 if (DeleteFileA(FileName)) Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1824 else
1825 {
1826 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1827 EmulatorSetRegister(EMULATOR_REG_AX, GetLastError());
1828 }
1829
1830 break;
1831 }
1832
1833 /* Seek File */
1834 case 0x42:
1835 {
1836 DWORD NewLocation;
1837 WORD ErrorCode = DosSeekFile(LOWORD(Ebx),
1838 MAKELONG(LOWORD(Edx), LOWORD(Ecx)),
1839 LOBYTE(Eax),
1840 &NewLocation);
1841
1842 if (ErrorCode == 0)
1843 {
1844 /* Clear CF */
1845 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1846
1847 /* Return the new offset in DX:AX */
1848 EmulatorSetRegister(EMULATOR_REG_DX,
1849 (Edx & 0xFFFF0000) | HIWORD(NewLocation));
1850 EmulatorSetRegister(EMULATOR_REG_AX,
1851 (Eax & 0xFFFF0000) | LOWORD(NewLocation));
1852 }
1853 else
1854 {
1855 /* Set CF */
1856 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1857
1858 /* Return the error code in AX */
1859 EmulatorSetRegister(EMULATOR_REG_AX,
1860 (Eax & 0xFFFF0000) | ErrorCode);
1861 }
1862
1863 break;
1864 }
1865
1866 /* Get/Set File Attributes */
1867 case 0x43:
1868 {
1869 DWORD Attributes;
1870 LPSTR FileName = (LPSTR)((ULONG_PTR)BaseAddress + TO_LINEAR(DataSegment, Edx));
1871
1872 if (LOBYTE(Eax) == 0x00)
1873 {
1874 /* Get the attributes */
1875 Attributes = GetFileAttributesA(FileName);
1876
1877 /* Check if it failed */
1878 if (Attributes == INVALID_FILE_ATTRIBUTES)
1879 {
1880 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1881 EmulatorSetRegister(EMULATOR_REG_AX, GetLastError());
1882
1883 break;
1884 }
1885
1886 /* Return the attributes that DOS can understand */
1887 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1888 EmulatorSetRegister(EMULATOR_REG_CX,
1889 (Ecx & 0xFFFFFF00) | LOBYTE(Attributes));
1890 }
1891 else if (LOBYTE(Eax) == 0x01)
1892 {
1893 /* Try to set the attributes */
1894 if (SetFileAttributesA(FileName, LOBYTE(Ecx)))
1895 {
1896 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1897 }
1898 else
1899 {
1900 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1901 EmulatorSetRegister(EMULATOR_REG_AX, GetLastError());
1902 }
1903 }
1904 else
1905 {
1906 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1907 EmulatorSetRegister(EMULATOR_REG_AX, ERROR_INVALID_FUNCTION);
1908 }
1909
1910 break;
1911 }
1912
1913 /* IOCTL */
1914 case 0x44:
1915 {
1916 if (DosHandleIoctl(LOBYTE(Eax), LOWORD(Ebx)))
1917 {
1918 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1919 }
1920 else
1921 {
1922 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1923 EmulatorSetRegister(EMULATOR_REG_AX, DosLastError);
1924 }
1925
1926 break;
1927 }
1928
1929 /* Duplicate Handle */
1930 case 0x45:
1931 {
1932 WORD NewHandle;
1933 HANDLE Handle = DosGetRealHandle(LOWORD(Ebx));
1934
1935 if (Handle != INVALID_HANDLE_VALUE)
1936 {
1937 /* The handle is invalid */
1938 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1939 EmulatorSetRegister(EMULATOR_REG_AX, ERROR_INVALID_HANDLE);
1940
1941 break;
1942 }
1943
1944 /* Open a new handle to the same entry */
1945 NewHandle = DosOpenHandle(Handle);
1946
1947 if (NewHandle == INVALID_DOS_HANDLE)
1948 {
1949 /* Too many files open */
1950 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1951 EmulatorSetRegister(EMULATOR_REG_AX, ERROR_TOO_MANY_OPEN_FILES);
1952
1953 break;
1954 }
1955
1956 /* Return the result */
1957 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1958 EmulatorSetRegister(EMULATOR_REG_AX, NewHandle);
1959
1960 break;
1961 }
1962
1963 /* Force Duplicate Handle */
1964 case 0x46:
1965 {
1966 if (DosDuplicateHandle(LOWORD(Ebx), LOWORD(Ecx)))
1967 {
1968 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1969 }
1970 else
1971 {
1972 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1973 EmulatorSetRegister(EMULATOR_REG_AX, ERROR_INVALID_HANDLE);
1974 }
1975
1976 break;
1977 }
1978
1979 /* Allocate Memory */
1980 case 0x48:
1981 {
1982 WORD MaxAvailable = 0;
1983 WORD Segment = DosAllocateMemory(LOWORD(Ebx), &MaxAvailable);
1984
1985 if (Segment != 0)
1986 {
1987 EmulatorSetRegister(EMULATOR_REG_AX, Segment);
1988 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
1989 }
1990 else
1991 {
1992 EmulatorSetRegister(EMULATOR_REG_AX, DosLastError);
1993 EmulatorSetRegister(EMULATOR_REG_BX, MaxAvailable);
1994 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
1995 }
1996
1997 break;
1998 }
1999
2000 /* Free Memory */
2001 case 0x49:
2002 {
2003 if (DosFreeMemory(ExtSegment))
2004 {
2005 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
2006 }
2007 else
2008 {
2009 EmulatorSetRegister(EMULATOR_REG_AX, ERROR_ARENA_TRASHED);
2010 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
2011 }
2012
2013 break;
2014 }
2015
2016 /* Resize Memory Block */
2017 case 0x4A:
2018 {
2019 WORD Size;
2020
2021 if (DosResizeMemory(ExtSegment, LOWORD(Ebx), &Size))
2022 {
2023 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
2024 }
2025 else
2026 {
2027 EmulatorSetRegister(EMULATOR_REG_AX, DosLastError);
2028 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
2029 EmulatorSetRegister(EMULATOR_REG_BX, Size);
2030 }
2031
2032 break;
2033 }
2034
2035 /* Terminate With Return Code */
2036 case 0x4C:
2037 {
2038 DosTerminateProcess(CurrentPsp, LOBYTE(Eax));
2039 break;
2040 }
2041
2042 /* Get Current Process */
2043 case 0x51:
2044 {
2045 EmulatorSetRegister(EMULATOR_REG_BX, CurrentPsp);
2046
2047 break;
2048 }
2049
2050 /* Get/Set Memory Management Options */
2051 case 0x58:
2052 {
2053 if (LOBYTE(Eax) == 0x00)
2054 {
2055 /* Get allocation strategy */
2056
2057 EmulatorSetRegister(EMULATOR_REG_AX, DosAllocStrategy);
2058 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
2059 }
2060 else if (LOBYTE(Eax) == 0x01)
2061 {
2062 /* Set allocation strategy */
2063
2064 if ((LOBYTE(Ebx) & (DOS_ALLOC_HIGH | DOS_ALLOC_HIGH_LOW))
2065 == (DOS_ALLOC_HIGH | DOS_ALLOC_HIGH_LOW))
2066 {
2067 /* Can't set both */
2068 EmulatorSetRegister(EMULATOR_REG_AX, ERROR_INVALID_PARAMETER);
2069 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
2070 break;
2071 }
2072
2073 if ((LOBYTE(Ebx) & 0x3F) > DOS_ALLOC_LAST_FIT)
2074 {
2075 /* Invalid allocation strategy */
2076 EmulatorSetRegister(EMULATOR_REG_AX, ERROR_INVALID_PARAMETER);
2077 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
2078 break;
2079 }
2080
2081 DosAllocStrategy = LOBYTE(Ebx);
2082 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
2083 }
2084 else if (LOBYTE(Eax) == 0x02)
2085 {
2086 /* Get UMB link state */
2087
2088 Eax &= 0xFFFFFF00;
2089 if (DosUmbLinked) Eax |= 1;
2090 EmulatorSetRegister(EMULATOR_REG_AX, Eax);
2091 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
2092 }
2093 else if (LOBYTE(Eax) == 0x03)
2094 {
2095 /* Set UMB link state */
2096
2097 if (Ebx) DosLinkUmb();
2098 else DosUnlinkUmb();
2099 Stack[STACK_FLAGS] &= ~EMULATOR_FLAG_CF;
2100 }
2101 else
2102 {
2103 /* Invalid or unsupported function */
2104
2105 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
2106 EmulatorSetRegister(EMULATOR_REG_AX, ERROR_INVALID_FUNCTION);
2107 }
2108
2109 break;
2110 }
2111
2112 /* Unsupported */
2113 default:
2114 {
2115 DPRINT1("DOS Function INT 0x21, AH = 0x%02X NOT IMPLEMENTED!\n", HIBYTE(Eax));
2116 Stack[STACK_FLAGS] |= EMULATOR_FLAG_CF;
2117 }
2118 }
2119 }
2120
2121 VOID DosBreakInterrupt(LPWORD Stack)
2122 {
2123 UNREFERENCED_PARAMETER(Stack);
2124
2125 VdmRunning = FALSE;
2126 }
2127
2128 BOOLEAN DosInitialize(VOID)
2129 {
2130 BYTE i;
2131 PDOS_MCB Mcb = SEGMENT_TO_MCB(FIRST_MCB_SEGMENT);
2132 FILE *Stream;
2133 WCHAR Buffer[256];
2134 LPWSTR SourcePtr, Environment;
2135 LPSTR AsciiString;
2136 LPSTR DestPtr = (LPSTR)((ULONG_PTR)BaseAddress + TO_LINEAR(SYSTEM_ENV_BLOCK, 0));
2137 DWORD AsciiSize;
2138 CHAR CurrentDirectory[MAX_PATH];
2139 CHAR DosDirectory[DOS_DIR_LENGTH];
2140 LPSTR Path;
2141
2142 /* Initialize the MCB */
2143 Mcb->BlockType = 'Z';
2144 Mcb->Size = USER_MEMORY_SIZE;
2145 Mcb->OwnerPsp = 0;
2146
2147 /* Initialize the link MCB to the UMB area */
2148 Mcb = SEGMENT_TO_MCB(FIRST_MCB_SEGMENT + USER_MEMORY_SIZE + 1);
2149 Mcb->BlockType = 'M';
2150 Mcb->Size = UMB_START_SEGMENT - FIRST_MCB_SEGMENT - USER_MEMORY_SIZE - 2;
2151 Mcb->OwnerPsp = SYSTEM_PSP;
2152
2153 /* Initialize the UMB area */
2154 Mcb = SEGMENT_TO_MCB(UMB_START_SEGMENT);
2155 Mcb->BlockType = 'Z';
2156 Mcb->Size = UMB_END_SEGMENT - UMB_START_SEGMENT;
2157 Mcb->OwnerPsp = 0;
2158
2159 /* Get the environment strings */
2160 SourcePtr = Environment = GetEnvironmentStringsW();
2161 if (Environment == NULL) return FALSE;
2162
2163 /* Fill the DOS system environment block */
2164 while (*SourcePtr)
2165 {
2166 /* Get the size of the ASCII string */
2167 AsciiSize = WideCharToMultiByte(CP_ACP,
2168 0,
2169 SourcePtr,
2170 -1,
2171 NULL,
2172 0,
2173 NULL,
2174 NULL);
2175
2176 /* Allocate memory for the ASCII string */
2177 AsciiString = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, AsciiSize);
2178 if (AsciiString == NULL)
2179 {
2180 FreeEnvironmentStringsW(Environment);
2181 return FALSE;
2182 }
2183
2184 /* Convert to ASCII */
2185 WideCharToMultiByte(CP_ACP,
2186 0,
2187 SourcePtr,
2188 -1,
2189 AsciiString,
2190 AsciiSize,
2191 NULL,
2192 NULL);
2193
2194 /* Copy the string into DOS memory */
2195 strcpy(DestPtr, AsciiString);
2196
2197 /* Move to the next string */
2198 SourcePtr += wcslen(SourcePtr) + 1;
2199 DestPtr += strlen(AsciiString);
2200 *(DestPtr++) = 0;
2201
2202 /* Free the memory */
2203 HeapFree(GetProcessHeap(), 0, AsciiString);
2204 }
2205 *DestPtr = 0;
2206
2207 /* Free the memory allocated for environment strings */
2208 FreeEnvironmentStringsW(Environment);
2209
2210 /* Clear the current directory buffer */
2211 ZeroMemory(CurrentDirectories, sizeof(CurrentDirectories));
2212
2213 /* Get the current directory */
2214 if (!GetCurrentDirectoryA(MAX_PATH, CurrentDirectory))
2215 {
2216 // TODO: Use some kind of default path?
2217 return FALSE;
2218 }
2219
2220 /* Convert that to a DOS path */
2221 if (!GetShortPathNameA(CurrentDirectory, DosDirectory, DOS_DIR_LENGTH))
2222 {
2223 // TODO: Use some kind of default path?
2224 return FALSE;
2225 }
2226
2227 /* Set the drive */
2228 CurrentDrive = DosDirectory[0] - 'A';
2229
2230 /* Get the path */
2231 Path = strchr(DosDirectory, '\\');
2232 if (Path != NULL)
2233 {
2234 /* Skip the backslash */
2235 Path++;
2236 }
2237
2238 /* Set the directory */
2239 if (Path != NULL) strcpy(CurrentDirectories[CurrentDrive], Path);
2240
2241 /* Read CONFIG.SYS */
2242 Stream = _wfopen(DOS_CONFIG_PATH, L"r");
2243 if (Stream != NULL)
2244 {
2245 while (fgetws(Buffer, 256, Stream))
2246 {
2247 // TODO: Parse the line
2248 }
2249 fclose(Stream);
2250 }
2251
2252 /* Initialize the SFT */
2253 for (i = 0; i < DOS_SFT_SIZE; i++)
2254 {
2255 DosSystemFileTable[i] = INVALID_HANDLE_VALUE;
2256 DosSftRefCount[i] = 0;
2257 }
2258
2259 /* Get handles to standard I/O devices */
2260 DosSystemFileTable[0] = GetStdHandle(STD_INPUT_HANDLE);
2261 DosSystemFileTable[1] = GetStdHandle(STD_OUTPUT_HANDLE);
2262 DosSystemFileTable[2] = GetStdHandle(STD_ERROR_HANDLE);
2263
2264 return TRUE;
2265 }
2266
2267 /* EOF */