krnl386.exe: Fix last error check for DOS compatibility hack.
[wine.git] / dlls / krnl386.exe16 / int21.c
blobf32c3a41fc8e04f1f94d318355ae3e05279ad10e
1 /*
2 * DOS interrupt 21h handler
4 * Copyright 1993, 1994 Erik Bos
5 * Copyright 1996 Alexandre Julliard
6 * Copyright 1997 Andreas Mohr
7 * Copyright 1998 Uwe Bonnes
8 * Copyright 1998, 1999 Ove Kaaven
9 * Copyright 2003 Thomas Mertes
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "config.h"
27 #include "wine/port.h"
29 #include <stdarg.h>
30 #include <stdio.h>
31 #ifdef HAVE_SYS_STAT_H
32 # include <sys/stat.h>
33 #endif
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
38 #include "windef.h"
39 #include "winbase.h"
40 #include "winreg.h"
41 #include "winternl.h"
42 #include "wine/winbase16.h"
43 #include "kernel16_private.h"
44 #include "dosexe.h"
45 #include "winerror.h"
46 #include "winuser.h"
47 #include "wine/unicode.h"
48 #include "wine/server.h"
49 #include "wine/debug.h"
50 #include "wine/exception.h"
52 BOOL WINAPI VerifyConsoleIoHandle(HANDLE);
54 * Note:
55 * - Most of the file related functions are wrong. NT's kernel32
56 * doesn't maintain a per drive current directory, while DOS does.
57 * We should in fact keep track in here of those per drive
58 * directories, and use this info while dealing with partial paths
59 * (drive defined, but only relative paths). This could even be
60 * created as an array of CDS (there should be an entry for that in
61 * the LOL)
65 * Forward declarations.
67 static BOOL INT21_RenameFile( CONTEXT86 *context );
69 WINE_DEFAULT_DEBUG_CHANNEL(int21);
72 #include "pshpack1.h"
75 * Extended Drive Parameter Block.
76 * This structure is compatible with standard DOS4+ DPB and
77 * extended DOS7 DPB.
79 typedef struct _INT21_DPB {
80 BYTE drive; /* 00 drive number (0=A, ...) */
81 BYTE unit; /* 01 unit number within device driver */
82 WORD sector_bytes; /* 02 bytes per sector */
83 BYTE cluster_sectors; /* 04 highest sector number within a cluster */
84 BYTE shift; /* 05 shift count to convert clusters into sectors */
85 WORD num_reserved; /* 06 reserved sectors at beginning of drive */
86 BYTE num_FAT; /* 08 number of FATs */
87 WORD num_root_entries; /* 09 number of root directory entries */
88 WORD first_data_sector; /* 0b number of first sector containing user data */
89 WORD num_clusters1; /* 0d highest cluster number (number of data clusters + 1) */
90 WORD sectors_per_FAT; /* 0f number of sectors per FAT */
91 WORD first_dir_sector; /* 11 sector number of first directory sector */
92 SEGPTR driver_header; /* 13 address of device driver header */
93 BYTE media_ID; /* 17 media ID byte */
94 BYTE access_flag; /* 18 0x00 if disk accessed, 0xff if not */
95 SEGPTR next; /* 19 pointer to next DPB */
96 WORD search_cluster1; /* 1d cluster at which to start search for free space */
97 WORD free_clusters_lo; /* 1f number of free clusters on drive or 0xffff if unknown */
98 WORD free_clusters_hi; /* 21 hiword of clusters_free */
99 WORD mirroring_flags; /* 23 active FAT/mirroring flags */
100 WORD info_sector; /* 25 sector number of file system info sector or 0xffff for none */
101 WORD spare_boot_sector; /* 27 sector number of backup boot sector or 0xffff for none */
102 DWORD first_cluster_sector; /* 29 sector number of the first cluster */
103 DWORD num_clusters2; /* 2d maximum cluster number */
104 DWORD fat_clusters; /* 31 number of clusters occupied by FAT */
105 DWORD root_cluster; /* 35 cluster number of start of root directory */
106 DWORD search_cluster2; /* 39 cluster at which to start searching for free space */
107 } INT21_DPB;
111 * Structure for DOS data that can be accessed directly from applications.
112 * Real and protected mode pointers will be returned to this structure so
113 * the structure must be correctly packed.
115 typedef struct _INT21_HEAP {
116 WORD uppercase_size; /* Size of the following table in bytes */
117 BYTE uppercase_table[128]; /* Uppercase equivalents of chars from 0x80 to 0xff. */
119 WORD lowercase_size; /* Size of the following table in bytes */
120 BYTE lowercase_table[256]; /* Lowercase equivalents of chars from 0x00 to 0xff. */
122 WORD collating_size; /* Size of the following table in bytes */
123 BYTE collating_table[256]; /* Values used to sort characters from 0x00 to 0xff. */
125 WORD filename_size; /* Size of the following filename data in bytes */
126 BYTE filename_reserved1; /* 0x01 for MS-DOS 3.30-6.00 */
127 BYTE filename_lowest; /* Lowest permissible character value for filename */
128 BYTE filename_highest; /* Highest permissible character value for filename */
129 BYTE filename_reserved2; /* 0x00 for MS-DOS 3.30-6.00 */
130 BYTE filename_exclude_first; /* First illegal character in permissible range */
131 BYTE filename_exclude_last; /* Last illegal character in permissible range */
132 BYTE filename_reserved3; /* 0x02 for MS-DOS 3.30-6.00 */
133 BYTE filename_illegal_size; /* Number of terminators in the following table */
134 BYTE filename_illegal_table[16]; /* Characters which terminate a filename */
136 WORD dbcs_size; /* Number of valid ranges in the following table */
137 BYTE dbcs_table[16]; /* Start/end bytes for N ranges and 00/00 as terminator */
139 BYTE misc_indos; /* Interrupt 21 nesting flag */
140 WORD misc_segment; /* Real mode segment for INT21_HEAP */
141 WORD misc_selector; /* Protected mode selector for INT21_HEAP */
142 INT21_DPB misc_dpb_list[MAX_DOS_DRIVES]; /* Drive parameter blocks for all drives */
144 } INT21_HEAP;
147 struct FCB {
148 BYTE drive_number;
149 CHAR file_name[8];
150 CHAR file_extension[3];
151 WORD current_block_number;
152 WORD logical_record_size;
153 DWORD file_size;
154 WORD date_of_last_write;
155 WORD time_of_last_write;
156 BYTE file_number;
157 BYTE attributes;
158 WORD starting_cluster;
159 WORD sequence_number;
160 BYTE file_attributes;
161 BYTE unused;
162 BYTE record_within_current_block;
163 BYTE random_access_record_number[4];
167 struct XFCB {
168 BYTE xfcb_signature;
169 BYTE reserved[5];
170 BYTE xfcb_file_attribute;
171 BYTE fcb[37];
174 /* DTA layout for FindFirst/FindNext */
175 typedef struct
177 BYTE drive; /* 00 drive letter */
178 char mask[11]; /* 01 search template */
179 BYTE search_attr; /* 0c search attributes */
180 WORD count; /* 0d entry count within directory */
181 WORD cluster; /* 0f cluster of parent directory */
182 WCHAR *fullPath; /* 11 full path (was: reserved) */
183 BYTE fileattr; /* 15 file attributes */
184 WORD filetime; /* 16 file time */
185 WORD filedate; /* 18 file date */
186 DWORD filesize; /* 1a file size */
187 char filename[13]; /* 1e file name + extension */
188 } FINDFILE_DTA;
190 /* FCB layout for FindFirstFCB/FindNextFCB */
191 typedef struct
193 BYTE drive; /* 00 drive letter */
194 char filename[11]; /* 01 filename 8+3 format */
195 int count; /* 0c entry count (was: reserved) */
196 WCHAR *fullPath; /* 10 full path (was: reserved) */
197 } FINDFILE_FCB;
199 /* DOS directory entry for FindFirstFCB/FindNextFCB */
200 typedef struct
202 char filename[11]; /* 00 filename 8+3 format */
203 BYTE fileattr; /* 0b file attributes */
204 BYTE reserved[10]; /* 0c reserved */
205 WORD filetime; /* 16 file time */
206 WORD filedate; /* 18 file date */
207 WORD cluster; /* 1a file first cluster */
208 DWORD filesize; /* 1c file size */
209 } DOS_DIRENTRY_LAYOUT;
211 #include "poppack.h"
213 /* dos file attributes */
214 #define FA_NORMAL 0x00 /* Normal file, no attributes */
215 #define FA_RDONLY 0x01 /* Read only attribute */
216 #define FA_HIDDEN 0x02 /* Hidden file */
217 #define FA_SYSTEM 0x04 /* System file */
218 #define FA_LABEL 0x08 /* Volume label */
219 #define FA_DIRECTORY 0x10 /* Directory */
220 #define FA_ARCHIVE 0x20 /* Archive */
221 #define FA_UNUSED 0x40 /* Unused */
223 /* Error codes */
224 #define ER_NoNetwork 0x49
226 /* Error classes */
227 #define EC_OutOfResource 0x01
228 #define EC_Temporary 0x02
229 #define EC_AccessDenied 0x03
230 #define EC_InternalError 0x04
231 #define EC_HardwareFailure 0x05
232 #define EC_SystemFailure 0x06
233 #define EC_ProgramError 0x07
234 #define EC_NotFound 0x08
235 #define EC_MediaError 0x0b
236 #define EC_Exists 0x0c
237 #define EC_Unknown 0x0d
239 /* Suggested actions */
240 #define SA_Retry 0x01
241 #define SA_DelayedRetry 0x02
242 #define SA_Abort 0x04
243 #define SA_Ignore 0x06
244 #define SA_Ask4Retry 0x07
246 /* Error locus */
247 #define EL_Unknown 0x01
248 #define EL_Disk 0x02
249 #define EL_Network 0x03
250 #define EL_Serial 0x04
251 #define EL_Memory 0x05
253 /* BIOS Keyboard Scancodes */
254 #define KEY_LEFT 0x4B
255 #define KEY_RIGHT 0x4D
256 #define KEY_UP 0x48
257 #define KEY_DOWN 0x50
258 #define KEY_IC 0x52 /* insert char */
259 #define KEY_DC 0x53 /* delete char */
260 #define KEY_BACKSPACE 0x0E
261 #define KEY_HOME 0x47
262 #define KEY_END 0x4F
263 #define KEY_NPAGE 0x49
264 #define KEY_PPAGE 0x51
267 struct magic_device
269 WCHAR name[10];
270 HANDLE handle;
271 LARGE_INTEGER index;
272 void (*ioctl_handler)(CONTEXT86 *);
275 static void INT21_IoctlScsiMgrHandler( CONTEXT86 * );
276 static void INT21_IoctlHPScanHandler( CONTEXT86 * );
278 static struct magic_device magic_devices[] =
280 { {'s','c','s','i','m','g','r','$',0}, NULL, { { 0, 0 } }, INT21_IoctlScsiMgrHandler },
281 { {'e','m','m','x','x','x','x','0',0}, NULL, { { 0, 0 } }, EMS_Ioctl_Handler },
282 { {'h','p','s','c','a','n',0}, NULL, { { 0, 0 } }, INT21_IoctlHPScanHandler },
285 #define NB_MAGIC_DEVICES (sizeof(magic_devices)/sizeof(magic_devices[0]))
288 /* Many calls translate a drive argument like this:
289 drive number (00h = default, 01h = A:, etc)
291 /******************************************************************
292 * INT21_DriveName
294 * Many calls translate a drive argument like this:
295 * drive number (00h = default, 01h = A:, etc)
297 static const char *INT21_DriveName(int drive)
299 if (drive > 0)
301 if (drive <= 26) return wine_dbg_sprintf("%c:", 'A' + drive - 1);
302 else return wine_dbg_sprintf( "<Bad drive: %d>", drive);
304 return "default";
307 /***********************************************************************
308 * INT21_GetCurrentDrive
310 * Return current drive using scheme (0=A:, 1=B:, 2=C:, ...) or
311 * MAX_DOS_DRIVES on error.
313 static BYTE INT21_GetCurrentDrive(void)
315 WCHAR current_directory[MAX_PATH];
317 if (!GetCurrentDirectoryW( MAX_PATH, current_directory ) ||
318 current_directory[1] != ':')
320 TRACE( "Failed to get current drive.\n" );
321 return MAX_DOS_DRIVES;
324 return toupperW( current_directory[0] ) - 'A';
328 /***********************************************************************
329 * INT21_MapDrive
331 * Convert drive number from scheme (0=default, 1=A:, 2=B:, ...) into
332 * scheme (0=A:, 1=B:, 2=C:, ...) or MAX_DOS_DRIVES on error.
334 static BYTE INT21_MapDrive( BYTE drive )
336 if (drive)
338 WCHAR drivespec[3] = {'A', ':', 0};
339 UINT drivetype;
341 drivespec[0] += drive - 1;
342 drivetype = GetDriveTypeW( drivespec );
344 if (drivetype == DRIVE_UNKNOWN || drivetype == DRIVE_NO_ROOT_DIR)
345 return MAX_DOS_DRIVES;
347 return drive - 1;
350 return INT21_GetCurrentDrive();
354 /***********************************************************************
355 * INT21_SetCurrentDrive
357 * Set current drive. Uses scheme (0=A:, 1=B:, 2=C:, ...).
359 static void INT21_SetCurrentDrive( BYTE drive )
361 WCHAR drivespec[3] = {'A', ':', 0};
363 drivespec[0] += drive;
365 if (!SetCurrentDirectoryW( drivespec ))
366 TRACE( "Failed to set current drive.\n" );
370 /***********************************************************************
371 * INT21_ReadChar
373 * Reads a character from the standard input.
374 * Extended keycodes will be returned as two separate characters.
376 static BOOL INT21_ReadChar( BYTE *input, CONTEXT86 *waitctx )
378 static BYTE pending_scan = 0;
380 if (pending_scan)
382 if (input)
383 *input = pending_scan;
384 if (waitctx)
385 pending_scan = 0;
386 return TRUE;
388 else
390 BYTE ascii;
391 BYTE scan;
392 if (!DOSVM_Int16ReadChar( &ascii, &scan, waitctx ))
393 return FALSE;
395 if (input)
396 *input = ascii;
397 if (waitctx && !ascii)
398 pending_scan = scan;
399 return TRUE;
404 /***********************************************************************
405 * INT21_GetSystemCountryCode
407 * Return DOS country code for default system locale.
409 static WORD INT21_GetSystemCountryCode( void )
412 * FIXME: Determine country code. We should probably use
413 * DOSCONF structure for that.
415 return GetSystemDefaultLangID();
419 /***********************************************************************
420 * INT21_FillCountryInformation
422 * Fill 34-byte buffer with country information data using
423 * default system locale.
425 static void INT21_FillCountryInformation( BYTE *buffer )
427 /* 00 - WORD: date format
428 * 00 = mm/dd/yy
429 * 01 = dd/mm/yy
430 * 02 = yy/mm/dd
432 *(WORD*)(buffer + 0) = 0; /* FIXME: Get from locale */
434 /* 02 - BYTE[5]: ASCIIZ currency symbol string */
435 buffer[2] = '$'; /* FIXME: Get from locale */
436 buffer[3] = 0;
438 /* 07 - BYTE[2]: ASCIIZ thousands separator */
439 buffer[7] = 0; /* FIXME: Get from locale */
440 buffer[8] = 0;
442 /* 09 - BYTE[2]: ASCIIZ decimal separator */
443 buffer[9] = '.'; /* FIXME: Get from locale */
444 buffer[10] = 0;
446 /* 11 - BYTE[2]: ASCIIZ date separator */
447 buffer[11] = '/'; /* FIXME: Get from locale */
448 buffer[12] = 0;
450 /* 13 - BYTE[2]: ASCIIZ time separator */
451 buffer[13] = ':'; /* FIXME: Get from locale */
452 buffer[14] = 0;
454 /* 15 - BYTE: Currency format
455 * bit 2 = set if currency symbol replaces decimal point
456 * bit 1 = number of spaces between value and currency symbol
457 * bit 0 = 0 if currency symbol precedes value
458 * 1 if currency symbol follows value
460 buffer[15] = 0; /* FIXME: Get from locale */
462 /* 16 - BYTE: Number of digits after decimal in currency */
463 buffer[16] = 0; /* FIXME: Get from locale */
465 /* 17 - BYTE: Time format
466 * bit 0 = 0 if 12-hour clock
467 * 1 if 24-hour clock
469 buffer[17] = 1; /* FIXME: Get from locale */
471 /* 18 - DWORD: Address of case map routine */
472 *(DWORD*)(buffer + 18) = 0; /* FIXME: ptr to case map routine */
474 /* 22 - BYTE[2]: ASCIIZ data-list separator */
475 buffer[22] = ','; /* FIXME: Get from locale */
476 buffer[23] = 0;
478 /* 24 - BYTE[10]: Reserved */
479 memset( buffer + 24, 0, 10 );
483 /***********************************************************************
484 * INT21_FillHeap
486 * Initialize DOS heap.
488 * Filename Terminator Table of w2k DE NTVDM:
489 * 16 00 01 00 FF 00 00 20-02 0E 2E 22 2F 5C 5B 5D ....... ..."/\[]
490 * 3A 7C 3C 3E 2B 3D 3B 2C-00 :|<>+=;,
492 static void INT21_FillHeap( INT21_HEAP *heap )
494 static const char terminators[] = ".\"/\\[]:|<>+=;,";
495 int i;
498 * Uppercase table.
500 heap->uppercase_size = 128;
501 for (i = 0; i < 128; i++)
502 heap->uppercase_table[i] = toupper( 128 + i );
505 * Lowercase table.
507 heap->lowercase_size = 256;
508 for (i = 0; i < 256; i++)
509 heap->lowercase_table[i] = tolower( i );
512 * Collating table.
514 heap->collating_size = 256;
515 for (i = 0; i < 256; i++)
516 heap->collating_table[i] = i;
519 * Filename table.
521 heap->filename_size = 8 + strlen(terminators);
522 heap->filename_illegal_size = strlen(terminators);
523 memcpy( heap->filename_illegal_table, terminators, heap->filename_illegal_size );
525 heap->filename_reserved1 = 0x01;
526 heap->filename_lowest = 0x00;
527 heap->filename_highest = 0xff;
528 heap->filename_reserved2 = 0x00;
529 heap->filename_exclude_first = 0x00;
530 heap->filename_exclude_last = 0x20;
531 heap->filename_reserved3 = 0x02;
534 * DBCS lead byte table. This table is empty.
536 heap->dbcs_size = 0;
537 memset( heap->dbcs_table, 0, sizeof(heap->dbcs_table) );
540 * Initialize InDos flag.
542 heap->misc_indos = 0;
545 * FIXME: Should drive parameter blocks (DPB) be
546 * initialized here and linked to DOS LOL?
551 /***********************************************************************
552 * INT21_GetHeapPointer
554 * Get pointer for DOS heap (INT21_HEAP).
555 * Creates and initializes heap on first call.
557 static INT21_HEAP *INT21_GetHeapPointer( void )
559 static INT21_HEAP *heap_pointer = NULL;
561 if (!heap_pointer)
563 WORD heap_segment;
564 WORD heap_selector;
566 heap_pointer = DOSVM_AllocDataUMB( sizeof(INT21_HEAP),
567 &heap_segment,
568 &heap_selector );
570 heap_pointer->misc_segment = heap_segment;
571 heap_pointer->misc_selector = heap_selector;
572 INT21_FillHeap( heap_pointer );
575 return heap_pointer;
579 /***********************************************************************
580 * INT21_GetHeapSelector
582 * Get segment/selector for DOS heap (INT21_HEAP).
583 * Creates and initializes heap on first call.
585 static WORD INT21_GetHeapSelector( CONTEXT86 *context )
587 INT21_HEAP *heap = INT21_GetHeapPointer();
589 if (!ISV86(context) && DOSVM_IsWin16())
590 return heap->misc_selector;
591 else
592 return heap->misc_segment;
596 /***********************************************************************
597 * INT21_FillDrivePB
599 * Fill DOS heap drive parameter block for the specified drive.
600 * Return TRUE if drive was valid and there were
601 * no errors while reading drive information.
603 static BOOL INT21_FillDrivePB( BYTE drive )
605 WCHAR drivespec[3] = {'A', ':', 0};
606 INT21_HEAP *heap = INT21_GetHeapPointer();
607 INT21_DPB *dpb;
608 UINT drivetype;
609 DWORD cluster_sectors;
610 DWORD sector_bytes;
611 DWORD free_clusters;
612 DWORD total_clusters;
614 if (drive >= MAX_DOS_DRIVES)
615 return FALSE;
617 dpb = &heap->misc_dpb_list[drive];
618 drivespec[0] += drive;
619 drivetype = GetDriveTypeW( drivespec );
622 * FIXME: Does this check work correctly with floppy/cdrom drives?
624 if (drivetype == DRIVE_NO_ROOT_DIR || drivetype == DRIVE_UNKNOWN)
625 return FALSE;
628 * FIXME: Does this check work correctly with floppy/cdrom drives?
630 if (!GetDiskFreeSpaceW( drivespec, &cluster_sectors, &sector_bytes,
631 &free_clusters, &total_clusters ))
632 return FALSE;
635 * FIXME: Most of the values listed below are incorrect.
636 * All values should be validated.
639 dpb->drive = drive;
640 dpb->unit = 0;
641 dpb->sector_bytes = sector_bytes;
642 dpb->cluster_sectors = cluster_sectors - 1;
644 dpb->shift = 0;
645 while (cluster_sectors > 1)
647 cluster_sectors /= 2;
648 dpb->shift++;
651 dpb->num_reserved = 0;
652 dpb->num_FAT = 1;
653 dpb->num_root_entries = 2;
654 dpb->first_data_sector = 2;
655 dpb->num_clusters1 = total_clusters;
656 dpb->sectors_per_FAT = 1;
657 dpb->first_dir_sector = 1;
658 dpb->driver_header = 0;
659 dpb->media_ID = (drivetype == DRIVE_FIXED) ? 0xF8 : 0xF0;
660 dpb->access_flag = 0;
661 dpb->next = 0;
662 dpb->search_cluster1 = 0;
663 dpb->free_clusters_lo = LOWORD(free_clusters);
664 dpb->free_clusters_hi = HIWORD(free_clusters);
665 dpb->mirroring_flags = 0;
666 dpb->info_sector = 0xffff;
667 dpb->spare_boot_sector = 0xffff;
668 dpb->first_cluster_sector = 0;
669 dpb->num_clusters2 = total_clusters;
670 dpb->fat_clusters = 32;
671 dpb->root_cluster = 0;
672 dpb->search_cluster2 = 0;
674 return TRUE;
678 /***********************************************************************
679 * INT21_GetCurrentDirectory
681 * Handler for:
682 * - function 0x47
683 * - subfunction 0x47 of function 0x71
685 static BOOL INT21_GetCurrentDirectory( CONTEXT86 *context, BOOL islong )
687 char *buffer = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi);
688 BYTE drive = INT21_MapDrive( DL_reg(context) );
689 WCHAR pathW[MAX_PATH];
690 char pathA[MAX_PATH];
691 WCHAR *ptr = pathW;
693 TRACE( "drive %d\n", DL_reg(context) );
695 if (drive == MAX_DOS_DRIVES)
697 SetLastError(ERROR_INVALID_DRIVE);
698 return FALSE;
702 * Grab current directory.
705 if (!GetCurrentDirectoryW( MAX_PATH, pathW )) return FALSE;
707 if (toupperW(pathW[0]) - 'A' != drive || pathW[1] != ':')
709 /* cwd is not on the requested drive, get the environment string instead */
711 WCHAR env_var[4];
713 env_var[0] = '=';
714 env_var[1] = 'A' + drive;
715 env_var[2] = ':';
716 env_var[3] = 0;
717 if (!GetEnvironmentVariableW( env_var, pathW, MAX_PATH ))
719 /* return empty path */
720 buffer[0] = 0;
721 return TRUE;
726 * Convert into short format.
729 if (!islong)
731 DWORD result = GetShortPathNameW( pathW, pathW, MAX_PATH );
732 if (!result)
733 return FALSE;
734 if (result > MAX_PATH)
736 WARN( "Short path too long!\n" );
737 SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
738 return FALSE;
743 * The returned pathname does not include
744 * the drive letter, colon or leading backslash.
747 if (ptr[0] == '\\')
750 * FIXME: We should probably just strip host part from name...
752 FIXME( "UNC names are not supported.\n" );
753 SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
754 return FALSE;
756 else if (!ptr[0] || ptr[1] != ':' || ptr[2] != '\\')
758 WARN( "Path is neither UNC nor DOS path: %s\n",
759 wine_dbgstr_w(ptr) );
760 SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
761 return FALSE;
763 else
765 /* Remove drive letter, colon and leading backslash. */
766 ptr += 3;
770 * Convert into OEM string.
773 if (!WideCharToMultiByte(CP_OEMCP, 0, ptr, -1, pathA,
774 MAX_PATH, NULL, NULL))
776 WARN( "Cannot convert path!\n" );
777 SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
778 return FALSE;
782 * Success.
785 if (!islong)
787 /* Undocumented success code. */
788 SET_AX( context, 0x0100 );
790 /* Truncate buffer to 64 bytes. */
791 pathA[63] = 0;
794 TRACE( "%c:=%s\n", 'A' + drive, pathA );
796 strcpy( buffer, pathA );
797 return TRUE;
801 /***********************************************************************
802 * INT21_SetCurrentDirectory
804 * Handler for:
805 * - function 0x3b
806 * - subfunction 0x3b of function 0x71
808 static BOOL INT21_SetCurrentDirectory( CONTEXT86 *context )
810 WCHAR dirW[MAX_PATH];
811 WCHAR env_var[4];
812 DWORD attr;
813 char *dirA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
814 BYTE drive = INT21_GetCurrentDrive();
815 BOOL result;
817 TRACE( "SET CURRENT DIRECTORY %s\n", dirA );
819 MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
820 if (!GetFullPathNameW( dirW, MAX_PATH, dirW, NULL )) return FALSE;
822 attr = GetFileAttributesW( dirW );
823 if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
825 SetLastError( ERROR_PATH_NOT_FOUND );
826 return FALSE;
829 env_var[0] = '=';
830 env_var[1] = dirW[0];
831 env_var[2] = ':';
832 env_var[3] = 0;
833 result = SetEnvironmentVariableW( env_var, dirW );
835 /* only set current directory if on the current drive */
836 if (result && (toupperW(dirW[0]) - 'A' == drive)) result = SetCurrentDirectoryW( dirW );
838 return result;
841 /***********************************************************************
842 * INT21_CreateMagicDeviceHandle
844 * Create a dummy file handle for a "magic" device.
846 static HANDLE INT21_CreateMagicDeviceHandle( LPCWSTR name )
848 static const WCHAR prefixW[] = {'\\','?','?','\\','u','n','i','x'};
849 const char *dir = wine_get_server_dir();
850 int len;
851 HANDLE ret;
852 NTSTATUS status;
853 OBJECT_ATTRIBUTES attr;
854 UNICODE_STRING nameW;
855 IO_STATUS_BLOCK io;
857 len = MultiByteToWideChar( CP_UNIXCP, 0, dir, -1, NULL, 0 );
858 nameW.Length = sizeof(prefixW) + (len + strlenW( name )) * sizeof(WCHAR);
859 nameW.MaximumLength = nameW.Length + sizeof(WCHAR);
860 if (!(nameW.Buffer = HeapAlloc( GetProcessHeap(), 0, nameW.MaximumLength )))
862 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
863 return 0;
865 memcpy( nameW.Buffer, prefixW, sizeof(prefixW) );
866 MultiByteToWideChar( CP_UNIXCP, 0, dir, -1, nameW.Buffer + sizeof(prefixW)/sizeof(WCHAR), len );
867 len += sizeof(prefixW) / sizeof(WCHAR);
868 nameW.Buffer[len-1] = '/';
869 strcpyW( nameW.Buffer + len, name );
871 attr.Length = sizeof(attr);
872 attr.RootDirectory = 0;
873 attr.Attributes = 0;
874 attr.ObjectName = &nameW;
875 attr.SecurityDescriptor = NULL;
876 attr.SecurityQualityOfService = NULL;
878 status = NtCreateFile( &ret, GENERIC_READ|GENERIC_WRITE, &attr, &io, NULL, 0,
879 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN_IF,
880 FILE_SYNCHRONOUS_IO_ALERT, NULL, 0 );
881 if (status)
883 ret = 0;
884 SetLastError( RtlNtStatusToDosError(status) );
886 RtlFreeUnicodeString( &nameW );
887 return ret;
891 /***********************************************************************
892 * INT21_OpenMagicDevice
894 * Open a file handle for "magic" devices like EMMXXXX0.
896 static HANDLE INT21_OpenMagicDevice( LPCWSTR name, DWORD access )
898 unsigned int i;
899 const WCHAR *p;
900 HANDLE handle;
902 if (name[0] && (name[1] == ':')) name += 2;
903 if ((p = strrchrW( name, '/' ))) name = p + 1;
904 if ((p = strrchrW( name, '\\' ))) name = p + 1;
906 for (i = 0; i < NB_MAGIC_DEVICES; i++)
908 int len = strlenW( magic_devices[i].name );
909 if (!strncmpiW( magic_devices[i].name, name, len ) &&
910 (!name[len] || name[len] == '.' || name[len] == ':')) break;
912 if (i == NB_MAGIC_DEVICES) return 0;
914 if (!magic_devices[i].handle) /* need to open it */
916 IO_STATUS_BLOCK io;
917 FILE_INTERNAL_INFORMATION info;
919 if (!(handle = INT21_CreateMagicDeviceHandle( magic_devices[i].name ))) return 0;
921 NtQueryInformationFile( handle, &io, &info, sizeof(info), FileInternalInformation );
922 magic_devices[i].index = info.IndexNumber;
923 magic_devices[i].handle = handle;
925 if (!DuplicateHandle( GetCurrentProcess(), magic_devices[i].handle,
926 GetCurrentProcess(), &handle, access, FALSE, 0 )) handle = 0;
927 return handle;
931 /***********************************************************************
932 * INT21_CreateFile
934 * Handler for:
935 * - function 0x3c
936 * - function 0x3d
937 * - function 0x5b
938 * - function 0x6c
939 * - subfunction 0x6c of function 0x71
941 static BOOL INT21_CreateFile( CONTEXT86 *context,
942 DWORD pathSegOff,
943 BOOL returnStatus,
944 WORD dosAccessShare,
945 BYTE dosAction )
947 WORD dosStatus;
948 char *pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, pathSegOff);
949 WCHAR pathW[MAX_PATH];
950 DWORD winAccess;
951 DWORD winAttributes;
952 HANDLE winHandle;
953 DWORD winMode;
954 DWORD winSharing;
956 TRACE( "CreateFile called: function=%02x, action=%02x, access/share=%04x, "
957 "create flags=%04x, file=%s.\n",
958 AH_reg(context), dosAction, dosAccessShare, CX_reg(context), pathA );
961 * Application tried to create/open a file whose name
962 * ends with a backslash. This is not allowed.
964 * FIXME: This needs to be validated, especially the return value.
966 if (pathA[strlen(pathA) - 1] == '/')
968 SetLastError( ERROR_FILE_NOT_FOUND );
969 return FALSE;
973 * Convert DOS action flags into Win32 creation disposition parameter.
975 switch(dosAction)
977 case 0x01:
978 winMode = OPEN_EXISTING;
979 break;
980 case 0x02:
981 winMode = TRUNCATE_EXISTING;
982 break;
983 case 0x10:
984 winMode = CREATE_NEW;
985 break;
986 case 0x11:
987 winMode = OPEN_ALWAYS;
988 break;
989 case 0x12:
990 winMode = CREATE_ALWAYS;
991 break;
992 default:
993 SetLastError( ERROR_INVALID_PARAMETER );
994 return FALSE;
998 * Convert DOS access/share flags into Win32 desired access parameter.
1000 switch(dosAccessShare & 0x07)
1002 case OF_READ:
1003 winAccess = GENERIC_READ;
1004 break;
1005 case OF_WRITE:
1006 winAccess = GENERIC_WRITE;
1007 break;
1008 case OF_READWRITE:
1009 winAccess = GENERIC_READ | GENERIC_WRITE;
1010 break;
1011 case 0x04:
1013 * Read-only, do not modify file's last-access time (DOS7).
1015 * FIXME: How to prevent modification of last-access time?
1017 winAccess = GENERIC_READ;
1018 break;
1019 default:
1020 winAccess = 0;
1024 * Convert DOS access/share flags into Win32 share mode parameter.
1026 switch(dosAccessShare & 0x70)
1028 case OF_SHARE_EXCLUSIVE:
1029 winSharing = 0;
1030 break;
1031 case OF_SHARE_DENY_WRITE:
1032 winSharing = FILE_SHARE_READ;
1033 break;
1034 case OF_SHARE_DENY_READ:
1035 winSharing = FILE_SHARE_WRITE;
1036 break;
1037 case OF_SHARE_DENY_NONE:
1038 case OF_SHARE_COMPAT:
1039 default:
1040 winSharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
1044 * FIXME: Bit (dosAccessShare & 0x80) represents inheritance.
1045 * What to do with this bit?
1046 * FIXME: Bits in the high byte of dosAccessShare are not supported.
1047 * See both function 0x6c and subfunction 0x6c of function 0x71 for
1048 * definition of these bits.
1052 * Convert DOS create attributes into Win32 flags and attributes parameter.
1054 if (winMode == OPEN_EXISTING || winMode == TRUNCATE_EXISTING)
1056 winAttributes = 0;
1058 else
1060 WORD dosAttributes = CX_reg(context);
1062 if (dosAttributes & FA_LABEL)
1065 * Application tried to create volume label entry.
1066 * This is difficult to support so we do not allow it.
1068 * FIXME: If volume does not already have a label,
1069 * this function is supposed to succeed.
1071 SetLastError( ERROR_ACCESS_DENIED );
1072 return TRUE;
1075 winAttributes = dosAttributes &
1076 (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN |
1077 FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE);
1081 * Open the file.
1083 MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
1085 if ((winHandle = INT21_OpenMagicDevice( pathW, winAccess )))
1087 dosStatus = 1;
1089 else
1091 winHandle = CreateFileW( pathW, winAccess, winSharing, NULL,
1092 winMode, winAttributes, 0 );
1093 /* DOS allows to open files on a CDROM R/W */
1094 if( winHandle == INVALID_HANDLE_VALUE &&
1095 (GetLastError() == ERROR_WRITE_PROTECT ||
1096 GetLastError() == ERROR_ACCESS_DENIED)) {
1097 winHandle = CreateFileW( pathW, winAccess & ~GENERIC_WRITE,
1098 winSharing, NULL, winMode, winAttributes, 0 );
1101 if (winHandle == INVALID_HANDLE_VALUE)
1102 return FALSE;
1105 * Determine DOS file status.
1107 * 1 = file opened
1108 * 2 = file created
1109 * 3 = file replaced
1111 switch(winMode)
1113 case OPEN_EXISTING:
1114 dosStatus = 1;
1115 break;
1116 case TRUNCATE_EXISTING:
1117 dosStatus = 3;
1118 break;
1119 case CREATE_NEW:
1120 dosStatus = 2;
1121 break;
1122 case OPEN_ALWAYS:
1123 dosStatus = (GetLastError() == ERROR_ALREADY_EXISTS) ? 1 : 2;
1124 break;
1125 case CREATE_ALWAYS:
1126 dosStatus = (GetLastError() == ERROR_ALREADY_EXISTS) ? 3 : 2;
1127 break;
1128 default:
1129 dosStatus = 0;
1134 * Return DOS file handle and DOS status.
1136 SET_AX( context, Win32HandleToDosFileHandle(winHandle) );
1138 if (returnStatus)
1139 SET_CX( context, dosStatus );
1141 TRACE( "CreateFile finished: handle=%d, status=%d.\n",
1142 AX_reg(context), dosStatus );
1144 return TRUE;
1148 /***********************************************************************
1149 * INT21_BufferedInput
1151 * Handler for function 0x0a and reading from console using
1152 * function 0x3f.
1154 * Reads a string of characters from standard input until
1155 * enter key is pressed. Returns either number of characters
1156 * read from console including terminating CR or
1157 * zero if capacity was zero.
1159 static WORD INT21_BufferedInput( CONTEXT86 *context, BYTE *ptr, WORD capacity )
1161 BYTE length = 0;
1164 * Return immediately if capacity is zero.
1166 if (capacity == 0)
1167 return 0;
1169 while(TRUE)
1171 BYTE ascii;
1172 BYTE scan;
1174 DOSVM_Int16ReadChar( &ascii, &scan, context );
1176 if (ascii == '\r' || ascii == '\n')
1178 ptr[length] = '\r';
1179 return length + 1;
1183 * DOS handles only backspace and KEY_LEFT
1184 * perhaps we should do more
1186 if (ascii == '\b' || scan == KEY_LEFT)
1188 if (length==0) continue;
1189 DOSVM_PutChar( '\b' );
1190 length--;
1191 continue;
1195 * If the buffer becomes filled to within one byte of
1196 * capacity, DOS rejects all further characters up to,
1197 * but not including, the terminating carriage return.
1199 if (ascii != 0 && length < capacity-1)
1201 DOSVM_PutChar( ascii );
1202 ptr[length] = ascii;
1203 length++;
1209 /***********************************************************************
1210 * INT21_GetCurrentDTA
1212 static BYTE *INT21_GetCurrentDTA( CONTEXT86 *context )
1214 TDB *pTask = GlobalLock16(GetCurrentTask());
1216 /* FIXME: This assumes DTA was set correctly! */
1217 return CTX_SEG_OFF_TO_LIN( context, SELECTOROF(pTask->dta),
1218 OFFSETOF(pTask->dta) );
1222 /***********************************************************************
1223 * INT21_OpenFileUsingFCB
1225 * Handler for function 0x0f.
1227 * PARAMS
1228 * DX:DX [I/O] File control block (FCB or XFCB) of unopened file
1230 * RETURNS (in AL)
1231 * 0x00: successful
1232 * 0xff: failed
1234 * NOTES
1235 * Opens a FCB file for read/write in compatibility mode. Upon calling
1236 * the FCB must have the drive_number, file_name, and file_extension
1237 * fields filled and all other bytes cleared.
1239 static void INT21_OpenFileUsingFCB( CONTEXT86 *context )
1241 struct FCB *fcb;
1242 struct XFCB *xfcb;
1243 char file_path[16];
1244 char *pos;
1245 HANDLE handle;
1246 HFILE16 hfile16;
1247 BY_HANDLE_FILE_INFORMATION info;
1248 BYTE AL_result;
1250 fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1251 if (fcb->drive_number == 0xff) {
1252 xfcb = (struct XFCB *) fcb;
1253 fcb = (struct FCB *) xfcb->fcb;
1254 } /* if */
1256 AL_result = 0;
1257 file_path[0] = 'A' + INT21_MapDrive( fcb->drive_number );
1259 if (AL_result == 0) {
1260 file_path[1] = ':';
1261 pos = &file_path[2];
1262 memcpy(pos, fcb->file_name, 8);
1263 pos[8] = ' ';
1264 pos[9] = '\0';
1265 pos = strchr(pos, ' ');
1266 *pos = '.';
1267 pos++;
1268 memcpy(pos, fcb->file_extension, 3);
1269 pos[3] = ' ';
1270 pos[4] = '\0';
1271 pos = strchr(pos, ' ');
1272 *pos = '\0';
1274 handle = (HANDLE) _lopen(file_path, OF_READWRITE);
1275 if (handle == INVALID_HANDLE_VALUE) {
1276 TRACE("_lopen(\"%s\") failed: INVALID_HANDLE_VALUE\n", file_path);
1277 AL_result = 0xff; /* failed */
1278 } else {
1279 hfile16 = Win32HandleToDosFileHandle(handle);
1280 if (hfile16 == HFILE_ERROR16) {
1281 TRACE("Win32HandleToDosFileHandle(%p) failed: HFILE_ERROR\n", handle);
1282 CloseHandle(handle);
1283 AL_result = 0xff; /* failed */
1284 } else if (hfile16 > 255) {
1285 TRACE("hfile16 (=%d) larger than 255 for \"%s\"\n", hfile16, file_path);
1286 _lclose16(hfile16);
1287 AL_result = 0xff; /* failed */
1288 } else {
1289 if (!GetFileInformationByHandle(handle, &info)) {
1290 TRACE("GetFileInformationByHandle(%d, %p) for \"%s\" failed\n",
1291 hfile16, handle, file_path);
1292 _lclose16(hfile16);
1293 AL_result = 0xff; /* failed */
1294 } else {
1295 fcb->drive_number = file_path[0] - 'A' + 1;
1296 fcb->current_block_number = 0;
1297 fcb->logical_record_size = 128;
1298 fcb->file_size = info.nFileSizeLow;
1299 FileTimeToDosDateTime(&info.ftLastWriteTime,
1300 &fcb->date_of_last_write, &fcb->time_of_last_write);
1301 fcb->file_number = hfile16;
1302 fcb->attributes = 0xc2;
1303 fcb->starting_cluster = 0; /* don't know correct init value */
1304 fcb->sequence_number = 0; /* don't know correct init value */
1305 fcb->file_attributes = info.dwFileAttributes;
1306 /* The following fields are not initialized */
1307 /* by the native function: */
1308 /* unused */
1309 /* record_within_current_block */
1310 /* random_access_record_number */
1312 TRACE("successful opened file \"%s\" as %d (handle %p)\n",
1313 file_path, hfile16, handle);
1314 AL_result = 0x00; /* successful */
1315 } /* if */
1316 } /* if */
1317 } /* if */
1318 } /* if */
1319 SET_AL(context, AL_result);
1323 /***********************************************************************
1324 * INT21_CloseFileUsingFCB
1326 * Handler for function 0x10.
1328 * PARAMS
1329 * DX:DX [I/O] File control block (FCB or XFCB) of open file
1331 * RETURNS (in AL)
1332 * 0x00: successful
1333 * 0xff: failed
1335 * NOTES
1336 * Closes a FCB file.
1338 static void INT21_CloseFileUsingFCB( CONTEXT86 *context )
1340 struct FCB *fcb;
1341 struct XFCB *xfcb;
1342 BYTE AL_result;
1344 fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1345 if (fcb->drive_number == 0xff) {
1346 xfcb = (struct XFCB *) fcb;
1347 fcb = (struct FCB *) xfcb->fcb;
1348 } /* if */
1350 if (_lclose16((HFILE16) fcb->file_number) != 0) {
1351 TRACE("_lclose16(%d) failed\n", fcb->file_number);
1352 AL_result = 0xff; /* failed */
1353 } else {
1354 TRACE("successful closed file %d\n", fcb->file_number);
1355 AL_result = 0x00; /* successful */
1356 } /* if */
1357 SET_AL(context, AL_result);
1361 /***********************************************************************
1362 * INT21_SequentialReadFromFCB
1364 * Handler for function 0x14.
1366 * PARAMS
1367 * DX:DX [I/O] File control block (FCB or XFCB) of open file
1369 * RETURNS (in AL)
1370 * 0: successful
1371 * 1: end of file, no data read
1372 * 2: segment wrap in DTA, no data read (not returned now)
1373 * 3: end of file, partial record read
1375 * NOTES
1376 * Reads a record with the size FCB->logical_record_size from the FCB
1377 * to the disk transfer area. The position of the record is specified
1378 * with FCB->current_block_number and FCB->record_within_current_block.
1379 * Then FCB->current_block_number and FCB->record_within_current_block
1380 * are updated to point to the next record. If a partial record is
1381 * read, it is filled with zeros up to the FCB->logical_record_size.
1383 static void INT21_SequentialReadFromFCB( CONTEXT86 *context )
1385 struct FCB *fcb;
1386 struct XFCB *xfcb;
1387 HANDLE handle;
1388 DWORD record_number;
1389 DWORD position;
1390 BYTE *disk_transfer_area;
1391 UINT bytes_read;
1392 BYTE AL_result;
1394 fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1395 if (fcb->drive_number == 0xff) {
1396 xfcb = (struct XFCB *) fcb;
1397 fcb = (struct FCB *) xfcb->fcb;
1398 } /* if */
1400 handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1401 if (handle == INVALID_HANDLE_VALUE) {
1402 TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1403 fcb->file_number);
1404 AL_result = 0x01; /* end of file, no data read */
1405 } else {
1406 record_number = 128 * fcb->current_block_number + fcb->record_within_current_block;
1407 position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1408 if (position != record_number * fcb->logical_record_size) {
1409 TRACE("seek(%d, %d, 0) failed with %u\n",
1410 fcb->file_number, record_number * fcb->logical_record_size, position);
1411 AL_result = 0x01; /* end of file, no data read */
1412 } else {
1413 disk_transfer_area = INT21_GetCurrentDTA(context);
1414 bytes_read = _lread((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
1415 if (bytes_read != fcb->logical_record_size) {
1416 TRACE("_lread(%d, %p, %d) failed with %d\n",
1417 fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_read);
1418 if (bytes_read == 0) {
1419 AL_result = 0x01; /* end of file, no data read */
1420 } else {
1421 memset(&disk_transfer_area[bytes_read], 0, fcb->logical_record_size - bytes_read);
1422 AL_result = 0x03; /* end of file, partial record read */
1423 } /* if */
1424 } else {
1425 TRACE("successful read %d bytes from record %d (position %u) of file %d (handle %p)\n",
1426 bytes_read, record_number, position, fcb->file_number, handle);
1427 AL_result = 0x00; /* successful */
1428 } /* if */
1429 } /* if */
1430 } /* if */
1431 if (AL_result == 0x00 || AL_result == 0x03) {
1432 if (fcb->record_within_current_block == 127) {
1433 fcb->record_within_current_block = 0;
1434 fcb->current_block_number++;
1435 } else {
1436 fcb->record_within_current_block++;
1437 } /* if */
1438 } /* if */
1439 SET_AL(context, AL_result);
1443 /***********************************************************************
1444 * INT21_SequentialWriteToFCB
1446 * Handler for function 0x15.
1448 * PARAMS
1449 * DX:DX [I/O] File control block (FCB or XFCB) of open file
1451 * RETURNS (in AL)
1452 * 0: successful
1453 * 1: disk full
1454 * 2: segment wrap in DTA (not returned now)
1456 * NOTES
1457 * Writes a record with the size FCB->logical_record_size from the disk
1458 * transfer area to the FCB. The position of the record is specified
1459 * with FCB->current_block_number and FCB->record_within_current_block.
1460 * Then FCB->current_block_number and FCB->record_within_current_block
1461 * are updated to point to the next record.
1463 static void INT21_SequentialWriteToFCB( CONTEXT86 *context )
1465 struct FCB *fcb;
1466 struct XFCB *xfcb;
1467 HANDLE handle;
1468 DWORD record_number;
1469 DWORD position;
1470 BYTE *disk_transfer_area;
1471 UINT bytes_written;
1472 BYTE AL_result;
1474 fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1475 if (fcb->drive_number == 0xff) {
1476 xfcb = (struct XFCB *) fcb;
1477 fcb = (struct FCB *) xfcb->fcb;
1478 } /* if */
1480 handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1481 if (handle == INVALID_HANDLE_VALUE) {
1482 TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1483 fcb->file_number);
1484 AL_result = 0x01; /* disk full */
1485 } else {
1486 record_number = 128 * fcb->current_block_number + fcb->record_within_current_block;
1487 position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1488 if (position != record_number * fcb->logical_record_size) {
1489 TRACE("seek(%d, %d, 0) failed with %u\n",
1490 fcb->file_number, record_number * fcb->logical_record_size, position);
1491 AL_result = 0x01; /* disk full */
1492 } else {
1493 disk_transfer_area = INT21_GetCurrentDTA(context);
1494 bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, fcb->logical_record_size);
1495 if (bytes_written != fcb->logical_record_size) {
1496 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1497 fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_written);
1498 AL_result = 0x01; /* disk full */
1499 } else {
1500 TRACE("successful written %d bytes from record %d (position %u) of file %d (handle %p)\n",
1501 bytes_written, record_number, position, fcb->file_number, handle);
1502 AL_result = 0x00; /* successful */
1503 } /* if */
1504 } /* if */
1505 } /* if */
1506 if (AL_result == 0x00) {
1507 if (fcb->record_within_current_block == 127) {
1508 fcb->record_within_current_block = 0;
1509 fcb->current_block_number++;
1510 } else {
1511 fcb->record_within_current_block++;
1512 } /* if */
1513 } /* if */
1514 SET_AL(context, AL_result);
1518 /***********************************************************************
1519 * INT21_ReadRandomRecordFromFCB
1521 * Handler for function 0x21.
1523 * PARAMS
1524 * DX:DX [I/O] File control block (FCB or XFCB) of open file
1526 * RETURNS (in AL)
1527 * 0: successful
1528 * 1: end of file, no data read
1529 * 2: segment wrap in DTA, no data read (not returned now)
1530 * 3: end of file, partial record read
1532 * NOTES
1533 * Reads a record with the size FCB->logical_record_size from
1534 * the FCB to the disk transfer area. The position of the record
1535 * is specified with FCB->random_access_record_number. The
1536 * FCB->random_access_record_number is not updated. If a partial record
1537 * is read, it is filled with zeros up to the FCB->logical_record_size.
1539 static void INT21_ReadRandomRecordFromFCB( CONTEXT86 *context )
1541 struct FCB *fcb;
1542 struct XFCB *xfcb;
1543 HANDLE handle;
1544 DWORD record_number;
1545 DWORD position;
1546 BYTE *disk_transfer_area;
1547 UINT bytes_read;
1548 BYTE AL_result;
1550 fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1551 if (fcb->drive_number == 0xff) {
1552 xfcb = (struct XFCB *) fcb;
1553 fcb = (struct FCB *) xfcb->fcb;
1554 } /* if */
1556 memcpy(&record_number, fcb->random_access_record_number, 4);
1557 handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1558 if (handle == INVALID_HANDLE_VALUE) {
1559 TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1560 fcb->file_number);
1561 AL_result = 0x01; /* end of file, no data read */
1562 } else {
1563 position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1564 if (position != record_number * fcb->logical_record_size) {
1565 TRACE("seek(%d, %d, 0) failed with %u\n",
1566 fcb->file_number, record_number * fcb->logical_record_size, position);
1567 AL_result = 0x01; /* end of file, no data read */
1568 } else {
1569 disk_transfer_area = INT21_GetCurrentDTA(context);
1570 bytes_read = _lread((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
1571 if (bytes_read != fcb->logical_record_size) {
1572 TRACE("_lread(%d, %p, %d) failed with %d\n",
1573 fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_read);
1574 if (bytes_read == 0) {
1575 AL_result = 0x01; /* end of file, no data read */
1576 } else {
1577 memset(&disk_transfer_area[bytes_read], 0, fcb->logical_record_size - bytes_read);
1578 AL_result = 0x03; /* end of file, partial record read */
1579 } /* if */
1580 } else {
1581 TRACE("successful read %d bytes from record %d (position %u) of file %d (handle %p)\n",
1582 bytes_read, record_number, position, fcb->file_number, handle);
1583 AL_result = 0x00; /* successful */
1584 } /* if */
1585 } /* if */
1586 } /* if */
1587 fcb->current_block_number = record_number / 128;
1588 fcb->record_within_current_block = record_number % 128;
1589 SET_AL(context, AL_result);
1593 /***********************************************************************
1594 * INT21_WriteRandomRecordToFCB
1596 * Handler for function 0x22.
1598 * PARAMS
1599 * DX:DX [I/O] File control block (FCB or XFCB) of open file
1601 * RETURNS (in AL)
1602 * 0: successful
1603 * 1: disk full
1604 * 2: segment wrap in DTA (not returned now)
1606 * NOTES
1607 * Writes a record with the size FCB->logical_record_size from
1608 * the disk transfer area to the FCB. The position of the record
1609 * is specified with FCB->random_access_record_number. The
1610 * FCB->random_access_record_number is not updated.
1612 static void INT21_WriteRandomRecordToFCB( CONTEXT86 *context )
1614 struct FCB *fcb;
1615 struct XFCB *xfcb;
1616 HANDLE handle;
1617 DWORD record_number;
1618 DWORD position;
1619 BYTE *disk_transfer_area;
1620 UINT bytes_written;
1621 BYTE AL_result;
1623 fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1624 if (fcb->drive_number == 0xff) {
1625 xfcb = (struct XFCB *) fcb;
1626 fcb = (struct FCB *) xfcb->fcb;
1627 } /* if */
1629 memcpy(&record_number, fcb->random_access_record_number, 4);
1630 handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1631 if (handle == INVALID_HANDLE_VALUE) {
1632 TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1633 fcb->file_number);
1634 AL_result = 0x01; /* disk full */
1635 } else {
1636 position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1637 if (position != record_number * fcb->logical_record_size) {
1638 TRACE("seek(%d, %d, 0) failed with %u\n",
1639 fcb->file_number, record_number * fcb->logical_record_size, position);
1640 AL_result = 0x01; /* disk full */
1641 } else {
1642 disk_transfer_area = INT21_GetCurrentDTA(context);
1643 bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, fcb->logical_record_size);
1644 if (bytes_written != fcb->logical_record_size) {
1645 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1646 fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_written);
1647 AL_result = 0x01; /* disk full */
1648 } else {
1649 TRACE("successful written %d bytes from record %d (position %u) of file %d (handle %p)\n",
1650 bytes_written, record_number, position, fcb->file_number, handle);
1651 AL_result = 0x00; /* successful */
1652 } /* if */
1653 } /* if */
1654 } /* if */
1655 fcb->current_block_number = record_number / 128;
1656 fcb->record_within_current_block = record_number % 128;
1657 SET_AL(context, AL_result);
1661 /***********************************************************************
1662 * INT21_RandomBlockReadFromFCB
1664 * Handler for function 0x27.
1666 * PARAMS
1667 * CX [I/O] Number of records to read
1668 * DX:DX [I/O] File control block (FCB or XFCB) of open file
1670 * RETURNS (in AL)
1671 * 0: successful
1672 * 1: end of file, no data read
1673 * 2: segment wrap in DTA, no data read (not returned now)
1674 * 3: end of file, partial record read
1676 * NOTES
1677 * Reads several records with the size FCB->logical_record_size from
1678 * the FCB to the disk transfer area. The number of records to be
1679 * read is specified in the CX register. The position of the first
1680 * record is specified with FCB->random_access_record_number. The
1681 * FCB->random_access_record_number, the FCB->current_block_number
1682 * and FCB->record_within_current_block are updated to point to the
1683 * next record after the records read. If a partial record is read,
1684 * it is filled with zeros up to the FCB->logical_record_size. The
1685 * CX register is set to the number of successfully read records.
1687 static void INT21_RandomBlockReadFromFCB( CONTEXT86 *context )
1689 struct FCB *fcb;
1690 struct XFCB *xfcb;
1691 HANDLE handle;
1692 DWORD record_number;
1693 DWORD position;
1694 BYTE *disk_transfer_area;
1695 UINT records_requested;
1696 UINT bytes_requested;
1697 UINT bytes_read;
1698 UINT records_read;
1699 BYTE AL_result;
1701 fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1702 if (fcb->drive_number == 0xff) {
1703 xfcb = (struct XFCB *) fcb;
1704 fcb = (struct FCB *) xfcb->fcb;
1705 } /* if */
1707 memcpy(&record_number, fcb->random_access_record_number, 4);
1708 handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1709 if (handle == INVALID_HANDLE_VALUE) {
1710 TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1711 fcb->file_number);
1712 records_read = 0;
1713 AL_result = 0x01; /* end of file, no data read */
1714 } else {
1715 position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1716 if (position != record_number * fcb->logical_record_size) {
1717 TRACE("seek(%d, %d, 0) failed with %u\n",
1718 fcb->file_number, record_number * fcb->logical_record_size, position);
1719 records_read = 0;
1720 AL_result = 0x01; /* end of file, no data read */
1721 } else {
1722 disk_transfer_area = INT21_GetCurrentDTA(context);
1723 records_requested = CX_reg(context);
1724 bytes_requested = records_requested * fcb->logical_record_size;
1725 bytes_read = _lread((HFILE) handle, disk_transfer_area, bytes_requested);
1726 if (bytes_read != bytes_requested) {
1727 TRACE("_lread(%d, %p, %d) failed with %d\n",
1728 fcb->file_number, disk_transfer_area, bytes_requested, bytes_read);
1729 records_read = bytes_read / fcb->logical_record_size;
1730 if (bytes_read % fcb->logical_record_size == 0) {
1731 AL_result = 0x01; /* end of file, no data read */
1732 } else {
1733 records_read++;
1734 memset(&disk_transfer_area[bytes_read], 0, records_read * fcb->logical_record_size - bytes_read);
1735 AL_result = 0x03; /* end of file, partial record read */
1736 } /* if */
1737 } else {
1738 TRACE("successful read %d bytes from record %d (position %u) of file %d (handle %p)\n",
1739 bytes_read, record_number, position, fcb->file_number, handle);
1740 records_read = records_requested;
1741 AL_result = 0x00; /* successful */
1742 } /* if */
1743 } /* if */
1744 } /* if */
1745 record_number += records_read;
1746 memcpy(fcb->random_access_record_number, &record_number, 4);
1747 fcb->current_block_number = record_number / 128;
1748 fcb->record_within_current_block = record_number % 128;
1749 SET_CX(context, records_read);
1750 SET_AL(context, AL_result);
1754 /***********************************************************************
1755 * INT21_RandomBlockWriteToFCB
1757 * Handler for function 0x28.
1759 * PARAMS
1760 * CX [I/O] Number of records to write
1761 * DX:DX [I/O] File control block (FCB or XFCB) of open file
1763 * RETURNS (in AL)
1764 * 0: successful
1765 * 1: disk full
1766 * 2: segment wrap in DTA (not returned now)
1768 * NOTES
1769 * Writes several records with the size FCB->logical_record_size from
1770 * the disk transfer area to the FCB. The number of records to be
1771 * written is specified in the CX register. The position of the first
1772 * record is specified with FCB->random_access_record_number. The
1773 * FCB->random_access_record_number, the FCB->current_block_number
1774 * and FCB->record_within_current_block are updated to point to the
1775 * next record after the records written. The CX register is set to
1776 * the number of successfully written records.
1778 static void INT21_RandomBlockWriteToFCB( CONTEXT86 *context )
1780 struct FCB *fcb;
1781 struct XFCB *xfcb;
1782 HANDLE handle;
1783 DWORD record_number;
1784 DWORD position;
1785 BYTE *disk_transfer_area;
1786 UINT records_requested;
1787 UINT bytes_requested;
1788 UINT bytes_written;
1789 UINT records_written;
1790 BYTE AL_result;
1792 fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1793 if (fcb->drive_number == 0xff) {
1794 xfcb = (struct XFCB *) fcb;
1795 fcb = (struct FCB *) xfcb->fcb;
1796 } /* if */
1798 memcpy(&record_number, fcb->random_access_record_number, 4);
1799 handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1800 if (handle == INVALID_HANDLE_VALUE) {
1801 TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1802 fcb->file_number);
1803 records_written = 0;
1804 AL_result = 0x01; /* disk full */
1805 } else {
1806 position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1807 if (position != record_number * fcb->logical_record_size) {
1808 TRACE("seek(%d, %d, 0) failed with %u\n",
1809 fcb->file_number, record_number * fcb->logical_record_size, position);
1810 records_written = 0;
1811 AL_result = 0x01; /* disk full */
1812 } else {
1813 disk_transfer_area = INT21_GetCurrentDTA(context);
1814 records_requested = CX_reg(context);
1815 bytes_requested = records_requested * fcb->logical_record_size;
1816 bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, bytes_requested);
1817 if (bytes_written != bytes_requested) {
1818 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1819 fcb->file_number, disk_transfer_area, bytes_requested, bytes_written);
1820 records_written = bytes_written / fcb->logical_record_size;
1821 AL_result = 0x01; /* disk full */
1822 } else {
1823 TRACE("successful write %d bytes from record %d (position %u) of file %d (handle %p)\n",
1824 bytes_written, record_number, position, fcb->file_number, handle);
1825 records_written = records_requested;
1826 AL_result = 0x00; /* successful */
1827 } /* if */
1828 } /* if */
1829 } /* if */
1830 record_number += records_written;
1831 memcpy(fcb->random_access_record_number, &record_number, 4);
1832 fcb->current_block_number = record_number / 128;
1833 fcb->record_within_current_block = record_number % 128;
1834 SET_CX(context, records_written);
1835 SET_AL(context, AL_result);
1839 /***********************************************************************
1840 * INT21_CreateDirectory
1842 * Handler for:
1843 * - function 0x39
1844 * - subfunction 0x39 of function 0x71
1845 * - subfunction 0xff of function 0x43 (CL == 0x39)
1847 static BOOL INT21_CreateDirectory( CONTEXT86 *context )
1849 WCHAR dirW[MAX_PATH];
1850 char *dirA = CTX_SEG_OFF_TO_LIN(context,
1851 context->SegDs,
1852 context->Edx);
1854 TRACE( "CREATE DIRECTORY %s\n", dirA );
1856 MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
1858 if (CreateDirectoryW(dirW, NULL))
1859 return TRUE;
1862 * FIXME: CreateDirectory's LastErrors will clash with the ones
1863 * used by DOS. AH=39 only returns 3 (path not found) and
1864 * 5 (access denied), while CreateDirectory return several
1865 * ones. Remap some of them. -Marcus
1867 switch (GetLastError())
1869 case ERROR_ALREADY_EXISTS:
1870 case ERROR_FILENAME_EXCED_RANGE:
1871 case ERROR_DISK_FULL:
1872 SetLastError(ERROR_ACCESS_DENIED);
1873 break;
1874 default:
1875 break;
1878 return FALSE;
1882 /***********************************************************************
1883 * INT21_ExtendedCountryInformation
1885 * Handler for function 0x65.
1887 static void INT21_ExtendedCountryInformation( CONTEXT86 *context )
1889 BYTE *dataptr = CTX_SEG_OFF_TO_LIN( context, context->SegEs, context->Edi );
1890 BYTE buffsize = CX_reg (context);
1892 TRACE( "GET EXTENDED COUNTRY INFORMATION, subfunction %02x\n",
1893 AL_reg(context) );
1896 * Check subfunctions that are passed country and code page.
1898 if (AL_reg(context) >= 0x01 && AL_reg(context) <= 0x07)
1900 WORD country = DX_reg(context);
1901 WORD codepage = BX_reg(context);
1903 if (country != 0xffff && country != INT21_GetSystemCountryCode())
1904 FIXME( "Requested info on non-default country %04x\n", country );
1906 if (codepage != 0xffff && codepage != GetOEMCP())
1907 FIXME( "Requested info on non-default code page %04x\n", codepage );
1910 switch (AL_reg(context)) {
1911 case 0x00: /* SET GENERAL INTERNATIONALIZATION INFO */
1912 INT_BARF( context, 0x21 );
1913 SET_CFLAG( context );
1914 break;
1916 case 0x01: /* GET GENERAL INTERNATIONALIZATION INFO */
1917 TRACE( "Get general internationalization info\n" );
1918 dataptr[0] = 0x01; /* Info ID */
1919 *(WORD*)(dataptr+1) = 38; /* Size of the following info */
1920 *(WORD*)(dataptr+3) = INT21_GetSystemCountryCode(); /* Country ID */
1921 *(WORD*)(dataptr+5) = GetOEMCP(); /* Code page */
1922 /* FIXME: fill buffer partially up to buffsize bytes*/
1923 if (buffsize >= 0x29){
1924 INT21_FillCountryInformation( dataptr + 7 );
1925 SET_CX( context, 0x29 ); /* Size of returned info */
1926 }else{
1927 SET_CX( context, 0x07 ); /* Size of returned info */
1929 break;
1931 case 0x02: /* GET POINTER TO UPPERCASE TABLE */
1932 case 0x04: /* GET POINTER TO FILENAME UPPERCASE TABLE */
1933 TRACE( "Get pointer to uppercase table\n" );
1934 dataptr[0] = AL_reg(context); /* Info ID */
1935 *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1936 offsetof(INT21_HEAP, uppercase_size) );
1937 SET_CX( context, 5 ); /* Size of returned info */
1938 break;
1940 case 0x03: /* GET POINTER TO LOWERCASE TABLE */
1941 TRACE( "Get pointer to lowercase table\n" );
1942 dataptr[0] = 0x03; /* Info ID */
1943 *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1944 offsetof(INT21_HEAP, lowercase_size) );
1945 SET_CX( context, 5 ); /* Size of returned info */
1946 break;
1948 case 0x05: /* GET POINTER TO FILENAME TERMINATOR TABLE */
1949 TRACE("Get pointer to filename terminator table\n");
1950 dataptr[0] = 0x05; /* Info ID */
1951 *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1952 offsetof(INT21_HEAP, filename_size) );
1953 SET_CX( context, 5 ); /* Size of returned info */
1954 break;
1956 case 0x06: /* GET POINTER TO COLLATING SEQUENCE TABLE */
1957 TRACE("Get pointer to collating sequence table\n");
1958 dataptr[0] = 0x06; /* Info ID */
1959 *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1960 offsetof(INT21_HEAP, collating_size) );
1961 SET_CX( context, 5 ); /* Size of returned info */
1962 break;
1964 case 0x07: /* GET POINTER TO DBCS LEAD BYTE TABLE */
1965 TRACE("Get pointer to DBCS lead byte table\n");
1966 dataptr[0] = 0x07; /* Info ID */
1967 *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1968 offsetof(INT21_HEAP, dbcs_size) );
1969 SET_CX( context, 5 ); /* Size of returned info */
1970 break;
1972 case 0x20: /* CAPITALIZE CHARACTER */
1973 case 0xa0: /* CAPITALIZE FILENAME CHARACTER */
1974 TRACE("Convert char to uppercase\n");
1975 SET_DL( context, toupper(DL_reg(context)) );
1976 break;
1978 case 0x21: /* CAPITALIZE STRING */
1979 case 0xa1: /* CAPITALIZE COUNTED FILENAME STRING */
1980 TRACE("Convert string to uppercase with length\n");
1982 char *ptr = CTX_SEG_OFF_TO_LIN( context, context->SegDs,
1983 context->Edx );
1984 WORD len = CX_reg(context);
1985 while (len--) { *ptr = toupper(*ptr); ptr++; }
1987 break;
1989 case 0x22: /* CAPITALIZE ASCIIZ STRING */
1990 case 0xa2: /* CAPITALIZE ASCIIZ FILENAME */
1991 TRACE("Convert ASCIIZ string to uppercase\n");
1993 char *p = CTX_SEG_OFF_TO_LIN( context, context->SegDs, context->Edx );
1994 for ( ; *p; p++) *p = toupper(*p);
1996 break;
1998 case 0x23: /* DETERMINE IF CHARACTER REPRESENTS YES/NO RESPONSE */
1999 INT_BARF( context, 0x21 );
2000 SET_CFLAG( context );
2001 break;
2003 default:
2004 INT_BARF( context, 0x21 );
2005 SET_CFLAG(context);
2006 break;
2011 /***********************************************************************
2012 * INT21_FileAttributes
2014 * Handler for:
2015 * - function 0x43
2016 * - subfunction 0x43 of function 0x71
2018 static BOOL INT21_FileAttributes( CONTEXT86 *context,
2019 BYTE subfunction,
2020 BOOL islong )
2022 WCHAR fileW[MAX_PATH];
2023 char *fileA = CTX_SEG_OFF_TO_LIN(context,
2024 context->SegDs,
2025 context->Edx);
2026 HANDLE handle;
2027 BOOL status;
2028 FILETIME filetime;
2029 DWORD result;
2030 WORD date, time;
2031 int len;
2033 switch (subfunction)
2035 case 0x00: /* GET FILE ATTRIBUTES */
2036 TRACE( "GET FILE ATTRIBUTES for %s\n", fileA );
2037 len = MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2039 /* Winbench 96 Disk Test fails if we don't complain
2040 * about a filename that ends in \
2042 if (!len || (fileW[len-1] == '/') || (fileW[len-1] == '\\'))
2043 return FALSE;
2045 result = GetFileAttributesW( fileW );
2046 if (result == INVALID_FILE_ATTRIBUTES)
2047 return FALSE;
2048 else
2050 SET_CX( context, (WORD)result );
2051 if (!islong)
2052 SET_AX( context, (WORD)result ); /* DR DOS */
2054 break;
2056 case 0x01: /* SET FILE ATTRIBUTES */
2057 TRACE( "SET FILE ATTRIBUTES 0x%02x for %s\n",
2058 CX_reg(context), fileA );
2059 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2061 if (!SetFileAttributesW( fileW, CX_reg(context) ))
2062 return FALSE;
2063 break;
2065 case 0x02: /* GET COMPRESSED FILE SIZE */
2066 TRACE( "GET COMPRESSED FILE SIZE for %s\n", fileA );
2067 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2069 result = GetCompressedFileSizeW( fileW, NULL );
2070 if (result == INVALID_FILE_SIZE)
2071 return FALSE;
2072 else
2074 SET_AX( context, LOWORD(result) );
2075 SET_DX( context, HIWORD(result) );
2077 break;
2079 case 0x03: /* SET FILE LAST-WRITTEN DATE AND TIME */
2080 if (!islong)
2081 INT_BARF( context, 0x21 );
2082 else
2084 TRACE( "SET FILE LAST-WRITTEN DATE AND TIME, file %s\n", fileA );
2085 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2087 handle = CreateFileW( fileW, GENERIC_WRITE,
2088 FILE_SHARE_READ | FILE_SHARE_WRITE,
2089 NULL, OPEN_EXISTING, 0, 0 );
2090 if (handle == INVALID_HANDLE_VALUE)
2091 return FALSE;
2093 DosDateTimeToFileTime( DI_reg(context),
2094 CX_reg(context),
2095 &filetime );
2096 status = SetFileTime( handle, NULL, NULL, &filetime );
2098 CloseHandle( handle );
2099 return status;
2101 break;
2103 case 0x04: /* GET FILE LAST-WRITTEN DATE AND TIME */
2104 if (!islong)
2105 INT_BARF( context, 0x21 );
2106 else
2108 TRACE( "GET FILE LAST-WRITTEN DATE AND TIME, file %s\n", fileA );
2109 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2111 handle = CreateFileW( fileW, GENERIC_READ,
2112 FILE_SHARE_READ | FILE_SHARE_WRITE,
2113 NULL, OPEN_EXISTING, 0, 0 );
2114 if (handle == INVALID_HANDLE_VALUE)
2115 return FALSE;
2117 status = GetFileTime( handle, NULL, NULL, &filetime );
2118 if (status)
2120 FileTimeToDosDateTime( &filetime, &date, &time );
2121 SET_DI( context, date );
2122 SET_CX( context, time );
2125 CloseHandle( handle );
2126 return status;
2128 break;
2130 case 0x05: /* SET FILE LAST ACCESS DATE */
2131 if (!islong)
2132 INT_BARF( context, 0x21 );
2133 else
2135 TRACE( "SET FILE LAST ACCESS DATE, file %s\n", fileA );
2136 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2138 handle = CreateFileW( fileW, GENERIC_WRITE,
2139 FILE_SHARE_READ | FILE_SHARE_WRITE,
2140 NULL, OPEN_EXISTING, 0, 0 );
2141 if (handle == INVALID_HANDLE_VALUE)
2142 return FALSE;
2144 DosDateTimeToFileTime( DI_reg(context),
2146 &filetime );
2147 status = SetFileTime( handle, NULL, &filetime, NULL );
2149 CloseHandle( handle );
2150 return status;
2152 break;
2154 case 0x06: /* GET FILE LAST ACCESS DATE */
2155 if (!islong)
2156 INT_BARF( context, 0x21 );
2157 else
2159 TRACE( "GET FILE LAST ACCESS DATE, file %s\n", fileA );
2160 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2162 handle = CreateFileW( fileW, GENERIC_READ,
2163 FILE_SHARE_READ | FILE_SHARE_WRITE,
2164 NULL, OPEN_EXISTING, 0, 0 );
2165 if (handle == INVALID_HANDLE_VALUE)
2166 return FALSE;
2168 status = GetFileTime( handle, NULL, &filetime, NULL );
2169 if (status)
2171 FileTimeToDosDateTime( &filetime, &date, NULL );
2172 SET_DI( context, date );
2175 CloseHandle( handle );
2176 return status;
2178 break;
2180 case 0x07: /* SET FILE CREATION DATE AND TIME */
2181 if (!islong)
2182 INT_BARF( context, 0x21 );
2183 else
2185 TRACE( "SET FILE CREATION DATE AND TIME, file %s\n", fileA );
2186 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2188 handle = CreateFileW( fileW, GENERIC_WRITE,
2189 FILE_SHARE_READ | FILE_SHARE_WRITE,
2190 NULL, OPEN_EXISTING, 0, 0 );
2191 if (handle == INVALID_HANDLE_VALUE)
2192 return FALSE;
2195 * FIXME: SI has number of 10-millisecond units past time in CX.
2197 DosDateTimeToFileTime( DI_reg(context),
2198 CX_reg(context),
2199 &filetime );
2200 status = SetFileTime( handle, &filetime, NULL, NULL );
2202 CloseHandle( handle );
2203 return status;
2205 break;
2207 case 0x08: /* GET FILE CREATION DATE AND TIME */
2208 if (!islong)
2209 INT_BARF( context, 0x21 );
2210 else
2212 TRACE( "GET FILE CREATION DATE AND TIME, file %s\n", fileA );
2213 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2215 handle = CreateFileW( fileW, GENERIC_READ,
2216 FILE_SHARE_READ | FILE_SHARE_WRITE,
2217 NULL, OPEN_EXISTING, 0, 0 );
2218 if (handle == INVALID_HANDLE_VALUE)
2219 return FALSE;
2221 status = GetFileTime( handle, &filetime, NULL, NULL );
2222 if (status)
2224 FileTimeToDosDateTime( &filetime, &date, &time );
2225 SET_DI( context, date );
2226 SET_CX( context, time );
2228 * FIXME: SI has number of 10-millisecond units past
2229 * time in CX.
2231 SET_SI( context, 0 );
2234 CloseHandle(handle);
2235 return status;
2237 break;
2239 case 0xff: /* EXTENDED-LENGTH FILENAME OPERATIONS */
2240 if (islong || context->Ebp != 0x5053)
2241 INT_BARF( context, 0x21 );
2242 else
2244 switch(CL_reg(context))
2246 case 0x39:
2247 if (!INT21_CreateDirectory( context ))
2248 return FALSE;
2249 break;
2251 case 0x56:
2252 if (!INT21_RenameFile( context ))
2253 return FALSE;
2254 break;
2256 default:
2257 INT_BARF( context, 0x21 );
2260 break;
2262 default:
2263 INT_BARF( context, 0x21 );
2266 return TRUE;
2270 /***********************************************************************
2271 * INT21_FileDateTime
2273 * Handler for function 0x57.
2275 static BOOL INT21_FileDateTime( CONTEXT86 *context )
2277 HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
2278 FILETIME filetime;
2279 WORD date, time;
2281 switch (AL_reg(context)) {
2282 case 0x00: /* Get last-written stamp */
2283 TRACE( "GET FILE LAST-WRITTEN DATE AND TIME, handle %d\n",
2284 BX_reg(context) );
2286 if (!GetFileTime( handle, NULL, NULL, &filetime ))
2287 return FALSE;
2288 FileTimeToDosDateTime( &filetime, &date, &time );
2289 SET_DX( context, date );
2290 SET_CX( context, time );
2291 break;
2294 case 0x01: /* Set last-written stamp */
2295 TRACE( "SET FILE LAST-WRITTEN DATE AND TIME, handle %d\n",
2296 BX_reg(context) );
2298 DosDateTimeToFileTime( DX_reg(context),
2299 CX_reg(context),
2300 &filetime );
2301 if (!SetFileTime( handle, NULL, NULL, &filetime ))
2302 return FALSE;
2303 break;
2306 case 0x04: /* Get last access stamp, DOS 7 */
2307 TRACE( "GET FILE LAST ACCESS DATE AND TIME, handle %d\n",
2308 BX_reg(context) );
2310 if (!GetFileTime( handle, NULL, &filetime, NULL ))
2311 return FALSE;
2312 FileTimeToDosDateTime( &filetime, &date, &time );
2313 SET_DX( context, date );
2314 SET_CX( context, time );
2315 break;
2318 case 0x05: /* Set last access stamp, DOS 7 */
2319 TRACE( "SET FILE LAST ACCESS DATE AND TIME, handle %d\n",
2320 BX_reg(context) );
2322 DosDateTimeToFileTime( DX_reg(context),
2323 CX_reg(context),
2324 &filetime );
2325 if (!SetFileTime( handle, NULL, &filetime, NULL ))
2326 return FALSE;
2327 break;
2330 case 0x06: /* Get creation stamp, DOS 7 */
2331 TRACE( "GET FILE CREATION DATE AND TIME, handle %d\n",
2332 BX_reg(context) );
2334 if (!GetFileTime( handle, &filetime, NULL, NULL ))
2335 return FALSE;
2336 FileTimeToDosDateTime( &filetime, &date, &time );
2337 SET_DX( context, date );
2338 SET_CX( context, time );
2340 * FIXME: SI has number of 10-millisecond units past time in CX.
2342 SET_SI( context, 0 );
2343 break;
2346 case 0x07: /* Set creation stamp, DOS 7 */
2347 TRACE( "SET FILE CREATION DATE AND TIME, handle %d\n",
2348 BX_reg(context) );
2351 * FIXME: SI has number of 10-millisecond units past time in CX.
2353 DosDateTimeToFileTime( DX_reg(context),
2354 CX_reg(context),
2355 &filetime );
2356 if (!SetFileTime( handle, &filetime, NULL, NULL ))
2357 return FALSE;
2358 break;
2361 default:
2362 INT_BARF( context, 0x21 );
2363 break;
2366 return TRUE;
2370 /***********************************************************************
2371 * INT21_GetPSP
2373 * Handler for functions 0x51 and 0x62.
2375 static void INT21_GetPSP( CONTEXT86 *context )
2377 TRACE( "GET CURRENT PSP ADDRESS (%02x)\n", AH_reg(context) );
2380 * FIXME: should we return the original DOS PSP upon
2381 * Windows startup ?
2383 if (!ISV86(context) && DOSVM_IsWin16())
2384 SET_BX( context, LOWORD(GetCurrentPDB16()) );
2385 else
2386 SET_BX( context, DOSVM_psp );
2389 static inline void setword( BYTE *ptr, WORD w )
2391 ptr[0] = (BYTE)w;
2392 ptr[1] = (BYTE)(w >> 8);
2395 static void CreateBPB(int drive, BYTE *data, BOOL16 limited)
2396 /* limited == TRUE is used with INT 0x21/0x440d */
2398 /* FIXME: we're forcing some values without checking that those are valid */
2399 if (drive > 1)
2401 setword(data, 512);
2402 data[2] = 2;
2403 setword(&data[3], 0);
2404 data[5] = 2;
2405 setword(&data[6], 240);
2406 setword(&data[8], 64000);
2407 data[0x0a] = 0xf8;
2408 setword(&data[0x0b], 40);
2409 setword(&data[0x0d], 56);
2410 setword(&data[0x0f], 2);
2411 setword(&data[0x11], 0);
2412 if (!limited)
2414 setword(&data[0x1f], 800);
2415 data[0x21] = 5;
2416 setword(&data[0x22], 1);
2419 else
2420 { /* 1.44mb */
2421 setword(data, 512);
2422 data[2] = 2;
2423 setword(&data[3], 0);
2424 data[5] = 2;
2425 setword(&data[6], 240);
2426 setword(&data[8], 2880);
2427 data[0x0a] = 0xf8;
2428 setword(&data[0x0b], 6);
2429 setword(&data[0x0d], 18);
2430 setword(&data[0x0f], 2);
2431 setword(&data[0x11], 0);
2432 if (!limited)
2434 setword(&data[0x1f], 80);
2435 data[0x21] = 7;
2436 setword(&data[0x22], 2);
2441 static inline DWORD INT21_Ioctl_CylHeadSect2Lin(DWORD cyl, WORD head, WORD sec, WORD cyl_cnt,
2442 WORD head_cnt, WORD sec_cnt)
2444 DWORD res = (cyl * head_cnt*sec_cnt + head * sec_cnt + sec);
2445 return res;
2448 /***********************************************************************
2449 * INT21_Ioctl_Block
2451 * Handler for block device IOCTLs.
2453 static void INT21_Ioctl_Block( CONTEXT86 *context )
2455 BYTE *dataptr;
2456 BYTE drive = INT21_MapDrive( BL_reg(context) );
2457 WCHAR drivespec[4] = {'A', ':', '\\', 0};
2458 UINT drivetype;
2460 drivespec[0] += drive;
2461 drivetype = GetDriveTypeW( drivespec );
2463 RESET_CFLAG(context);
2464 if (drivetype == DRIVE_UNKNOWN || drivetype == DRIVE_NO_ROOT_DIR)
2466 TRACE( "IOCTL - SUBFUNCTION %d - INVALID DRIVE %c:\n",
2467 AL_reg(context), 'A' + drive );
2468 SetLastError( ERROR_INVALID_DRIVE );
2469 SET_AX( context, ERROR_INVALID_DRIVE );
2470 SET_CFLAG( context );
2471 return;
2474 switch (AL_reg(context))
2476 case 0x04: /* READ FROM BLOCK DEVICE CONTROL CHANNEL */
2477 case 0x05: /* WRITE TO BLOCK DEVICE CONTROL CHANNEL */
2478 INT_BARF( context, 0x21 );
2479 break;
2481 case 0x08: /* CHECK IF BLOCK DEVICE REMOVABLE */
2482 TRACE( "IOCTL - CHECK IF BLOCK DEVICE REMOVABLE - %c:\n",
2483 'A' + drive );
2485 if (drivetype == DRIVE_REMOVABLE)
2486 SET_AX( context, 0 ); /* removable */
2487 else
2488 SET_AX( context, 1 ); /* not removable */
2489 break;
2491 case 0x09: /* CHECK IF BLOCK DEVICE REMOTE */
2492 TRACE( "IOCTL - CHECK IF BLOCK DEVICE REMOTE - %c:\n",
2493 'A' + drive );
2495 if (drivetype == DRIVE_REMOTE)
2496 SET_DX( context, (1<<9) | (1<<12) ); /* remote + no direct IO */
2497 else
2498 SET_DX( context, 0 ); /* FIXME: use driver attr here */
2499 break;
2501 case 0x0d: /* GENERIC BLOCK DEVICE REQUEST */
2502 /* Get pointer to IOCTL parameter block */
2503 dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
2505 switch (CX_reg(context))
2507 case 0x0841: /* write logical device track */
2508 TRACE( "GENERIC IOCTL - Write logical device track - %c:\n",
2509 'A' + drive);
2511 WORD head = *(WORD *)(dataptr+1);
2512 WORD cyl = *(WORD *)(dataptr+3);
2513 WORD sect = *(WORD *)(dataptr+5);
2514 WORD nrsect = *(WORD *)(dataptr+7);
2515 BYTE *data = CTX_SEG_OFF_TO_LIN(context, *(WORD *)(dataptr+11), *(WORD *)(dataptr+9));
2516 WORD cyl_cnt, head_cnt, sec_cnt;
2518 /* FIXME: we're faking some values here */
2519 if (drive > 1)
2521 /* cyl_cnt = 0x300;
2522 head_cnt = 16;
2523 sec_cnt = 255; */
2524 SET_AX( context, ERROR_WRITE_FAULT );
2525 SET_CFLAG(context);
2526 break;
2528 else
2529 { /* floppy */
2530 cyl_cnt = 80;
2531 head_cnt = 2;
2532 sec_cnt = 18;
2535 if (!DOSVM_RawWrite(drive, INT21_Ioctl_CylHeadSect2Lin(cyl, head, sect, cyl_cnt, head_cnt, sec_cnt), nrsect, data, FALSE))
2537 SET_AX( context, ERROR_WRITE_FAULT );
2538 SET_CFLAG(context);
2541 break;
2543 case 0x084a: /* lock logical volume */
2544 TRACE( "GENERIC IOCTL - Lock logical volume, level %d mode %d - %c:\n",
2545 BH_reg(context), DX_reg(context), 'A' + drive );
2546 break;
2548 case 0x0860: /* get device parameters */
2549 /* FIXME: we're faking some values here */
2550 /* used by w4wgrp's winfile */
2551 memset(dataptr, 0, 0x20); /* DOS 6.22 uses 0x20 bytes */
2552 dataptr[0] = 0x04;
2553 dataptr[6] = 0; /* media type */
2554 if (drive > 1)
2556 dataptr[1] = 0x05; /* fixed disk */
2557 setword(&dataptr[2], 0x01); /* non removable */
2558 setword(&dataptr[4], 0x300); /* # of cylinders */
2560 else
2562 dataptr[1] = 0x07; /* block dev, floppy */
2563 setword(&dataptr[2], 0x02); /* removable */
2564 setword(&dataptr[4], 80); /* # of cylinders */
2566 CreateBPB(drive, &dataptr[7], TRUE);
2567 RESET_CFLAG(context);
2568 break;
2570 case 0x0861: /* read logical device track */
2571 TRACE( "GENERIC IOCTL - Read logical device track - %c:\n",
2572 'A' + drive);
2574 WORD head = *(WORD *)(dataptr+1);
2575 WORD cyl = *(WORD *)(dataptr+3);
2576 WORD sect = *(WORD *)(dataptr+5);
2577 WORD nrsect = *(WORD *)(dataptr+7);
2578 BYTE *data = CTX_SEG_OFF_TO_LIN(context, *(WORD *)(dataptr+11), *(WORD *)(dataptr+9));
2579 WORD cyl_cnt, head_cnt, sec_cnt;
2581 /* FIXME: we're faking some values here */
2582 if (drive > 1)
2584 cyl_cnt = 0x300;
2585 head_cnt = 16;
2586 sec_cnt = 255;
2588 else
2589 { /* floppy */
2590 cyl_cnt = 80;
2591 head_cnt = 2;
2592 sec_cnt = 18;
2595 if (!DOSVM_RawRead(drive, INT21_Ioctl_CylHeadSect2Lin(cyl, head, sect, cyl_cnt, head_cnt, sec_cnt), nrsect, data, FALSE))
2597 SET_AX( context, ERROR_READ_FAULT );
2598 SET_CFLAG(context);
2601 break;
2603 case 0x0866: /* get volume serial number */
2605 WCHAR label[12],fsname[9];
2606 DWORD serial;
2608 drivespec[0] += drive;
2609 GetVolumeInformationW(drivespec, label, 12, &serial, NULL, NULL, fsname, 9);
2610 *(WORD*)dataptr = 0;
2611 memcpy(dataptr+2,&serial,4);
2612 WideCharToMultiByte(CP_OEMCP, 0, label, 11, (LPSTR)dataptr + 6, 11, NULL, NULL);
2613 WideCharToMultiByte(CP_OEMCP, 0, fsname, 8, (LPSTR)dataptr + 17, 8, NULL, NULL);
2615 break;
2617 case 0x086a: /* unlock logical volume */
2618 TRACE( "GENERIC IOCTL - Logical volume unlocked - %c:\n",
2619 'A' + drive );
2620 break;
2622 case 0x086f: /* get drive map information */
2623 memset(dataptr+1, '\0', dataptr[0]-1);
2624 dataptr[1] = dataptr[0];
2625 dataptr[2] = 0x07; /* protected mode driver; no eject; no notification */
2626 dataptr[3] = 0xFF; /* no physical drive */
2627 break;
2629 case 0x0872:
2630 /* Trial and error implementation */
2631 SET_AX( context, drivetype == DRIVE_UNKNOWN ? 0x0f : 0x01 );
2632 SET_CFLAG(context); /* Seems to be set all the time */
2633 break;
2635 default:
2636 INT_BARF( context, 0x21 );
2638 break;
2640 case 0x0e: /* GET LOGICAL DRIVE MAP */
2641 TRACE( "IOCTL - GET LOGICAL DRIVE MAP - %c:\n",
2642 'A' + drive );
2643 /* FIXME: this is not correct if drive has mappings */
2644 SET_AL( context, 0 ); /* drive has no mapping */
2645 break;
2647 case 0x0f: /* SET LOGICAL DRIVE MAP */
2648 TRACE("IOCTL - SET LOGICAL DRIVE MAP for drive %s\n",
2649 INT21_DriveName( BL_reg(context)));
2650 /* FIXME: as of today, we don't support logical drive mapping... */
2651 SET_AL( context, 0 );
2652 break;
2654 case 0x11: /* QUERY GENERIC IOCTL CAPABILITY */
2655 default:
2656 INT_BARF( context, 0x21 );
2661 /***********************************************************************
2662 * INT21_IoctlScsiMgrHandler
2664 * IOCTL handler for the SCSIMGR device.
2666 static void INT21_IoctlScsiMgrHandler( CONTEXT86 *context )
2668 switch (AL_reg(context))
2670 case 0x00: /* GET DEVICE INFORMATION */
2671 SET_DX( context, 0xc0c0 );
2672 break;
2674 case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
2675 DOSVM_ASPIHandler(context);
2676 break;
2678 case 0x0a: /* CHECK IF HANDLE IS REMOTE */
2679 SET_DX( context, 0 );
2680 break;
2682 case 0x01: /* SET DEVICE INFORMATION */
2683 case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
2684 case 0x06: /* GET INPUT STATUS */
2685 case 0x07: /* GET OUTPUT STATUS */
2686 case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
2687 case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
2688 default:
2689 INT_BARF( context, 0x21 );
2690 break;
2695 /***********************************************************************
2696 * INT21_IoctlHPScanHandler
2698 * IOCTL handler for the HPSCAN device.
2700 static void INT21_IoctlHPScanHandler( CONTEXT86 *context )
2702 switch (AL_reg(context))
2704 case 0x00: /* GET DEVICE INFORMATION */
2705 SET_DX( context, 0xc0c0 );
2706 break;
2708 case 0x0a: /* CHECK IF HANDLE IS REMOTE */
2709 SET_DX( context, 0 );
2710 break;
2712 case 0x01: /* SET DEVICE INFORMATION */
2713 case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
2714 case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
2715 case 0x06: /* GET INPUT STATUS */
2716 case 0x07: /* GET OUTPUT STATUS */
2717 case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
2718 case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
2719 default:
2720 INT_BARF( context, 0x21 );
2721 break;
2726 /***********************************************************************
2727 * INT21_Ioctl_Char
2729 * Handler for character device IOCTLs.
2731 static void INT21_Ioctl_Char( CONTEXT86 *context )
2733 int status;
2734 int IsConsoleIOHandle = 0;
2735 IO_STATUS_BLOCK io;
2736 FILE_INTERNAL_INFORMATION info;
2737 HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
2739 status = NtQueryInformationFile( handle, &io, &info, sizeof(info), FileInternalInformation );
2740 if (status)
2742 if( VerifyConsoleIoHandle( handle))
2743 IsConsoleIOHandle = 1;
2744 else {
2745 SET_AX( context, RtlNtStatusToDosError(status) );
2746 SET_CFLAG( context );
2747 return;
2749 } else {
2750 UINT i;
2751 for (i = 0; i < NB_MAGIC_DEVICES; i++)
2753 if (!magic_devices[i].handle) continue;
2754 if (magic_devices[i].index.QuadPart == info.IndexNumber.QuadPart)
2756 /* found it */
2757 magic_devices[i].ioctl_handler( context );
2758 return;
2763 /* no magic device found, do default handling */
2765 switch (AL_reg(context))
2767 case 0x00: /* GET DEVICE INFORMATION */
2768 TRACE( "IOCTL - GET DEVICE INFORMATION - %d\n", BX_reg(context) );
2769 if (IsConsoleIOHandle || GetFileType(handle) == FILE_TYPE_CHAR)
2772 * Returns attribute word in DX:
2773 * Bit 14 - Device driver can process IOCTL requests.
2774 * Bit 13 - Output until busy supported.
2775 * Bit 11 - Driver supports OPEN/CLOSE calls.
2776 * Bit 8 - Unknown.
2777 * Bit 7 - Set (indicates device).
2778 * Bit 6 - EOF on input.
2779 * Bit 5 - Raw (binary) mode.
2780 * Bit 4 - Device is special (uses int29).
2781 * Bit 3 - Clock device.
2782 * Bit 2 - NUL device.
2783 * Bit 1 - Console output device.
2784 * Bit 0 - Console input device.
2786 SET_DX( context, IsConsoleIOHandle ? 0x80c3 : 0x80c0 /* FIXME */ );
2788 else
2791 * Returns attribute word in DX:
2792 * Bit 15 - File is remote.
2793 * Bit 14 - Don't set file date/time on closing.
2794 * Bit 11 - Media not removable.
2795 * Bit 8 - Generate int24 if no disk space on write
2796 * or read past end of file
2797 * Bit 7 - Clear (indicates file).
2798 * Bit 6 - File has not been written.
2799 * Bit 5..0 - Drive number (0=A:,...)
2801 * FIXME: Should check if file is on remote or removable drive.
2802 * FIXME: Should use drive file is located on (and not current).
2804 SET_DX( context, 0x0140 + INT21_GetCurrentDrive() );
2806 break;
2808 case 0x0a: /* CHECK IF HANDLE IS REMOTE */
2809 TRACE( "IOCTL - CHECK IF HANDLE IS REMOTE - %d\n", BX_reg(context) );
2811 * Returns attribute word in DX:
2812 * Bit 15 - Set if remote.
2813 * Bit 14 - Set if date/time not set on close.
2815 * FIXME: Should check if file is on remote drive.
2817 SET_DX( context, 0 );
2818 break;
2820 case 0x01: /* SET DEVICE INFORMATION */
2821 case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
2822 case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
2823 case 0x06: /* GET INPUT STATUS */
2824 case 0x07: /* GET OUTPUT STATUS */
2825 case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
2826 case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
2827 default:
2828 INT_BARF( context, 0x21 );
2829 break;
2834 /***********************************************************************
2835 * INT21_Ioctl
2837 * Handler for function 0x44.
2839 static void INT21_Ioctl( CONTEXT86 *context )
2841 switch (AL_reg(context))
2843 case 0x00:
2844 case 0x01:
2845 case 0x02:
2846 case 0x03:
2847 INT21_Ioctl_Char( context );
2848 break;
2850 case 0x04:
2851 case 0x05:
2852 INT21_Ioctl_Block( context );
2853 break;
2855 case 0x06:
2856 case 0x07:
2857 INT21_Ioctl_Char( context );
2858 break;
2860 case 0x08:
2861 case 0x09:
2862 INT21_Ioctl_Block( context );
2863 break;
2865 case 0x0a:
2866 INT21_Ioctl_Char( context );
2867 break;
2869 case 0x0b: /* SET SHARING RETRY COUNT */
2870 TRACE( "SET SHARING RETRY COUNT: Pause %d, retries %d.\n",
2871 CX_reg(context), DX_reg(context) );
2872 if (!CX_reg(context))
2874 SET_AX( context, 1 );
2875 SET_CFLAG( context );
2877 else
2879 DOSDEV_SetSharingRetry( CX_reg(context), DX_reg(context) );
2880 RESET_CFLAG( context );
2882 break;
2884 case 0x0c:
2885 INT21_Ioctl_Char( context );
2886 break;
2888 case 0x0d:
2889 case 0x0e:
2890 case 0x0f:
2891 INT21_Ioctl_Block( context );
2892 break;
2894 case 0x10:
2895 INT21_Ioctl_Char( context );
2896 break;
2898 case 0x11:
2899 INT21_Ioctl_Block( context );
2900 break;
2902 case 0x12: /* DR DOS - DETERMINE DOS TYPE (OBSOLETE FUNCTION) */
2903 TRACE( "DR DOS - DETERMINE DOS TYPE (OBSOLETE FUNCTION)\n" );
2904 SET_CFLAG(context); /* Error / This is not DR DOS. */
2905 SET_AX( context, 0x0001 ); /* Invalid function */
2906 break;
2908 case 0x52: /* DR DOS - DETERMINE DOS TYPE */
2909 TRACE( "DR DOS - DETERMINE DOS TYPE\n" );
2910 SET_CFLAG(context); /* Error / This is not DR DOS. */
2911 SET_AX( context, 0x0001 ); /* Invalid function */
2912 break;
2914 case 0xe0: /* Sun PC-NFS API */
2915 TRACE( "Sun PC-NFS API\n" );
2916 /* not installed */
2917 break;
2919 default:
2920 INT_BARF( context, 0x21 );
2925 /***********************************************************************
2926 * INT21_Fat32
2928 * Handler for function 0x73.
2930 static BOOL INT21_Fat32( CONTEXT86 *context )
2932 switch (AL_reg(context))
2934 case 0x02: /* FAT32 - GET EXTENDED DPB */
2936 BYTE drive = INT21_MapDrive( DL_reg(context) );
2937 WORD *ptr = CTX_SEG_OFF_TO_LIN(context,
2938 context->SegEs, context->Edi);
2939 INT21_DPB *target = (INT21_DPB*)(ptr + 1);
2940 INT21_DPB *source;
2942 TRACE( "FAT32 - GET EXTENDED DPB %d\n", DL_reg(context) );
2944 if ( CX_reg(context) < sizeof(INT21_DPB) + 2 || *ptr < sizeof(INT21_DPB) )
2946 SetLastError( ERROR_BAD_LENGTH );
2947 return FALSE;
2950 if ( !INT21_FillDrivePB( drive ) )
2952 SetLastError( ERROR_INVALID_DRIVE );
2953 return FALSE;
2956 source = &INT21_GetHeapPointer()->misc_dpb_list[drive];
2958 *ptr = sizeof(INT21_DPB);
2959 *target = *source;
2961 if (LOWORD(context->Esi) != 0xF1A6)
2963 target->driver_header = 0;
2964 target->next = 0;
2966 else
2968 FIXME( "Caller requested driver and next DPB pointers!\n" );
2971 break;
2973 case 0x03: /* FAT32 - GET EXTENDED FREE SPACE ON DRIVE */
2975 WCHAR dirW[MAX_PATH];
2976 char *dirA = CTX_SEG_OFF_TO_LIN( context,
2977 context->SegDs, context->Edx );
2978 BYTE *data = CTX_SEG_OFF_TO_LIN( context,
2979 context->SegEs, context->Edi );
2980 DWORD cluster_sectors;
2981 DWORD sector_bytes;
2982 DWORD free_clusters;
2983 DWORD total_clusters;
2985 TRACE( "FAT32 - GET EXTENDED FREE SPACE ON DRIVE %s\n", dirA );
2986 MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
2988 if (CX_reg(context) < 44)
2990 SetLastError( ERROR_BAD_LENGTH );
2991 return FALSE;
2994 if (!GetDiskFreeSpaceW( dirW, &cluster_sectors, &sector_bytes,
2995 &free_clusters, &total_clusters ))
2996 return FALSE;
2998 *(WORD*) (data + 0) = 44; /* size of structure */
2999 *(WORD*) (data + 2) = 0; /* version */
3000 *(DWORD*)(data + 4) = cluster_sectors;
3001 *(DWORD*)(data + 8) = sector_bytes;
3002 *(DWORD*)(data + 12) = free_clusters;
3003 *(DWORD*)(data + 16) = total_clusters;
3006 * Below we have free/total sectors and
3007 * free/total allocation units without adjustment
3008 * for compression. We fake both using cluster information.
3010 *(DWORD*)(data + 20) = free_clusters * cluster_sectors;
3011 *(DWORD*)(data + 24) = total_clusters * cluster_sectors;
3012 *(DWORD*)(data + 28) = free_clusters;
3013 *(DWORD*)(data + 32) = total_clusters;
3016 * Between (data + 36) and (data + 43) there
3017 * are eight reserved bytes.
3020 break;
3022 default:
3023 INT_BARF( context, 0x21 );
3026 return TRUE;
3029 static void INT21_ConvertFindDataWtoA(WIN32_FIND_DATAA *dataA,
3030 const WIN32_FIND_DATAW *dataW)
3032 dataA->dwFileAttributes = dataW->dwFileAttributes;
3033 dataA->ftCreationTime = dataW->ftCreationTime;
3034 dataA->ftLastAccessTime = dataW->ftLastAccessTime;
3035 dataA->ftLastWriteTime = dataW->ftLastWriteTime;
3036 dataA->nFileSizeHigh = dataW->nFileSizeHigh;
3037 dataA->nFileSizeLow = dataW->nFileSizeLow;
3038 WideCharToMultiByte( CP_OEMCP, 0, dataW->cFileName, -1,
3039 dataA->cFileName, sizeof(dataA->cFileName), NULL, NULL );
3040 WideCharToMultiByte( CP_OEMCP, 0, dataW->cAlternateFileName, -1,
3041 dataA->cAlternateFileName, sizeof(dataA->cAlternateFileName), NULL, NULL );
3044 /***********************************************************************
3045 * INT21_LongFilename
3047 * Handler for function 0x71.
3049 static void INT21_LongFilename( CONTEXT86 *context )
3051 BOOL bSetDOSExtendedError = FALSE;
3052 WCHAR pathW[MAX_PATH];
3053 char* pathA;
3055 switch (AL_reg(context))
3057 case 0x0d: /* RESET DRIVE */
3058 INT_BARF( context, 0x21 );
3059 break;
3061 case 0x39: /* LONG FILENAME - MAKE DIRECTORY */
3062 if (!INT21_CreateDirectory( context ))
3063 bSetDOSExtendedError = TRUE;
3064 break;
3066 case 0x3a: /* LONG FILENAME - REMOVE DIRECTORY */
3067 pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3069 TRACE( "LONG FILENAME - REMOVE DIRECTORY %s\n", pathA);
3070 MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3071 if (!RemoveDirectoryW( pathW )) bSetDOSExtendedError = TRUE;
3072 break;
3074 case 0x3b: /* LONG FILENAME - CHANGE DIRECTORY */
3075 if (!INT21_SetCurrentDirectory( context ))
3076 bSetDOSExtendedError = TRUE;
3077 break;
3079 case 0x41: /* LONG FILENAME - DELETE FILE */
3080 pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3082 TRACE( "LONG FILENAME - DELETE FILE %s\n", pathA );
3083 MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3085 if (!DeleteFileW( pathW )) bSetDOSExtendedError = TRUE;
3086 break;
3088 case 0x43: /* LONG FILENAME - EXTENDED GET/SET FILE ATTRIBUTES */
3089 if (!INT21_FileAttributes( context, BL_reg(context), TRUE ))
3090 bSetDOSExtendedError = TRUE;
3091 break;
3093 case 0x47: /* LONG FILENAME - GET CURRENT DIRECTORY */
3094 if (!INT21_GetCurrentDirectory( context, TRUE ))
3095 bSetDOSExtendedError = TRUE;
3096 break;
3098 case 0x4e: /* LONG FILENAME - FIND FIRST MATCHING FILE */
3100 HANDLE handle;
3101 HGLOBAL16 h16;
3102 WIN32_FIND_DATAW dataW;
3103 WIN32_FIND_DATAA* dataA;
3105 pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx);
3106 TRACE(" LONG FILENAME - FIND FIRST MATCHING FILE for %s\n", pathA);
3108 MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3109 handle = FindFirstFileW(pathW, &dataW);
3111 dataA = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi);
3112 if (handle != INVALID_HANDLE_VALUE &&
3113 (h16 = GlobalAlloc16(GMEM_MOVEABLE, sizeof(handle))))
3115 HANDLE* ptr = GlobalLock16( h16 );
3116 *ptr = handle;
3117 GlobalUnlock16( h16 );
3118 SET_AX( context, h16 );
3119 INT21_ConvertFindDataWtoA(dataA, &dataW);
3121 else
3123 if (handle != INVALID_HANDLE_VALUE) FindClose(handle);
3124 SET_AX( context, INVALID_HANDLE_VALUE16);
3125 bSetDOSExtendedError = TRUE;
3128 break;
3130 case 0x4f: /* LONG FILENAME - FIND NEXT MATCHING FILE */
3132 HGLOBAL16 h16 = BX_reg(context);
3133 HANDLE* ptr;
3134 WIN32_FIND_DATAW dataW;
3135 WIN32_FIND_DATAA* dataA;
3137 TRACE("LONG FILENAME - FIND NEXT MATCHING FILE for handle %d\n",
3138 BX_reg(context));
3140 dataA = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi);
3142 if (h16 != INVALID_HANDLE_VALUE16 && (ptr = GlobalLock16( h16 )))
3144 if (!FindNextFileW(*ptr, &dataW)) bSetDOSExtendedError = TRUE;
3145 else INT21_ConvertFindDataWtoA(dataA, &dataW);
3146 GlobalUnlock16( h16 );
3148 else
3150 SetLastError( ERROR_INVALID_HANDLE );
3151 bSetDOSExtendedError = TRUE;
3154 break;
3156 case 0x56: /* LONG FILENAME - RENAME FILE */
3157 if (!INT21_RenameFile(context))
3158 bSetDOSExtendedError = TRUE;
3159 break;
3161 case 0x60: /* LONG FILENAME - CONVERT PATH */
3163 WCHAR res[MAX_PATH];
3165 switch (CL_reg(context))
3167 case 0x00: /* "truename" - Canonicalize path */
3169 * FIXME: This is not 100% equal to 0x01 case,
3170 * if you fix this, fix int21 subfunction 0x60, too.
3173 case 0x01: /* Get short filename or path */
3174 MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
3175 if (!GetShortPathNameW(pathW, res, 67))
3176 bSetDOSExtendedError = TRUE;
3177 else
3179 SET_AX( context, 0 );
3180 WideCharToMultiByte(CP_OEMCP, 0, res, -1,
3181 CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi),
3182 67, NULL, NULL);
3184 break;
3186 case 0x02: /* Get canonical long filename or path */
3187 MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
3188 if (!GetFullPathNameW(pathW, 128, res, NULL))
3189 bSetDOSExtendedError = TRUE;
3190 else
3192 SET_AX( context, 0 );
3193 WideCharToMultiByte(CP_OEMCP, 0, res, -1,
3194 CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi),
3195 128, NULL, NULL);
3197 break;
3198 default:
3199 FIXME("Unimplemented long file name function:\n");
3200 INT_BARF( context, 0x21 );
3201 SET_CFLAG(context);
3202 SET_AL( context, 0 );
3203 break;
3206 break;
3208 case 0x6c: /* LONG FILENAME - CREATE OR OPEN FILE */
3209 if (!INT21_CreateFile( context, context->Esi, TRUE,
3210 BX_reg(context), DL_reg(context) ))
3211 bSetDOSExtendedError = TRUE;
3212 break;
3214 case 0xa0: /* LONG FILENAME - GET VOLUME INFORMATION */
3216 DWORD filename_len, flags;
3217 WCHAR dstW[8];
3219 pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx);
3221 TRACE("LONG FILENAME - GET VOLUME INFORMATION for drive having root dir '%s'.\n", pathA);
3222 SET_AX( context, 0 );
3223 MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3224 if (!GetVolumeInformationW( pathW, NULL, 0, NULL, &filename_len,
3225 &flags, dstW, 8 ))
3227 INT_BARF( context, 0x21 );
3228 SET_CFLAG(context);
3229 break;
3231 SET_BX( context, flags | 0x4000 ); /* support for LFN functions */
3232 SET_CX( context, filename_len );
3233 SET_DX( context, MAX_PATH ); /* FIXME: which len if DRIVE_SHORT_NAMES ? */
3234 WideCharToMultiByte(CP_OEMCP, 0, dstW, -1,
3235 CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi),
3236 8, NULL, NULL);
3238 break;
3240 case 0xa1: /* LONG FILENAME - "FindClose" - TERMINATE DIRECTORY SEARCH */
3242 HGLOBAL16 h16 = BX_reg(context);
3243 HANDLE* ptr;
3245 TRACE("LONG FILENAME - FINDCLOSE for handle %d\n",
3246 BX_reg(context));
3247 if (h16 != INVALID_HANDLE_VALUE16 && (ptr = GlobalLock16( h16 )))
3249 if (!FindClose( *ptr )) bSetDOSExtendedError = TRUE;
3250 GlobalUnlock16( h16 );
3251 GlobalFree16( h16 );
3253 else
3255 SetLastError( ERROR_INVALID_HANDLE );
3256 bSetDOSExtendedError = TRUE;
3259 break;
3261 case 0xa6: /* LONG FILENAME - GET FILE INFO BY HANDLE */
3263 HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
3264 BY_HANDLE_FILE_INFORMATION *info =
3265 CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3267 TRACE( "LONG FILENAME - GET FILE INFO BY HANDLE\n" );
3269 if (!GetFileInformationByHandle(handle, info))
3270 bSetDOSExtendedError = TRUE;
3272 break;
3274 case 0xa7: /* LONG FILENAME - CONVERT TIME */
3275 switch (BL_reg(context))
3277 case 0x00: /* FILE TIME TO DOS TIME */
3279 WORD date, time;
3280 FILETIME *filetime = CTX_SEG_OFF_TO_LIN(context,
3281 context->SegDs,
3282 context->Esi);
3284 TRACE( "LONG FILENAME - FILE TIME TO DOS TIME\n" );
3286 FileTimeToDosDateTime( filetime, &date, &time );
3288 SET_DX( context, date );
3289 SET_CX( context, time );
3292 * FIXME: BH has number of 10-millisecond units
3293 * past time in CX.
3295 SET_BH( context, 0 );
3297 break;
3299 case 0x01: /* DOS TIME TO FILE TIME */
3301 FILETIME *filetime = CTX_SEG_OFF_TO_LIN(context,
3302 context->SegEs,
3303 context->Edi);
3305 TRACE( "LONG FILENAME - DOS TIME TO FILE TIME\n" );
3308 * FIXME: BH has number of 10-millisecond units
3309 * past time in CX.
3311 DosDateTimeToFileTime( DX_reg(context), CX_reg(context),
3312 filetime );
3314 break;
3316 default:
3317 INT_BARF( context, 0x21 );
3318 break;
3320 break;
3322 case 0xa8: /* LONG FILENAME - GENERATE SHORT FILENAME */
3323 case 0xa9: /* LONG FILENAME - SERVER CREATE OR OPEN FILE */
3324 case 0xaa: /* LONG FILENAME - SUBST */
3325 default:
3326 FIXME("Unimplemented long file name function:\n");
3327 INT_BARF( context, 0x21 );
3328 SET_CFLAG(context);
3329 SET_AL( context, 0 );
3330 break;
3333 if (bSetDOSExtendedError)
3335 SET_AX( context, GetLastError() );
3336 SET_CFLAG( context );
3341 /***********************************************************************
3342 * INT21_RenameFile
3344 * Handler for:
3345 * - function 0x56
3346 * - subfunction 0x56 of function 0x71
3347 * - subfunction 0xff of function 0x43 (CL == 0x56)
3349 static BOOL INT21_RenameFile( CONTEXT86 *context )
3351 WCHAR fromW[MAX_PATH];
3352 WCHAR toW[MAX_PATH];
3353 char *fromA = CTX_SEG_OFF_TO_LIN(context,
3354 context->SegDs,context->Edx);
3355 char *toA = CTX_SEG_OFF_TO_LIN(context,
3356 context->SegEs,context->Edi);
3358 TRACE( "RENAME FILE %s to %s\n", fromA, toA );
3359 MultiByteToWideChar(CP_OEMCP, 0, fromA, -1, fromW, MAX_PATH);
3360 MultiByteToWideChar(CP_OEMCP, 0, toA, -1, toW, MAX_PATH);
3362 return MoveFileW( fromW, toW );
3366 /***********************************************************************
3367 * INT21_NetworkFunc
3369 * Handler for:
3370 * - function 0x5e
3372 static BOOL INT21_NetworkFunc (CONTEXT86 *context)
3374 switch (AL_reg(context))
3376 case 0x00: /* Get machine name. */
3378 WCHAR dstW[MAX_COMPUTERNAME_LENGTH + 1];
3379 DWORD s = sizeof(dstW) / sizeof(WCHAR);
3380 int len;
3382 char *dst = CTX_SEG_OFF_TO_LIN (context,context->SegDs,context->Edx);
3383 TRACE("getting machine name to %p\n", dst);
3384 if (!GetComputerNameW(dstW, &s) ||
3385 !WideCharToMultiByte(CP_OEMCP, 0, dstW, -1, dst, 16, NULL, NULL))
3387 WARN("failed!\n");
3388 SetLastError( ER_NoNetwork );
3389 return TRUE;
3391 for (len = strlen(dst); len < 15; len++) dst[len] = ' ';
3392 dst[15] = 0;
3393 SET_CH( context, 1 ); /* Valid */
3394 SET_CL( context, 1 ); /* NETbios number??? */
3395 TRACE("returning %s\n", debugstr_an(dst, 16));
3396 return FALSE;
3399 default:
3400 SetLastError( ER_NoNetwork );
3401 return TRUE;
3405 /******************************************************************
3406 * INT21_GetDiskSerialNumber
3409 static int INT21_GetDiskSerialNumber( CONTEXT86 *context )
3411 BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3412 WCHAR path[] = {'A',':','\\',0}, label[11];
3413 DWORD serial;
3415 path[0] += INT21_MapDrive(BL_reg(context));
3416 if (!GetVolumeInformationW( path, label, 11, &serial, NULL, NULL, NULL, 0))
3418 SetLastError( ERROR_INVALID_DRIVE );
3419 return 0;
3422 *(WORD *)dataptr = 0;
3423 memcpy(dataptr + 2, &serial, sizeof(DWORD));
3424 WideCharToMultiByte(CP_OEMCP, 0, label, 11, (LPSTR)dataptr + 6, 11, NULL, NULL);
3425 memcpy(dataptr + 17, "FAT16 ", 8);
3426 return 1;
3430 /******************************************************************
3431 * INT21_SetDiskSerialNumber
3434 static int INT21_SetDiskSerialNumber( CONTEXT86 *context )
3436 #if 0
3437 BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3438 int drive = INT21_MapDrive(BL_reg(context));
3440 if (!is_valid_drive(drive))
3442 SetLastError( ERROR_INVALID_DRIVE );
3443 return 0;
3446 DRIVE_SetSerialNumber( drive, *(DWORD *)(dataptr + 2) );
3447 return 1;
3448 #else
3449 FIXME("Setting drive serial number is no longer supported\n");
3450 SetLastError( ERROR_NOT_SUPPORTED );
3451 return 0;
3452 #endif
3456 /******************************************************************
3457 * INT21_GetFreeDiskSpace
3460 static int INT21_GetFreeDiskSpace( CONTEXT86 *context )
3462 DWORD cluster_sectors, sector_bytes, free_clusters, total_clusters;
3463 WCHAR root[] = {'A',':','\\',0};
3464 const DWORD max_clusters = 0x3d83;
3465 const DWORD max_sectors_per_cluster = 0x7f;
3466 const DWORD max_bytes_per_sector = 0x200;
3468 root[0] += INT21_MapDrive(DL_reg(context));
3469 if (!GetDiskFreeSpaceW( root, &cluster_sectors, &sector_bytes,
3470 &free_clusters, &total_clusters )) return 0;
3472 /* Some old win31 apps (Lotus SmartSuite 5.1) crap out if there's too
3473 * much disk space, so Windows XP seems to apply the following limits:
3474 * cluster_sectors <= 0x7f
3475 * sector size <= 0x200
3476 * clusters <= 0x3D83
3477 * This means total reported space is limited to about 1GB.
3480 /* Make sure bytes-per-sector is in [, max] */
3481 while (sector_bytes > max_bytes_per_sector) {
3482 sector_bytes >>= 1;
3483 free_clusters <<= 1;
3484 total_clusters <<= 1;
3486 /* Then make sure sectors-per-cluster is in [max/2, max]. */
3487 while (cluster_sectors <= max_sectors_per_cluster/2) {
3488 cluster_sectors <<= 1;
3489 free_clusters >>= 1;
3490 total_clusters >>= 1;
3492 while (cluster_sectors > max_sectors_per_cluster) {
3493 cluster_sectors >>= 1;
3494 free_clusters <<= 1;
3495 total_clusters <<= 1;
3498 /* scale up sectors_per_cluster to exactly max_sectors_per_cluster.
3499 * We could skip this, but that would impose an artificially low
3500 * limit on reported disk space.
3501 * To avoid overflow, first apply a preliminary cap on sector count;
3502 * this will not affect the correctness of the final result,
3503 * because if the preliminary cap hits, the final one will, too.
3505 if (total_clusters > 4 * max_clusters)
3506 total_clusters = 4 * max_clusters;
3507 if (free_clusters > 4 * max_clusters)
3508 free_clusters = 4 * max_clusters;
3509 if (cluster_sectors < max_sectors_per_cluster) {
3510 free_clusters *= cluster_sectors;
3511 free_clusters /= max_sectors_per_cluster;
3512 total_clusters *= cluster_sectors;
3513 total_clusters /= max_sectors_per_cluster;
3514 cluster_sectors = max_sectors_per_cluster;
3517 /* Finally, apply real cluster count cap. */
3518 if (total_clusters > max_clusters)
3519 total_clusters = max_clusters;
3520 if (free_clusters > max_clusters)
3521 free_clusters = max_clusters;
3523 SET_AX( context, cluster_sectors );
3524 SET_BX( context, free_clusters );
3525 SET_CX( context, sector_bytes );
3526 SET_DX( context, total_clusters );
3527 return 1;
3530 /******************************************************************
3531 * INT21_GetDriveAllocInfo
3534 static int INT21_GetDriveAllocInfo( CONTEXT86 *context, BYTE drive )
3536 INT21_DPB *dpb;
3538 drive = INT21_MapDrive( drive );
3539 if (!INT21_FillDrivePB( drive )) return 0;
3540 dpb = &(INT21_GetHeapPointer()->misc_dpb_list[drive]);
3541 SET_AL( context, dpb->cluster_sectors + 1 );
3542 SET_CX( context, dpb->sector_bytes );
3543 SET_DX( context, dpb->num_clusters1 );
3545 context->SegDs = INT21_GetHeapSelector( context );
3546 SET_BX( context, offsetof( INT21_HEAP, misc_dpb_list[drive].media_ID ) );
3547 return 1;
3550 /***********************************************************************
3551 * INT21_GetExtendedError
3553 static void INT21_GetExtendedError( CONTEXT86 *context )
3555 BYTE class, action, locus;
3556 WORD error = GetLastError();
3558 switch(error)
3560 case ERROR_SUCCESS:
3561 class = action = locus = 0;
3562 break;
3563 case ERROR_DIR_NOT_EMPTY:
3564 class = EC_Exists;
3565 action = SA_Ignore;
3566 locus = EL_Disk;
3567 break;
3568 case ERROR_ACCESS_DENIED:
3569 class = EC_AccessDenied;
3570 action = SA_Abort;
3571 locus = EL_Disk;
3572 break;
3573 case ERROR_CANNOT_MAKE:
3574 class = EC_AccessDenied;
3575 action = SA_Abort;
3576 locus = EL_Unknown;
3577 break;
3578 case ERROR_DISK_FULL:
3579 case ERROR_HANDLE_DISK_FULL:
3580 class = EC_MediaError;
3581 action = SA_Abort;
3582 locus = EL_Disk;
3583 break;
3584 case ERROR_FILE_EXISTS:
3585 case ERROR_ALREADY_EXISTS:
3586 class = EC_Exists;
3587 action = SA_Abort;
3588 locus = EL_Disk;
3589 break;
3590 case ERROR_FILE_NOT_FOUND:
3591 case ERROR_PATH_NOT_FOUND:
3592 case ERROR_INVALID_NAME:
3593 class = EC_NotFound;
3594 action = SA_Abort;
3595 locus = EL_Disk;
3596 break;
3597 case ERROR_GEN_FAILURE:
3598 class = EC_SystemFailure;
3599 action = SA_Abort;
3600 locus = EL_Unknown;
3601 break;
3602 case ERROR_INVALID_DRIVE:
3603 class = EC_MediaError;
3604 action = SA_Abort;
3605 locus = EL_Disk;
3606 break;
3607 case ERROR_INVALID_HANDLE:
3608 class = EC_ProgramError;
3609 action = SA_Abort;
3610 locus = EL_Disk;
3611 break;
3612 case ERROR_LOCK_VIOLATION:
3613 class = EC_AccessDenied;
3614 action = SA_Abort;
3615 locus = EL_Disk;
3616 break;
3617 case ERROR_NO_MORE_FILES:
3618 class = EC_MediaError;
3619 action = SA_Abort;
3620 locus = EL_Disk;
3621 break;
3622 case ER_NoNetwork:
3623 class = EC_NotFound;
3624 action = SA_Abort;
3625 locus = EL_Network;
3626 break;
3627 case ERROR_NOT_ENOUGH_MEMORY:
3628 class = EC_OutOfResource;
3629 action = SA_Abort;
3630 locus = EL_Memory;
3631 break;
3632 case ERROR_SEEK:
3633 class = EC_NotFound;
3634 action = SA_Ignore;
3635 locus = EL_Disk;
3636 break;
3637 case ERROR_SHARING_VIOLATION:
3638 class = EC_Temporary;
3639 action = SA_Retry;
3640 locus = EL_Disk;
3641 break;
3642 case ERROR_TOO_MANY_OPEN_FILES:
3643 class = EC_ProgramError;
3644 action = SA_Abort;
3645 locus = EL_Disk;
3646 break;
3647 default:
3648 FIXME("Unknown error %d\n", error );
3649 class = EC_SystemFailure;
3650 action = SA_Abort;
3651 locus = EL_Unknown;
3652 break;
3654 TRACE("GET EXTENDED ERROR code 0x%02x class 0x%02x action 0x%02x locus %02x\n",
3655 error, class, action, locus );
3656 SET_AX( context, error );
3657 SET_BH( context, class );
3658 SET_BL( context, action );
3659 SET_CH( context, locus );
3662 static BOOL INT21_CreateTempFile( CONTEXT86 *context )
3664 static int counter = 0;
3665 char *name = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx );
3666 char *p = name + strlen(name);
3668 /* despite what Ralf Brown says, some programs seem to call without
3669 * ending backslash (DOS accepts that, so we accept it too) */
3670 if ((p == name) || (p[-1] != '\\')) *p++ = '\\';
3672 for (;;)
3674 sprintf( p, "wine%04x.%03d", (int)getpid(), counter );
3675 counter = (counter + 1) % 1000;
3677 SET_AX( context,
3678 Win32HandleToDosFileHandle(
3679 CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
3680 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
3681 CREATE_NEW, 0, 0 ) ) );
3682 if (AX_reg(context) != HFILE_ERROR16)
3684 TRACE("created %s\n", name );
3685 return TRUE;
3687 if (GetLastError() != ERROR_FILE_EXISTS) return FALSE;
3691 /***********************************************************************
3692 * DOSFS_ToDosFCBFormat
3694 * Convert a file name to DOS FCB format (8+3 chars, padded with blanks),
3695 * expanding wild cards and converting to upper-case in the process.
3696 * File name can be terminated by '\0', '\\' or '/'.
3697 * Return FALSE if the name is not a valid DOS name.
3698 * 'buffer' must be at least 12 characters long.
3700 /* Chars we don't want to see in DOS file names */
3701 static BOOL INT21_ToDosFCBFormat( LPCWSTR name, LPWSTR buffer )
3703 static const WCHAR invalid_chars[] = {'*','?','<','>','|','\\','"','+','=',',',';','[',']',' ','\345',0};
3704 LPCWSTR p = name;
3705 int i;
3707 /* Check for "." and ".." */
3708 if (*p == '.')
3710 p++;
3711 buffer[0] = '.';
3712 for(i = 1; i < 11; i++) buffer[i] = ' ';
3713 buffer[11] = 0;
3714 if (*p == '.')
3716 buffer[1] = '.';
3717 p++;
3719 return (!*p || (*p == '/') || (*p == '\\'));
3722 for (i = 0; i < 8; i++)
3724 switch(*p)
3726 case '\0':
3727 case '\\':
3728 case '/':
3729 case '.':
3730 buffer[i] = ' ';
3731 break;
3732 case '?':
3733 p++;
3734 /* fall through */
3735 case '*':
3736 buffer[i] = '?';
3737 break;
3738 default:
3739 if (strchrW( invalid_chars, *p )) return FALSE;
3740 buffer[i] = toupperW(*p);
3741 p++;
3742 break;
3746 if (*p == '*')
3748 /* Skip all chars after wildcard up to first dot */
3749 while (*p && (*p != '/') && (*p != '\\') && (*p != '.')) p++;
3751 else
3753 /* Check if name too long */
3754 if (*p && (*p != '/') && (*p != '\\') && (*p != '.')) return FALSE;
3756 if (*p == '.') p++; /* Skip dot */
3758 for (i = 8; i < 11; i++)
3760 switch(*p)
3762 case '\0':
3763 case '\\':
3764 case '/':
3765 buffer[i] = ' ';
3766 break;
3767 case '.':
3768 return FALSE; /* Second extension not allowed */
3769 case '?':
3770 p++;
3771 /* fall through */
3772 case '*':
3773 buffer[i] = '?';
3774 break;
3775 default:
3776 if (strchrW( invalid_chars, *p )) return FALSE;
3777 buffer[i] = toupperW(*p);
3778 p++;
3779 break;
3782 buffer[11] = '\0';
3784 /* at most 3 character of the extension are processed
3785 * is something behind this ?
3787 while (*p == '*' || *p == ' ') p++; /* skip wildcards and spaces */
3788 return (!*p || (*p == '/') || (*p == '\\'));
3791 static HANDLE INT21_FindHandle;
3792 static const WCHAR *INT21_FindPath; /* will point to current dta->fullPath search */
3794 /******************************************************************
3795 * INT21_FindFirst
3797 static int INT21_FindFirst( CONTEXT86 *context )
3799 WCHAR *p, *q;
3800 const char *path;
3801 FINDFILE_DTA *dta = (FINDFILE_DTA *)INT21_GetCurrentDTA(context);
3802 WCHAR maskW[12], pathW[MAX_PATH];
3803 static const WCHAR wildcardW[] = {'*','.','*',0};
3805 path = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3806 MultiByteToWideChar(CP_OEMCP, 0, path, -1, pathW, MAX_PATH);
3808 p = strrchrW( pathW, '\\');
3809 q = strrchrW( pathW, '/');
3810 if (q>p) p = q;
3811 if (!p)
3813 if (pathW[0] && pathW[1] == ':') p = pathW + 2;
3814 else p = pathW;
3816 else p++;
3818 /* Note: terminating NULL in dta->mask overwrites dta->search_attr
3819 * (doesn't matter as it is set below anyway)
3821 if (!INT21_ToDosFCBFormat( p, maskW ))
3823 SetLastError( ERROR_FILE_NOT_FOUND );
3824 SET_AX( context, ERROR_FILE_NOT_FOUND );
3825 SET_CFLAG(context);
3826 return 0;
3828 WideCharToMultiByte(CP_OEMCP, 0, maskW, 12, dta->mask, sizeof(dta->mask), NULL, NULL);
3830 dta->fullPath = HeapAlloc( GetProcessHeap(), 0, sizeof(wildcardW) + (p - pathW)*sizeof(WCHAR) );
3831 memcpy( dta->fullPath, pathW, (p - pathW) * sizeof(WCHAR) );
3832 memcpy( dta->fullPath + (p - pathW), wildcardW, sizeof(wildcardW) );
3833 /* we must have a fully qualified file name in dta->fullPath
3834 * (we could have a UNC path, but this would lead to some errors later on)
3836 dta->drive = toupperW(dta->fullPath[0]) - 'A';
3837 dta->count = 0;
3838 dta->search_attr = CL_reg(context);
3839 return 1;
3842 /******************************************************************
3843 * match_short
3845 * Check is a short path name (DTA unicode) matches a mask (FCB ansi)
3847 static BOOL match_short(LPCWSTR shortW, LPCSTR maskA)
3849 WCHAR mask[11], file[12];
3850 int i;
3852 if (!INT21_ToDosFCBFormat( shortW, file )) return FALSE;
3853 MultiByteToWideChar(CP_OEMCP, 0, maskA, 11, mask, 11);
3854 for (i = 0; i < 11; i++)
3855 if (mask[i] != '?' && mask[i] != file[i]) return FALSE;
3856 return TRUE;
3859 static unsigned INT21_FindHelper(LPCWSTR fullPath, unsigned drive, unsigned count,
3860 LPCSTR mask, unsigned search_attr,
3861 WIN32_FIND_DATAW* entry)
3863 unsigned ncalls;
3865 if ((search_attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
3867 WCHAR path[] = {' ',':','\\',0};
3869 if (count) return 0;
3870 path[0] = drive + 'A';
3871 if (!GetVolumeInformationW(path, entry->cAlternateFileName, 13, NULL, NULL, NULL, NULL, 0)) return 0;
3872 RtlSecondsSince1970ToTime( 0, (LARGE_INTEGER *)&entry->ftCreationTime );
3873 RtlSecondsSince1970ToTime( 0, (LARGE_INTEGER *)&entry->ftLastAccessTime );
3874 RtlSecondsSince1970ToTime( 0, (LARGE_INTEGER *)&entry->ftLastWriteTime );
3875 entry->dwFileAttributes = FA_LABEL;
3876 entry->nFileSizeHigh = entry->nFileSizeLow = 0;
3877 TRACE("returning %s as label\n", debugstr_w(entry->cAlternateFileName));
3878 return 1;
3881 if (!INT21_FindHandle || INT21_FindPath != fullPath || count == 0)
3883 if (INT21_FindHandle) FindClose(INT21_FindHandle);
3884 INT21_FindHandle = FindFirstFileW(fullPath, entry);
3885 if (INT21_FindHandle == INVALID_HANDLE_VALUE)
3887 INT21_FindHandle = 0;
3888 return 0;
3890 INT21_FindPath = fullPath;
3891 /* we need to resync search */
3892 ncalls = count;
3894 else ncalls = 1;
3896 while (ncalls-- != 0)
3898 if (!FindNextFileW(INT21_FindHandle, entry))
3900 FindClose(INT21_FindHandle); INT21_FindHandle = 0;
3901 return 0;
3904 while (count < 0xffff)
3906 count++;
3907 /* Check the file attributes, and path */
3908 if (!(entry->dwFileAttributes & ~search_attr) &&
3909 match_short(entry->cAlternateFileName[0] ? entry->cAlternateFileName : entry->cFileName,
3910 mask))
3912 return count;
3914 if (!FindNextFileW(INT21_FindHandle, entry))
3916 FindClose(INT21_FindHandle); INT21_FindHandle = 0;
3917 return 0;
3920 WARN("Too many directory entries in %s\n", debugstr_w(fullPath) );
3921 return 0;
3924 /******************************************************************
3925 * INT21_FindNext
3927 static int INT21_FindNext( CONTEXT86 *context )
3929 FINDFILE_DTA *dta = (FINDFILE_DTA *)INT21_GetCurrentDTA(context);
3930 DWORD attr = dta->search_attr | FA_UNUSED | FA_ARCHIVE | FA_RDONLY;
3931 WIN32_FIND_DATAW entry;
3932 int n;
3934 if (!dta->fullPath) return 0;
3936 n = INT21_FindHelper(dta->fullPath, dta->drive, dta->count,
3937 dta->mask, attr, &entry);
3938 if (n)
3940 dta->fileattr = entry.dwFileAttributes;
3941 dta->filesize = entry.nFileSizeLow;
3942 FileTimeToDosDateTime( &entry.ftLastWriteTime, &dta->filedate, &dta->filetime );
3943 if (entry.cAlternateFileName[0])
3944 WideCharToMultiByte(CP_OEMCP, 0, entry.cAlternateFileName, -1,
3945 dta->filename, 13, NULL, NULL);
3946 else
3947 WideCharToMultiByte(CP_OEMCP, 0, entry.cFileName, -1, dta->filename, 13, NULL, NULL);
3949 if (!memchr(dta->mask,'?',11))
3951 /* wildcardless search, release resources in case no findnext will
3952 * be issued, and as a workaround in case file creation messes up
3953 * findnext, as sometimes happens with pkunzip
3955 HeapFree( GetProcessHeap(), 0, dta->fullPath );
3956 INT21_FindPath = dta->fullPath = NULL;
3958 dta->count = n;
3959 return 1;
3961 HeapFree( GetProcessHeap(), 0, dta->fullPath );
3962 INT21_FindPath = dta->fullPath = NULL;
3963 return 0;
3966 /* microsoft's programmers should be shot for using CP/M style int21
3967 calls in Windows for Workgroup's winfile.exe */
3969 /******************************************************************
3970 * INT21_FindFirstFCB
3973 static int INT21_FindFirstFCB( CONTEXT86 *context )
3975 BYTE *fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3976 FINDFILE_FCB *pFCB;
3977 int drive;
3978 WCHAR p[] = {' ',':',};
3980 if (*fcb == 0xff) pFCB = (FINDFILE_FCB *)(fcb + 7);
3981 else pFCB = (FINDFILE_FCB *)fcb;
3982 drive = INT21_MapDrive( pFCB->drive );
3983 if (drive == MAX_DOS_DRIVES) return 0;
3985 p[0] = 'A' + drive;
3986 pFCB->fullPath = HeapAlloc(GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR));
3987 if (!pFCB->fullPath) return 0;
3988 GetLongPathNameW(p, pFCB->fullPath, MAX_PATH);
3989 pFCB->count = 0;
3990 return 1;
3993 /******************************************************************
3994 * INT21_FindNextFCB
3997 static int INT21_FindNextFCB( CONTEXT86 *context )
3999 BYTE *fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
4000 FINDFILE_FCB *pFCB;
4001 LPBYTE pResult = INT21_GetCurrentDTA(context);
4002 DOS_DIRENTRY_LAYOUT *ddl;
4003 WIN32_FIND_DATAW entry;
4004 BYTE attr;
4005 int n;
4006 WCHAR nameW[12];
4008 if (*fcb == 0xff) /* extended FCB ? */
4010 attr = fcb[6];
4011 pFCB = (FINDFILE_FCB *)(fcb + 7);
4013 else
4015 attr = 0;
4016 pFCB = (FINDFILE_FCB *)fcb;
4019 if (!pFCB->fullPath) return 0;
4020 n = INT21_FindHelper(pFCB->fullPath, INT21_MapDrive( pFCB->drive ),
4021 pFCB->count, pFCB->filename, attr, &entry);
4022 if (!n)
4024 HeapFree( GetProcessHeap(), 0, pFCB->fullPath );
4025 INT21_FindPath = pFCB->fullPath = NULL;
4026 return 0;
4028 pFCB->count += n;
4030 if (*fcb == 0xff)
4032 /* place extended FCB header before pResult if called with extended FCB */
4033 *pResult = 0xff;
4034 pResult += 6; /* leave reserved field behind */
4035 *pResult++ = entry.dwFileAttributes;
4037 *pResult++ = INT21_MapDrive( pFCB->drive ); /* DOS_DIRENTRY_LAYOUT after current drive number */
4038 ddl = (DOS_DIRENTRY_LAYOUT*)pResult;
4039 ddl->fileattr = entry.dwFileAttributes;
4040 ddl->cluster = 0; /* what else? */
4041 ddl->filesize = entry.nFileSizeLow;
4042 memset( ddl->reserved, 0, sizeof(ddl->reserved) );
4043 FileTimeToDosDateTime( &entry.ftLastWriteTime,
4044 &ddl->filedate, &ddl->filetime );
4046 /* Convert file name to FCB format */
4047 if (entry.cAlternateFileName[0])
4048 INT21_ToDosFCBFormat( entry.cAlternateFileName, nameW );
4049 else
4050 INT21_ToDosFCBFormat( entry.cFileName, nameW );
4051 WideCharToMultiByte(CP_OEMCP, 0, nameW, 11, ddl->filename, 11, NULL, NULL);
4052 return 1;
4056 /******************************************************************
4057 * INT21_ParseFileNameIntoFCB
4060 static void INT21_ParseFileNameIntoFCB( CONTEXT86 *context )
4062 char *filename =
4063 CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi );
4064 char *fcb =
4065 CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi );
4066 char *s;
4067 WCHAR *buffer;
4068 WCHAR fcbW[12];
4069 INT buffer_len, len;
4071 SET_AL( context, 0xff ); /* failed */
4073 TRACE("filename: '%s'\n", filename);
4075 s = filename;
4076 while (*s && (*s != ' ') && (*s != '\r') && (*s != '\n'))
4077 s++;
4078 len = filename - s;
4080 buffer_len = MultiByteToWideChar(CP_OEMCP, 0, filename, len, NULL, 0);
4081 buffer = HeapAlloc( GetProcessHeap(), 0, (buffer_len + 1) * sizeof(WCHAR));
4082 len = MultiByteToWideChar(CP_OEMCP, 0, filename, len, buffer, buffer_len);
4083 buffer[len] = 0;
4084 INT21_ToDosFCBFormat(buffer, fcbW);
4085 HeapFree(GetProcessHeap(), 0, buffer);
4086 WideCharToMultiByte(CP_OEMCP, 0, fcbW, 12, fcb + 1, 12, NULL, NULL);
4087 *fcb = 0;
4088 TRACE("FCB: '%s'\n", fcb + 1);
4090 SET_AL( context, ((strchr(filename, '*')) || (strchr(filename, '$'))) != 0 );
4092 /* point DS:SI to first unparsed character */
4093 SET_SI( context, context->Esi + (int)s - (int)filename );
4096 static BOOL INT21_Dup2(HFILE16 hFile1, HFILE16 hFile2)
4098 HFILE16 res = HFILE_ERROR16;
4099 HANDLE handle, new_handle;
4100 #define DOS_TABLE_SIZE 256
4101 DWORD map[DOS_TABLE_SIZE / 32];
4102 int i;
4104 handle = DosFileHandleToWin32Handle(hFile1);
4105 if (handle == INVALID_HANDLE_VALUE)
4106 return FALSE;
4108 _lclose16(hFile2);
4109 /* now loop to allocate the same one... */
4110 memset(map, 0, sizeof(map));
4111 for (i = 0; i < DOS_TABLE_SIZE; i++)
4113 if (!DuplicateHandle(GetCurrentProcess(), handle,
4114 GetCurrentProcess(), &new_handle,
4115 0, FALSE, DUPLICATE_SAME_ACCESS))
4117 res = HFILE_ERROR16;
4118 break;
4120 res = Win32HandleToDosFileHandle(new_handle);
4121 if (res == HFILE_ERROR16 || res == hFile2) break;
4122 map[res / 32] |= 1 << (res % 32);
4124 /* clean up the allocated slots */
4125 for (i = 0; i < DOS_TABLE_SIZE; i++)
4127 if (map[i / 32] & (1 << (i % 32)))
4128 _lclose16((HFILE16)i);
4130 return res == hFile2;
4134 /***********************************************************************
4135 * DOSVM_Int21Handler
4137 * Interrupt 0x21 handler.
4139 void WINAPI DOSVM_Int21Handler( CONTEXT86 *context )
4141 BOOL bSetDOSExtendedError = FALSE;
4143 TRACE( "AX=%04x BX=%04x CX=%04x DX=%04x "
4144 "SI=%04x DI=%04x DS=%04x ES=%04x EFL=%08x\n",
4145 AX_reg(context), BX_reg(context),
4146 CX_reg(context), DX_reg(context),
4147 SI_reg(context), DI_reg(context),
4148 (WORD)context->SegDs, (WORD)context->SegEs,
4149 context->EFlags );
4152 * Extended error is used by (at least) functions 0x2f to 0x62.
4153 * Function 0x59 returns extended error and error should not
4154 * be cleared before handling the function.
4156 if (AH_reg(context) >= 0x2f && AH_reg(context) != 0x59)
4157 SetLastError(0);
4159 RESET_CFLAG(context); /* Not sure if this is a good idea. */
4161 switch(AH_reg(context))
4163 case 0x00: /* TERMINATE PROGRAM */
4164 TRACE("TERMINATE PROGRAM\n");
4165 if (DOSVM_IsWin16())
4166 DOSVM_Exit( 0 );
4167 else if(ISV86(context))
4168 MZ_Exit( context, FALSE, 0 );
4169 else
4170 ERR( "Called from DOS protected mode\n" );
4171 break;
4173 case 0x01: /* READ CHARACTER FROM STANDARD INPUT, WITH ECHO */
4175 BYTE ascii;
4176 TRACE("DIRECT CHARACTER INPUT WITH ECHO\n");
4177 INT21_ReadChar( &ascii, context );
4178 SET_AL( context, ascii );
4180 * FIXME: What to echo when extended keycodes are read?
4182 DOSVM_PutChar(AL_reg(context));
4184 break;
4186 case 0x02: /* WRITE CHARACTER TO STANDARD OUTPUT */
4187 TRACE("Write Character to Standard Output\n");
4188 DOSVM_PutChar(DL_reg(context));
4189 break;
4191 case 0x03: /* READ CHARACTER FROM STDAUX */
4192 case 0x04: /* WRITE CHARACTER TO STDAUX */
4193 case 0x05: /* WRITE CHARACTER TO PRINTER */
4194 INT_BARF( context, 0x21 );
4195 break;
4197 case 0x06: /* DIRECT CONSOLE IN/OUTPUT */
4198 if (DL_reg(context) == 0xff)
4200 TRACE("Direct Console Input\n");
4202 if (INT21_ReadChar( NULL, NULL ))
4204 BYTE ascii;
4205 INT21_ReadChar( &ascii, context );
4206 SET_AL( context, ascii );
4207 RESET_ZFLAG( context );
4209 else
4211 /* no character available */
4212 SET_AL( context, 0 );
4213 SET_ZFLAG( context );
4216 else
4218 TRACE("Direct Console Output\n");
4219 DOSVM_PutChar(DL_reg(context));
4221 * At least DOS versions 2.1-7.0 return character
4222 * that was written in AL register.
4224 SET_AL( context, DL_reg(context) );
4226 break;
4228 case 0x07: /* DIRECT CHARACTER INPUT WITHOUT ECHO */
4230 BYTE ascii;
4231 TRACE("DIRECT CHARACTER INPUT WITHOUT ECHO\n");
4232 INT21_ReadChar( &ascii, context );
4233 SET_AL( context, ascii );
4235 break;
4237 case 0x08: /* CHARACTER INPUT WITHOUT ECHO */
4239 BYTE ascii;
4240 TRACE("CHARACTER INPUT WITHOUT ECHO\n");
4241 INT21_ReadChar( &ascii, context );
4242 SET_AL( context, ascii );
4244 break;
4246 case 0x09: /* WRITE STRING TO STANDARD OUTPUT */
4247 TRACE("WRITE '$'-terminated string from %04X:%04X to stdout\n",
4248 context->SegDs, DX_reg(context) );
4250 LPSTR data = CTX_SEG_OFF_TO_LIN( context,
4251 context->SegDs, context->Edx );
4252 LPSTR p = data;
4253 DWORD w;
4255 * Do NOT use strchr() to calculate the string length,
4256 * as '\0' is valid string content, too!
4257 * Maybe we should check for non-'$' strings, but DOS doesn't.
4259 while (*p != '$') p++;
4261 if (DOSVM_IsWin16())
4262 WriteFile( DosFileHandleToWin32Handle(1),
4263 data, p - data, &w, NULL );
4264 else
4265 for(; data != p; data++)
4266 DOSVM_PutChar( *data );
4268 SET_AL( context, '$' ); /* yes, '$' (0x24) gets returned in AL */
4270 break;
4272 case 0x0a: /* BUFFERED INPUT */
4274 BYTE *ptr = CTX_SEG_OFF_TO_LIN(context,
4275 context->SegDs,
4276 context->Edx);
4277 WORD result;
4279 TRACE( "BUFFERED INPUT (size=%d)\n", ptr[0] );
4282 * FIXME: Some documents state that
4283 * ptr[1] holds number of chars from last input which
4284 * may be recalled on entry, other documents do not mention
4285 * this at all.
4287 if (ptr[1])
4288 TRACE( "Handle old chars in buffer!\n" );
4291 * ptr[0] - capacity (includes terminating CR)
4292 * ptr[1] - characters read (excludes terminating CR)
4294 result = INT21_BufferedInput( context, ptr + 2, ptr[0] );
4295 if (result > 0)
4296 ptr[1] = (BYTE)result - 1;
4297 else
4298 ptr[1] = 0;
4300 break;
4302 case 0x0b: /* GET STDIN STATUS */
4303 TRACE( "GET STDIN STATUS\n" );
4305 if (INT21_ReadChar( NULL, NULL ))
4306 SET_AL( context, 0xff ); /* character available */
4307 else
4308 SET_AL( context, 0 ); /* no character available */
4310 break;
4312 case 0x0c: /* FLUSH BUFFER AND READ STANDARD INPUT */
4314 BYTE al = AL_reg(context); /* Input function to execute after flush. */
4316 TRACE( "FLUSH BUFFER AND READ STANDARD INPUT - 0x%02x\n", al );
4318 /* FIXME: buffers are not flushed */
4321 * If AL is one of 0x01, 0x06, 0x07, 0x08, or 0x0a,
4322 * int21 function identified by AL will be called.
4324 if(al == 0x01 || al == 0x06 || al == 0x07 || al == 0x08 || al == 0x0a)
4326 SET_AH( context, al );
4327 DOSVM_Int21Handler( context );
4330 break;
4332 case 0x0d: /* DISK BUFFER FLUSH */
4333 TRACE("DISK BUFFER FLUSH ignored\n");
4334 break;
4336 case 0x0e: /* SELECT DEFAULT DRIVE */
4337 TRACE( "SELECT DEFAULT DRIVE - %c:\n", 'A' + DL_reg(context) );
4338 INT21_SetCurrentDrive( DL_reg(context) );
4339 SET_AL( context, MAX_DOS_DRIVES );
4340 break;
4342 case 0x0f: /* OPEN FILE USING FCB */
4343 INT21_OpenFileUsingFCB( context );
4344 break;
4346 case 0x10: /* CLOSE FILE USING FCB */
4347 INT21_CloseFileUsingFCB( context );
4348 break;
4350 case 0x11: /* FIND FIRST MATCHING FILE USING FCB */
4351 TRACE("FIND FIRST MATCHING FILE USING FCB %p\n",
4352 CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx));
4353 if (!INT21_FindFirstFCB(context))
4355 SET_AL( context, 0xff );
4356 break;
4358 /* else fall through */
4360 case 0x12: /* FIND NEXT MATCHING FILE USING FCB */
4361 SET_AL( context, INT21_FindNextFCB(context) ? 0x00 : 0xff );
4362 break;
4364 case 0x13: /* DELETE FILE USING FCB */
4365 INT_BARF( context, 0x21 );
4366 break;
4368 case 0x14: /* SEQUENTIAL READ FROM FCB FILE */
4369 INT21_SequentialReadFromFCB( context );
4370 break;
4372 case 0x15: /* SEQUENTIAL WRITE TO FCB FILE */
4373 INT21_SequentialWriteToFCB( context );
4374 break;
4376 case 0x16: /* CREATE OR TRUNCATE FILE USING FCB */
4377 case 0x17: /* RENAME FILE USING FCB */
4378 INT_BARF( context, 0x21 );
4379 break;
4381 case 0x18: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
4382 SET_AL( context, 0 );
4383 break;
4385 case 0x19: /* GET CURRENT DEFAULT DRIVE */
4386 SET_AL( context, INT21_GetCurrentDrive() );
4387 TRACE( "GET CURRENT DRIVE -> %c:\n", 'A' + AL_reg( context ) );
4388 break;
4390 case 0x1a: /* SET DISK TRANSFER AREA ADDRESS */
4391 TRACE( "SET DISK TRANSFER AREA ADDRESS %04X:%04X\n",
4392 context->SegDs, DX_reg(context) );
4394 TDB *task = GlobalLock16( GetCurrentTask() );
4395 task->dta = MAKESEGPTR( context->SegDs, DX_reg(context) );
4397 break;
4399 case 0x1b: /* GET ALLOCATION INFORMATION FOR DEFAULT DRIVE */
4400 if (!INT21_GetDriveAllocInfo(context, 0))
4401 SET_AX( context, 0xffff );
4402 break;
4404 case 0x1c: /* GET ALLOCATION INFORMATION FOR SPECIFIC DRIVE */
4405 if (!INT21_GetDriveAllocInfo(context, DL_reg(context)))
4406 SET_AX( context, 0xffff );
4407 break;
4409 case 0x1d: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
4410 case 0x1e: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
4411 SET_AL( context, 0 );
4412 break;
4414 case 0x1f: /* GET DRIVE PARAMETER BLOCK FOR DEFAULT DRIVE */
4416 BYTE drive = INT21_MapDrive( 0 );
4417 TRACE( "GET DPB FOR DEFAULT DRIVE\n" );
4419 if (INT21_FillDrivePB( drive ))
4421 SET_AL( context, 0x00 ); /* success */
4422 SET_BX( context, offsetof( INT21_HEAP, misc_dpb_list[drive] ) );
4423 context->SegDs = INT21_GetHeapSelector( context );
4425 else
4427 SET_AL( context, 0xff ); /* invalid or network drive */
4430 break;
4432 case 0x20: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
4433 SET_AL( context, 0 );
4434 break;
4436 case 0x21: /* READ RANDOM RECORD FROM FCB FILE */
4437 INT21_ReadRandomRecordFromFCB( context );
4438 break;
4440 case 0x22: /* WRITE RANDOM RECORD TO FCB FILE */
4441 INT21_WriteRandomRecordToFCB( context );
4442 break;
4444 case 0x23: /* GET FILE SIZE FOR FCB */
4445 case 0x24: /* SET RANDOM RECORD NUMBER FOR FCB */
4446 INT_BARF( context, 0x21 );
4447 break;
4449 case 0x25: /* SET INTERRUPT VECTOR */
4450 TRACE("SET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
4452 FARPROC16 ptr = (FARPROC16)MAKESEGPTR( context->SegDs, DX_reg(context) );
4453 if (!ISV86(context) && DOSVM_IsWin16())
4454 DOSVM_SetPMHandler16( AL_reg(context), ptr );
4455 else
4456 DOSVM_SetRMHandler( AL_reg(context), ptr );
4458 break;
4460 case 0x26: /* CREATE NEW PROGRAM SEGMENT PREFIX */
4461 INT_BARF( context, 0x21 );
4462 break;
4464 case 0x27: /* RANDOM BLOCK READ FROM FCB FILE */
4465 INT21_RandomBlockReadFromFCB( context );
4466 break;
4468 case 0x28: /* RANDOM BLOCK WRITE TO FCB FILE */
4469 INT21_RandomBlockWriteToFCB( context );
4470 break;
4472 case 0x29: /* PARSE FILENAME INTO FCB */
4473 INT21_ParseFileNameIntoFCB(context);
4474 break;
4476 case 0x2a: /* GET SYSTEM DATE */
4477 TRACE( "GET SYSTEM DATE\n" );
4479 SYSTEMTIME systime;
4480 GetLocalTime( &systime );
4481 SET_CX( context, systime.wYear );
4482 SET_DH( context, systime.wMonth );
4483 SET_DL( context, systime.wDay );
4484 SET_AL( context, systime.wDayOfWeek );
4486 break;
4488 case 0x2b: /* SET SYSTEM DATE */
4489 TRACE( "SET SYSTEM DATE\n" );
4491 WORD year = CX_reg(context);
4492 BYTE month = DH_reg(context);
4493 BYTE day = DL_reg(context);
4495 if (year >= 1980 && year <= 2099 &&
4496 month >= 1 && month <= 12 &&
4497 day >= 1 && day <= 31)
4499 FIXME( "SetSystemDate(%02d/%02d/%04d): not allowed\n",
4500 day, month, year );
4501 SET_AL( context, 0 ); /* Let's pretend we succeeded */
4503 else
4505 SET_AL( context, 0xff ); /* invalid date */
4506 TRACE( "SetSystemDate(%02d/%02d/%04d): invalid date\n",
4507 day, month, year );
4510 break;
4512 case 0x2c: /* GET SYSTEM TIME */
4513 TRACE( "GET SYSTEM TIME\n" );
4515 SYSTEMTIME systime;
4516 GetLocalTime( &systime );
4517 SET_CH( context, systime.wHour );
4518 SET_CL( context, systime.wMinute );
4519 SET_DH( context, systime.wSecond );
4520 SET_DL( context, systime.wMilliseconds / 10 );
4522 break;
4524 case 0x2d: /* SET SYSTEM TIME */
4525 if( CH_reg(context) >= 24 || CL_reg(context) >= 60 || DH_reg(context) >= 60 || DL_reg(context) >= 100 ) {
4526 TRACE("SetSystemTime(%02d:%02d:%02d.%02d): wrong time\n",
4527 CH_reg(context), CL_reg(context),
4528 DH_reg(context), DL_reg(context) );
4529 SET_AL( context, 0xFF );
4531 else
4533 FIXME("SetSystemTime(%02d:%02d:%02d.%02d): not allowed\n",
4534 CH_reg(context), CL_reg(context),
4535 DH_reg(context), DL_reg(context) );
4536 SET_AL( context, 0 ); /* Let's pretend we succeeded */
4538 break;
4540 case 0x2e: /* SET VERIFY FLAG */
4541 TRACE("SET VERIFY FLAG ignored\n");
4542 /* we cannot change the behaviour anyway, so just ignore it */
4543 break;
4545 case 0x2f: /* GET DISK TRANSFER AREA ADDRESS */
4546 TRACE( "GET DISK TRANSFER AREA ADDRESS\n" );
4548 TDB *task = GlobalLock16( GetCurrentTask() );
4549 context->SegEs = SELECTOROF( task->dta );
4550 SET_BX( context, OFFSETOF( task->dta ) );
4552 break;
4554 case 0x30: /* GET DOS VERSION */
4555 TRACE( "GET DOS VERSION - %s requested\n",
4556 (AL_reg(context) == 0x00) ? "OEM number" : "version flag" );
4558 if (AL_reg(context) == 0x00)
4559 SET_BH( context, 0xff ); /* OEM number => undefined */
4560 else
4561 SET_BH( context, 0x08 ); /* version flag => DOS is in ROM */
4563 SET_AL( context, HIBYTE(HIWORD(GetVersion16())) ); /* major version */
4564 SET_AH( context, LOBYTE(HIWORD(GetVersion16())) ); /* minor version */
4566 SET_BL( context, 0x12 ); /* 0x123456 is 24-bit Wine's serial # */
4567 SET_CX( context, 0x3456 );
4568 break;
4570 case 0x31: /* TERMINATE AND STAY RESIDENT */
4571 FIXME("TERMINATE AND STAY RESIDENT stub\n");
4572 break;
4574 case 0x32: /* GET DOS DRIVE PARAMETER BLOCK FOR SPECIFIC DRIVE */
4576 BYTE drive = INT21_MapDrive( DL_reg(context) );
4577 TRACE( "GET DPB FOR SPECIFIC DRIVE %d\n", DL_reg(context) );
4579 if (INT21_FillDrivePB( drive ))
4581 SET_AL( context, 0x00 ); /* success */
4582 SET_BX( context, offsetof( INT21_HEAP, misc_dpb_list[drive] ) );
4583 context->SegDs = INT21_GetHeapSelector( context );
4585 else
4587 SET_AL( context, 0xff ); /* invalid or network drive */
4590 break;
4592 case 0x33: /* MULTIPLEXED */
4593 switch (AL_reg(context))
4595 case 0x00: /* GET CURRENT EXTENDED BREAK STATE */
4596 TRACE("GET CURRENT EXTENDED BREAK STATE\n");
4597 SET_DL( context, DOSCONF_GetConfig()->brk_flag );
4598 break;
4600 case 0x01: /* SET EXTENDED BREAK STATE */
4601 TRACE("SET CURRENT EXTENDED BREAK STATE\n");
4602 DOSCONF_GetConfig()->brk_flag = (DL_reg(context) > 0) ? 1 : 0;
4603 break;
4605 case 0x02: /* GET AND SET EXTENDED CONTROL-BREAK CHECKING STATE*/
4606 TRACE("GET AND SET EXTENDED CONTROL-BREAK CHECKING STATE\n");
4607 /* ugly coding in order to stay reentrant */
4608 if (DL_reg(context))
4610 SET_DL( context, DOSCONF_GetConfig()->brk_flag );
4611 DOSCONF_GetConfig()->brk_flag = 1;
4613 else
4615 SET_DL( context, DOSCONF_GetConfig()->brk_flag );
4616 DOSCONF_GetConfig()->brk_flag = 0;
4618 break;
4620 case 0x05: /* GET BOOT DRIVE */
4621 TRACE("GET BOOT DRIVE\n");
4622 SET_DL( context, 3 );
4623 /* c: is Wine's bootdrive (a: is 1)*/
4624 break;
4626 case 0x06: /* GET TRUE VERSION NUMBER */
4627 TRACE("GET TRUE VERSION NUMBER\n");
4628 SET_BL( context, HIBYTE(HIWORD(GetVersion16())) ); /* major */
4629 SET_BH( context, LOBYTE(HIWORD(GetVersion16())) ); /* minor */
4630 SET_DL( context, 0x00 ); /* revision */
4631 SET_DH( context, 0x08 ); /* DOS is in ROM */
4632 break;
4634 default:
4635 INT_BARF( context, 0x21 );
4636 break;
4638 break;
4640 case 0x34: /* GET ADDRESS OF INDOS FLAG */
4641 TRACE( "GET ADDRESS OF INDOS FLAG\n" );
4642 context->SegEs = INT21_GetHeapSelector( context );
4643 SET_BX( context, offsetof(INT21_HEAP, misc_indos) );
4644 break;
4646 case 0x35: /* GET INTERRUPT VECTOR */
4647 TRACE("GET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
4649 FARPROC16 addr;
4650 if (!ISV86(context) && DOSVM_IsWin16())
4651 addr = DOSVM_GetPMHandler16( AL_reg(context) );
4652 else
4653 addr = DOSVM_GetRMHandler( AL_reg(context) );
4654 context->SegEs = SELECTOROF(addr);
4655 SET_BX( context, OFFSETOF(addr) );
4657 break;
4659 case 0x36: /* GET FREE DISK SPACE */
4660 TRACE("GET FREE DISK SPACE FOR DRIVE %s (limited to about 1GB)\n",
4661 INT21_DriveName( DL_reg(context) ));
4662 if (!INT21_GetFreeDiskSpace(context)) SET_AX( context, 0xffff );
4663 break;
4665 case 0x37: /* SWITCHAR */
4667 switch (AL_reg(context))
4669 case 0x00: /* "SWITCHAR" - GET SWITCH CHARACTER */
4670 TRACE( "SWITCHAR - GET SWITCH CHARACTER\n" );
4671 SET_AL( context, 0x00 ); /* success*/
4672 SET_DL( context, '/' );
4673 break;
4674 case 0x01: /*"SWITCHAR" - SET SWITCH CHARACTER*/
4675 FIXME( "SWITCHAR - SET SWITCH CHARACTER: %c\n",
4676 DL_reg( context ));
4677 SET_AL( context, 0x00 ); /* success*/
4678 break;
4679 default:
4680 INT_BARF( context, 0x21 );
4681 break;
4684 break;
4686 case 0x38: /* GET COUNTRY-SPECIFIC INFORMATION */
4687 TRACE( "GET COUNTRY-SPECIFIC INFORMATION\n" );
4688 if (AL_reg(context))
4690 WORD country = AL_reg(context);
4691 if (country == 0xff)
4692 country = BX_reg(context);
4693 if (country != INT21_GetSystemCountryCode()) {
4694 FIXME( "Requested info on non-default country %04x\n", country );
4695 SET_AX(context, 2);
4696 SET_CFLAG(context);
4699 if(AX_reg(context) != 2 )
4701 INT21_FillCountryInformation( CTX_SEG_OFF_TO_LIN(context,
4702 context->SegDs,
4703 context->Edx) );
4704 SET_AX( context, INT21_GetSystemCountryCode() );
4705 SET_BX( context, INT21_GetSystemCountryCode() );
4706 RESET_CFLAG(context);
4708 break;
4710 case 0x39: /* "MKDIR" - CREATE SUBDIRECTORY */
4711 if (!INT21_CreateDirectory( context ))
4712 bSetDOSExtendedError = TRUE;
4713 else
4714 RESET_CFLAG(context);
4715 break;
4717 case 0x3a: /* "RMDIR" - REMOVE DIRECTORY */
4719 WCHAR dirW[MAX_PATH];
4720 char *dirA = CTX_SEG_OFF_TO_LIN(context,
4721 context->SegDs, context->Edx);
4723 TRACE( "REMOVE DIRECTORY %s\n", dirA );
4725 MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
4727 if (!RemoveDirectoryW( dirW ))
4728 bSetDOSExtendedError = TRUE;
4729 else
4730 RESET_CFLAG(context);
4732 break;
4734 case 0x3b: /* "CHDIR" - SET CURRENT DIRECTORY */
4735 if (!INT21_SetCurrentDirectory( context ))
4736 bSetDOSExtendedError = TRUE;
4737 else
4738 RESET_CFLAG(context);
4739 break;
4741 case 0x3c: /* "CREAT" - CREATE OR TRUNCATE FILE */
4742 if (!INT21_CreateFile( context, context->Edx, FALSE,
4743 OF_READWRITE | OF_SHARE_COMPAT, 0x12 ))
4744 bSetDOSExtendedError = TRUE;
4745 else
4746 RESET_CFLAG(context);
4747 break;
4749 case 0x3d: /* "OPEN" - OPEN EXISTING FILE */
4750 if (!INT21_CreateFile( context, context->Edx, FALSE,
4751 AL_reg(context), 0x01 ))
4752 bSetDOSExtendedError = TRUE;
4753 else
4754 RESET_CFLAG(context);
4755 break;
4757 case 0x3e: /* "CLOSE" - CLOSE FILE */
4758 TRACE( "CLOSE handle %d\n", BX_reg(context) );
4759 if (_lclose16( BX_reg(context) ) == HFILE_ERROR16)
4760 bSetDOSExtendedError = TRUE;
4761 else
4762 RESET_CFLAG(context);
4763 break;
4765 case 0x3f: /* "READ" - READ FROM FILE OR DEVICE */
4766 TRACE( "READ from %d to %04X:%04X for %d bytes\n",
4767 BX_reg(context),
4768 context->SegDs,
4769 DX_reg(context),
4770 CX_reg(context) );
4772 DWORD result;
4773 WORD count = CX_reg(context);
4774 BYTE *buffer = CTX_SEG_OFF_TO_LIN( context,
4775 context->SegDs,
4776 context->Edx );
4778 /* Some programs pass a count larger than the allocated buffer */
4779 if (DOSVM_IsWin16())
4781 DWORD maxcount = GetSelectorLimit16( context->SegDs )
4782 - DX_reg(context) + 1;
4783 if (count > maxcount)
4784 count = maxcount;
4788 * FIXME: Reading from console (BX=1) in DOS mode
4789 * does not work as it is supposed to work.
4792 RESET_CFLAG(context); /* set if error */
4793 if (!DOSVM_IsWin16() && BX_reg(context) == 0)
4795 result = INT21_BufferedInput( context, buffer, count );
4796 SET_AX( context, (WORD)result );
4798 else if (ReadFile( DosFileHandleToWin32Handle(BX_reg(context)),
4799 buffer, count, &result, NULL ))
4800 SET_AX( context, (WORD)result );
4801 else
4802 bSetDOSExtendedError = TRUE;
4804 break;
4806 case 0x40: /* "WRITE" - WRITE TO FILE OR DEVICE */
4807 TRACE( "WRITE from %04X:%04X to handle %d for %d byte\n",
4808 context->SegDs, DX_reg(context),
4809 BX_reg(context), CX_reg(context) );
4811 char *ptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
4813 if (!DOSVM_IsWin16() &&
4814 (BX_reg(context) == 1 || BX_reg(context) == 2))
4816 int i;
4817 for(i=0; i<CX_reg(context); i++)
4818 DOSVM_PutChar(ptr[i]);
4819 SET_AX(context, CX_reg(context));
4820 RESET_CFLAG(context);
4822 else
4824 HFILE handle = (HFILE)DosFileHandleToWin32Handle(BX_reg(context));
4825 LONG result = _hwrite( handle, ptr, CX_reg(context) );
4826 if (result == HFILE_ERROR)
4827 bSetDOSExtendedError = TRUE;
4828 else
4830 SET_AX( context, (WORD)result );
4831 RESET_CFLAG(context);
4835 break;
4837 case 0x41: /* "UNLINK" - DELETE FILE */
4839 WCHAR fileW[MAX_PATH];
4840 char *fileA = CTX_SEG_OFF_TO_LIN(context,
4841 context->SegDs,
4842 context->Edx);
4844 TRACE( "UNLINK %s\n", fileA );
4845 MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
4847 if (!DeleteFileW( fileW ))
4848 bSetDOSExtendedError = TRUE;
4849 else
4850 RESET_CFLAG(context);
4852 break;
4854 case 0x42: /* "LSEEK" - SET CURRENT FILE POSITION */
4855 TRACE( "LSEEK handle %d offset %d from %s\n",
4856 BX_reg(context),
4857 MAKELONG( DX_reg(context), CX_reg(context) ),
4858 (AL_reg(context) == 0) ?
4859 "start of file" : ((AL_reg(context) == 1) ?
4860 "current file position" : "end of file") );
4862 HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
4863 LONG offset = MAKELONG( DX_reg(context), CX_reg(context) );
4864 DWORD status = SetFilePointer( handle, offset,
4865 NULL, AL_reg(context) );
4866 if (status == INVALID_SET_FILE_POINTER)
4867 bSetDOSExtendedError = TRUE;
4868 else
4870 SET_AX( context, LOWORD(status) );
4871 SET_DX( context, HIWORD(status) );
4872 RESET_CFLAG(context);
4875 break;
4877 case 0x43: /* FILE ATTRIBUTES */
4878 if (!INT21_FileAttributes( context, AL_reg(context), FALSE ))
4879 bSetDOSExtendedError = TRUE;
4880 else
4881 RESET_CFLAG(context);
4882 break;
4884 case 0x44: /* IOCTL */
4885 INT21_Ioctl( context );
4886 break;
4888 case 0x45: /* "DUP" - DUPLICATE FILE HANDLE */
4889 TRACE( "DUPLICATE FILE HANDLE %d\n", BX_reg(context) );
4891 HANDLE handle32;
4892 HFILE handle16 = HFILE_ERROR;
4894 if (DuplicateHandle( GetCurrentProcess(),
4895 DosFileHandleToWin32Handle(BX_reg(context)),
4896 GetCurrentProcess(),
4897 &handle32,
4898 0, TRUE, DUPLICATE_SAME_ACCESS ))
4899 handle16 = Win32HandleToDosFileHandle(handle32);
4901 if (handle16 == HFILE_ERROR)
4902 bSetDOSExtendedError = TRUE;
4903 else
4905 SET_AX( context, handle16 );
4906 RESET_CFLAG(context);
4909 break;
4911 case 0x46: /* "DUP2", "FORCEDUP" - FORCE DUPLICATE FILE HANDLE */
4912 TRACE( "FORCEDUP - FORCE DUPLICATE FILE HANDLE %d to %d\n",
4913 BX_reg(context), CX_reg(context) );
4914 if (!INT21_Dup2(BX_reg(context), CX_reg(context)))
4915 bSetDOSExtendedError = TRUE;
4916 else
4917 RESET_CFLAG(context);
4918 break;
4920 case 0x47: /* "CWD" - GET CURRENT DIRECTORY */
4921 if (!INT21_GetCurrentDirectory( context, FALSE ))
4922 bSetDOSExtendedError = TRUE;
4923 else
4924 RESET_CFLAG(context);
4925 break;
4927 case 0x48: /* ALLOCATE MEMORY */
4928 TRACE( "ALLOCATE MEMORY for %d paragraphs\n", BX_reg(context) );
4930 WORD selector = 0;
4931 DWORD bytes = (DWORD)BX_reg(context) << 4;
4933 if (!ISV86(context) && DOSVM_IsWin16())
4935 DWORD rv = GlobalDOSAlloc16( bytes );
4936 selector = LOWORD( rv );
4938 else
4939 DOSMEM_AllocBlock( bytes, &selector );
4941 if (selector)
4943 SET_AX( context, selector );
4944 RESET_CFLAG(context);
4946 else
4948 SET_CFLAG(context);
4949 SET_AX( context, 0x0008 ); /* insufficient memory */
4950 SET_BX( context, DOSMEM_Available() >> 4 );
4953 break;
4955 case 0x49: /* FREE MEMORY */
4956 TRACE( "FREE MEMORY segment %04X\n", context->SegEs );
4958 BOOL ok;
4960 if (!ISV86(context) && DOSVM_IsWin16())
4962 ok = !GlobalDOSFree16( context->SegEs );
4964 /* If we don't reset ES_reg, we will fail in the relay code */
4965 if (ok)
4966 context->SegEs = 0;
4968 else
4969 ok = DOSMEM_FreeBlock( PTR_REAL_TO_LIN(context->SegEs, 0) );
4971 if (!ok)
4973 TRACE("FREE MEMORY failed\n");
4974 SET_CFLAG(context);
4975 SET_AX( context, 0x0009 ); /* memory block address invalid */
4978 break;
4980 case 0x4a: /* RESIZE MEMORY BLOCK */
4981 TRACE( "RESIZE MEMORY segment %04X to %d paragraphs\n",
4982 context->SegEs, BX_reg(context) );
4984 DWORD newsize = (DWORD)BX_reg(context) << 4;
4986 if (!ISV86(context) && DOSVM_IsWin16())
4988 FIXME( "Resize memory block - unsupported under Win16\n" );
4989 SET_CFLAG(context);
4991 else
4993 LPVOID address = (void*)(context->SegEs << 4);
4994 UINT blocksize = DOSMEM_ResizeBlock( address, newsize, FALSE );
4996 RESET_CFLAG(context);
4997 if (blocksize == (UINT)-1)
4999 SET_CFLAG( context );
5000 SET_AX( context, 0x0009 ); /* illegal address */
5002 else if(blocksize != newsize)
5004 SET_CFLAG( context );
5005 SET_AX( context, 0x0008 ); /* insufficient memory */
5006 SET_BX( context, blocksize >> 4 ); /* new block size */
5010 break;
5012 case 0x4b: /* "EXEC" - LOAD AND/OR EXECUTE PROGRAM */
5014 char *program = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
5015 BYTE *paramblk = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Ebx);
5017 TRACE( "EXEC %s\n", program );
5019 RESET_CFLAG(context);
5020 if (DOSVM_IsWin16())
5022 HINSTANCE16 instance = WinExec16( program, SW_NORMAL );
5023 if (instance < 32)
5025 SET_CFLAG( context );
5026 SET_AX( context, instance );
5029 else
5031 if (!MZ_Exec( context, program, AL_reg(context), paramblk))
5032 bSetDOSExtendedError = TRUE;
5035 break;
5037 case 0x4c: /* "EXIT" - TERMINATE WITH RETURN CODE */
5038 TRACE( "EXIT with return code %d\n", AL_reg(context) );
5039 if (DOSVM_IsWin16())
5040 DOSVM_Exit( AL_reg(context) );
5041 else if(ISV86(context))
5042 MZ_Exit( context, FALSE, AL_reg(context) );
5043 else
5046 * Exit from DPMI.
5048 ULONG_PTR rv = AL_reg(context);
5049 RaiseException( EXCEPTION_VM86_INTx, 0, 1, &rv );
5051 break;
5053 case 0x4d: /* GET RETURN CODE */
5054 TRACE("GET RETURN CODE (ERRORLEVEL)\n");
5055 SET_AX( context, DOSVM_retval );
5056 DOSVM_retval = 0;
5057 break;
5059 case 0x4e: /* "FINDFIRST" - FIND FIRST MATCHING FILE */
5060 TRACE("FINDFIRST mask 0x%04x spec %s\n",CX_reg(context),
5061 (LPCSTR)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx));
5062 if (!INT21_FindFirst(context)) break;
5063 /* fall through */
5065 case 0x4f: /* "FINDNEXT" - FIND NEXT MATCHING FILE */
5066 TRACE("FINDNEXT\n");
5067 if (!INT21_FindNext(context))
5069 SetLastError( ERROR_NO_MORE_FILES );
5070 SET_AX( context, ERROR_NO_MORE_FILES );
5071 SET_CFLAG(context);
5073 else SET_AX( context, 0 ); /* OK */
5074 break;
5076 case 0x50: /* SET CURRENT PROCESS ID (SET PSP ADDRESS) */
5077 TRACE("SET CURRENT PROCESS ID (SET PSP ADDRESS)\n");
5078 DOSVM_psp = BX_reg(context);
5079 break;
5081 case 0x51: /* GET PSP ADDRESS */
5082 INT21_GetPSP( context );
5083 break;
5085 case 0x52: /* "SYSVARS" - GET LIST OF LISTS */
5087 SEGPTR ptr = DOSDEV_GetLOL( ISV86(context) || !DOSVM_IsWin16() );
5088 context->SegEs = SELECTOROF(ptr);
5089 SET_BX( context, OFFSETOF(ptr) );
5091 break;
5093 case 0x54: /* Get Verify Flag */
5094 TRACE("Get Verify Flag - Not Supported\n");
5095 SET_AL( context, 0x00 ); /* pretend we can tell. 00h = off 01h = on */
5096 break;
5098 case 0x56: /* "RENAME" - RENAME FILE */
5099 if (!INT21_RenameFile( context ))
5100 bSetDOSExtendedError = TRUE;
5101 else
5102 RESET_CFLAG(context);
5103 break;
5105 case 0x57: /* FILE DATE AND TIME */
5106 if (!INT21_FileDateTime( context ))
5107 bSetDOSExtendedError = TRUE;
5108 else
5109 RESET_CFLAG(context);
5110 break;
5112 case 0x58: /* GET OR SET MEMORY ALLOCATION STRATEGY */
5113 switch (AL_reg(context))
5115 case 0x00: /* GET MEMORY ALLOCATION STRATEGY */
5116 TRACE( "GET MEMORY ALLOCATION STRATEGY\n" );
5117 SET_AX( context, 0 ); /* low memory first fit */
5118 break;
5120 case 0x01: /* SET ALLOCATION STRATEGY */
5121 TRACE( "SET MEMORY ALLOCATION STRATEGY to %d - ignored\n",
5122 BL_reg(context) );
5123 break;
5125 case 0x02: /* GET UMB LINK STATE */
5126 TRACE( "GET UMB LINK STATE\n" );
5127 SET_AL( context, 0 ); /* UMBs not part of DOS memory chain */
5128 break;
5130 case 0x03: /* SET UMB LINK STATE */
5131 TRACE( "SET UMB LINK STATE to %d - ignored\n",
5132 BX_reg(context) );
5133 break;
5135 default:
5136 INT_BARF( context, 0x21 );
5138 break;
5140 case 0x59: /* GET EXTENDED ERROR INFO */
5141 INT21_GetExtendedError( context );
5142 break;
5144 case 0x5a: /* CREATE TEMPORARY FILE */
5145 TRACE("CREATE TEMPORARY FILE\n");
5146 bSetDOSExtendedError = !INT21_CreateTempFile(context);
5147 break;
5149 case 0x5b: /* CREATE NEW FILE */
5150 if (!INT21_CreateFile( context, context->Edx, FALSE,
5151 OF_READWRITE | OF_SHARE_COMPAT, 0x10 ))
5152 bSetDOSExtendedError = TRUE;
5153 else
5154 RESET_CFLAG(context);
5155 break;
5157 case 0x5c: /* "FLOCK" - RECORD LOCKING */
5159 DWORD offset = MAKELONG(DX_reg(context), CX_reg(context));
5160 DWORD length = MAKELONG(DI_reg(context), SI_reg(context));
5161 HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
5163 RESET_CFLAG(context);
5164 switch (AL_reg(context))
5166 case 0x00: /* LOCK */
5167 TRACE( "lock handle %d offset %d length %d\n",
5168 BX_reg(context), offset, length );
5169 if (!LockFile( handle, offset, 0, length, 0 ))
5170 bSetDOSExtendedError = TRUE;
5171 break;
5173 case 0x01: /* UNLOCK */
5174 TRACE( "unlock handle %d offset %d length %d\n",
5175 BX_reg(context), offset, length );
5176 if (!UnlockFile( handle, offset, 0, length, 0 ))
5177 bSetDOSExtendedError = TRUE;
5178 break;
5180 default:
5181 INT_BARF( context, 0x21 );
5184 break;
5186 case 0x5d: /* NETWORK 5D */
5187 FIXME( "Network function 5D not implemented.\n" );
5188 SetLastError( ER_NoNetwork );
5189 bSetDOSExtendedError = TRUE;
5190 break;
5192 case 0x5e: /* NETWORK 5E */
5193 bSetDOSExtendedError = INT21_NetworkFunc( context);
5194 break;
5196 case 0x5f: /* NETWORK 5F */
5197 /* FIXME: supporting this would need to 1:
5198 * - implement per drive current directory (as kernel32 doesn't)
5199 * - assign enabled/disabled flag on a per drive basis
5201 /* network software not installed */
5202 TRACE("NETWORK function AX=%04x not implemented\n",AX_reg(context));
5203 SetLastError( ER_NoNetwork );
5204 bSetDOSExtendedError = TRUE;
5205 break;
5207 case 0x60: /* "TRUENAME" - CANONICALIZE FILENAME OR PATH */
5209 WCHAR pathW[MAX_PATH], res[MAX_PATH];
5210 /* FIXME: likely to be broken */
5212 TRACE("TRUENAME %s\n",
5213 (LPCSTR)CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Esi));
5214 MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
5215 if (!GetFullPathNameW( pathW, 128, res, NULL ))
5216 bSetDOSExtendedError = TRUE;
5217 else
5219 SET_AX( context, 0 );
5220 WideCharToMultiByte(CP_OEMCP, 0, res, -1,
5221 CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi),
5222 128, NULL, NULL);
5225 break;
5227 case 0x61: /* UNUSED */
5228 SET_AL( context, 0 );
5229 break;
5231 case 0x62: /* GET PSP ADDRESS */
5232 INT21_GetPSP( context );
5233 break;
5235 case 0x63: /* MISC. LANGUAGE SUPPORT */
5236 switch (AL_reg(context)) {
5237 case 0x00: /* GET DOUBLE BYTE CHARACTER SET LEAD-BYTE TABLE */
5238 TRACE( "GET DOUBLE BYTE CHARACTER SET LEAD-BYTE TABLE\n" );
5239 context->SegDs = INT21_GetHeapSelector( context );
5240 SET_SI( context, offsetof(INT21_HEAP, dbcs_table) );
5241 SET_AL( context, 0 ); /* success */
5242 break;
5244 break;
5246 case 0x64: /* OS/2 DOS BOX */
5247 INT_BARF( context, 0x21 );
5248 SET_CFLAG(context);
5249 break;
5251 case 0x65: /* EXTENDED COUNTRY INFORMATION */
5252 INT21_ExtendedCountryInformation( context );
5253 break;
5255 case 0x66: /* GLOBAL CODE PAGE TABLE */
5256 switch (AL_reg(context))
5258 case 0x01:
5259 TRACE( "GET GLOBAL CODE PAGE TABLE\n" );
5260 SET_BX( context, GetOEMCP() );
5261 SET_DX( context, GetOEMCP() );
5262 break;
5263 case 0x02:
5264 FIXME( "SET GLOBAL CODE PAGE TABLE, active %d, system %d - ignored\n",
5265 BX_reg(context), DX_reg(context) );
5266 break;
5268 break;
5270 case 0x67: /* SET HANDLE COUNT */
5271 TRACE( "SET HANDLE COUNT to %d\n", BX_reg(context) );
5272 if (SetHandleCount( BX_reg(context) ) < BX_reg(context) )
5273 bSetDOSExtendedError = TRUE;
5274 break;
5276 case 0x68: /* "FFLUSH" - COMMIT FILE */
5277 TRACE( "FFLUSH - handle %d\n", BX_reg(context) );
5278 if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
5279 bSetDOSExtendedError = TRUE;
5280 break;
5282 case 0x69: /* DISK SERIAL NUMBER */
5283 switch (AL_reg(context))
5285 case 0x00:
5286 TRACE("GET DISK SERIAL NUMBER for drive %s\n",
5287 INT21_DriveName(BL_reg(context)));
5288 if (!INT21_GetDiskSerialNumber(context)) bSetDOSExtendedError = TRUE;
5289 else SET_AX( context, 0 );
5290 break;
5292 case 0x01:
5293 TRACE("SET DISK SERIAL NUMBER for drive %s\n",
5294 INT21_DriveName(BL_reg(context)));
5295 if (!INT21_SetDiskSerialNumber(context)) bSetDOSExtendedError = TRUE;
5296 else SET_AX( context, 1 );
5297 break;
5299 break;
5301 case 0x6a: /* COMMIT FILE */
5302 TRACE( "COMMIT FILE - handle %d\n", BX_reg(context) );
5303 if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
5304 bSetDOSExtendedError = TRUE;
5305 break;
5307 case 0x6b: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
5308 SET_AL( context, 0 );
5309 break;
5311 case 0x6c: /* EXTENDED OPEN/CREATE */
5312 if (!INT21_CreateFile( context, context->Esi, TRUE,
5313 BX_reg(context), DL_reg(context) ))
5314 bSetDOSExtendedError = TRUE;
5315 break;
5317 case 0x70: /* MSDOS 7 - GET/SET INTERNATIONALIZATION INFORMATION */
5318 FIXME( "MS-DOS 7 - GET/SET INTERNATIONALIZATION INFORMATION\n" );
5319 SET_CFLAG( context );
5320 SET_AL( context, 0 );
5321 break;
5323 case 0x71: /* MSDOS 7 - LONG FILENAME FUNCTIONS */
5324 INT21_LongFilename( context );
5325 break;
5327 case 0x73: /* MSDOS7 - FAT32 */
5328 RESET_CFLAG( context );
5329 if (!INT21_Fat32( context ))
5330 bSetDOSExtendedError = TRUE;
5331 break;
5333 case 0xdc: /* CONNECTION SERVICES - GET CONNECTION NUMBER */
5334 TRACE( "CONNECTION SERVICES - GET CONNECTION NUMBER - ignored\n" );
5335 break;
5337 case 0xea: /* NOVELL NETWARE - RETURN SHELL VERSION */
5338 TRACE( "NOVELL NETWARE - RETURN SHELL VERSION - ignored\n" );
5339 break;
5341 case 0xff: /* DOS32 EXTENDER (DOS/4GW) - API */
5342 /* we don't implement a DOS32 extender */
5343 TRACE( "DOS32 EXTENDER API - ignored\n" );
5344 break;
5346 default:
5347 INT_BARF( context, 0x21 );
5348 break;
5350 } /* END OF SWITCH */
5352 /* Set general error condition. */
5353 if (bSetDOSExtendedError)
5355 SET_AX( context, GetLastError() );
5356 SET_CFLAG( context );
5359 /* Print error code if carry flag is set. */
5360 if (context->EFlags & 0x0001)
5361 TRACE("failed, error %d\n", GetLastError() );
5363 TRACE( "returning: AX=%04x BX=%04x CX=%04x DX=%04x "
5364 "SI=%04x DI=%04x DS=%04x ES=%04x EFL=%08x\n",
5365 AX_reg(context), BX_reg(context),
5366 CX_reg(context), DX_reg(context),
5367 SI_reg(context), DI_reg(context),
5368 (WORD)context->SegDs, (WORD)context->SegEs,
5369 context->EFlags );