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(LPCSTR Environment
, LPCSTR ProgramName
)
408 PCHAR Ptr
, DestBuffer
= NULL
;
412 Ptr
= (PCHAR
)Environment
;
414 /* Calculate the size of the environment block */
415 while (*Ptr
) Ptr
+= strlen(Ptr
) + 1;
416 TotalSize
= (ULONG_PTR
)Ptr
- (ULONG_PTR
)Environment
+ 1; // Add final NULL-terminator
418 /* Add the string buffer size */
419 TotalSize
+= strlen(ProgramName
) + 1;
421 /* Add the two extra bytes */
424 /* Allocate the memory for the environment block */
425 DestSegment
= DosAllocateMemory((WORD
)((TotalSize
+ 0x0F) >> 4), NULL
);
426 if (!DestSegment
) return 0;
428 Ptr
= (PCHAR
)Environment
;
430 DestBuffer
= (PCHAR
)SEG_OFF_TO_PTR(DestSegment
, 0);
433 /* Copy the string and NULL-terminate it */
434 strcpy(DestBuffer
, Ptr
);
435 DestBuffer
+= strlen(Ptr
);
436 *(DestBuffer
++) = '\0';
438 /* Move to the next string */
439 Ptr
+= strlen(Ptr
) + 1;
441 /* NULL-terminate the environment block */
442 *(DestBuffer
++) = '\0';
444 /* Store the special program name tag */
445 *(DestBuffer
++) = LOBYTE(DOS_PROGRAM_NAME_TAG
);
446 *(DestBuffer
++) = HIBYTE(DOS_PROGRAM_NAME_TAG
);
448 /* Copy the program name after the environment block */
449 strcpy(DestBuffer
, ProgramName
);
459 /* Taken from base/shell/cmd/console.c */
460 BOOL
IsConsoleHandle(HANDLE hHandle
)
464 /* Check whether the handle may be that of a console... */
465 if ((GetFileType(hHandle
) & FILE_TYPE_CHAR
) == 0) return FALSE
;
468 * It may be. Perform another test... The idea comes from the
469 * MSDN description of the WriteConsole API:
471 * "WriteConsole fails if it is used with a standard handle
472 * that is redirected to a file. If an application processes
473 * multilingual output that can be redirected, determine whether
474 * the output handle is a console handle (one method is to call
475 * the GetConsoleMode function and check whether it succeeds).
476 * If the handle is a console handle, call WriteConsole. If the
477 * handle is not a console handle, the output is redirected and
478 * you should call WriteFile to perform the I/O."
480 return GetConsoleMode(hHandle
, &dwMode
);
483 WORD
DosOpenHandle(HANDLE Handle
)
490 /* The system PSP has no handle table */
491 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_DOS_HANDLE
;
493 /* Get a pointer to the handle table */
494 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
495 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
497 /* Find a free entry in the JFT */
498 for (DosHandle
= 0; DosHandle
< PspBlock
->HandleTableSize
; DosHandle
++)
500 if (HandleTable
[DosHandle
] == 0xFF) break;
503 /* If there are no free entries, fail */
504 if (DosHandle
== PspBlock
->HandleTableSize
) return INVALID_DOS_HANDLE
;
506 /* Check if the handle is already in the SFT */
507 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
509 /* Check if this is the same handle */
510 if (DosSystemFileTable
[i
].Handle
!= Handle
) continue;
512 /* Already in the table, reference it */
513 DosSystemFileTable
[i
].RefCount
++;
515 /* Set the JFT entry to that SFT index */
516 HandleTable
[DosHandle
] = i
;
518 /* Return the new handle */
522 /* Add the handle to the SFT */
523 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
525 /* Make sure this is an empty table entry */
526 if (DosSystemFileTable
[i
].Handle
!= INVALID_HANDLE_VALUE
) continue;
528 /* Initialize the empty table entry */
529 DosSystemFileTable
[i
].Handle
= Handle
;
530 DosSystemFileTable
[i
].RefCount
= 1;
532 /* Set the JFT entry to that SFT index */
533 HandleTable
[DosHandle
] = i
;
535 /* Return the new handle */
539 /* The SFT is full */
540 return INVALID_DOS_HANDLE
;
543 HANDLE
DosGetRealHandle(WORD DosHandle
)
548 /* The system PSP has no handle table */
549 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_HANDLE_VALUE
;
551 /* Get a pointer to the handle table */
552 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
553 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
555 /* Make sure the handle is open */
556 if (HandleTable
[DosHandle
] == 0xFF) return INVALID_HANDLE_VALUE
;
558 /* Return the Win32 handle */
559 return DosSystemFileTable
[HandleTable
[DosHandle
]].Handle
;
562 static VOID
DosCopyHandleTable(LPBYTE DestinationTable
)
568 /* Clear the table first */
569 for (i
= 0; i
< 20; i
++) DestinationTable
[i
] = 0xFF;
571 /* Check if this is the initial process */
572 if (CurrentPsp
== SYSTEM_PSP
)
574 /* Set up the standard I/O devices */
575 for (i
= 0; i
<= 2; i
++)
577 /* Set the index in the SFT */
578 DestinationTable
[i
] = (BYTE
)i
;
580 /* Increase the reference count */
581 DosSystemFileTable
[i
].RefCount
++;
588 /* Get the parent PSP block and handle table */
589 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
590 SourceTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
592 /* Copy the first 20 handles into the new table */
593 for (i
= 0; i
< 20; i
++)
595 DestinationTable
[i
] = SourceTable
[i
];
597 /* Increase the reference count */
598 DosSystemFileTable
[SourceTable
[i
]].RefCount
++;
602 static BOOLEAN
DosResizeHandleTable(WORD NewSize
)
608 /* Get the PSP block */
609 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
611 if (NewSize
== PspBlock
->HandleTableSize
)
617 if (PspBlock
->HandleTableSize
> 20)
619 /* Get the segment of the current table */
620 Segment
= (LOWORD(PspBlock
->HandleTablePtr
) >> 4) + HIWORD(PspBlock
->HandleTablePtr
);
624 /* Get the current handle table */
625 HandleTable
= FAR_POINTER(PspBlock
->HandleTablePtr
);
627 /* Copy it to the PSP */
628 RtlCopyMemory(PspBlock
->HandleTable
, HandleTable
, NewSize
);
630 /* Free the memory */
631 DosFreeMemory(Segment
);
633 /* Update the handle table pointer and size */
634 PspBlock
->HandleTableSize
= NewSize
;
635 PspBlock
->HandleTablePtr
= MAKELONG(0x18, CurrentPsp
);
639 /* Resize the memory */
640 if (!DosResizeMemory(Segment
, NewSize
, NULL
))
642 /* Unable to resize, try allocating it somewhere else */
643 Segment
= DosAllocateMemory(NewSize
, NULL
);
644 if (Segment
== 0) return FALSE
;
646 /* Get the new handle table */
647 HandleTable
= SEG_OFF_TO_PTR(Segment
, 0);
649 /* Copy the handles to the new table */
650 RtlCopyMemory(HandleTable
,
651 FAR_POINTER(PspBlock
->HandleTablePtr
),
652 PspBlock
->HandleTableSize
);
654 /* Update the handle table pointer */
655 PspBlock
->HandleTablePtr
= MAKELONG(0, Segment
);
658 /* Update the handle table size */
659 PspBlock
->HandleTableSize
= NewSize
;
662 else if (NewSize
> 20)
664 Segment
= DosAllocateMemory(NewSize
, NULL
);
665 if (Segment
== 0) return FALSE
;
667 /* Get the new handle table */
668 HandleTable
= SEG_OFF_TO_PTR(Segment
, 0);
670 /* Copy the handles from the PSP to the new table */
671 RtlCopyMemory(HandleTable
,
672 FAR_POINTER(PspBlock
->HandleTablePtr
),
673 PspBlock
->HandleTableSize
);
675 /* Update the handle table pointer and size */
676 PspBlock
->HandleTableSize
= NewSize
;
677 PspBlock
->HandleTablePtr
= MAKELONG(0, Segment
);
683 static BOOLEAN
DosCloseHandle(WORD DosHandle
)
689 DPRINT("DosCloseHandle: DosHandle 0x%04X\n", DosHandle
);
691 /* The system PSP has no handle table */
692 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
694 /* Get a pointer to the handle table */
695 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
696 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
698 /* Make sure the handle is open */
699 if (HandleTable
[DosHandle
] == 0xFF) return FALSE
;
701 /* Decrement the reference count of the SFT entry */
702 SftIndex
= HandleTable
[DosHandle
];
703 DosSystemFileTable
[SftIndex
].RefCount
--;
705 /* Check if the reference count fell to zero */
706 if (!DosSystemFileTable
[SftIndex
].RefCount
)
708 /* Close the file, it's no longer needed */
709 CloseHandle(DosSystemFileTable
[SftIndex
].Handle
);
711 /* Clear the handle */
712 DosSystemFileTable
[SftIndex
].Handle
= INVALID_HANDLE_VALUE
;
715 /* Clear the entry in the JFT */
716 HandleTable
[DosHandle
] = 0xFF;
721 static BOOLEAN
DosDuplicateHandle(WORD OldHandle
, WORD NewHandle
)
727 DPRINT("DosDuplicateHandle: OldHandle 0x%04X, NewHandle 0x%04X\n",
731 /* The system PSP has no handle table */
732 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
734 /* Get a pointer to the handle table */
735 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
736 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
738 /* Make sure the old handle is open */
739 if (HandleTable
[OldHandle
] == 0xFF) return FALSE
;
741 /* Check if the new handle is open */
742 if (HandleTable
[NewHandle
] != 0xFF)
745 DosCloseHandle(NewHandle
);
748 /* Increment the reference count of the SFT entry */
749 SftIndex
= HandleTable
[OldHandle
];
750 DosSystemFileTable
[SftIndex
].RefCount
++;
752 /* Make the new handle point to that SFT entry */
753 HandleTable
[NewHandle
] = SftIndex
;
765 static BOOLEAN
DosChangeDrive(BYTE Drive
)
767 WCHAR DirectoryPath
[DOS_CMDLINE_LENGTH
];
769 /* Make sure the drive exists */
770 if (Drive
> (LastDrive
- 'A')) return FALSE
;
772 /* Find the path to the new current directory */
773 swprintf(DirectoryPath
, L
"%c\\%S", Drive
+ 'A', CurrentDirectories
[Drive
]);
775 /* Change the current directory of the process */
776 if (!SetCurrentDirectory(DirectoryPath
)) return FALSE
;
778 /* Set the current drive */
779 CurrentDrive
= Drive
;
785 static BOOLEAN
DosChangeDirectory(LPSTR Directory
)
791 /* Make sure the directory path is not too long */
792 if (strlen(Directory
) >= DOS_DIR_LENGTH
)
794 DosLastError
= ERROR_PATH_NOT_FOUND
;
798 /* Get the drive number */
799 DriveNumber
= Directory
[0] - 'A';
801 /* Make sure the drive exists */
802 if (DriveNumber
> (LastDrive
- 'A'))
804 DosLastError
= ERROR_PATH_NOT_FOUND
;
808 /* Get the file attributes */
809 Attributes
= GetFileAttributesA(Directory
);
811 /* Make sure the path exists and is a directory */
812 if ((Attributes
== INVALID_FILE_ATTRIBUTES
)
813 || !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
815 DosLastError
= ERROR_PATH_NOT_FOUND
;
819 /* Check if this is the current drive */
820 if (DriveNumber
== CurrentDrive
)
822 /* Change the directory */
823 if (!SetCurrentDirectoryA(Directory
))
825 DosLastError
= LOWORD(GetLastError());
830 /* Get the directory part of the path */
831 Path
= strchr(Directory
, '\\');
834 /* Skip the backslash */
838 /* Set the directory for the drive */
841 strncpy(CurrentDirectories
[DriveNumber
], Path
, DOS_DIR_LENGTH
);
845 CurrentDirectories
[DriveNumber
][0] = '\0';
852 /* PUBLIC FUNCTIONS ***********************************************************/
854 VOID
DosInitializePsp(WORD PspSegment
, LPCSTR CommandLine
, WORD ProgramSize
, WORD Environment
)
856 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(PspSegment
);
857 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
859 RtlZeroMemory(PspBlock
, sizeof(*PspBlock
));
861 /* Set the exit interrupt */
862 PspBlock
->Exit
[0] = 0xCD; // int 0x20
863 PspBlock
->Exit
[1] = 0x20;
865 /* Set the number of the last paragraph */
866 PspBlock
->LastParagraph
= PspSegment
+ ProgramSize
- 1;
868 /* Save the interrupt vectors */
869 PspBlock
->TerminateAddress
= IntVecTable
[0x22];
870 PspBlock
->BreakAddress
= IntVecTable
[0x23];
871 PspBlock
->CriticalAddress
= IntVecTable
[0x24];
873 /* Set the parent PSP */
874 PspBlock
->ParentPsp
= CurrentPsp
;
876 /* Copy the parent handle table */
877 DosCopyHandleTable(PspBlock
->HandleTable
);
879 /* Set the environment block */
880 PspBlock
->EnvBlock
= Environment
;
882 /* Set the handle table pointers to the internal handle table */
883 PspBlock
->HandleTableSize
= 20;
884 PspBlock
->HandleTablePtr
= MAKELONG(0x18, PspSegment
);
886 /* Set the DOS version */
887 PspBlock
->DosVersion
= DOS_VERSION
;
889 /* Set the far call opcodes */
890 PspBlock
->FarCall
[0] = 0xCD; // int 0x21
891 PspBlock
->FarCall
[1] = 0x21;
892 PspBlock
->FarCall
[2] = 0xCB; // retf
894 /* Set the command line */
895 PspBlock
->CommandLineSize
= (BYTE
)min(strlen(CommandLine
), DOS_CMDLINE_LENGTH
- 1);
896 RtlCopyMemory(PspBlock
->CommandLine
, CommandLine
, PspBlock
->CommandLineSize
);
897 PspBlock
->CommandLine
[PspBlock
->CommandLineSize
] = '\r';
900 DWORD
DosLoadExecutable(IN DOS_EXEC_TYPE LoadType
,
901 IN LPCSTR ExecutablePath
,
902 IN LPCSTR CommandLine
,
903 IN LPCSTR Environment
,
904 OUT PDWORD StackLocation OPTIONAL
,
905 OUT PDWORD EntryPoint OPTIONAL
)
907 DWORD Result
= ERROR_SUCCESS
;
908 HANDLE FileHandle
= INVALID_HANDLE_VALUE
, FileMapping
= NULL
;
909 LPBYTE Address
= NULL
;
913 DWORD i
, FileSize
, ExeSize
;
914 PIMAGE_DOS_HEADER Header
;
915 PDWORD RelocationTable
;
917 LPSTR CmdLinePtr
= (LPSTR
)CommandLine
;
919 DPRINT("DosLoadExecutable(%d, %s, %s, %s, 0x%08X, 0x%08X)\n",
927 if (LoadType
== DOS_LOAD_OVERLAY
)
929 DPRINT1("Overlay loading is not supported yet.\n");
930 return ERROR_NOT_SUPPORTED
;
933 /* NULL-terminate the command line by removing the return carriage character */
934 while (*CmdLinePtr
&& *CmdLinePtr
!= '\r') CmdLinePtr
++;
937 /* Open a handle to the executable */
938 FileHandle
= CreateFileA(ExecutablePath
,
943 FILE_ATTRIBUTE_NORMAL
,
945 if (FileHandle
== INVALID_HANDLE_VALUE
)
947 Result
= GetLastError();
951 /* Get the file size */
952 FileSize
= GetFileSize(FileHandle
, NULL
);
954 /* Create a mapping object for the file */
955 FileMapping
= CreateFileMapping(FileHandle
,
961 if (FileMapping
== NULL
)
963 Result
= GetLastError();
967 /* Map the file into memory */
968 Address
= (LPBYTE
)MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 0);
971 Result
= GetLastError();
975 /* Copy the environment block to DOS memory */
976 EnvBlock
= DosCopyEnvironmentBlock(Environment
, ExecutablePath
);
979 Result
= ERROR_NOT_ENOUGH_MEMORY
;
983 /* Check if this is an EXE file or a COM file */
984 if (Address
[0] == 'M' && Address
[1] == 'Z')
988 /* Get the MZ header */
989 Header
= (PIMAGE_DOS_HEADER
)Address
;
991 /* Get the base size of the file, in paragraphs (rounded up) */
992 ExeSize
= (((Header
->e_cp
- 1) * 512) + Header
->e_cblp
+ 0x0F) >> 4;
994 /* Add the PSP size, in paragraphs */
995 ExeSize
+= sizeof(DOS_PSP
) >> 4;
997 /* Add the maximum size that should be allocated */
998 ExeSize
+= Header
->e_maxalloc
;
1000 /* Make sure it does not pass 0xFFFF */
1001 if (ExeSize
> 0xFFFF) ExeSize
= 0xFFFF;
1003 /* Reduce the size one by one until the allocation is successful */
1004 for (i
= Header
->e_maxalloc
; i
>= Header
->e_minalloc
; i
--, ExeSize
--)
1006 /* Try to allocate that much memory */
1007 Segment
= DosAllocateMemory((WORD
)ExeSize
, NULL
);
1008 if (Segment
!= 0) break;
1011 /* Check if at least the lowest allocation was successful */
1014 Result
= DosLastError
;
1018 /* Initialize the PSP */
1019 DosInitializePsp(Segment
,
1024 /* The process owns its own memory */
1025 DosChangeMemoryOwner(Segment
, Segment
);
1026 DosChangeMemoryOwner(EnvBlock
, Segment
);
1028 /* Copy the program to Segment:0100 */
1029 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1030 Address
+ (Header
->e_cparhdr
<< 4),
1031 min(FileSize
- (Header
->e_cparhdr
<< 4),
1032 (ExeSize
<< 4) - sizeof(DOS_PSP
)));
1034 /* Get the relocation table */
1035 RelocationTable
= (PDWORD
)(Address
+ Header
->e_lfarlc
);
1037 /* Perform relocations */
1038 for (i
= 0; i
< Header
->e_crlc
; i
++)
1040 /* Get a pointer to the word that needs to be patched */
1041 RelocWord
= (PWORD
)SEG_OFF_TO_PTR(Segment
+ HIWORD(RelocationTable
[i
]),
1042 0x100 + LOWORD(RelocationTable
[i
]));
1044 /* Add the number of the EXE segment to it */
1045 *RelocWord
+= Segment
+ (sizeof(DOS_PSP
) >> 4);
1048 if (LoadType
== DOS_LOAD_AND_EXECUTE
)
1050 /* Set the initial segment registers */
1054 /* Set the stack to the location from the header */
1055 setSS(Segment
+ (sizeof(DOS_PSP
) >> 4) + Header
->e_ss
);
1056 setSP(Header
->e_sp
);
1059 CurrentPsp
= Segment
;
1060 DiskTransferArea
= MAKELONG(0x80, Segment
);
1061 CpuExecute(Segment
+ Header
->e_cs
+ (sizeof(DOS_PSP
) >> 4),
1069 /* Find the maximum amount of memory that can be allocated */
1070 DosAllocateMemory(0xFFFF, &MaxAllocSize
);
1072 /* Make sure it's enough for the whole program and the PSP */
1073 if (((DWORD
)MaxAllocSize
<< 4) < (FileSize
+ sizeof(DOS_PSP
)))
1075 Result
= ERROR_NOT_ENOUGH_MEMORY
;
1079 /* Allocate all of it */
1080 Segment
= DosAllocateMemory(MaxAllocSize
, NULL
);
1083 Result
= DosLastError
;
1087 /* The process owns its own memory */
1088 DosChangeMemoryOwner(Segment
, Segment
);
1089 DosChangeMemoryOwner(EnvBlock
, Segment
);
1091 /* Copy the program to Segment:0100 */
1092 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1096 /* Initialize the PSP */
1097 DosInitializePsp(Segment
,
1102 if (LoadType
== DOS_LOAD_AND_EXECUTE
)
1104 /* Set the initial segment registers */
1108 /* Set the stack to the last word of the segment */
1113 * Set the value on the stack to 0, so that a near return
1114 * jumps to PSP:0000 which has the exit code.
1116 *((LPWORD
)SEG_OFF_TO_PTR(Segment
, 0xFFFE)) = 0;
1119 CurrentPsp
= Segment
;
1120 DiskTransferArea
= MAKELONG(0x80, Segment
);
1121 CpuExecute(Segment
, 0x100);
1126 if (Result
!= ERROR_SUCCESS
)
1128 /* It was not successful, cleanup the DOS memory */
1129 if (EnvBlock
) DosFreeMemory(EnvBlock
);
1130 if (Segment
) DosFreeMemory(Segment
);
1134 if (Address
!= NULL
) UnmapViewOfFile(Address
);
1136 /* Close the file mapping object */
1137 if (FileMapping
!= NULL
) CloseHandle(FileMapping
);
1139 /* Close the file handle */
1140 if (FileHandle
!= INVALID_HANDLE_VALUE
) CloseHandle(FileHandle
);
1145 DWORD
DosStartProcess(IN LPCSTR ExecutablePath
,
1146 IN LPCSTR CommandLine
,
1147 IN LPCSTR Environment
)
1151 Result
= DosLoadExecutable(DOS_LOAD_AND_EXECUTE
,
1158 if (Result
!= ERROR_SUCCESS
) goto Quit
;
1160 /* Attach to the console */
1161 VidBiosAttachToConsole(); // FIXME: And in fact, attach the full NTVDM UI to the console
1163 // HACK: Simulate a ENTER key release scancode on the PS/2 port because
1164 // some apps expect to read a key release scancode (> 0x80) when they
1166 IOWriteB(PS2_CONTROL_PORT
, 0xD2); // Next write is for the first PS/2 port
1167 IOWriteB(PS2_DATA_PORT
, 0x80 | 0x1C); // ENTER key release
1169 /* Start simulation */
1170 SetEvent(VdmTaskEvent
);
1173 /* Detach from the console */
1174 VidBiosDetachFromConsole(); // FIXME: And in fact, detach the full NTVDM UI from the console
1181 WORD
DosCreateProcess(DOS_EXEC_TYPE LoadType
,
1183 PDOS_EXEC_PARAM_BLOCK Parameters
)
1187 LPVOID Environment
= NULL
;
1188 VDM_COMMAND_INFO CommandInfo
;
1189 CHAR CmdLine
[MAX_PATH
];
1190 CHAR AppName
[MAX_PATH
];
1191 CHAR PifFile
[MAX_PATH
];
1192 CHAR Desktop
[MAX_PATH
];
1193 CHAR Title
[MAX_PATH
];
1195 STARTUPINFOA StartupInfo
;
1196 PROCESS_INFORMATION ProcessInfo
;
1198 /* Get the binary type */
1199 if (!GetBinaryTypeA(ProgramName
, &BinaryType
)) return GetLastError();
1201 /* Did the caller specify an environment segment? */
1202 if (Parameters
->Environment
)
1204 /* Yes, use it instead of the parent one */
1205 Environment
= SEG_OFF_TO_PTR(Parameters
->Environment
, 0);
1208 /* Set up the startup info structure */
1209 RtlZeroMemory(&StartupInfo
, sizeof(StartupInfo
));
1210 StartupInfo
.cb
= sizeof(StartupInfo
);
1212 /* Create the process */
1213 if (!CreateProcessA(ProgramName
,
1214 FAR_POINTER(Parameters
->CommandLine
),
1224 return GetLastError();
1227 /* Check the type of the program */
1230 /* These are handled by NTVDM */
1231 case SCS_DOS_BINARY
:
1232 case SCS_WOW_BINARY
:
1234 /* Clear the structure */
1235 RtlZeroMemory(&CommandInfo
, sizeof(CommandInfo
));
1237 /* Initialize the structure members */
1238 CommandInfo
.TaskId
= SessionId
;
1239 CommandInfo
.VDMState
= VDM_FLAG_NESTED_TASK
| VDM_FLAG_DONT_WAIT
;
1240 CommandInfo
.CmdLine
= CmdLine
;
1241 CommandInfo
.CmdLen
= sizeof(CmdLine
);
1242 CommandInfo
.AppName
= AppName
;
1243 CommandInfo
.AppLen
= sizeof(AppName
);
1244 CommandInfo
.PifFile
= PifFile
;
1245 CommandInfo
.PifLen
= sizeof(PifFile
);
1246 CommandInfo
.Desktop
= Desktop
;
1247 CommandInfo
.DesktopLen
= sizeof(Desktop
);
1248 CommandInfo
.Title
= Title
;
1249 CommandInfo
.TitleLen
= sizeof(Title
);
1250 CommandInfo
.Env
= Env
;
1251 CommandInfo
.EnvLen
= sizeof(Env
);
1253 /* Get the VDM command information */
1254 if (!GetNextVDMCommand(&CommandInfo
))
1256 /* Shouldn't happen */
1260 /* Increment the re-entry count */
1261 CommandInfo
.VDMState
= VDM_INC_REENTER_COUNT
;
1262 GetNextVDMCommand(&CommandInfo
);
1264 /* Load the executable */
1265 Result
= DosLoadExecutable(LoadType
,
1269 &Parameters
->StackLocation
,
1270 &Parameters
->EntryPoint
);
1271 if (Result
!= ERROR_SUCCESS
)
1273 DisplayMessage(L
"Could not load '%S'. Error: %u", AppName
, Result
);
1274 // FIXME: Decrement the reenter count. Or, instead, just increment
1275 // the VDM reenter count *only* if this call succeeds...
1281 /* Not handled by NTVDM */
1284 /* Wait for the process to finish executing */
1285 WaitForSingleObject(ProcessInfo
.hProcess
, INFINITE
);
1289 /* Close the handles */
1290 CloseHandle(ProcessInfo
.hProcess
);
1291 CloseHandle(ProcessInfo
.hThread
);
1293 return ERROR_SUCCESS
;
1297 VOID
DosTerminateProcess(WORD Psp
, BYTE ReturnCode
)
1300 WORD McbSegment
= FIRST_MCB_SEGMENT
;
1301 PDOS_MCB CurrentMcb
;
1302 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
1303 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(Psp
);
1305 DPRINT("DosTerminateProcess: Psp 0x%04X, ReturnCode 0x%02X\n",
1309 /* Check if this PSP is it's own parent */
1310 if (PspBlock
->ParentPsp
== Psp
) goto Done
;
1312 for (i
= 0; i
< PspBlock
->HandleTableSize
; i
++)
1314 /* Close the handle */
1318 /* Free the memory used by the process */
1321 /* Get a pointer to the MCB */
1322 CurrentMcb
= SEGMENT_TO_MCB(McbSegment
);
1324 /* Make sure the MCB is valid */
1325 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!='Z') break;
1327 /* If this block was allocated by the process, free it */
1328 if (CurrentMcb
->OwnerPsp
== Psp
) DosFreeMemory(McbSegment
+ 1);
1330 /* If this was the last block, quit */
1331 if (CurrentMcb
->BlockType
== 'Z') break;
1333 /* Update the segment and continue */
1334 McbSegment
+= CurrentMcb
->Size
+ 1;
1338 /* Restore the interrupt vectors */
1339 IntVecTable
[0x22] = PspBlock
->TerminateAddress
;
1340 IntVecTable
[0x23] = PspBlock
->BreakAddress
;
1341 IntVecTable
[0x24] = PspBlock
->CriticalAddress
;
1343 /* Update the current PSP */
1344 if (Psp
== CurrentPsp
)
1346 CurrentPsp
= PspBlock
->ParentPsp
;
1347 if (CurrentPsp
== SYSTEM_PSP
)
1349 ResetEvent(VdmTaskEvent
);
1355 // FIXME: This is probably not the best way to do it
1356 /* Check if this was a nested DOS task */
1357 if (CurrentPsp
!= SYSTEM_PSP
)
1359 VDM_COMMAND_INFO CommandInfo
;
1361 /* Decrement the re-entry count */
1362 CommandInfo
.TaskId
= SessionId
;
1363 CommandInfo
.VDMState
= VDM_DEC_REENTER_COUNT
;
1364 GetNextVDMCommand(&CommandInfo
);
1366 /* Clear the structure */
1367 RtlZeroMemory(&CommandInfo
, sizeof(CommandInfo
));
1369 /* Update the VDM state of the task */
1370 CommandInfo
.TaskId
= SessionId
;
1371 CommandInfo
.VDMState
= VDM_FLAG_DONT_WAIT
;
1372 GetNextVDMCommand(&CommandInfo
);
1376 /* Save the return code - Normal termination */
1377 DosErrorLevel
= MAKEWORD(ReturnCode
, 0x00);
1379 /* Return control to the parent process */
1380 CpuExecute(HIWORD(PspBlock
->TerminateAddress
),
1381 LOWORD(PspBlock
->TerminateAddress
));
1384 BOOLEAN
DosHandleIoctl(BYTE ControlCode
, WORD FileHandle
)
1386 HANDLE Handle
= DosGetRealHandle(FileHandle
);
1388 if (Handle
== INVALID_HANDLE_VALUE
)
1391 DosLastError
= ERROR_FILE_NOT_FOUND
;
1395 switch (ControlCode
)
1397 /* Get Device Information */
1403 * See Ralf Brown: http://www.ctyme.com/intr/rb-2820.htm
1404 * for a list of possible flags.
1407 if (Handle
== DosSystemFileTable
[DOS_INPUT_HANDLE
].Handle
)
1412 /* It is a device */
1415 else if (Handle
== DosSystemFileTable
[DOS_OUTPUT_HANDLE
].Handle
)
1417 /* Console output */
1420 /* It is a device */
1424 /* Return the device information word */
1429 /* Unsupported control code */
1432 DPRINT1("Unsupported IOCTL: 0x%02X\n", ControlCode
);
1434 DosLastError
= ERROR_INVALID_PARAMETER
;
1440 VOID WINAPI
DosInt20h(LPWORD Stack
)
1442 /* This is the exit interrupt */
1443 DosTerminateProcess(Stack
[STACK_CS
], 0);
1446 VOID WINAPI
DosInt21h(LPWORD Stack
)
1449 SYSTEMTIME SystemTime
;
1451 PDOS_INPUT_BUFFER InputBuffer
;
1453 /* Check the value in the AH register */
1456 /* Terminate Program */
1459 DosTerminateProcess(Stack
[STACK_CS
], 0);
1463 /* Read Character from STDIN with Echo */
1466 DPRINT("INT 21h, AH = 01h\n");
1468 // FIXME: Under DOS 2+, input / output handle may be redirected!!!!
1470 Character
= DosReadCharacter(DOS_INPUT_HANDLE
);
1473 // FIXME: Check whether Ctrl-C / Ctrl-Break is pressed, and call INT 23h if so.
1474 // Check also Ctrl-P and set echo-to-printer flag.
1475 // Ctrl-Z is not interpreted.
1481 /* Write Character to STDOUT */
1484 // FIXME: Under DOS 2+, output handle may be redirected!!!!
1485 Character
= getDL();
1486 DosPrintCharacter(DOS_OUTPUT_HANDLE
, Character
);
1489 * We return the output character (DOS 2.1+).
1490 * Also, if we're going to output a TAB, then
1491 * don't return a TAB but a SPACE instead.
1492 * See Ralf Brown: http://www.ctyme.com/intr/rb-2554.htm
1493 * for more information.
1495 setAL(Character
== '\t' ? ' ' : Character
);
1499 /* Read Character from STDAUX */
1502 // FIXME: Really read it from STDAUX!
1503 DPRINT1("INT 16h, 03h: Read character from STDAUX is HALFPLEMENTED\n");
1504 // setAL(DosReadCharacter());
1508 /* Write Character to STDAUX */
1511 // FIXME: Really write it to STDAUX!
1512 DPRINT1("INT 16h, 04h: Write character to STDAUX is HALFPLEMENTED\n");
1513 // DosPrintCharacter(getDL());
1517 /* Write Character to Printer */
1520 // FIXME: Really write it to printer!
1521 DPRINT1("INT 16h, 05h: Write character to printer is HALFPLEMENTED -\n\n");
1522 DPRINT1("0x%p\n", getDL());
1523 DPRINT1("\n\n-----------\n\n");
1527 /* Direct Console I/O */
1530 Character
= getDL();
1532 // FIXME: Under DOS 2+, output handle may be redirected!!!!
1534 if (Character
!= 0xFF)
1537 DosPrintCharacter(DOS_OUTPUT_HANDLE
, Character
);
1540 * We return the output character (DOS 2.1+).
1541 * See Ralf Brown: http://www.ctyme.com/intr/rb-2558.htm
1542 * for more information.
1549 if (DosCheckInput())
1551 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_ZF
;
1552 setAL(DosReadCharacter(DOS_INPUT_HANDLE
));
1556 /* No character available */
1557 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_ZF
;
1565 /* Character Input without Echo */
1569 DPRINT("Char input without echo\n");
1571 // FIXME: Under DOS 2+, input handle may be redirected!!!!
1572 Character
= DosReadCharacter(DOS_INPUT_HANDLE
);
1574 // FIXME: For 0x07, do not check Ctrl-C/Break.
1575 // For 0x08, do check those control sequences and if needed,
1578 // /* Let the BOP repeat if needed */
1579 // if (getCF()) break;
1585 /* Write string to STDOUT */
1588 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1590 while (*String
!= '$')
1592 DosPrintCharacter(DOS_OUTPUT_HANDLE
, *String
);
1597 * We return the terminating character (DOS 2.1+).
1598 * See Ralf Brown: http://www.ctyme.com/intr/rb-2562.htm
1599 * for more information.
1601 setAL('$'); // *String
1605 /* Read Buffered Input */
1609 InputBuffer
= (PDOS_INPUT_BUFFER
)SEG_OFF_TO_PTR(getDS(), getDX());
1611 DPRINT("Read Buffered Input\n");
1613 while (Count
< InputBuffer
->MaxLength
)
1615 // FIXME!! This function should interpret backspaces etc...
1617 /* Try to read a character (wait) */
1618 Character
= DosReadCharacter(DOS_INPUT_HANDLE
);
1620 // FIXME: Check whether Ctrl-C / Ctrl-Break is pressed, and call INT 23h if so.
1622 /* Echo the character and append it to the buffer */
1623 DosPrintCharacter(DOS_OUTPUT_HANDLE
, Character
);
1624 InputBuffer
->Buffer
[Count
] = Character
;
1626 Count
++; /* Carriage returns are also counted */
1628 if (Character
== '\r') break;
1631 /* Update the length */
1632 InputBuffer
->Length
= Count
;
1637 /* Get STDIN Status */
1640 setAL(DosCheckInput() ? 0xFF : 0x00);
1644 /* Flush Buffer and Read STDIN */
1647 BYTE InputFunction
= getAL();
1649 /* Flush STDIN buffer */
1650 DosFlushFileBuffers(DOS_INPUT_HANDLE
);
1653 * If the input function number contained in AL is valid, i.e.
1654 * AL == 0x01 or 0x06 or 0x07 or 0x08 or 0x0A, call ourselves
1655 * recursively with AL == AH.
1657 if (InputFunction
== 0x01 || InputFunction
== 0x06 ||
1658 InputFunction
== 0x07 || InputFunction
== 0x08 ||
1659 InputFunction
== 0x0A)
1661 /* Call ourselves recursively */
1662 setAH(InputFunction
);
1671 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1673 // TODO: Flush what's needed.
1674 DPRINT1("INT 21h, 0Dh is UNIMPLEMENTED\n");
1676 /* Clear CF in DOS 6 only */
1677 if (PspBlock
->DosVersion
== 0x0006)
1678 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1683 /* Set Default Drive */
1686 DosChangeDrive(getDL());
1687 setAL(LastDrive
- 'A' + 1);
1691 /* NULL Function for CP/M Compatibility */
1695 * This function corresponds to the CP/M BDOS function
1696 * "get bit map of logged drives", which is meaningless
1699 * For: PTS-DOS 6.51 & S/DOS 1.0 - EXTENDED RENAME FILE USING FCB
1700 * See Ralf Brown: http://www.ctyme.com/intr/rb-2584.htm
1701 * for more information.
1707 /* Get Default Drive */
1710 setAL(CurrentDrive
);
1714 /* Set Disk Transfer Area */
1717 DiskTransferArea
= MAKELONG(getDX(), getDS());
1721 /* NULL Function for CP/M Compatibility */
1726 * Function 0x1D corresponds to the CP/M BDOS function
1727 * "get bit map of read-only drives", which is meaningless
1729 * See Ralf Brown: http://www.ctyme.com/intr/rb-2592.htm
1730 * for more information.
1732 * Function 0x1E corresponds to the CP/M BDOS function
1733 * "set file attributes", which was meaningless under MS-DOS 1.x.
1734 * See Ralf Brown: http://www.ctyme.com/intr/rb-2593.htm
1735 * for more information.
1741 /* NULL Function for CP/M Compatibility */
1745 * This function corresponds to the CP/M BDOS function
1746 * "get/set default user (sublibrary) number", which is meaningless
1749 * For: S/DOS 1.0+ & PTS-DOS 6.51+ - GET OEM REVISION
1750 * See Ralf Brown: http://www.ctyme.com/intr/rb-2596.htm
1751 * for more information.
1757 /* Set Interrupt Vector */
1760 ULONG FarPointer
= MAKELONG(getDX(), getDS());
1761 DPRINT1("Setting interrupt 0x%02X to %04X:%04X ...\n",
1762 getAL(), HIWORD(FarPointer
), LOWORD(FarPointer
));
1764 /* Write the new far pointer to the IDT */
1765 ((PULONG
)BaseAddress
)[getAL()] = FarPointer
;
1769 /* Create New PSP */
1772 DPRINT1("INT 21h, AH = 26h - Create New PSP is UNIMPLEMENTED\n");
1776 /* Get System Date */
1779 GetLocalTime(&SystemTime
);
1780 setCX(SystemTime
.wYear
);
1781 setDX(MAKEWORD(SystemTime
.wDay
, SystemTime
.wMonth
));
1782 setAL(SystemTime
.wDayOfWeek
);
1786 /* Set System Date */
1789 GetLocalTime(&SystemTime
);
1790 SystemTime
.wYear
= getCX();
1791 SystemTime
.wMonth
= getDH();
1792 SystemTime
.wDay
= getDL();
1794 /* Return success or failure */
1795 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1799 /* Get System Time */
1802 GetLocalTime(&SystemTime
);
1803 setCX(MAKEWORD(SystemTime
.wMinute
, SystemTime
.wHour
));
1804 setDX(MAKEWORD(SystemTime
.wMilliseconds
/ 10, SystemTime
.wSecond
));
1808 /* Set System Time */
1811 GetLocalTime(&SystemTime
);
1812 SystemTime
.wHour
= getCH();
1813 SystemTime
.wMinute
= getCL();
1814 SystemTime
.wSecond
= getDH();
1815 SystemTime
.wMilliseconds
= getDL() * 10; // In hundredths of seconds
1817 /* Return success or failure */
1818 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1822 /* Get Disk Transfer Area */
1825 setES(HIWORD(DiskTransferArea
));
1826 setBX(LOWORD(DiskTransferArea
));
1830 /* Get DOS Version */
1833 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1836 * DOS 2+ - GET DOS VERSION
1837 * See Ralf Brown: http://www.ctyme.com/intr/rb-2711.htm
1838 * for more information.
1841 if (LOBYTE(PspBlock
->DosVersion
) < 5 || getAL() == 0x00)
1844 * Return DOS OEM number:
1845 * 0x00 for IBM PC-DOS
1846 * 0x02 for packaged MS-DOS
1852 if (LOBYTE(PspBlock
->DosVersion
) >= 5 && getAL() == 0x01)
1855 * Return version flag:
1856 * 1 << 3 if DOS is in ROM,
1857 * 0 (reserved) if not.
1862 /* Return DOS 24-bit user serial number in BL:CX */
1867 * Return DOS version: Minor:Major in AH:AL
1868 * The Windows NT DOS box returns version 5.00, subject to SETVER.
1870 setAX(PspBlock
->DosVersion
);
1875 /* Extended functionalities */
1878 if (getAL() == 0x06)
1881 * DOS 5+ - GET TRUE VERSION NUMBER
1882 * This function always returns the true version number, unlike
1883 * AH=30h, whose return value may be changed with SETVER.
1884 * See Ralf Brown: http://www.ctyme.com/intr/rb-2730.htm
1885 * for more information.
1889 * Return the true DOS version: Minor:Major in BH:BL
1890 * The Windows NT DOS box returns BX=3205h (version 5.50).
1892 setBX(NTDOS_VERSION
);
1894 /* DOS revision 0 */
1902 // /* Invalid subfunction */
1909 /* Get Interrupt Vector */
1912 DWORD FarPointer
= ((PDWORD
)BaseAddress
)[getAL()];
1914 /* Read the address from the IDT into ES:BX */
1915 setES(HIWORD(FarPointer
));
1916 setBX(LOWORD(FarPointer
));
1920 /* SWITCH character - AVAILDEV */
1923 if (getAL() == 0x00)
1926 * DOS 2+ - "SWITCHAR" - GET SWITCH CHARACTER
1927 * This setting is ignored by MS-DOS 4.0+.
1928 * MS-DOS 5+ always return AL=00h/DL=2Fh.
1929 * See Ralf Brown: http://www.ctyme.com/intr/rb-2752.htm
1930 * for more information.
1935 else if (getAL() == 0x01)
1938 * DOS 2+ - "SWITCHAR" - SET SWITCH CHARACTER
1939 * This setting is ignored by MS-DOS 5+.
1940 * See Ralf Brown: http://www.ctyme.com/intr/rb-2753.htm
1941 * for more information.
1946 else if (getAL() == 0x02)
1949 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1950 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1951 * for more information.
1956 else if (getAL() == 0x03)
1959 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1960 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1961 * for more information.
1968 /* Invalid subfunction */
1975 /* Create Directory */
1978 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1980 if (CreateDirectoryA(String
, NULL
))
1982 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1986 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1987 setAX(LOWORD(GetLastError()));
1993 /* Remove Directory */
1996 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1998 if (RemoveDirectoryA(String
))
2000 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2004 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2005 setAX(LOWORD(GetLastError()));
2011 /* Set Current Directory */
2014 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
2016 if (DosChangeDirectory(String
))
2018 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2022 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2023 setAX(DosLastError
);
2029 /* Create or Truncate File */
2033 WORD ErrorCode
= DosCreateFile(&FileHandle
,
2034 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
2038 if (ErrorCode
== ERROR_SUCCESS
)
2040 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2045 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2056 WORD ErrorCode
= DosOpenFile(&FileHandle
,
2057 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
2060 if (ErrorCode
== ERROR_SUCCESS
)
2062 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2067 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2077 if (DosCloseHandle(getBX()))
2079 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2083 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2084 setAX(ERROR_INVALID_HANDLE
);
2090 /* Read from File or Device */
2096 DPRINT("INT 21h, AH = 3Fh\n");
2099 ErrorCode
= DosReadFile(getBX(),
2100 SEG_OFF_TO_PTR(getDS(), getDX()),
2105 if (ErrorCode
== ERROR_SUCCESS
)
2107 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2110 else if (ErrorCode
!= ERROR_NOT_READY
)
2112 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2119 /* Write to File or Device */
2122 WORD BytesWritten
= 0;
2123 WORD ErrorCode
= DosWriteFile(getBX(),
2124 SEG_OFF_TO_PTR(getDS(), getDX()),
2128 if (ErrorCode
== ERROR_SUCCESS
)
2130 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2131 setAX(BytesWritten
);
2135 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2145 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2147 if (demFileDelete(FileName
) == ERROR_SUCCESS
)
2149 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2151 * See Ralf Brown: http://www.ctyme.com/intr/rb-2797.htm
2152 * "AX destroyed (DOS 3.3) AL seems to be drive of deleted file."
2154 setAL(FileName
[0] - 'A');
2158 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2159 setAX(GetLastError());
2169 WORD ErrorCode
= DosSeekFile(getBX(),
2170 MAKELONG(getDX(), getCX()),
2174 if (ErrorCode
== ERROR_SUCCESS
)
2176 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2178 /* Return the new offset in DX:AX */
2179 setDX(HIWORD(NewLocation
));
2180 setAX(LOWORD(NewLocation
));
2184 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2191 /* Get/Set File Attributes */
2195 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2197 if (getAL() == 0x00)
2199 /* Get the attributes */
2200 Attributes
= GetFileAttributesA(FileName
);
2202 /* Check if it failed */
2203 if (Attributes
== INVALID_FILE_ATTRIBUTES
)
2205 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2206 setAX(GetLastError());
2210 /* Return the attributes that DOS can understand */
2211 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2212 setCX(Attributes
& 0x00FF);
2215 else if (getAL() == 0x01)
2217 /* Try to set the attributes */
2218 if (SetFileAttributesA(FileName
, getCL()))
2220 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2224 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2225 setAX(GetLastError());
2230 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2231 setAX(ERROR_INVALID_FUNCTION
);
2240 if (DosHandleIoctl(getAL(), getBX()))
2242 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2246 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2247 setAX(DosLastError
);
2253 /* Duplicate Handle */
2257 HANDLE Handle
= DosGetRealHandle(getBX());
2259 if (Handle
== INVALID_HANDLE_VALUE
)
2261 /* The handle is invalid */
2262 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2263 setAX(ERROR_INVALID_HANDLE
);
2267 /* Open a new handle to the same entry */
2268 NewHandle
= DosOpenHandle(Handle
);
2270 if (NewHandle
== INVALID_DOS_HANDLE
)
2272 /* Too many files open */
2273 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2274 setAX(ERROR_TOO_MANY_OPEN_FILES
);
2278 /* Return the result */
2279 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2284 /* Force Duplicate Handle */
2287 if (DosDuplicateHandle(getBX(), getCX()))
2289 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2293 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2294 setAX(ERROR_INVALID_HANDLE
);
2300 /* Get Current Directory */
2303 BYTE DriveNumber
= getDL();
2304 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getSI());
2306 /* Get the real drive number */
2307 if (DriveNumber
== 0)
2309 DriveNumber
= CurrentDrive
;
2313 /* Decrement DriveNumber since it was 1-based */
2317 if (DriveNumber
<= LastDrive
- 'A')
2320 * Copy the current directory into the target buffer.
2321 * It doesn't contain the drive letter and the backslash.
2323 strncpy(String
, CurrentDirectories
[DriveNumber
], DOS_DIR_LENGTH
);
2324 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2325 setAX(0x0100); // Undocumented, see Ralf Brown: http://www.ctyme.com/intr/rb-2933.htm
2329 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2330 setAX(ERROR_INVALID_DRIVE
);
2336 /* Allocate Memory */
2339 WORD MaxAvailable
= 0;
2340 WORD Segment
= DosAllocateMemory(getBX(), &MaxAvailable
);
2344 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2349 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2350 setAX(DosLastError
);
2351 setBX(MaxAvailable
);
2360 if (DosFreeMemory(getES()))
2362 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2366 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2367 setAX(ERROR_ARENA_TRASHED
);
2373 /* Resize Memory Block */
2378 if (DosResizeMemory(getES(), getBX(), &Size
))
2380 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2384 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2385 setAX(DosLastError
);
2396 DOS_EXEC_TYPE LoadType
= (DOS_EXEC_TYPE
)getAL();
2397 LPSTR ProgramName
= SEG_OFF_TO_PTR(getDS(), getDX());
2398 PDOS_EXEC_PARAM_BLOCK ParamBlock
= SEG_OFF_TO_PTR(getES(), getBX());
2399 WORD ErrorCode
= DosCreateProcess(LoadType
, ProgramName
, ParamBlock
);
2401 if (ErrorCode
== ERROR_SUCCESS
)
2403 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2407 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2415 /* Terminate With Return Code */
2418 DosTerminateProcess(CurrentPsp
, getAL());
2422 /* Get Return Code (ERRORLEVEL) */
2426 * According to Ralf Brown: http://www.ctyme.com/intr/rb-2976.htm
2427 * DosErrorLevel is cleared after being read by this function.
2429 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2430 setAX(DosErrorLevel
);
2431 DosErrorLevel
= 0x0000; // Clear it
2435 /* Find First File */
2438 WORD Result
= (WORD
)demFileFindFirst(FAR_POINTER(DiskTransferArea
),
2439 SEG_OFF_TO_PTR(getDS(), getDX()),
2444 if (Result
== ERROR_SUCCESS
)
2445 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2447 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2452 /* Find Next File */
2455 WORD Result
= (WORD
)demFileFindNext(FAR_POINTER(DiskTransferArea
));
2459 if (Result
== ERROR_SUCCESS
)
2460 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2462 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2467 /* Internal - Set Current Process ID (Set PSP Address) */
2470 // FIXME: Is it really what it's done ??
2471 CurrentPsp
= getBX();
2475 /* Internal - Get Current Process ID (Get PSP Address) */
2477 /* Get Current PSP Address */
2481 * Undocumented AH=51h is identical to the documented AH=62h.
2482 * See Ralf Brown: http://www.ctyme.com/intr/rb-2982.htm
2483 * and http://www.ctyme.com/intr/rb-3140.htm
2484 * for more information.
2490 /* Internal - Get "List of lists" (SYSVARS) */
2494 * On return, ES points at the DOS data segment (see also INT 2F/AX=1203h).
2495 * See Ralf Brown: http://www.ctyme.com/intr/rb-2983.htm
2496 * for more information.
2499 /* Return the DOS "list of lists" in ES:BX */
2503 DisplayMessage(L
"Required for AARD code, do you remember? :P");
2510 LPSTR ExistingFileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2511 LPSTR NewFileName
= (LPSTR
)SEG_OFF_TO_PTR(getES(), getDI());
2514 * See Ralf Brown: http://www.ctyme.com/intr/rb-2990.htm
2515 * for more information.
2518 if (MoveFileA(ExistingFileName
, NewFileName
))
2520 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2524 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2525 setAX(GetLastError());
2531 /* Get/Set Memory Management Options */
2534 if (getAL() == 0x00)
2536 /* Get allocation strategy */
2537 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2538 setAX(DosAllocStrategy
);
2540 else if (getAL() == 0x01)
2542 /* Set allocation strategy */
2544 if ((getBL() & (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2545 == (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2547 /* Can't set both */
2548 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2549 setAX(ERROR_INVALID_PARAMETER
);
2553 if ((getBL() & 0x3F) > DOS_ALLOC_LAST_FIT
)
2555 /* Invalid allocation strategy */
2556 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2557 setAX(ERROR_INVALID_PARAMETER
);
2561 DosAllocStrategy
= getBL();
2562 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2564 else if (getAL() == 0x02)
2566 /* Get UMB link state */
2567 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2568 setAL(DosUmbLinked
? 0x01 : 0x00);
2570 else if (getAL() == 0x03)
2572 /* Set UMB link state */
2573 if (getBX()) DosLinkUmb();
2574 else DosUnlinkUmb();
2575 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2579 /* Invalid or unsupported function */
2580 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2581 setAX(ERROR_INVALID_FUNCTION
);
2587 /* Get Extended Error Information */
2590 DPRINT1("INT 21h, AH = 59h, BX = %04Xh - Get Extended Error Information is UNIMPLEMENTED\n",
2595 /* Create Temporary File */
2598 LPSTR PathName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2599 LPSTR FileName
= PathName
; // The buffer for the path and the full file name is the same.
2605 * See Ralf Brown: http://www.ctyme.com/intr/rb-3014.htm
2606 * for more information.
2609 // FIXME: Check for buffer validity?
2610 // It should be a ASCIZ path ending with a '\' + 13 zero bytes
2611 // to receive the generated filename.
2613 /* First create the temporary file */
2614 uRetVal
= GetTempFileNameA(PathName
, NULL
, 0, FileName
);
2617 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2618 setAX(GetLastError());
2622 /* Now try to open it in read/write access */
2623 ErrorCode
= DosOpenFile(&FileHandle
, FileName
, 2);
2624 if (ErrorCode
== ERROR_SUCCESS
)
2626 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2631 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2638 /* Create New File */
2642 WORD ErrorCode
= DosCreateFile(&FileHandle
,
2643 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
2647 if (ErrorCode
== ERROR_SUCCESS
)
2649 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2654 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2661 /* Lock/Unlock Region of File */
2664 HANDLE Handle
= DosGetRealHandle(getBX());
2666 if (Handle
== INVALID_HANDLE_VALUE
)
2668 /* The handle is invalid */
2669 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2670 setAX(ERROR_INVALID_HANDLE
);
2674 if (getAL() == 0x00)
2676 /* Lock region of file */
2677 if (LockFile(Handle
,
2678 MAKELONG(getCX(), getDX()), 0,
2679 MAKELONG(getSI(), getDI()), 0))
2681 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2685 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2686 setAX(GetLastError());
2689 else if (getAL() == 0x01)
2691 /* Unlock region of file */
2692 if (UnlockFile(Handle
,
2693 MAKELONG(getCX(), getDX()), 0,
2694 MAKELONG(getSI(), getDI()), 0))
2696 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2700 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2701 setAX(GetLastError());
2706 /* Invalid subfunction */
2707 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2708 setAX(ERROR_INVALID_FUNCTION
);
2714 /* Canonicalize File Name or Path */
2718 * See Ralf Brown: http://www.ctyme.com/intr/rb-3137.htm
2719 * for more information.
2723 * We suppose that the DOS app gave to us a valid
2724 * 128-byte long buffer for the canonicalized name.
2726 DWORD dwRetVal
= GetFullPathNameA(SEG_OFF_TO_PTR(getDS(), getSI()),
2728 SEG_OFF_TO_PTR(getES(), getDI()),
2732 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2733 setAX(GetLastError());
2737 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2741 // FIXME: Convert the full path name into short version.
2742 // We cannot reliably use GetShortPathName, because it fails
2743 // if the path name given doesn't exist. However this DOS
2744 // function AH=60h should be able to work even for non-existing
2745 // path and file names.
2750 /* Set Handle Count */
2753 if (!DosResizeHandleTable(getBX()))
2755 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2756 setAX(DosLastError
);
2758 else Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2768 * Function 6Ah is identical to function 68h,
2769 * and sets AH to 68h if success.
2770 * See Ralf Brown: http://www.ctyme.com/intr/rb-3176.htm
2771 * for more information.
2775 if (DosFlushFileBuffers(getBX()))
2777 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2781 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2782 setAX(GetLastError());
2788 /* Extended Open/Create */
2792 WORD CreationStatus
;
2795 /* Check for AL == 00 */
2796 if (getAL() != 0x00)
2798 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2799 setAX(ERROR_INVALID_FUNCTION
);
2804 * See Ralf Brown: http://www.ctyme.com/intr/rb-3179.htm
2805 * for the full detailed description.
2807 * WARNING: BH contains some extended flags that are NOT SUPPORTED.
2810 ErrorCode
= DosCreateFileEx(&FileHandle
,
2812 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getSI()),
2817 if (ErrorCode
== ERROR_SUCCESS
)
2819 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2820 setCX(CreationStatus
);
2825 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2835 DPRINT1("DOS Function INT 0x21, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2838 setAL(0); // Some functions expect AL to be 0 when it's not supported.
2839 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2844 VOID WINAPI
DosBreakInterrupt(LPWORD Stack
)
2846 UNREFERENCED_PARAMETER(Stack
);
2848 /* Stop the VDM task */
2849 ResetEvent(VdmTaskEvent
);
2853 VOID WINAPI
DosFastConOut(LPWORD Stack
)
2856 * This is the DOS 2+ Fast Console Output Interrupt.
2857 * The default handler under DOS 2.x and 3.x simply calls INT 10h/AH=0Eh.
2859 * See Ralf Brown: http://www.ctyme.com/intr/rb-4124.htm
2860 * for more information.
2863 /* Save AX and BX */
2864 USHORT AX
= getAX();
2865 USHORT BX
= getBX();
2868 * Set the parameters:
2869 * AL contains the character to print (already set),
2870 * BL contains the character attribute,
2871 * BH contains the video page to use.
2873 setBL(DOS_CHAR_ATTRIBUTE
);
2874 setBH(Bda
->VideoPage
);
2876 /* Call the BIOS INT 10h, AH=0Eh "Teletype Output" */
2878 Int32Call(&DosContext
, BIOS_VIDEO_INTERRUPT
);
2880 /* Restore AX and BX */
2885 VOID WINAPI
DosInt2Fh(LPWORD Stack
)
2887 DPRINT1("DOS Internal System Function INT 0x2F, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2889 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2892 BOOLEAN
DosKRNLInitialize(VOID
)
2898 CHAR CurrentDirectory
[MAX_PATH
];
2899 CHAR DosDirectory
[DOS_DIR_LENGTH
];
2905 /* Clear the current directory buffer */
2906 RtlZeroMemory(CurrentDirectories
, sizeof(CurrentDirectories
));
2908 /* Get the current directory */
2909 if (!GetCurrentDirectoryA(MAX_PATH
, CurrentDirectory
))
2911 // TODO: Use some kind of default path?
2915 /* Convert that to a DOS path */
2916 if (!GetShortPathNameA(CurrentDirectory
, DosDirectory
, DOS_DIR_LENGTH
))
2918 // TODO: Use some kind of default path?
2923 CurrentDrive
= DosDirectory
[0] - 'A';
2925 /* Get the directory part of the path */
2926 Path
= strchr(DosDirectory
, '\\');
2929 /* Skip the backslash */
2933 /* Set the directory */
2936 strncpy(CurrentDirectories
[CurrentDrive
], Path
, DOS_DIR_LENGTH
);
2939 /* Read CONFIG.SYS */
2940 Stream
= _wfopen(DOS_CONFIG_PATH
, L
"r");
2943 while (fgetws(Buffer
, 256, Stream
))
2945 // TODO: Parse the line
2950 /* Initialize the SFT */
2951 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
2953 DosSystemFileTable
[i
].Handle
= INVALID_HANDLE_VALUE
;
2954 DosSystemFileTable
[i
].RefCount
= 0;
2957 /* Get handles to standard I/O devices */
2958 DosSystemFileTable
[0].Handle
= GetStdHandle(STD_INPUT_HANDLE
);
2959 DosSystemFileTable
[1].Handle
= GetStdHandle(STD_OUTPUT_HANDLE
);
2960 DosSystemFileTable
[2].Handle
= GetStdHandle(STD_ERROR_HANDLE
);
2962 /* Initialize the reference counts */
2963 DosSystemFileTable
[0].RefCount
=
2964 DosSystemFileTable
[1].RefCount
=
2965 DosSystemFileTable
[2].RefCount
= 1;
2969 /* Initialize the callback context */
2970 InitializeContext(&DosContext
, 0x0070, 0x0000);
2972 /* Register the DOS 32-bit Interrupts */
2973 RegisterDosInt32(0x20, DosInt20h
);
2974 RegisterDosInt32(0x21, DosInt21h
);
2975 // RegisterDosInt32(0x22, DosInt22h ); // Termination
2976 RegisterDosInt32(0x23, DosBreakInterrupt
); // Ctrl-C / Ctrl-Break
2977 // RegisterDosInt32(0x24, DosInt24h ); // Critical Error
2978 RegisterDosInt32(0x29, DosFastConOut
); // DOS 2+ Fast Console Output
2979 RegisterDosInt32(0x2F, DosInt2Fh
);