2 * COPYRIGHT: GPL - See COPYING in the top level directory
3 * PROJECT: ReactOS Virtual DOS Machine
4 * FILE: dos/dos32krnl/dos.c
5 * PURPOSE: DOS32 Kernel
6 * PROGRAMMERS: Aleksandar Andrejevic <theflash AT sdf DOT lonestar DOT org>
7 * Hermes Belusca-Maito (hermes.belusca@sfr.fr)
10 /* INCLUDES *******************************************************************/
21 #include "bios/bios.h"
24 #include "hardware/ps2.h"
26 /* PRIVATE VARIABLES **********************************************************/
28 CALLBACK16 DosContext
;
30 static WORD CurrentPsp
= SYSTEM_PSP
;
31 static WORD DosLastError
= 0;
32 static DWORD DiskTransferArea
;
33 /*static*/ BYTE CurrentDrive
;
34 static CHAR LastDrive
= 'E';
35 static CHAR CurrentDirectories
[NUM_DRIVES
][DOS_DIR_LENGTH
];
41 } DosSystemFileTable
[DOS_SFT_SIZE
];
43 static BYTE DosAllocStrategy
= DOS_ALLOC_BEST_FIT
;
44 static BOOLEAN DosUmbLinked
= FALSE
;
45 static WORD DosErrorLevel
= 0x0000;
47 /* Echo state for INT 21h, AH = 01h and AH = 3Fh */
48 BOOLEAN DoEcho
= FALSE
;
50 /* PRIVATE FUNCTIONS **********************************************************/
53 * Memory management functions
55 static VOID
DosCombineFreeBlocks(WORD StartBlock
)
57 PDOS_MCB CurrentMcb
= SEGMENT_TO_MCB(StartBlock
), NextMcb
;
59 /* If this is the last block or it's not free, quit */
60 if (CurrentMcb
->BlockType
== 'Z' || CurrentMcb
->OwnerPsp
!= 0) return;
64 /* Get a pointer to the next MCB */
65 NextMcb
= SEGMENT_TO_MCB(StartBlock
+ CurrentMcb
->Size
+ 1);
67 /* Check if the next MCB is free */
68 if (NextMcb
->OwnerPsp
== 0)
71 CurrentMcb
->Size
+= NextMcb
->Size
+ 1;
72 CurrentMcb
->BlockType
= NextMcb
->BlockType
;
73 NextMcb
->BlockType
= 'I';
77 /* No more adjoining free blocks */
83 static WORD
DosAllocateMemory(WORD Size
, WORD
*MaxAvailable
)
85 WORD Result
= 0, Segment
= FIRST_MCB_SEGMENT
, MaxSize
= 0;
86 PDOS_MCB CurrentMcb
, NextMcb
;
87 BOOLEAN SearchUmb
= FALSE
;
89 DPRINT("DosAllocateMemory: Size 0x%04X\n", Size
);
91 if (DosUmbLinked
&& (DosAllocStrategy
& (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
)))
93 /* Search UMB first */
94 Segment
= UMB_START_SEGMENT
;
100 /* Get a pointer to the MCB */
101 CurrentMcb
= SEGMENT_TO_MCB(Segment
);
103 /* Make sure it's valid */
104 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!= 'Z')
106 DPRINT("The DOS memory arena is corrupted!\n");
107 DosLastError
= ERROR_ARENA_TRASHED
;
111 /* Only check free blocks */
112 if (CurrentMcb
->OwnerPsp
!= 0) goto Next
;
114 /* Combine this free block with adjoining free blocks */
115 DosCombineFreeBlocks(Segment
);
117 /* Update the maximum block size */
118 if (CurrentMcb
->Size
> MaxSize
) MaxSize
= CurrentMcb
->Size
;
120 /* Check if this block is big enough */
121 if (CurrentMcb
->Size
< Size
) goto Next
;
123 switch (DosAllocStrategy
& 0x3F)
125 case DOS_ALLOC_FIRST_FIT
:
127 /* For first fit, stop immediately */
132 case DOS_ALLOC_BEST_FIT
:
134 /* For best fit, update the smallest block found so far */
135 if ((Result
== 0) || (CurrentMcb
->Size
< SEGMENT_TO_MCB(Result
)->Size
))
143 case DOS_ALLOC_LAST_FIT
:
145 /* For last fit, make the current block the result, but keep searching */
152 /* If this was the last MCB in the chain, quit */
153 if (CurrentMcb
->BlockType
== 'Z')
155 /* Check if nothing was found while searching through UMBs */
156 if ((Result
== 0) && SearchUmb
&& (DosAllocStrategy
& DOS_ALLOC_HIGH_LOW
))
158 /* Search low memory */
159 Segment
= FIRST_MCB_SEGMENT
;
166 /* Otherwise, update the segment and continue */
167 Segment
+= CurrentMcb
->Size
+ 1;
172 /* If we didn't find a free block, return 0 */
175 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
176 if (MaxAvailable
) *MaxAvailable
= MaxSize
;
180 /* Get a pointer to the MCB */
181 CurrentMcb
= SEGMENT_TO_MCB(Result
);
183 /* Check if the block is larger than requested */
184 if (CurrentMcb
->Size
> Size
)
186 /* It is, split it into two blocks */
187 NextMcb
= SEGMENT_TO_MCB(Result
+ Size
+ 1);
189 /* Initialize the new MCB structure */
190 NextMcb
->BlockType
= CurrentMcb
->BlockType
;
191 NextMcb
->Size
= CurrentMcb
->Size
- Size
- 1;
192 NextMcb
->OwnerPsp
= 0;
194 /* Update the current block */
195 CurrentMcb
->BlockType
= 'M';
196 CurrentMcb
->Size
= Size
;
199 /* Take ownership of the block */
200 CurrentMcb
->OwnerPsp
= CurrentPsp
;
202 /* Return the segment of the data portion of the block */
206 static BOOLEAN
DosResizeMemory(WORD BlockData
, WORD NewSize
, WORD
*MaxAvailable
)
208 BOOLEAN Success
= TRUE
;
209 WORD Segment
= BlockData
- 1, ReturnSize
= 0, NextSegment
;
210 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
), NextMcb
;
212 DPRINT("DosResizeMemory: BlockData 0x%04X, NewSize 0x%04X\n",
216 /* Make sure this is a valid, allocated block */
217 if ((Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z') || Mcb
->OwnerPsp
== 0)
220 DosLastError
= ERROR_INVALID_HANDLE
;
224 ReturnSize
= Mcb
->Size
;
226 /* Check if we need to expand or contract the block */
227 if (NewSize
> Mcb
->Size
)
229 /* We can't expand the last block */
230 if (Mcb
->BlockType
!= 'M')
236 /* Get the pointer and segment of the next MCB */
237 NextSegment
= Segment
+ Mcb
->Size
+ 1;
238 NextMcb
= SEGMENT_TO_MCB(NextSegment
);
240 /* Make sure the next segment is free */
241 if (NextMcb
->OwnerPsp
!= 0)
243 DPRINT("Cannot expand memory block: next segment is not free!\n");
244 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
249 /* Combine this free block with adjoining free blocks */
250 DosCombineFreeBlocks(NextSegment
);
252 /* Set the maximum possible size of the block */
253 ReturnSize
+= NextMcb
->Size
+ 1;
255 if (ReturnSize
< NewSize
)
257 DPRINT("Cannot expand memory block: insufficient free segments available!\n");
258 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
263 /* Maximize the current block */
264 Mcb
->Size
= ReturnSize
;
265 Mcb
->BlockType
= NextMcb
->BlockType
;
267 /* Invalidate the next block */
268 NextMcb
->BlockType
= 'I';
270 /* Check if the block is larger than requested */
271 if (Mcb
->Size
> NewSize
)
273 DPRINT("Block too large, reducing size from 0x%04X to 0x%04X\n",
277 /* It is, split it into two blocks */
278 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
280 /* Initialize the new MCB structure */
281 NextMcb
->BlockType
= Mcb
->BlockType
;
282 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
283 NextMcb
->OwnerPsp
= 0;
285 /* Update the current block */
286 Mcb
->BlockType
= 'M';
290 else if (NewSize
< Mcb
->Size
)
292 DPRINT("Shrinking block from 0x%04X to 0x%04X\n",
296 /* Just split the block */
297 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
298 NextMcb
->BlockType
= Mcb
->BlockType
;
299 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
300 NextMcb
->OwnerPsp
= 0;
303 Mcb
->BlockType
= 'M';
308 /* Check if the operation failed */
311 DPRINT("DosResizeMemory FAILED. Maximum available: 0x%04X\n",
314 /* Return the maximum possible size */
315 if (MaxAvailable
) *MaxAvailable
= ReturnSize
;
321 static BOOLEAN
DosFreeMemory(WORD BlockData
)
323 PDOS_MCB Mcb
= SEGMENT_TO_MCB(BlockData
- 1);
325 DPRINT("DosFreeMemory: BlockData 0x%04X\n", BlockData
);
327 /* Make sure the MCB is valid */
328 if (Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z')
330 DPRINT("MCB block type '%c' not valid!\n", Mcb
->BlockType
);
334 /* Mark the block as free */
340 static BOOLEAN
DosLinkUmb(VOID
)
342 DWORD Segment
= FIRST_MCB_SEGMENT
;
343 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
);
345 DPRINT("Linking UMB\n");
347 /* Check if UMBs are already linked */
348 if (DosUmbLinked
) return FALSE
;
350 /* Find the last block */
351 while ((Mcb
->BlockType
== 'M') && (Segment
<= 0xFFFF))
353 Segment
+= Mcb
->Size
+ 1;
354 Mcb
= SEGMENT_TO_MCB(Segment
);
357 /* Make sure it's valid */
358 if (Mcb
->BlockType
!= 'Z') return FALSE
;
360 /* Connect the MCB with the UMB chain */
361 Mcb
->BlockType
= 'M';
367 static BOOLEAN
DosUnlinkUmb(VOID
)
369 DWORD Segment
= FIRST_MCB_SEGMENT
;
370 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
);
372 DPRINT("Unlinking UMB\n");
374 /* Check if UMBs are already unlinked */
375 if (!DosUmbLinked
) return FALSE
;
377 /* Find the block preceding the MCB that links it with the UMB chain */
378 while (Segment
<= 0xFFFF)
380 if ((Segment
+ Mcb
->Size
) == (FIRST_MCB_SEGMENT
+ USER_MEMORY_SIZE
))
382 /* This is the last non-UMB segment */
386 /* Advance to the next MCB */
387 Segment
+= Mcb
->Size
+ 1;
388 Mcb
= SEGMENT_TO_MCB(Segment
);
391 /* Mark the MCB as the last MCB */
392 Mcb
->BlockType
= 'Z';
394 DosUmbLinked
= FALSE
;
398 static VOID
DosChangeMemoryOwner(WORD Segment
, WORD NewOwner
)
400 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
- 1);
402 /* Just set the owner */
403 Mcb
->OwnerPsp
= NewOwner
;
406 static WORD
DosCopyEnvironmentBlock(LPCVOID Environment
, LPCSTR ProgramName
)
408 PCHAR Ptr
, DestBuffer
= NULL
;
412 Ptr
= (PCHAR
)Environment
;
414 /* Calculate the size of the environment block */
417 TotalSize
+= strlen(Ptr
) + 1;
418 Ptr
+= strlen(Ptr
) + 1;
422 /* Add the string buffer size */
423 TotalSize
+= strlen(ProgramName
) + 1;
425 /* Add the two extra bytes */
428 /* Allocate the memory for the environment block */
429 DestSegment
= DosAllocateMemory((WORD
)((TotalSize
+ 0x0F) >> 4), NULL
);
430 if (!DestSegment
) return 0;
432 Ptr
= (PCHAR
)Environment
;
434 DestBuffer
= (PCHAR
)SEG_OFF_TO_PTR(DestSegment
, 0);
437 /* Copy the string */
438 strcpy(DestBuffer
, Ptr
);
440 /* Advance to the next string */
441 DestBuffer
+= strlen(Ptr
);
442 Ptr
+= strlen(Ptr
) + 1;
444 /* Put a zero after the string */
448 /* Set the final zero */
451 /* Store the special program name tag */
452 *(DestBuffer
++) = LOBYTE(DOS_PROGRAM_NAME_TAG
);
453 *(DestBuffer
++) = HIBYTE(DOS_PROGRAM_NAME_TAG
);
455 /* Copy the program name after the environment block */
456 strcpy(DestBuffer
, ProgramName
);
466 /* Taken from base/shell/cmd/console.c */
467 BOOL
IsConsoleHandle(HANDLE hHandle
)
471 /* Check whether the handle may be that of a console... */
472 if ((GetFileType(hHandle
) & FILE_TYPE_CHAR
) == 0) return FALSE
;
475 * It may be. Perform another test... The idea comes from the
476 * MSDN description of the WriteConsole API:
478 * "WriteConsole fails if it is used with a standard handle
479 * that is redirected to a file. If an application processes
480 * multilingual output that can be redirected, determine whether
481 * the output handle is a console handle (one method is to call
482 * the GetConsoleMode function and check whether it succeeds).
483 * If the handle is a console handle, call WriteConsole. If the
484 * handle is not a console handle, the output is redirected and
485 * you should call WriteFile to perform the I/O."
487 return GetConsoleMode(hHandle
, &dwMode
);
490 WORD
DosOpenHandle(HANDLE Handle
)
497 /* The system PSP has no handle table */
498 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_DOS_HANDLE
;
500 /* Get a pointer to the handle table */
501 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
502 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
504 /* Find a free entry in the JFT */
505 for (DosHandle
= 0; DosHandle
< PspBlock
->HandleTableSize
; DosHandle
++)
507 if (HandleTable
[DosHandle
] == 0xFF) break;
510 /* If there are no free entries, fail */
511 if (DosHandle
== PspBlock
->HandleTableSize
) return INVALID_DOS_HANDLE
;
513 /* Check if the handle is already in the SFT */
514 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
516 /* Check if this is the same handle */
517 if (DosSystemFileTable
[i
].Handle
!= Handle
) continue;
519 /* Already in the table, reference it */
520 DosSystemFileTable
[i
].RefCount
++;
522 /* Set the JFT entry to that SFT index */
523 HandleTable
[DosHandle
] = i
;
525 /* Return the new handle */
529 /* Add the handle to the SFT */
530 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
532 /* Make sure this is an empty table entry */
533 if (DosSystemFileTable
[i
].Handle
!= INVALID_HANDLE_VALUE
) continue;
535 /* Initialize the empty table entry */
536 DosSystemFileTable
[i
].Handle
= Handle
;
537 DosSystemFileTable
[i
].RefCount
= 1;
539 /* Set the JFT entry to that SFT index */
540 HandleTable
[DosHandle
] = i
;
542 /* Return the new handle */
546 /* The SFT is full */
547 return INVALID_DOS_HANDLE
;
550 HANDLE
DosGetRealHandle(WORD DosHandle
)
555 /* The system PSP has no handle table */
556 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_HANDLE_VALUE
;
558 /* Get a pointer to the handle table */
559 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
560 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
562 /* Make sure the handle is open */
563 if (HandleTable
[DosHandle
] == 0xFF) return INVALID_HANDLE_VALUE
;
565 /* Return the Win32 handle */
566 return DosSystemFileTable
[HandleTable
[DosHandle
]].Handle
;
569 static VOID
DosCopyHandleTable(LPBYTE DestinationTable
)
575 /* Clear the table first */
576 for (i
= 0; i
< 20; i
++) DestinationTable
[i
] = 0xFF;
578 /* Check if this is the initial process */
579 if (CurrentPsp
== SYSTEM_PSP
)
581 /* Set up the standard I/O devices */
582 for (i
= 0; i
<= 2; i
++)
584 /* Set the index in the SFT */
585 DestinationTable
[i
] = (BYTE
)i
;
587 /* Increase the reference count */
588 DosSystemFileTable
[i
].RefCount
++;
595 /* Get the parent PSP block and handle table */
596 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
597 SourceTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
599 /* Copy the first 20 handles into the new table */
600 for (i
= 0; i
< 20; i
++)
602 DestinationTable
[i
] = SourceTable
[i
];
604 /* Increase the reference count */
605 DosSystemFileTable
[SourceTable
[i
]].RefCount
++;
609 static BOOLEAN
DosResizeHandleTable(WORD NewSize
)
615 /* Get the PSP block */
616 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
618 if (NewSize
== PspBlock
->HandleTableSize
)
624 if (PspBlock
->HandleTableSize
> 20)
626 /* Get the segment of the current table */
627 Segment
= (LOWORD(PspBlock
->HandleTablePtr
) >> 4) + HIWORD(PspBlock
->HandleTablePtr
);
631 /* Get the current handle table */
632 HandleTable
= FAR_POINTER(PspBlock
->HandleTablePtr
);
634 /* Copy it to the PSP */
635 RtlCopyMemory(PspBlock
->HandleTable
, HandleTable
, NewSize
);
637 /* Free the memory */
638 DosFreeMemory(Segment
);
640 /* Update the handle table pointer and size */
641 PspBlock
->HandleTableSize
= NewSize
;
642 PspBlock
->HandleTablePtr
= MAKELONG(0x18, CurrentPsp
);
646 /* Resize the memory */
647 if (!DosResizeMemory(Segment
, NewSize
, NULL
))
649 /* Unable to resize, try allocating it somewhere else */
650 Segment
= DosAllocateMemory(NewSize
, NULL
);
651 if (Segment
== 0) return FALSE
;
653 /* Get the new handle table */
654 HandleTable
= SEG_OFF_TO_PTR(Segment
, 0);
656 /* Copy the handles to the new table */
657 RtlCopyMemory(HandleTable
,
658 FAR_POINTER(PspBlock
->HandleTablePtr
),
659 PspBlock
->HandleTableSize
);
661 /* Update the handle table pointer */
662 PspBlock
->HandleTablePtr
= MAKELONG(0, Segment
);
665 /* Update the handle table size */
666 PspBlock
->HandleTableSize
= NewSize
;
669 else if (NewSize
> 20)
671 Segment
= DosAllocateMemory(NewSize
, NULL
);
672 if (Segment
== 0) return FALSE
;
674 /* Get the new handle table */
675 HandleTable
= SEG_OFF_TO_PTR(Segment
, 0);
677 /* Copy the handles from the PSP to the new table */
678 RtlCopyMemory(HandleTable
,
679 FAR_POINTER(PspBlock
->HandleTablePtr
),
680 PspBlock
->HandleTableSize
);
682 /* Update the handle table pointer and size */
683 PspBlock
->HandleTableSize
= NewSize
;
684 PspBlock
->HandleTablePtr
= MAKELONG(0, Segment
);
690 static BOOLEAN
DosCloseHandle(WORD DosHandle
)
696 DPRINT("DosCloseHandle: DosHandle 0x%04X\n", DosHandle
);
698 /* The system PSP has no handle table */
699 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
701 /* Get a pointer to the handle table */
702 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
703 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
705 /* Make sure the handle is open */
706 if (HandleTable
[DosHandle
] == 0xFF) return FALSE
;
708 /* Decrement the reference count of the SFT entry */
709 SftIndex
= HandleTable
[DosHandle
];
710 DosSystemFileTable
[SftIndex
].RefCount
--;
712 /* Check if the reference count fell to zero */
713 if (!DosSystemFileTable
[SftIndex
].RefCount
)
715 /* Close the file, it's no longer needed */
716 CloseHandle(DosSystemFileTable
[SftIndex
].Handle
);
718 /* Clear the handle */
719 DosSystemFileTable
[SftIndex
].Handle
= INVALID_HANDLE_VALUE
;
722 /* Clear the entry in the JFT */
723 HandleTable
[DosHandle
] = 0xFF;
728 static BOOLEAN
DosDuplicateHandle(WORD OldHandle
, WORD NewHandle
)
734 DPRINT("DosDuplicateHandle: OldHandle 0x%04X, NewHandle 0x%04X\n",
738 /* The system PSP has no handle table */
739 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
741 /* Get a pointer to the handle table */
742 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
743 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
745 /* Make sure the old handle is open */
746 if (HandleTable
[OldHandle
] == 0xFF) return FALSE
;
748 /* Check if the new handle is open */
749 if (HandleTable
[NewHandle
] != 0xFF)
752 DosCloseHandle(NewHandle
);
755 /* Increment the reference count of the SFT entry */
756 SftIndex
= HandleTable
[OldHandle
];
757 DosSystemFileTable
[SftIndex
].RefCount
++;
759 /* Make the new handle point to that SFT entry */
760 HandleTable
[NewHandle
] = SftIndex
;
772 static BOOLEAN
DosChangeDrive(BYTE Drive
)
774 WCHAR DirectoryPath
[DOS_CMDLINE_LENGTH
];
776 /* Make sure the drive exists */
777 if (Drive
> (LastDrive
- 'A')) return FALSE
;
779 /* Find the path to the new current directory */
780 swprintf(DirectoryPath
, L
"%c\\%S", Drive
+ 'A', CurrentDirectories
[Drive
]);
782 /* Change the current directory of the process */
783 if (!SetCurrentDirectory(DirectoryPath
)) return FALSE
;
785 /* Set the current drive */
786 CurrentDrive
= Drive
;
792 static BOOLEAN
DosChangeDirectory(LPSTR Directory
)
798 /* Make sure the directory path is not too long */
799 if (strlen(Directory
) >= DOS_DIR_LENGTH
)
801 DosLastError
= ERROR_PATH_NOT_FOUND
;
805 /* Get the drive number */
806 DriveNumber
= Directory
[0] - 'A';
808 /* Make sure the drive exists */
809 if (DriveNumber
> (LastDrive
- 'A'))
811 DosLastError
= ERROR_PATH_NOT_FOUND
;
815 /* Get the file attributes */
816 Attributes
= GetFileAttributesA(Directory
);
818 /* Make sure the path exists and is a directory */
819 if ((Attributes
== INVALID_FILE_ATTRIBUTES
)
820 || !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
822 DosLastError
= ERROR_PATH_NOT_FOUND
;
826 /* Check if this is the current drive */
827 if (DriveNumber
== CurrentDrive
)
829 /* Change the directory */
830 if (!SetCurrentDirectoryA(Directory
))
832 DosLastError
= LOWORD(GetLastError());
837 /* Get the directory part of the path */
838 Path
= strchr(Directory
, '\\');
841 /* Skip the backslash */
845 /* Set the directory for the drive */
848 strncpy(CurrentDirectories
[DriveNumber
], Path
, DOS_DIR_LENGTH
);
852 CurrentDirectories
[DriveNumber
][0] = '\0';
859 /* PUBLIC FUNCTIONS ***********************************************************/
861 VOID
DosInitializePsp(WORD PspSegment
, LPCSTR CommandLine
, WORD ProgramSize
, WORD Environment
)
863 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(PspSegment
);
864 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
866 RtlZeroMemory(PspBlock
, sizeof(*PspBlock
));
868 /* Set the exit interrupt */
869 PspBlock
->Exit
[0] = 0xCD; // int 0x20
870 PspBlock
->Exit
[1] = 0x20;
872 /* Set the number of the last paragraph */
873 PspBlock
->LastParagraph
= PspSegment
+ ProgramSize
- 1;
875 /* Save the interrupt vectors */
876 PspBlock
->TerminateAddress
= IntVecTable
[0x22];
877 PspBlock
->BreakAddress
= IntVecTable
[0x23];
878 PspBlock
->CriticalAddress
= IntVecTable
[0x24];
880 /* Set the parent PSP */
881 PspBlock
->ParentPsp
= CurrentPsp
;
883 /* Copy the parent handle table */
884 DosCopyHandleTable(PspBlock
->HandleTable
);
886 /* Set the environment block */
887 PspBlock
->EnvBlock
= Environment
;
889 /* Set the handle table pointers to the internal handle table */
890 PspBlock
->HandleTableSize
= 20;
891 PspBlock
->HandleTablePtr
= MAKELONG(0x18, PspSegment
);
893 /* Set the DOS version */
894 PspBlock
->DosVersion
= DOS_VERSION
;
896 /* Set the far call opcodes */
897 PspBlock
->FarCall
[0] = 0xCD; // int 0x21
898 PspBlock
->FarCall
[1] = 0x21;
899 PspBlock
->FarCall
[2] = 0xCB; // retf
901 /* Set the command line */
902 PspBlock
->CommandLineSize
= (BYTE
)min(strlen(CommandLine
), DOS_CMDLINE_LENGTH
- 1);
903 RtlCopyMemory(PspBlock
->CommandLine
, CommandLine
, PspBlock
->CommandLineSize
);
904 PspBlock
->CommandLine
[PspBlock
->CommandLineSize
] = '\r';
907 DWORD
DosLoadExecutable(IN DOS_EXEC_TYPE LoadType
,
908 IN LPCSTR ExecutablePath
,
909 IN LPCSTR CommandLine
,
910 IN PVOID Environment
,
911 OUT PDWORD StackLocation OPTIONAL
,
912 OUT PDWORD EntryPoint OPTIONAL
)
914 DWORD Result
= ERROR_SUCCESS
;
915 HANDLE FileHandle
= INVALID_HANDLE_VALUE
, FileMapping
= NULL
;
916 LPBYTE Address
= NULL
;
920 DWORD i
, FileSize
, ExeSize
;
921 PIMAGE_DOS_HEADER Header
;
922 PDWORD RelocationTable
;
924 LPSTR CmdLinePtr
= (LPSTR
)CommandLine
;
926 DPRINT1("DosLoadExecutable(%d, %s, %s, %s, 0x%08X, 0x%08X)\n",
934 if (LoadType
== DOS_LOAD_OVERLAY
)
936 DPRINT1("Overlay loading is not supported yet.\n");
937 return ERROR_NOT_SUPPORTED
;
940 /* NULL-terminate the command line by removing the return carriage character */
941 while (*CmdLinePtr
&& *CmdLinePtr
!= '\r') CmdLinePtr
++;
944 /* Open a handle to the executable */
945 FileHandle
= CreateFileA(ExecutablePath
,
950 FILE_ATTRIBUTE_NORMAL
,
952 if (FileHandle
== INVALID_HANDLE_VALUE
)
954 Result
= GetLastError();
958 /* Get the file size */
959 FileSize
= GetFileSize(FileHandle
, NULL
);
961 /* Create a mapping object for the file */
962 FileMapping
= CreateFileMapping(FileHandle
,
968 if (FileMapping
== NULL
)
970 Result
= GetLastError();
974 /* Map the file into memory */
975 Address
= (LPBYTE
)MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 0);
978 Result
= GetLastError();
982 /* Copy the environment block to DOS memory */
983 EnvBlock
= DosCopyEnvironmentBlock(Environment
, ExecutablePath
);
986 Result
= ERROR_NOT_ENOUGH_MEMORY
;
990 /* Check if this is an EXE file or a COM file */
991 if (Address
[0] == 'M' && Address
[1] == 'Z')
995 /* Get the MZ header */
996 Header
= (PIMAGE_DOS_HEADER
)Address
;
998 /* Get the base size of the file, in paragraphs (rounded up) */
999 ExeSize
= (((Header
->e_cp
- 1) * 512) + Header
->e_cblp
+ 0x0F) >> 4;
1001 /* Add the PSP size, in paragraphs */
1002 ExeSize
+= sizeof(DOS_PSP
) >> 4;
1004 /* Add the maximum size that should be allocated */
1005 ExeSize
+= Header
->e_maxalloc
;
1007 /* Make sure it does not pass 0xFFFF */
1008 if (ExeSize
> 0xFFFF) ExeSize
= 0xFFFF;
1010 /* Reduce the size one by one until the allocation is successful */
1011 for (i
= Header
->e_maxalloc
; i
>= Header
->e_minalloc
; i
--, ExeSize
--)
1013 /* Try to allocate that much memory */
1014 Segment
= DosAllocateMemory((WORD
)ExeSize
, NULL
);
1015 if (Segment
!= 0) break;
1018 /* Check if at least the lowest allocation was successful */
1021 Result
= DosLastError
;
1025 /* Initialize the PSP */
1026 DosInitializePsp(Segment
,
1031 /* The process owns its own memory */
1032 DosChangeMemoryOwner(Segment
, Segment
);
1033 DosChangeMemoryOwner(EnvBlock
, Segment
);
1035 /* Copy the program to Segment:0100 */
1036 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1037 Address
+ (Header
->e_cparhdr
<< 4),
1038 min(FileSize
- (Header
->e_cparhdr
<< 4),
1039 (ExeSize
<< 4) - sizeof(DOS_PSP
)));
1041 /* Get the relocation table */
1042 RelocationTable
= (PDWORD
)(Address
+ Header
->e_lfarlc
);
1044 /* Perform relocations */
1045 for (i
= 0; i
< Header
->e_crlc
; i
++)
1047 /* Get a pointer to the word that needs to be patched */
1048 RelocWord
= (PWORD
)SEG_OFF_TO_PTR(Segment
+ HIWORD(RelocationTable
[i
]),
1049 0x100 + LOWORD(RelocationTable
[i
]));
1051 /* Add the number of the EXE segment to it */
1052 *RelocWord
+= Segment
+ (sizeof(DOS_PSP
) >> 4);
1055 if (LoadType
== DOS_LOAD_AND_EXECUTE
)
1057 /* Set the initial segment registers */
1061 /* Set the stack to the location from the header */
1062 setSS(Segment
+ (sizeof(DOS_PSP
) >> 4) + Header
->e_ss
);
1063 setSP(Header
->e_sp
);
1066 CurrentPsp
= Segment
;
1067 DiskTransferArea
= MAKELONG(0x80, Segment
);
1068 CpuExecute(Segment
+ Header
->e_cs
+ (sizeof(DOS_PSP
) >> 4),
1076 /* Find the maximum amount of memory that can be allocated */
1077 DosAllocateMemory(0xFFFF, &MaxAllocSize
);
1079 /* Make sure it's enough for the whole program and the PSP */
1080 if (((DWORD
)MaxAllocSize
<< 4) < (FileSize
+ sizeof(DOS_PSP
)))
1082 Result
= ERROR_NOT_ENOUGH_MEMORY
;
1086 /* Allocate all of it */
1087 Segment
= DosAllocateMemory(MaxAllocSize
, NULL
);
1090 Result
= DosLastError
;
1094 /* The process owns its own memory */
1095 DosChangeMemoryOwner(Segment
, Segment
);
1096 DosChangeMemoryOwner(EnvBlock
, Segment
);
1098 /* Copy the program to Segment:0100 */
1099 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1103 /* Initialize the PSP */
1104 DosInitializePsp(Segment
,
1109 if (LoadType
== DOS_LOAD_AND_EXECUTE
)
1111 /* Set the initial segment registers */
1115 /* Set the stack to the last word of the segment */
1120 * Set the value on the stack to 0, so that a near return
1121 * jumps to PSP:0000 which has the exit code.
1123 *((LPWORD
)SEG_OFF_TO_PTR(Segment
, 0xFFFE)) = 0;
1126 CurrentPsp
= Segment
;
1127 DiskTransferArea
= MAKELONG(0x80, Segment
);
1128 CpuExecute(Segment
, 0x100);
1133 if (Result
!= ERROR_SUCCESS
)
1135 /* It was not successful, cleanup the DOS memory */
1136 if (EnvBlock
) DosFreeMemory(EnvBlock
);
1137 if (Segment
) DosFreeMemory(Segment
);
1141 if (Address
!= NULL
) UnmapViewOfFile(Address
);
1143 /* Close the file mapping object */
1144 if (FileMapping
!= NULL
) CloseHandle(FileMapping
);
1146 /* Close the file handle */
1147 if (FileHandle
!= INVALID_HANDLE_VALUE
) CloseHandle(FileHandle
);
1152 DWORD
DosStartProcess(IN LPCSTR ExecutablePath
,
1153 IN LPCSTR CommandLine
,
1154 IN PVOID Environment
)
1158 Result
= DosLoadExecutable(DOS_LOAD_AND_EXECUTE
,
1165 if (Result
!= ERROR_SUCCESS
) goto Quit
;
1167 /* Attach to the console */
1168 VidBiosAttachToConsole(); // FIXME: And in fact, attach the full NTVDM UI to the console
1170 // HACK: Simulate a ENTER key release scancode on the PS/2 port because
1171 // some apps expect to read a key release scancode (> 0x80) when they
1173 IOWriteB(PS2_CONTROL_PORT
, 0xD2); // Next write is for the first PS/2 port
1174 IOWriteB(PS2_DATA_PORT
, 0x80 | 0x1C); // ENTER key release
1176 /* Start simulation */
1177 SetEvent(VdmTaskEvent
);
1180 /* Detach from the console */
1181 VidBiosDetachFromConsole(); // FIXME: And in fact, detach the full NTVDM UI from the console
1188 WORD
DosCreateProcess(DOS_EXEC_TYPE LoadType
,
1190 PDOS_EXEC_PARAM_BLOCK Parameters
)
1194 LPVOID Environment
= NULL
;
1195 VDM_COMMAND_INFO CommandInfo
;
1196 CHAR CmdLine
[MAX_PATH
];
1197 CHAR AppName
[MAX_PATH
];
1198 CHAR PifFile
[MAX_PATH
];
1199 CHAR Desktop
[MAX_PATH
];
1200 CHAR Title
[MAX_PATH
];
1202 STARTUPINFOA StartupInfo
;
1203 PROCESS_INFORMATION ProcessInfo
;
1205 /* Get the binary type */
1206 if (!GetBinaryTypeA(ProgramName
, &BinaryType
)) return GetLastError();
1208 /* Did the caller specify an environment segment? */
1209 if (Parameters
->Environment
)
1211 /* Yes, use it instead of the parent one */
1212 Environment
= SEG_OFF_TO_PTR(Parameters
->Environment
, 0);
1215 /* Set up the startup info structure */
1216 RtlZeroMemory(&StartupInfo
, sizeof(StartupInfo
));
1217 StartupInfo
.cb
= sizeof(StartupInfo
);
1219 /* Create the process */
1220 if (!CreateProcessA(ProgramName
,
1221 FAR_POINTER(Parameters
->CommandLine
),
1231 return GetLastError();
1234 /* Check the type of the program */
1237 /* These are handled by NTVDM */
1238 case SCS_DOS_BINARY
:
1239 case SCS_WOW_BINARY
:
1241 /* Clear the structure */
1242 RtlZeroMemory(&CommandInfo
, sizeof(CommandInfo
));
1244 /* Initialize the structure members */
1245 CommandInfo
.TaskId
= SessionId
;
1246 CommandInfo
.VDMState
= VDM_FLAG_NESTED_TASK
| VDM_FLAG_DONT_WAIT
;
1247 CommandInfo
.CmdLine
= CmdLine
;
1248 CommandInfo
.CmdLen
= sizeof(CmdLine
);
1249 CommandInfo
.AppName
= AppName
;
1250 CommandInfo
.AppLen
= sizeof(AppName
);
1251 CommandInfo
.PifFile
= PifFile
;
1252 CommandInfo
.PifLen
= sizeof(PifFile
);
1253 CommandInfo
.Desktop
= Desktop
;
1254 CommandInfo
.DesktopLen
= sizeof(Desktop
);
1255 CommandInfo
.Title
= Title
;
1256 CommandInfo
.TitleLen
= sizeof(Title
);
1257 CommandInfo
.Env
= Env
;
1258 CommandInfo
.EnvLen
= sizeof(Env
);
1260 /* Get the VDM command information */
1261 if (!GetNextVDMCommand(&CommandInfo
))
1263 /* Shouldn't happen */
1267 /* Increment the re-entry count */
1268 CommandInfo
.VDMState
= VDM_INC_REENTER_COUNT
;
1269 GetNextVDMCommand(&CommandInfo
);
1271 /* Load the executable */
1272 Result
= DosLoadExecutable(LoadType
,
1276 &Parameters
->StackLocation
,
1277 &Parameters
->EntryPoint
);
1278 if (Result
!= ERROR_SUCCESS
)
1280 DisplayMessage(L
"Could not load '%S'. Error: %u", AppName
, Result
);
1281 // FIXME: Decrement the reenter count. Or, instead, just increment
1282 // the VDM reenter count *only* if this call succeeds...
1288 /* Not handled by NTVDM */
1291 /* Wait for the process to finish executing */
1292 WaitForSingleObject(ProcessInfo
.hProcess
, INFINITE
);
1296 /* Close the handles */
1297 CloseHandle(ProcessInfo
.hProcess
);
1298 CloseHandle(ProcessInfo
.hThread
);
1300 return ERROR_SUCCESS
;
1304 VOID
DosTerminateProcess(WORD Psp
, BYTE ReturnCode
)
1307 WORD McbSegment
= FIRST_MCB_SEGMENT
;
1308 PDOS_MCB CurrentMcb
;
1309 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
1310 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(Psp
);
1312 DPRINT("DosTerminateProcess: Psp 0x%04X, ReturnCode 0x%02X\n",
1316 /* Check if this PSP is it's own parent */
1317 if (PspBlock
->ParentPsp
== Psp
) goto Done
;
1319 for (i
= 0; i
< PspBlock
->HandleTableSize
; i
++)
1321 /* Close the handle */
1325 /* Free the memory used by the process */
1328 /* Get a pointer to the MCB */
1329 CurrentMcb
= SEGMENT_TO_MCB(McbSegment
);
1331 /* Make sure the MCB is valid */
1332 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!='Z') break;
1334 /* If this block was allocated by the process, free it */
1335 if (CurrentMcb
->OwnerPsp
== Psp
) DosFreeMemory(McbSegment
+ 1);
1337 /* If this was the last block, quit */
1338 if (CurrentMcb
->BlockType
== 'Z') break;
1340 /* Update the segment and continue */
1341 McbSegment
+= CurrentMcb
->Size
+ 1;
1345 /* Restore the interrupt vectors */
1346 IntVecTable
[0x22] = PspBlock
->TerminateAddress
;
1347 IntVecTable
[0x23] = PspBlock
->BreakAddress
;
1348 IntVecTable
[0x24] = PspBlock
->CriticalAddress
;
1350 /* Update the current PSP */
1351 if (Psp
== CurrentPsp
)
1353 CurrentPsp
= PspBlock
->ParentPsp
;
1354 if (CurrentPsp
== SYSTEM_PSP
)
1356 ResetEvent(VdmTaskEvent
);
1362 // FIXME: This is probably not the best way to do it
1363 /* Check if this was a nested DOS task */
1364 if (CurrentPsp
!= SYSTEM_PSP
)
1366 VDM_COMMAND_INFO CommandInfo
;
1368 /* Decrement the re-entry count */
1369 CommandInfo
.TaskId
= SessionId
;
1370 CommandInfo
.VDMState
= VDM_DEC_REENTER_COUNT
;
1371 GetNextVDMCommand(&CommandInfo
);
1373 /* Clear the structure */
1374 RtlZeroMemory(&CommandInfo
, sizeof(CommandInfo
));
1376 /* Update the VDM state of the task */
1377 CommandInfo
.TaskId
= SessionId
;
1378 CommandInfo
.VDMState
= VDM_FLAG_DONT_WAIT
;
1379 GetNextVDMCommand(&CommandInfo
);
1383 /* Save the return code - Normal termination */
1384 DosErrorLevel
= MAKEWORD(ReturnCode
, 0x00);
1386 /* Return control to the parent process */
1387 CpuExecute(HIWORD(PspBlock
->TerminateAddress
),
1388 LOWORD(PspBlock
->TerminateAddress
));
1391 BOOLEAN
DosHandleIoctl(BYTE ControlCode
, WORD FileHandle
)
1393 HANDLE Handle
= DosGetRealHandle(FileHandle
);
1395 if (Handle
== INVALID_HANDLE_VALUE
)
1398 DosLastError
= ERROR_FILE_NOT_FOUND
;
1402 switch (ControlCode
)
1404 /* Get Device Information */
1410 * See Ralf Brown: http://www.ctyme.com/intr/rb-2820.htm
1411 * for a list of possible flags.
1414 if (Handle
== DosSystemFileTable
[DOS_INPUT_HANDLE
].Handle
)
1419 /* It is a device */
1422 else if (Handle
== DosSystemFileTable
[DOS_OUTPUT_HANDLE
].Handle
)
1424 /* Console output */
1427 /* It is a device */
1431 /* Return the device information word */
1436 /* Unsupported control code */
1439 DPRINT1("Unsupported IOCTL: 0x%02X\n", ControlCode
);
1441 DosLastError
= ERROR_INVALID_PARAMETER
;
1447 VOID WINAPI
DosInt20h(LPWORD Stack
)
1449 /* This is the exit interrupt */
1450 DosTerminateProcess(Stack
[STACK_CS
], 0);
1453 VOID WINAPI
DosInt21h(LPWORD Stack
)
1456 SYSTEMTIME SystemTime
;
1458 PDOS_INPUT_BUFFER InputBuffer
;
1460 /* Check the value in the AH register */
1463 /* Terminate Program */
1466 DosTerminateProcess(Stack
[STACK_CS
], 0);
1470 /* Read Character from STDIN with Echo */
1473 DPRINT("INT 21h, AH = 01h\n");
1475 // FIXME: Under DOS 2+, input / output handle may be redirected!!!!
1477 Character
= DosReadCharacter(DOS_INPUT_HANDLE
);
1480 // FIXME: Check whether Ctrl-C / Ctrl-Break is pressed, and call INT 23h if so.
1481 // Check also Ctrl-P and set echo-to-printer flag.
1482 // Ctrl-Z is not interpreted.
1488 /* Write Character to STDOUT */
1491 // FIXME: Under DOS 2+, output handle may be redirected!!!!
1492 Character
= getDL();
1493 DosPrintCharacter(DOS_OUTPUT_HANDLE
, Character
);
1496 * We return the output character (DOS 2.1+).
1497 * Also, if we're going to output a TAB, then
1498 * don't return a TAB but a SPACE instead.
1499 * See Ralf Brown: http://www.ctyme.com/intr/rb-2554.htm
1500 * for more information.
1502 setAL(Character
== '\t' ? ' ' : Character
);
1506 /* Read Character from STDAUX */
1509 // FIXME: Really read it from STDAUX!
1510 DPRINT1("INT 16h, 03h: Read character from STDAUX is HALFPLEMENTED\n");
1511 // setAL(DosReadCharacter());
1515 /* Write Character to STDAUX */
1518 // FIXME: Really write it to STDAUX!
1519 DPRINT1("INT 16h, 04h: Write character to STDAUX is HALFPLEMENTED\n");
1520 // DosPrintCharacter(getDL());
1524 /* Write Character to Printer */
1527 // FIXME: Really write it to printer!
1528 DPRINT1("INT 16h, 05h: Write character to printer is HALFPLEMENTED -\n\n");
1529 DPRINT1("0x%p\n", getDL());
1530 DPRINT1("\n\n-----------\n\n");
1534 /* Direct Console I/O */
1537 Character
= getDL();
1539 // FIXME: Under DOS 2+, output handle may be redirected!!!!
1541 if (Character
!= 0xFF)
1544 DosPrintCharacter(DOS_OUTPUT_HANDLE
, Character
);
1547 * We return the output character (DOS 2.1+).
1548 * See Ralf Brown: http://www.ctyme.com/intr/rb-2558.htm
1549 * for more information.
1556 if (DosCheckInput())
1558 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_ZF
;
1559 setAL(DosReadCharacter(DOS_INPUT_HANDLE
));
1563 /* No character available */
1564 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_ZF
;
1572 /* Character Input without Echo */
1576 DPRINT("Char input without echo\n");
1578 // FIXME: Under DOS 2+, input handle may be redirected!!!!
1579 Character
= DosReadCharacter(DOS_INPUT_HANDLE
);
1581 // FIXME: For 0x07, do not check Ctrl-C/Break.
1582 // For 0x08, do check those control sequences and if needed,
1585 // /* Let the BOP repeat if needed */
1586 // if (getCF()) break;
1592 /* Write string to STDOUT */
1595 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1597 while (*String
!= '$')
1599 DosPrintCharacter(DOS_OUTPUT_HANDLE
, *String
);
1604 * We return the terminating character (DOS 2.1+).
1605 * See Ralf Brown: http://www.ctyme.com/intr/rb-2562.htm
1606 * for more information.
1608 setAL('$'); // *String
1612 /* Read Buffered Input */
1616 InputBuffer
= (PDOS_INPUT_BUFFER
)SEG_OFF_TO_PTR(getDS(), getDX());
1618 DPRINT("Read Buffered Input\n");
1620 while (Count
< InputBuffer
->MaxLength
)
1622 // FIXME!! This function should interpret backspaces etc...
1624 /* Try to read a character (wait) */
1625 Character
= DosReadCharacter(DOS_INPUT_HANDLE
);
1627 // FIXME: Check whether Ctrl-C / Ctrl-Break is pressed, and call INT 23h if so.
1629 /* Echo the character and append it to the buffer */
1630 DosPrintCharacter(DOS_OUTPUT_HANDLE
, Character
);
1631 InputBuffer
->Buffer
[Count
] = Character
;
1633 Count
++; /* Carriage returns are also counted */
1635 if (Character
== '\r') break;
1638 /* Update the length */
1639 InputBuffer
->Length
= Count
;
1644 /* Get STDIN Status */
1647 setAL(DosCheckInput() ? 0xFF : 0x00);
1651 /* Flush Buffer and Read STDIN */
1654 BYTE InputFunction
= getAL();
1656 /* Flush STDIN buffer */
1657 DosFlushFileBuffers(DOS_INPUT_HANDLE
);
1660 * If the input function number contained in AL is valid, i.e.
1661 * AL == 0x01 or 0x06 or 0x07 or 0x08 or 0x0A, call ourselves
1662 * recursively with AL == AH.
1664 if (InputFunction
== 0x01 || InputFunction
== 0x06 ||
1665 InputFunction
== 0x07 || InputFunction
== 0x08 ||
1666 InputFunction
== 0x0A)
1668 /* Call ourselves recursively */
1669 setAH(InputFunction
);
1678 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1680 // TODO: Flush what's needed.
1681 DPRINT1("INT 21h, 0Dh is UNIMPLEMENTED\n");
1683 /* Clear CF in DOS 6 only */
1684 if (PspBlock
->DosVersion
== 0x0006)
1685 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1690 /* Set Default Drive */
1693 DosChangeDrive(getDL());
1694 setAL(LastDrive
- 'A' + 1);
1698 /* NULL Function for CP/M Compatibility */
1702 * This function corresponds to the CP/M BDOS function
1703 * "get bit map of logged drives", which is meaningless
1706 * For: PTS-DOS 6.51 & S/DOS 1.0 - EXTENDED RENAME FILE USING FCB
1707 * See Ralf Brown: http://www.ctyme.com/intr/rb-2584.htm
1708 * for more information.
1714 /* Get Default Drive */
1717 setAL(CurrentDrive
);
1721 /* Set Disk Transfer Area */
1724 DiskTransferArea
= MAKELONG(getDX(), getDS());
1728 /* NULL Function for CP/M Compatibility */
1733 * Function 0x1D corresponds to the CP/M BDOS function
1734 * "get bit map of read-only drives", which is meaningless
1736 * See Ralf Brown: http://www.ctyme.com/intr/rb-2592.htm
1737 * for more information.
1739 * Function 0x1E corresponds to the CP/M BDOS function
1740 * "set file attributes", which was meaningless under MS-DOS 1.x.
1741 * See Ralf Brown: http://www.ctyme.com/intr/rb-2593.htm
1742 * for more information.
1748 /* NULL Function for CP/M Compatibility */
1752 * This function corresponds to the CP/M BDOS function
1753 * "get/set default user (sublibrary) number", which is meaningless
1756 * For: S/DOS 1.0+ & PTS-DOS 6.51+ - GET OEM REVISION
1757 * See Ralf Brown: http://www.ctyme.com/intr/rb-2596.htm
1758 * for more information.
1764 /* Set Interrupt Vector */
1767 ULONG FarPointer
= MAKELONG(getDX(), getDS());
1768 DPRINT1("Setting interrupt 0x%02X to %04X:%04X ...\n",
1769 getAL(), HIWORD(FarPointer
), LOWORD(FarPointer
));
1771 /* Write the new far pointer to the IDT */
1772 ((PULONG
)BaseAddress
)[getAL()] = FarPointer
;
1776 /* Create New PSP */
1779 DPRINT1("INT 21h, AH = 26h - Create New PSP is UNIMPLEMENTED\n");
1783 /* Get System Date */
1786 GetLocalTime(&SystemTime
);
1787 setCX(SystemTime
.wYear
);
1788 setDX(MAKEWORD(SystemTime
.wDay
, SystemTime
.wMonth
));
1789 setAL(SystemTime
.wDayOfWeek
);
1793 /* Set System Date */
1796 GetLocalTime(&SystemTime
);
1797 SystemTime
.wYear
= getCX();
1798 SystemTime
.wMonth
= getDH();
1799 SystemTime
.wDay
= getDL();
1801 /* Return success or failure */
1802 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1806 /* Get System Time */
1809 GetLocalTime(&SystemTime
);
1810 setCX(MAKEWORD(SystemTime
.wMinute
, SystemTime
.wHour
));
1811 setDX(MAKEWORD(SystemTime
.wMilliseconds
/ 10, SystemTime
.wSecond
));
1815 /* Set System Time */
1818 GetLocalTime(&SystemTime
);
1819 SystemTime
.wHour
= getCH();
1820 SystemTime
.wMinute
= getCL();
1821 SystemTime
.wSecond
= getDH();
1822 SystemTime
.wMilliseconds
= getDL() * 10; // In hundredths of seconds
1824 /* Return success or failure */
1825 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1829 /* Get Disk Transfer Area */
1832 setES(HIWORD(DiskTransferArea
));
1833 setBX(LOWORD(DiskTransferArea
));
1837 /* Get DOS Version */
1840 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1843 * DOS 2+ - GET DOS VERSION
1844 * See Ralf Brown: http://www.ctyme.com/intr/rb-2711.htm
1845 * for more information.
1848 if (LOBYTE(PspBlock
->DosVersion
) < 5 || getAL() == 0x00)
1851 * Return DOS OEM number:
1852 * 0x00 for IBM PC-DOS
1853 * 0x02 for packaged MS-DOS
1859 if (LOBYTE(PspBlock
->DosVersion
) >= 5 && getAL() == 0x01)
1862 * Return version flag:
1863 * 1 << 3 if DOS is in ROM,
1864 * 0 (reserved) if not.
1869 /* Return DOS 24-bit user serial number in BL:CX */
1874 * Return DOS version: Minor:Major in AH:AL
1875 * The Windows NT DOS box returns version 5.00, subject to SETVER.
1877 setAX(PspBlock
->DosVersion
);
1882 /* Extended functionalities */
1885 if (getAL() == 0x06)
1888 * DOS 5+ - GET TRUE VERSION NUMBER
1889 * This function always returns the true version number, unlike
1890 * AH=30h, whose return value may be changed with SETVER.
1891 * See Ralf Brown: http://www.ctyme.com/intr/rb-2730.htm
1892 * for more information.
1896 * Return the true DOS version: Minor:Major in BH:BL
1897 * The Windows NT DOS box returns BX=3205h (version 5.50).
1899 setBX(NTDOS_VERSION
);
1901 /* DOS revision 0 */
1909 // /* Invalid subfunction */
1916 /* Get Interrupt Vector */
1919 DWORD FarPointer
= ((PDWORD
)BaseAddress
)[getAL()];
1921 /* Read the address from the IDT into ES:BX */
1922 setES(HIWORD(FarPointer
));
1923 setBX(LOWORD(FarPointer
));
1927 /* SWITCH character - AVAILDEV */
1930 if (getAL() == 0x00)
1933 * DOS 2+ - "SWITCHAR" - GET SWITCH CHARACTER
1934 * This setting is ignored by MS-DOS 4.0+.
1935 * MS-DOS 5+ always return AL=00h/DL=2Fh.
1936 * See Ralf Brown: http://www.ctyme.com/intr/rb-2752.htm
1937 * for more information.
1942 else if (getAL() == 0x01)
1945 * DOS 2+ - "SWITCHAR" - SET SWITCH CHARACTER
1946 * This setting is ignored by MS-DOS 5+.
1947 * See Ralf Brown: http://www.ctyme.com/intr/rb-2753.htm
1948 * for more information.
1953 else if (getAL() == 0x02)
1956 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1957 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1958 * for more information.
1963 else if (getAL() == 0x03)
1966 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1967 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1968 * for more information.
1975 /* Invalid subfunction */
1982 /* Create Directory */
1985 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1987 if (CreateDirectoryA(String
, NULL
))
1989 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1993 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1994 setAX(LOWORD(GetLastError()));
2000 /* Remove Directory */
2003 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
2005 if (RemoveDirectoryA(String
))
2007 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2011 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2012 setAX(LOWORD(GetLastError()));
2018 /* Set Current Directory */
2021 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
2023 if (DosChangeDirectory(String
))
2025 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2029 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2030 setAX(DosLastError
);
2036 /* Create or Truncate File */
2040 WORD ErrorCode
= DosCreateFile(&FileHandle
,
2041 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
2045 if (ErrorCode
== ERROR_SUCCESS
)
2047 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2052 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2063 WORD ErrorCode
= DosOpenFile(&FileHandle
,
2064 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
2067 if (ErrorCode
== ERROR_SUCCESS
)
2069 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2074 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2084 if (DosCloseHandle(getBX()))
2086 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2090 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2091 setAX(ERROR_INVALID_HANDLE
);
2097 /* Read from File or Device */
2103 DPRINT("INT 21h, AH = 3Fh\n");
2106 ErrorCode
= DosReadFile(getBX(),
2107 SEG_OFF_TO_PTR(getDS(), getDX()),
2112 if (ErrorCode
== ERROR_SUCCESS
)
2114 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2117 else if (ErrorCode
!= ERROR_NOT_READY
)
2119 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2126 /* Write to File or Device */
2129 WORD BytesWritten
= 0;
2130 WORD ErrorCode
= DosWriteFile(getBX(),
2131 SEG_OFF_TO_PTR(getDS(), getDX()),
2135 if (ErrorCode
== ERROR_SUCCESS
)
2137 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2138 setAX(BytesWritten
);
2142 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2152 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2154 if (demFileDelete(FileName
) == ERROR_SUCCESS
)
2156 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2158 * See Ralf Brown: http://www.ctyme.com/intr/rb-2797.htm
2159 * "AX destroyed (DOS 3.3) AL seems to be drive of deleted file."
2161 setAL(FileName
[0] - 'A');
2165 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2166 setAX(GetLastError());
2176 WORD ErrorCode
= DosSeekFile(getBX(),
2177 MAKELONG(getDX(), getCX()),
2181 if (ErrorCode
== ERROR_SUCCESS
)
2183 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2185 /* Return the new offset in DX:AX */
2186 setDX(HIWORD(NewLocation
));
2187 setAX(LOWORD(NewLocation
));
2191 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2198 /* Get/Set File Attributes */
2202 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2204 if (getAL() == 0x00)
2206 /* Get the attributes */
2207 Attributes
= GetFileAttributesA(FileName
);
2209 /* Check if it failed */
2210 if (Attributes
== INVALID_FILE_ATTRIBUTES
)
2212 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2213 setAX(GetLastError());
2217 /* Return the attributes that DOS can understand */
2218 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2219 setCX(Attributes
& 0x00FF);
2222 else if (getAL() == 0x01)
2224 /* Try to set the attributes */
2225 if (SetFileAttributesA(FileName
, getCL()))
2227 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2231 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2232 setAX(GetLastError());
2237 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2238 setAX(ERROR_INVALID_FUNCTION
);
2247 if (DosHandleIoctl(getAL(), getBX()))
2249 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2253 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2254 setAX(DosLastError
);
2260 /* Duplicate Handle */
2264 HANDLE Handle
= DosGetRealHandle(getBX());
2266 if (Handle
== INVALID_HANDLE_VALUE
)
2268 /* The handle is invalid */
2269 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2270 setAX(ERROR_INVALID_HANDLE
);
2274 /* Open a new handle to the same entry */
2275 NewHandle
= DosOpenHandle(Handle
);
2277 if (NewHandle
== INVALID_DOS_HANDLE
)
2279 /* Too many files open */
2280 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2281 setAX(ERROR_TOO_MANY_OPEN_FILES
);
2285 /* Return the result */
2286 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2291 /* Force Duplicate Handle */
2294 if (DosDuplicateHandle(getBX(), getCX()))
2296 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2300 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2301 setAX(ERROR_INVALID_HANDLE
);
2307 /* Get Current Directory */
2310 BYTE DriveNumber
= getDL();
2311 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getSI());
2313 /* Get the real drive number */
2314 if (DriveNumber
== 0)
2316 DriveNumber
= CurrentDrive
;
2320 /* Decrement DriveNumber since it was 1-based */
2324 if (DriveNumber
<= LastDrive
- 'A')
2327 * Copy the current directory into the target buffer.
2328 * It doesn't contain the drive letter and the backslash.
2330 strncpy(String
, CurrentDirectories
[DriveNumber
], DOS_DIR_LENGTH
);
2331 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2332 setAX(0x0100); // Undocumented, see Ralf Brown: http://www.ctyme.com/intr/rb-2933.htm
2336 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2337 setAX(ERROR_INVALID_DRIVE
);
2343 /* Allocate Memory */
2346 WORD MaxAvailable
= 0;
2347 WORD Segment
= DosAllocateMemory(getBX(), &MaxAvailable
);
2351 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2356 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2357 setAX(DosLastError
);
2358 setBX(MaxAvailable
);
2367 if (DosFreeMemory(getES()))
2369 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2373 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2374 setAX(ERROR_ARENA_TRASHED
);
2380 /* Resize Memory Block */
2385 if (DosResizeMemory(getES(), getBX(), &Size
))
2387 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2391 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2392 setAX(DosLastError
);
2403 DOS_EXEC_TYPE LoadType
= (DOS_EXEC_TYPE
)getAL();
2404 LPSTR ProgramName
= SEG_OFF_TO_PTR(getDS(), getDX());
2405 PDOS_EXEC_PARAM_BLOCK ParamBlock
= SEG_OFF_TO_PTR(getES(), getBX());
2406 WORD ErrorCode
= DosCreateProcess(LoadType
, ProgramName
, ParamBlock
);
2408 if (ErrorCode
== ERROR_SUCCESS
)
2410 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2414 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2422 /* Terminate With Return Code */
2425 DosTerminateProcess(CurrentPsp
, getAL());
2429 /* Get Return Code (ERRORLEVEL) */
2433 * According to Ralf Brown: http://www.ctyme.com/intr/rb-2976.htm
2434 * DosErrorLevel is cleared after being read by this function.
2436 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2437 setAX(DosErrorLevel
);
2438 DosErrorLevel
= 0x0000; // Clear it
2442 /* Find First File */
2445 WORD Result
= (WORD
)demFileFindFirst(FAR_POINTER(DiskTransferArea
),
2446 SEG_OFF_TO_PTR(getDS(), getDX()),
2451 if (Result
== ERROR_SUCCESS
)
2452 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2454 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2459 /* Find Next File */
2462 WORD Result
= (WORD
)demFileFindNext(FAR_POINTER(DiskTransferArea
));
2466 if (Result
== ERROR_SUCCESS
)
2467 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2469 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2474 /* Internal - Set Current Process ID (Set PSP Address) */
2477 // FIXME: Is it really what it's done ??
2478 CurrentPsp
= getBX();
2482 /* Internal - Get Current Process ID (Get PSP Address) */
2484 /* Get Current PSP Address */
2488 * Undocumented AH=51h is identical to the documented AH=62h.
2489 * See Ralf Brown: http://www.ctyme.com/intr/rb-2982.htm
2490 * and http://www.ctyme.com/intr/rb-3140.htm
2491 * for more information.
2497 /* Internal - Get "List of lists" (SYSVARS) */
2501 * On return, ES points at the DOS data segment (see also INT 2F/AX=1203h).
2502 * See Ralf Brown: http://www.ctyme.com/intr/rb-2983.htm
2503 * for more information.
2506 /* Return the DOS "list of lists" in ES:BX */
2510 DisplayMessage(L
"Required for AARD code, do you remember? :P");
2517 LPSTR ExistingFileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2518 LPSTR NewFileName
= (LPSTR
)SEG_OFF_TO_PTR(getES(), getDI());
2521 * See Ralf Brown: http://www.ctyme.com/intr/rb-2990.htm
2522 * for more information.
2525 if (MoveFileA(ExistingFileName
, NewFileName
))
2527 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2531 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2532 setAX(GetLastError());
2538 /* Get/Set Memory Management Options */
2541 if (getAL() == 0x00)
2543 /* Get allocation strategy */
2544 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2545 setAX(DosAllocStrategy
);
2547 else if (getAL() == 0x01)
2549 /* Set allocation strategy */
2551 if ((getBL() & (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2552 == (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2554 /* Can't set both */
2555 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2556 setAX(ERROR_INVALID_PARAMETER
);
2560 if ((getBL() & 0x3F) > DOS_ALLOC_LAST_FIT
)
2562 /* Invalid allocation strategy */
2563 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2564 setAX(ERROR_INVALID_PARAMETER
);
2568 DosAllocStrategy
= getBL();
2569 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2571 else if (getAL() == 0x02)
2573 /* Get UMB link state */
2574 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2575 setAL(DosUmbLinked
? 0x01 : 0x00);
2577 else if (getAL() == 0x03)
2579 /* Set UMB link state */
2580 if (getBX()) DosLinkUmb();
2581 else DosUnlinkUmb();
2582 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2586 /* Invalid or unsupported function */
2587 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2588 setAX(ERROR_INVALID_FUNCTION
);
2594 /* Get Extended Error Information */
2597 DPRINT1("INT 21h, AH = 59h, BX = %04Xh - Get Extended Error Information is UNIMPLEMENTED\n",
2602 /* Create Temporary File */
2605 LPSTR PathName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2606 LPSTR FileName
= PathName
; // The buffer for the path and the full file name is the same.
2612 * See Ralf Brown: http://www.ctyme.com/intr/rb-3014.htm
2613 * for more information.
2616 // FIXME: Check for buffer validity?
2617 // It should be a ASCIZ path ending with a '\' + 13 zero bytes
2618 // to receive the generated filename.
2620 /* First create the temporary file */
2621 uRetVal
= GetTempFileNameA(PathName
, NULL
, 0, FileName
);
2624 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2625 setAX(GetLastError());
2629 /* Now try to open it in read/write access */
2630 ErrorCode
= DosOpenFile(&FileHandle
, FileName
, 2);
2631 if (ErrorCode
== ERROR_SUCCESS
)
2633 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2638 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2645 /* Create New File */
2649 WORD ErrorCode
= DosCreateFile(&FileHandle
,
2650 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
2654 if (ErrorCode
== ERROR_SUCCESS
)
2656 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2661 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2668 /* Lock/Unlock Region of File */
2671 HANDLE Handle
= DosGetRealHandle(getBX());
2673 if (Handle
== INVALID_HANDLE_VALUE
)
2675 /* The handle is invalid */
2676 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2677 setAX(ERROR_INVALID_HANDLE
);
2681 if (getAL() == 0x00)
2683 /* Lock region of file */
2684 if (LockFile(Handle
,
2685 MAKELONG(getCX(), getDX()), 0,
2686 MAKELONG(getSI(), getDI()), 0))
2688 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2692 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2693 setAX(GetLastError());
2696 else if (getAL() == 0x01)
2698 /* Unlock region of file */
2699 if (UnlockFile(Handle
,
2700 MAKELONG(getCX(), getDX()), 0,
2701 MAKELONG(getSI(), getDI()), 0))
2703 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2707 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2708 setAX(GetLastError());
2713 /* Invalid subfunction */
2714 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2715 setAX(ERROR_INVALID_FUNCTION
);
2721 /* Canonicalize File Name or Path */
2725 * See Ralf Brown: http://www.ctyme.com/intr/rb-3137.htm
2726 * for more information.
2730 * We suppose that the DOS app gave to us a valid
2731 * 128-byte long buffer for the canonicalized name.
2733 DWORD dwRetVal
= GetFullPathNameA(SEG_OFF_TO_PTR(getDS(), getSI()),
2735 SEG_OFF_TO_PTR(getES(), getDI()),
2739 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2740 setAX(GetLastError());
2744 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2748 // FIXME: Convert the full path name into short version.
2749 // We cannot reliably use GetShortPathName, because it fails
2750 // if the path name given doesn't exist. However this DOS
2751 // function AH=60h should be able to work even for non-existing
2752 // path and file names.
2757 /* Set Handle Count */
2760 if (!DosResizeHandleTable(getBX()))
2762 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2763 setAX(DosLastError
);
2765 else Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2775 * Function 6Ah is identical to function 68h,
2776 * and sets AH to 68h if success.
2777 * See Ralf Brown: http://www.ctyme.com/intr/rb-3176.htm
2778 * for more information.
2782 if (DosFlushFileBuffers(getBX()))
2784 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2788 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2789 setAX(GetLastError());
2795 /* Extended Open/Create */
2799 WORD CreationStatus
;
2802 /* Check for AL == 00 */
2803 if (getAL() != 0x00)
2805 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2806 setAX(ERROR_INVALID_FUNCTION
);
2811 * See Ralf Brown: http://www.ctyme.com/intr/rb-3179.htm
2812 * for the full detailed description.
2814 * WARNING: BH contains some extended flags that are NOT SUPPORTED.
2817 ErrorCode
= DosCreateFileEx(&FileHandle
,
2819 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getSI()),
2824 if (ErrorCode
== ERROR_SUCCESS
)
2826 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2827 setCX(CreationStatus
);
2832 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2842 DPRINT1("DOS Function INT 0x21, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2845 setAL(0); // Some functions expect AL to be 0 when it's not supported.
2846 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2851 VOID WINAPI
DosBreakInterrupt(LPWORD Stack
)
2853 UNREFERENCED_PARAMETER(Stack
);
2855 /* Stop the VDM task */
2856 ResetEvent(VdmTaskEvent
);
2860 VOID WINAPI
DosFastConOut(LPWORD Stack
)
2863 * This is the DOS 2+ Fast Console Output Interrupt.
2864 * The default handler under DOS 2.x and 3.x simply calls INT 10h/AH=0Eh.
2866 * See Ralf Brown: http://www.ctyme.com/intr/rb-4124.htm
2867 * for more information.
2870 /* Save AX and BX */
2871 USHORT AX
= getAX();
2872 USHORT BX
= getBX();
2875 * Set the parameters:
2876 * AL contains the character to print (already set),
2877 * BL contains the character attribute,
2878 * BH contains the video page to use.
2880 setBL(DOS_CHAR_ATTRIBUTE
);
2881 setBH(Bda
->VideoPage
);
2883 /* Call the BIOS INT 10h, AH=0Eh "Teletype Output" */
2885 Int32Call(&DosContext
, BIOS_VIDEO_INTERRUPT
);
2887 /* Restore AX and BX */
2892 VOID WINAPI
DosInt2Fh(LPWORD Stack
)
2894 DPRINT1("DOS Internal System Function INT 0x2F, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2896 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2899 BOOLEAN
DosKRNLInitialize(VOID
)
2905 CHAR CurrentDirectory
[MAX_PATH
];
2906 CHAR DosDirectory
[DOS_DIR_LENGTH
];
2912 /* Clear the current directory buffer */
2913 RtlZeroMemory(CurrentDirectories
, sizeof(CurrentDirectories
));
2915 /* Get the current directory */
2916 if (!GetCurrentDirectoryA(MAX_PATH
, CurrentDirectory
))
2918 // TODO: Use some kind of default path?
2922 /* Convert that to a DOS path */
2923 if (!GetShortPathNameA(CurrentDirectory
, DosDirectory
, DOS_DIR_LENGTH
))
2925 // TODO: Use some kind of default path?
2930 CurrentDrive
= DosDirectory
[0] - 'A';
2932 /* Get the directory part of the path */
2933 Path
= strchr(DosDirectory
, '\\');
2936 /* Skip the backslash */
2940 /* Set the directory */
2943 strncpy(CurrentDirectories
[CurrentDrive
], Path
, DOS_DIR_LENGTH
);
2946 /* Read CONFIG.SYS */
2947 Stream
= _wfopen(DOS_CONFIG_PATH
, L
"r");
2950 while (fgetws(Buffer
, 256, Stream
))
2952 // TODO: Parse the line
2957 /* Initialize the SFT */
2958 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
2960 DosSystemFileTable
[i
].Handle
= INVALID_HANDLE_VALUE
;
2961 DosSystemFileTable
[i
].RefCount
= 0;
2964 /* Get handles to standard I/O devices */
2965 DosSystemFileTable
[0].Handle
= GetStdHandle(STD_INPUT_HANDLE
);
2966 DosSystemFileTable
[1].Handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2967 DosSystemFileTable
[2].Handle
= GetStdHandle(STD_ERROR_HANDLE
);
2969 /* Initialize the reference counts */
2970 DosSystemFileTable
[0].RefCount
=
2971 DosSystemFileTable
[1].RefCount
=
2972 DosSystemFileTable
[2].RefCount
= 1;
2976 /* Initialize the callback context */
2977 InitializeContext(&DosContext
, 0x0070, 0x0000);
2979 /* Register the DOS 32-bit Interrupts */
2980 RegisterDosInt32(0x20, DosInt20h
);
2981 RegisterDosInt32(0x21, DosInt21h
);
2982 // RegisterDosInt32(0x22, DosInt22h ); // Termination
2983 RegisterDosInt32(0x23, DosBreakInterrupt
); // Ctrl-C / Ctrl-Break
2984 // RegisterDosInt32(0x24, DosInt24h ); // Critical Error
2985 RegisterDosInt32(0x29, DosFastConOut
); // DOS 2+ Fast Console Output
2986 RegisterDosInt32(0x2F, DosInt2Fh
);