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