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 *******************************************************************/
15 /* PRIVATE VARIABLES **********************************************************/
17 static WORD CurrentPsp
= SYSTEM_PSP
;
18 static DWORD DiskTransferArea
;
19 static HANDLE DosSystemFileTable
[DOS_SFT_SIZE
];
20 static WORD DosSftRefCount
[DOS_SFT_SIZE
];
22 /* PRIVATE FUNCTIONS **********************************************************/
24 static VOID
DosCombineFreeBlocks(WORD StartBlock
)
26 PDOS_MCB CurrentMcb
= SEGMENT_TO_MCB(StartBlock
), NextMcb
;
28 /* If this is the last block or it's not free, quit */
29 if (CurrentMcb
->BlockType
== 'Z' || CurrentMcb
->OwnerPsp
!= 0) return;
33 /* Get a pointer to the next MCB */
34 NextMcb
= SEGMENT_TO_MCB(StartBlock
+ CurrentMcb
->Size
+ 1);
36 /* Check if the next MCB is free */
37 if (NextMcb
->OwnerPsp
== 0)
40 CurrentMcb
->Size
+= NextMcb
->Size
+ 1;
41 CurrentMcb
->BlockType
= NextMcb
->BlockType
;
42 NextMcb
->BlockType
= 'I';
46 /* No more adjoining free blocks */
52 static WORD
DosCopyEnvironmentBlock(WORD SourceSegment
)
54 PCHAR Ptr
, SourceBuffer
, DestBuffer
= NULL
;
58 Ptr
= SourceBuffer
= (PCHAR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(SourceSegment
, 0));
60 /* Calculate the size of the environment block */
63 TotalSize
+= strlen(Ptr
) + 1;
64 Ptr
+= strlen(Ptr
) + 1;
68 /* Allocate the memory for the environment block */
69 DestSegment
= DosAllocateMemory((TotalSize
+ 0x0F) >> 4, NULL
);
70 if (!DestSegment
) return 0;
74 DestBuffer
= (PCHAR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(DestSegment
, 0));
78 strcpy(DestBuffer
, Ptr
);
80 /* Advance to the next string */
81 Ptr
+= strlen(Ptr
) + 1;
82 DestBuffer
+= strlen(Ptr
);
84 /* Put a zero after the string */
88 /* Set the final zero */
94 static VOID
DosChangeMemoryOwner(WORD Segment
, WORD NewOwner
)
96 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
- 1);
98 /* Just set the owner */
99 Mcb
->OwnerPsp
= NewOwner
;
102 static WORD
DosOpenHandle(HANDLE Handle
)
109 /* The system PSP has no handle table */
110 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_DOS_HANDLE
;
112 /* Get a pointer to the handle table */
113 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
114 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
116 /* Find a free entry in the JFT */
117 for (DosHandle
= 0; DosHandle
< PspBlock
->HandleTableSize
; DosHandle
++)
119 if (HandleTable
[DosHandle
] == 0xFF) break;
122 /* If there are no free entries, fail */
123 if (DosHandle
== PspBlock
->HandleTableSize
) return INVALID_DOS_HANDLE
;
125 /* Check if the handle is already in the SFT */
126 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
128 /* Check if this is the same handle */
129 if (DosSystemFileTable
[i
] != Handle
) continue;
131 /* Already in the table, reference it */
134 /* Set the JFT entry to that SFT index */
135 HandleTable
[DosHandle
] = i
;
137 /* Return the new handle */
141 /* Add the handle to the SFT */
142 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
144 /* Make sure this is an empty table entry */
145 if (DosSystemFileTable
[i
] != INVALID_HANDLE_VALUE
) continue;
147 /* Initialize the empty table entry */
148 DosSystemFileTable
[i
] = Handle
;
149 DosSftRefCount
[i
] = 1;
151 /* Set the JFT entry to that SFT index */
152 HandleTable
[DosHandle
] = i
;
154 /* Return the new handle */
158 /* The SFT is full */
159 return INVALID_DOS_HANDLE
;
162 static HANDLE
DosGetRealHandle(WORD DosHandle
)
167 /* The system PSP has no handle table */
168 if (CurrentPsp
== SYSTEM_PSP
) return INVALID_HANDLE_VALUE
;
170 /* Get a pointer to the handle table */
171 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
172 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
174 /* Make sure the handle is open */
175 if (HandleTable
[DosHandle
] == 0xFF) return INVALID_HANDLE_VALUE
;
177 /* Return the Win32 handle */
178 return DosSystemFileTable
[HandleTable
[DosHandle
]];
181 static VOID
DosCopyHandleTable(LPBYTE DestinationTable
)
187 /* Clear the table first */
188 for (i
= 0; i
< 20; i
++) DestinationTable
[i
] = 0xFF;
190 /* Check if this is the initial process */
191 if (CurrentPsp
== SYSTEM_PSP
)
193 /* Set up the standard I/O devices */
194 for (i
= 0; i
<= 2; i
++)
196 /* Set the index in the SFT */
197 DestinationTable
[i
] = i
;
199 /* Increase the reference count */
207 /* Get the parent PSP block and handle table */
208 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
209 SourceTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
211 /* Copy the first 20 handles into the new table */
212 for (i
= 0; i
< 20; i
++)
214 DestinationTable
[i
] = SourceTable
[i
];
216 /* Increase the reference count */
217 DosSftRefCount
[SourceTable
[i
]]++;
221 /* PUBLIC FUNCTIONS ***********************************************************/
223 WORD
DosAllocateMemory(WORD Size
, WORD
*MaxAvailable
)
225 WORD Result
= 0, Segment
= FIRST_MCB_SEGMENT
, MaxSize
= 0;
226 PDOS_MCB CurrentMcb
, NextMcb
;
230 /* Get a pointer to the MCB */
231 CurrentMcb
= SEGMENT_TO_MCB(Segment
);
233 /* Make sure it's valid */
234 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!= 'Z')
239 /* Only check free blocks */
240 if (CurrentMcb
->OwnerPsp
!= 0) goto Next
;
242 /* Combine this free block with adjoining free blocks */
243 DosCombineFreeBlocks(Segment
);
245 /* Update the maximum block size */
246 if (CurrentMcb
->Size
> MaxSize
) MaxSize
= CurrentMcb
->Size
;
248 /* Check if this block is big enough */
249 if (CurrentMcb
->Size
< Size
) goto Next
;
251 /* It is, update the smallest found so far */
252 if ((Result
== 0) || (CurrentMcb
->Size
< SEGMENT_TO_MCB(Result
)->Size
))
258 /* If this was the last MCB in the chain, quit */
259 if (CurrentMcb
->BlockType
== 'Z') break;
261 /* Otherwise, update the segment and continue */
262 Segment
+= CurrentMcb
->Size
+ 1;
265 /* If we didn't find a free block, return 0 */
268 if (MaxAvailable
) *MaxAvailable
= MaxSize
;
272 /* Get a pointer to the MCB */
273 CurrentMcb
= SEGMENT_TO_MCB(Result
);
275 /* Check if the block is larger than requested */
276 if (CurrentMcb
->Size
> Size
)
278 /* It is, split it into two blocks */
279 NextMcb
= SEGMENT_TO_MCB(Result
+ Size
+ 1);
281 /* Initialize the new MCB structure */
282 NextMcb
->BlockType
= CurrentMcb
->BlockType
;
283 NextMcb
->Size
= CurrentMcb
->Size
- Size
- 1;
284 NextMcb
->OwnerPsp
= 0;
286 /* Update the current block */
287 CurrentMcb
->BlockType
= 'M';
288 CurrentMcb
->Size
= Size
;
291 /* Take ownership of the block */
292 CurrentMcb
->OwnerPsp
= CurrentPsp
;
294 /* Return the segment of the data portion of the block */
298 BOOLEAN
DosResizeMemory(WORD BlockData
, WORD NewSize
, WORD
*MaxAvailable
)
300 BOOLEAN Success
= TRUE
;
301 WORD Segment
= BlockData
- 1, ReturnSize
= 0, NextSegment
;
302 PDOS_MCB Mcb
= SEGMENT_TO_MCB(Segment
), NextMcb
;
304 /* Make sure this is a valid, allocated block */
305 if ((Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z') || Mcb
->OwnerPsp
== 0)
311 ReturnSize
= Mcb
->Size
;
313 /* Check if we need to expand or contract the block */
314 if (NewSize
> Mcb
->Size
)
316 /* We can't expand the last block */
317 if (Mcb
->BlockType
!= 'M')
323 /* Get the pointer and segment of the next MCB */
324 NextSegment
= Segment
+ Mcb
->Size
+ 1;
325 NextMcb
= SEGMENT_TO_MCB(NextSegment
);
327 /* Make sure the next segment is free */
328 if (NextMcb
->OwnerPsp
!= 0)
334 /* Combine this free block with adjoining free blocks */
335 DosCombineFreeBlocks(NextSegment
);
337 /* Set the maximum possible size of the block */
338 ReturnSize
+= NextMcb
->Size
+ 1;
340 /* Maximize the current block */
341 Mcb
->Size
= ReturnSize
;
342 Mcb
->BlockType
= NextMcb
->BlockType
;
344 /* Invalidate the next block */
345 NextMcb
->BlockType
= 'I';
347 /* Check if the block is larger than requested */
348 if (Mcb
->Size
> NewSize
)
350 /* It is, split it into two blocks */
351 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
353 /* Initialize the new MCB structure */
354 NextMcb
->BlockType
= Mcb
->BlockType
;
355 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
356 NextMcb
->OwnerPsp
= 0;
358 /* Update the current block */
359 Mcb
->BlockType
= 'M';
363 else if (NewSize
< Mcb
->Size
)
365 /* Just split the block */
366 NextMcb
= SEGMENT_TO_MCB(Segment
+ NewSize
+ 1);
367 NextMcb
->BlockType
= Mcb
->BlockType
;
368 NextMcb
->Size
= Mcb
->Size
- NewSize
- 1;
369 NextMcb
->OwnerPsp
= 0;
372 Mcb
->BlockType
= 'M';
377 /* Check if the operation failed */
380 /* Return the maximum possible size */
381 if (MaxAvailable
) *MaxAvailable
= ReturnSize
;
387 BOOLEAN
DosFreeMemory(WORD BlockData
)
389 PDOS_MCB Mcb
= SEGMENT_TO_MCB(BlockData
- 1);
391 /* Make sure the MCB is valid */
392 if (Mcb
->BlockType
!= 'M' && Mcb
->BlockType
!= 'Z') return FALSE
;
394 /* Mark the block as free */
400 WORD
DosCreateFile(LPWORD Handle
, LPCSTR FilePath
, WORD Attributes
)
405 /* Create the file */
406 FileHandle
= CreateFileA(FilePath
,
407 GENERIC_READ
| GENERIC_WRITE
,
408 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
414 if (FileHandle
== INVALID_HANDLE_VALUE
)
416 /* Return the error code */
417 return GetLastError();
420 /* Open the DOS handle */
421 DosHandle
= DosOpenHandle(FileHandle
);
423 if (DosHandle
== INVALID_DOS_HANDLE
)
425 /* Close the handle */
426 CloseHandle(FileHandle
);
428 /* Return the error code */
429 return ERROR_TOO_MANY_OPEN_FILES
;
432 /* It was successful */
434 return ERROR_SUCCESS
;
437 WORD
DosOpenFile(LPWORD Handle
, LPCSTR FilePath
, BYTE AccessMode
)
440 ACCESS_MASK Access
= 0;
443 /* Parse the access mode */
444 switch (AccessMode
& 3)
449 Access
= GENERIC_READ
;
456 Access
= GENERIC_WRITE
;
463 Access
= GENERIC_READ
| GENERIC_WRITE
;
470 return ERROR_INVALID_PARAMETER
;
475 FileHandle
= CreateFileA(FilePath
,
477 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
480 FILE_ATTRIBUTE_NORMAL
,
483 if (FileHandle
== INVALID_HANDLE_VALUE
)
485 /* Return the error code */
486 return GetLastError();
489 /* Open the DOS handle */
490 DosHandle
= DosOpenHandle(FileHandle
);
492 if (DosHandle
== INVALID_DOS_HANDLE
)
494 /* Close the handle */
495 CloseHandle(FileHandle
);
497 /* Return the error code */
498 return ERROR_TOO_MANY_OPEN_FILES
;
501 /* It was successful */
503 return ERROR_SUCCESS
;
506 WORD
DosReadFile(WORD FileHandle
, LPVOID Buffer
, WORD Count
, LPWORD BytesRead
)
508 WORD Result
= ERROR_SUCCESS
;
509 DWORD BytesRead32
= 0;
510 HANDLE Handle
= DosGetRealHandle(FileHandle
);
512 /* Make sure the handle is valid */
513 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_PARAMETER
;
516 if (!ReadFile(Handle
, Buffer
, Count
, &BytesRead32
, NULL
))
518 /* Store the error code */
519 Result
= GetLastError();
522 /* The number of bytes read is always 16-bit */
523 *BytesRead
= LOWORD(BytesRead32
);
525 /* Return the error code */
529 WORD
DosWriteFile(WORD FileHandle
, LPVOID Buffer
, WORD Count
, LPWORD BytesWritten
)
531 WORD Result
= ERROR_SUCCESS
;
532 DWORD BytesWritten32
= 0;
533 HANDLE Handle
= DosGetRealHandle(FileHandle
);
535 /* Make sure the handle is valid */
536 if (Handle
== INVALID_HANDLE_VALUE
) return ERROR_INVALID_PARAMETER
;
539 if (!WriteFile(Handle
, Buffer
, Count
, &BytesWritten32
, NULL
))
541 /* Store the error code */
542 Result
= GetLastError();
545 /* The number of bytes written is always 16-bit */
546 *BytesWritten
= LOWORD(BytesWritten32
);
548 /* Return the error code */
552 BOOLEAN
DosCloseHandle(WORD DosHandle
)
558 /* The system PSP has no handle table */
559 if (CurrentPsp
== SYSTEM_PSP
) return FALSE
;
561 /* Get a pointer to the handle table */
562 PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
563 HandleTable
= (LPBYTE
)FAR_POINTER(PspBlock
->HandleTablePtr
);
565 /* Make sure the handle is open */
566 if (HandleTable
[DosHandle
] == 0xFF) return FALSE
;
568 /* Decrement the reference count of the SFT entry */
569 SftIndex
= HandleTable
[DosHandle
];
570 DosSftRefCount
[SftIndex
]--;
572 /* Check if the reference count fell to zero */
573 if (!DosSftRefCount
[SftIndex
])
575 /* Close the file, it's no longer needed */
576 CloseHandle(DosSystemFileTable
[SftIndex
]);
578 /* Clear the handle */
579 DosSystemFileTable
[SftIndex
] = INVALID_HANDLE_VALUE
;
585 VOID
DosInitializePsp(WORD PspSegment
, LPCSTR CommandLine
, WORD ProgramSize
, WORD Environment
)
587 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(PspSegment
);
588 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
590 ZeroMemory(PspBlock
, sizeof(DOS_PSP
));
592 /* Set the exit interrupt */
593 PspBlock
->Exit
[0] = 0xCD; // int 0x20
594 PspBlock
->Exit
[1] = 0x20;
596 /* Set the number of the last paragraph */
597 PspBlock
->LastParagraph
= PspSegment
+ ProgramSize
- 1;
599 /* Save the interrupt vectors */
600 PspBlock
->TerminateAddress
= IntVecTable
[0x22];
601 PspBlock
->BreakAddress
= IntVecTable
[0x23];
602 PspBlock
->CriticalAddress
= IntVecTable
[0x24];
604 /* Set the parent PSP */
605 PspBlock
->ParentPsp
= CurrentPsp
;
607 /* Copy the parent handle table */
608 DosCopyHandleTable(PspBlock
->HandleTable
);
610 /* Set the environment block */
611 PspBlock
->EnvBlock
= Environment
;
613 /* Set the handle table pointers to the internal handle table */
614 PspBlock
->HandleTableSize
= 20;
615 PspBlock
->HandleTablePtr
= MAKELONG(0x18, PspSegment
);
617 /* Set the DOS version */
618 PspBlock
->DosVersion
= DOS_VERSION
;
620 /* Set the far call opcodes */
621 PspBlock
->FarCall
[0] = 0xCD; // int 0x21
622 PspBlock
->FarCall
[1] = 0x21;
623 PspBlock
->FarCall
[2] = 0xCB; // retf
625 /* Set the command line */
626 PspBlock
->CommandLineSize
= strlen(CommandLine
);
627 RtlCopyMemory(PspBlock
->CommandLine
, CommandLine
, PspBlock
->CommandLineSize
);
628 PspBlock
->CommandLine
[PspBlock
->CommandLineSize
] = '\r';
631 BOOLEAN
DosCreateProcess(LPCSTR CommandLine
, WORD EnvBlock
)
633 BOOLEAN Success
= FALSE
, AllocatedEnvBlock
= FALSE
;
634 HANDLE FileHandle
= INVALID_HANDLE_VALUE
, FileMapping
= NULL
;
635 LPBYTE Address
= NULL
;
636 LPSTR ProgramFilePath
, Parameters
[128];
637 CHAR CommandLineCopy
[128];
640 DWORD i
, FileSize
, ExeSize
;
641 PIMAGE_DOS_HEADER Header
;
642 PDWORD RelocationTable
;
645 /* Save a copy of the command line */
646 strcpy(CommandLineCopy
, CommandLine
);
648 /* Get the file name of the executable */
649 ProgramFilePath
= strtok(CommandLineCopy
, " \t");
651 /* Load the parameters in the local array */
652 while ((ParamCount
< 256)
653 && ((Parameters
[ParamCount
] = strtok(NULL
, " \t")) != NULL
))
658 /* Open a handle to the executable */
659 FileHandle
= CreateFileA(ProgramFilePath
,
664 FILE_ATTRIBUTE_NORMAL
,
666 if (FileHandle
== INVALID_HANDLE_VALUE
) goto Cleanup
;
668 /* Get the file size */
669 FileSize
= GetFileSize(FileHandle
, NULL
);
671 /* Create a mapping object for the file */
672 FileMapping
= CreateFileMapping(FileHandle
,
678 if (FileMapping
== NULL
) goto Cleanup
;
680 /* Map the file into memory */
681 Address
= (LPBYTE
)MapViewOfFile(FileMapping
, FILE_MAP_READ
, 0, 0, 0);
682 if (Address
== NULL
) goto Cleanup
;
684 /* Did we get an environment segment? */
687 /* Set a flag to know if the environment block was allocated here */
688 AllocatedEnvBlock
= TRUE
;
690 /* No, copy the one from the parent */
691 EnvBlock
= DosCopyEnvironmentBlock((CurrentPsp
!= SYSTEM_PSP
)
692 ? SEGMENT_TO_PSP(CurrentPsp
)->EnvBlock
696 /* Check if this is an EXE file or a COM file */
697 if (Address
[0] == 'M' && Address
[1] == 'Z')
701 /* Get the MZ header */
702 Header
= (PIMAGE_DOS_HEADER
)Address
;
704 // TODO: Verify checksum and executable!
706 /* Get the base size of the file, in paragraphs (rounded up) */
707 ExeSize
= (((Header
->e_cp
- 1) * 512) + Header
->e_cblp
+ 0x0F) >> 4;
709 /* Add the PSP size, in paragraphs */
710 ExeSize
+= sizeof(DOS_PSP
) >> 4;
712 /* Add the maximum size that should be allocated */
713 ExeSize
+= Header
->e_maxalloc
;
715 /* Make sure it does not pass 0xFFFF */
716 if (ExeSize
> 0xFFFF) ExeSize
= 0xFFFF;
718 /* Reduce the size one by one until the allocation is successful */
719 for (i
= Header
->e_maxalloc
; i
>= Header
->e_minalloc
; i
--, ExeSize
--)
721 /* Try to allocate that much memory */
722 Segment
= DosAllocateMemory(ExeSize
, NULL
);
723 if (Segment
!= 0) break;
726 /* Check if at least the lowest allocation was successful */
727 if (Segment
== 0) goto Cleanup
;
729 /* Initialize the PSP */
730 DosInitializePsp(Segment
,
735 /* The process owns its own memory */
736 DosChangeMemoryOwner(Segment
, Segment
);
737 DosChangeMemoryOwner(EnvBlock
, Segment
);
739 /* Copy the program to Segment:0100 */
740 RtlCopyMemory((PVOID
)((ULONG_PTR
)BaseAddress
741 + TO_LINEAR(Segment
, 0x100)),
742 Address
+ (Header
->e_cparhdr
<< 4),
743 FileSize
- (Header
->e_cparhdr
<< 4));
745 /* Get the relocation table */
746 RelocationTable
= (PDWORD
)(Address
+ Header
->e_lfarlc
);
748 /* Perform relocations */
749 for (i
= 0; i
< Header
->e_crlc
; i
++)
751 /* Get a pointer to the word that needs to be patched */
752 RelocWord
= (PWORD
)((ULONG_PTR
)BaseAddress
753 + TO_LINEAR(Segment
+ HIWORD(RelocationTable
[i
]),
754 0x100 + LOWORD(RelocationTable
[i
])));
756 /* Add the number of the EXE segment to it */
757 *RelocWord
+= Segment
+ (sizeof(DOS_PSP
) >> 4);
760 /* Set the initial segment registers */
761 EmulatorSetRegister(EMULATOR_REG_DS
, Segment
);
762 EmulatorSetRegister(EMULATOR_REG_ES
, Segment
);
764 /* Set the stack to the location from the header */
765 EmulatorSetStack(Segment
+ (sizeof(DOS_PSP
) >> 4) + Header
->e_ss
,
769 CurrentPsp
= Segment
;
770 DiskTransferArea
= MAKELONG(0x80, Segment
);
771 EmulatorExecute(Segment
+ Header
->e_cs
+ (sizeof(DOS_PSP
) >> 4),
780 /* Allocate memory for the whole program and the PSP */
781 Segment
= DosAllocateMemory((FileSize
+ sizeof(DOS_PSP
)) >> 4, NULL
);
782 if (Segment
== 0) goto Cleanup
;
784 /* Copy the program to Segment:0100 */
785 RtlCopyMemory((PVOID
)((ULONG_PTR
)BaseAddress
786 + TO_LINEAR(Segment
, 0x100)),
790 /* Initialize the PSP */
791 DosInitializePsp(Segment
,
793 (FileSize
+ sizeof(DOS_PSP
)) >> 4,
796 /* Set the initial segment registers */
797 EmulatorSetRegister(EMULATOR_REG_DS
, Segment
);
798 EmulatorSetRegister(EMULATOR_REG_ES
, Segment
);
800 /* Set the stack to the last word of the segment */
801 EmulatorSetStack(Segment
, 0xFFFE);
804 CurrentPsp
= Segment
;
805 DiskTransferArea
= MAKELONG(0x80, Segment
);
806 EmulatorExecute(Segment
, 0x100);
814 /* It was not successful, cleanup the DOS memory */
815 if (AllocatedEnvBlock
) DosFreeMemory(EnvBlock
);
816 if (Segment
) DosFreeMemory(Segment
);
820 if (Address
!= NULL
) UnmapViewOfFile(Address
);
822 /* Close the file mapping object */
823 if (FileMapping
!= NULL
) CloseHandle(FileMapping
);
825 /* Close the file handle */
826 if (FileHandle
!= INVALID_HANDLE_VALUE
) CloseHandle(FileHandle
);
831 VOID
DosTerminateProcess(WORD Psp
, BYTE ReturnCode
)
833 WORD McbSegment
= FIRST_MCB_SEGMENT
;
835 LPDWORD IntVecTable
= (LPDWORD
)((ULONG_PTR
)BaseAddress
);
836 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(Psp
);
838 /* Check if this PSP is it's own parent */
839 if (PspBlock
->ParentPsp
== Psp
) goto Done
;
841 // TODO: Close all handles opened by the process
843 /* Free the memory used by the process */
846 /* Get a pointer to the MCB */
847 CurrentMcb
= SEGMENT_TO_MCB(McbSegment
);
849 /* Make sure the MCB is valid */
850 if (CurrentMcb
->BlockType
!= 'M' && CurrentMcb
->BlockType
!='Z') break;
852 /* If this block was allocated by the process, free it */
853 if (CurrentMcb
->OwnerPsp
== Psp
) DosFreeMemory(McbSegment
);
855 /* If this was the last block, quit */
856 if (CurrentMcb
->BlockType
== 'Z') break;
858 /* Update the segment and continue */
859 McbSegment
+= CurrentMcb
->Size
+ 1;
863 /* Restore the interrupt vectors */
864 IntVecTable
[0x22] = PspBlock
->TerminateAddress
;
865 IntVecTable
[0x23] = PspBlock
->BreakAddress
;
866 IntVecTable
[0x24] = PspBlock
->CriticalAddress
;
868 /* Update the current PSP */
869 if (Psp
== CurrentPsp
)
871 CurrentPsp
= PspBlock
->ParentPsp
;
872 if (CurrentPsp
== SYSTEM_PSP
) VdmRunning
= FALSE
;
875 /* Return control to the parent process */
876 EmulatorExecute(HIWORD(PspBlock
->TerminateAddress
),
877 LOWORD(PspBlock
->TerminateAddress
));
880 CHAR
DosReadCharacter()
882 CHAR Character
= '\0';
885 /* Use the file reading function */
886 DosReadFile(DOS_INPUT_HANDLE
, &Character
, sizeof(CHAR
), &BytesRead
);
891 VOID
DosPrintCharacter(CHAR Character
)
895 /* Use the file writing function */
896 DosWriteFile(DOS_OUTPUT_HANDLE
, &Character
, sizeof(CHAR
), &BytesWritten
);
899 VOID
DosInt20h(WORD CodeSegment
)
901 /* This is the exit interrupt */
902 DosTerminateProcess(CodeSegment
, 0);
905 VOID
DosInt21h(WORD CodeSegment
)
909 SYSTEMTIME SystemTime
;
911 PDOS_INPUT_BUFFER InputBuffer
;
912 DWORD Eax
= EmulatorGetRegister(EMULATOR_REG_AX
);
913 DWORD Ecx
= EmulatorGetRegister(EMULATOR_REG_CX
);
914 DWORD Edx
= EmulatorGetRegister(EMULATOR_REG_DX
);
915 DWORD Ebx
= EmulatorGetRegister(EMULATOR_REG_BX
);
916 WORD DataSegment
= EmulatorGetRegister(EMULATOR_REG_DS
);
917 WORD ExtSegment
= EmulatorGetRegister(EMULATOR_REG_ES
);
919 /* Check the value in the AH register */
922 /* Terminate Program */
925 DosTerminateProcess(CodeSegment
, 0);
929 /* Read Character And Echo */
932 Character
= DosReadCharacter();
933 DosPrintCharacter(Character
);
934 EmulatorSetRegister(EMULATOR_REG_AX
, (Eax
& 0xFFFFFF00) | Character
);
938 /* Print Character */
941 DosPrintCharacter(LOBYTE(Edx
));
945 /* Read Character Without Echo */
949 EmulatorSetRegister(EMULATOR_REG_AX
,
950 (Eax
& 0xFFFFFF00) | DosReadCharacter());
957 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
958 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
960 while ((*String
) != '$')
962 DosPrintCharacter(*String
);
969 /* Read Buffered Input */
972 InputBuffer
= (PDOS_INPUT_BUFFER
)((ULONG_PTR
)BaseAddress
973 + TO_LINEAR(DataSegment
,
976 InputBuffer
->Length
= 0;
977 for (i
= 0; i
< InputBuffer
->MaxLength
; i
++)
979 Character
= DosReadCharacter();
980 DosPrintCharacter(Character
);
981 InputBuffer
->Buffer
[InputBuffer
->Length
] = Character
;
982 if (Character
== '\r') break;
983 InputBuffer
->Length
++;
989 /* Set Disk Transfer Area */
992 DiskTransferArea
= MAKELONG(LOWORD(Edx
), DataSegment
);
996 /* Set Interrupt Vector */
999 DWORD FarPointer
= MAKELONG(LOWORD(Edx
), DataSegment
);
1001 /* Write the new far pointer to the IDT */
1002 ((PDWORD
)BaseAddress
)[LOBYTE(Eax
)] = FarPointer
;
1007 /* Get system date */
1010 GetLocalTime(&SystemTime
);
1011 EmulatorSetRegister(EMULATOR_REG_CX
,
1012 (Ecx
& 0xFFFF0000) | SystemTime
.wYear
);
1013 EmulatorSetRegister(EMULATOR_REG_DX
,
1015 | (SystemTime
.wMonth
<< 8)
1017 EmulatorSetRegister(EMULATOR_REG_AX
,
1018 (Eax
& 0xFFFFFF00) | SystemTime
.wDayOfWeek
);
1022 /* Set system date */
1025 GetLocalTime(&SystemTime
);
1026 SystemTime
.wYear
= LOWORD(Ecx
);
1027 SystemTime
.wMonth
= HIBYTE(Edx
);
1028 SystemTime
.wDay
= LOBYTE(Edx
);
1030 if (SetLocalTime(&SystemTime
))
1032 /* Return success */
1033 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
& 0xFFFFFF00);
1037 /* Return failure */
1038 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
| 0xFF);
1044 /* Get system time */
1047 GetLocalTime(&SystemTime
);
1048 EmulatorSetRegister(EMULATOR_REG_CX
,
1050 | (SystemTime
.wHour
<< 8)
1051 | SystemTime
.wMinute
);
1052 EmulatorSetRegister(EMULATOR_REG_DX
,
1054 | (SystemTime
.wSecond
<< 8)
1055 | (SystemTime
.wMilliseconds
/ 10));
1059 /* Set system time */
1062 GetLocalTime(&SystemTime
);
1063 SystemTime
.wHour
= HIBYTE(Ecx
);
1064 SystemTime
.wMinute
= LOBYTE(Ecx
);
1065 SystemTime
.wSecond
= HIBYTE(Edx
);
1066 SystemTime
.wMilliseconds
= LOBYTE(Edx
) * 10;
1068 if (SetLocalTime(&SystemTime
))
1070 /* Return success */
1071 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
& 0xFFFFFF00);
1075 /* Return failure */
1076 EmulatorSetRegister(EMULATOR_REG_AX
, Eax
| 0xFF);
1082 /* Get Disk Transfer Area */
1085 EmulatorSetRegister(EMULATOR_REG_ES
, HIWORD(DiskTransferArea
));
1086 EmulatorSetRegister(EMULATOR_REG_BX
, LOWORD(DiskTransferArea
));
1091 /* Get DOS Version */
1094 PDOS_PSP PspBlock
= SEGMENT_TO_PSP(CurrentPsp
);
1096 EmulatorSetRegister(EMULATOR_REG_AX
, PspBlock
->DosVersion
);
1100 /* Get Interrupt Vector */
1103 DWORD FarPointer
= ((PDWORD
)BaseAddress
)[LOBYTE(Eax
)];
1105 /* Read the address from the IDT into ES:BX */
1106 EmulatorSetRegister(EMULATOR_REG_ES
, HIWORD(FarPointer
));
1107 EmulatorSetRegister(EMULATOR_REG_BX
, LOWORD(FarPointer
));
1112 /* Create Directory */
1115 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1116 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1118 if (CreateDirectoryA(String
, NULL
))
1120 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1124 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1125 EmulatorSetRegister(EMULATOR_REG_AX
,
1126 (Eax
& 0xFFFF0000) | LOWORD(GetLastError()));
1132 /* Remove Directory */
1135 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1136 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1138 if (RemoveDirectoryA(String
))
1140 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1144 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1145 EmulatorSetRegister(EMULATOR_REG_AX
,
1146 (Eax
& 0xFFFF0000) | LOWORD(GetLastError()));
1153 /* Set Current Directory */
1156 String
= (PCHAR
)((ULONG_PTR
)BaseAddress
1157 + TO_LINEAR(DataSegment
, LOWORD(Edx
)));
1159 if (SetCurrentDirectoryA(String
))
1161 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1165 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1166 EmulatorSetRegister(EMULATOR_REG_AX
,
1167 (Eax
& 0xFFFF0000) | LOWORD(GetLastError()));
1177 WORD ErrorCode
= DosCreateFile(&FileHandle
,
1178 (LPCSTR
)(ULONG_PTR
)BaseAddress
1179 + TO_LINEAR(DataSegment
, LOWORD(Edx
)),
1185 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1187 /* Return the handle in AX */
1188 EmulatorSetRegister(EMULATOR_REG_AX
,
1189 (Eax
& 0xFFFF0000) | FileHandle
);
1194 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1196 /* Return the error code in AX */
1197 EmulatorSetRegister(EMULATOR_REG_AX
,
1198 (Eax
& 0xFFFF0000) | ErrorCode
);
1208 WORD ErrorCode
= DosCreateFile(&FileHandle
,
1209 (LPCSTR
)(ULONG_PTR
)BaseAddress
1210 + TO_LINEAR(DataSegment
, LOWORD(Edx
)),
1216 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1218 /* Return the handle in AX */
1219 EmulatorSetRegister(EMULATOR_REG_AX
,
1220 (Eax
& 0xFFFF0000) | FileHandle
);
1225 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1227 /* Return the error code in AX */
1228 EmulatorSetRegister(EMULATOR_REG_AX
,
1229 (Eax
& 0xFFFF0000) | ErrorCode
);
1238 if (DosCloseHandle(LOWORD(Ebx
)))
1241 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1246 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1248 /* Return the error code in AX */
1249 EmulatorSetRegister(EMULATOR_REG_AX
,
1250 (Eax
& 0xFFFF0000) | ERROR_INVALID_PARAMETER
);
1260 WORD ErrorCode
= DosReadFile(LOWORD(Ebx
),
1261 (LPVOID
)((ULONG_PTR
)BaseAddress
1262 + TO_LINEAR(DataSegment
, LOWORD(Edx
))),
1269 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1271 /* Return the number of bytes read in AX */
1272 EmulatorSetRegister(EMULATOR_REG_AX
,
1273 (Eax
& 0xFFFF0000) | BytesRead
);
1278 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1280 /* Return the error code in AX */
1281 EmulatorSetRegister(EMULATOR_REG_AX
,
1282 (Eax
& 0xFFFF0000) | ErrorCode
);
1290 WORD BytesWritten
= 0;
1291 WORD ErrorCode
= DosWriteFile(LOWORD(Ebx
),
1292 (LPVOID
)((ULONG_PTR
)BaseAddress
1293 + TO_LINEAR(DataSegment
, LOWORD(Edx
))),
1300 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1302 /* Return the number of bytes written in AX */
1303 EmulatorSetRegister(EMULATOR_REG_AX
,
1304 (Eax
& 0xFFFF0000) | BytesWritten
);
1309 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1311 /* Return the error code in AX */
1312 EmulatorSetRegister(EMULATOR_REG_AX
,
1313 (Eax
& 0xFFFF0000) | ErrorCode
);
1319 /* Allocate Memory */
1322 WORD MaxAvailable
= 0;
1323 WORD Segment
= DosAllocateMemory(LOWORD(Ebx
), &MaxAvailable
);
1327 EmulatorSetRegister(EMULATOR_REG_AX
, Segment
);
1328 EmulatorSetRegister(EMULATOR_REG_BX
, MaxAvailable
);
1329 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1331 else EmulatorSetFlag(EMULATOR_FLAG_CF
);
1339 if (DosFreeMemory(ExtSegment
))
1341 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1343 else EmulatorSetFlag(EMULATOR_FLAG_CF
);
1348 /* Resize Memory Block */
1353 if (DosResizeMemory(ExtSegment
, LOWORD(Ebx
), &Size
))
1355 EmulatorClearFlag(EMULATOR_FLAG_CF
);
1359 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1360 EmulatorSetRegister(EMULATOR_REG_BX
, Size
);
1366 /* Terminate With Return Code */
1369 DosTerminateProcess(CurrentPsp
, LOBYTE(Eax
));
1376 DPRINT1("DOS Function INT 0x21, AH = 0x%02X NOT IMPLEMENTED!\n", HIBYTE(Eax
));
1377 EmulatorSetFlag(EMULATOR_FLAG_CF
);
1382 VOID
DosBreakInterrupt()
1387 BOOLEAN
DosInitialize()
1390 PDOS_MCB Mcb
= SEGMENT_TO_MCB(FIRST_MCB_SEGMENT
);
1393 LPWSTR SourcePtr
, Environment
;
1395 LPSTR DestPtr
= (LPSTR
)((ULONG_PTR
)BaseAddress
+ TO_LINEAR(SYSTEM_ENV_BLOCK
, 0));
1398 /* Initialize the MCB */
1399 Mcb
->BlockType
= 'Z';
1400 Mcb
->Size
= USER_MEMORY_SIZE
;
1403 /* Get the environment strings */
1404 SourcePtr
= Environment
= GetEnvironmentStringsW();
1405 if (Environment
== NULL
) return FALSE
;
1407 /* Fill the DOS system environment block */
1410 /* Get the size of the ASCII string */
1411 AsciiSize
= WideCharToMultiByte(CP_ACP
,
1420 /* Allocate memory for the ASCII string */
1421 AsciiString
= HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY
, AsciiSize
);
1422 if (AsciiString
== NULL
)
1424 FreeEnvironmentStringsW(Environment
);
1428 /* Convert to ASCII */
1429 WideCharToMultiByte(CP_ACP
,
1438 /* Copy the string into DOS memory */
1439 strcpy(DestPtr
, AsciiString
);
1441 /* Free the memory */
1442 HeapFree(GetProcessHeap(), 0, AsciiString
);
1444 /* Move to the next string */
1445 SourcePtr
+= wcslen(SourcePtr
) + 1;
1446 DestPtr
+= strlen(AsciiString
);
1451 /* Free the memory allocated for environment strings */
1452 FreeEnvironmentStringsW(Environment
);
1454 /* Read CONFIG.SYS */
1455 Stream
= _wfopen(DOS_CONFIG_PATH
, L
"r");
1458 while (fgetws(Buffer
, 256, Stream
))
1460 // TODO: Parse the line
1465 /* Initialize the SFT */
1466 for (i
= 0; i
< DOS_SFT_SIZE
; i
++)
1468 DosSystemFileTable
[i
] = INVALID_HANDLE_VALUE
;
1469 DosSftRefCount
[i
] = 0;
1472 /* Get handles to standard I/O devices */
1473 DosSystemFileTable
[0] = GetStdHandle(STD_INPUT_HANDLE
);
1474 DosSystemFileTable
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
1475 DosSystemFileTable
[2] = GetStdHandle(STD_ERROR_HANDLE
);