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 *******************************************************************/
17 /* PRIVATE VARIABLES **********************************************************/
19 static WORD CurrentPsp
= SYSTEM_PSP
;
20 static WORD DosLastError
= 0;
21 static DWORD DiskTransferArea
;
22 static BYTE CurrentDrive
;
23 static CHAR LastDrive
= 'E';
24 static CHAR CurrentDirectories
[NUM_DRIVES
][DOS_DIR_LENGTH
];
25 static HANDLE DosSystemFileTable
[DOS_SFT_SIZE
];
26 static WORD DosSftRefCount
[DOS_SFT_SIZE
];
27 static BYTE DosAllocStrategy
= DOS_ALLOC_BEST_FIT
;
28 static BOOLEAN DosUmbLinked
= FALSE
;
30 /* PRIVATE FUNCTIONS **********************************************************/
32 /* Taken from base/shell/cmd/console.c */
33 static BOOL
IsConsoleHandle(HANDLE hHandle
)
37 /* Check whether the handle may be that of a console... */
38 if ((GetFileType(hHandle
) & FILE_TYPE_CHAR
) == 0) return FALSE
;
41 * It may be. Perform another test... The idea comes from the
42 * MSDN description of the WriteConsole API:
44 * "WriteConsole fails if it is used with a standard handle
45 * that is redirected to a file. If an application processes
46 * multilingual output that can be redirected, determine whether
47 * the output handle is a console handle (one method is to call
48 * the GetConsoleMode function and check whether it succeeds).
49 * If the handle is a console handle, call WriteConsole. If the
50 * handle is not a console handle, the output is redirected and
51 * you should call WriteFile to perform the I/O."
53 return GetConsoleMode(hHandle
, &dwMode
);
56 static VOID
DosCombineFreeBlocks(WORD StartBlock
)
58 PDOS_MCB CurrentMcb
= SEGMENT_TO_MCB(StartBlock
), NextMcb
;
60 /* If this is the last block or it's not free, quit */
61 if (CurrentMcb
->BlockType
== 'Z' || CurrentMcb
->OwnerPsp
!= 0) return;
65 /* Get a pointer to the next MCB */
66 NextMcb
= SEGMENT_TO_MCB(StartBlock
+ CurrentMcb
->Size
+ 1);
68 /* Check if the next MCB is free */
69 if (NextMcb
->OwnerPsp
== 0)
72 CurrentMcb
->Size
+= NextMcb
->Size
+ 1;
73 CurrentMcb
->BlockType
= NextMcb
->BlockType
;
74 NextMcb
->BlockType
= 'I';
78 /* No more adjoining free blocks */
84 static WORD
DosCopyEnvironmentBlock(WORD SourceSegment
, LPCSTR ProgramName
)
86 PCHAR Ptr
, SourceBuffer
, DestBuffer
= NULL
;
90 Ptr
= SourceBuffer
= (PCHAR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(SourceSegment
, 0));
92 /* Calculate the size of the environment block */
95 TotalSize
+= strlen(Ptr
) + 1;
96 Ptr
+= strlen(Ptr
) + 1;
100 /* Add the string buffer size */
101 TotalSize
+= strlen(ProgramName
) + 1;
103 /* Allocate the memory for the environment block */
104 DestSegment
= DosAllocateMemory((WORD
)((TotalSize
+ 0x0F) >> 4), NULL
);
105 if (!DestSegment
) return 0;
109 DestBuffer
= (PCHAR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(DestSegment
, 0));
112 /* Copy the string */
113 strcpy(DestBuffer
, Ptr
);
115 /* Advance to the next string */
116 DestBuffer
+= strlen(Ptr
);
117 Ptr
+= strlen(Ptr
) + 1;
119 /* Put a zero after the string */
123 /* Set the final zero */
126 /* Copy the program name after the environment block */
127 strcpy(DestBuffer
, ProgramName
);
132 static VOID
DosChangeMemoryOwner(WORD Segment
, WORD NewOwner
)
134 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
- 1);
136 /* Just set the owner */
137 Mcb
->OwnerPsp
= NewOwner
;
140 static WORD
DosOpenHandle(HANDLE Handle
)
147 /* The system PSP has no handle table */
148 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_DOS_HANDLE
;
150 /* Get a pointer to the handle table */
151 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
152 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
154 /* Find a free entry in the JFT */
155 for (DosHandle
= 0; DosHandle
< PspBlock
->HandleTableSize
; DosHandle
++)
157 if (HandleTable
[DosHandle
] == 0xFF) break;
160 /* If there are no free entries, fail */
161 if (DosHandle
== PspBlock
->HandleTableSize
) return INVALID_DOS_HANDLE
;
163 /* Check if the handle is already in the SFT */
164 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
166 /* Check if this is the same handle */
167 if (DosSystemFileTable
[i
] != Handle
) continue;
169 /* Already in the table, reference it */
172 /* Set the JFT entry to that SFT index */
173 HandleTable
[DosHandle
] = i
;
175 /* Return the new handle */
179 /* Add the handle to the SFT */
180 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
182 /* Make sure this is an empty table entry */
183 if (DosSystemFileTable
[i
] != INVALID_HANDLE_VALUE
) continue;
185 /* Initialize the empty table entry */
186 DosSystemFileTable
[i
] = Handle
;
187 DosSftRefCount
[i
] = 1;
189 /* Set the JFT entry to that SFT index */
190 HandleTable
[DosHandle
] = i
;
192 /* Return the new handle */
196 /* The SFT is full */
197 return INVALID_DOS_HANDLE
;
200 static HANDLE
DosGetRealHandle(WORD DosHandle
)
205 /* The system PSP has no handle table */
206 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_HANDLE_VALUE
;
208 /* Get a pointer to the handle table */
209 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
210 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
212 /* Make sure the handle is open */
213 if (HandleTable
[DosHandle
] == 0xFF) return INVALID_HANDLE_VALUE
;
215 /* Return the Win32 handle */
216 return DosSystemFileTable
[HandleTable
[DosHandle
]];
219 static VOID
DosCopyHandleTable(LPBYTE DestinationTable
)
225 /* Clear the table first */
226 for (i
= 0; i
< 20; i
++) DestinationTable
[i
] = 0xFF;
228 /* Check if this is the initial process */
229 if (CurrentPsp
== SYSTEM_PSP
)
231 /* Set up the standard I/O devices */
232 for (i
= 0; i
<= 2; i
++)
234 /* Set the index in the SFT */
235 DestinationTable
[i
] = (BYTE
)i
;
237 /* Increase the reference count */
245 /* Get the parent PSP block and handle table */
246 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
247 SourceTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
249 /* Copy the first 20 handles into the new table */
250 for (i
= 0; i
< 20; i
++)
252 DestinationTable
[i
] = SourceTable
[i
];
254 /* Increase the reference count */
255 DosSftRefCount
[SourceTable
[i
]]++;
259 /* PUBLIC FUNCTIONS ***********************************************************/
261 WORD
DosAllocateMemory(WORD Size
, WORD
*MaxAvailable
)
263 WORD Result
= 0, Segment
= FIRST_MCB_SEGMENT
, MaxSize
= 0;
264 PDOS_MCB CurrentMcb
, NextMcb
;
265 BOOLEAN SearchUmb
= FALSE
;
267 DPRINT("DosAllocateMemory: Size 0x%04X\n", Size
);
269 if (DosUmbLinked
&& (DosAllocStrategy
& (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
)))
271 /* Search UMB first */
272 Segment
= UMB_START_SEGMENT
;
278 /* Get a pointer to the MCB */
279 CurrentMcb
= SEGMENT_TO_MCB(Segment
);
281 /* Make sure it's valid */
282 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!= 'Z')
284 DPRINT("The DOS memory arena is corrupted!\n");
285 DosLastError
= ERROR_ARENA_TRASHED
;
289 /* Only check free blocks */
290 if (CurrentMcb
->OwnerPsp
!= 0) goto Next
;
292 /* Combine this free block with adjoining free blocks */
293 DosCombineFreeBlocks(Segment
);
295 /* Update the maximum block size */
296 if (CurrentMcb
->Size
> MaxSize
) MaxSize
= CurrentMcb
->Size
;
298 /* Check if this block is big enough */
299 if (CurrentMcb
->Size
< Size
) goto Next
;
301 switch (DosAllocStrategy
& 0x3F)
303 case DOS_ALLOC_FIRST_FIT
:
305 /* For first fit, stop immediately */
310 case DOS_ALLOC_BEST_FIT
:
312 /* For best fit, update the smallest block found so far */
313 if ((Result
== 0) || (CurrentMcb
->Size
< SEGMENT_TO_MCB(Result
)->Size
))
321 case DOS_ALLOC_LAST_FIT
:
323 /* For last fit, make the current block the result, but keep searching */
330 /* If this was the last MCB in the chain, quit */
331 if (CurrentMcb
->BlockType
== 'Z')
333 /* Check if nothing was found while searching through UMBs */
334 if ((Result
== 0) && SearchUmb
&& (DosAllocStrategy
& DOS_ALLOC_HIGH_LOW
))
336 /* Search low memory */
337 Segment
= FIRST_MCB_SEGMENT
;
344 /* Otherwise, update the segment and continue */
345 Segment
+= CurrentMcb
->Size
+ 1;
350 /* If we didn't find a free block, return 0 */
353 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
354 if (MaxAvailable
) *MaxAvailable
= MaxSize
;
358 /* Get a pointer to the MCB */
359 CurrentMcb
= SEGMENT_TO_MCB(Result
);
361 /* Check if the block is larger than requested */
362 if (CurrentMcb
->Size
> Size
)
364 /* It is, split it into two blocks */
365 NextMcb
= SEGMENT_TO_MCB(Result
+ Size
+ 1);
367 /* Initialize the new MCB structure */
368 NextMcb
->BlockType
= CurrentMcb
->BlockType
;
369 NextMcb
->Size
= CurrentMcb
->Size
- Size
- 1;
370 NextMcb
->OwnerPsp
= 0;
372 /* Update the current block */
373 CurrentMcb
->BlockType
= 'M';
374 CurrentMcb
->Size
= Size
;
377 /* Take ownership of the block */
378 CurrentMcb
->OwnerPsp
= CurrentPsp
;
380 /* Return the segment of the data portion of the block */
384 BOOLEAN
DosResizeMemory(WORD BlockData
, WORD NewSize
, WORD
*MaxAvailable
)
386 BOOLEAN Success
= TRUE
;
387 WORD Segment
= BlockData
- 1, ReturnSize
= 0, NextSegment
;
388 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
), NextMcb
;
390 DPRINT("DosResizeMemory: BlockData 0x%04X, NewSize 0x%04X\n",
394 /* Make sure this is a valid, allocated block */
395 if ((Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z') || Mcb
->OwnerPsp
== 0)
398 DosLastError
= ERROR_INVALID_HANDLE
;
402 ReturnSize
= Mcb
->Size
;
404 /* Check if we need to expand or contract the block */
405 if (NewSize
> Mcb
->Size
)
407 /* We can't expand the last block */
408 if (Mcb
->BlockType
!= 'M')
414 /* Get the pointer and segment of the next MCB */
415 NextSegment
= Segment
+ Mcb
->Size
+ 1;
416 NextMcb
= SEGMENT_TO_MCB(NextSegment
);
418 /* Make sure the next segment is free */
419 if (NextMcb
->OwnerPsp
!= 0)
421 DPRINT("Cannot expand memory block: next segment is not free!\n");
422 DosLastError
= ERROR_NOT_ENOUGH_MEMORY
;
427 /* Combine this free block with adjoining free blocks */
428 DosCombineFreeBlocks(NextSegment
);
430 /* Set the maximum possible size of the block */
431 ReturnSize
+= NextMcb
->Size
+ 1;
433 /* Maximize the current block */
434 Mcb
->Size
= ReturnSize
;
435 Mcb
->BlockType
= NextMcb
->BlockType
;
437 /* Invalidate the next block */
438 NextMcb
->BlockType
= 'I';
440 /* Check if the block is larger than requested */
441 if (Mcb
->Size
> NewSize
)
443 DPRINT("Block too large, reducing size from 0x%04X to 0x%04X\n",
447 /* It is, split it into two blocks */
448 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
450 /* Initialize the new MCB structure */
451 NextMcb
->BlockType
= Mcb
->BlockType
;
452 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
453 NextMcb
->OwnerPsp
= 0;
455 /* Update the current block */
456 Mcb
->BlockType
= 'M';
460 else if (NewSize
< Mcb
->Size
)
462 DPRINT("Shrinking block from 0x%04X to 0x%04X\n",
466 /* Just split the block */
467 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
468 NextMcb
->BlockType
= Mcb
->BlockType
;
469 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
470 NextMcb
->OwnerPsp
= 0;
473 Mcb
->BlockType
= 'M';
478 /* Check if the operation failed */
481 DPRINT("DosResizeMemory FAILED. Maximum available: 0x%04X\n",
484 /* Return the maximum possible size */
485 if (MaxAvailable
) *MaxAvailable
= ReturnSize
;
491 BOOLEAN
DosFreeMemory(WORD BlockData
)
493 PDOS_MCB Mcb
= SEGMENT_TO_MCB(BlockData
- 1);
495 DPRINT("DosFreeMemory: BlockData 0x%04X\n", BlockData
);
497 /* Make sure the MCB is valid */
498 if (Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z')
500 DPRINT("MCB block type '%c' not valid!\n", Mcb
->BlockType
);
504 /* Mark the block as free */
510 BOOLEAN
DosLinkUmb(VOID
)
512 DWORD Segment
= FIRST_MCB_SEGMENT
;
513 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
);
515 DPRINT("Linking UMB\n");
517 /* Check if UMBs are already linked */
518 if (DosUmbLinked
) return FALSE
;
520 /* Find the last block */
521 while ((Mcb
->BlockType
== 'M') && (Segment
<= 0xFFFF))
523 Segment
+= Mcb
->Size
+ 1;
524 Mcb
= SEGMENT_TO_MCB(Segment
);
527 /* Make sure it's valid */
528 if (Mcb
->BlockType
!= 'Z') return FALSE
;
530 /* Connect the MCB with the UMB chain */
531 Mcb
->BlockType
= 'M';
537 BOOLEAN
DosUnlinkUmb(VOID
)
539 DWORD Segment
= FIRST_MCB_SEGMENT
;
540 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
);
542 DPRINT("Unlinking UMB\n");
544 /* Check if UMBs are already unlinked */
545 if (!DosUmbLinked
) return FALSE
;
547 /* Find the block preceding the MCB that links it with the UMB chain */
548 while (Segment
<= 0xFFFF)
550 if ((Segment
+ Mcb
->Size
) == (FIRST_MCB_SEGMENT
+ USER_MEMORY_SIZE
))
552 /* This is the last non-UMB segment */
556 /* Advance to the next MCB */
557 Segment
+= Mcb
->Size
+ 1;
558 Mcb
= SEGMENT_TO_MCB(Segment
);
561 /* Mark the MCB as the last MCB */
562 Mcb
->BlockType
= 'Z';
564 DosUmbLinked
= FALSE
;
568 WORD
DosCreateFile(LPWORD Handle
, LPCSTR FilePath
, WORD Attributes
)
573 DPRINT("DosCreateFile: FilePath \"%s\", Attributes 0x%04X\n",
577 /* Create the file */
578 FileHandle
= CreateFileA(FilePath
,
579 GENERIC_READ
| GENERIC_WRITE
,
580 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
586 if (FileHandle
== INVALID_HANDLE_VALUE
)
588 /* Return the error code */
589 return (WORD
)GetLastError();
592 /* Open the DOS handle */
593 DosHandle
= DosOpenHandle(FileHandle
);
595 if (DosHandle
== INVALID_DOS_HANDLE
)
597 /* Close the handle */
598 CloseHandle(FileHandle
);
600 /* Return the error code */
601 return ERROR_TOO_MANY_OPEN_FILES
;
604 /* It was successful */
606 return ERROR_SUCCESS
;
609 WORD
DosOpenFile(LPWORD Handle
, LPCSTR FilePath
, BYTE AccessMode
)
612 ACCESS_MASK Access
= 0;
615 DPRINT("DosOpenFile: FilePath \"%s\", AccessMode 0x%04X\n",
619 /* Parse the access mode */
620 switch (AccessMode
& 3)
625 Access
= GENERIC_READ
;
632 Access
= GENERIC_WRITE
;
639 Access
= GENERIC_READ
| GENERIC_WRITE
;
646 return ERROR_INVALID_PARAMETER
;
651 FileHandle
= CreateFileA(FilePath
,
653 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
656 FILE_ATTRIBUTE_NORMAL
,
659 if (FileHandle
== INVALID_HANDLE_VALUE
)
661 /* Return the error code */
662 return (WORD
)GetLastError();
665 /* Open the DOS handle */
666 DosHandle
= DosOpenHandle(FileHandle
);
668 if (DosHandle
== INVALID_DOS_HANDLE
)
670 /* Close the handle */
671 CloseHandle(FileHandle
);
673 /* Return the error code */
674 return ERROR_TOO_MANY_OPEN_FILES
;
677 /* It was successful */
679 return ERROR_SUCCESS
;
682 WORD
DosReadFile(WORD FileHandle
, LPVOID Buffer
, WORD Count
, LPWORD BytesRead
)
684 WORD Result
= ERROR_SUCCESS
;
685 DWORD BytesRead32
= 0;
686 HANDLE Handle
= DosGetRealHandle(FileHandle
);
689 DPRINT("DosReadFile: FileHandle 0x%04X, Count 0x%04X\n", FileHandle
, Count
);
691 /* Make sure the handle is valid */
692 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
694 if (IsConsoleHandle(Handle
))
696 for (i
= 0; i
< Count
; i
++)
698 /* Call the BIOS function to read the character */
699 ((LPBYTE
)Buffer
)[i
] = LOBYTE(BiosGetCharacter());
706 if (!ReadFile(Handle
, Buffer
, Count
, &BytesRead32
, NULL
))
708 /* Store the error code */
709 Result
= (WORD
)GetLastError();
713 /* The number of bytes read is always 16-bit */
714 *BytesRead
= LOWORD(BytesRead32
);
716 /* Return the error code */
720 WORD
DosWriteFile(WORD FileHandle
, LPVOID Buffer
, WORD Count
, LPWORD BytesWritten
)
722 WORD Result
= ERROR_SUCCESS
;
723 DWORD BytesWritten32
= 0;
724 HANDLE Handle
= DosGetRealHandle(FileHandle
);
727 DPRINT("DosWriteFile: FileHandle 0x%04X, Count 0x%04X\n",
731 /* Make sure the handle is valid */
732 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
734 if (IsConsoleHandle(Handle
))
736 for (i
= 0; i
< Count
; i
++)
738 /* Call the BIOS to print the character */
739 BiosPrintCharacter(((LPBYTE
)Buffer
)[i
], DOS_CHAR_ATTRIBUTE
, Bda
->VideoPage
);
746 if (!WriteFile(Handle
, Buffer
, Count
, &BytesWritten32
, NULL
))
748 /* Store the error code */
749 Result
= (WORD
)GetLastError();
753 /* The number of bytes written is always 16-bit */
754 *BytesWritten
= LOWORD(BytesWritten32
);
756 /* Return the error code */
760 WORD
DosSeekFile(WORD FileHandle
, LONG Offset
, BYTE Origin
, LPDWORD NewOffset
)
762 WORD Result
= ERROR_SUCCESS
;
764 HANDLE Handle
= DosGetRealHandle(FileHandle
);
766 DPRINT("DosSeekFile: FileHandle 0x%04X, Offset 0x%08X, Origin 0x%02X\n",
771 /* Make sure the handle is valid */
772 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_HANDLE
;
774 /* Check if the origin is valid */
775 if (Origin
!= FILE_BEGIN
&& Origin
!= FILE_CURRENT
&& Origin
!= FILE_END
)
777 return ERROR_INVALID_FUNCTION
;
780 /* Move the file pointer */
781 FilePointer
= SetFilePointer(Handle
, Offset
, NULL
, Origin
);
783 /* Check if there's a possibility the operation failed */
784 if (FilePointer
== INVALID_SET_FILE_POINTER
)
786 /* Get the real error code */
787 Result
= (WORD
)GetLastError();
790 if (Result
!= ERROR_SUCCESS
)
792 /* The operation did fail */
796 /* Return the file pointer, if requested */
797 if (NewOffset
) *NewOffset
= FilePointer
;
800 return ERROR_SUCCESS
;
803 BOOLEAN
DosDuplicateHandle(WORD OldHandle
, WORD NewHandle
)
809 DPRINT("DosDuplicateHandle: OldHandle 0x%04X, NewHandle 0x%04X\n",
813 /* The system PSP has no handle table */
814 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
816 /* Get a pointer to the handle table */
817 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
818 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
820 /* Make sure the old handle is open */
821 if (HandleTable
[OldHandle
] == 0xFF) return FALSE
;
823 /* Check if the new handle is open */
824 if (HandleTable
[NewHandle
] != 0xFF)
827 DosCloseHandle(NewHandle
);
830 /* Increment the reference count of the SFT entry */
831 SftIndex
= HandleTable
[OldHandle
];
832 DosSftRefCount
[SftIndex
]++;
834 /* Make the new handle point to that SFT entry */
835 HandleTable
[NewHandle
] = SftIndex
;
841 BOOLEAN
DosCloseHandle(WORD DosHandle
)
847 DPRINT("DosCloseHandle: DosHandle 0x%04X\n", DosHandle
);
849 /* The system PSP has no handle table */
850 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
852 /* Get a pointer to the handle table */
853 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
854 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
856 /* Make sure the handle is open */
857 if (HandleTable
[DosHandle
] == 0xFF) return FALSE
;
859 /* Decrement the reference count of the SFT entry */
860 SftIndex
= HandleTable
[DosHandle
];
861 DosSftRefCount
[SftIndex
]--;
863 /* Check if the reference count fell to zero */
864 if (!DosSftRefCount
[SftIndex
])
866 /* Close the file, it's no longer needed */
867 CloseHandle(DosSystemFileTable
[SftIndex
]);
869 /* Clear the handle */
870 DosSystemFileTable
[SftIndex
] = INVALID_HANDLE_VALUE
;
873 /* Clear the entry in the JFT */
874 HandleTable
[DosHandle
] = 0xFF;
879 BOOLEAN
DosChangeDrive(BYTE Drive
)
881 WCHAR DirectoryPath
[DOS_CMDLINE_LENGTH
];
883 /* Make sure the drive exists */
884 if (Drive
> (LastDrive
- 'A')) return FALSE
;
886 /* Find the path to the new current directory */
887 swprintf(DirectoryPath
, L
"%c\\%S", Drive
+ 'A', CurrentDirectories
[Drive
]);
889 /* Change the current directory of the process */
890 if (!SetCurrentDirectory(DirectoryPath
)) return FALSE
;
892 /* Set the current drive */
893 CurrentDrive
= Drive
;
899 BOOLEAN
DosChangeDirectory(LPSTR Directory
)
905 /* Make sure the directory path is not too long */
906 if (strlen(Directory
) >= DOS_DIR_LENGTH
)
908 DosLastError
= ERROR_PATH_NOT_FOUND
;
912 /* Get the drive number */
913 DriveNumber
= Directory
[0] - 'A';
915 /* Make sure the drive exists */
916 if (DriveNumber
> (LastDrive
- 'A'))
918 DosLastError
= ERROR_PATH_NOT_FOUND
;
922 /* Get the file attributes */
923 Attributes
= GetFileAttributesA(Directory
);
925 /* Make sure the path exists and is a directory */
926 if ((Attributes
== INVALID_FILE_ATTRIBUTES
)
927 || !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
929 DosLastError
= ERROR_PATH_NOT_FOUND
;
933 /* Check if this is the current drive */
934 if (DriveNumber
== CurrentDrive
)
936 /* Change the directory */
937 if (!SetCurrentDirectoryA(Directory
))
939 DosLastError
= LOWORD(GetLastError());
944 /* Get the directory part of the path */
945 Path
= strchr(Directory
, '\\');
948 /* Skip the backslash */
952 /* Set the directory for the drive */
953 if (Path
!= NULL
) strcpy(CurrentDirectories
[DriveNumber
], Path
);
954 else strcpy(CurrentDirectories
[DriveNumber
], "");
960 VOID
DosInitializePsp(WORD PspSegment
, LPCSTR CommandLine
, WORD ProgramSize
, WORD Environment
)
962 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(PspSegment
);
963 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
965 ZeroMemory(PspBlock
, sizeof(DOS_PSP
));
967 /* Set the exit interrupt */
968 PspBlock
->Exit
[0] = 0xCD; // int 0x20
969 PspBlock
->Exit
[1] = 0x20;
971 /* Set the number of the last paragraph */
972 PspBlock
->LastParagraph
= PspSegment
+ ProgramSize
- 1;
974 /* Save the interrupt vectors */
975 PspBlock
->TerminateAddress
= IntVecTable
[0x22];
976 PspBlock
->BreakAddress
= IntVecTable
[0x23];
977 PspBlock
->CriticalAddress
= IntVecTable
[0x24];
979 /* Set the parent PSP */
980 PspBlock
->ParentPsp
= CurrentPsp
;
982 /* Copy the parent handle table */
983 DosCopyHandleTable(PspBlock
->HandleTable
);
985 /* Set the environment block */
986 PspBlock
->EnvBlock
= Environment
;
988 /* Set the handle table pointers to the internal handle table */
989 PspBlock
->HandleTableSize
= 20;
990 PspBlock
->HandleTablePtr
= MAKELONG(0x18, PspSegment
);
992 /* Set the DOS version */
993 PspBlock
->DosVersion
= DOS_VERSION
;
995 /* Set the far call opcodes */
996 PspBlock
->FarCall
[0] = 0xCD; // int 0x21
997 PspBlock
->FarCall
[1] = 0x21;
998 PspBlock
->FarCall
[2] = 0xCB; // retf
1000 /* Set the command line */
1001 PspBlock
->CommandLineSize
= (BYTE
)min(strlen(CommandLine
), DOS_CMDLINE_LENGTH
- 1);
1002 RtlCopyMemory(PspBlock
->CommandLine
, CommandLine
, PspBlock
->CommandLineSize
);
1003 PspBlock
->CommandLine
[PspBlock
->CommandLineSize
] = '\r';
1006 BOOLEAN
DosCreateProcess(LPCSTR CommandLine
, WORD EnvBlock
)
1008 BOOLEAN Success
= FALSE
, AllocatedEnvBlock
= FALSE
;
1009 HANDLE FileHandle
= INVALID_HANDLE_VALUE
, FileMapping
= NULL
;
1010 LPBYTE Address
= NULL
;
1011 LPSTR ProgramFilePath
, Parameters
[256];
1012 CHAR CommandLineCopy
[DOS_CMDLINE_LENGTH
];
1016 DWORD i
, FileSize
, ExeSize
;
1017 PIMAGE_DOS_HEADER Header
;
1018 PDWORD RelocationTable
;
1021 DPRINT("DosCreateProcess: CommandLine \"%s\", EnvBlock 0x%04X\n",
1025 /* Save a copy of the command line */
1026 strcpy(CommandLineCopy
, CommandLine
);
1028 // FIXME: Improve parsing (especially: "some_path\with spaces\program.exe" options)
1030 /* Get the file name of the executable */
1031 ProgramFilePath
= strtok(CommandLineCopy
, " \t");
1033 /* Load the parameters in the local array */
1034 while ((ParamCount
< sizeof(Parameters
)/sizeof(Parameters
[0]))
1035 && ((Parameters
[ParamCount
] = strtok(NULL
, " \t")) != NULL
))
1040 /* Open a handle to the executable */
1041 FileHandle
= CreateFileA(ProgramFilePath
,
1046 FILE_ATTRIBUTE_NORMAL
,
1048 if (FileHandle
== INVALID_HANDLE_VALUE
) goto Cleanup
;
1050 /* Get the file size */
1051 FileSize
= GetFileSize(FileHandle
, NULL
);
1053 /* Create a mapping object for the file */
1054 FileMapping
= CreateFileMapping(FileHandle
,
1060 if (FileMapping
== NULL
) goto Cleanup
;
1062 /* Map the file into memory */
1063 Address
= (LPBYTE
)MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 0);
1064 if (Address
== NULL
) goto Cleanup
;
1066 /* Did we get an environment segment? */
1069 /* Set a flag to know if the environment block was allocated here */
1070 AllocatedEnvBlock
= TRUE
;
1072 /* No, copy the one from the parent */
1073 EnvBlock
= DosCopyEnvironmentBlock((CurrentPsp
!= SYSTEM_PSP
)
1074 ? SEGMENT_TO_PSP(CurrentPsp
)->EnvBlock
1079 /* Check if this is an EXE file or a COM file */
1080 if (Address
[0] == 'M' && Address
[1] == 'Z')
1084 /* Get the MZ header */
1085 Header
= (PIMAGE_DOS_HEADER
)Address
;
1087 /* Get the base size of the file, in paragraphs (rounded up) */
1088 ExeSize
= (((Header
->e_cp
- 1) * 512) + Header
->e_cblp
+ 0x0F) >> 4;
1090 /* Add the PSP size, in paragraphs */
1091 ExeSize
+= sizeof(DOS_PSP
) >> 4;
1093 /* Add the maximum size that should be allocated */
1094 ExeSize
+= Header
->e_maxalloc
;
1096 /* Make sure it does not pass 0xFFFF */
1097 if (ExeSize
> 0xFFFF) ExeSize
= 0xFFFF;
1099 /* Reduce the size one by one until the allocation is successful */
1100 for (i
= Header
->e_maxalloc
; i
>= Header
->e_minalloc
; i
--, ExeSize
--)
1102 /* Try to allocate that much memory */
1103 Segment
= DosAllocateMemory((WORD
)ExeSize
, NULL
);
1104 if (Segment
!= 0) break;
1107 /* Check if at least the lowest allocation was successful */
1108 if (Segment
== 0) goto Cleanup
;
1110 /* Initialize the PSP */
1111 DosInitializePsp(Segment
,
1116 /* The process owns its own memory */
1117 DosChangeMemoryOwner(Segment
, Segment
);
1118 DosChangeMemoryOwner(EnvBlock
, Segment
);
1120 /* Copy the program to Segment:0100 */
1121 RtlCopyMemory((PVOID
)((ULONG_PTR
)BaseAddress
1122 + TO_LINEAR(Segment
, 0x100)),
1123 Address
+ (Header
->e_cparhdr
<< 4),
1124 min(FileSize
- (Header
->e_cparhdr
<< 4),
1125 (ExeSize
<< 4) - sizeof(DOS_PSP
)));
1127 /* Get the relocation table */
1128 RelocationTable
= (PDWORD
)(Address
+ Header
->e_lfarlc
);
1130 /* Perform relocations */
1131 for (i
= 0; i
< Header
->e_crlc
; i
++)
1133 /* Get a pointer to the word that needs to be patched */
1134 RelocWord
= (PWORD
)((ULONG_PTR
)BaseAddress
1135 + TO_LINEAR(Segment
+ HIWORD(RelocationTable
[i
]),
1136 0x100 + LOWORD(RelocationTable
[i
])));
1138 /* Add the number of the EXE segment to it */
1139 *RelocWord
+= Segment
+ (sizeof(DOS_PSP
) >> 4);
1142 /* Set the initial segment registers */
1143 EmulatorSetRegister(EMULATOR_REG_DS
, Segment
);
1144 EmulatorSetRegister(EMULATOR_REG_ES
, Segment
);
1146 /* Set the stack to the location from the header */
1147 EmulatorSetStack(Segment
+ (sizeof(DOS_PSP
) >> 4) + Header
->e_ss
,
1151 CurrentPsp
= Segment
;
1152 DiskTransferArea
= MAKELONG(0x80, Segment
);
1153 EmulatorExecute(Segment
+ Header
->e_cs
+ (sizeof(DOS_PSP
) >> 4),
1162 /* Find the maximum amount of memory that can be allocated */
1163 DosAllocateMemory(0xFFFF, &MaxAllocSize
);
1165 /* Make sure it's enough for the whole program and the PSP */
1166 if (((DWORD
)MaxAllocSize
<< 4) < (FileSize
+ sizeof(DOS_PSP
))) goto Cleanup
;
1168 /* Allocate all of it */
1169 Segment
= DosAllocateMemory(MaxAllocSize
, NULL
);
1170 if (Segment
== 0) goto Cleanup
;
1172 /* The process owns its own memory */
1173 DosChangeMemoryOwner(Segment
, Segment
);
1174 DosChangeMemoryOwner(EnvBlock
, Segment
);
1176 /* Copy the program to Segment:0100 */
1177 RtlCopyMemory((PVOID
)((ULONG_PTR
)BaseAddress
1178 + TO_LINEAR(Segment
, 0x100)),
1182 /* Initialize the PSP */
1183 DosInitializePsp(Segment
,
1185 (WORD
)((FileSize
+ sizeof(DOS_PSP
)) >> 4),
1188 /* Set the initial segment registers */
1189 EmulatorSetRegister(EMULATOR_REG_DS
, Segment
);
1190 EmulatorSetRegister(EMULATOR_REG_ES
, Segment
);
1192 /* Set the stack to the last word of the segment */
1193 EmulatorSetStack(Segment
, 0xFFFE);
1196 CurrentPsp
= Segment
;
1197 DiskTransferArea
= MAKELONG(0x80, Segment
);
1198 EmulatorExecute(Segment
, 0x100);
1206 /* It was not successful, cleanup the DOS memory */
1207 if (AllocatedEnvBlock
) DosFreeMemory(EnvBlock
);
1208 if (Segment
) DosFreeMemory(Segment
);
1212 if (Address
!= NULL
) UnmapViewOfFile(Address
);
1214 /* Close the file mapping object */
1215 if (FileMapping
!= NULL
) CloseHandle(FileMapping
);
1217 /* Close the file handle */
1218 if (FileHandle
!= INVALID_HANDLE_VALUE
) CloseHandle(FileHandle
);
1223 VOID
DosTerminateProcess(WORD Psp
, BYTE ReturnCode
)
1226 WORD McbSegment
= FIRST_MCB_SEGMENT
;
1227 PDOS_MCB CurrentMcb
;
1228 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
1229 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(Psp
);
1231 DPRINT("DosTerminateProcess: Psp 0x%04X, ReturnCode 0x%02X\n",
1235 /* Check if this PSP is it's own parent */
1236 if (PspBlock
->ParentPsp
== Psp
) goto Done
;
1238 for (i
= 0; i
< PspBlock
->HandleTableSize
; i
++)
1240 /* Close the handle */
1244 /* Free the memory used by the process */
1247 /* Get a pointer to the MCB */
1248 CurrentMcb
= SEGMENT_TO_MCB(McbSegment
);
1250 /* Make sure the MCB is valid */
1251 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!='Z') break;
1253 /* If this block was allocated by the process, free it */
1254 if (CurrentMcb
->OwnerPsp
== Psp
) DosFreeMemory(McbSegment
+ 1);
1256 /* If this was the last block, quit */
1257 if (CurrentMcb
->BlockType
== 'Z') break;
1259 /* Update the segment and continue */
1260 McbSegment
+= CurrentMcb
->Size
+ 1;
1264 /* Restore the interrupt vectors */
1265 IntVecTable
[0x22] = PspBlock
->TerminateAddress
;
1266 IntVecTable
[0x23] = PspBlock
->BreakAddress
;
1267 IntVecTable
[0x24] = PspBlock
->CriticalAddress
;
1269 /* Update the current PSP */
1270 if (Psp
== CurrentPsp
)
1272 CurrentPsp
= PspBlock
->ParentPsp
;
1273 if (CurrentPsp
== SYSTEM_PSP
) VdmRunning
= FALSE
;
1276 /* Return control to the parent process */
1277 EmulatorExecute(HIWORD(PspBlock
->TerminateAddress
),
1278 LOWORD(PspBlock
->TerminateAddress
));
1281 CHAR
DosReadCharacter(VOID
)
1283 CHAR Character
= '\0';
1286 /* Use the file reading function */
1287 DosReadFile(DOS_INPUT_HANDLE
, &Character
, sizeof(CHAR
), &BytesRead
);
1292 VOID
DosPrintCharacter(CHAR Character
)
1296 /* Use the file writing function */
1297 DosWriteFile(DOS_OUTPUT_HANDLE
, &Character
, sizeof(CHAR
), &BytesWritten
);
1300 BOOLEAN
DosHandleIoctl(BYTE ControlCode
, WORD FileHandle
)
1302 HANDLE Handle
= DosGetRealHandle(FileHandle
);
1304 if (Handle
== INVALID_HANDLE_VALUE
)
1307 DosLastError
= ERROR_FILE_NOT_FOUND
;
1311 switch (ControlCode
)
1313 /* Get Device Information */
1318 if (Handle
== DosSystemFileTable
[0])
1323 else if (Handle
== DosSystemFileTable
[1])
1325 /* Console output */
1329 /* It is a character device */
1332 /* Return the device information word */
1333 EmulatorSetRegister(EMULATOR_REG_DX
, InfoWord
);
1338 /* Unsupported control code */
1341 DPRINT1("Unsupported IOCTL: 0x%02X\n", ControlCode
);
1343 DosLastError
= ERROR_INVALID_PARAMETER
;
1349 VOID
DosInt20h(LPWORD Stack
)
1351 /* This is the exit interrupt */
1352 DosTerminateProcess(Stack
[STACK_CS
], 0);
1355 VOID
DosInt21h(LPWORD Stack
)
1359 SYSTEMTIME SystemTime
;
1361 PDOS_INPUT_BUFFER InputBuffer
;
1362 DWORD Eax
= EmulatorGetRegister(EMULATOR_REG_AX
);
1363 DWORD Ecx
= EmulatorGetRegister(EMULATOR_REG_CX
);
1364 DWORD Edx
= EmulatorGetRegister(EMULATOR_REG_DX
);
1365 DWORD Ebx
= EmulatorGetRegister(EMULATOR_REG_BX
);
1366 WORD DataSegment
= (WORD
)EmulatorGetRegister(EMULATOR_REG_DS
);
1367 WORD ExtSegment
= (WORD
)EmulatorGetRegister(EMULATOR_REG_ES
);
1369 /* Check the value in the AH register */
1370 switch (HIBYTE(Eax
))
1372 /* Terminate Program */
1375 DosTerminateProcess(Stack
[STACK_CS
], 0);
1379 /* Read Character And Echo */
1382 Character
= DosReadCharacter();
1383 DosPrintCharacter(Character
);
1384 EmulatorSetRegister(EMULATOR_REG_AX
, (Eax
& 0xFFFFFF00) | Character
);
1388 /* Print Character */
1391 DosPrintCharacter(LOBYTE(Edx
));
1395 /* Read Character Without Echo */
1399 EmulatorSetRegister(EMULATOR_REG_AX
,
1400 (Eax
& 0xFFFFFF00) | DosReadCharacter());
1407 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1408 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1410 while ((*String
) != '$')
1412 DosPrintCharacter(*String
);
1419 /* Read Buffered Input */
1422 InputBuffer
= (PDOS_INPUT_BUFFER
)((ULONG_PTR
)BaseAddress
1423 + TO_LINEAR(DataSegment
,
1426 InputBuffer
->Length
= 0;
1427 for (i
= 0; i
< InputBuffer
->MaxLength
; i
++)
1429 Character
= DosReadCharacter();
1430 DosPrintCharacter(Character
);
1431 InputBuffer
->Buffer
[InputBuffer
->Length
] = Character
;
1432 if (Character
== '\r') break;
1433 InputBuffer
->Length
++;
1439 /* Set Default Drive */
1442 DosChangeDrive(LOBYTE(Edx
));
1443 EmulatorSetRegister(EMULATOR_REG_AX
,
1444 (Eax
& 0xFFFFFF00) | (LastDrive
- 'A' + 1));
1449 /* Set Disk Transfer Area */
1452 DiskTransferArea
= MAKELONG(LOWORD(Edx
), DataSegment
);
1456 /* Set Interrupt Vector */
1459 DWORD FarPointer
= MAKELONG(LOWORD(Edx
), DataSegment
);
1461 /* Write the new far pointer to the IDT */
1462 ((PDWORD
)BaseAddress
)[LOBYTE(Eax
)] = FarPointer
;
1467 /* Get system date */
1470 GetLocalTime(&SystemTime
);
1471 EmulatorSetRegister(EMULATOR_REG_CX
,
1472 (Ecx
& 0xFFFF0000) | SystemTime
.wYear
);
1473 EmulatorSetRegister(EMULATOR_REG_DX
,
1475 | (SystemTime
.wMonth
<< 8)
1477 EmulatorSetRegister(EMULATOR_REG_AX
,
1478 (Eax
& 0xFFFFFF00) | SystemTime
.wDayOfWeek
);
1482 /* Set system date */
1485 GetLocalTime(&SystemTime
);
1486 SystemTime
.wYear
= LOWORD(Ecx
);
1487 SystemTime
.wMonth
= HIBYTE(Edx
);
1488 SystemTime
.wDay
= LOBYTE(Edx
);
1490 if (SetLocalTime(&SystemTime
))
1492 /* Return success */
1493 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
& 0xFFFFFF00);
1497 /* Return failure */
1498 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
| 0xFF);
1504 /* Get system time */
1507 GetLocalTime(&SystemTime
);
1508 EmulatorSetRegister(EMULATOR_REG_CX
,
1510 | (SystemTime
.wHour
<< 8)
1511 | SystemTime
.wMinute
);
1512 EmulatorSetRegister(EMULATOR_REG_DX
,
1514 | (SystemTime
.wSecond
<< 8)
1515 | (SystemTime
.wMilliseconds
/ 10));
1519 /* Set system time */
1522 GetLocalTime(&SystemTime
);
1523 SystemTime
.wHour
= HIBYTE(Ecx
);
1524 SystemTime
.wMinute
= LOBYTE(Ecx
);
1525 SystemTime
.wSecond
= HIBYTE(Edx
);
1526 SystemTime
.wMilliseconds
= LOBYTE(Edx
) * 10;
1528 if (SetLocalTime(&SystemTime
))
1530 /* Return success */
1531 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
& 0xFFFFFF00);
1535 /* Return failure */
1536 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
| 0xFF);
1542 /* Get Disk Transfer Area */
1545 EmulatorSetRegister(EMULATOR_REG_ES
, HIWORD(DiskTransferArea
));
1546 EmulatorSetRegister(EMULATOR_REG_BX
, LOWORD(DiskTransferArea
));
1551 /* Get DOS Version */
1554 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1556 EmulatorSetRegister(EMULATOR_REG_AX
, PspBlock
->DosVersion
);
1560 /* Get Interrupt Vector */
1563 DWORD FarPointer
= ((PDWORD
)BaseAddress
)[LOBYTE(Eax
)];
1565 /* Read the address from the IDT into ES:BX */
1566 EmulatorSetRegister(EMULATOR_REG_ES
, HIWORD(FarPointer
));
1567 EmulatorSetRegister(EMULATOR_REG_BX
, LOWORD(FarPointer
));
1572 /* Create Directory */
1575 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1576 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1578 if (CreateDirectoryA(String
, NULL
))
1580 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1584 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1585 EmulatorSetRegister(EMULATOR_REG_AX
,
1586 (Eax
& 0xFFFF0000) | LOWORD(GetLastError()));
1592 /* Remove Directory */
1595 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1596 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1598 if (RemoveDirectoryA(String
))
1600 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1604 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1605 EmulatorSetRegister(EMULATOR_REG_AX
,
1606 (Eax
& 0xFFFF0000) | LOWORD(GetLastError()));
1613 /* Set Current Directory */
1616 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1617 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1619 if (DosChangeDirectory(String
))
1621 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1625 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1626 EmulatorSetRegister(EMULATOR_REG_AX
,
1627 (Eax
& 0xFFFF0000) | DosLastError
);
1637 WORD ErrorCode
= DosCreateFile(&FileHandle
,
1638 (LPCSTR
)(ULONG_PTR
)BaseAddress
1639 + TO_LINEAR(DataSegment
, LOWORD(Edx
)),
1645 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1647 /* Return the handle in AX */
1648 EmulatorSetRegister(EMULATOR_REG_AX
,
1649 (Eax
& 0xFFFF0000) | FileHandle
);
1654 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1656 /* Return the error code in AX */
1657 EmulatorSetRegister(EMULATOR_REG_AX
,
1658 (Eax
& 0xFFFF0000) | ErrorCode
);
1668 WORD ErrorCode
= DosOpenFile(&FileHandle
,
1669 (LPCSTR
)(ULONG_PTR
)BaseAddress
1670 + TO_LINEAR(DataSegment
, LOWORD(Edx
)),
1676 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1678 /* Return the handle in AX */
1679 EmulatorSetRegister(EMULATOR_REG_AX
,
1680 (Eax
& 0xFFFF0000) | FileHandle
);
1685 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1687 /* Return the error code in AX */
1688 EmulatorSetRegister(EMULATOR_REG_AX
,
1689 (Eax
& 0xFFFF0000) | ErrorCode
);
1698 if (DosCloseHandle(LOWORD(Ebx
)))
1701 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1706 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1708 /* Return the error code in AX */
1709 EmulatorSetRegister(EMULATOR_REG_AX
,
1710 (Eax
& 0xFFFF0000) | ERROR_INVALID_HANDLE
);
1720 WORD ErrorCode
= DosReadFile(LOWORD(Ebx
),
1721 (LPVOID
)((ULONG_PTR
)BaseAddress
1722 + TO_LINEAR(DataSegment
, LOWORD(Edx
))),
1729 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1731 /* Return the number of bytes read in AX */
1732 EmulatorSetRegister(EMULATOR_REG_AX
,
1733 (Eax
& 0xFFFF0000) | BytesRead
);
1738 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1740 /* Return the error code in AX */
1741 EmulatorSetRegister(EMULATOR_REG_AX
,
1742 (Eax
& 0xFFFF0000) | ErrorCode
);
1750 WORD BytesWritten
= 0;
1751 WORD ErrorCode
= DosWriteFile(LOWORD(Ebx
),
1752 (LPVOID
)((ULONG_PTR
)BaseAddress
1753 + TO_LINEAR(DataSegment
, LOWORD(Edx
))),
1760 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1762 /* Return the number of bytes written in AX */
1763 EmulatorSetRegister(EMULATOR_REG_AX
,
1764 (Eax
& 0xFFFF0000) | BytesWritten
);
1769 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1771 /* Return the error code in AX */
1772 EmulatorSetRegister(EMULATOR_REG_AX
,
1773 (Eax
& 0xFFFF0000) | ErrorCode
);
1782 LPSTR FileName
= (LPSTR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(DataSegment
, Edx
));
1784 /* Call the API function */
1785 if (DeleteFileA(FileName
)) Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1788 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1789 EmulatorSetRegister(EMULATOR_REG_AX
, GetLastError());
1799 WORD ErrorCode
= DosSeekFile(LOWORD(Ebx
),
1800 MAKELONG(LOWORD(Edx
), LOWORD(Ecx
)),
1807 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1809 /* Return the new offset in DX:AX */
1810 EmulatorSetRegister(EMULATOR_REG_DX
,
1811 (Edx
& 0xFFFF0000) | HIWORD(NewLocation
));
1812 EmulatorSetRegister(EMULATOR_REG_AX
,
1813 (Eax
& 0xFFFF0000) | LOWORD(NewLocation
));
1818 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1820 /* Return the error code in AX */
1821 EmulatorSetRegister(EMULATOR_REG_AX
,
1822 (Eax
& 0xFFFF0000) | ErrorCode
);
1828 /* Get/Set File Attributes */
1832 LPSTR FileName
= (LPSTR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(DataSegment
, Edx
));
1834 if (LOBYTE(Eax
) == 0x00)
1836 /* Get the attributes */
1837 Attributes
= GetFileAttributesA(FileName
);
1839 /* Check if it failed */
1840 if (Attributes
== INVALID_FILE_ATTRIBUTES
)
1842 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1843 EmulatorSetRegister(EMULATOR_REG_AX
, GetLastError());
1848 /* Return the attributes that DOS can understand */
1849 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1850 EmulatorSetRegister(EMULATOR_REG_CX
,
1851 (Ecx
& 0xFFFFFF00) | LOBYTE(Attributes
));
1853 else if (LOBYTE(Eax
) == 0x01)
1855 /* Try to set the attributes */
1856 if (SetFileAttributesA(FileName
, LOBYTE(Ecx
)))
1858 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1862 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1863 EmulatorSetRegister(EMULATOR_REG_AX
, GetLastError());
1868 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1869 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_FUNCTION
);
1878 if (DosHandleIoctl(LOBYTE(Eax
), LOWORD(Ebx
)))
1880 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1884 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1885 EmulatorSetRegister(EMULATOR_REG_AX
, DosLastError
);
1891 /* Duplicate Handle */
1895 HANDLE Handle
= DosGetRealHandle(LOWORD(Ebx
));
1897 if (Handle
!= INVALID_HANDLE_VALUE
)
1899 /* The handle is invalid */
1900 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1901 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_HANDLE
);
1906 /* Open a new handle to the same entry */
1907 NewHandle
= DosOpenHandle(Handle
);
1909 if (NewHandle
== INVALID_DOS_HANDLE
)
1911 /* Too many files open */
1912 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1913 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_TOO_MANY_OPEN_FILES
);
1918 /* Return the result */
1919 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1920 EmulatorSetRegister(EMULATOR_REG_AX
, NewHandle
);
1925 /* Force Duplicate Handle */
1928 if (DosDuplicateHandle(LOWORD(Ebx
), LOWORD(Ecx
)))
1930 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1934 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1935 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_HANDLE
);
1941 /* Allocate Memory */
1944 WORD MaxAvailable
= 0;
1945 WORD Segment
= DosAllocateMemory(LOWORD(Ebx
), &MaxAvailable
);
1949 EmulatorSetRegister(EMULATOR_REG_AX
, Segment
);
1950 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1954 EmulatorSetRegister(EMULATOR_REG_AX
, DosLastError
);
1955 EmulatorSetRegister(EMULATOR_REG_BX
, MaxAvailable
);
1956 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1965 if (DosFreeMemory(ExtSegment
))
1967 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1971 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_ARENA_TRASHED
);
1972 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1978 /* Resize Memory Block */
1983 if (DosResizeMemory(ExtSegment
, LOWORD(Ebx
), &Size
))
1985 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1989 EmulatorSetRegister(EMULATOR_REG_AX
, DosLastError
);
1990 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1991 EmulatorSetRegister(EMULATOR_REG_BX
, Size
);
1997 /* Terminate With Return Code */
2000 DosTerminateProcess(CurrentPsp
, LOBYTE(Eax
));
2004 /* Get Current Process */
2007 EmulatorSetRegister(EMULATOR_REG_BX
, CurrentPsp
);
2012 /* Get/Set Memory Management Options */
2015 if (LOBYTE(Eax
) == 0x00)
2017 /* Get allocation strategy */
2019 EmulatorSetRegister(EMULATOR_REG_AX
, DosAllocStrategy
);
2020 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2022 else if (LOBYTE(Eax
) == 0x01)
2024 /* Set allocation strategy */
2026 if ((LOBYTE(Ebx
) & (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2027 == (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2029 /* Can't set both */
2030 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_PARAMETER
);
2031 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2035 if ((LOBYTE(Ebx
) & 0x3F) > DOS_ALLOC_LAST_FIT
)
2037 /* Invalid allocation strategy */
2038 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_PARAMETER
);
2039 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2043 DosAllocStrategy
= LOBYTE(Ebx
);
2044 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2046 else if (LOBYTE(Eax
) == 0x02)
2048 /* Get UMB link state */
2051 if (DosUmbLinked
) Eax
|= 1;
2052 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
);
2053 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2055 else if (LOBYTE(Eax
) == 0x03)
2057 /* Set UMB link state */
2059 if (Ebx
) DosLinkUmb();
2060 else DosUnlinkUmb();
2061 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2065 /* Invalid or unsupported function */
2067 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2068 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_FUNCTION
);
2077 DPRINT1("DOS Function INT 0x21, AH = 0x%02X NOT IMPLEMENTED!\n", HIBYTE(Eax
));
2078 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2083 VOID
DosBreakInterrupt(LPWORD Stack
)
2085 UNREFERENCED_PARAMETER(Stack
);
2090 BOOLEAN
DosInitialize(VOID
)
2093 PDOS_MCB Mcb
= SEGMENT_TO_MCB(FIRST_MCB_SEGMENT
);
2096 LPWSTR SourcePtr
, Environment
;
2098 LPSTR DestPtr
= (LPSTR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(SYSTEM_ENV_BLOCK
, 0));
2100 CHAR CurrentDirectory
[MAX_PATH
];
2101 CHAR DosDirectory
[DOS_DIR_LENGTH
];
2104 /* Initialize the MCB */
2105 Mcb
->BlockType
= 'Z';
2106 Mcb
->Size
= USER_MEMORY_SIZE
;
2109 /* Initialize the link MCB to the UMB area */
2110 Mcb
= SEGMENT_TO_MCB(FIRST_MCB_SEGMENT
+ USER_MEMORY_SIZE
+ 1);
2111 Mcb
->BlockType
= 'M';
2112 Mcb
->Size
= UMB_START_SEGMENT
- FIRST_MCB_SEGMENT
- USER_MEMORY_SIZE
- 2;
2113 Mcb
->OwnerPsp
= SYSTEM_PSP
;
2115 /* Initialize the UMB area */
2116 Mcb
= SEGMENT_TO_MCB(UMB_START_SEGMENT
);
2117 Mcb
->BlockType
= 'Z';
2118 Mcb
->Size
= UMB_END_SEGMENT
- UMB_START_SEGMENT
;
2121 /* Get the environment strings */
2122 SourcePtr
= Environment
= GetEnvironmentStringsW();
2123 if (Environment
== NULL
) return FALSE
;
2125 /* Fill the DOS system environment block */
2128 /* Get the size of the ASCII string */
2129 AsciiSize
= WideCharToMultiByte(CP_ACP
,
2138 /* Allocate memory for the ASCII string */
2139 AsciiString
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, AsciiSize
);
2140 if (AsciiString
== NULL
)
2142 FreeEnvironmentStringsW(Environment
);
2146 /* Convert to ASCII */
2147 WideCharToMultiByte(CP_ACP
,
2156 /* Copy the string into DOS memory */
2157 strcpy(DestPtr
, AsciiString
);
2159 /* Move to the next string */
2160 SourcePtr
+= wcslen(SourcePtr
) + 1;
2161 DestPtr
+= strlen(AsciiString
);
2164 /* Free the memory */
2165 HeapFree(GetProcessHeap(), 0, AsciiString
);
2169 /* Free the memory allocated for environment strings */
2170 FreeEnvironmentStringsW(Environment
);
2172 /* Clear the current directory buffer */
2173 ZeroMemory(CurrentDirectories
, sizeof(CurrentDirectories
));
2175 /* Get the current directory */
2176 if (!GetCurrentDirectoryA(MAX_PATH
, CurrentDirectory
))
2178 // TODO: Use some kind of default path?
2182 /* Convert that to a DOS path */
2183 if (!GetShortPathNameA(CurrentDirectory
, DosDirectory
, DOS_DIR_LENGTH
))
2185 // TODO: Use some kind of default path?
2190 CurrentDrive
= DosDirectory
[0] - 'A';
2193 Path
= strchr(DosDirectory
, '\\');
2196 /* Skip the backslash */
2200 /* Set the directory */
2201 if (Path
!= NULL
) strcpy(CurrentDirectories
[CurrentDrive
], Path
);
2203 /* Read CONFIG.SYS */
2204 Stream
= _wfopen(DOS_CONFIG_PATH
, L
"r");
2207 while (fgetws(Buffer
, 256, Stream
))
2209 // TODO: Parse the line
2214 /* Initialize the SFT */
2215 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
2217 DosSystemFileTable
[i
] = INVALID_HANDLE_VALUE
;
2218 DosSftRefCount
[i
] = 0;
2221 /* Get handles to standard I/O devices */
2222 DosSystemFileTable
[0] = GetStdHandle(STD_INPUT_HANDLE
);
2223 DosSystemFileTable
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
2224 DosSystemFileTable
[2] = GetStdHandle(STD_ERROR_HANDLE
);