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 *******************************************************************/
18 #include "registers.h"
20 /* PRIVATE VARIABLES **********************************************************/
22 static WORD CurrentPsp
= SYSTEM_PSP
;
23 static WORD DosLastError
= 0;
24 static DWORD DiskTransferArea
;
25 static BYTE CurrentDrive
;
26 static CHAR LastDrive
= 'E';
27 static CHAR CurrentDirectories
[NUM_DRIVES
][DOS_DIR_LENGTH
];
28 static HANDLE DosSystemFileTable
[DOS_SFT_SIZE
];
29 static WORD DosSftRefCount
[DOS_SFT_SIZE
];
30 static BYTE DosAllocStrategy
= DOS_ALLOC_BEST_FIT
;
31 static BOOLEAN DosUmbLinked
= FALSE
;
32 static WORD DosErrorLevel
= 0x0000;
34 /* PRIVATE FUNCTIONS **********************************************************/
36 /* Taken from base/shell/cmd/console.c */
37 static BOOL
IsConsoleHandle(HANDLE hHandle
)
41 /* Check whether the handle may be that of a console... */
42 if ((GetFileType(hHandle
) & FILE_TYPE_CHAR
) == 0) return FALSE
;
45 * It may be. Perform another test... The idea comes from the
46 * MSDN description of the WriteConsole API:
48 * "WriteConsole fails if it is used with a standard handle
49 * that is redirected to a file. If an application processes
50 * multilingual output that can be redirected, determine whether
51 * the output handle is a console handle (one method is to call
52 * the GetConsoleMode function and check whether it succeeds).
53 * If the handle is a console handle, call WriteConsole. If the
54 * handle is not a console handle, the output is redirected and
55 * you should call WriteFile to perform the I/O."
57 return GetConsoleMode(hHandle
, &dwMode
);
60 static VOID
DosCombineFreeBlocks(WORD StartBlock
)
62 PDOS_MCB CurrentMcb
= SEGMENT_TO_MCB(StartBlock
), NextMcb
;
64 /* If this is the last block or it's not free, quit */
65 if (CurrentMcb
->BlockType
== 'Z' || CurrentMcb
->OwnerPsp
!= 0) return;
69 /* Get a pointer to the next MCB */
70 NextMcb
= SEGMENT_TO_MCB(StartBlock
+ CurrentMcb
->Size
+ 1);
72 /* Check if the next MCB is free */
73 if (NextMcb
->OwnerPsp
== 0)
76 CurrentMcb
->Size
+= NextMcb
->Size
+ 1;
77 CurrentMcb
->BlockType
= NextMcb
->BlockType
;
78 NextMcb
->BlockType
= 'I';
82 /* No more adjoining free blocks */
88 static WORD
DosCopyEnvironmentBlock(WORD SourceSegment
, LPCSTR ProgramName
)
90 PCHAR Ptr
, SourceBuffer
, DestBuffer
= NULL
;
94 Ptr
= SourceBuffer
= (PCHAR
)SEG_OFF_TO_PTR(SourceSegment
, 0);
96 /* Calculate the size of the environment block */
99 TotalSize
+= strlen(Ptr
) + 1;
100 Ptr
+= strlen(Ptr
) + 1;
104 /* Add the string buffer size */
105 TotalSize
+= strlen(ProgramName
) + 1;
107 /* Allocate the memory for the environment block */
108 DestSegment
= DosAllocateMemory((WORD
)((TotalSize
+ 0x0F) >> 4), NULL
);
109 if (!DestSegment
) return 0;
113 DestBuffer
= (PCHAR
)SEG_OFF_TO_PTR(DestSegment
, 0);
116 /* Copy the string */
117 strcpy(DestBuffer
, Ptr
);
119 /* Advance to the next string */
120 DestBuffer
+= strlen(Ptr
);
121 Ptr
+= strlen(Ptr
) + 1;
123 /* Put a zero after the string */
127 /* Set the final zero */
130 /* Copy the program name after the environment block */
131 strcpy(DestBuffer
, ProgramName
);
136 static VOID
DosChangeMemoryOwner(WORD Segment
, WORD NewOwner
)
138 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
- 1);
140 /* Just set the owner */
141 Mcb
->OwnerPsp
= NewOwner
;
144 static WORD
DosOpenHandle(HANDLE Handle
)
151 /* The system PSP has no handle table */
152 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_DOS_HANDLE
;
154 /* Get a pointer to the handle table */
155 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
156 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
158 /* Find a free entry in the JFT */
159 for (DosHandle
= 0; DosHandle
< PspBlock
->HandleTableSize
; DosHandle
++)
161 if (HandleTable
[DosHandle
] == 0xFF) break;
164 /* If there are no free entries, fail */
165 if (DosHandle
== PspBlock
->HandleTableSize
) return INVALID_DOS_HANDLE
;
167 /* Check if the handle is already in the SFT */
168 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
170 /* Check if this is the same handle */
171 if (DosSystemFileTable
[i
] != Handle
) continue;
173 /* Already in the table, reference it */
176 /* Set the JFT entry to that SFT index */
177 HandleTable
[DosHandle
] = i
;
179 /* Return the new handle */
183 /* Add the handle to the SFT */
184 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
186 /* Make sure this is an empty table entry */
187 if (DosSystemFileTable
[i
] != INVALID_HANDLE_VALUE
) continue;
189 /* Initialize the empty table entry */
190 DosSystemFileTable
[i
] = Handle
;
191 DosSftRefCount
[i
] = 1;
193 /* Set the JFT entry to that SFT index */
194 HandleTable
[DosHandle
] = i
;
196 /* Return the new handle */
200 /* The SFT is full */
201 return INVALID_DOS_HANDLE
;
204 static HANDLE
DosGetRealHandle(WORD DosHandle
)
209 /* The system PSP has no handle table */
210 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_HANDLE_VALUE
;
212 /* Get a pointer to the handle table */
213 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
214 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
216 /* Make sure the handle is open */
217 if (HandleTable
[DosHandle
] == 0xFF) return INVALID_HANDLE_VALUE
;
219 /* Return the Win32 handle */
220 return DosSystemFileTable
[HandleTable
[DosHandle
]];
223 static VOID
DosCopyHandleTable(LPBYTE DestinationTable
)
229 /* Clear the table first */
230 for (i
= 0; i
< 20; i
++) DestinationTable
[i
] = 0xFF;
232 /* Check if this is the initial process */
233 if (CurrentPsp
== SYSTEM_PSP
)
235 /* Set up the standard I/O devices */
236 for (i
= 0; i
<= 2; i
++)
238 /* Set the index in the SFT */
239 DestinationTable
[i
] = (BYTE
)i
;
241 /* Increase the reference count */
249 /* Get the parent PSP block and handle table */
250 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
251 SourceTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
253 /* Copy the first 20 handles into the new table */
254 for (i
= 0; i
< 20; i
++)
256 DestinationTable
[i
] = SourceTable
[i
];
258 /* Increase the reference count */
259 DosSftRefCount
[SourceTable
[i
]]++;
263 /* PUBLIC FUNCTIONS ***********************************************************/
265 WORD
DosAllocateMemory(WORD Size
, WORD
*MaxAvailable
)
267 WORD Result
= 0, Segment
= FIRST_MCB_SEGMENT
, MaxSize
= 0;
268 PDOS_MCB CurrentMcb
, NextMcb
;
269 BOOLEAN SearchUmb
= FALSE
;
271 DPRINT("DosAllocateMemory: Size 0x%04X\n", Size
);
273 if (DosUmbLinked
&& (DosAllocStrategy
& (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
)))
275 /* Search UMB first */
276 Segment
= UMB_START_SEGMENT
;
282 /* Get a pointer to the MCB */
283 CurrentMcb
= SEGMENT_TO_MCB(Segment
);
285 /* Make sure it's valid */
286 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!= 'Z')
288 DPRINT("The DOS memory arena is corrupted!\n");
289 DosLastError
= ERROR_ARENA_TRASHED
;
293 /* Only check free blocks */
294 if (CurrentMcb
->OwnerPsp
!= 0) goto Next
;
296 /* Combine this free block with adjoining free blocks */
297 DosCombineFreeBlocks(Segment
);
299 /* Update the maximum block size */
300 if (CurrentMcb
->Size
> MaxSize
) MaxSize
= CurrentMcb
->Size
;
302 /* Check if this block is big enough */
303 if (CurrentMcb
->Size
< Size
) goto Next
;
305 switch (DosAllocStrategy
& 0x3F)
307 case DOS_ALLOC_FIRST_FIT
:
309 /* For first fit, stop immediately */
314 case DOS_ALLOC_BEST_FIT
:
316 /* For best fit, update the smallest block found so far */
317 if ((Result
== 0) || (CurrentMcb
->Size
< SEGMENT_TO_MCB(Result
)->Size
))
325 case DOS_ALLOC_LAST_FIT
:
327 /* For last fit, make the current block the result, but keep searching */
334 /* If this was the last MCB in the chain, quit */
335 if (CurrentMcb
->BlockType
== 'Z')
337 /* Check if nothing was found while searching through UMBs */
338 if ((Result
== 0) && SearchUmb
&& (DosAllocStrategy
& DOS_ALLOC_HIGH_LOW
))
340 /* Search low memory */
341 Segment
= FIRST_MCB_SEGMENT
;
348 /* Otherwise, update the segment and continue */
349 Segment
+= CurrentMcb
->Size
+ 1;
354 /* If we didn't find a free block, return 0 */
357 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
358 if (MaxAvailable
) *MaxAvailable
= MaxSize
;
362 /* Get a pointer to the MCB */
363 CurrentMcb
= SEGMENT_TO_MCB(Result
);
365 /* Check if the block is larger than requested */
366 if (CurrentMcb
->Size
> Size
)
368 /* It is, split it into two blocks */
369 NextMcb
= SEGMENT_TO_MCB(Result
+ Size
+ 1);
371 /* Initialize the new MCB structure */
372 NextMcb
->BlockType
= CurrentMcb
->BlockType
;
373 NextMcb
->Size
= CurrentMcb
->Size
- Size
- 1;
374 NextMcb
->OwnerPsp
= 0;
376 /* Update the current block */
377 CurrentMcb
->BlockType
= 'M';
378 CurrentMcb
->Size
= Size
;
381 /* Take ownership of the block */
382 CurrentMcb
->OwnerPsp
= CurrentPsp
;
384 /* Return the segment of the data portion of the block */
388 BOOLEAN
DosResizeMemory(WORD BlockData
, WORD NewSize
, WORD
*MaxAvailable
)
390 BOOLEAN Success
= TRUE
;
391 WORD Segment
= BlockData
- 1, ReturnSize
= 0, NextSegment
;
392 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
), NextMcb
;
394 DPRINT("DosResizeMemory: BlockData 0x%04X, NewSize 0x%04X\n",
398 /* Make sure this is a valid, allocated block */
399 if ((Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z') || Mcb
->OwnerPsp
== 0)
402 DosLastError
= ERROR_INVALID_HANDLE
;
406 ReturnSize
= Mcb
->Size
;
408 /* Check if we need to expand or contract the block */
409 if (NewSize
> Mcb
->Size
)
411 /* We can't expand the last block */
412 if (Mcb
->BlockType
!= 'M')
418 /* Get the pointer and segment of the next MCB */
419 NextSegment
= Segment
+ Mcb
->Size
+ 1;
420 NextMcb
= SEGMENT_TO_MCB(NextSegment
);
422 /* Make sure the next segment is free */
423 if (NextMcb
->OwnerPsp
!= 0)
425 DPRINT("Cannot expand memory block: next segment is not free!\n");
426 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
431 /* Combine this free block with adjoining free blocks */
432 DosCombineFreeBlocks(NextSegment
);
434 /* Set the maximum possible size of the block */
435 ReturnSize
+= NextMcb
->Size
+ 1;
437 /* Maximize the current block */
438 Mcb
->Size
= ReturnSize
;
439 Mcb
->BlockType
= NextMcb
->BlockType
;
441 /* Invalidate the next block */
442 NextMcb
->BlockType
= 'I';
444 /* Check if the block is larger than requested */
445 if (Mcb
->Size
> NewSize
)
447 DPRINT("Block too large, reducing size from 0x%04X to 0x%04X\n",
451 /* It is, split it into two blocks */
452 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
454 /* Initialize the new MCB structure */
455 NextMcb
->BlockType
= Mcb
->BlockType
;
456 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
457 NextMcb
->OwnerPsp
= 0;
459 /* Update the current block */
460 Mcb
->BlockType
= 'M';
464 else if (NewSize
< Mcb
->Size
)
466 DPRINT("Shrinking block from 0x%04X to 0x%04X\n",
470 /* Just split the block */
471 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
472 NextMcb
->BlockType
= Mcb
->BlockType
;
473 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
474 NextMcb
->OwnerPsp
= 0;
477 Mcb
->BlockType
= 'M';
482 /* Check if the operation failed */
485 DPRINT("DosResizeMemory FAILED. Maximum available: 0x%04X\n",
488 /* Return the maximum possible size */
489 if (MaxAvailable
) *MaxAvailable
= ReturnSize
;
495 BOOLEAN
DosFreeMemory(WORD BlockData
)
497 PDOS_MCB Mcb
= SEGMENT_TO_MCB(BlockData
- 1);
499 DPRINT("DosFreeMemory: BlockData 0x%04X\n", BlockData
);
501 /* Make sure the MCB is valid */
502 if (Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z')
504 DPRINT("MCB block type '%c' not valid!\n", Mcb
->BlockType
);
508 /* Mark the block as free */
514 BOOLEAN
DosLinkUmb(VOID
)
516 DWORD Segment
= FIRST_MCB_SEGMENT
;
517 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
);
519 DPRINT("Linking UMB\n");
521 /* Check if UMBs are already linked */
522 if (DosUmbLinked
) return FALSE
;
524 /* Find the last block */
525 while ((Mcb
->BlockType
== 'M') && (Segment
<= 0xFFFF))
527 Segment
+= Mcb
->Size
+ 1;
528 Mcb
= SEGMENT_TO_MCB(Segment
);
531 /* Make sure it's valid */
532 if (Mcb
->BlockType
!= 'Z') return FALSE
;
534 /* Connect the MCB with the UMB chain */
535 Mcb
->BlockType
= 'M';
541 BOOLEAN
DosUnlinkUmb(VOID
)
543 DWORD Segment
= FIRST_MCB_SEGMENT
;
544 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
);
546 DPRINT("Unlinking UMB\n");
548 /* Check if UMBs are already unlinked */
549 if (!DosUmbLinked
) return FALSE
;
551 /* Find the block preceding the MCB that links it with the UMB chain */
552 while (Segment
<= 0xFFFF)
554 if ((Segment
+ Mcb
->Size
) == (FIRST_MCB_SEGMENT
+ USER_MEMORY_SIZE
))
556 /* This is the last non-UMB segment */
560 /* Advance to the next MCB */
561 Segment
+= Mcb
->Size
+ 1;
562 Mcb
= SEGMENT_TO_MCB(Segment
);
565 /* Mark the MCB as the last MCB */
566 Mcb
->BlockType
= 'Z';
568 DosUmbLinked
= FALSE
;
572 WORD
DosCreateFile(LPWORD Handle
, LPCSTR FilePath
, WORD Attributes
)
577 DPRINT("DosCreateFile: FilePath \"%s\", Attributes 0x%04X\n",
581 /* Create the file */
582 FileHandle
= CreateFileA(FilePath
,
583 GENERIC_READ
| GENERIC_WRITE
,
584 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
590 if (FileHandle
== INVALID_HANDLE_VALUE
)
592 /* Return the error code */
593 return (WORD
)GetLastError();
596 /* Open the DOS handle */
597 DosHandle
= DosOpenHandle(FileHandle
);
599 if (DosHandle
== INVALID_DOS_HANDLE
)
601 /* Close the handle */
602 CloseHandle(FileHandle
);
604 /* Return the error code */
605 return ERROR_TOO_MANY_OPEN_FILES
;
608 /* It was successful */
610 return ERROR_SUCCESS
;
613 WORD
DosOpenFile(LPWORD Handle
, LPCSTR FilePath
, BYTE AccessMode
)
616 ACCESS_MASK Access
= 0;
619 DPRINT("DosOpenFile: FilePath \"%s\", AccessMode 0x%04X\n",
623 /* Parse the access mode */
624 switch (AccessMode
& 3)
629 Access
= GENERIC_READ
;
636 Access
= GENERIC_WRITE
;
643 Access
= GENERIC_READ
| GENERIC_WRITE
;
650 return ERROR_INVALID_PARAMETER
;
655 FileHandle
= CreateFileA(FilePath
,
657 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
660 FILE_ATTRIBUTE_NORMAL
,
663 if (FileHandle
== INVALID_HANDLE_VALUE
)
665 /* Return the error code */
666 return (WORD
)GetLastError();
669 /* Open the DOS handle */
670 DosHandle
= DosOpenHandle(FileHandle
);
672 if (DosHandle
== INVALID_DOS_HANDLE
)
674 /* Close the handle */
675 CloseHandle(FileHandle
);
677 /* Return the error code */
678 return ERROR_TOO_MANY_OPEN_FILES
;
681 /* It was successful */
683 return ERROR_SUCCESS
;
686 WORD
DosReadFile(WORD FileHandle
, LPVOID Buffer
, WORD Count
, LPWORD BytesRead
)
688 WORD Result
= ERROR_SUCCESS
;
689 DWORD BytesRead32
= 0;
690 HANDLE Handle
= DosGetRealHandle(FileHandle
);
692 DPRINT("DosReadFile: FileHandle 0x%04X, Count 0x%04X\n", FileHandle
, Count
);
694 /* Make sure the handle is valid */
695 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
698 if (!ReadFile(Handle
, Buffer
, Count
, &BytesRead32
, NULL
))
700 /* Store the error code */
701 Result
= (WORD
)GetLastError();
704 /* The number of bytes read is always 16-bit */
705 *BytesRead
= LOWORD(BytesRead32
);
707 /* Return the error code */
711 WORD
DosWriteFile(WORD FileHandle
, LPVOID Buffer
, WORD Count
, LPWORD BytesWritten
)
713 WORD Result
= ERROR_SUCCESS
;
714 DWORD BytesWritten32
= 0;
715 HANDLE Handle
= DosGetRealHandle(FileHandle
);
718 DPRINT("DosWriteFile: FileHandle 0x%04X, Count 0x%04X\n",
722 /* Make sure the handle is valid */
723 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
725 if (IsConsoleHandle(Handle
))
727 for (i
= 0; i
< Count
; i
++)
729 /* Call the BIOS to print the character */
730 BiosPrintCharacter(((LPBYTE
)Buffer
)[i
], DOS_CHAR_ATTRIBUTE
, Bda
->VideoPage
);
737 if (!WriteFile(Handle
, Buffer
, Count
, &BytesWritten32
, NULL
))
739 /* Store the error code */
740 Result
= (WORD
)GetLastError();
744 /* The number of bytes written is always 16-bit */
745 *BytesWritten
= LOWORD(BytesWritten32
);
747 /* Return the error code */
751 WORD
DosSeekFile(WORD FileHandle
, LONG Offset
, BYTE Origin
, LPDWORD NewOffset
)
753 WORD Result
= ERROR_SUCCESS
;
755 HANDLE Handle
= DosGetRealHandle(FileHandle
);
757 DPRINT("DosSeekFile: FileHandle 0x%04X, Offset 0x%08X, Origin 0x%02X\n",
762 /* Make sure the handle is valid */
763 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
765 /* Check if the origin is valid */
766 if (Origin
!= FILE_BEGIN
&& Origin
!= FILE_CURRENT
&& Origin
!= FILE_END
)
768 return ERROR_INVALID_FUNCTION
;
771 /* Move the file pointer */
772 FilePointer
= SetFilePointer(Handle
, Offset
, NULL
, Origin
);
774 /* Check if there's a possibility the operation failed */
775 if (FilePointer
== INVALID_SET_FILE_POINTER
)
777 /* Get the real error code */
778 Result
= (WORD
)GetLastError();
781 if (Result
!= ERROR_SUCCESS
)
783 /* The operation did fail */
787 /* Return the file pointer, if requested */
788 if (NewOffset
) *NewOffset
= FilePointer
;
791 return ERROR_SUCCESS
;
794 BOOLEAN
DosFlushFileBuffers(WORD FileHandle
)
796 HANDLE Handle
= DosGetRealHandle(FileHandle
);
798 /* Make sure the handle is valid */
799 if (Handle
== INVALID_HANDLE_VALUE
) return FALSE
;
802 * No need to check whether the handle is a console handle since
803 * FlushFileBuffers() automatically does this check and calls
804 * FlushConsoleInputBuffer() for us.
806 // if (IsConsoleHandle(Handle))
807 // return (BOOLEAN)FlushConsoleInputBuffer(Handle);
809 return (BOOLEAN
)FlushFileBuffers(Handle
);
812 BOOLEAN
DosDuplicateHandle(WORD OldHandle
, WORD NewHandle
)
818 DPRINT("DosDuplicateHandle: OldHandle 0x%04X, NewHandle 0x%04X\n",
822 /* The system PSP has no handle table */
823 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
825 /* Get a pointer to the handle table */
826 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
827 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
829 /* Make sure the old handle is open */
830 if (HandleTable
[OldHandle
] == 0xFF) return FALSE
;
832 /* Check if the new handle is open */
833 if (HandleTable
[NewHandle
] != 0xFF)
836 DosCloseHandle(NewHandle
);
839 /* Increment the reference count of the SFT entry */
840 SftIndex
= HandleTable
[OldHandle
];
841 DosSftRefCount
[SftIndex
]++;
843 /* Make the new handle point to that SFT entry */
844 HandleTable
[NewHandle
] = SftIndex
;
850 BOOLEAN
DosCloseHandle(WORD DosHandle
)
856 DPRINT("DosCloseHandle: DosHandle 0x%04X\n", DosHandle
);
858 /* The system PSP has no handle table */
859 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
861 /* Get a pointer to the handle table */
862 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
863 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
865 /* Make sure the handle is open */
866 if (HandleTable
[DosHandle
] == 0xFF) return FALSE
;
868 /* Decrement the reference count of the SFT entry */
869 SftIndex
= HandleTable
[DosHandle
];
870 DosSftRefCount
[SftIndex
]--;
872 /* Check if the reference count fell to zero */
873 if (!DosSftRefCount
[SftIndex
])
875 /* Close the file, it's no longer needed */
876 CloseHandle(DosSystemFileTable
[SftIndex
]);
878 /* Clear the handle */
879 DosSystemFileTable
[SftIndex
] = INVALID_HANDLE_VALUE
;
882 /* Clear the entry in the JFT */
883 HandleTable
[DosHandle
] = 0xFF;
888 BOOLEAN
DosChangeDrive(BYTE Drive
)
890 WCHAR DirectoryPath
[DOS_CMDLINE_LENGTH
];
892 /* Make sure the drive exists */
893 if (Drive
> (LastDrive
- 'A')) return FALSE
;
895 /* Find the path to the new current directory */
896 swprintf(DirectoryPath
, L
"%c\\%S", Drive
+ 'A', CurrentDirectories
[Drive
]);
898 /* Change the current directory of the process */
899 if (!SetCurrentDirectory(DirectoryPath
)) return FALSE
;
901 /* Set the current drive */
902 CurrentDrive
= Drive
;
908 BOOLEAN
DosChangeDirectory(LPSTR Directory
)
914 /* Make sure the directory path is not too long */
915 if (strlen(Directory
) >= DOS_DIR_LENGTH
)
917 DosLastError
= ERROR_PATH_NOT_FOUND
;
921 /* Get the drive number */
922 DriveNumber
= Directory
[0] - 'A';
924 /* Make sure the drive exists */
925 if (DriveNumber
> (LastDrive
- 'A'))
927 DosLastError
= ERROR_PATH_NOT_FOUND
;
931 /* Get the file attributes */
932 Attributes
= GetFileAttributesA(Directory
);
934 /* Make sure the path exists and is a directory */
935 if ((Attributes
== INVALID_FILE_ATTRIBUTES
)
936 || !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
938 DosLastError
= ERROR_PATH_NOT_FOUND
;
942 /* Check if this is the current drive */
943 if (DriveNumber
== CurrentDrive
)
945 /* Change the directory */
946 if (!SetCurrentDirectoryA(Directory
))
948 DosLastError
= LOWORD(GetLastError());
953 /* Get the directory part of the path */
954 Path
= strchr(Directory
, '\\');
957 /* Skip the backslash */
961 /* Set the directory for the drive */
964 strncpy(CurrentDirectories
[DriveNumber
], Path
, DOS_DIR_LENGTH
);
968 CurrentDirectories
[DriveNumber
][0] = '\0';
975 VOID
DosInitializePsp(WORD PspSegment
, LPCSTR CommandLine
, WORD ProgramSize
, WORD Environment
)
977 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(PspSegment
);
978 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
980 ZeroMemory(PspBlock
, sizeof(DOS_PSP
));
982 /* Set the exit interrupt */
983 PspBlock
->Exit
[0] = 0xCD; // int 0x20
984 PspBlock
->Exit
[1] = 0x20;
986 /* Set the number of the last paragraph */
987 PspBlock
->LastParagraph
= PspSegment
+ ProgramSize
- 1;
989 /* Save the interrupt vectors */
990 PspBlock
->TerminateAddress
= IntVecTable
[0x22];
991 PspBlock
->BreakAddress
= IntVecTable
[0x23];
992 PspBlock
->CriticalAddress
= IntVecTable
[0x24];
994 /* Set the parent PSP */
995 PspBlock
->ParentPsp
= CurrentPsp
;
997 /* Copy the parent handle table */
998 DosCopyHandleTable(PspBlock
->HandleTable
);
1000 /* Set the environment block */
1001 PspBlock
->EnvBlock
= Environment
;
1003 /* Set the handle table pointers to the internal handle table */
1004 PspBlock
->HandleTableSize
= 20;
1005 PspBlock
->HandleTablePtr
= MAKELONG(0x18, PspSegment
);
1007 /* Set the DOS version */
1008 PspBlock
->DosVersion
= DOS_VERSION
;
1010 /* Set the far call opcodes */
1011 PspBlock
->FarCall
[0] = 0xCD; // int 0x21
1012 PspBlock
->FarCall
[1] = 0x21;
1013 PspBlock
->FarCall
[2] = 0xCB; // retf
1015 /* Set the command line */
1016 PspBlock
->CommandLineSize
= (BYTE
)min(strlen(CommandLine
), DOS_CMDLINE_LENGTH
- 1);
1017 RtlCopyMemory(PspBlock
->CommandLine
, CommandLine
, PspBlock
->CommandLineSize
);
1018 PspBlock
->CommandLine
[PspBlock
->CommandLineSize
] = '\r';
1021 BOOLEAN
DosCreateProcess(LPCSTR CommandLine
, WORD EnvBlock
)
1023 BOOLEAN Success
= FALSE
, AllocatedEnvBlock
= FALSE
;
1024 HANDLE FileHandle
= INVALID_HANDLE_VALUE
, FileMapping
= NULL
;
1025 LPBYTE Address
= NULL
;
1026 LPSTR ProgramFilePath
, Parameters
[256];
1027 CHAR CommandLineCopy
[DOS_CMDLINE_LENGTH
];
1031 DWORD i
, FileSize
, ExeSize
;
1032 PIMAGE_DOS_HEADER Header
;
1033 PDWORD RelocationTable
;
1036 DPRINT("DosCreateProcess: CommandLine \"%s\", EnvBlock 0x%04X\n",
1040 /* Save a copy of the command line */
1041 strcpy(CommandLineCopy
, CommandLine
);
1043 // FIXME: Improve parsing (especially: "some_path\with spaces\program.exe" options)
1045 /* Get the file name of the executable */
1046 ProgramFilePath
= strtok(CommandLineCopy
, " \t");
1048 /* Load the parameters in the local array */
1049 while ((ParamCount
< sizeof(Parameters
)/sizeof(Parameters
[0]))
1050 && ((Parameters
[ParamCount
] = strtok(NULL
, " \t")) != NULL
))
1055 /* Open a handle to the executable */
1056 FileHandle
= CreateFileA(ProgramFilePath
,
1061 FILE_ATTRIBUTE_NORMAL
,
1063 if (FileHandle
== INVALID_HANDLE_VALUE
) goto Cleanup
;
1065 /* Get the file size */
1066 FileSize
= GetFileSize(FileHandle
, NULL
);
1068 /* Create a mapping object for the file */
1069 FileMapping
= CreateFileMapping(FileHandle
,
1075 if (FileMapping
== NULL
) goto Cleanup
;
1077 /* Map the file into memory */
1078 Address
= (LPBYTE
)MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 0);
1079 if (Address
== NULL
) goto Cleanup
;
1081 /* Did we get an environment segment? */
1084 /* Set a flag to know if the environment block was allocated here */
1085 AllocatedEnvBlock
= TRUE
;
1087 /* No, copy the one from the parent */
1088 EnvBlock
= DosCopyEnvironmentBlock((CurrentPsp
!= SYSTEM_PSP
)
1089 ? SEGMENT_TO_PSP(CurrentPsp
)->EnvBlock
1094 /* Check if this is an EXE file or a COM file */
1095 if (Address
[0] == 'M' && Address
[1] == 'Z')
1099 /* Get the MZ header */
1100 Header
= (PIMAGE_DOS_HEADER
)Address
;
1102 /* Get the base size of the file, in paragraphs (rounded up) */
1103 ExeSize
= (((Header
->e_cp
- 1) * 512) + Header
->e_cblp
+ 0x0F) >> 4;
1105 /* Add the PSP size, in paragraphs */
1106 ExeSize
+= sizeof(DOS_PSP
) >> 4;
1108 /* Add the maximum size that should be allocated */
1109 ExeSize
+= Header
->e_maxalloc
;
1111 /* Make sure it does not pass 0xFFFF */
1112 if (ExeSize
> 0xFFFF) ExeSize
= 0xFFFF;
1114 /* Reduce the size one by one until the allocation is successful */
1115 for (i
= Header
->e_maxalloc
; i
>= Header
->e_minalloc
; i
--, ExeSize
--)
1117 /* Try to allocate that much memory */
1118 Segment
= DosAllocateMemory((WORD
)ExeSize
, NULL
);
1119 if (Segment
!= 0) break;
1122 /* Check if at least the lowest allocation was successful */
1123 if (Segment
== 0) goto Cleanup
;
1125 /* Initialize the PSP */
1126 DosInitializePsp(Segment
,
1131 /* The process owns its own memory */
1132 DosChangeMemoryOwner(Segment
, Segment
);
1133 DosChangeMemoryOwner(EnvBlock
, Segment
);
1135 /* Copy the program to Segment:0100 */
1136 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1137 Address
+ (Header
->e_cparhdr
<< 4),
1138 min(FileSize
- (Header
->e_cparhdr
<< 4),
1139 (ExeSize
<< 4) - sizeof(DOS_PSP
)));
1141 /* Get the relocation table */
1142 RelocationTable
= (PDWORD
)(Address
+ Header
->e_lfarlc
);
1144 /* Perform relocations */
1145 for (i
= 0; i
< Header
->e_crlc
; i
++)
1147 /* Get a pointer to the word that needs to be patched */
1148 RelocWord
= (PWORD
)SEG_OFF_TO_PTR(Segment
+ HIWORD(RelocationTable
[i
]),
1149 0x100 + LOWORD(RelocationTable
[i
]));
1151 /* Add the number of the EXE segment to it */
1152 *RelocWord
+= Segment
+ (sizeof(DOS_PSP
) >> 4);
1155 /* Set the initial segment registers */
1159 /* Set the stack to the location from the header */
1160 EmulatorSetStack(Segment
+ (sizeof(DOS_PSP
) >> 4) + Header
->e_ss
,
1164 CurrentPsp
= Segment
;
1165 DiskTransferArea
= MAKELONG(0x80, Segment
);
1166 EmulatorExecute(Segment
+ Header
->e_cs
+ (sizeof(DOS_PSP
) >> 4),
1175 /* Find the maximum amount of memory that can be allocated */
1176 DosAllocateMemory(0xFFFF, &MaxAllocSize
);
1178 /* Make sure it's enough for the whole program and the PSP */
1179 if (((DWORD
)MaxAllocSize
<< 4) < (FileSize
+ sizeof(DOS_PSP
))) goto Cleanup
;
1181 /* Allocate all of it */
1182 Segment
= DosAllocateMemory(MaxAllocSize
, NULL
);
1183 if (Segment
== 0) goto Cleanup
;
1185 /* The process owns its own memory */
1186 DosChangeMemoryOwner(Segment
, Segment
);
1187 DosChangeMemoryOwner(EnvBlock
, Segment
);
1189 /* Copy the program to Segment:0100 */
1190 RtlCopyMemory(SEG_OFF_TO_PTR(Segment
, 0x100),
1194 /* Initialize the PSP */
1195 DosInitializePsp(Segment
,
1197 (WORD
)((FileSize
+ sizeof(DOS_PSP
)) >> 4),
1200 /* Set the initial segment registers */
1204 /* Set the stack to the last word of the segment */
1205 EmulatorSetStack(Segment
, 0xFFFE);
1208 * Set the value on the stack to 0, so that a near return
1209 * jumps to PSP:0000 which has the exit code.
1211 *((LPWORD
)SEG_OFF_TO_PTR(Segment
, 0xFFFE)) = 0;
1214 CurrentPsp
= Segment
;
1215 DiskTransferArea
= MAKELONG(0x80, Segment
);
1216 EmulatorExecute(Segment
, 0x100);
1224 /* It was not successful, cleanup the DOS memory */
1225 if (AllocatedEnvBlock
) DosFreeMemory(EnvBlock
);
1226 if (Segment
) DosFreeMemory(Segment
);
1230 if (Address
!= NULL
) UnmapViewOfFile(Address
);
1232 /* Close the file mapping object */
1233 if (FileMapping
!= NULL
) CloseHandle(FileMapping
);
1235 /* Close the file handle */
1236 if (FileHandle
!= INVALID_HANDLE_VALUE
) CloseHandle(FileHandle
);
1241 VOID
DosTerminateProcess(WORD Psp
, BYTE ReturnCode
)
1244 WORD McbSegment
= FIRST_MCB_SEGMENT
;
1245 PDOS_MCB CurrentMcb
;
1246 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
1247 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(Psp
);
1249 DPRINT("DosTerminateProcess: Psp 0x%04X, ReturnCode 0x%02X\n",
1253 /* Check if this PSP is it's own parent */
1254 if (PspBlock
->ParentPsp
== Psp
) goto Done
;
1256 for (i
= 0; i
< PspBlock
->HandleTableSize
; i
++)
1258 /* Close the handle */
1262 /* Free the memory used by the process */
1265 /* Get a pointer to the MCB */
1266 CurrentMcb
= SEGMENT_TO_MCB(McbSegment
);
1268 /* Make sure the MCB is valid */
1269 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!='Z') break;
1271 /* If this block was allocated by the process, free it */
1272 if (CurrentMcb
->OwnerPsp
== Psp
) DosFreeMemory(McbSegment
+ 1);
1274 /* If this was the last block, quit */
1275 if (CurrentMcb
->BlockType
== 'Z') break;
1277 /* Update the segment and continue */
1278 McbSegment
+= CurrentMcb
->Size
+ 1;
1282 /* Restore the interrupt vectors */
1283 IntVecTable
[0x22] = PspBlock
->TerminateAddress
;
1284 IntVecTable
[0x23] = PspBlock
->BreakAddress
;
1285 IntVecTable
[0x24] = PspBlock
->CriticalAddress
;
1287 /* Update the current PSP */
1288 if (Psp
== CurrentPsp
)
1290 CurrentPsp
= PspBlock
->ParentPsp
;
1291 if (CurrentPsp
== SYSTEM_PSP
) VdmRunning
= FALSE
;
1294 /* Save the return code - Normal termination */
1295 DosErrorLevel
= MAKEWORD(ReturnCode
, 0x00);
1297 /* Return control to the parent process */
1298 EmulatorExecute(HIWORD(PspBlock
->TerminateAddress
),
1299 LOWORD(PspBlock
->TerminateAddress
));
1302 CHAR
DosReadCharacter(VOID
)
1304 CHAR Character
= '\0';
1307 if (IsConsoleHandle(DosGetRealHandle(DOS_INPUT_HANDLE
)))
1310 Character
= LOBYTE(BiosGetCharacter());
1314 /* Use the file reading function */
1315 DosReadFile(DOS_INPUT_HANDLE
, &Character
, sizeof(CHAR
), &BytesRead
);
1321 BOOLEAN
DosCheckInput(VOID
)
1323 HANDLE Handle
= DosGetRealHandle(DOS_INPUT_HANDLE
);
1325 if (IsConsoleHandle(Handle
))
1328 return (BiosPeekCharacter() != 0xFFFF);
1333 DWORD FileSize
= GetFileSize(Handle
, &FileSizeHigh
);
1334 LONG LocationHigh
= 0;
1335 DWORD Location
= SetFilePointer(Handle
, 0, &LocationHigh
, FILE_CURRENT
);
1337 return ((Location
!= FileSize
) || (LocationHigh
!= FileSizeHigh
));
1341 VOID
DosPrintCharacter(CHAR Character
)
1345 /* Use the file writing function */
1346 DosWriteFile(DOS_OUTPUT_HANDLE
, &Character
, sizeof(CHAR
), &BytesWritten
);
1349 BOOLEAN
DosHandleIoctl(BYTE ControlCode
, WORD FileHandle
)
1351 HANDLE Handle
= DosGetRealHandle(FileHandle
);
1353 if (Handle
== INVALID_HANDLE_VALUE
)
1356 DosLastError
= ERROR_FILE_NOT_FOUND
;
1360 switch (ControlCode
)
1362 /* Get Device Information */
1367 if (Handle
== DosSystemFileTable
[0])
1372 else if (Handle
== DosSystemFileTable
[1])
1374 /* Console output */
1378 /* It is a character device */
1381 /* Return the device information word */
1386 /* Unsupported control code */
1389 DPRINT1("Unsupported IOCTL: 0x%02X\n", ControlCode
);
1391 DosLastError
= ERROR_INVALID_PARAMETER
;
1397 VOID WINAPI
DosInt20h(LPWORD Stack
)
1399 /* This is the exit interrupt */
1400 DosTerminateProcess(Stack
[STACK_CS
], 0);
1403 VOID WINAPI
DosInt21h(LPWORD Stack
)
1406 SYSTEMTIME SystemTime
;
1408 PDOS_INPUT_BUFFER InputBuffer
;
1410 /* Check the value in the AH register */
1413 /* Terminate Program */
1416 DosTerminateProcess(Stack
[STACK_CS
], 0);
1420 /* Read Character from STDIN with Echo */
1423 Character
= DosReadCharacter();
1424 DosPrintCharacter(Character
);
1426 /* Let the BOP repeat if needed */
1433 /* Write Character to STDOUT */
1436 Character
= getDL();
1437 DosPrintCharacter(Character
);
1440 * We return the output character (DOS 2.1+).
1441 * Also, if we're going to output a TAB, then
1442 * don't return a TAB but a SPACE instead.
1443 * See Ralf Brown: http://www.ctyme.com/intr/rb-2554.htm
1444 * for more information.
1446 setAL(Character
== '\t' ? ' ' : Character
);
1450 /* Read Character from STDAUX */
1453 // FIXME: Really read it from STDAUX!
1454 DPRINT1("INT 16h, 03h: Read character from STDAUX is HALFPLEMENTED\n");
1455 setAL(DosReadCharacter());
1459 /* Write Character to STDAUX */
1462 // FIXME: Really write it to STDAUX!
1463 DPRINT1("INT 16h, 04h: Write character to STDAUX is HALFPLEMENTED\n");
1464 DosPrintCharacter(getDL());
1468 /* Write Character to Printer */
1471 // FIXME: Really write it to printer!
1472 DPRINT1("INT 16h, 05h: Write character to printer is HALFPLEMENTED -\n\n");
1473 DPRINT1("0x%p\n", getDL());
1474 DPRINT1("\n\n-----------\n\n");
1478 /* Direct Console I/O */
1481 Character
= getDL();
1483 if (Character
!= 0xFF)
1486 DosPrintCharacter(Character
);
1489 * We return the output character (DOS 2.1+).
1490 * See Ralf Brown: http://www.ctyme.com/intr/rb-2558.htm
1491 * for more information.
1498 if (DosCheckInput())
1500 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_ZF
;
1501 setAL(DosReadCharacter());
1505 /* No character available */
1506 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_ZF
;
1514 /* Character Input without Echo */
1518 Character
= DosReadCharacter();
1520 /* Let the BOP repeat if needed */
1527 /* Write string to STDOUT */
1530 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1532 while (*String
!= '$')
1534 DosPrintCharacter(*String
);
1539 * We return the terminating character (DOS 2.1+).
1540 * See Ralf Brown: http://www.ctyme.com/intr/rb-2562.htm
1541 * for more information.
1547 /* Read Buffered Input */
1550 InputBuffer
= (PDOS_INPUT_BUFFER
)SEG_OFF_TO_PTR(getDS(), getDX());
1552 while (Stack
[STACK_COUNTER
] < InputBuffer
->MaxLength
)
1554 /* Try to read a character */
1555 Character
= DosReadCharacter();
1557 /* If it's not ready yet, let the BOP repeat */
1560 /* Echo the character and append it to the buffer */
1561 DosPrintCharacter(Character
);
1562 InputBuffer
->Buffer
[Stack
[STACK_COUNTER
]] = Character
;
1564 if (Character
== '\r') break;
1565 Stack
[STACK_COUNTER
]++;
1568 /* Update the length */
1569 InputBuffer
->Length
= Stack
[STACK_COUNTER
];
1573 /* Get STDIN Status */
1576 setAL(DosCheckInput() ? 0xFF : 0x00);
1580 /* Flush Buffer and Read STDIN */
1583 BYTE InputFunction
= getAL();
1585 /* Flush STDIN buffer */
1586 DosFlushFileBuffers(DOS_INPUT_HANDLE
); // Maybe just create a DosFlushInputBuffer...
1589 * If the input function number contained in AL is valid, i.e.
1590 * AL == 0x01 or 0x06 or 0x07 or 0x08 or 0x0A, call ourselves
1591 * recursively with AL == AH.
1593 if (InputFunction
== 0x01 || InputFunction
== 0x06 ||
1594 InputFunction
== 0x07 || InputFunction
== 0x08 ||
1595 InputFunction
== 0x0A)
1597 setAH(InputFunction
);
1599 * Instead of calling ourselves really recursively as in:
1601 * prefer resetting the CF flag to let the BOP repeat.
1611 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1613 // TODO: Flush what's needed.
1614 DPRINT1("INT 21h, 0Dh is UNIMPLEMENTED\n");
1616 /* Clear CF in DOS 6 only */
1617 if (PspBlock
->DosVersion
== 0x0006)
1618 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1623 /* Set Default Drive */
1626 DosChangeDrive(getDL());
1627 setAL(LastDrive
- 'A' + 1);
1631 /* NULL Function for CP/M Compatibility */
1635 * This function corresponds to the CP/M BDOS function
1636 * "get bit map of logged drives", which is meaningless
1639 * For: PTS-DOS 6.51 & S/DOS 1.0 - EXTENDED RENAME FILE USING FCB
1640 * See Ralf Brown: http://www.ctyme.com/intr/rb-2584.htm
1641 * for more information.
1647 /* Get Default Drive */
1650 setAL(CurrentDrive
);
1654 /* Set Disk Transfer Area */
1657 DiskTransferArea
= MAKELONG(getDX(), getDS());
1661 /* NULL Function for CP/M Compatibility */
1666 * Function 0x1D corresponds to the CP/M BDOS function
1667 * "get bit map of read-only drives", which is meaningless
1669 * See Ralf Brown: http://www.ctyme.com/intr/rb-2592.htm
1670 * for more information.
1672 * Function 0x1E corresponds to the CP/M BDOS function
1673 * "set file attributes", which was meaningless under MS-DOS 1.x.
1674 * See Ralf Brown: http://www.ctyme.com/intr/rb-2593.htm
1675 * for more information.
1681 /* NULL Function for CP/M Compatibility */
1685 * This function corresponds to the CP/M BDOS function
1686 * "get/set default user (sublibrary) number", which is meaningless
1689 * For: S/DOS 1.0+ & PTS-DOS 6.51+ - GET OEM REVISION
1690 * See Ralf Brown: http://www.ctyme.com/intr/rb-2596.htm
1691 * for more information.
1697 /* Set Interrupt Vector */
1700 DWORD FarPointer
= MAKELONG(getDX(), getDS());
1701 DPRINT1("Setting interrupt 0x%x ...\n", getAL());
1703 /* Write the new far pointer to the IDT */
1704 ((PDWORD
)BaseAddress
)[getAL()] = FarPointer
;
1708 /* Create New PSP */
1711 DPRINT1("INT 21h, 26h - Create New PSP is UNIMPLEMENTED\n");
1715 /* Get System Date */
1718 GetLocalTime(&SystemTime
);
1719 setCX(SystemTime
.wYear
);
1720 setDX(MAKEWORD(SystemTime
.wDay
, SystemTime
.wMonth
));
1721 setAL(SystemTime
.wDayOfWeek
);
1725 /* Set System Date */
1728 GetLocalTime(&SystemTime
);
1729 SystemTime
.wYear
= getCX();
1730 SystemTime
.wMonth
= getDH();
1731 SystemTime
.wDay
= getDL();
1733 /* Return success or failure */
1734 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1738 /* Get System Time */
1741 GetLocalTime(&SystemTime
);
1742 setCX(MAKEWORD(SystemTime
.wMinute
, SystemTime
.wHour
));
1743 setDX(MAKEWORD(SystemTime
.wMilliseconds
/ 10, SystemTime
.wSecond
));
1747 /* Set System Time */
1750 GetLocalTime(&SystemTime
);
1751 SystemTime
.wHour
= getCH();
1752 SystemTime
.wMinute
= getCL();
1753 SystemTime
.wSecond
= getDH();
1754 SystemTime
.wMilliseconds
= getDL() * 10; // In hundredths of seconds
1756 /* Return success or failure */
1757 setAL(SetLocalTime(&SystemTime
) ? 0x00 : 0xFF);
1761 /* Get Disk Transfer Area */
1764 setES(HIWORD(DiskTransferArea
));
1765 setBX(LOWORD(DiskTransferArea
));
1769 /* Get DOS Version */
1772 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1775 * See Ralf Brown: http://www.ctyme.com/intr/rb-2711.htm
1776 * for more information.
1779 if (LOBYTE(PspBlock
->DosVersion
) < 5 || getAL() == 0x00)
1782 * Return DOS OEM number:
1783 * 0x00 for IBM PC-DOS
1784 * 0x02 for packaged MS-DOS
1789 if (LOBYTE(PspBlock
->DosVersion
) >= 5 && getAL() == 0x01)
1792 * Return version flag:
1793 * 1 << 3 if DOS is in ROM,
1794 * 0 (reserved) if not.
1799 /* Return DOS 24-bit user serial number in BL:CX */
1803 /* Return DOS version: Minor:Major in AH:AL */
1804 setAX(PspBlock
->DosVersion
);
1809 /* Get Interrupt Vector */
1812 DWORD FarPointer
= ((PDWORD
)BaseAddress
)[getAL()];
1814 /* Read the address from the IDT into ES:BX */
1815 setES(HIWORD(FarPointer
));
1816 setBX(LOWORD(FarPointer
));
1820 /* SWITCH character - AVAILDEV */
1823 if (getAL() == 0x00)
1826 * DOS 2+ - "SWITCHAR" - GET SWITCH CHARACTER
1827 * This setting is ignored by MS-DOS 4.0+.
1828 * MS-DOS 5+ always return AL=00h/DL=2Fh.
1829 * See Ralf Brown: http://www.ctyme.com/intr/rb-2752.htm
1830 * for more information.
1835 else if (getAL() == 0x01)
1838 * DOS 2+ - "SWITCHAR" - SET SWITCH CHARACTER
1839 * This setting is ignored by MS-DOS 5+.
1840 * See Ralf Brown: http://www.ctyme.com/intr/rb-2753.htm
1841 * for more information.
1846 else if (getAL() == 0x02)
1849 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1850 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1851 * for more information.
1856 else if (getAL() == 0x03)
1859 * DOS 2.x and 3.3+ only - "AVAILDEV" - SPECIFY \DEV\ PREFIX USE
1860 * See Ralf Brown: http://www.ctyme.com/intr/rb-2754.htm
1861 * for more information.
1874 /* Create Directory */
1877 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1879 if (CreateDirectoryA(String
, NULL
))
1881 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1885 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1886 setAX(LOWORD(GetLastError()));
1892 /* Remove Directory */
1895 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1897 if (RemoveDirectoryA(String
))
1899 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1903 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1904 setAX(LOWORD(GetLastError()));
1910 /* Set Current Directory */
1913 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getDX());
1915 if (DosChangeDirectory(String
))
1917 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1921 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1922 setAX(DosLastError
);
1932 WORD ErrorCode
= DosCreateFile(&FileHandle
,
1933 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
1938 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1943 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1954 WORD ErrorCode
= DosOpenFile(&FileHandle
,
1955 (LPCSTR
)SEG_OFF_TO_PTR(getDS(), getDX()),
1960 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1965 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1975 if (DosCloseHandle(getBX()))
1977 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1981 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1982 setAX(ERROR_INVALID_HANDLE
);
1988 /* Read from File or Device */
1991 WORD Handle
= getBX();
1992 LPBYTE Buffer
= (LPBYTE
)SEG_OFF_TO_PTR(getDS(), getDX());
1993 WORD Count
= getCX();
1995 WORD ErrorCode
= ERROR_SUCCESS
;
1997 if (IsConsoleHandle(DosGetRealHandle(Handle
)))
1999 while (Stack
[STACK_COUNTER
] < Count
)
2001 /* Read a character from the BIOS */
2002 // FIXME: Security checks!
2003 Buffer
[Stack
[STACK_COUNTER
]] = LOBYTE(BiosGetCharacter());
2005 /* Stop if the BOP needs to be repeated */
2008 /* Increment the counter */
2009 Stack
[STACK_COUNTER
]++;
2012 if (Stack
[STACK_COUNTER
] < Count
)
2013 ErrorCode
= ERROR_NOT_READY
;
2019 /* Use the file reading function */
2020 ErrorCode
= DosReadFile(Handle
, Buffer
, Count
, &BytesRead
);
2023 if (ErrorCode
== ERROR_SUCCESS
)
2025 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2028 else if (ErrorCode
!= ERROR_NOT_READY
)
2030 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2036 /* Write to File or Device */
2039 WORD BytesWritten
= 0;
2040 WORD ErrorCode
= DosWriteFile(getBX(),
2041 SEG_OFF_TO_PTR(getDS(), getDX()),
2045 if (ErrorCode
== ERROR_SUCCESS
)
2047 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2048 setAX(BytesWritten
);
2052 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2062 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2064 /* Call the API function */
2065 if (DeleteFileA(FileName
))
2067 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2069 * See Ralf Brown: http://www.ctyme.com/intr/rb-2797.htm
2070 * "AX destroyed (DOS 3.3) AL seems to be drive of deleted file."
2072 setAL(FileName
[0] - 'A');
2076 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2077 setAX(GetLastError());
2087 WORD ErrorCode
= DosSeekFile(getBX(),
2088 MAKELONG(getDX(), getCX()),
2092 if (ErrorCode
== ERROR_SUCCESS
)
2094 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2096 /* Return the new offset in DX:AX */
2097 setDX(HIWORD(NewLocation
));
2098 setAX(LOWORD(NewLocation
));
2102 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2109 /* Get/Set File Attributes */
2113 LPSTR FileName
= (LPSTR
)SEG_OFF_TO_PTR(getDS(), getDX());
2115 if (getAL() == 0x00)
2117 /* Get the attributes */
2118 Attributes
= GetFileAttributesA(FileName
);
2120 /* Check if it failed */
2121 if (Attributes
== INVALID_FILE_ATTRIBUTES
)
2123 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2124 setAX(GetLastError());
2128 /* Return the attributes that DOS can understand */
2129 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2130 setCX(Attributes
& 0x00FF);
2133 else if (getAL() == 0x01)
2135 /* Try to set the attributes */
2136 if (SetFileAttributesA(FileName
, getCL()))
2138 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2142 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2143 setAX(GetLastError());
2148 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2149 setAX(ERROR_INVALID_FUNCTION
);
2158 if (DosHandleIoctl(getAL(), getBX()))
2160 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2164 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2165 setAX(DosLastError
);
2171 /* Duplicate Handle */
2175 HANDLE Handle
= DosGetRealHandle(getBX());
2177 if (Handle
!= INVALID_HANDLE_VALUE
)
2179 /* The handle is invalid */
2180 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2181 setAX(ERROR_INVALID_HANDLE
);
2185 /* Open a new handle to the same entry */
2186 NewHandle
= DosOpenHandle(Handle
);
2188 if (NewHandle
== INVALID_DOS_HANDLE
)
2190 /* Too many files open */
2191 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2192 setAX(ERROR_TOO_MANY_OPEN_FILES
);
2196 /* Return the result */
2197 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2202 /* Force Duplicate Handle */
2205 if (DosDuplicateHandle(getBX(), getCX()))
2207 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2211 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2212 setAX(ERROR_INVALID_HANDLE
);
2218 /* Get Current Directory */
2221 BYTE DriveNumber
= getDL();
2222 String
= (PCHAR
)SEG_OFF_TO_PTR(getDS(), getSI());
2224 /* Get the real drive number */
2225 if (DriveNumber
== 0)
2227 DriveNumber
= CurrentDrive
;
2231 /* Decrement DriveNumber since it was 1-based */
2235 if (DriveNumber
<= LastDrive
- 'A')
2238 * Copy the current directory into the target buffer.
2239 * It doesn't contain the drive letter and the backslash.
2241 strncpy(String
, CurrentDirectories
[DriveNumber
], DOS_DIR_LENGTH
);
2242 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2243 setAX(0x0100); // Undocumented, see Ralf Brown: http://www.ctyme.com/intr/rb-2933.htm
2247 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2248 setAX(ERROR_INVALID_DRIVE
);
2254 /* Allocate Memory */
2257 WORD MaxAvailable
= 0;
2258 WORD Segment
= DosAllocateMemory(getBX(), &MaxAvailable
);
2262 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2267 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2268 setAX(DosLastError
);
2269 setBX(MaxAvailable
);
2278 if (DosFreeMemory(getES()))
2280 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2284 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2285 setAX(ERROR_ARENA_TRASHED
);
2291 /* Resize Memory Block */
2296 if (DosResizeMemory(getES(), getBX(), &Size
))
2298 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2302 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2303 setAX(DosLastError
);
2310 /* Terminate With Return Code */
2313 DosTerminateProcess(CurrentPsp
, getAL());
2317 /* Get Return Code (ERRORLEVEL) */
2321 * According to Ralf Brown: http://www.ctyme.com/intr/rb-2976.htm
2322 * DosErrorLevel is cleared after being read by this function.
2324 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2325 setAX(DosErrorLevel
);
2326 DosErrorLevel
= 0x0000; // Clear it
2330 /* Internal - Set Current Process ID (Set PSP Address) */
2333 // FIXME: Is it really what it's done ??
2334 CurrentPsp
= getBX();
2338 /* Internal - Get Current Process ID (Get PSP Address) */
2340 /* Get Current PSP Address */
2344 * Undocumented AH=51h is identical to the documented AH=62h.
2345 * See Ralf Brown: http://www.ctyme.com/intr/rb-2982.htm
2346 * and http://www.ctyme.com/intr/rb-3140.htm
2347 * for more information.
2353 /* Get/Set Memory Management Options */
2356 if (getAL() == 0x00)
2358 /* Get allocation strategy */
2359 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2360 setAX(DosAllocStrategy
);
2362 else if (getAL() == 0x01)
2364 /* Set allocation strategy */
2366 if ((getBL() & (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2367 == (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2369 /* Can't set both */
2370 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2371 setAX(ERROR_INVALID_PARAMETER
);
2375 if ((getBL() & 0x3F) > DOS_ALLOC_LAST_FIT
)
2377 /* Invalid allocation strategy */
2378 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2379 setAX(ERROR_INVALID_PARAMETER
);
2383 DosAllocStrategy
= getBL();
2384 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2386 else if (getAL() == 0x02)
2388 /* Get UMB link state */
2389 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2390 setAL(DosUmbLinked
? 0x01 : 0x00);
2392 else if (getAL() == 0x03)
2394 /* Set UMB link state */
2395 if (getBX()) DosLinkUmb();
2396 else DosUnlinkUmb();
2397 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2401 /* Invalid or unsupported function */
2402 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2403 setAX(ERROR_INVALID_FUNCTION
);
2412 DPRINT1("DOS Function INT 0x21, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2414 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2419 VOID WINAPI
DosBreakInterrupt(LPWORD Stack
)
2421 UNREFERENCED_PARAMETER(Stack
);
2426 VOID WINAPI
DosInt2Fh(LPWORD Stack
)
2428 DPRINT1("DOS System Function INT 0x2F, AH = %xh, AL = %xh NOT IMPLEMENTED!\n",
2430 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2433 BOOLEAN
DosInitialize(VOID
)
2436 PDOS_MCB Mcb
= SEGMENT_TO_MCB(FIRST_MCB_SEGMENT
);
2439 LPWSTR SourcePtr
, Environment
;
2441 LPSTR DestPtr
= (LPSTR
)SEG_OFF_TO_PTR(SYSTEM_ENV_BLOCK
, 0);
2443 CHAR CurrentDirectory
[MAX_PATH
];
2444 CHAR DosDirectory
[DOS_DIR_LENGTH
];
2447 /* Initialize the MCB */
2448 Mcb
->BlockType
= 'Z';
2449 Mcb
->Size
= USER_MEMORY_SIZE
;
2452 /* Initialize the link MCB to the UMB area */
2453 Mcb
= SEGMENT_TO_MCB(FIRST_MCB_SEGMENT
+ USER_MEMORY_SIZE
+ 1);
2454 Mcb
->BlockType
= 'M';
2455 Mcb
->Size
= UMB_START_SEGMENT
- FIRST_MCB_SEGMENT
- USER_MEMORY_SIZE
- 2;
2456 Mcb
->OwnerPsp
= SYSTEM_PSP
;
2458 /* Initialize the UMB area */
2459 Mcb
= SEGMENT_TO_MCB(UMB_START_SEGMENT
);
2460 Mcb
->BlockType
= 'Z';
2461 Mcb
->Size
= UMB_END_SEGMENT
- UMB_START_SEGMENT
;
2464 /* Get the environment strings */
2465 SourcePtr
= Environment
= GetEnvironmentStringsW();
2466 if (Environment
== NULL
) return FALSE
;
2468 /* Fill the DOS system environment block */
2471 /* Get the size of the ASCII string */
2472 AsciiSize
= WideCharToMultiByte(CP_ACP
,
2481 /* Allocate memory for the ASCII string */
2482 AsciiString
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, AsciiSize
);
2483 if (AsciiString
== NULL
)
2485 FreeEnvironmentStringsW(Environment
);
2489 /* Convert to ASCII */
2490 WideCharToMultiByte(CP_ACP
,
2499 /* Copy the string into DOS memory */
2500 strcpy(DestPtr
, AsciiString
);
2502 /* Move to the next string */
2503 SourcePtr
+= wcslen(SourcePtr
) + 1;
2504 DestPtr
+= strlen(AsciiString
);
2507 /* Free the memory */
2508 HeapFree(GetProcessHeap(), 0, AsciiString
);
2512 /* Free the memory allocated for environment strings */
2513 FreeEnvironmentStringsW(Environment
);
2515 /* Clear the current directory buffer */
2516 ZeroMemory(CurrentDirectories
, sizeof(CurrentDirectories
));
2518 /* Get the current directory */
2519 if (!GetCurrentDirectoryA(MAX_PATH
, CurrentDirectory
))
2521 // TODO: Use some kind of default path?
2525 /* Convert that to a DOS path */
2526 if (!GetShortPathNameA(CurrentDirectory
, DosDirectory
, DOS_DIR_LENGTH
))
2528 // TODO: Use some kind of default path?
2533 CurrentDrive
= DosDirectory
[0] - 'A';
2535 /* Get the directory part of the path */
2536 Path
= strchr(DosDirectory
, '\\');
2539 /* Skip the backslash */
2543 /* Set the directory */
2546 strncpy(CurrentDirectories
[CurrentDrive
], Path
, DOS_DIR_LENGTH
);
2549 /* Read CONFIG.SYS */
2550 Stream
= _wfopen(DOS_CONFIG_PATH
, L
"r");
2553 while (fgetws(Buffer
, 256, Stream
))
2555 // TODO: Parse the line
2560 /* Initialize the SFT */
2561 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
2563 DosSystemFileTable
[i
] = INVALID_HANDLE_VALUE
;
2564 DosSftRefCount
[i
] = 0;
2567 /* Get handles to standard I/O devices */
2568 DosSystemFileTable
[0] = GetStdHandle(STD_INPUT_HANDLE
);
2569 DosSystemFileTable
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
2570 DosSystemFileTable
[2] = GetStdHandle(STD_ERROR_HANDLE
);
2572 /* Register the DOS 32-bit Interrupts */
2573 RegisterInt32(0x20, DosInt20h
);
2574 RegisterInt32(0x21, DosInt21h
);
2575 RegisterInt32(0x23, DosBreakInterrupt
);
2576 RegisterInt32(0x2F, DosInt2Fh
);