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 /* Get Default Drive */
1452 EmulatorSetRegister(EMULATOR_REG_AX
,
1453 (Eax
& 0xFFFFFF00) | CurrentDrive
);
1458 /* Set Disk Transfer Area */
1461 DiskTransferArea
= MAKELONG(LOWORD(Edx
), DataSegment
);
1465 /* Set Interrupt Vector */
1468 DWORD FarPointer
= MAKELONG(LOWORD(Edx
), DataSegment
);
1470 /* Write the new far pointer to the IDT */
1471 ((PDWORD
)BaseAddress
)[LOBYTE(Eax
)] = FarPointer
;
1476 /* Get system date */
1479 GetLocalTime(&SystemTime
);
1480 EmulatorSetRegister(EMULATOR_REG_CX
,
1481 (Ecx
& 0xFFFF0000) | SystemTime
.wYear
);
1482 EmulatorSetRegister(EMULATOR_REG_DX
,
1484 | (SystemTime
.wMonth
<< 8)
1486 EmulatorSetRegister(EMULATOR_REG_AX
,
1487 (Eax
& 0xFFFFFF00) | SystemTime
.wDayOfWeek
);
1491 /* Set system date */
1494 GetLocalTime(&SystemTime
);
1495 SystemTime
.wYear
= LOWORD(Ecx
);
1496 SystemTime
.wMonth
= HIBYTE(Edx
);
1497 SystemTime
.wDay
= LOBYTE(Edx
);
1499 if (SetLocalTime(&SystemTime
))
1501 /* Return success */
1502 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
& 0xFFFFFF00);
1506 /* Return failure */
1507 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
| 0xFF);
1513 /* Get system time */
1516 GetLocalTime(&SystemTime
);
1517 EmulatorSetRegister(EMULATOR_REG_CX
,
1519 | (SystemTime
.wHour
<< 8)
1520 | SystemTime
.wMinute
);
1521 EmulatorSetRegister(EMULATOR_REG_DX
,
1523 | (SystemTime
.wSecond
<< 8)
1524 | (SystemTime
.wMilliseconds
/ 10));
1528 /* Set system time */
1531 GetLocalTime(&SystemTime
);
1532 SystemTime
.wHour
= HIBYTE(Ecx
);
1533 SystemTime
.wMinute
= LOBYTE(Ecx
);
1534 SystemTime
.wSecond
= HIBYTE(Edx
);
1535 SystemTime
.wMilliseconds
= LOBYTE(Edx
) * 10;
1537 if (SetLocalTime(&SystemTime
))
1539 /* Return success */
1540 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
& 0xFFFFFF00);
1544 /* Return failure */
1545 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
| 0xFF);
1551 /* Get Disk Transfer Area */
1554 EmulatorSetRegister(EMULATOR_REG_ES
, HIWORD(DiskTransferArea
));
1555 EmulatorSetRegister(EMULATOR_REG_BX
, LOWORD(DiskTransferArea
));
1560 /* Get DOS Version */
1563 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1565 EmulatorSetRegister(EMULATOR_REG_AX
, PspBlock
->DosVersion
);
1569 /* Get Interrupt Vector */
1572 DWORD FarPointer
= ((PDWORD
)BaseAddress
)[LOBYTE(Eax
)];
1574 /* Read the address from the IDT into ES:BX */
1575 EmulatorSetRegister(EMULATOR_REG_ES
, HIWORD(FarPointer
));
1576 EmulatorSetRegister(EMULATOR_REG_BX
, LOWORD(FarPointer
));
1581 /* Create Directory */
1584 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1585 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1587 if (CreateDirectoryA(String
, NULL
))
1589 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1593 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1594 EmulatorSetRegister(EMULATOR_REG_AX
,
1595 (Eax
& 0xFFFF0000) | LOWORD(GetLastError()));
1601 /* Remove Directory */
1604 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1605 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1607 if (RemoveDirectoryA(String
))
1609 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1613 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1614 EmulatorSetRegister(EMULATOR_REG_AX
,
1615 (Eax
& 0xFFFF0000) | LOWORD(GetLastError()));
1622 /* Set Current Directory */
1625 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1626 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1628 if (DosChangeDirectory(String
))
1630 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1634 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1635 EmulatorSetRegister(EMULATOR_REG_AX
,
1636 (Eax
& 0xFFFF0000) | DosLastError
);
1646 WORD ErrorCode
= DosCreateFile(&FileHandle
,
1647 (LPCSTR
)(ULONG_PTR
)BaseAddress
1648 + TO_LINEAR(DataSegment
, LOWORD(Edx
)),
1654 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1656 /* Return the handle in AX */
1657 EmulatorSetRegister(EMULATOR_REG_AX
,
1658 (Eax
& 0xFFFF0000) | FileHandle
);
1663 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1665 /* Return the error code in AX */
1666 EmulatorSetRegister(EMULATOR_REG_AX
,
1667 (Eax
& 0xFFFF0000) | ErrorCode
);
1677 WORD ErrorCode
= DosOpenFile(&FileHandle
,
1678 (LPCSTR
)(ULONG_PTR
)BaseAddress
1679 + TO_LINEAR(DataSegment
, LOWORD(Edx
)),
1685 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1687 /* Return the handle in AX */
1688 EmulatorSetRegister(EMULATOR_REG_AX
,
1689 (Eax
& 0xFFFF0000) | FileHandle
);
1694 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1696 /* Return the error code in AX */
1697 EmulatorSetRegister(EMULATOR_REG_AX
,
1698 (Eax
& 0xFFFF0000) | ErrorCode
);
1707 if (DosCloseHandle(LOWORD(Ebx
)))
1710 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1715 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1717 /* Return the error code in AX */
1718 EmulatorSetRegister(EMULATOR_REG_AX
,
1719 (Eax
& 0xFFFF0000) | ERROR_INVALID_HANDLE
);
1729 WORD ErrorCode
= DosReadFile(LOWORD(Ebx
),
1730 (LPVOID
)((ULONG_PTR
)BaseAddress
1731 + TO_LINEAR(DataSegment
, LOWORD(Edx
))),
1738 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1740 /* Return the number of bytes read in AX */
1741 EmulatorSetRegister(EMULATOR_REG_AX
,
1742 (Eax
& 0xFFFF0000) | BytesRead
);
1747 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1749 /* Return the error code in AX */
1750 EmulatorSetRegister(EMULATOR_REG_AX
,
1751 (Eax
& 0xFFFF0000) | ErrorCode
);
1759 WORD BytesWritten
= 0;
1760 WORD ErrorCode
= DosWriteFile(LOWORD(Ebx
),
1761 (LPVOID
)((ULONG_PTR
)BaseAddress
1762 + TO_LINEAR(DataSegment
, LOWORD(Edx
))),
1769 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1771 /* Return the number of bytes written in AX */
1772 EmulatorSetRegister(EMULATOR_REG_AX
,
1773 (Eax
& 0xFFFF0000) | BytesWritten
);
1778 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1780 /* Return the error code in AX */
1781 EmulatorSetRegister(EMULATOR_REG_AX
,
1782 (Eax
& 0xFFFF0000) | ErrorCode
);
1791 LPSTR FileName
= (LPSTR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(DataSegment
, Edx
));
1793 /* Call the API function */
1794 if (DeleteFileA(FileName
)) Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1797 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1798 EmulatorSetRegister(EMULATOR_REG_AX
, GetLastError());
1808 WORD ErrorCode
= DosSeekFile(LOWORD(Ebx
),
1809 MAKELONG(LOWORD(Edx
), LOWORD(Ecx
)),
1816 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1818 /* Return the new offset in DX:AX */
1819 EmulatorSetRegister(EMULATOR_REG_DX
,
1820 (Edx
& 0xFFFF0000) | HIWORD(NewLocation
));
1821 EmulatorSetRegister(EMULATOR_REG_AX
,
1822 (Eax
& 0xFFFF0000) | LOWORD(NewLocation
));
1827 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1829 /* Return the error code in AX */
1830 EmulatorSetRegister(EMULATOR_REG_AX
,
1831 (Eax
& 0xFFFF0000) | ErrorCode
);
1837 /* Get/Set File Attributes */
1841 LPSTR FileName
= (LPSTR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(DataSegment
, Edx
));
1843 if (LOBYTE(Eax
) == 0x00)
1845 /* Get the attributes */
1846 Attributes
= GetFileAttributesA(FileName
);
1848 /* Check if it failed */
1849 if (Attributes
== INVALID_FILE_ATTRIBUTES
)
1851 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1852 EmulatorSetRegister(EMULATOR_REG_AX
, GetLastError());
1857 /* Return the attributes that DOS can understand */
1858 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1859 EmulatorSetRegister(EMULATOR_REG_CX
,
1860 (Ecx
& 0xFFFFFF00) | LOBYTE(Attributes
));
1862 else if (LOBYTE(Eax
) == 0x01)
1864 /* Try to set the attributes */
1865 if (SetFileAttributesA(FileName
, LOBYTE(Ecx
)))
1867 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1871 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1872 EmulatorSetRegister(EMULATOR_REG_AX
, GetLastError());
1877 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1878 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_FUNCTION
);
1887 if (DosHandleIoctl(LOBYTE(Eax
), LOWORD(Ebx
)))
1889 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1893 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1894 EmulatorSetRegister(EMULATOR_REG_AX
, DosLastError
);
1900 /* Duplicate Handle */
1904 HANDLE Handle
= DosGetRealHandle(LOWORD(Ebx
));
1906 if (Handle
!= INVALID_HANDLE_VALUE
)
1908 /* The handle is invalid */
1909 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1910 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_HANDLE
);
1915 /* Open a new handle to the same entry */
1916 NewHandle
= DosOpenHandle(Handle
);
1918 if (NewHandle
== INVALID_DOS_HANDLE
)
1920 /* Too many files open */
1921 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1922 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_TOO_MANY_OPEN_FILES
);
1927 /* Return the result */
1928 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1929 EmulatorSetRegister(EMULATOR_REG_AX
, NewHandle
);
1934 /* Force Duplicate Handle */
1937 if (DosDuplicateHandle(LOWORD(Ebx
), LOWORD(Ecx
)))
1939 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1943 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1944 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_HANDLE
);
1950 /* Allocate Memory */
1953 WORD MaxAvailable
= 0;
1954 WORD Segment
= DosAllocateMemory(LOWORD(Ebx
), &MaxAvailable
);
1958 EmulatorSetRegister(EMULATOR_REG_AX
, Segment
);
1959 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1963 EmulatorSetRegister(EMULATOR_REG_AX
, DosLastError
);
1964 EmulatorSetRegister(EMULATOR_REG_BX
, MaxAvailable
);
1965 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1974 if (DosFreeMemory(ExtSegment
))
1976 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1980 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_ARENA_TRASHED
);
1981 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
1987 /* Resize Memory Block */
1992 if (DosResizeMemory(ExtSegment
, LOWORD(Ebx
), &Size
))
1994 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
1998 EmulatorSetRegister(EMULATOR_REG_AX
, DosLastError
);
1999 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2000 EmulatorSetRegister(EMULATOR_REG_BX
, Size
);
2006 /* Terminate With Return Code */
2009 DosTerminateProcess(CurrentPsp
, LOBYTE(Eax
));
2013 /* Get Current Process */
2016 EmulatorSetRegister(EMULATOR_REG_BX
, CurrentPsp
);
2021 /* Get/Set Memory Management Options */
2024 if (LOBYTE(Eax
) == 0x00)
2026 /* Get allocation strategy */
2028 EmulatorSetRegister(EMULATOR_REG_AX
, DosAllocStrategy
);
2029 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2031 else if (LOBYTE(Eax
) == 0x01)
2033 /* Set allocation strategy */
2035 if ((LOBYTE(Ebx
) & (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2036 == (DOS_ALLOC_HIGH
| DOS_ALLOC_HIGH_LOW
))
2038 /* Can't set both */
2039 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_PARAMETER
);
2040 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2044 if ((LOBYTE(Ebx
) & 0x3F) > DOS_ALLOC_LAST_FIT
)
2046 /* Invalid allocation strategy */
2047 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_PARAMETER
);
2048 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2052 DosAllocStrategy
= LOBYTE(Ebx
);
2053 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2055 else if (LOBYTE(Eax
) == 0x02)
2057 /* Get UMB link state */
2060 if (DosUmbLinked
) Eax
|= 1;
2061 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
);
2062 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2064 else if (LOBYTE(Eax
) == 0x03)
2066 /* Set UMB link state */
2068 if (Ebx
) DosLinkUmb();
2069 else DosUnlinkUmb();
2070 Stack
[STACK_FLAGS
] &= ~EMULATOR_FLAG_CF
;
2074 /* Invalid or unsupported function */
2076 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2077 EmulatorSetRegister(EMULATOR_REG_AX
, ERROR_INVALID_FUNCTION
);
2086 DPRINT1("DOS Function INT 0x21, AH = 0x%02X NOT IMPLEMENTED!\n", HIBYTE(Eax
));
2087 Stack
[STACK_FLAGS
] |= EMULATOR_FLAG_CF
;
2092 VOID
DosBreakInterrupt(LPWORD Stack
)
2094 UNREFERENCED_PARAMETER(Stack
);
2099 BOOLEAN
DosInitialize(VOID
)
2102 PDOS_MCB Mcb
= SEGMENT_TO_MCB(FIRST_MCB_SEGMENT
);
2105 LPWSTR SourcePtr
, Environment
;
2107 LPSTR DestPtr
= (LPSTR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(SYSTEM_ENV_BLOCK
, 0));
2109 CHAR CurrentDirectory
[MAX_PATH
];
2110 CHAR DosDirectory
[DOS_DIR_LENGTH
];
2113 /* Initialize the MCB */
2114 Mcb
->BlockType
= 'Z';
2115 Mcb
->Size
= USER_MEMORY_SIZE
;
2118 /* Initialize the link MCB to the UMB area */
2119 Mcb
= SEGMENT_TO_MCB(FIRST_MCB_SEGMENT
+ USER_MEMORY_SIZE
+ 1);
2120 Mcb
->BlockType
= 'M';
2121 Mcb
->Size
= UMB_START_SEGMENT
- FIRST_MCB_SEGMENT
- USER_MEMORY_SIZE
- 2;
2122 Mcb
->OwnerPsp
= SYSTEM_PSP
;
2124 /* Initialize the UMB area */
2125 Mcb
= SEGMENT_TO_MCB(UMB_START_SEGMENT
);
2126 Mcb
->BlockType
= 'Z';
2127 Mcb
->Size
= UMB_END_SEGMENT
- UMB_START_SEGMENT
;
2130 /* Get the environment strings */
2131 SourcePtr
= Environment
= GetEnvironmentStringsW();
2132 if (Environment
== NULL
) return FALSE
;
2134 /* Fill the DOS system environment block */
2137 /* Get the size of the ASCII string */
2138 AsciiSize
= WideCharToMultiByte(CP_ACP
,
2147 /* Allocate memory for the ASCII string */
2148 AsciiString
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, AsciiSize
);
2149 if (AsciiString
== NULL
)
2151 FreeEnvironmentStringsW(Environment
);
2155 /* Convert to ASCII */
2156 WideCharToMultiByte(CP_ACP
,
2165 /* Copy the string into DOS memory */
2166 strcpy(DestPtr
, AsciiString
);
2168 /* Move to the next string */
2169 SourcePtr
+= wcslen(SourcePtr
) + 1;
2170 DestPtr
+= strlen(AsciiString
);
2173 /* Free the memory */
2174 HeapFree(GetProcessHeap(), 0, AsciiString
);
2178 /* Free the memory allocated for environment strings */
2179 FreeEnvironmentStringsW(Environment
);
2181 /* Clear the current directory buffer */
2182 ZeroMemory(CurrentDirectories
, sizeof(CurrentDirectories
));
2184 /* Get the current directory */
2185 if (!GetCurrentDirectoryA(MAX_PATH
, CurrentDirectory
))
2187 // TODO: Use some kind of default path?
2191 /* Convert that to a DOS path */
2192 if (!GetShortPathNameA(CurrentDirectory
, DosDirectory
, DOS_DIR_LENGTH
))
2194 // TODO: Use some kind of default path?
2199 CurrentDrive
= DosDirectory
[0] - 'A';
2202 Path
= strchr(DosDirectory
, '\\');
2205 /* Skip the backslash */
2209 /* Set the directory */
2210 if (Path
!= NULL
) strcpy(CurrentDirectories
[CurrentDrive
], Path
);
2212 /* Read CONFIG.SYS */
2213 Stream
= _wfopen(DOS_CONFIG_PATH
, L
"r");
2216 while (fgetws(Buffer
, 256, Stream
))
2218 // TODO: Parse the line
2223 /* Initialize the SFT */
2224 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
2226 DosSystemFileTable
[i
] = INVALID_HANDLE_VALUE
;
2227 DosSftRefCount
[i
] = 0;
2230 /* Get handles to standard I/O devices */
2231 DosSystemFileTable
[0] = GetStdHandle(STD_INPUT_HANDLE
);
2232 DosSystemFileTable
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
2233 DosSystemFileTable
[2] = GetStdHandle(STD_ERROR_HANDLE
);