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
++)
816 /* Set the parameters */
817 setAL(((PCHAR
)Buffer
)[i
]);
818 setBL(DOS_CHAR_ATTRIBUTE
);
819 setBH(Bda
->VideoPage
);
821 /* Call the BIOS INT 10h, AH=0Eh "Teletype Output" */
823 Int32Call(&DosContext
, BIOS_VIDEO_INTERRUPT
);
825 /* Restore AX and BX */
835 if (!WriteFile(Handle
, Buffer
, Count
, &BytesWritten32
, NULL
))
837 /* Store the error code */
838 Result
= (WORD
)GetLastError();
842 /* The number of bytes written is always 16-bit */
843 *BytesWritten
= LOWORD(BytesWritten32
);
845 /* Return the error code */
849 static WORD
DosSeekFile(WORD FileHandle
, LONG Offset
, BYTE Origin
, LPDWORD NewOffset
)
851 WORD Result
= ERROR_SUCCESS
;
853 HANDLE Handle
= DosGetRealHandle(FileHandle
);
855 DPRINT("DosSeekFile: FileHandle 0x%04X, Offset 0x%08X, Origin 0x%02X\n",
860 /* Make sure the handle is valid */
861 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
863 /* Check if the origin is valid */
864 if (Origin
!= FILE_BEGIN
&& Origin
!= FILE_CURRENT
&& Origin
!= FILE_END
)
866 return ERROR_INVALID_FUNCTION
;
869 /* Move the file pointer */
870 FilePointer
= SetFilePointer(Handle
, Offset
, NULL
, Origin
);
872 /* Check if there's a possibility the operation failed */
873 if (FilePointer
== INVALID_SET_FILE_POINTER
)
875 /* Get the real error code */
876 Result
= (WORD
)GetLastError();
879 if (Result
!= ERROR_SUCCESS
)
881 /* The operation did fail */
885 /* Return the file pointer, if requested */
886 if (NewOffset
) *NewOffset
= FilePointer
;
889 return ERROR_SUCCESS
;
892 static BOOLEAN
DosFlushFileBuffers(WORD FileHandle
)
894 HANDLE Handle
= DosGetRealHandle(FileHandle
);
896 /* Make sure the handle is valid */
897 if (Handle
== INVALID_HANDLE_VALUE
) return FALSE
;
900 * No need to check whether the handle is a console handle since
901 * FlushFileBuffers() automatically does this check and calls
902 * FlushConsoleInputBuffer() for us.
904 // if (IsConsoleHandle(Handle))
905 // return (BOOLEAN)FlushConsoleInputBuffer(Handle);
907 return (BOOLEAN
)FlushFileBuffers(Handle
);
910 static BOOLEAN
DosChangeDrive(BYTE Drive
)
912 WCHAR DirectoryPath
[DOS_CMDLINE_LENGTH
];
914 /* Make sure the drive exists */
915 if (Drive
> (LastDrive
- 'A')) return FALSE
;
917 /* Find the path to the new current directory */
918 swprintf(DirectoryPath
, L
"%c\\%S", Drive
+ 'A', CurrentDirectories
[Drive
]);
920 /* Change the current directory of the process */
921 if (!SetCurrentDirectory(DirectoryPath
)) return FALSE
;
923 /* Set the current drive */
924 CurrentDrive
= Drive
;
930 static BOOLEAN
DosChangeDirectory(LPSTR Directory
)
936 /* Make sure the directory path is not too long */
937 if (strlen(Directory
) >= DOS_DIR_LENGTH
)
939 DosLastError
= ERROR_PATH_NOT_FOUND
;
943 /* Get the drive number */
944 DriveNumber
= Directory
[0] - 'A';
946 /* Make sure the drive exists */
947 if (DriveNumber
> (LastDrive
- 'A'))
949 DosLastError
= ERROR_PATH_NOT_FOUND
;
953 /* Get the file attributes */
954 Attributes
= GetFileAttributesA(Directory
);
956 /* Make sure the path exists and is a directory */
957 if ((Attributes
== INVALID_FILE_ATTRIBUTES
)
958 || !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
960 DosLastError
= ERROR_PATH_NOT_FOUND
;
964 /* Check if this is the current drive */
965 if (DriveNumber
== CurrentDrive
)
967 /* Change the directory */
968 if (!SetCurrentDirectoryA(Directory
))
970 DosLastError
= LOWORD(GetLastError());
975 /* Get the directory part of the path */
976 Path
= strchr(Directory
, '\\');
979 /* Skip the backslash */
983 /* Set the directory for the drive */
986 strncpy(CurrentDirectories
[DriveNumber
], Path
, DOS_DIR_LENGTH
);
990 CurrentDirectories
[DriveNumber
][0] = '\0';
997 /* PUBLIC FUNCTIONS ***********************************************************/
999 VOID
DosInitializePsp(WORD PspSegment
, LPCSTR CommandLine
, WORD ProgramSize
, WORD Environment
)
1001 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(PspSegment
);
1002 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
1004 ZeroMemory(PspBlock
, sizeof(DOS_PSP
));
1006 /* Set the exit interrupt */
1007 PspBlock
->Exit
[0] = 0xCD; // int 0x20
1008 PspBlock
->Exit
[1] = 0x20;
1010 /* Set the number of the last paragraph */
1011 PspBlock
->LastParagraph
= PspSegment
+ ProgramSize
- 1;
1013 /* Save the interrupt vectors */
1014 PspBlock
->TerminateAddress
= IntVecTable
[0x22];
1015 PspBlock
->BreakAddress
= IntVecTable
[0x23];
1016 PspBlock
->CriticalAddress
= IntVecTable
[0x24];
1018 /* Set the parent PSP */
1019 PspBlock
->ParentPsp
= CurrentPsp
;
1021 /* Copy the parent handle table */
1022 DosCopyHandleTable(PspBlock
->HandleTable
);
1024 /* Set the environment block */
1025 PspBlock
->EnvBlock
= Environment
;
1027 /* Set the handle table pointers to the internal handle table */
1028 PspBlock
->HandleTableSize
= 20;
1029 PspBlock
->HandleTablePtr
= MAKELONG(0x18, PspSegment
);
1031 /* Set the DOS version */
1032 PspBlock
->DosVersion
= DOS_VERSION
;
1034 /* Set the far call opcodes */
1035 PspBlock
->FarCall
[0] = 0xCD; // int 0x21
1036 PspBlock
->FarCall
[1] = 0x21;
1037 PspBlock
->FarCall
[2] = 0xCB; // retf
1039 /* Set the command line */
1040 PspBlock
->CommandLineSize
= (BYTE
)min(strlen(CommandLine
), DOS_CMDLINE_LENGTH
- 1);
1041 RtlCopyMemory(PspBlock
->CommandLine
, CommandLine
, PspBlock
->CommandLineSize
);
1042 PspBlock
->CommandLine
[PspBlock
->CommandLineSize
] = '\r';
1045 BOOLEAN
DosCreateProcess(LPCSTR CommandLine
, WORD EnvBlock
)
1047 BOOLEAN Success
= FALSE
, AllocatedEnvBlock
= FALSE
;
1048 HANDLE FileHandle
= INVALID_HANDLE_VALUE
, FileMapping
= NULL
;
1049 LPBYTE Address
= NULL
;
1050 LPSTR ProgramFilePath
, Parameters
[256];
1051 CHAR CommandLineCopy
[DOS_CMDLINE_LENGTH
];
1052 CHAR ParamString
[DOS_CMDLINE_LENGTH
];
1053 DWORD ParamCount
= 0;
1056 DWORD i
, FileSize
, ExeSize
;
1057 PIMAGE_DOS_HEADER Header
;
1058 PDWORD RelocationTable
;
1061 DPRINT("DosCreateProcess: CommandLine \"%s\", EnvBlock 0x%04X\n",
1065 /* Save a copy of the command line */
1066 strcpy(CommandLineCopy
, CommandLine
);
1068 /* Get the file name of the executable */
1069 ProgramFilePath
= strtok(CommandLineCopy
, " \t");
1071 /* Load the parameters in the local array */
1072 while ((ParamCount
< sizeof(Parameters
)/sizeof(Parameters
[0]))
1073 && ((Parameters
[ParamCount
] = strtok(NULL
, " \t")) != NULL
))
1078 ZeroMemory(ParamString
, sizeof(ParamString
));
1080 /* Store the parameters in a string */
1081 for (i
= 0; i
< ParamCount
; i
++)
1083 strncat(ParamString
, Parameters
[i
], DOS_CMDLINE_LENGTH
- strlen(ParamString
) - 1);
1084 strncat(ParamString
, " ", DOS_CMDLINE_LENGTH
- strlen(ParamString
) - 1);
1087 /* Open a handle to the executable */
1088 FileHandle
= CreateFileA(ProgramFilePath
,
1093 FILE_ATTRIBUTE_NORMAL
,
1095 if (FileHandle
== INVALID_HANDLE_VALUE
) goto Cleanup
;
1097 /* Get the file size */
1098 FileSize
= GetFileSize(FileHandle
, NULL
);
1100 /* Create a mapping object for the file */
1101 FileMapping
= CreateFileMapping(FileHandle
,
1107 if (FileMapping
== NULL
) goto Cleanup
;
1109 /* Map the file into memory */
1110 Address
= (LPBYTE
)MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 0);
1111 if (Address
== NULL
) goto Cleanup
;
1113 /* Did we get an environment segment? */
1116 /* Set a flag to know if the environment block was allocated here */
1117 AllocatedEnvBlock
= TRUE
;
1119 /* No, copy the one from the parent */
1120 EnvBlock
= DosCopyEnvironmentBlock((CurrentPsp
!= SYSTEM_PSP
)
1121 ? SEGMENT_TO_PSP(CurrentPsp
)->EnvBlock
1126 /* Check if this is an EXE file or a COM file */
1127 if (Address
[0] == 'M' && Address
[1] == 'Z')
1131 /* Get the MZ header */
1132 Header
= (PIMAGE_DOS_HEADER
)Address
;
1134 /* Get the base size of the file, in paragraphs (rounded up) */
1135 ExeSize
= (((Header
->e_cp
- 1) * 512) + Header
->e_cblp
+ 0x0F) >> 4;
1137 /* Add the PSP size, in paragraphs */
1138 ExeSize
+= sizeof(DOS_PSP
) >> 4;
1140 /* Add the maximum size that should be allocated */
1141 ExeSize
+= Header
->e_maxalloc
;
1143 /* Make sure it does not pass 0xFFFF */
1144 if (ExeSize
> 0xFFFF) ExeSize
= 0xFFFF;
1146 /* Reduce the size one by one until the allocation is successful */
1147 for (i
= Header
->e_maxalloc
; i
>= Header
->e_minalloc
; i
--, ExeSize
--)
1149 /* Try to allocate that much memory */
1150 Segment
= DosAllocateMemory((WORD
)ExeSize
, NULL
);
1151 if (Segment
!= 0) break;
1154 /* Check if at least the lowest allocation was successful */
1155 if (Segment
== 0) goto Cleanup
;
1157 /* Initialize the PSP */
1158 DosInitializePsp(Segment
,
1163 /* The process owns its own memory */
1164 DosChangeMemoryOwner(Segment
, Segment
);
1165 DosChangeMemoryOwner(EnvBlock
, Segment
);
1167 /* Copy the program to Segment:0100 */
1168 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1169 Address
+ (Header
->e_cparhdr
<< 4),
1170 min(FileSize
- (Header
->e_cparhdr
<< 4),
1171 (ExeSize
<< 4) - sizeof(DOS_PSP
)));
1173 /* Get the relocation table */
1174 RelocationTable
= (PDWORD
)(Address
+ Header
->e_lfarlc
);
1176 /* Perform relocations */
1177 for (i
= 0; i
< Header
->e_crlc
; i
++)
1179 /* Get a pointer to the word that needs to be patched */
1180 RelocWord
= (PWORD
)SEG_OFF_TO_PTR(Segment
+ HIWORD(RelocationTable
[i
]),
1181 0x100 + LOWORD(RelocationTable
[i
]));
1183 /* Add the number of the EXE segment to it */
1184 *RelocWord
+= Segment
+ (sizeof(DOS_PSP
) >> 4);
1187 /* Set the initial segment registers */
1191 /* Set the stack to the location from the header */
1192 EmulatorSetStack(Segment
+ (sizeof(DOS_PSP
) >> 4) + Header
->e_ss
,
1196 CurrentPsp
= Segment
;
1197 DiskTransferArea
= MAKELONG(0x80, Segment
);
1198 EmulatorExecute(Segment
+ Header
->e_cs
+ (sizeof(DOS_PSP
) >> 4),
1207 /* Find the maximum amount of memory that can be allocated */
1208 DosAllocateMemory(0xFFFF, &MaxAllocSize
);
1210 /* Make sure it's enough for the whole program and the PSP */
1211 if (((DWORD
)MaxAllocSize
<< 4) < (FileSize
+ sizeof(DOS_PSP
))) goto Cleanup
;
1213 /* Allocate all of it */
1214 Segment
= DosAllocateMemory(MaxAllocSize
, NULL
);
1215 if (Segment
== 0) goto Cleanup
;
1217 /* The process owns its own memory */
1218 DosChangeMemoryOwner(Segment
, Segment
);
1219 DosChangeMemoryOwner(EnvBlock
, Segment
);
1221 /* Copy the program to Segment:0100 */
1222 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1226 /* Initialize the PSP */
1227 DosInitializePsp(Segment
,
1232 /* Set the initial segment registers */
1236 /* Set the stack to the last word of the segment */
1237 EmulatorSetStack(Segment
, 0xFFFE);
1240 * Set the value on the stack to 0, so that a near return
1241 * jumps to PSP:0000 which has the exit code.
1243 *((LPWORD
)SEG_OFF_TO_PTR(Segment
, 0xFFFE)) = 0;
1246 CurrentPsp
= Segment
;
1247 DiskTransferArea
= MAKELONG(0x80, Segment
);
1248 EmulatorExecute(Segment
, 0x100);
1256 /* It was not successful, cleanup the DOS memory */
1257 if (AllocatedEnvBlock
) DosFreeMemory(EnvBlock
);
1258 if (Segment
) DosFreeMemory(Segment
);
1262 if (Address
!= NULL
) UnmapViewOfFile(Address
);
1264 /* Close the file mapping object */
1265 if (FileMapping
!= NULL
) CloseHandle(FileMapping
);
1267 /* Close the file handle */
1268 if (FileHandle
!= INVALID_HANDLE_VALUE
) CloseHandle(FileHandle
);
1273 VOID
DosTerminateProcess(WORD Psp
, BYTE ReturnCode
)
1276 WORD McbSegment
= FIRST_MCB_SEGMENT
;
1277 PDOS_MCB CurrentMcb
;
1278 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
1279 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(Psp
);
1281 DPRINT("DosTerminateProcess: Psp 0x%04X, ReturnCode 0x%02X\n",
1285 /* Check if this PSP is it's own parent */
1286 if (PspBlock
->ParentPsp
== Psp
) goto Done
;
1288 for (i
= 0; i
< PspBlock
->HandleTableSize
; i
++)
1290 /* Close the handle */
1294 /* Free the memory used by the process */
1297 /* Get a pointer to the MCB */
1298 CurrentMcb
= SEGMENT_TO_MCB(McbSegment
);
1300 /* Make sure the MCB is valid */
1301 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!='Z') break;
1303 /* If this block was allocated by the process, free it */
1304 if (CurrentMcb
->OwnerPsp
== Psp
) DosFreeMemory(McbSegment
+ 1);
1306 /* If this was the last block, quit */
1307 if (CurrentMcb
->BlockType
== 'Z') break;
1309 /* Update the segment and continue */
1310 McbSegment
+= CurrentMcb
->Size
+ 1;
1314 /* Restore the interrupt vectors */
1315 IntVecTable
[0x22] = PspBlock
->TerminateAddress
;
1316 IntVecTable
[0x23] = PspBlock
->BreakAddress
;
1317 IntVecTable
[0x24] = PspBlock
->CriticalAddress
;
1319 /* Update the current PSP */
1320 if (Psp
== CurrentPsp
)
1322 CurrentPsp
= PspBlock
->ParentPsp
;
1323 if (CurrentPsp
== SYSTEM_PSP
) VdmRunning
= FALSE
;
1326 /* Save the return code - Normal termination */
1327 DosErrorLevel
= MAKEWORD(ReturnCode
, 0x00);
1329 /* Return control to the parent process */
1330 EmulatorExecute(HIWORD(PspBlock
->TerminateAddress
),
1331 LOWORD(PspBlock
->TerminateAddress
));
1334 BOOLEAN
DosHandleIoctl(BYTE ControlCode
, WORD FileHandle
)
1336 HANDLE Handle
= DosGetRealHandle(FileHandle
);
1338 if (Handle
== INVALID_HANDLE_VALUE
)
1341 DosLastError
= ERROR_FILE_NOT_FOUND
;
1345 switch (ControlCode
)
1347 /* Get Device Information */
1353 * See Ralf Brown: http://www.ctyme.com/intr/rb-2820.htm
1354 * for a list of possible flags.
1357 if (Handle
== DosSystemFileTable
[0])
1362 else if (Handle
== DosSystemFileTable
[1])
1364 /* Console output */
1368 /* It is a device */
1371 /* Return the device information word */
1376 /* Unsupported control code */
1379 DPRINT1("Unsupported IOCTL: 0x%02X\n", ControlCode
);
1381 DosLastError
= ERROR_INVALID_PARAMETER
;
1387 VOID WINAPI
DosInt20h(LPWORD Stack
)
1389 /* This is the exit interrupt */
1390 DosTerminateProcess(Stack
[STACK_CS
], 0);
1393 VOID WINAPI
DosInt21h(LPWORD Stack
)
1396 SYSTEMTIME SystemTime
;
1398 PDOS_INPUT_BUFFER InputBuffer
;
1400 /* Check the value in the AH register */
1403 /* Terminate Program */
1406 DosTerminateProcess(Stack
[STACK_CS
], 0);
1410 /* Read Character from STDIN with Echo */
1413 Character
= DosReadCharacter();
1414 DosPrintCharacter(Character
);
1416 /* Let the BOP repeat if needed */
1423 /* Write Character to STDOUT */
1426 Character
= getDL();
1427 DosPrintCharacter(Character
);
1430 * We return the output character (DOS 2.1+).
1431 * Also, if we're going to output a TAB, then
1432 * don't return a TAB but a SPACE instead.
1433 * See Ralf Brown: http://www.ctyme.com/intr/rb-2554.htm
1434 * for more information.
1436 setAL(Character
== '\t' ? ' ' : Character
);
1440 /* Read Character from STDAUX */
1443 // FIXME: Really read it from STDAUX!
1444 DPRINT1("INT 16h, 03h: Read character from STDAUX is HALFPLEMENTED\n");
1445 setAL(DosReadCharacter());
1449 /* Write Character to STDAUX */
1452 // FIXME: Really write it to STDAUX!
1453 DPRINT1("INT 16h, 04h: Write character to STDAUX is HALFPLEMENTED\n");
1454 DosPrintCharacter(getDL());
1458 /* Write Character to Printer */
1461 // FIXME: Really write it to printer!
1462 DPRINT1("INT 16h, 05h: Write character to printer is HALFPLEMENTED -\n\n");
1463 DPRINT1("0x%p\n", getDL());
1464 DPRINT1("\n\n-----------\n\n");
1468 /* Direct Console I/O */
1471 Character
= getDL();
1473 if (Character
!= 0xFF)
1476 DosPrintCharacter(Character
);
1479 * We return the output character (DOS 2.1+).
1480 * See Ralf Brown: http://www.ctyme.com/intr/rb-2558.htm
1481 * for more information.
1488 if (DosCheckInput())
1490 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_ZF
;
1491 setAL(DosReadCharacter());
1495 /* No character available */
1496 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_ZF
;
1504 /* Character Input without Echo */
1508 Character
= DosReadCharacter();
1510 /* Let the BOP repeat if needed */
1517 /* Write string to STDOUT */
1520 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1522 while (*String
!= '$')
1524 DosPrintCharacter(*String
);
1529 * We return the terminating character (DOS 2.1+).
1530 * See Ralf Brown: http://www.ctyme.com/intr/rb-2562.htm
1531 * for more information.
1537 /* Read Buffered Input */
1540 InputBuffer
= (PDOS_INPUT_BUFFER
)SEG_OFF_TO_PTR(getDS(), getDX());
1542 while (Stack
[STACK_COUNTER
] < InputBuffer
->MaxLength
)
1544 /* Try to read a character */
1545 Character
= DosReadCharacter();
1547 /* If it's not ready yet, let the BOP repeat */
1550 /* Echo the character and append it to the buffer */
1551 DosPrintCharacter(Character
);
1552 InputBuffer
->Buffer
[Stack
[STACK_COUNTER
]] = Character
;
1554 if (Character
== '\r') break;
1555 Stack
[STACK_COUNTER
]++;
1558 /* Update the length */
1559 InputBuffer
->Length
= Stack
[STACK_COUNTER
];
1563 /* Get STDIN Status */
1566 setAL(DosCheckInput() ? 0xFF : 0x00);
1570 /* Flush Buffer and Read STDIN */
1573 BYTE InputFunction
= getAL();
1575 /* Flush STDIN buffer */
1576 DosFlushFileBuffers(DOS_INPUT_HANDLE
); // Maybe just create a DosFlushInputBuffer...
1579 * If the input function number contained in AL is valid, i.e.
1580 * AL == 0x01 or 0x06 or 0x07 or 0x08 or 0x0A, call ourselves
1581 * recursively with AL == AH.
1583 if (InputFunction
== 0x01 || InputFunction
== 0x06 ||
1584 InputFunction
== 0x07 || InputFunction
== 0x08 ||
1585 InputFunction
== 0x0A)
1587 setAH(InputFunction
);
1589 * Instead of calling ourselves really recursively as in:
1591 * prefer resetting the CF flag to let the BOP repeat.
1601 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1603 // TODO: Flush what's needed.
1604 DPRINT1("INT 21h, 0Dh is UNIMPLEMENTED\n");
1606 /* Clear CF in DOS 6 only */
1607 if (PspBlock
->DosVersion
== 0x0006)
1608 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1613 /* Set Default Drive */
1616 DosChangeDrive(getDL());
1617 setAL(LastDrive
- 'A' + 1);
1621 /* NULL Function for CP/M Compatibility */
1625 * This function corresponds to the CP/M BDOS function
1626 * "get bit map of logged drives", which is meaningless
1629 * For: PTS-DOS 6.51 & S/DOS 1.0 - EXTENDED RENAME FILE USING FCB
1630 * See Ralf Brown: http://www.ctyme.com/intr/rb-2584.htm
1631 * for more information.
1637 /* Get Default Drive */
1640 setAL(CurrentDrive
);
1644 /* Set Disk Transfer Area */
1647 DiskTransferArea
= MAKELONG(getDX(), getDS());
1651 /* NULL Function for CP/M Compatibility */
1656 * Function 0x1D corresponds to the CP/M BDOS function
1657 * "get bit map of read-only drives", which is meaningless
1659 * See Ralf Brown: http://www.ctyme.com/intr/rb-2592.htm
1660 * for more information.
1662 * Function 0x1E corresponds to the CP/M BDOS function
1663 * "set file attributes", which was meaningless under MS-DOS 1.x.
1664 * See Ralf Brown: http://www.ctyme.com/intr/rb-2593.htm
1665 * for more information.
1671 /* NULL Function for CP/M Compatibility */
1675 * This function corresponds to the CP/M BDOS function
1676 * "get/set default user (sublibrary) number", which is meaningless
1679 * For: S/DOS 1.0+ & PTS-DOS 6.51+ - GET OEM REVISION
1680 * See Ralf Brown: http://www.ctyme.com/intr/rb-2596.htm
1681 * for more information.
1687 /* Set Interrupt Vector */
1690 ULONG FarPointer
= MAKELONG(getDX(), getDS());
1691 DPRINT1("Setting interrupt 0x%x ...\n", getAL());
1693 /* Write the new far pointer to the IDT */
1694 ((PULONG
)BaseAddress
)[getAL()] = FarPointer
;
1698 /* Create New PSP */
1701 DPRINT1("INT 21h, 26h - Create New PSP is UNIMPLEMENTED\n");
1705 /* Get System Date */
1708 GetLocalTime(&SystemTime
);
1709 setCX(SystemTime
.wYear
);
1710 setDX(MAKEWORD(SystemTime
.wDay
, SystemTime
.wMonth
));
1711 setAL(SystemTime
.wDayOfWeek
);
1715 /* Set System Date */
1718 GetLocalTime(&SystemTime
);
1719 SystemTime
.wYear
= getCX();
1720 SystemTime
.wMonth
= getDH();
1721 SystemTime
.wDay
= getDL();
1723 /* Return success or failure */
1724 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1728 /* Get System Time */
1731 GetLocalTime(&SystemTime
);
1732 setCX(MAKEWORD(SystemTime
.wMinute
, SystemTime
.wHour
));
1733 setDX(MAKEWORD(SystemTime
.wMilliseconds
/ 10, SystemTime
.wSecond
));
1737 /* Set System Time */
1740 GetLocalTime(&SystemTime
);
1741 SystemTime
.wHour
= getCH();
1742 SystemTime
.wMinute
= getCL();
1743 SystemTime
.wSecond
= getDH();
1744 SystemTime
.wMilliseconds
= getDL() * 10; // In hundredths of seconds
1746 /* Return success or failure */
1747 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1751 /* Get Disk Transfer Area */
1754 setES(HIWORD(DiskTransferArea
));
1755 setBX(LOWORD(DiskTransferArea
));
1759 /* Get DOS Version */
1762 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1765 * DOS 2+ - GET DOS VERSION
1766 * See Ralf Brown: http://www.ctyme.com/intr/rb-2711.htm
1767 * for more information.
1770 if (LOBYTE(PspBlock
->DosVersion
) < 5 || getAL() == 0x00)
1773 * Return DOS OEM number:
1774 * 0x00 for IBM PC-DOS
1775 * 0x02 for packaged MS-DOS
1780 if (LOBYTE(PspBlock
->DosVersion
) >= 5 && getAL() == 0x01)
1783 * Return version flag:
1784 * 1 << 3 if DOS is in ROM,
1785 * 0 (reserved) if not.
1790 /* Return DOS 24-bit user serial number in BL:CX */
1795 * Return DOS version: Minor:Major in AH:AL
1796 * The Windows NT DOS box returns version 5.00, subject to SETVER.
1798 setAX(PspBlock
->DosVersion
);
1803 /* Extended functionalities */
1806 if (getAL() == 0x06)
1809 * DOS 5+ - GET TRUE VERSION NUMBER
1810 * This function always returns the true version number, unlike
1811 * AH=30h, whose return value may be changed with SETVER.
1812 * See Ralf Brown: http://www.ctyme.com/intr/rb-2730.htm
1813 * for more information.
1817 * Return the true DOS version: Minor:Major in BH:BL
1818 * The Windows NT DOS box returns BX=3205h (version 5.50).
1820 setBX(NTDOS_VERSION
);
1822 /* DOS revision 0 */
1830 // /* Invalid subfunction */
1837 /* Get Interrupt Vector */
1840 DWORD FarPointer
= ((PDWORD
)BaseAddress
)[getAL()];
1842 /* Read the address from the IDT into ES:BX */
1843 setES(HIWORD(FarPointer
));
1844 setBX(LOWORD(FarPointer
));
1848 /* SWITCH character - AVAILDEV */
1851 if (getAL() == 0x00)
1854 * DOS 2+ - "SWITCHAR" - GET SWITCH CHARACTER
1855 * This setting is ignored by MS-DOS 4.0+.
1856 * MS-DOS 5+ always return AL=00h/DL=2Fh.
1857 * See Ralf Brown: http://www.ctyme.com/intr/rb-2752.htm
1858 * for more information.
1863 else if (getAL() == 0x01)
1866 * DOS 2+ - "SWITCHAR" - SET SWITCH CHARACTER
1867 * This setting is ignored by MS-DOS 5+.
1868 * See Ralf Brown: http://www.ctyme.com/intr/rb-2753.htm
1869 * for more information.
1874 else if (getAL() == 0x02)
1877 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1878 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1879 * for more information.
1884 else if (getAL() == 0x03)
1887 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1888 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1889 * for more information.
1896 /* Invalid subfunction */
1903 /* Create Directory */
1906 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1908 if (CreateDirectoryA(String
, NULL
))
1910 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1914 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1915 setAX(LOWORD(GetLastError()));
1921 /* Remove Directory */
1924 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1926 if (RemoveDirectoryA(String
))
1928 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1932 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1933 setAX(LOWORD(GetLastError()));
1939 /* Set Current Directory */
1942 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1944 if (DosChangeDirectory(String
))
1946 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1950 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1951 setAX(DosLastError
);
1961 WORD ErrorCode
= DosCreateFile(&FileHandle
,
1962 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
1967 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1972 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1983 WORD ErrorCode
= DosOpenFile(&FileHandle
,
1984 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
1989 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1994 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2004 if (DosCloseHandle(getBX()))
2006 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2010 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2011 setAX(ERROR_INVALID_HANDLE
);
2017 /* Read from File or Device */
2020 WORD Handle
= getBX();
2021 LPBYTE Buffer
= (LPBYTE
)SEG_OFF_TO_PTR(getDS(), getDX());
2022 WORD Count
= getCX();
2024 WORD ErrorCode
= ERROR_SUCCESS
;
2027 if (IsConsoleHandle(DosGetRealHandle(Handle
)))
2029 while (Stack
[STACK_COUNTER
] < Count
)
2031 /* Read a character from the BIOS */
2032 Character
= LOBYTE(BiosGetCharacter());
2034 /* Stop if the BOP needs to be repeated */
2037 // FIXME: Security checks!
2038 DosPrintCharacter(Character
);
2039 Buffer
[Stack
[STACK_COUNTER
]++] = Character
;
2041 if (Character
== '\r')
2043 /* Stop on first carriage return */
2044 DosPrintCharacter('\n');
2049 if (Character
!= '\r')
2051 if (Stack
[STACK_COUNTER
] < Count
) ErrorCode
= ERROR_NOT_READY
;
2052 else BytesRead
= Count
;
2054 else BytesRead
= Stack
[STACK_COUNTER
];
2058 /* Use the file reading function */
2059 ErrorCode
= DosReadFile(Handle
, Buffer
, Count
, &BytesRead
);
2062 if (ErrorCode
== ERROR_SUCCESS
)
2064 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2067 else if (ErrorCode
!= ERROR_NOT_READY
)
2069 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2075 /* Write to File or Device */
2078 WORD BytesWritten
= 0;
2079 WORD ErrorCode
= DosWriteFile(getBX(),
2080 SEG_OFF_TO_PTR(getDS(), getDX()),
2084 if (ErrorCode
== ERROR_SUCCESS
)
2086 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2087 setAX(BytesWritten
);
2091 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2101 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2103 if (demFileDelete(FileName
) == ERROR_SUCCESS
)
2105 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2107 * See Ralf Brown: http://www.ctyme.com/intr/rb-2797.htm
2108 * "AX destroyed (DOS 3.3) AL seems to be drive of deleted file."
2110 setAL(FileName
[0] - 'A');
2114 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2115 setAX(GetLastError());
2125 WORD ErrorCode
= DosSeekFile(getBX(),
2126 MAKELONG(getDX(), getCX()),
2130 if (ErrorCode
== ERROR_SUCCESS
)
2132 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2134 /* Return the new offset in DX:AX */
2135 setDX(HIWORD(NewLocation
));
2136 setAX(LOWORD(NewLocation
));
2140 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2147 /* Get/Set File Attributes */
2151 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2153 if (getAL() == 0x00)
2155 /* Get the attributes */
2156 Attributes
= GetFileAttributesA(FileName
);
2158 /* Check if it failed */
2159 if (Attributes
== INVALID_FILE_ATTRIBUTES
)
2161 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2162 setAX(GetLastError());
2166 /* Return the attributes that DOS can understand */
2167 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2168 setCX(Attributes
& 0x00FF);
2171 else if (getAL() == 0x01)
2173 /* Try to set the attributes */
2174 if (SetFileAttributesA(FileName
, getCL()))
2176 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2180 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2181 setAX(GetLastError());
2186 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2187 setAX(ERROR_INVALID_FUNCTION
);
2196 if (DosHandleIoctl(getAL(), getBX()))
2198 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2202 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2203 setAX(DosLastError
);
2209 /* Duplicate Handle */
2213 HANDLE Handle
= DosGetRealHandle(getBX());
2215 if (Handle
!= INVALID_HANDLE_VALUE
)
2217 /* The handle is invalid */
2218 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2219 setAX(ERROR_INVALID_HANDLE
);
2223 /* Open a new handle to the same entry */
2224 NewHandle
= DosOpenHandle(Handle
);
2226 if (NewHandle
== INVALID_DOS_HANDLE
)
2228 /* Too many files open */
2229 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2230 setAX(ERROR_TOO_MANY_OPEN_FILES
);
2234 /* Return the result */
2235 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2240 /* Force Duplicate Handle */
2243 if (DosDuplicateHandle(getBX(), getCX()))
2245 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2249 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2250 setAX(ERROR_INVALID_HANDLE
);
2256 /* Get Current Directory */
2259 BYTE DriveNumber
= getDL();
2260 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getSI());
2262 /* Get the real drive number */
2263 if (DriveNumber
== 0)
2265 DriveNumber
= CurrentDrive
;
2269 /* Decrement DriveNumber since it was 1-based */
2273 if (DriveNumber
<= LastDrive
- 'A')
2276 * Copy the current directory into the target buffer.
2277 * It doesn't contain the drive letter and the backslash.
2279 strncpy(String
, CurrentDirectories
[DriveNumber
], DOS_DIR_LENGTH
);
2280 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2281 setAX(0x0100); // Undocumented, see Ralf Brown: http://www.ctyme.com/intr/rb-2933.htm
2285 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2286 setAX(ERROR_INVALID_DRIVE
);
2292 /* Allocate Memory */
2295 WORD MaxAvailable
= 0;
2296 WORD Segment
= DosAllocateMemory(getBX(), &MaxAvailable
);
2300 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2305 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2306 setAX(DosLastError
);
2307 setBX(MaxAvailable
);
2316 if (DosFreeMemory(getES()))
2318 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2322 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2323 setAX(ERROR_ARENA_TRASHED
);
2329 /* Resize Memory Block */
2334 if (DosResizeMemory(getES(), getBX(), &Size
))
2336 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2340 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2341 setAX(DosLastError
);
2348 /* Terminate With Return Code */
2351 DosTerminateProcess(CurrentPsp
, getAL());
2355 /* Get Return Code (ERRORLEVEL) */
2359 * According to Ralf Brown: http://www.ctyme.com/intr/rb-2976.htm
2360 * DosErrorLevel is cleared after being read by this function.
2362 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2363 setAX(DosErrorLevel
);
2364 DosErrorLevel
= 0x0000; // Clear it
2368 /* Find First File */
2371 WORD Result
= (WORD
)demFileFindFirst(FAR_POINTER(DiskTransferArea
),
2372 SEG_OFF_TO_PTR(getDS(), getDX()),
2376 if (Result
== ERROR_SUCCESS
) Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2377 else Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2382 /* Find Next File */
2385 WORD Result
= (WORD
)demFileFindNext(FAR_POINTER(DiskTransferArea
));
2388 if (Result
== ERROR_SUCCESS
) Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2389 else Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2394 /* Internal - Set Current Process ID (Set PSP Address) */
2397 // FIXME: Is it really what it's done ??
2398 CurrentPsp
= getBX();
2402 /* Internal - Get Current Process ID (Get PSP Address) */
2404 /* Get Current PSP Address */
2408 * Undocumented AH=51h is identical to the documented AH=62h.
2409 * See Ralf Brown: http://www.ctyme.com/intr/rb-2982.htm
2410 * and http://www.ctyme.com/intr/rb-3140.htm
2411 * for more information.
2417 /* Get/Set Memory Management Options */
2420 if (getAL() == 0x00)
2422 /* Get allocation strategy */
2423 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2424 setAX(DosAllocStrategy
);
2426 else if (getAL() == 0x01)
2428 /* Set allocation strategy */
2430 if ((getBL() & (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2431 == (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2433 /* Can't set both */
2434 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2435 setAX(ERROR_INVALID_PARAMETER
);
2439 if ((getBL() & 0x3F) > DOS_ALLOC_LAST_FIT
)
2441 /* Invalid allocation strategy */
2442 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2443 setAX(ERROR_INVALID_PARAMETER
);
2447 DosAllocStrategy
= getBL();
2448 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2450 else if (getAL() == 0x02)
2452 /* Get UMB link state */
2453 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2454 setAL(DosUmbLinked
? 0x01 : 0x00);
2456 else if (getAL() == 0x03)
2458 /* Set UMB link state */
2459 if (getBX()) DosLinkUmb();
2460 else DosUnlinkUmb();
2461 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2465 /* Invalid or unsupported function */
2466 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2467 setAX(ERROR_INVALID_FUNCTION
);
2476 DPRINT1("DOS Function INT 0x21, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2479 setAL(0); // Some functions expect AL to be 0 when it's not supported.
2480 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2485 VOID WINAPI
DosBreakInterrupt(LPWORD Stack
)
2487 UNREFERENCED_PARAMETER(Stack
);
2493 VOID WINAPI
DosFastConOut(LPWORD Stack
)
2496 * This is the DOS 2+ Fast Console Output Interrupt.
2497 * See Ralf Brown: http://www.ctyme.com/intr/rb-4124.htm
2498 * for more information.
2502 if (Stack
[STACK_COUNTER
] == 0)
2504 Stack
[STACK_COUNTER
]++;
2506 /* Save AX and BX */
2507 Stack
[STACK_VAR_A
] = getAX();
2508 Stack
[STACK_VAR_B
] = getBX();
2510 /* Rewind the BOP manually, we can't use CF because the interrupt could modify it */
2511 EmulatorExecute(getCS(), getIP() - 4);
2513 /* Call INT 0x10, AH = 0x0E */
2515 setBL(DOS_CHAR_ATTRIBUTE
);
2516 setBH(Bda
->VideoPage
);
2518 EmulatorInterrupt(0x10);
2522 /* Restore AX and BX */
2523 setAX(Stack
[STACK_VAR_A
]);
2524 setBX(Stack
[STACK_VAR_B
]);
2527 /* Save AX and BX */
2528 USHORT AX
= getAX();
2529 USHORT BX
= getBX();
2531 /* Set the parameters (AL = character, already set) */
2532 setBL(DOS_CHAR_ATTRIBUTE
);
2533 setBH(Bda
->VideoPage
);
2535 /* Call the BIOS INT 10h, AH=0Eh "Teletype Output" */
2537 Int32Call(&DosContext
, BIOS_VIDEO_INTERRUPT
);
2539 /* Restore AX and BX */
2545 VOID WINAPI
DosInt2Fh(LPWORD Stack
)
2547 DPRINT1("DOS System Function INT 0x2F, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2549 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2552 BOOLEAN
DosKRNLInitialize(VOID
)
2558 CHAR CurrentDirectory
[MAX_PATH
];
2559 CHAR DosDirectory
[DOS_DIR_LENGTH
];
2565 /* Clear the current directory buffer */
2566 ZeroMemory(CurrentDirectories
, sizeof(CurrentDirectories
));
2568 /* Get the current directory */
2569 if (!GetCurrentDirectoryA(MAX_PATH
, CurrentDirectory
))
2571 // TODO: Use some kind of default path?
2575 /* Convert that to a DOS path */
2576 if (!GetShortPathNameA(CurrentDirectory
, DosDirectory
, DOS_DIR_LENGTH
))
2578 // TODO: Use some kind of default path?
2583 CurrentDrive
= DosDirectory
[0] - 'A';
2585 /* Get the directory part of the path */
2586 Path
= strchr(DosDirectory
, '\\');
2589 /* Skip the backslash */
2593 /* Set the directory */
2596 strncpy(CurrentDirectories
[CurrentDrive
], Path
, DOS_DIR_LENGTH
);
2599 /* Read CONFIG.SYS */
2600 Stream
= _wfopen(DOS_CONFIG_PATH
, L
"r");
2603 while (fgetws(Buffer
, 256, Stream
))
2605 // TODO: Parse the line
2610 /* Initialize the SFT */
2611 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
2613 DosSystemFileTable
[i
] = INVALID_HANDLE_VALUE
;
2614 DosSftRefCount
[i
] = 0;
2617 /* Get handles to standard I/O devices */
2618 DosSystemFileTable
[0] = GetStdHandle(STD_INPUT_HANDLE
);
2619 DosSystemFileTable
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
2620 DosSystemFileTable
[2] = GetStdHandle(STD_ERROR_HANDLE
);
2624 /* Initialize the callback context */
2625 InitializeContext(&DosContext
, 0x0070, 0x0000);
2627 /* Register the DOS 32-bit Interrupts */
2628 RegisterDosInt32(0x20, DosInt20h
);
2629 RegisterDosInt32(0x21, DosInt21h
);
2630 // RegisterDosInt32(0x22, DosInt22h ); // Termination
2631 RegisterDosInt32(0x23, DosBreakInterrupt
); // Ctrl-C / Ctrl-Break
2632 // RegisterDosInt32(0x24, DosInt24h ); // Critical Error
2633 RegisterDosInt32(0x29, DosFastConOut
); // DOS 2+ Fast Console Output
2634 RegisterDosInt32(0x2F, DosInt2Fh
);