2 * COPYRIGHT: GPL - See COPYING in the top level directory
3 * PROJECT: ReactOS Virtual DOS Machine
5 * PURPOSE: VDM DOS Kernel
6 * PROGRAMMERS: Aleksandar Andrejevic <theflash AT sdf DOT lonestar DOT org>
9 /* INCLUDES *******************************************************************/
19 #include "bios/bios.h"
20 #include "registers.h"
22 /* PRIVATE VARIABLES **********************************************************/
24 CALLBACK16 DosContext
;
26 static WORD CurrentPsp
= SYSTEM_PSP
;
27 static WORD DosLastError
= 0;
28 static DWORD DiskTransferArea
;
29 /*static*/ BYTE CurrentDrive
;
30 static CHAR LastDrive
= 'E';
31 static CHAR CurrentDirectories
[NUM_DRIVES
][DOS_DIR_LENGTH
];
32 static HANDLE DosSystemFileTable
[DOS_SFT_SIZE
];
33 static WORD DosSftRefCount
[DOS_SFT_SIZE
];
34 static BYTE DosAllocStrategy
= DOS_ALLOC_BEST_FIT
;
35 static BOOLEAN DosUmbLinked
= FALSE
;
36 static WORD DosErrorLevel
= 0x0000;
38 /* PRIVATE FUNCTIONS **********************************************************/
41 * Memory management functions
43 static VOID
DosCombineFreeBlocks(WORD StartBlock
)
45 PDOS_MCB CurrentMcb
= SEGMENT_TO_MCB(StartBlock
), NextMcb
;
47 /* If this is the last block or it's not free, quit */
48 if (CurrentMcb
->BlockType
== 'Z' || CurrentMcb
->OwnerPsp
!= 0) return;
52 /* Get a pointer to the next MCB */
53 NextMcb
= SEGMENT_TO_MCB(StartBlock
+ CurrentMcb
->Size
+ 1);
55 /* Check if the next MCB is free */
56 if (NextMcb
->OwnerPsp
== 0)
59 CurrentMcb
->Size
+= NextMcb
->Size
+ 1;
60 CurrentMcb
->BlockType
= NextMcb
->BlockType
;
61 NextMcb
->BlockType
= 'I';
65 /* No more adjoining free blocks */
71 static WORD
DosAllocateMemory(WORD Size
, WORD
*MaxAvailable
)
73 WORD Result
= 0, Segment
= FIRST_MCB_SEGMENT
, MaxSize
= 0;
74 PDOS_MCB CurrentMcb
, NextMcb
;
75 BOOLEAN SearchUmb
= FALSE
;
77 DPRINT("DosAllocateMemory: Size 0x%04X\n", Size
);
79 if (DosUmbLinked
&& (DosAllocStrategy
& (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
)))
81 /* Search UMB first */
82 Segment
= UMB_START_SEGMENT
;
88 /* Get a pointer to the MCB */
89 CurrentMcb
= SEGMENT_TO_MCB(Segment
);
91 /* Make sure it's valid */
92 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!= 'Z')
94 DPRINT("The DOS memory arena is corrupted!\n");
95 DosLastError
= ERROR_ARENA_TRASHED
;
99 /* Only check free blocks */
100 if (CurrentMcb
->OwnerPsp
!= 0) goto Next
;
102 /* Combine this free block with adjoining free blocks */
103 DosCombineFreeBlocks(Segment
);
105 /* Update the maximum block size */
106 if (CurrentMcb
->Size
> MaxSize
) MaxSize
= CurrentMcb
->Size
;
108 /* Check if this block is big enough */
109 if (CurrentMcb
->Size
< Size
) goto Next
;
111 switch (DosAllocStrategy
& 0x3F)
113 case DOS_ALLOC_FIRST_FIT
:
115 /* For first fit, stop immediately */
120 case DOS_ALLOC_BEST_FIT
:
122 /* For best fit, update the smallest block found so far */
123 if ((Result
== 0) || (CurrentMcb
->Size
< SEGMENT_TO_MCB(Result
)->Size
))
131 case DOS_ALLOC_LAST_FIT
:
133 /* For last fit, make the current block the result, but keep searching */
140 /* If this was the last MCB in the chain, quit */
141 if (CurrentMcb
->BlockType
== 'Z')
143 /* Check if nothing was found while searching through UMBs */
144 if ((Result
== 0) && SearchUmb
&& (DosAllocStrategy
& DOS_ALLOC_HIGH_LOW
))
146 /* Search low memory */
147 Segment
= FIRST_MCB_SEGMENT
;
154 /* Otherwise, update the segment and continue */
155 Segment
+= CurrentMcb
->Size
+ 1;
160 /* If we didn't find a free block, return 0 */
163 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
164 if (MaxAvailable
) *MaxAvailable
= MaxSize
;
168 /* Get a pointer to the MCB */
169 CurrentMcb
= SEGMENT_TO_MCB(Result
);
171 /* Check if the block is larger than requested */
172 if (CurrentMcb
->Size
> Size
)
174 /* It is, split it into two blocks */
175 NextMcb
= SEGMENT_TO_MCB(Result
+ Size
+ 1);
177 /* Initialize the new MCB structure */
178 NextMcb
->BlockType
= CurrentMcb
->BlockType
;
179 NextMcb
->Size
= CurrentMcb
->Size
- Size
- 1;
180 NextMcb
->OwnerPsp
= 0;
182 /* Update the current block */
183 CurrentMcb
->BlockType
= 'M';
184 CurrentMcb
->Size
= Size
;
187 /* Take ownership of the block */
188 CurrentMcb
->OwnerPsp
= CurrentPsp
;
190 /* Return the segment of the data portion of the block */
194 static BOOLEAN
DosResizeMemory(WORD BlockData
, WORD NewSize
, WORD
*MaxAvailable
)
196 BOOLEAN Success
= TRUE
;
197 WORD Segment
= BlockData
- 1, ReturnSize
= 0, NextSegment
;
198 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
), NextMcb
;
200 DPRINT("DosResizeMemory: BlockData 0x%04X, NewSize 0x%04X\n",
204 /* Make sure this is a valid, allocated block */
205 if ((Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z') || Mcb
->OwnerPsp
== 0)
208 DosLastError
= ERROR_INVALID_HANDLE
;
212 ReturnSize
= Mcb
->Size
;
214 /* Check if we need to expand or contract the block */
215 if (NewSize
> Mcb
->Size
)
217 /* We can't expand the last block */
218 if (Mcb
->BlockType
!= 'M')
224 /* Get the pointer and segment of the next MCB */
225 NextSegment
= Segment
+ Mcb
->Size
+ 1;
226 NextMcb
= SEGMENT_TO_MCB(NextSegment
);
228 /* Make sure the next segment is free */
229 if (NextMcb
->OwnerPsp
!= 0)
231 DPRINT("Cannot expand memory block: next segment is not free!\n");
232 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
237 /* Combine this free block with adjoining free blocks */
238 DosCombineFreeBlocks(NextSegment
);
240 /* Set the maximum possible size of the block */
241 ReturnSize
+= NextMcb
->Size
+ 1;
243 /* Maximize the current block */
244 Mcb
->Size
= ReturnSize
;
245 Mcb
->BlockType
= NextMcb
->BlockType
;
247 /* Invalidate the next block */
248 NextMcb
->BlockType
= 'I';
250 /* Check if the block is larger than requested */
251 if (Mcb
->Size
> NewSize
)
253 DPRINT("Block too large, reducing size from 0x%04X to 0x%04X\n",
257 /* It is, split it into two blocks */
258 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
260 /* Initialize the new MCB structure */
261 NextMcb
->BlockType
= Mcb
->BlockType
;
262 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
263 NextMcb
->OwnerPsp
= 0;
265 /* Update the current block */
266 Mcb
->BlockType
= 'M';
270 else if (NewSize
< Mcb
->Size
)
272 DPRINT("Shrinking block from 0x%04X to 0x%04X\n",
276 /* Just split the block */
277 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
278 NextMcb
->BlockType
= Mcb
->BlockType
;
279 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
280 NextMcb
->OwnerPsp
= 0;
283 Mcb
->BlockType
= 'M';
288 /* Check if the operation failed */
291 DPRINT("DosResizeMemory FAILED. Maximum available: 0x%04X\n",
294 /* Return the maximum possible size */
295 if (MaxAvailable
) *MaxAvailable
= ReturnSize
;
301 static BOOLEAN
DosFreeMemory(WORD BlockData
)
303 PDOS_MCB Mcb
= SEGMENT_TO_MCB(BlockData
- 1);
305 DPRINT("DosFreeMemory: BlockData 0x%04X\n", BlockData
);
307 /* Make sure the MCB is valid */
308 if (Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z')
310 DPRINT("MCB block type '%c' not valid!\n", Mcb
->BlockType
);
314 /* Mark the block as free */
320 static BOOLEAN
DosLinkUmb(VOID
)
322 DWORD Segment
= FIRST_MCB_SEGMENT
;
323 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
);
325 DPRINT("Linking UMB\n");
327 /* Check if UMBs are already linked */
328 if (DosUmbLinked
) return FALSE
;
330 /* Find the last block */
331 while ((Mcb
->BlockType
== 'M') && (Segment
<= 0xFFFF))
333 Segment
+= Mcb
->Size
+ 1;
334 Mcb
= SEGMENT_TO_MCB(Segment
);
337 /* Make sure it's valid */
338 if (Mcb
->BlockType
!= 'Z') return FALSE
;
340 /* Connect the MCB with the UMB chain */
341 Mcb
->BlockType
= 'M';
347 static BOOLEAN
DosUnlinkUmb(VOID
)
349 DWORD Segment
= FIRST_MCB_SEGMENT
;
350 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
);
352 DPRINT("Unlinking UMB\n");
354 /* Check if UMBs are already unlinked */
355 if (!DosUmbLinked
) return FALSE
;
357 /* Find the block preceding the MCB that links it with the UMB chain */
358 while (Segment
<= 0xFFFF)
360 if ((Segment
+ Mcb
->Size
) == (FIRST_MCB_SEGMENT
+ USER_MEMORY_SIZE
))
362 /* This is the last non-UMB segment */
366 /* Advance to the next MCB */
367 Segment
+= Mcb
->Size
+ 1;
368 Mcb
= SEGMENT_TO_MCB(Segment
);
371 /* Mark the MCB as the last MCB */
372 Mcb
->BlockType
= 'Z';
374 DosUmbLinked
= FALSE
;
378 static VOID
DosChangeMemoryOwner(WORD Segment
, WORD NewOwner
)
380 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
- 1);
382 /* Just set the owner */
383 Mcb
->OwnerPsp
= NewOwner
;
388 static WORD
DosCopyEnvironmentBlock(WORD SourceSegment
, LPCSTR ProgramName
)
390 PCHAR Ptr
, SourceBuffer
, DestBuffer
= NULL
;
394 Ptr
= SourceBuffer
= (PCHAR
)SEG_OFF_TO_PTR(SourceSegment
, 0);
396 /* Calculate the size of the environment block */
399 TotalSize
+= strlen(Ptr
) + 1;
400 Ptr
+= strlen(Ptr
) + 1;
404 /* Add the string buffer size */
405 TotalSize
+= strlen(ProgramName
) + 1;
407 /* Allocate the memory for the environment block */
408 DestSegment
= DosAllocateMemory((WORD
)((TotalSize
+ 0x0F) >> 4), NULL
);
409 if (!DestSegment
) return 0;
413 DestBuffer
= (PCHAR
)SEG_OFF_TO_PTR(DestSegment
, 0);
416 /* Copy the string */
417 strcpy(DestBuffer
, Ptr
);
419 /* Advance to the next string */
420 DestBuffer
+= strlen(Ptr
);
421 Ptr
+= strlen(Ptr
) + 1;
423 /* Put a zero after the string */
427 /* Set the final zero */
430 /* Copy the program name after the environment block */
431 strcpy(DestBuffer
, ProgramName
);
436 /* Taken from base/shell/cmd/console.c */
437 BOOL
IsConsoleHandle(HANDLE hHandle
)
441 /* Check whether the handle may be that of a console... */
442 if ((GetFileType(hHandle
) & FILE_TYPE_CHAR
) == 0) return FALSE
;
445 * It may be. Perform another test... The idea comes from the
446 * MSDN description of the WriteConsole API:
448 * "WriteConsole fails if it is used with a standard handle
449 * that is redirected to a file. If an application processes
450 * multilingual output that can be redirected, determine whether
451 * the output handle is a console handle (one method is to call
452 * the GetConsoleMode function and check whether it succeeds).
453 * If the handle is a console handle, call WriteConsole. If the
454 * handle is not a console handle, the output is redirected and
455 * you should call WriteFile to perform the I/O."
457 return GetConsoleMode(hHandle
, &dwMode
);
460 static WORD
DosOpenHandle(HANDLE Handle
)
467 /* The system PSP has no handle table */
468 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_DOS_HANDLE
;
470 /* Get a pointer to the handle table */
471 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
472 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
474 /* Find a free entry in the JFT */
475 for (DosHandle
= 0; DosHandle
< PspBlock
->HandleTableSize
; DosHandle
++)
477 if (HandleTable
[DosHandle
] == 0xFF) break;
480 /* If there are no free entries, fail */
481 if (DosHandle
== PspBlock
->HandleTableSize
) return INVALID_DOS_HANDLE
;
483 /* Check if the handle is already in the SFT */
484 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
486 /* Check if this is the same handle */
487 if (DosSystemFileTable
[i
] != Handle
) continue;
489 /* Already in the table, reference it */
492 /* Set the JFT entry to that SFT index */
493 HandleTable
[DosHandle
] = i
;
495 /* Return the new handle */
499 /* Add the handle to the SFT */
500 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
502 /* Make sure this is an empty table entry */
503 if (DosSystemFileTable
[i
] != INVALID_HANDLE_VALUE
) continue;
505 /* Initialize the empty table entry */
506 DosSystemFileTable
[i
] = Handle
;
507 DosSftRefCount
[i
] = 1;
509 /* Set the JFT entry to that SFT index */
510 HandleTable
[DosHandle
] = i
;
512 /* Return the new handle */
516 /* The SFT is full */
517 return INVALID_DOS_HANDLE
;
520 HANDLE
DosGetRealHandle(WORD DosHandle
)
525 /* The system PSP has no handle table */
526 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_HANDLE_VALUE
;
528 /* Get a pointer to the handle table */
529 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
530 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
532 /* Make sure the handle is open */
533 if (HandleTable
[DosHandle
] == 0xFF) return INVALID_HANDLE_VALUE
;
535 /* Return the Win32 handle */
536 return DosSystemFileTable
[HandleTable
[DosHandle
]];
539 static VOID
DosCopyHandleTable(LPBYTE DestinationTable
)
545 /* Clear the table first */
546 for (i
= 0; i
< 20; i
++) DestinationTable
[i
] = 0xFF;
548 /* Check if this is the initial process */
549 if (CurrentPsp
== SYSTEM_PSP
)
551 /* Set up the standard I/O devices */
552 for (i
= 0; i
<= 2; i
++)
554 /* Set the index in the SFT */
555 DestinationTable
[i
] = (BYTE
)i
;
557 /* Increase the reference count */
565 /* Get the parent PSP block and handle table */
566 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
567 SourceTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
569 /* Copy the first 20 handles into the new table */
570 for (i
= 0; i
< 20; i
++)
572 DestinationTable
[i
] = SourceTable
[i
];
574 /* Increase the reference count */
575 DosSftRefCount
[SourceTable
[i
]]++;
579 static BOOLEAN
DosCloseHandle(WORD DosHandle
)
585 DPRINT("DosCloseHandle: DosHandle 0x%04X\n", DosHandle
);
587 /* The system PSP has no handle table */
588 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
590 /* Get a pointer to the handle table */
591 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
592 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
594 /* Make sure the handle is open */
595 if (HandleTable
[DosHandle
] == 0xFF) return FALSE
;
597 /* Decrement the reference count of the SFT entry */
598 SftIndex
= HandleTable
[DosHandle
];
599 DosSftRefCount
[SftIndex
]--;
601 /* Check if the reference count fell to zero */
602 if (!DosSftRefCount
[SftIndex
])
604 /* Close the file, it's no longer needed */
605 CloseHandle(DosSystemFileTable
[SftIndex
]);
607 /* Clear the handle */
608 DosSystemFileTable
[SftIndex
] = INVALID_HANDLE_VALUE
;
611 /* Clear the entry in the JFT */
612 HandleTable
[DosHandle
] = 0xFF;
617 static BOOLEAN
DosDuplicateHandle(WORD OldHandle
, WORD NewHandle
)
623 DPRINT("DosDuplicateHandle: OldHandle 0x%04X, NewHandle 0x%04X\n",
627 /* The system PSP has no handle table */
628 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
630 /* Get a pointer to the handle table */
631 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
632 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
634 /* Make sure the old handle is open */
635 if (HandleTable
[OldHandle
] == 0xFF) return FALSE
;
637 /* Check if the new handle is open */
638 if (HandleTable
[NewHandle
] != 0xFF)
641 DosCloseHandle(NewHandle
);
644 /* Increment the reference count of the SFT entry */
645 SftIndex
= HandleTable
[OldHandle
];
646 DosSftRefCount
[SftIndex
]++;
648 /* Make the new handle point to that SFT entry */
649 HandleTable
[NewHandle
] = SftIndex
;
655 static WORD
DosCreateFile(LPWORD Handle
, LPCSTR FilePath
, WORD Attributes
)
660 DPRINT("DosCreateFile: FilePath \"%s\", Attributes 0x%04X\n",
664 /* Create the file */
665 FileHandle
= CreateFileA(FilePath
,
666 GENERIC_READ
| GENERIC_WRITE
,
667 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
673 if (FileHandle
== INVALID_HANDLE_VALUE
)
675 /* Return the error code */
676 return (WORD
)GetLastError();
679 /* Open the DOS handle */
680 DosHandle
= DosOpenHandle(FileHandle
);
682 if (DosHandle
== INVALID_DOS_HANDLE
)
684 /* Close the handle */
685 CloseHandle(FileHandle
);
687 /* Return the error code */
688 return ERROR_TOO_MANY_OPEN_FILES
;
691 /* It was successful */
693 return ERROR_SUCCESS
;
696 static WORD
DosOpenFile(LPWORD Handle
, LPCSTR FilePath
, BYTE AccessMode
)
699 ACCESS_MASK Access
= 0;
702 DPRINT("DosOpenFile: FilePath \"%s\", AccessMode 0x%04X\n",
706 /* Parse the access mode */
707 switch (AccessMode
& 3)
712 Access
= GENERIC_READ
;
719 Access
= GENERIC_WRITE
;
726 Access
= GENERIC_READ
| GENERIC_WRITE
;
733 return ERROR_INVALID_PARAMETER
;
738 FileHandle
= CreateFileA(FilePath
,
740 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
743 FILE_ATTRIBUTE_NORMAL
,
746 if (FileHandle
== INVALID_HANDLE_VALUE
)
748 /* Return the error code */
749 return (WORD
)GetLastError();
752 /* Open the DOS handle */
753 DosHandle
= DosOpenHandle(FileHandle
);
755 if (DosHandle
== INVALID_DOS_HANDLE
)
757 /* Close the handle */
758 CloseHandle(FileHandle
);
760 /* Return the error code */
761 return ERROR_TOO_MANY_OPEN_FILES
;
764 /* It was successful */
766 return ERROR_SUCCESS
;
769 WORD
DosReadFile(WORD FileHandle
, LPVOID Buffer
, WORD Count
, LPWORD BytesRead
)
771 WORD Result
= ERROR_SUCCESS
;
772 DWORD BytesRead32
= 0;
773 HANDLE Handle
= DosGetRealHandle(FileHandle
);
775 DPRINT("DosReadFile: FileHandle 0x%04X, Count 0x%04X\n", FileHandle
, Count
);
777 /* Make sure the handle is valid */
778 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
781 if (!ReadFile(Handle
, Buffer
, Count
, &BytesRead32
, NULL
))
783 /* Store the error code */
784 Result
= (WORD
)GetLastError();
787 /* The number of bytes read is always 16-bit */
788 *BytesRead
= LOWORD(BytesRead32
);
790 /* Return the error code */
794 WORD
DosWriteFile(WORD FileHandle
, LPVOID Buffer
, WORD Count
, LPWORD BytesWritten
)
796 WORD Result
= ERROR_SUCCESS
;
797 DWORD BytesWritten32
= 0;
798 HANDLE Handle
= DosGetRealHandle(FileHandle
);
801 DPRINT("DosWriteFile: FileHandle 0x%04X, Count 0x%04X\n",
805 /* Make sure the handle is valid */
806 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
808 if (IsConsoleHandle(Handle
))
810 for (i
= 0; i
< Count
; i
++)
812 /* Call the BIOS to print the character */
813 VidBiosPrintCharacter(((LPBYTE
)Buffer
)[i
], DOS_CHAR_ATTRIBUTE
, Bda
->VideoPage
);
820 if (!WriteFile(Handle
, Buffer
, Count
, &BytesWritten32
, NULL
))
822 /* Store the error code */
823 Result
= (WORD
)GetLastError();
827 /* The number of bytes written is always 16-bit */
828 *BytesWritten
= LOWORD(BytesWritten32
);
830 /* Return the error code */
834 static WORD
DosSeekFile(WORD FileHandle
, LONG Offset
, BYTE Origin
, LPDWORD NewOffset
)
836 WORD Result
= ERROR_SUCCESS
;
838 HANDLE Handle
= DosGetRealHandle(FileHandle
);
840 DPRINT("DosSeekFile: FileHandle 0x%04X, Offset 0x%08X, Origin 0x%02X\n",
845 /* Make sure the handle is valid */
846 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
848 /* Check if the origin is valid */
849 if (Origin
!= FILE_BEGIN
&& Origin
!= FILE_CURRENT
&& Origin
!= FILE_END
)
851 return ERROR_INVALID_FUNCTION
;
854 /* Move the file pointer */
855 FilePointer
= SetFilePointer(Handle
, Offset
, NULL
, Origin
);
857 /* Check if there's a possibility the operation failed */
858 if (FilePointer
== INVALID_SET_FILE_POINTER
)
860 /* Get the real error code */
861 Result
= (WORD
)GetLastError();
864 if (Result
!= ERROR_SUCCESS
)
866 /* The operation did fail */
870 /* Return the file pointer, if requested */
871 if (NewOffset
) *NewOffset
= FilePointer
;
874 return ERROR_SUCCESS
;
877 static BOOLEAN
DosFlushFileBuffers(WORD FileHandle
)
879 HANDLE Handle
= DosGetRealHandle(FileHandle
);
881 /* Make sure the handle is valid */
882 if (Handle
== INVALID_HANDLE_VALUE
) return FALSE
;
885 * No need to check whether the handle is a console handle since
886 * FlushFileBuffers() automatically does this check and calls
887 * FlushConsoleInputBuffer() for us.
889 // if (IsConsoleHandle(Handle))
890 // return (BOOLEAN)FlushConsoleInputBuffer(Handle);
892 return (BOOLEAN
)FlushFileBuffers(Handle
);
895 static BOOLEAN
DosChangeDrive(BYTE Drive
)
897 WCHAR DirectoryPath
[DOS_CMDLINE_LENGTH
];
899 /* Make sure the drive exists */
900 if (Drive
> (LastDrive
- 'A')) return FALSE
;
902 /* Find the path to the new current directory */
903 swprintf(DirectoryPath
, L
"%c\\%S", Drive
+ 'A', CurrentDirectories
[Drive
]);
905 /* Change the current directory of the process */
906 if (!SetCurrentDirectory(DirectoryPath
)) return FALSE
;
908 /* Set the current drive */
909 CurrentDrive
= Drive
;
915 static BOOLEAN
DosChangeDirectory(LPSTR Directory
)
921 /* Make sure the directory path is not too long */
922 if (strlen(Directory
) >= DOS_DIR_LENGTH
)
924 DosLastError
= ERROR_PATH_NOT_FOUND
;
928 /* Get the drive number */
929 DriveNumber
= Directory
[0] - 'A';
931 /* Make sure the drive exists */
932 if (DriveNumber
> (LastDrive
- 'A'))
934 DosLastError
= ERROR_PATH_NOT_FOUND
;
938 /* Get the file attributes */
939 Attributes
= GetFileAttributesA(Directory
);
941 /* Make sure the path exists and is a directory */
942 if ((Attributes
== INVALID_FILE_ATTRIBUTES
)
943 || !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
945 DosLastError
= ERROR_PATH_NOT_FOUND
;
949 /* Check if this is the current drive */
950 if (DriveNumber
== CurrentDrive
)
952 /* Change the directory */
953 if (!SetCurrentDirectoryA(Directory
))
955 DosLastError
= LOWORD(GetLastError());
960 /* Get the directory part of the path */
961 Path
= strchr(Directory
, '\\');
964 /* Skip the backslash */
968 /* Set the directory for the drive */
971 strncpy(CurrentDirectories
[DriveNumber
], Path
, DOS_DIR_LENGTH
);
975 CurrentDirectories
[DriveNumber
][0] = '\0';
982 /* PUBLIC FUNCTIONS ***********************************************************/
984 VOID
DosInitializePsp(WORD PspSegment
, LPCSTR CommandLine
, WORD ProgramSize
, WORD Environment
)
986 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(PspSegment
);
987 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
989 ZeroMemory(PspBlock
, sizeof(DOS_PSP
));
991 /* Set the exit interrupt */
992 PspBlock
->Exit
[0] = 0xCD; // int 0x20
993 PspBlock
->Exit
[1] = 0x20;
995 /* Set the number of the last paragraph */
996 PspBlock
->LastParagraph
= PspSegment
+ ProgramSize
- 1;
998 /* Save the interrupt vectors */
999 PspBlock
->TerminateAddress
= IntVecTable
[0x22];
1000 PspBlock
->BreakAddress
= IntVecTable
[0x23];
1001 PspBlock
->CriticalAddress
= IntVecTable
[0x24];
1003 /* Set the parent PSP */
1004 PspBlock
->ParentPsp
= CurrentPsp
;
1006 /* Copy the parent handle table */
1007 DosCopyHandleTable(PspBlock
->HandleTable
);
1009 /* Set the environment block */
1010 PspBlock
->EnvBlock
= Environment
;
1012 /* Set the handle table pointers to the internal handle table */
1013 PspBlock
->HandleTableSize
= 20;
1014 PspBlock
->HandleTablePtr
= MAKELONG(0x18, PspSegment
);
1016 /* Set the DOS version */
1017 PspBlock
->DosVersion
= DOS_VERSION
;
1019 /* Set the far call opcodes */
1020 PspBlock
->FarCall
[0] = 0xCD; // int 0x21
1021 PspBlock
->FarCall
[1] = 0x21;
1022 PspBlock
->FarCall
[2] = 0xCB; // retf
1024 /* Set the command line */
1025 PspBlock
->CommandLineSize
= (BYTE
)min(strlen(CommandLine
), DOS_CMDLINE_LENGTH
- 1);
1026 RtlCopyMemory(PspBlock
->CommandLine
, CommandLine
, PspBlock
->CommandLineSize
);
1027 PspBlock
->CommandLine
[PspBlock
->CommandLineSize
] = '\r';
1030 BOOLEAN
DosCreateProcess(LPCSTR CommandLine
, WORD EnvBlock
)
1032 BOOLEAN Success
= FALSE
, AllocatedEnvBlock
= FALSE
;
1033 HANDLE FileHandle
= INVALID_HANDLE_VALUE
, FileMapping
= NULL
;
1034 LPBYTE Address
= NULL
;
1035 LPSTR ProgramFilePath
, Parameters
[256];
1036 CHAR CommandLineCopy
[DOS_CMDLINE_LENGTH
];
1037 CHAR ParamString
[DOS_CMDLINE_LENGTH
];
1038 DWORD ParamCount
= 0;
1041 DWORD i
, FileSize
, ExeSize
;
1042 PIMAGE_DOS_HEADER Header
;
1043 PDWORD RelocationTable
;
1046 DPRINT("DosCreateProcess: CommandLine \"%s\", EnvBlock 0x%04X\n",
1050 /* Save a copy of the command line */
1051 strcpy(CommandLineCopy
, CommandLine
);
1053 /* Get the file name of the executable */
1054 ProgramFilePath
= strtok(CommandLineCopy
, " \t");
1056 /* Load the parameters in the local array */
1057 while ((ParamCount
< sizeof(Parameters
)/sizeof(Parameters
[0]))
1058 && ((Parameters
[ParamCount
] = strtok(NULL
, " \t")) != NULL
))
1063 ZeroMemory(ParamString
, sizeof(ParamString
));
1065 /* Store the parameters in a string */
1066 for (i
= 0; i
< ParamCount
; i
++)
1068 strncat(ParamString
, Parameters
[i
], DOS_CMDLINE_LENGTH
- strlen(ParamString
) - 1);
1069 strncat(ParamString
, " ", DOS_CMDLINE_LENGTH
- strlen(ParamString
) - 1);
1072 /* Open a handle to the executable */
1073 FileHandle
= CreateFileA(ProgramFilePath
,
1078 FILE_ATTRIBUTE_NORMAL
,
1080 if (FileHandle
== INVALID_HANDLE_VALUE
) goto Cleanup
;
1082 /* Get the file size */
1083 FileSize
= GetFileSize(FileHandle
, NULL
);
1085 /* Create a mapping object for the file */
1086 FileMapping
= CreateFileMapping(FileHandle
,
1092 if (FileMapping
== NULL
) goto Cleanup
;
1094 /* Map the file into memory */
1095 Address
= (LPBYTE
)MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 0);
1096 if (Address
== NULL
) goto Cleanup
;
1098 /* Did we get an environment segment? */
1101 /* Set a flag to know if the environment block was allocated here */
1102 AllocatedEnvBlock
= TRUE
;
1104 /* No, copy the one from the parent */
1105 EnvBlock
= DosCopyEnvironmentBlock((CurrentPsp
!= SYSTEM_PSP
)
1106 ? SEGMENT_TO_PSP(CurrentPsp
)->EnvBlock
1111 /* Check if this is an EXE file or a COM file */
1112 if (Address
[0] == 'M' && Address
[1] == 'Z')
1116 /* Get the MZ header */
1117 Header
= (PIMAGE_DOS_HEADER
)Address
;
1119 /* Get the base size of the file, in paragraphs (rounded up) */
1120 ExeSize
= (((Header
->e_cp
- 1) * 512) + Header
->e_cblp
+ 0x0F) >> 4;
1122 /* Add the PSP size, in paragraphs */
1123 ExeSize
+= sizeof(DOS_PSP
) >> 4;
1125 /* Add the maximum size that should be allocated */
1126 ExeSize
+= Header
->e_maxalloc
;
1128 /* Make sure it does not pass 0xFFFF */
1129 if (ExeSize
> 0xFFFF) ExeSize
= 0xFFFF;
1131 /* Reduce the size one by one until the allocation is successful */
1132 for (i
= Header
->e_maxalloc
; i
>= Header
->e_minalloc
; i
--, ExeSize
--)
1134 /* Try to allocate that much memory */
1135 Segment
= DosAllocateMemory((WORD
)ExeSize
, NULL
);
1136 if (Segment
!= 0) break;
1139 /* Check if at least the lowest allocation was successful */
1140 if (Segment
== 0) goto Cleanup
;
1142 /* Initialize the PSP */
1143 DosInitializePsp(Segment
,
1148 /* The process owns its own memory */
1149 DosChangeMemoryOwner(Segment
, Segment
);
1150 DosChangeMemoryOwner(EnvBlock
, Segment
);
1152 /* Copy the program to Segment:0100 */
1153 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1154 Address
+ (Header
->e_cparhdr
<< 4),
1155 min(FileSize
- (Header
->e_cparhdr
<< 4),
1156 (ExeSize
<< 4) - sizeof(DOS_PSP
)));
1158 /* Get the relocation table */
1159 RelocationTable
= (PDWORD
)(Address
+ Header
->e_lfarlc
);
1161 /* Perform relocations */
1162 for (i
= 0; i
< Header
->e_crlc
; i
++)
1164 /* Get a pointer to the word that needs to be patched */
1165 RelocWord
= (PWORD
)SEG_OFF_TO_PTR(Segment
+ HIWORD(RelocationTable
[i
]),
1166 0x100 + LOWORD(RelocationTable
[i
]));
1168 /* Add the number of the EXE segment to it */
1169 *RelocWord
+= Segment
+ (sizeof(DOS_PSP
) >> 4);
1172 /* Set the initial segment registers */
1176 /* Set the stack to the location from the header */
1177 EmulatorSetStack(Segment
+ (sizeof(DOS_PSP
) >> 4) + Header
->e_ss
,
1181 CurrentPsp
= Segment
;
1182 DiskTransferArea
= MAKELONG(0x80, Segment
);
1183 EmulatorExecute(Segment
+ Header
->e_cs
+ (sizeof(DOS_PSP
) >> 4),
1192 /* Find the maximum amount of memory that can be allocated */
1193 DosAllocateMemory(0xFFFF, &MaxAllocSize
);
1195 /* Make sure it's enough for the whole program and the PSP */
1196 if (((DWORD
)MaxAllocSize
<< 4) < (FileSize
+ sizeof(DOS_PSP
))) goto Cleanup
;
1198 /* Allocate all of it */
1199 Segment
= DosAllocateMemory(MaxAllocSize
, NULL
);
1200 if (Segment
== 0) goto Cleanup
;
1202 /* The process owns its own memory */
1203 DosChangeMemoryOwner(Segment
, Segment
);
1204 DosChangeMemoryOwner(EnvBlock
, Segment
);
1206 /* Copy the program to Segment:0100 */
1207 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1211 /* Initialize the PSP */
1212 DosInitializePsp(Segment
,
1217 /* Set the initial segment registers */
1221 /* Set the stack to the last word of the segment */
1222 EmulatorSetStack(Segment
, 0xFFFE);
1225 * Set the value on the stack to 0, so that a near return
1226 * jumps to PSP:0000 which has the exit code.
1228 *((LPWORD
)SEG_OFF_TO_PTR(Segment
, 0xFFFE)) = 0;
1231 CurrentPsp
= Segment
;
1232 DiskTransferArea
= MAKELONG(0x80, Segment
);
1233 EmulatorExecute(Segment
, 0x100);
1241 /* It was not successful, cleanup the DOS memory */
1242 if (AllocatedEnvBlock
) DosFreeMemory(EnvBlock
);
1243 if (Segment
) DosFreeMemory(Segment
);
1247 if (Address
!= NULL
) UnmapViewOfFile(Address
);
1249 /* Close the file mapping object */
1250 if (FileMapping
!= NULL
) CloseHandle(FileMapping
);
1252 /* Close the file handle */
1253 if (FileHandle
!= INVALID_HANDLE_VALUE
) CloseHandle(FileHandle
);
1258 VOID
DosTerminateProcess(WORD Psp
, BYTE ReturnCode
)
1261 WORD McbSegment
= FIRST_MCB_SEGMENT
;
1262 PDOS_MCB CurrentMcb
;
1263 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
1264 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(Psp
);
1266 DPRINT("DosTerminateProcess: Psp 0x%04X, ReturnCode 0x%02X\n",
1270 /* Check if this PSP is it's own parent */
1271 if (PspBlock
->ParentPsp
== Psp
) goto Done
;
1273 for (i
= 0; i
< PspBlock
->HandleTableSize
; i
++)
1275 /* Close the handle */
1279 /* Free the memory used by the process */
1282 /* Get a pointer to the MCB */
1283 CurrentMcb
= SEGMENT_TO_MCB(McbSegment
);
1285 /* Make sure the MCB is valid */
1286 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!='Z') break;
1288 /* If this block was allocated by the process, free it */
1289 if (CurrentMcb
->OwnerPsp
== Psp
) DosFreeMemory(McbSegment
+ 1);
1291 /* If this was the last block, quit */
1292 if (CurrentMcb
->BlockType
== 'Z') break;
1294 /* Update the segment and continue */
1295 McbSegment
+= CurrentMcb
->Size
+ 1;
1299 /* Restore the interrupt vectors */
1300 IntVecTable
[0x22] = PspBlock
->TerminateAddress
;
1301 IntVecTable
[0x23] = PspBlock
->BreakAddress
;
1302 IntVecTable
[0x24] = PspBlock
->CriticalAddress
;
1304 /* Update the current PSP */
1305 if (Psp
== CurrentPsp
)
1307 CurrentPsp
= PspBlock
->ParentPsp
;
1308 if (CurrentPsp
== SYSTEM_PSP
) VdmRunning
= FALSE
;
1311 /* Save the return code - Normal termination */
1312 DosErrorLevel
= MAKEWORD(ReturnCode
, 0x00);
1314 /* Return control to the parent process */
1315 EmulatorExecute(HIWORD(PspBlock
->TerminateAddress
),
1316 LOWORD(PspBlock
->TerminateAddress
));
1319 BOOLEAN
DosHandleIoctl(BYTE ControlCode
, WORD FileHandle
)
1321 HANDLE Handle
= DosGetRealHandle(FileHandle
);
1323 if (Handle
== INVALID_HANDLE_VALUE
)
1326 DosLastError
= ERROR_FILE_NOT_FOUND
;
1330 switch (ControlCode
)
1332 /* Get Device Information */
1338 * See Ralf Brown: http://www.ctyme.com/intr/rb-2820.htm
1339 * for a list of possible flags.
1342 if (Handle
== DosSystemFileTable
[0])
1347 else if (Handle
== DosSystemFileTable
[1])
1349 /* Console output */
1353 /* It is a device */
1356 /* Return the device information word */
1361 /* Unsupported control code */
1364 DPRINT1("Unsupported IOCTL: 0x%02X\n", ControlCode
);
1366 DosLastError
= ERROR_INVALID_PARAMETER
;
1372 VOID WINAPI
DosInt20h(LPWORD Stack
)
1374 /* This is the exit interrupt */
1375 DosTerminateProcess(Stack
[STACK_CS
], 0);
1378 VOID WINAPI
DosInt21h(LPWORD Stack
)
1381 SYSTEMTIME SystemTime
;
1383 PDOS_INPUT_BUFFER InputBuffer
;
1385 /* Check the value in the AH register */
1388 /* Terminate Program */
1391 DosTerminateProcess(Stack
[STACK_CS
], 0);
1395 /* Read Character from STDIN with Echo */
1398 Character
= DosReadCharacter();
1399 DosPrintCharacter(Character
);
1401 /* Let the BOP repeat if needed */
1408 /* Write Character to STDOUT */
1411 Character
= getDL();
1412 DosPrintCharacter(Character
);
1415 * We return the output character (DOS 2.1+).
1416 * Also, if we're going to output a TAB, then
1417 * don't return a TAB but a SPACE instead.
1418 * See Ralf Brown: http://www.ctyme.com/intr/rb-2554.htm
1419 * for more information.
1421 setAL(Character
== '\t' ? ' ' : Character
);
1425 /* Read Character from STDAUX */
1428 // FIXME: Really read it from STDAUX!
1429 DPRINT1("INT 16h, 03h: Read character from STDAUX is HALFPLEMENTED\n");
1430 setAL(DosReadCharacter());
1434 /* Write Character to STDAUX */
1437 // FIXME: Really write it to STDAUX!
1438 DPRINT1("INT 16h, 04h: Write character to STDAUX is HALFPLEMENTED\n");
1439 DosPrintCharacter(getDL());
1443 /* Write Character to Printer */
1446 // FIXME: Really write it to printer!
1447 DPRINT1("INT 16h, 05h: Write character to printer is HALFPLEMENTED -\n\n");
1448 DPRINT1("0x%p\n", getDL());
1449 DPRINT1("\n\n-----------\n\n");
1453 /* Direct Console I/O */
1456 Character
= getDL();
1458 if (Character
!= 0xFF)
1461 DosPrintCharacter(Character
);
1464 * We return the output character (DOS 2.1+).
1465 * See Ralf Brown: http://www.ctyme.com/intr/rb-2558.htm
1466 * for more information.
1473 if (DosCheckInput())
1475 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_ZF
;
1476 setAL(DosReadCharacter());
1480 /* No character available */
1481 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_ZF
;
1489 /* Character Input without Echo */
1493 Character
= DosReadCharacter();
1495 /* Let the BOP repeat if needed */
1502 /* Write string to STDOUT */
1505 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1507 while (*String
!= '$')
1509 DosPrintCharacter(*String
);
1514 * We return the terminating character (DOS 2.1+).
1515 * See Ralf Brown: http://www.ctyme.com/intr/rb-2562.htm
1516 * for more information.
1522 /* Read Buffered Input */
1525 InputBuffer
= (PDOS_INPUT_BUFFER
)SEG_OFF_TO_PTR(getDS(), getDX());
1527 while (Stack
[STACK_COUNTER
] < InputBuffer
->MaxLength
)
1529 /* Try to read a character */
1530 Character
= DosReadCharacter();
1532 /* If it's not ready yet, let the BOP repeat */
1535 /* Echo the character and append it to the buffer */
1536 DosPrintCharacter(Character
);
1537 InputBuffer
->Buffer
[Stack
[STACK_COUNTER
]] = Character
;
1539 if (Character
== '\r') break;
1540 Stack
[STACK_COUNTER
]++;
1543 /* Update the length */
1544 InputBuffer
->Length
= Stack
[STACK_COUNTER
];
1548 /* Get STDIN Status */
1551 setAL(DosCheckInput() ? 0xFF : 0x00);
1555 /* Flush Buffer and Read STDIN */
1558 BYTE InputFunction
= getAL();
1560 /* Flush STDIN buffer */
1561 DosFlushFileBuffers(DOS_INPUT_HANDLE
); // Maybe just create a DosFlushInputBuffer...
1564 * If the input function number contained in AL is valid, i.e.
1565 * AL == 0x01 or 0x06 or 0x07 or 0x08 or 0x0A, call ourselves
1566 * recursively with AL == AH.
1568 if (InputFunction
== 0x01 || InputFunction
== 0x06 ||
1569 InputFunction
== 0x07 || InputFunction
== 0x08 ||
1570 InputFunction
== 0x0A)
1572 setAH(InputFunction
);
1574 * Instead of calling ourselves really recursively as in:
1576 * prefer resetting the CF flag to let the BOP repeat.
1586 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1588 // TODO: Flush what's needed.
1589 DPRINT1("INT 21h, 0Dh is UNIMPLEMENTED\n");
1591 /* Clear CF in DOS 6 only */
1592 if (PspBlock
->DosVersion
== 0x0006)
1593 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1598 /* Set Default Drive */
1601 DosChangeDrive(getDL());
1602 setAL(LastDrive
- 'A' + 1);
1606 /* NULL Function for CP/M Compatibility */
1610 * This function corresponds to the CP/M BDOS function
1611 * "get bit map of logged drives", which is meaningless
1614 * For: PTS-DOS 6.51 & S/DOS 1.0 - EXTENDED RENAME FILE USING FCB
1615 * See Ralf Brown: http://www.ctyme.com/intr/rb-2584.htm
1616 * for more information.
1622 /* Get Default Drive */
1625 setAL(CurrentDrive
);
1629 /* Set Disk Transfer Area */
1632 DiskTransferArea
= MAKELONG(getDX(), getDS());
1636 /* NULL Function for CP/M Compatibility */
1641 * Function 0x1D corresponds to the CP/M BDOS function
1642 * "get bit map of read-only drives", which is meaningless
1644 * See Ralf Brown: http://www.ctyme.com/intr/rb-2592.htm
1645 * for more information.
1647 * Function 0x1E corresponds to the CP/M BDOS function
1648 * "set file attributes", which was meaningless under MS-DOS 1.x.
1649 * See Ralf Brown: http://www.ctyme.com/intr/rb-2593.htm
1650 * for more information.
1656 /* NULL Function for CP/M Compatibility */
1660 * This function corresponds to the CP/M BDOS function
1661 * "get/set default user (sublibrary) number", which is meaningless
1664 * For: S/DOS 1.0+ & PTS-DOS 6.51+ - GET OEM REVISION
1665 * See Ralf Brown: http://www.ctyme.com/intr/rb-2596.htm
1666 * for more information.
1672 /* Set Interrupt Vector */
1675 ULONG FarPointer
= MAKELONG(getDX(), getDS());
1676 DPRINT1("Setting interrupt 0x%x ...\n", getAL());
1678 /* Write the new far pointer to the IDT */
1679 ((PULONG
)BaseAddress
)[getAL()] = FarPointer
;
1683 /* Create New PSP */
1686 DPRINT1("INT 21h, 26h - Create New PSP is UNIMPLEMENTED\n");
1690 /* Get System Date */
1693 GetLocalTime(&SystemTime
);
1694 setCX(SystemTime
.wYear
);
1695 setDX(MAKEWORD(SystemTime
.wDay
, SystemTime
.wMonth
));
1696 setAL(SystemTime
.wDayOfWeek
);
1700 /* Set System Date */
1703 GetLocalTime(&SystemTime
);
1704 SystemTime
.wYear
= getCX();
1705 SystemTime
.wMonth
= getDH();
1706 SystemTime
.wDay
= getDL();
1708 /* Return success or failure */
1709 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1713 /* Get System Time */
1716 GetLocalTime(&SystemTime
);
1717 setCX(MAKEWORD(SystemTime
.wMinute
, SystemTime
.wHour
));
1718 setDX(MAKEWORD(SystemTime
.wMilliseconds
/ 10, SystemTime
.wSecond
));
1722 /* Set System Time */
1725 GetLocalTime(&SystemTime
);
1726 SystemTime
.wHour
= getCH();
1727 SystemTime
.wMinute
= getCL();
1728 SystemTime
.wSecond
= getDH();
1729 SystemTime
.wMilliseconds
= getDL() * 10; // In hundredths of seconds
1731 /* Return success or failure */
1732 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1736 /* Get Disk Transfer Area */
1739 setES(HIWORD(DiskTransferArea
));
1740 setBX(LOWORD(DiskTransferArea
));
1744 /* Get DOS Version */
1747 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1750 * DOS 2+ - GET DOS VERSION
1751 * See Ralf Brown: http://www.ctyme.com/intr/rb-2711.htm
1752 * for more information.
1755 if (LOBYTE(PspBlock
->DosVersion
) < 5 || getAL() == 0x00)
1758 * Return DOS OEM number:
1759 * 0x00 for IBM PC-DOS
1760 * 0x02 for packaged MS-DOS
1765 if (LOBYTE(PspBlock
->DosVersion
) >= 5 && getAL() == 0x01)
1768 * Return version flag:
1769 * 1 << 3 if DOS is in ROM,
1770 * 0 (reserved) if not.
1775 /* Return DOS 24-bit user serial number in BL:CX */
1780 * Return DOS version: Minor:Major in AH:AL
1781 * The Windows NT DOS box returns version 5.00, subject to SETVER.
1783 setAX(PspBlock
->DosVersion
);
1788 /* Extended functionalities */
1791 if (getAL() == 0x06)
1794 * DOS 5+ - GET TRUE VERSION NUMBER
1795 * This function always returns the true version number, unlike
1796 * AH=30h, whose return value may be changed with SETVER.
1797 * See Ralf Brown: http://www.ctyme.com/intr/rb-2730.htm
1798 * for more information.
1802 * Return the true DOS version: Minor:Major in BH:BL
1803 * The Windows NT DOS box returns BX=3205h (version 5.50).
1805 setBX(NTDOS_VERSION
);
1807 /* DOS revision 0 */
1815 // /* Invalid subfunction */
1822 /* Get Interrupt Vector */
1825 DWORD FarPointer
= ((PDWORD
)BaseAddress
)[getAL()];
1827 /* Read the address from the IDT into ES:BX */
1828 setES(HIWORD(FarPointer
));
1829 setBX(LOWORD(FarPointer
));
1833 /* SWITCH character - AVAILDEV */
1836 if (getAL() == 0x00)
1839 * DOS 2+ - "SWITCHAR" - GET SWITCH CHARACTER
1840 * This setting is ignored by MS-DOS 4.0+.
1841 * MS-DOS 5+ always return AL=00h/DL=2Fh.
1842 * See Ralf Brown: http://www.ctyme.com/intr/rb-2752.htm
1843 * for more information.
1848 else if (getAL() == 0x01)
1851 * DOS 2+ - "SWITCHAR" - SET SWITCH CHARACTER
1852 * This setting is ignored by MS-DOS 5+.
1853 * See Ralf Brown: http://www.ctyme.com/intr/rb-2753.htm
1854 * for more information.
1859 else if (getAL() == 0x02)
1862 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1863 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1864 * for more information.
1869 else if (getAL() == 0x03)
1872 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1873 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1874 * for more information.
1881 /* Invalid subfunction */
1888 /* Create Directory */
1891 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1893 if (CreateDirectoryA(String
, NULL
))
1895 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1899 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1900 setAX(LOWORD(GetLastError()));
1906 /* Remove Directory */
1909 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1911 if (RemoveDirectoryA(String
))
1913 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1917 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1918 setAX(LOWORD(GetLastError()));
1924 /* Set Current Directory */
1927 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1929 if (DosChangeDirectory(String
))
1931 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1935 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1936 setAX(DosLastError
);
1946 WORD ErrorCode
= DosCreateFile(&FileHandle
,
1947 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
1952 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1957 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1968 WORD ErrorCode
= DosOpenFile(&FileHandle
,
1969 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
1974 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1979 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1989 if (DosCloseHandle(getBX()))
1991 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1995 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1996 setAX(ERROR_INVALID_HANDLE
);
2002 /* Read from File or Device */
2005 WORD Handle
= getBX();
2006 LPBYTE Buffer
= (LPBYTE
)SEG_OFF_TO_PTR(getDS(), getDX());
2007 WORD Count
= getCX();
2009 WORD ErrorCode
= ERROR_SUCCESS
;
2012 if (IsConsoleHandle(DosGetRealHandle(Handle
)))
2014 while (Stack
[STACK_COUNTER
] < Count
)
2016 /* Read a character from the BIOS */
2017 Character
= LOBYTE(BiosGetCharacter());
2019 /* Stop if the BOP needs to be repeated */
2022 // FIXME: Security checks!
2023 DosPrintCharacter(Character
);
2024 Buffer
[Stack
[STACK_COUNTER
]++] = Character
;
2026 if (Character
== '\r')
2028 /* Stop on first carriage return */
2029 DosPrintCharacter('\n');
2034 if (Character
!= '\r')
2036 if (Stack
[STACK_COUNTER
] < Count
) ErrorCode
= ERROR_NOT_READY
;
2037 else BytesRead
= Count
;
2039 else BytesRead
= Stack
[STACK_COUNTER
];
2043 /* Use the file reading function */
2044 ErrorCode
= DosReadFile(Handle
, Buffer
, Count
, &BytesRead
);
2047 if (ErrorCode
== ERROR_SUCCESS
)
2049 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2052 else if (ErrorCode
!= ERROR_NOT_READY
)
2054 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2060 /* Write to File or Device */
2063 WORD BytesWritten
= 0;
2064 WORD ErrorCode
= DosWriteFile(getBX(),
2065 SEG_OFF_TO_PTR(getDS(), getDX()),
2069 if (ErrorCode
== ERROR_SUCCESS
)
2071 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2072 setAX(BytesWritten
);
2076 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2086 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2088 if (demFileDelete(FileName
) == ERROR_SUCCESS
)
2090 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2092 * See Ralf Brown: http://www.ctyme.com/intr/rb-2797.htm
2093 * "AX destroyed (DOS 3.3) AL seems to be drive of deleted file."
2095 setAL(FileName
[0] - 'A');
2099 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2100 setAX(GetLastError());
2110 WORD ErrorCode
= DosSeekFile(getBX(),
2111 MAKELONG(getDX(), getCX()),
2115 if (ErrorCode
== ERROR_SUCCESS
)
2117 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2119 /* Return the new offset in DX:AX */
2120 setDX(HIWORD(NewLocation
));
2121 setAX(LOWORD(NewLocation
));
2125 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2132 /* Get/Set File Attributes */
2136 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2138 if (getAL() == 0x00)
2140 /* Get the attributes */
2141 Attributes
= GetFileAttributesA(FileName
);
2143 /* Check if it failed */
2144 if (Attributes
== INVALID_FILE_ATTRIBUTES
)
2146 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2147 setAX(GetLastError());
2151 /* Return the attributes that DOS can understand */
2152 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2153 setCX(Attributes
& 0x00FF);
2156 else if (getAL() == 0x01)
2158 /* Try to set the attributes */
2159 if (SetFileAttributesA(FileName
, getCL()))
2161 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2165 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2166 setAX(GetLastError());
2171 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2172 setAX(ERROR_INVALID_FUNCTION
);
2181 if (DosHandleIoctl(getAL(), getBX()))
2183 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2187 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2188 setAX(DosLastError
);
2194 /* Duplicate Handle */
2198 HANDLE Handle
= DosGetRealHandle(getBX());
2200 if (Handle
!= INVALID_HANDLE_VALUE
)
2202 /* The handle is invalid */
2203 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2204 setAX(ERROR_INVALID_HANDLE
);
2208 /* Open a new handle to the same entry */
2209 NewHandle
= DosOpenHandle(Handle
);
2211 if (NewHandle
== INVALID_DOS_HANDLE
)
2213 /* Too many files open */
2214 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2215 setAX(ERROR_TOO_MANY_OPEN_FILES
);
2219 /* Return the result */
2220 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2225 /* Force Duplicate Handle */
2228 if (DosDuplicateHandle(getBX(), getCX()))
2230 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2234 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2235 setAX(ERROR_INVALID_HANDLE
);
2241 /* Get Current Directory */
2244 BYTE DriveNumber
= getDL();
2245 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getSI());
2247 /* Get the real drive number */
2248 if (DriveNumber
== 0)
2250 DriveNumber
= CurrentDrive
;
2254 /* Decrement DriveNumber since it was 1-based */
2258 if (DriveNumber
<= LastDrive
- 'A')
2261 * Copy the current directory into the target buffer.
2262 * It doesn't contain the drive letter and the backslash.
2264 strncpy(String
, CurrentDirectories
[DriveNumber
], DOS_DIR_LENGTH
);
2265 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2266 setAX(0x0100); // Undocumented, see Ralf Brown: http://www.ctyme.com/intr/rb-2933.htm
2270 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2271 setAX(ERROR_INVALID_DRIVE
);
2277 /* Allocate Memory */
2280 WORD MaxAvailable
= 0;
2281 WORD Segment
= DosAllocateMemory(getBX(), &MaxAvailable
);
2285 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2290 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2291 setAX(DosLastError
);
2292 setBX(MaxAvailable
);
2301 if (DosFreeMemory(getES()))
2303 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2307 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2308 setAX(ERROR_ARENA_TRASHED
);
2314 /* Resize Memory Block */
2319 if (DosResizeMemory(getES(), getBX(), &Size
))
2321 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2325 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2326 setAX(DosLastError
);
2333 /* Terminate With Return Code */
2336 DosTerminateProcess(CurrentPsp
, getAL());
2340 /* Get Return Code (ERRORLEVEL) */
2344 * According to Ralf Brown: http://www.ctyme.com/intr/rb-2976.htm
2345 * DosErrorLevel is cleared after being read by this function.
2347 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2348 setAX(DosErrorLevel
);
2349 DosErrorLevel
= 0x0000; // Clear it
2353 /* Find First File */
2356 WORD Result
= (WORD
)demFileFindFirst(FAR_POINTER(DiskTransferArea
),
2357 SEG_OFF_TO_PTR(getDS(), getDX()),
2361 if (Result
== ERROR_SUCCESS
) Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2362 else Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2367 /* Find Next File */
2370 WORD Result
= (WORD
)demFileFindNext(FAR_POINTER(DiskTransferArea
));
2373 if (Result
== ERROR_SUCCESS
) Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2374 else Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2379 /* Internal - Set Current Process ID (Set PSP Address) */
2382 // FIXME: Is it really what it's done ??
2383 CurrentPsp
= getBX();
2387 /* Internal - Get Current Process ID (Get PSP Address) */
2389 /* Get Current PSP Address */
2393 * Undocumented AH=51h is identical to the documented AH=62h.
2394 * See Ralf Brown: http://www.ctyme.com/intr/rb-2982.htm
2395 * and http://www.ctyme.com/intr/rb-3140.htm
2396 * for more information.
2402 /* Get/Set Memory Management Options */
2405 if (getAL() == 0x00)
2407 /* Get allocation strategy */
2408 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2409 setAX(DosAllocStrategy
);
2411 else if (getAL() == 0x01)
2413 /* Set allocation strategy */
2415 if ((getBL() & (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2416 == (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2418 /* Can't set both */
2419 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2420 setAX(ERROR_INVALID_PARAMETER
);
2424 if ((getBL() & 0x3F) > DOS_ALLOC_LAST_FIT
)
2426 /* Invalid allocation strategy */
2427 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2428 setAX(ERROR_INVALID_PARAMETER
);
2432 DosAllocStrategy
= getBL();
2433 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2435 else if (getAL() == 0x02)
2437 /* Get UMB link state */
2438 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2439 setAL(DosUmbLinked
? 0x01 : 0x00);
2441 else if (getAL() == 0x03)
2443 /* Set UMB link state */
2444 if (getBX()) DosLinkUmb();
2445 else DosUnlinkUmb();
2446 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2450 /* Invalid or unsupported function */
2451 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2452 setAX(ERROR_INVALID_FUNCTION
);
2461 DPRINT1("DOS Function INT 0x21, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2464 setAL(0); // Some functions expect AL to be 0 when it's not supported.
2465 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2470 VOID WINAPI
DosBreakInterrupt(LPWORD Stack
)
2472 UNREFERENCED_PARAMETER(Stack
);
2478 VOID WINAPI
DosFastConOut(LPWORD Stack
)
2481 * This is the DOS 2+ Fast Console Output Interrupt.
2482 * See Ralf Brown: http://www.ctyme.com/intr/rb-4124.htm
2483 * for more information.
2487 if (Stack
[STACK_COUNTER
] == 0)
2489 Stack
[STACK_COUNTER
]++;
2491 /* Save AX and BX */
2492 Stack
[STACK_VAR_A
] = getAX();
2493 Stack
[STACK_VAR_B
] = getBX();
2495 /* Rewind the BOP manually, we can't use CF because the interrupt could modify it */
2496 EmulatorExecute(getCS(), getIP() - 4);
2498 /* Call INT 0x10, AH = 0x0E */
2500 setBL(DOS_CHAR_ATTRIBUTE
);
2501 setBH(Bda
->VideoPage
);
2503 EmulatorInterrupt(0x10);
2507 /* Restore AX and BX */
2508 setAX(Stack
[STACK_VAR_A
]);
2509 setBX(Stack
[STACK_VAR_B
]);
2512 /* Save AX and BX */
2513 USHORT AX
= getAX();
2514 USHORT BX
= getBX();
2516 setBL(DOS_CHAR_ATTRIBUTE
);
2517 setBH(Bda
->VideoPage
);
2519 Int32Call(&DosContext
, 0x10);
2521 /* Restore AX and BX */
2527 VOID WINAPI
DosInt2Fh(LPWORD Stack
)
2529 DPRINT1("DOS System Function INT 0x2F, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2531 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2534 BOOLEAN
DosKRNLInitialize(VOID
)
2540 CHAR CurrentDirectory
[MAX_PATH
];
2541 CHAR DosDirectory
[DOS_DIR_LENGTH
];
2547 /* Clear the current directory buffer */
2548 ZeroMemory(CurrentDirectories
, sizeof(CurrentDirectories
));
2550 /* Get the current directory */
2551 if (!GetCurrentDirectoryA(MAX_PATH
, CurrentDirectory
))
2553 // TODO: Use some kind of default path?
2557 /* Convert that to a DOS path */
2558 if (!GetShortPathNameA(CurrentDirectory
, DosDirectory
, DOS_DIR_LENGTH
))
2560 // TODO: Use some kind of default path?
2565 CurrentDrive
= DosDirectory
[0] - 'A';
2567 /* Get the directory part of the path */
2568 Path
= strchr(DosDirectory
, '\\');
2571 /* Skip the backslash */
2575 /* Set the directory */
2578 strncpy(CurrentDirectories
[CurrentDrive
], Path
, DOS_DIR_LENGTH
);
2581 /* Read CONFIG.SYS */
2582 Stream
= _wfopen(DOS_CONFIG_PATH
, L
"r");
2585 while (fgetws(Buffer
, 256, Stream
))
2587 // TODO: Parse the line
2592 /* Initialize the SFT */
2593 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
2595 DosSystemFileTable
[i
] = INVALID_HANDLE_VALUE
;
2596 DosSftRefCount
[i
] = 0;
2599 /* Get handles to standard I/O devices */
2600 DosSystemFileTable
[0] = GetStdHandle(STD_INPUT_HANDLE
);
2601 DosSystemFileTable
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
2602 DosSystemFileTable
[2] = GetStdHandle(STD_ERROR_HANDLE
);
2606 /* Initialize the callback context */
2607 InitializeContext(&DosContext
, 0x0070, 0x0000);
2609 /* Register the DOS 32-bit Interrupts */
2610 RegisterDosInt32(0x20, DosInt20h
);
2611 RegisterDosInt32(0x21, DosInt21h
);
2612 // RegisterDosInt32(0x22, DosInt22h ); // Termination
2613 RegisterDosInt32(0x23, DosBreakInterrupt
); // Ctrl-C / Ctrl-Break
2614 // RegisterDosInt32(0x24, DosInt24h ); // Critical Error
2615 RegisterDosInt32(0x29, DosFastConOut
); // DOS 2+ Fast Console Output
2616 RegisterDosInt32(0x2F, DosInt2Fh
);