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