crypt32/tests: Fix some test failures on Win9x.
[wine] / dlls / winedos / int21.c
1 /*
2  * DOS interrupt 21h handler
3  *
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
10  *
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.
15  *
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.
20  *
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
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28
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
37
38 #include "windef.h"
39 #include "winbase.h"
40 #include "winreg.h"
41 #include "winternl.h"
42 #include "wine/winbase16.h"
43 #include "dosexe.h"
44 #include "winerror.h"
45 #include "winuser.h"
46 #include "wine/unicode.h"
47 #include "wine/server.h"
48 #include "wine/debug.h"
49 #include "wine/exception.h"
50
51 BOOL    WINAPI VerifyConsoleIoHandle(HANDLE);
52 /*
53  * Note:
54  * - Most of the file related functions are wrong. NT's kernel32
55  *   doesn't maintain a per drive current directory, while DOS does. 
56  *   We should in fact keep track in here of those per drive
57  *   directories, and use this info while dealing with partial paths
58  *   (drive defined, but only relative paths). This could even be
59  *   created as an array of CDS (there should be an entry for that in
60  *   the LOL)
61  */
62
63 /*
64  * Forward declarations.
65  */
66 static BOOL INT21_RenameFile( CONTEXT86 *context );
67
68 WINE_DEFAULT_DEBUG_CHANNEL(int21);
69
70
71 #include "pshpack1.h"
72
73 /*
74  * Extended Drive Parameter Block.
75  * This structure is compatible with standard DOS4+ DPB and 
76  * extended DOS7 DPB.
77  */
78 typedef struct _INT21_DPB {
79     BYTE   drive;                /* 00 drive number (0=A, ...) */
80     BYTE   unit;                 /* 01 unit number within device driver */
81     WORD   sector_bytes;         /* 02 bytes per sector */
82     BYTE   cluster_sectors;      /* 04 highest sector number within a cluster */
83     BYTE   shift;                /* 05 shift count to convert clusters into sectors */
84     WORD   num_reserved;         /* 06 reserved sectors at beginning of drive */
85     BYTE   num_FAT;              /* 08 number of FATs */
86     WORD   num_root_entries;     /* 09 number of root directory entries */
87     WORD   first_data_sector;    /* 0b number of first sector containing user data */
88     WORD   num_clusters1;        /* 0d highest cluster number (number of data clusters + 1) */
89     WORD   sectors_per_FAT;      /* 0f number of sectors per FAT */
90     WORD   first_dir_sector;     /* 11 sector number of first directory sector */
91     SEGPTR driver_header;        /* 13 address of device driver header */
92     BYTE   media_ID;             /* 17 media ID byte */
93     BYTE   access_flag;          /* 18 0x00 if disk accessed, 0xff if not */
94     SEGPTR next;                 /* 19 pointer to next DPB */
95     WORD   search_cluster1;      /* 1d cluster at which to start search for free space */
96     WORD   free_clusters_lo;     /* 1f number of free clusters on drive or 0xffff if unknown */
97     WORD   free_clusters_hi;     /* 21 hiword of clusters_free */
98     WORD   mirroring_flags;      /* 23 active FAT/mirroring flags */
99     WORD   info_sector;          /* 25 sector number of file system info sector or 0xffff for none */
100     WORD   spare_boot_sector;    /* 27 sector number of backup boot sector or 0xffff for none */
101     DWORD  first_cluster_sector; /* 29 sector number of the first cluster */
102     DWORD  num_clusters2;        /* 2d maximum cluster number */
103     DWORD  fat_clusters;         /* 31 number of clusters occupied by FAT */
104     DWORD  root_cluster;         /* 35 cluster number of start of root directory */
105     DWORD  search_cluster2;      /* 39 cluster at which to start searching for free space */
106 } INT21_DPB;
107
108
109 /*
110  * Structure for DOS data that can be accessed directly from applications.
111  * Real and protected mode pointers will be returned to this structure so
112  * the structure must be correctly packed.
113  */
114 typedef struct _INT21_HEAP {
115     WORD uppercase_size;             /* Size of the following table in bytes */
116     BYTE uppercase_table[128];       /* Uppercase equivalents of chars from 0x80 to 0xff. */
117
118     WORD lowercase_size;             /* Size of the following table in bytes */
119     BYTE lowercase_table[256];       /* Lowercase equivalents of chars from 0x00 to 0xff. */
120
121     WORD collating_size;             /* Size of the following table in bytes */
122     BYTE collating_table[256];       /* Values used to sort characters from 0x00 to 0xff. */
123
124     WORD filename_size;              /* Size of the following filename data in bytes */
125     BYTE filename_reserved1;         /* 0x01 for MS-DOS 3.30-6.00 */
126     BYTE filename_lowest;            /* Lowest permissible character value for filename */
127     BYTE filename_highest;           /* Highest permissible character value for filename */
128     BYTE filename_reserved2;         /* 0x00 for MS-DOS 3.30-6.00 */
129     BYTE filename_exclude_first;     /* First illegal character in permissible range */
130     BYTE filename_exclude_last;      /* Last illegal character in permissible range */
131     BYTE filename_reserved3;         /* 0x02 for MS-DOS 3.30-6.00 */
132     BYTE filename_illegal_size;      /* Number of terminators in the following table */
133     BYTE filename_illegal_table[16]; /* Characters which terminate a filename */
134
135     WORD dbcs_size;                  /* Number of valid ranges in the following table */
136     BYTE dbcs_table[16];             /* Start/end bytes for N ranges and 00/00 as terminator */
137
138     BYTE      misc_indos;                    /* Interrupt 21 nesting flag */
139     WORD      misc_segment;                  /* Real mode segment for INT21_HEAP */
140     WORD      misc_selector;                 /* Protected mode selector for INT21_HEAP */
141     INT21_DPB misc_dpb_list[MAX_DOS_DRIVES]; /* Drive parameter blocks for all drives */
142
143 } INT21_HEAP;
144
145
146 struct FCB {
147     BYTE  drive_number;
148     CHAR  file_name[8];
149     CHAR  file_extension[3];
150     WORD  current_block_number;
151     WORD  logical_record_size;
152     DWORD file_size;
153     WORD  date_of_last_write;
154     WORD  time_of_last_write;
155     BYTE  file_number;
156     BYTE  attributes;
157     WORD  starting_cluster;
158     WORD  sequence_number;
159     BYTE  file_attributes;
160     BYTE  unused;
161     BYTE  record_within_current_block;
162     BYTE  random_access_record_number[4];
163 };
164
165
166 struct XFCB {
167     BYTE  xfcb_signature;
168     BYTE  reserved[5];
169     BYTE  xfcb_file_attribute;
170     BYTE  fcb[37];
171 };
172
173 /* DTA layout for FindFirst/FindNext */
174 typedef struct
175 {
176     BYTE   drive;        /* 00 drive letter */
177     char   mask[11];     /* 01 search template */
178     BYTE   search_attr;  /* 0c search attributes */
179     WORD   count;        /* 0d entry count within directory */
180     WORD   cluster;      /* 0f cluster of parent directory */
181     WCHAR *fullPath;     /* 11 full path (was: reserved) */
182     BYTE   fileattr;     /* 15 file attributes */
183     WORD   filetime;     /* 16 file time */
184     WORD   filedate;     /* 18 file date */
185     DWORD  filesize;     /* 1a file size */
186     char   filename[13]; /* 1e file name + extension */
187 } FINDFILE_DTA;
188
189 /* FCB layout for FindFirstFCB/FindNextFCB */
190 typedef struct
191 {
192     BYTE   drive;                /* 00 drive letter */
193     char   filename[11];         /* 01 filename 8+3 format */
194     int    count;                /* 0c entry count (was: reserved) */
195     WCHAR *fullPath;             /* 10 full path (was: reserved) */
196 } FINDFILE_FCB;
197
198 /* DOS directory entry for FindFirstFCB/FindNextFCB */
199 typedef struct
200 {
201     char   filename[11];         /* 00 filename 8+3 format */
202     BYTE   fileattr;             /* 0b file attributes */
203     BYTE   reserved[10];         /* 0c reserved */
204     WORD   filetime;             /* 16 file time */
205     WORD   filedate;             /* 18 file date */
206     WORD   cluster;              /* 1a file first cluster */
207     DWORD  filesize;             /* 1c file size */
208 } DOS_DIRENTRY_LAYOUT;
209
210 #include "poppack.h"
211
212 /* dos file attributes */
213 #define FA_NORMAL    0x00        /* Normal file, no attributes */
214 #define FA_RDONLY    0x01        /* Read only attribute */
215 #define FA_HIDDEN    0x02        /* Hidden file */
216 #define FA_SYSTEM    0x04        /* System file */
217 #define FA_LABEL     0x08        /* Volume label */
218 #define FA_DIRECTORY 0x10        /* Directory */
219 #define FA_ARCHIVE   0x20        /* Archive */
220 #define FA_UNUSED    0x40        /* Unused */
221
222 /* Error codes */
223 #define ER_NoNetwork         0x49
224
225 /* Error classes */
226 #define EC_OutOfResource     0x01
227 #define EC_Temporary         0x02
228 #define EC_AccessDenied      0x03
229 #define EC_InternalError     0x04
230 #define EC_HardwareFailure   0x05
231 #define EC_SystemFailure     0x06
232 #define EC_ProgramError      0x07
233 #define EC_NotFound          0x08
234 #define EC_MediaError        0x0b
235 #define EC_Exists            0x0c
236 #define EC_Unknown           0x0d
237
238 /* Suggested actions */
239 #define SA_Retry             0x01
240 #define SA_DelayedRetry      0x02
241 #define SA_Abort             0x04
242 #define SA_Ignore            0x06
243 #define SA_Ask4Retry         0x07
244
245 /* Error locus */
246 #define EL_Unknown           0x01
247 #define EL_Disk              0x02
248 #define EL_Network           0x03
249 #define EL_Serial            0x04
250 #define EL_Memory            0x05
251
252 /* BIOS Keyboard Scancodes */
253 #define KEY_LEFT        0x4B
254 #define KEY_RIGHT       0x4D
255 #define KEY_UP          0x48
256 #define KEY_DOWN        0x50
257 #define KEY_IC          0x52 /* insert char */
258 #define KEY_DC          0x53 /* delete char */
259 #define KEY_BACKSPACE   0x0E
260 #define KEY_HOME        0x47
261 #define KEY_END         0x4F
262 #define KEY_NPAGE       0x49
263 #define KEY_PPAGE       0x51
264
265
266 struct magic_device
267 {
268     WCHAR  name[10];
269     HANDLE handle;
270     LARGE_INTEGER index;
271     void (*ioctl_handler)(CONTEXT86 *);
272 };
273
274 static void INT21_IoctlScsiMgrHandler( CONTEXT86 * );
275 static void INT21_IoctlEMSHandler( CONTEXT86 * );
276 static void INT21_IoctlHPScanHandler( CONTEXT86 * );
277
278 static struct magic_device magic_devices[] =
279 {
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 } }, INT21_IoctlEMSHandler },
282     { {'h','p','s','c','a','n',0},         NULL, { { 0, 0 } }, INT21_IoctlHPScanHandler },
283 };
284
285 #define NB_MAGIC_DEVICES  (sizeof(magic_devices)/sizeof(magic_devices[0]))
286
287
288 /* Many calls translate a drive argument like this:
289    drive number (00h = default, 01h = A:, etc)
290    */
291 /******************************************************************
292  *              INT21_DriveName
293  *
294  * Many calls translate a drive argument like this:
295  * drive number (00h = default, 01h = A:, etc)
296  */
297 static const char *INT21_DriveName(int drive)
298 {
299     if (drive > 0) 
300     {
301         if (drive <= 26) return wine_dbg_sprintf("%c:", 'A' + drive - 1);
302         else return wine_dbg_sprintf( "<Bad drive: %d>", drive);
303     }
304     return "default";
305 }
306
307 /***********************************************************************
308  *           INT21_GetCurrentDrive
309  *
310  * Return current drive using scheme (0=A:, 1=B:, 2=C:, ...) or
311  * MAX_DOS_DRIVES on error.
312  */
313 static BYTE INT21_GetCurrentDrive(void)
314 {
315     WCHAR current_directory[MAX_PATH];
316
317     if (!GetCurrentDirectoryW( MAX_PATH, current_directory ) ||
318         current_directory[1] != ':')
319     {
320         TRACE( "Failed to get current drive.\n" );
321         return MAX_DOS_DRIVES;
322     }
323
324     return toupperW( current_directory[0] ) - 'A';
325 }
326
327
328 /***********************************************************************
329  *           INT21_MapDrive
330  *
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.
333  */
334 static BYTE INT21_MapDrive( BYTE drive )
335 {
336     if (drive)
337     {
338         WCHAR drivespec[3] = {'A', ':', 0};
339         UINT  drivetype;
340
341         drivespec[0] += drive - 1;
342         drivetype = GetDriveTypeW( drivespec );
343
344         if (drivetype == DRIVE_UNKNOWN || drivetype == DRIVE_NO_ROOT_DIR)
345             return MAX_DOS_DRIVES;
346
347         return drive - 1;
348     }
349
350     return INT21_GetCurrentDrive();
351 }
352
353
354 /***********************************************************************
355  *           INT21_SetCurrentDrive
356  *
357  * Set current drive. Uses scheme (0=A:, 1=B:, 2=C:, ...).
358  */
359 static void INT21_SetCurrentDrive( BYTE drive )
360 {
361     WCHAR drivespec[3] = {'A', ':', 0};
362
363     drivespec[0] += drive;
364
365     if (!SetCurrentDirectoryW( drivespec ))
366         TRACE( "Failed to set current drive.\n" );
367 }
368
369
370 /***********************************************************************
371  *           INT21_ReadChar
372  *
373  * Reads a character from the standard input.
374  * Extended keycodes will be returned as two separate characters.
375  */
376 static BOOL INT21_ReadChar( BYTE *input, CONTEXT86 *waitctx )
377 {
378     static BYTE pending_scan = 0;
379
380     if (pending_scan)
381     {
382         if (input)
383             *input = pending_scan;
384         if (waitctx)
385             pending_scan = 0;
386         return TRUE;
387     }
388     else
389     {
390         BYTE ascii;
391         BYTE scan;
392         if (!DOSVM_Int16ReadChar( &ascii, &scan, waitctx ))
393             return FALSE;
394
395         if (input)
396             *input = ascii;
397         if (waitctx && !ascii)
398             pending_scan = scan;
399         return TRUE;
400     }
401 }
402
403
404 /***********************************************************************
405  *           INT21_GetSystemCountryCode
406  *
407  * Return DOS country code for default system locale.
408  */
409 static WORD INT21_GetSystemCountryCode( void )
410 {
411     /*
412      * FIXME: Determine country code. We should probably use
413      *        DOSCONF structure for that.
414      */
415     return GetSystemDefaultLangID();
416 }
417
418
419 /***********************************************************************
420  *           INT21_FillCountryInformation
421  *
422  * Fill 34-byte buffer with country information data using
423  * default system locale.
424  */
425 static void INT21_FillCountryInformation( BYTE *buffer )
426 {
427     /* 00 - WORD: date format
428      *          00 = mm/dd/yy
429      *          01 = dd/mm/yy
430      *          02 = yy/mm/dd
431      */
432     *(WORD*)(buffer + 0) = 0; /* FIXME: Get from locale */
433
434     /* 02 - BYTE[5]: ASCIIZ currency symbol string */
435     buffer[2] = '$'; /* FIXME: Get from locale */
436     buffer[3] = 0;
437
438     /* 07 - BYTE[2]: ASCIIZ thousands separator */
439     buffer[7] = 0; /* FIXME: Get from locale */
440     buffer[8] = 0;
441
442     /* 09 - BYTE[2]: ASCIIZ decimal separator */
443     buffer[9]  = '.'; /* FIXME: Get from locale */
444     buffer[10] = 0;
445
446     /* 11 - BYTE[2]: ASCIIZ date separator */
447     buffer[11] = '/'; /* FIXME: Get from locale */
448     buffer[12] = 0;
449
450     /* 13 - BYTE[2]: ASCIIZ time separator */
451     buffer[13] = ':'; /* FIXME: Get from locale */
452     buffer[14] = 0;
453
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
459      */
460     buffer[15] = 0; /* FIXME: Get from locale */
461
462     /* 16 - BYTE: Number of digits after decimal in currency */
463     buffer[16] = 0; /* FIXME: Get from locale */
464
465     /* 17 - BYTE: Time format
466      *          bit 0 = 0 if 12-hour clock
467      *                  1 if 24-hour clock
468      */
469     buffer[17] = 1; /* FIXME: Get from locale */
470
471     /* 18 - DWORD: Address of case map routine */
472     *(DWORD*)(buffer + 18) = 0; /* FIXME: ptr to case map routine */
473
474     /* 22 - BYTE[2]: ASCIIZ data-list separator */
475     buffer[22] = ','; /* FIXME: Get from locale */
476     buffer[23] = 0;
477
478     /* 24 - BYTE[10]: Reserved */
479     memset( buffer + 24, 0, 10 );
480 }
481
482
483 /***********************************************************************
484  *           INT21_FillHeap
485  *
486  * Initialize DOS heap.
487  *
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                       :|<>+=;,
491  */
492 static void INT21_FillHeap( INT21_HEAP *heap )
493 {
494     static const char terminators[] = ".\"/\\[]:|<>+=;,";
495     int i;
496
497     /*
498      * Uppercase table.
499      */
500     heap->uppercase_size = 128;
501     for (i = 0; i < 128; i++) 
502         heap->uppercase_table[i] = toupper( 128 + i );
503
504     /*
505      * Lowercase table.
506      */
507     heap->lowercase_size = 256;
508     for (i = 0; i < 256; i++) 
509         heap->lowercase_table[i] = tolower( i );
510     
511     /*
512      * Collating table.
513      */
514     heap->collating_size = 256;
515     for (i = 0; i < 256; i++) 
516         heap->collating_table[i] = i;
517
518     /*
519      * Filename table.
520      */
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 );
524
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;
532
533     /*
534      * DBCS lead byte table. This table is empty.
535      */
536     heap->dbcs_size = 0;
537     memset( heap->dbcs_table, 0, sizeof(heap->dbcs_table) );
538
539     /*
540      * Initialize InDos flag.
541      */
542     heap->misc_indos = 0;
543
544     /*
545      * FIXME: Should drive parameter blocks (DPB) be
546      *        initialized here and linked to DOS LOL?
547      */
548 }
549
550
551 /***********************************************************************
552  *           INT21_GetHeapPointer
553  *
554  * Get pointer for DOS heap (INT21_HEAP).
555  * Creates and initializes heap on first call.
556  */
557 static INT21_HEAP *INT21_GetHeapPointer( void )
558 {
559     static INT21_HEAP *heap_pointer = NULL;
560
561     if (!heap_pointer)
562     {
563         WORD heap_segment;
564         WORD heap_selector;
565
566         heap_pointer = DOSVM_AllocDataUMB( sizeof(INT21_HEAP), 
567                                            &heap_segment,
568                                            &heap_selector );
569
570         heap_pointer->misc_segment  = heap_segment;
571         heap_pointer->misc_selector = heap_selector;
572         INT21_FillHeap( heap_pointer );
573     }
574
575     return heap_pointer;
576 }
577
578
579 /***********************************************************************
580  *           INT21_GetHeapSelector
581  *
582  * Get segment/selector for DOS heap (INT21_HEAP).
583  * Creates and initializes heap on first call.
584  */
585 static WORD INT21_GetHeapSelector( CONTEXT86 *context )
586 {
587     INT21_HEAP *heap = INT21_GetHeapPointer();
588
589     if (!ISV86(context) && DOSVM_IsWin16())
590         return heap->misc_selector;
591     else
592         return heap->misc_segment;
593 }
594
595
596 /***********************************************************************
597  *           INT21_FillDrivePB
598  *
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.
602  */
603 static BOOL INT21_FillDrivePB( BYTE drive )
604 {
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;
613
614     if (drive >= MAX_DOS_DRIVES)
615         return FALSE;
616
617     dpb = &heap->misc_dpb_list[drive];
618     drivespec[0] += drive;
619     drivetype = GetDriveTypeW( drivespec );
620
621     /*
622      * FIXME: Does this check work correctly with floppy/cdrom drives?
623      */
624     if (drivetype == DRIVE_NO_ROOT_DIR || drivetype == DRIVE_UNKNOWN)
625         return FALSE;
626
627     /*
628      * FIXME: Does this check work correctly with floppy/cdrom drives?
629      */
630     if (!GetDiskFreeSpaceW( drivespec, &cluster_sectors, &sector_bytes,
631                             &free_clusters, &total_clusters ))
632         return FALSE;
633
634     /*
635      * FIXME: Most of the values listed below are incorrect.
636      *        All values should be validated.
637      */
638  
639     dpb->drive           = drive;
640     dpb->unit            = 0;
641     dpb->sector_bytes    = sector_bytes;
642     dpb->cluster_sectors = cluster_sectors - 1;
643
644     dpb->shift = 0;
645     while (cluster_sectors > 1)
646     {
647         cluster_sectors /= 2;
648         dpb->shift++;
649     }
650
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;
673
674     return TRUE;
675 }
676
677
678 /***********************************************************************
679  *           INT21_GetCurrentDirectory
680  *
681  * Handler for:
682  * - function 0x47
683  * - subfunction 0x47 of function 0x71
684  */
685 static BOOL INT21_GetCurrentDirectory( CONTEXT86 *context, BOOL islong )
686 {
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;
692
693     TRACE( "drive %d\n", DL_reg(context) );
694
695     if (drive == MAX_DOS_DRIVES)
696     {
697         SetLastError(ERROR_INVALID_DRIVE);
698         return FALSE;
699     }
700     
701     /*
702      * Grab current directory.
703      */
704
705     if (!GetCurrentDirectoryW( MAX_PATH, pathW )) return FALSE;
706
707     if (toupperW(pathW[0]) - 'A' != drive || pathW[1] != ':')
708     {
709         /* cwd is not on the requested drive, get the environment string instead */
710
711         WCHAR env_var[4];
712
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 ))
718         {
719             /* return empty path */
720             buffer[0] = 0;
721             return TRUE;
722         }
723     }
724
725     /*
726      * Convert into short format.
727      */
728
729     if (!islong)
730     {
731         DWORD result = GetShortPathNameW( pathW, pathW, MAX_PATH );
732         if (!result)
733             return FALSE;
734         if (result > MAX_PATH)
735         {
736             WARN( "Short path too long!\n" );
737             SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
738             return FALSE;
739         }
740     }
741
742     /*
743      * The returned pathname does not include 
744      * the drive letter, colon or leading backslash.
745      */
746
747     if (ptr[0] == '\\')
748     {
749         /*
750          * FIXME: We should probably just strip host part from name...
751          */
752         FIXME( "UNC names are not supported.\n" );
753         SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
754         return FALSE;
755     }
756     else if (!ptr[0] || ptr[1] != ':' || ptr[2] != '\\')
757     {
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;
762     }
763     else
764     {
765         /* Remove drive letter, colon and leading backslash. */
766         ptr += 3;
767     }
768
769     /*
770      * Convert into OEM string.
771      */
772     
773     if (!WideCharToMultiByte(CP_OEMCP, 0, ptr, -1, pathA, 
774                              MAX_PATH, NULL, NULL))
775     {
776         WARN( "Cannot convert path!\n" );
777         SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
778         return FALSE;
779     }
780
781     /*
782      * Success.
783      */
784
785     if (!islong)
786     {
787         /* Undocumented success code. */
788         SET_AX( context, 0x0100 );
789         
790         /* Truncate buffer to 64 bytes. */
791         pathA[63] = 0;
792     }
793
794     TRACE( "%c:=%s\n", 'A' + drive, pathA );
795
796     strcpy( buffer, pathA );
797     return TRUE;
798 }
799
800
801 /***********************************************************************
802  *           INT21_SetCurrentDirectory
803  *
804  * Handler for:
805  * - function 0x3b
806  * - subfunction 0x3b of function 0x71
807  */
808 static BOOL INT21_SetCurrentDirectory( CONTEXT86 *context )
809 {
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;
816
817     TRACE( "SET CURRENT DIRECTORY %s\n", dirA );
818
819     MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
820     if (!GetFullPathNameW( dirW, MAX_PATH, dirW, NULL )) return FALSE;
821
822     attr = GetFileAttributesW( dirW );
823     if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
824     {
825         SetLastError( ERROR_PATH_NOT_FOUND );
826         return FALSE;
827     }
828
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 );
834
835     /* only set current directory if on the current drive */
836     if (result && (toupperW(dirW[0]) - 'A' == drive)) result = SetCurrentDirectoryW( dirW );
837
838     return result;
839 }
840
841 /***********************************************************************
842  *           INT21_CreateMagicDeviceHandle
843  *
844  * Create a dummy file handle for a "magic" device.
845  */
846 static HANDLE INT21_CreateMagicDeviceHandle( LPCWSTR name )
847 {
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;
856
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 )))
861     {
862         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
863         return 0;
864     }
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 );
870
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;
877
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)
882     {
883         ret = 0;
884         SetLastError( RtlNtStatusToDosError(status) );
885     }
886     RtlFreeUnicodeString( &nameW );
887     return ret;
888 }
889
890
891 /***********************************************************************
892  *           INT21_OpenMagicDevice
893  *
894  * Open a file handle for "magic" devices like EMMXXXX0.
895  */
896 static HANDLE INT21_OpenMagicDevice( LPCWSTR name, DWORD access )
897 {
898     unsigned int i;
899     const WCHAR *p;
900     HANDLE handle;
901
902     if (name[0] && (name[1] == ':')) name += 2;
903     if ((p = strrchrW( name, '/' ))) name = p + 1;
904     if ((p = strrchrW( name, '\\' ))) name = p + 1;
905
906     for (i = 0; i < NB_MAGIC_DEVICES; i++)
907     {
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;
911     }
912     if (i == NB_MAGIC_DEVICES) return 0;
913
914     if (!magic_devices[i].handle) /* need to open it */
915     {
916         IO_STATUS_BLOCK io;
917         FILE_INTERNAL_INFORMATION info;
918
919         if (!(handle = INT21_CreateMagicDeviceHandle( magic_devices[i].name ))) return 0;
920
921         NtQueryInformationFile( handle, &io, &info, sizeof(info), FileInternalInformation );
922         magic_devices[i].index = info.IndexNumber;
923         magic_devices[i].handle = handle;
924     }
925     if (!DuplicateHandle( GetCurrentProcess(), magic_devices[i].handle,
926                           GetCurrentProcess(), &handle, access, FALSE, 0 )) handle = 0;
927     return handle;
928 }
929
930
931 /***********************************************************************
932  *           INT21_CreateFile
933  *
934  * Handler for:
935  * - function 0x3c
936  * - function 0x3d
937  * - function 0x5b
938  * - function 0x6c
939  * - subfunction 0x6c of function 0x71
940  */
941 static BOOL INT21_CreateFile( CONTEXT86 *context, 
942                               DWORD      pathSegOff,
943                               BOOL       returnStatus,
944                               WORD       dosAccessShare,
945                               BYTE       dosAction )
946 {
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;
955
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 );
959
960     /*
961      * Application tried to create/open a file whose name 
962      * ends with a backslash. This is not allowed.
963      *
964      * FIXME: This needs to be validated, especially the return value.
965      */
966     if (pathA[strlen(pathA) - 1] == '/')
967     {
968         SetLastError( ERROR_FILE_NOT_FOUND );
969         return FALSE;
970     }
971
972     /*
973      * Convert DOS action flags into Win32 creation disposition parameter.
974      */ 
975     switch(dosAction)
976     {
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;
995     }
996
997     /*
998      * Convert DOS access/share flags into Win32 desired access parameter.
999      */ 
1000     switch(dosAccessShare & 0x07)
1001     {
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:
1012         /*
1013          * Read-only, do not modify file's last-access time (DOS7).
1014          *
1015          * FIXME: How to prevent modification of last-access time?
1016          */
1017         winAccess = GENERIC_READ;
1018         break;
1019     default:
1020         winAccess = 0;
1021     }
1022
1023     /*
1024      * Convert DOS access/share flags into Win32 share mode parameter.
1025      */ 
1026     switch(dosAccessShare & 0x70)
1027     {
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;
1041     }
1042
1043     /*
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.
1049      */
1050
1051     /*
1052      * Convert DOS create attributes into Win32 flags and attributes parameter.
1053      */
1054     if (winMode == OPEN_EXISTING || winMode == TRUNCATE_EXISTING)
1055     {
1056         winAttributes = 0;
1057     }
1058     else
1059     {        
1060         WORD dosAttributes = CX_reg(context);
1061
1062         if (dosAttributes & FA_LABEL)
1063         {
1064             /*
1065              * Application tried to create volume label entry.
1066              * This is difficult to support so we do not allow it.
1067              *
1068              * FIXME: If volume does not already have a label, 
1069              *        this function is supposed to succeed.
1070              */
1071             SetLastError( ERROR_ACCESS_DENIED );
1072             return TRUE;
1073         }
1074
1075         winAttributes = dosAttributes & 
1076             (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | 
1077              FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE);
1078     }
1079
1080     /*
1081      * Open the file.
1082      */
1083     MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
1084
1085     if ((winHandle = INT21_OpenMagicDevice( pathW, winAccess )))
1086     {
1087         dosStatus = 1;
1088     }
1089     else
1090     {
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             winHandle = CreateFileW( pathW, winAccess & ~GENERIC_WRITE,
1097                     winSharing, NULL, winMode, winAttributes, 0 );
1098         }
1099
1100         if (winHandle == INVALID_HANDLE_VALUE)
1101             return FALSE;
1102
1103         /*
1104          * Determine DOS file status.
1105          *
1106          * 1 = file opened
1107          * 2 = file created
1108          * 3 = file replaced
1109          */
1110         switch(winMode)
1111         {
1112         case OPEN_EXISTING:
1113             dosStatus = 1;
1114             break;
1115         case TRUNCATE_EXISTING:
1116             dosStatus = 3;
1117             break;
1118         case CREATE_NEW:
1119             dosStatus = 2;
1120             break;
1121         case OPEN_ALWAYS:
1122             dosStatus = (GetLastError() == ERROR_ALREADY_EXISTS) ? 1 : 2;
1123             break;
1124         case CREATE_ALWAYS:
1125             dosStatus = (GetLastError() == ERROR_ALREADY_EXISTS) ? 3 : 2;
1126             break;
1127         default:
1128             dosStatus = 0;
1129         }
1130     }
1131
1132     /*
1133      * Return DOS file handle and DOS status.
1134      */
1135     SET_AX( context, Win32HandleToDosFileHandle(winHandle) );
1136
1137     if (returnStatus)
1138         SET_CX( context, dosStatus );
1139
1140     TRACE( "CreateFile finished: handle=%d, status=%d.\n", 
1141            AX_reg(context), dosStatus );
1142
1143     return TRUE;
1144 }
1145
1146
1147 /***********************************************************************
1148  *           INT21_BufferedInput
1149  *
1150  * Handler for function 0x0a and reading from console using
1151  * function 0x3f.
1152  *
1153  * Reads a string of characters from standard input until
1154  * enter key is pressed. Returns either number of characters 
1155  * read from console including terminating CR or 
1156  * zero if capacity was zero.
1157  */
1158 static WORD INT21_BufferedInput( CONTEXT86 *context, BYTE *ptr, WORD capacity )
1159 {
1160     BYTE length = 0;
1161
1162     /*
1163      * Return immediately if capacity is zero.
1164      */
1165     if (capacity == 0)
1166         return 0;
1167
1168     while(TRUE)
1169     {
1170         BYTE ascii;
1171         BYTE scan;
1172
1173         DOSVM_Int16ReadChar( &ascii, &scan, context );
1174
1175         if (ascii == '\r' || ascii == '\n')
1176         {
1177             ptr[length] = '\r';
1178             return length + 1;
1179         }
1180
1181         /*
1182          * DOS handles only backspace and KEY_LEFT
1183          *        perhaps we should do more
1184          */
1185         if (ascii == '\b' || scan == KEY_LEFT)
1186         {
1187             if (length==0) continue;
1188             DOSVM_PutChar( '\b' );
1189             length--;
1190             continue;
1191         }
1192
1193         /*
1194          * If the buffer becomes filled to within one byte of
1195          * capacity, DOS rejects all further characters up to,
1196          * but not including, the terminating carriage return.
1197          */
1198         if (ascii != 0 && length < capacity-1)
1199         {
1200             DOSVM_PutChar( ascii );
1201             ptr[length] = ascii;
1202             length++;
1203         }
1204     }
1205 }
1206
1207
1208 /***********************************************************************
1209  *           INT21_GetCurrentDTA
1210  */
1211 static BYTE *INT21_GetCurrentDTA( CONTEXT86 *context )
1212 {
1213     TDB *pTask = GlobalLock16(GetCurrentTask());
1214
1215     /* FIXME: This assumes DTA was set correctly! */
1216     return CTX_SEG_OFF_TO_LIN( context, SELECTOROF(pTask->dta),
1217                                OFFSETOF(pTask->dta) );
1218 }
1219
1220
1221 /***********************************************************************
1222  *           INT21_OpenFileUsingFCB
1223  *
1224  * Handler for function 0x0f.
1225  *
1226  * PARAMS
1227  *  DX:DX [I/O] File control block (FCB or XFCB) of unopened file
1228  *
1229  * RETURNS (in AL)
1230  *  0x00: successful
1231  *  0xff: failed
1232  *
1233  * NOTES
1234  *  Opens a FCB file for read/write in compatibility mode. Upon calling
1235  *  the FCB must have the drive_number, file_name, and file_extension
1236  *  fields filled and all other bytes cleared.
1237  */
1238 static void INT21_OpenFileUsingFCB( CONTEXT86 *context )
1239 {
1240     struct FCB *fcb;
1241     struct XFCB *xfcb;
1242     char file_path[16];
1243     char *pos;
1244     HANDLE handle;
1245     HFILE16 hfile16;
1246     BY_HANDLE_FILE_INFORMATION info;
1247     BYTE AL_result;
1248
1249     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1250     if (fcb->drive_number == 0xff) {
1251         xfcb = (struct XFCB *) fcb;
1252         fcb = (struct FCB *) xfcb->fcb;
1253     } /* if */
1254
1255     AL_result = 0;
1256     file_path[0] = 'A' + INT21_MapDrive( fcb->drive_number );
1257
1258     if (AL_result == 0) {
1259         file_path[1] = ':';
1260         pos = &file_path[2];
1261         memcpy(pos, fcb->file_name, 8);
1262         pos[8] = ' ';
1263         pos[9] = '\0';
1264         pos = strchr(pos, ' ');
1265         *pos = '.';
1266         pos++;
1267         memcpy(pos, fcb->file_extension, 3);
1268         pos[3] = ' ';
1269         pos[4] = '\0';
1270         pos = strchr(pos, ' ');
1271         *pos = '\0';
1272
1273         handle = (HANDLE) _lopen(file_path, OF_READWRITE);
1274         if (handle == INVALID_HANDLE_VALUE) {
1275             TRACE("_lopen(\"%s\") failed: INVALID_HANDLE_VALUE\n", file_path);
1276             AL_result = 0xff; /* failed */
1277         } else {
1278             hfile16 = Win32HandleToDosFileHandle(handle);
1279             if (hfile16 == HFILE_ERROR16) {
1280                 TRACE("Win32HandleToDosFileHandle(%p) failed: HFILE_ERROR\n", handle);
1281                 CloseHandle(handle);
1282                 AL_result = 0xff; /* failed */
1283             } else if (hfile16 > 255) {
1284                 TRACE("hfile16 (=%d) larger than 255 for \"%s\"\n", hfile16, file_path);
1285                 _lclose16(hfile16);
1286                 AL_result = 0xff; /* failed */
1287             } else {
1288                 if (!GetFileInformationByHandle(handle, &info)) {
1289                     TRACE("GetFileInformationByHandle(%d, %p) for \"%s\" failed\n",
1290                           hfile16, handle, file_path);
1291                     _lclose16(hfile16);
1292                     AL_result = 0xff; /* failed */
1293                 } else {
1294                     fcb->drive_number = file_path[0] - 'A' + 1;
1295                     fcb->current_block_number = 0;
1296                     fcb->logical_record_size = 128;
1297                     fcb->file_size = info.nFileSizeLow;
1298                     FileTimeToDosDateTime(&info.ftLastWriteTime,
1299                         &fcb->date_of_last_write, &fcb->time_of_last_write);
1300                     fcb->file_number = hfile16;
1301                     fcb->attributes = 0xc2;
1302                     fcb->starting_cluster = 0; /* don't know correct init value */
1303                     fcb->sequence_number = 0; /* don't know correct init value */
1304                     fcb->file_attributes = info.dwFileAttributes;
1305                     /* The following fields are not initialized */
1306                     /* by the native function: */
1307                     /* unused */
1308                     /* record_within_current_block */
1309                     /* random_access_record_number */
1310
1311                     TRACE("successful opened file \"%s\" as %d (handle %p)\n",
1312                           file_path, hfile16, handle);
1313                     AL_result = 0x00; /* successful */
1314                 } /* if */
1315             } /* if */
1316         } /* if */
1317     } /* if */
1318     SET_AL(context, AL_result);
1319 }
1320
1321
1322 /***********************************************************************
1323  *           INT21_CloseFileUsingFCB
1324  *
1325  * Handler for function 0x10.
1326  *
1327  * PARAMS
1328  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1329  *
1330  * RETURNS (in AL)
1331  *  0x00: successful
1332  *  0xff: failed
1333  *
1334  * NOTES
1335  *  Closes a FCB file.
1336  */
1337 static void INT21_CloseFileUsingFCB( CONTEXT86 *context )
1338 {
1339     struct FCB *fcb;
1340     struct XFCB *xfcb;
1341     BYTE AL_result;
1342
1343     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1344     if (fcb->drive_number == 0xff) {
1345         xfcb = (struct XFCB *) fcb;
1346         fcb = (struct FCB *) xfcb->fcb;
1347     } /* if */
1348
1349     if (_lclose16((HFILE16) fcb->file_number) != 0) {
1350         TRACE("_lclose16(%d) failed\n", fcb->file_number);
1351         AL_result = 0xff; /* failed */
1352     } else {
1353         TRACE("successful closed file %d\n", fcb->file_number);
1354         AL_result = 0x00; /* successful */
1355     } /* if */
1356     SET_AL(context, AL_result);
1357 }
1358
1359
1360 /***********************************************************************
1361  *           INT21_SequentialReadFromFCB
1362  *
1363  * Handler for function 0x14.
1364  *
1365  * PARAMS
1366  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1367  *
1368  * RETURNS (in AL)
1369  *  0: successful
1370  *  1: end of file, no data read
1371  *  2: segment wrap in DTA, no data read (not returned now)
1372  *  3: end of file, partial record read
1373  *
1374  * NOTES
1375  *  Reads a record with the size FCB->logical_record_size from the FCB
1376  *  to the disk transfer area. The position of the record is specified
1377  *  with FCB->current_block_number and FCB->record_within_current_block.
1378  *  Then FCB->current_block_number and FCB->record_within_current_block
1379  *  are updated to point to the next record. If a partial record is
1380  *  read, it is filled with zeros up to the FCB->logical_record_size.
1381  */
1382 static void INT21_SequentialReadFromFCB( CONTEXT86 *context )
1383 {
1384     struct FCB *fcb;
1385     struct XFCB *xfcb;
1386     HANDLE handle;
1387     DWORD record_number;
1388     DWORD position;
1389     BYTE *disk_transfer_area;
1390     UINT bytes_read;
1391     BYTE AL_result;
1392
1393     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1394     if (fcb->drive_number == 0xff) {
1395         xfcb = (struct XFCB *) fcb;
1396         fcb = (struct FCB *) xfcb->fcb;
1397     } /* if */
1398
1399     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1400     if (handle == INVALID_HANDLE_VALUE) {
1401         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1402             fcb->file_number);
1403         AL_result = 0x01; /* end of file, no data read */
1404     } else {
1405         record_number = 128 * fcb->current_block_number + fcb->record_within_current_block;
1406         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1407         if (position != record_number * fcb->logical_record_size) {
1408             TRACE("seek(%d, %d, 0) failed with %u\n",
1409                   fcb->file_number, record_number * fcb->logical_record_size, position);
1410             AL_result = 0x01; /* end of file, no data read */
1411         } else {
1412             disk_transfer_area = INT21_GetCurrentDTA(context);
1413             bytes_read = _lread((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
1414             if (bytes_read != fcb->logical_record_size) {
1415                 TRACE("_lread(%d, %p, %d) failed with %d\n",
1416                       fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_read);
1417                 if (bytes_read == 0) {
1418                     AL_result = 0x01; /* end of file, no data read */
1419                 } else {
1420                     memset(&disk_transfer_area[bytes_read], 0, fcb->logical_record_size - bytes_read);
1421                     AL_result = 0x03; /* end of file, partial record read */
1422                 } /* if */
1423             } else {
1424                 TRACE("successful read %d bytes from record %d (position %u) of file %d (handle %p)\n",
1425                     bytes_read, record_number, position, fcb->file_number, handle);
1426                 AL_result = 0x00; /* successful */
1427             } /* if */
1428         } /* if */
1429     } /* if */
1430     if (AL_result == 0x00 || AL_result == 0x03) {
1431         if (fcb->record_within_current_block == 127) {
1432             fcb->record_within_current_block = 0;
1433             fcb->current_block_number++;
1434         } else {
1435             fcb->record_within_current_block++;
1436         } /* if */
1437     } /* if */
1438     SET_AL(context, AL_result);
1439 }
1440
1441
1442 /***********************************************************************
1443  *           INT21_SequentialWriteToFCB
1444  *
1445  * Handler for function 0x15.
1446  *
1447  * PARAMS
1448  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1449  *
1450  * RETURNS (in AL)
1451  *  0: successful
1452  *  1: disk full
1453  *  2: segment wrap in DTA (not returned now)
1454  *
1455  * NOTES
1456  *  Writes a record with the size FCB->logical_record_size from the disk
1457  *  transfer area to the FCB. The position of the record is specified
1458  *  with FCB->current_block_number and FCB->record_within_current_block.
1459  *  Then FCB->current_block_number and FCB->record_within_current_block
1460  *  are updated to point to the next record. 
1461  */
1462 static void INT21_SequentialWriteToFCB( CONTEXT86 *context )
1463 {
1464     struct FCB *fcb;
1465     struct XFCB *xfcb;
1466     HANDLE handle;
1467     DWORD record_number;
1468     DWORD position;
1469     BYTE *disk_transfer_area;
1470     UINT bytes_written;
1471     BYTE AL_result;
1472
1473     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1474     if (fcb->drive_number == 0xff) {
1475         xfcb = (struct XFCB *) fcb;
1476         fcb = (struct FCB *) xfcb->fcb;
1477     } /* if */
1478
1479     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1480     if (handle == INVALID_HANDLE_VALUE) {
1481         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1482             fcb->file_number);
1483         AL_result = 0x01; /* disk full */
1484     } else {
1485         record_number = 128 * fcb->current_block_number + fcb->record_within_current_block;
1486         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1487         if (position != record_number * fcb->logical_record_size) {
1488             TRACE("seek(%d, %d, 0) failed with %u\n",
1489                   fcb->file_number, record_number * fcb->logical_record_size, position);
1490             AL_result = 0x01; /* disk full */
1491         } else {
1492             disk_transfer_area = INT21_GetCurrentDTA(context);
1493             bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, fcb->logical_record_size);
1494             if (bytes_written != fcb->logical_record_size) {
1495                 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1496                       fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_written);
1497                 AL_result = 0x01; /* disk full */
1498             } else {
1499                 TRACE("successful written %d bytes from record %d (position %u) of file %d (handle %p)\n",
1500                     bytes_written, record_number, position, fcb->file_number, handle);
1501                 AL_result = 0x00; /* successful */
1502             } /* if */
1503         } /* if */
1504     } /* if */
1505     if (AL_result == 0x00) {
1506         if (fcb->record_within_current_block == 127) {
1507             fcb->record_within_current_block = 0;
1508             fcb->current_block_number++;
1509         } else {
1510             fcb->record_within_current_block++;
1511         } /* if */
1512     } /* if */
1513     SET_AL(context, AL_result);
1514 }
1515
1516
1517 /***********************************************************************
1518  *           INT21_ReadRandomRecordFromFCB
1519  *
1520  * Handler for function 0x21.
1521  *
1522  * PARAMS
1523  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1524  *
1525  * RETURNS (in AL)
1526  *  0: successful
1527  *  1: end of file, no data read
1528  *  2: segment wrap in DTA, no data read (not returned now)
1529  *  3: end of file, partial record read
1530  *
1531  * NOTES
1532  *  Reads a record with the size FCB->logical_record_size from
1533  *  the FCB to the disk transfer area. The position of the record
1534  *  is specified with FCB->random_access_record_number. The
1535  *  FCB->random_access_record_number is not updated. If a partial record
1536  *  is read, it is filled with zeros up to the FCB->logical_record_size.
1537  */
1538 static void INT21_ReadRandomRecordFromFCB( CONTEXT86 *context )
1539 {
1540     struct FCB *fcb;
1541     struct XFCB *xfcb;
1542     HANDLE handle;
1543     DWORD record_number;
1544     DWORD position;
1545     BYTE *disk_transfer_area;
1546     UINT bytes_read;
1547     BYTE AL_result;
1548
1549     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1550     if (fcb->drive_number == 0xff) {
1551         xfcb = (struct XFCB *) fcb;
1552         fcb = (struct FCB *) xfcb->fcb;
1553     } /* if */
1554
1555     memcpy(&record_number, fcb->random_access_record_number, 4);
1556     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1557     if (handle == INVALID_HANDLE_VALUE) {
1558         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1559             fcb->file_number);
1560         AL_result = 0x01; /* end of file, no data read */
1561     } else {
1562         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1563         if (position != record_number * fcb->logical_record_size) {
1564             TRACE("seek(%d, %d, 0) failed with %u\n",
1565                   fcb->file_number, record_number * fcb->logical_record_size, position);
1566             AL_result = 0x01; /* end of file, no data read */
1567         } else {
1568             disk_transfer_area = INT21_GetCurrentDTA(context);
1569             bytes_read = _lread((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
1570             if (bytes_read != fcb->logical_record_size) {
1571                 TRACE("_lread(%d, %p, %d) failed with %d\n",
1572                       fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_read);
1573                 if (bytes_read == 0) {
1574                     AL_result = 0x01; /* end of file, no data read */
1575                 } else {
1576                     memset(&disk_transfer_area[bytes_read], 0, fcb->logical_record_size - bytes_read);
1577                     AL_result = 0x03; /* end of file, partial record read */
1578                 } /* if */
1579             } else {
1580                 TRACE("successful read %d bytes from record %d (position %u) of file %d (handle %p)\n",
1581                     bytes_read, record_number, position, fcb->file_number, handle);
1582                 AL_result = 0x00; /* successful */
1583             } /* if */
1584         } /* if */
1585     } /* if */
1586     fcb->current_block_number = record_number / 128;
1587     fcb->record_within_current_block = record_number % 128;
1588     SET_AL(context, AL_result);
1589 }
1590
1591
1592 /***********************************************************************
1593  *           INT21_WriteRandomRecordToFCB
1594  *
1595  * Handler for function 0x22.
1596  *
1597  * PARAMS
1598  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1599  *
1600  * RETURNS (in AL)
1601  *  0: successful
1602  *  1: disk full
1603  *  2: segment wrap in DTA (not returned now)
1604  *
1605  * NOTES
1606  *  Writes a record with the size FCB->logical_record_size from
1607  *  the disk transfer area to the FCB. The position of the record
1608  *  is specified with FCB->random_access_record_number. The
1609  *  FCB->random_access_record_number is not updated.
1610  */
1611 static void INT21_WriteRandomRecordToFCB( CONTEXT86 *context )
1612 {
1613     struct FCB *fcb;
1614     struct XFCB *xfcb;
1615     HANDLE handle;
1616     DWORD record_number;
1617     DWORD position;
1618     BYTE *disk_transfer_area;
1619     UINT bytes_written;
1620     BYTE AL_result;
1621
1622     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1623     if (fcb->drive_number == 0xff) {
1624         xfcb = (struct XFCB *) fcb;
1625         fcb = (struct FCB *) xfcb->fcb;
1626     } /* if */
1627
1628     memcpy(&record_number, fcb->random_access_record_number, 4);
1629     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1630     if (handle == INVALID_HANDLE_VALUE) {
1631         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1632             fcb->file_number);
1633         AL_result = 0x01; /* disk full */
1634     } else {
1635         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1636         if (position != record_number * fcb->logical_record_size) {
1637             TRACE("seek(%d, %d, 0) failed with %u\n",
1638                   fcb->file_number, record_number * fcb->logical_record_size, position);
1639             AL_result = 0x01; /* disk full */
1640         } else {
1641             disk_transfer_area = INT21_GetCurrentDTA(context);
1642             bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, fcb->logical_record_size);
1643             if (bytes_written != fcb->logical_record_size) {
1644                 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1645                       fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_written);
1646                 AL_result = 0x01; /* disk full */
1647             } else {
1648                 TRACE("successful written %d bytes from record %d (position %u) of file %d (handle %p)\n",
1649                     bytes_written, record_number, position, fcb->file_number, handle);
1650                 AL_result = 0x00; /* successful */
1651             } /* if */
1652         } /* if */
1653     } /* if */
1654     fcb->current_block_number = record_number / 128;
1655     fcb->record_within_current_block = record_number % 128;
1656     SET_AL(context, AL_result);
1657 }
1658
1659
1660 /***********************************************************************
1661  *           INT21_RandomBlockReadFromFCB
1662  *
1663  * Handler for function 0x27.
1664  *
1665  * PARAMS
1666  *  CX    [I/O] Number of records to read
1667  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1668  *
1669  * RETURNS (in AL)
1670  *  0: successful
1671  *  1: end of file, no data read
1672  *  2: segment wrap in DTA, no data read (not returned now)
1673  *  3: end of file, partial record read
1674  *
1675  * NOTES
1676  *  Reads several records with the size FCB->logical_record_size from
1677  *  the FCB to the disk transfer area. The number of records to be
1678  *  read is specified in the CX register. The position of the first
1679  *  record is specified with FCB->random_access_record_number. The
1680  *  FCB->random_access_record_number, the FCB->current_block_number
1681  *  and FCB->record_within_current_block are updated to point to the
1682  *  next record after the records read. If a partial record is read,
1683  *  it is filled with zeros up to the FCB->logical_record_size. The
1684  *  CX register is set to the number of successfully read records.
1685  */
1686 static void INT21_RandomBlockReadFromFCB( CONTEXT86 *context )
1687 {
1688     struct FCB *fcb;
1689     struct XFCB *xfcb;
1690     HANDLE handle;
1691     DWORD record_number;
1692     DWORD position;
1693     BYTE *disk_transfer_area;
1694     UINT records_requested;
1695     UINT bytes_requested;
1696     UINT bytes_read;
1697     UINT records_read;
1698     BYTE AL_result;
1699
1700     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1701     if (fcb->drive_number == 0xff) {
1702         xfcb = (struct XFCB *) fcb;
1703         fcb = (struct FCB *) xfcb->fcb;
1704     } /* if */
1705
1706     memcpy(&record_number, fcb->random_access_record_number, 4);
1707     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1708     if (handle == INVALID_HANDLE_VALUE) {
1709         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1710             fcb->file_number);
1711         records_read = 0;
1712         AL_result = 0x01; /* end of file, no data read */
1713     } else {
1714         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1715         if (position != record_number * fcb->logical_record_size) {
1716             TRACE("seek(%d, %d, 0) failed with %u\n",
1717                   fcb->file_number, record_number * fcb->logical_record_size, position);
1718             records_read = 0;
1719             AL_result = 0x01; /* end of file, no data read */
1720         } else {
1721             disk_transfer_area = INT21_GetCurrentDTA(context);
1722             records_requested = CX_reg(context);
1723             bytes_requested = records_requested * fcb->logical_record_size;
1724             bytes_read = _lread((HFILE) handle, disk_transfer_area, bytes_requested);
1725             if (bytes_read != bytes_requested) {
1726                 TRACE("_lread(%d, %p, %d) failed with %d\n",
1727                       fcb->file_number, disk_transfer_area, bytes_requested, bytes_read);
1728                 records_read = bytes_read / fcb->logical_record_size;
1729                 if (bytes_read % fcb->logical_record_size == 0) {
1730                     AL_result = 0x01; /* end of file, no data read */
1731                 } else {
1732                     records_read++;
1733                     memset(&disk_transfer_area[bytes_read], 0, records_read * fcb->logical_record_size - bytes_read);
1734                     AL_result = 0x03; /* end of file, partial record read */
1735                 } /* if */
1736             } else {
1737                 TRACE("successful read %d bytes from record %d (position %u) of file %d (handle %p)\n",
1738                     bytes_read, record_number, position, fcb->file_number, handle);
1739                 records_read = records_requested;
1740                 AL_result = 0x00; /* successful */
1741             } /* if */
1742         } /* if */
1743     } /* if */
1744     record_number += records_read;
1745     memcpy(fcb->random_access_record_number, &record_number, 4);
1746     fcb->current_block_number = record_number / 128;
1747     fcb->record_within_current_block = record_number % 128;
1748     SET_CX(context, records_read);
1749     SET_AL(context, AL_result);
1750 }
1751
1752
1753 /***********************************************************************
1754  *           INT21_RandomBlockWriteToFCB
1755  *
1756  * Handler for function 0x28.
1757  *
1758  * PARAMS
1759  *  CX    [I/O] Number of records to write
1760  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1761  *
1762  * RETURNS (in AL)
1763  *  0: successful
1764  *  1: disk full
1765  *  2: segment wrap in DTA (not returned now)
1766  *
1767  * NOTES
1768  *  Writes several records with the size FCB->logical_record_size from
1769  *  the disk transfer area to the FCB. The number of records to be
1770  *  written is specified in the CX register. The position of the first
1771  *  record is specified with FCB->random_access_record_number. The
1772  *  FCB->random_access_record_number, the FCB->current_block_number
1773  *  and FCB->record_within_current_block are updated to point to the
1774  *  next record after the records written. The CX register is set to
1775  *  the number of successfully written records.
1776  */
1777 static void INT21_RandomBlockWriteToFCB( CONTEXT86 *context )
1778 {
1779     struct FCB *fcb;
1780     struct XFCB *xfcb;
1781     HANDLE handle;
1782     DWORD record_number;
1783     DWORD position;
1784     BYTE *disk_transfer_area;
1785     UINT records_requested;
1786     UINT bytes_requested;
1787     UINT bytes_written;
1788     UINT records_written;
1789     BYTE AL_result;
1790
1791     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1792     if (fcb->drive_number == 0xff) {
1793         xfcb = (struct XFCB *) fcb;
1794         fcb = (struct FCB *) xfcb->fcb;
1795     } /* if */
1796
1797     memcpy(&record_number, fcb->random_access_record_number, 4);
1798     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1799     if (handle == INVALID_HANDLE_VALUE) {
1800         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1801             fcb->file_number);
1802         records_written = 0;
1803         AL_result = 0x01; /* disk full */
1804     } else {
1805         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1806         if (position != record_number * fcb->logical_record_size) {
1807             TRACE("seek(%d, %d, 0) failed with %u\n",
1808                   fcb->file_number, record_number * fcb->logical_record_size, position);
1809             records_written = 0;
1810             AL_result = 0x01; /* disk full */
1811         } else {
1812             disk_transfer_area = INT21_GetCurrentDTA(context);
1813             records_requested = CX_reg(context);
1814             bytes_requested = records_requested * fcb->logical_record_size;
1815             bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, bytes_requested);
1816             if (bytes_written != bytes_requested) {
1817                 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1818                       fcb->file_number, disk_transfer_area, bytes_requested, bytes_written);
1819                 records_written = bytes_written / fcb->logical_record_size;
1820                 AL_result = 0x01; /* disk full */
1821             } else {
1822                 TRACE("successful write %d bytes from record %d (position %u) of file %d (handle %p)\n",
1823                     bytes_written, record_number, position, fcb->file_number, handle);
1824                 records_written = records_requested;
1825                 AL_result = 0x00; /* successful */
1826             } /* if */
1827         } /* if */
1828     } /* if */
1829     record_number += records_written;
1830     memcpy(fcb->random_access_record_number, &record_number, 4);
1831     fcb->current_block_number = record_number / 128;
1832     fcb->record_within_current_block = record_number % 128;
1833     SET_CX(context, records_written);
1834     SET_AL(context, AL_result);
1835 }
1836
1837
1838 /***********************************************************************
1839  *           INT21_CreateDirectory
1840  *
1841  * Handler for:
1842  * - function 0x39
1843  * - subfunction 0x39 of function 0x71
1844  * - subfunction 0xff of function 0x43 (CL == 0x39)
1845  */
1846 static BOOL INT21_CreateDirectory( CONTEXT86 *context )
1847 {
1848     WCHAR dirW[MAX_PATH];
1849     char *dirA = CTX_SEG_OFF_TO_LIN(context,
1850                                     context->SegDs, 
1851                                     context->Edx);
1852
1853     TRACE( "CREATE DIRECTORY %s\n", dirA );
1854
1855     MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
1856
1857     if (CreateDirectoryW(dirW, NULL))
1858         return TRUE;
1859
1860     /*
1861      * FIXME: CreateDirectory's LastErrors will clash with the ones
1862      *        used by DOS. AH=39 only returns 3 (path not found) and 
1863      *        5 (access denied), while CreateDirectory return several
1864      *        ones. Remap some of them. -Marcus
1865      */
1866     switch (GetLastError()) 
1867     {
1868     case ERROR_ALREADY_EXISTS:
1869     case ERROR_FILENAME_EXCED_RANGE:
1870     case ERROR_DISK_FULL:
1871         SetLastError(ERROR_ACCESS_DENIED);
1872         break;
1873     default: 
1874         break;
1875     }
1876
1877     return FALSE;
1878 }
1879
1880
1881 /***********************************************************************
1882  *           INT21_ExtendedCountryInformation
1883  *
1884  * Handler for function 0x65.
1885  */
1886 static void INT21_ExtendedCountryInformation( CONTEXT86 *context )
1887 {
1888     BYTE *dataptr = CTX_SEG_OFF_TO_LIN( context, context->SegEs, context->Edi );
1889     BYTE buffsize = CX_reg (context);
1890     
1891     TRACE( "GET EXTENDED COUNTRY INFORMATION, subfunction %02x\n",
1892            AL_reg(context) );
1893
1894     /*
1895      * Check subfunctions that are passed country and code page.
1896      */
1897     if (AL_reg(context) >= 0x01 && AL_reg(context) <= 0x07)
1898     {
1899         WORD country = DX_reg(context);
1900         WORD codepage = BX_reg(context);
1901
1902         if (country != 0xffff && country != INT21_GetSystemCountryCode())
1903             FIXME( "Requested info on non-default country %04x\n", country );
1904
1905         if (codepage != 0xffff && codepage != GetOEMCP())
1906             FIXME( "Requested info on non-default code page %04x\n", codepage );
1907     }
1908
1909     switch (AL_reg(context)) {
1910     case 0x00: /* SET GENERAL INTERNATIONALIZATION INFO */
1911         INT_BARF( context, 0x21 );
1912         SET_CFLAG( context );
1913         break;
1914
1915     case 0x01: /* GET GENERAL INTERNATIONALIZATION INFO */
1916         TRACE( "Get general internationalization info\n" );
1917         dataptr[0] = 0x01; /* Info ID */
1918         *(WORD*)(dataptr+1) = 38; /* Size of the following info */
1919         *(WORD*)(dataptr+3) = INT21_GetSystemCountryCode(); /* Country ID */
1920         *(WORD*)(dataptr+5) = GetOEMCP(); /* Code page */
1921         /* FIXME: fill buffer partially up to buffsize bytes*/
1922         if (buffsize >= 0x29){
1923             INT21_FillCountryInformation( dataptr + 7 );
1924             SET_CX( context, 0x29 ); /* Size of returned info */
1925         }else{
1926             SET_CX( context, 0x07 ); /* Size of returned info */        
1927         }
1928         break;
1929         
1930     case 0x02: /* GET POINTER TO UPPERCASE TABLE */
1931     case 0x04: /* GET POINTER TO FILENAME UPPERCASE TABLE */
1932         TRACE( "Get pointer to uppercase table\n" );
1933         dataptr[0] = AL_reg(context); /* Info ID */
1934         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1935                                            offsetof(INT21_HEAP, uppercase_size) );
1936         SET_CX( context, 5 ); /* Size of returned info */
1937         break;
1938
1939     case 0x03: /* GET POINTER TO LOWERCASE TABLE */
1940         TRACE( "Get pointer to lowercase table\n" );
1941         dataptr[0] = 0x03; /* Info ID */
1942         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1943                                            offsetof(INT21_HEAP, lowercase_size) );
1944         SET_CX( context, 5 ); /* Size of returned info */
1945         break;
1946
1947     case 0x05: /* GET POINTER TO FILENAME TERMINATOR TABLE */
1948         TRACE("Get pointer to filename terminator table\n");
1949         dataptr[0] = 0x05; /* Info ID */
1950         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1951                                            offsetof(INT21_HEAP, filename_size) );
1952         SET_CX( context, 5 ); /* Size of returned info */
1953         break;
1954
1955     case 0x06: /* GET POINTER TO COLLATING SEQUENCE TABLE */
1956         TRACE("Get pointer to collating sequence table\n");
1957         dataptr[0] = 0x06; /* Info ID */
1958         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1959                                            offsetof(INT21_HEAP, collating_size) );
1960         SET_CX( context, 5 ); /* Size of returned info */
1961         break;
1962
1963     case 0x07: /* GET POINTER TO DBCS LEAD BYTE TABLE */
1964         TRACE("Get pointer to DBCS lead byte table\n");
1965         dataptr[0] = 0x07; /* Info ID */
1966         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1967                                            offsetof(INT21_HEAP, dbcs_size) );
1968         SET_CX( context, 5 ); /* Size of returned info */
1969         break;
1970
1971     case 0x20: /* CAPITALIZE CHARACTER */
1972     case 0xa0: /* CAPITALIZE FILENAME CHARACTER */
1973         TRACE("Convert char to uppercase\n");
1974         SET_DL( context, toupper(DL_reg(context)) );
1975         break;
1976
1977     case 0x21: /* CAPITALIZE STRING */
1978     case 0xa1: /* CAPITALIZE COUNTED FILENAME STRING */
1979         TRACE("Convert string to uppercase with length\n");
1980         {
1981             char *ptr = CTX_SEG_OFF_TO_LIN( context, context->SegDs,
1982                                             context->Edx );
1983             WORD len = CX_reg(context);
1984             while (len--) { *ptr = toupper(*ptr); ptr++; }
1985         }
1986         break;
1987
1988     case 0x22: /* CAPITALIZE ASCIIZ STRING */
1989     case 0xa2: /* CAPITALIZE ASCIIZ FILENAME */
1990         TRACE("Convert ASCIIZ string to uppercase\n");
1991         {
1992             char *p = CTX_SEG_OFF_TO_LIN( context, context->SegDs, context->Edx );
1993             for ( ; *p; p++) *p = toupper(*p);
1994         }
1995         break;
1996
1997     case 0x23: /* DETERMINE IF CHARACTER REPRESENTS YES/NO RESPONSE */
1998         INT_BARF( context, 0x21 );
1999         SET_CFLAG( context );
2000         break;
2001
2002     default:
2003         INT_BARF( context, 0x21 );
2004         SET_CFLAG(context);
2005         break;
2006     }
2007 }
2008
2009
2010 /***********************************************************************
2011  *           INT21_FileAttributes
2012  *
2013  * Handler for:
2014  * - function 0x43
2015  * - subfunction 0x43 of function 0x71
2016  */
2017 static BOOL INT21_FileAttributes( CONTEXT86 *context, 
2018                                   BYTE       subfunction,
2019                                   BOOL       islong )
2020 {
2021     WCHAR fileW[MAX_PATH];
2022     char *fileA = CTX_SEG_OFF_TO_LIN(context, 
2023                                      context->SegDs, 
2024                                      context->Edx);
2025     HANDLE   handle;
2026     BOOL     status;
2027     FILETIME filetime;
2028     DWORD    result;
2029     WORD     date, time;
2030     int      len;
2031
2032     switch (subfunction)
2033     {
2034     case 0x00: /* GET FILE ATTRIBUTES */
2035         TRACE( "GET FILE ATTRIBUTES for %s\n", fileA );
2036         len = MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2037
2038         /* Winbench 96 Disk Test fails if we don't complain
2039          * about a filename that ends in \
2040          */
2041         if (!len || (fileW[len-1] == '/') || (fileW[len-1] == '\\'))
2042             return FALSE;
2043
2044         result = GetFileAttributesW( fileW );
2045         if (result == INVALID_FILE_ATTRIBUTES)
2046             return FALSE;
2047         else
2048         {
2049             SET_CX( context, (WORD)result );
2050             if (!islong)
2051                 SET_AX( context, (WORD)result ); /* DR DOS */
2052         }
2053         break;
2054
2055     case 0x01: /* SET FILE ATTRIBUTES */
2056         TRACE( "SET FILE ATTRIBUTES 0x%02x for %s\n", 
2057                CX_reg(context), fileA );
2058         MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2059
2060         if (!SetFileAttributesW( fileW, CX_reg(context) ))
2061             return FALSE;
2062         break;
2063
2064     case 0x02: /* GET COMPRESSED FILE SIZE */
2065         TRACE( "GET COMPRESSED FILE SIZE for %s\n", fileA );
2066         MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2067
2068         result = GetCompressedFileSizeW( fileW, NULL );
2069         if (result == INVALID_FILE_SIZE)
2070             return FALSE;
2071         else
2072         {
2073             SET_AX( context, LOWORD(result) );
2074             SET_DX( context, HIWORD(result) );
2075         }
2076         break;
2077
2078     case 0x03: /* SET FILE LAST-WRITTEN DATE AND TIME */
2079         if (!islong)
2080             INT_BARF( context, 0x21 );
2081         else
2082         {
2083             TRACE( "SET FILE LAST-WRITTEN DATE AND TIME, file %s\n", fileA );
2084             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2085
2086             handle = CreateFileW( fileW, GENERIC_WRITE, 
2087                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
2088                                   NULL, OPEN_EXISTING, 0, 0 );
2089             if (handle == INVALID_HANDLE_VALUE)
2090                 return FALSE;
2091
2092             DosDateTimeToFileTime( DI_reg(context), 
2093                                    CX_reg(context),
2094                                    &filetime );
2095             status = SetFileTime( handle, NULL, NULL, &filetime );
2096
2097             CloseHandle( handle );
2098             return status;
2099         }
2100         break;
2101
2102     case 0x04: /* GET FILE LAST-WRITTEN DATE AND TIME */
2103         if (!islong)
2104             INT_BARF( context, 0x21 );
2105         else
2106         {
2107             TRACE( "GET FILE LAST-WRITTEN DATE AND TIME, file %s\n", fileA );
2108             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2109
2110             handle = CreateFileW( fileW, GENERIC_READ, 
2111                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
2112                                   NULL, OPEN_EXISTING, 0, 0 );
2113             if (handle == INVALID_HANDLE_VALUE)
2114                 return FALSE;
2115
2116             status = GetFileTime( handle, NULL, NULL, &filetime );
2117             if (status)
2118             {
2119                 FileTimeToDosDateTime( &filetime, &date, &time );
2120                 SET_DI( context, date );
2121                 SET_CX( context, time );
2122             }
2123
2124             CloseHandle( handle );
2125             return status;
2126         }
2127         break;
2128
2129     case 0x05: /* SET FILE LAST ACCESS DATE */
2130         if (!islong)
2131             INT_BARF( context, 0x21 );
2132         else
2133         {
2134             TRACE( "SET FILE LAST ACCESS DATE, file %s\n", fileA );
2135             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2136
2137             handle = CreateFileW( fileW, GENERIC_WRITE, 
2138                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
2139                                   NULL, OPEN_EXISTING, 0, 0 );
2140             if (handle == INVALID_HANDLE_VALUE)
2141                 return FALSE;
2142
2143             DosDateTimeToFileTime( DI_reg(context), 
2144                                    0,
2145                                    &filetime );
2146             status = SetFileTime( handle, NULL, &filetime, NULL );
2147
2148             CloseHandle( handle );
2149             return status;
2150         }
2151         break;
2152
2153     case 0x06: /* GET FILE LAST ACCESS DATE */
2154         if (!islong)
2155             INT_BARF( context, 0x21 );
2156         else
2157         {
2158             TRACE( "GET FILE LAST ACCESS DATE, file %s\n", fileA );
2159             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2160
2161             handle = CreateFileW( fileW, GENERIC_READ, 
2162                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
2163                                   NULL, OPEN_EXISTING, 0, 0 );
2164             if (handle == INVALID_HANDLE_VALUE)
2165                 return FALSE;
2166
2167             status = GetFileTime( handle, NULL, &filetime, NULL );
2168             if (status)
2169             {
2170                 FileTimeToDosDateTime( &filetime, &date, NULL );
2171                 SET_DI( context, date );
2172             }
2173
2174             CloseHandle( handle );
2175             return status;
2176         }
2177         break;
2178
2179     case 0x07: /* SET FILE CREATION DATE AND TIME */
2180         if (!islong)
2181             INT_BARF( context, 0x21 );
2182         else
2183         {
2184             TRACE( "SET FILE CREATION DATE AND TIME, file %s\n", fileA );
2185
2186             handle = CreateFileW( fileW, GENERIC_WRITE,
2187                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
2188                                   NULL, OPEN_EXISTING, 0, 0 );
2189             if (handle == INVALID_HANDLE_VALUE)
2190                 return FALSE;
2191             
2192             /*
2193              * FIXME: SI has number of 10-millisecond units past time in CX.
2194              */
2195             DosDateTimeToFileTime( DI_reg(context),
2196                                    CX_reg(context),
2197                                    &filetime );
2198             status = SetFileTime( handle, &filetime, NULL, NULL );
2199
2200             CloseHandle( handle );
2201             return status;
2202         }
2203         break;
2204
2205     case 0x08: /* GET FILE CREATION DATE AND TIME */
2206         if (!islong)
2207             INT_BARF( context, 0x21 );
2208         else
2209         {
2210             TRACE( "GET FILE CREATION DATE AND TIME, handle %d\n",
2211                    BX_reg(context) );
2212
2213             handle = CreateFileW( fileW, GENERIC_READ, 
2214                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
2215                                   NULL, OPEN_EXISTING, 0, 0 );
2216             if (handle == INVALID_HANDLE_VALUE)
2217                 return FALSE;
2218
2219             status = GetFileTime( handle, &filetime, NULL, NULL );
2220             if (status)
2221             {            
2222                 FileTimeToDosDateTime( &filetime, &date, &time );
2223                 SET_DI( context, date );
2224                 SET_CX( context, time );
2225                 /*
2226                  * FIXME: SI has number of 10-millisecond units past 
2227                  *        time in CX.
2228                  */
2229                 SET_SI( context, 0 );
2230             }
2231
2232             CloseHandle(handle);
2233             return status;
2234         }
2235         break;
2236
2237     case 0xff: /* EXTENDED-LENGTH FILENAME OPERATIONS */
2238         if (islong || context->Ebp != 0x5053)
2239             INT_BARF( context, 0x21 );
2240         else
2241         {
2242             switch(CL_reg(context))
2243             {
2244             case 0x39:
2245                 if (!INT21_CreateDirectory( context ))
2246                     return FALSE;
2247                 break;
2248
2249             case 0x56:
2250                 if (!INT21_RenameFile( context ))
2251                     return FALSE;
2252                 break;
2253
2254             default:
2255                 INT_BARF( context, 0x21 );
2256             }
2257         }
2258         break;
2259
2260     default:
2261         INT_BARF( context, 0x21 );
2262     }
2263
2264     return TRUE;
2265 }
2266
2267
2268 /***********************************************************************
2269  *           INT21_FileDateTime
2270  *
2271  * Handler for function 0x57.
2272  */
2273 static BOOL INT21_FileDateTime( CONTEXT86 *context )
2274 {
2275     HANDLE   handle = DosFileHandleToWin32Handle(BX_reg(context));
2276     FILETIME filetime;
2277     WORD     date, time;
2278
2279     switch (AL_reg(context)) {
2280     case 0x00:  /* Get last-written stamp */
2281         TRACE( "GET FILE LAST-WRITTEN DATE AND TIME, handle %d\n",
2282                BX_reg(context) );
2283         {
2284             if (!GetFileTime( handle, NULL, NULL, &filetime ))
2285                 return FALSE;
2286             FileTimeToDosDateTime( &filetime, &date, &time );
2287             SET_DX( context, date );
2288             SET_CX( context, time );
2289             break;
2290         }
2291
2292     case 0x01:  /* Set last-written stamp */
2293         TRACE( "SET FILE LAST-WRITTEN DATE AND TIME, handle %d\n",
2294                BX_reg(context) );
2295         {
2296             DosDateTimeToFileTime( DX_reg(context), 
2297                                    CX_reg(context),
2298                                    &filetime );
2299             if (!SetFileTime( handle, NULL, NULL, &filetime ))
2300                 return FALSE;
2301             break;
2302         }
2303
2304     case 0x04:  /* Get last access stamp, DOS 7 */
2305         TRACE( "GET FILE LAST ACCESS DATE AND TIME, handle %d\n",
2306                BX_reg(context) );
2307         {
2308             if (!GetFileTime( handle, NULL, &filetime, NULL ))
2309                 return FALSE;
2310             FileTimeToDosDateTime( &filetime, &date, &time );
2311             SET_DX( context, date );
2312             SET_CX( context, time );
2313             break;
2314         }
2315
2316     case 0x05:  /* Set last access stamp, DOS 7 */
2317         TRACE( "SET FILE LAST ACCESS DATE AND TIME, handle %d\n",
2318                BX_reg(context) );
2319         {
2320             DosDateTimeToFileTime( DX_reg(context), 
2321                                    CX_reg(context),
2322                                    &filetime );
2323             if (!SetFileTime( handle, NULL, &filetime, NULL ))
2324                 return FALSE;
2325             break;
2326         }
2327
2328     case 0x06:  /* Get creation stamp, DOS 7 */
2329         TRACE( "GET FILE CREATION DATE AND TIME, handle %d\n",
2330                BX_reg(context) );
2331         {
2332             if (!GetFileTime( handle, &filetime, NULL, NULL ))
2333                 return FALSE;
2334             FileTimeToDosDateTime( &filetime, &date, &time );
2335             SET_DX( context, date );
2336             SET_CX( context, time );
2337             /*
2338              * FIXME: SI has number of 10-millisecond units past time in CX.
2339              */
2340             SET_SI( context, 0 );
2341             break;
2342         }
2343
2344     case 0x07:  /* Set creation stamp, DOS 7 */
2345         TRACE( "SET FILE CREATION DATE AND TIME, handle %d\n",
2346                BX_reg(context) );
2347         {
2348             /*
2349              * FIXME: SI has number of 10-millisecond units past time in CX.
2350              */
2351             DosDateTimeToFileTime( DX_reg(context), 
2352                                    CX_reg(context),
2353                                    &filetime );
2354             if (!SetFileTime( handle, &filetime, NULL, NULL ))
2355                 return FALSE;
2356             break;
2357         }
2358
2359     default:
2360         INT_BARF( context, 0x21 );
2361         break;
2362     }
2363
2364     return TRUE;
2365 }
2366
2367
2368 /***********************************************************************
2369  *           INT21_GetPSP
2370  *
2371  * Handler for functions 0x51 and 0x62.
2372  */
2373 static void INT21_GetPSP( CONTEXT86 *context )
2374 {
2375     TRACE( "GET CURRENT PSP ADDRESS (%02x)\n", AH_reg(context) );
2376
2377     /*
2378      * FIXME: should we return the original DOS PSP upon
2379      *        Windows startup ? 
2380      */
2381     if (!ISV86(context) && DOSVM_IsWin16())
2382         SET_BX( context, LOWORD(GetCurrentPDB16()) );
2383     else
2384         SET_BX( context, DOSVM_psp );
2385 }
2386
2387 static inline void setword( BYTE *ptr, WORD w )
2388 {
2389     ptr[0] = (BYTE)w;
2390     ptr[1] = (BYTE)(w >> 8);
2391 }
2392
2393 static void CreateBPB(int drive, BYTE *data, BOOL16 limited)
2394 /* limited == TRUE is used with INT 0x21/0x440d */
2395 {
2396     /* FIXME: we're forcing some values without checking that those are valid */
2397     if (drive > 1) 
2398     {
2399         setword(data, 512);
2400         data[2] = 2;
2401         setword(&data[3], 0);
2402         data[5] = 2;
2403         setword(&data[6], 240);
2404         setword(&data[8], 64000);
2405         data[0x0a] = 0xf8;
2406         setword(&data[0x0b], 40);
2407         setword(&data[0x0d], 56);
2408         setword(&data[0x0f], 2);
2409         setword(&data[0x11], 0);
2410         if (!limited) 
2411         {
2412             setword(&data[0x1f], 800);
2413             data[0x21] = 5;
2414             setword(&data[0x22], 1);
2415         }
2416     }
2417     else
2418     { /* 1.44mb */
2419         setword(data, 512);
2420         data[2] = 2;
2421         setword(&data[3], 0);
2422         data[5] = 2;
2423         setword(&data[6], 240);
2424         setword(&data[8], 2880);
2425         data[0x0a] = 0xf8;
2426         setword(&data[0x0b], 6);
2427         setword(&data[0x0d], 18);
2428         setword(&data[0x0f], 2);
2429         setword(&data[0x11], 0);
2430         if (!limited) 
2431         {
2432             setword(&data[0x1f], 80);
2433             data[0x21] = 7;
2434             setword(&data[0x22], 2);
2435         }
2436     }
2437 }
2438
2439 static inline DWORD INT21_Ioctl_CylHeadSect2Lin(DWORD cyl, WORD head, WORD sec, WORD cyl_cnt,
2440                                                  WORD head_cnt, WORD sec_cnt)
2441 {
2442     DWORD res = (cyl * head_cnt*sec_cnt + head * sec_cnt + sec);
2443     return res;
2444 }
2445
2446 /***********************************************************************
2447  *           INT21_Ioctl_Block
2448  *
2449  * Handler for block device IOCTLs.
2450  */
2451 static void INT21_Ioctl_Block( CONTEXT86 *context )
2452 {
2453     BYTE *dataptr;
2454     BYTE  drive = INT21_MapDrive( BL_reg(context) );
2455     WCHAR drivespec[4] = {'A', ':', '\\', 0};
2456     UINT  drivetype;
2457
2458     drivespec[0] += drive;
2459     drivetype = GetDriveTypeW( drivespec );
2460
2461     RESET_CFLAG(context);
2462     if (drivetype == DRIVE_UNKNOWN || drivetype == DRIVE_NO_ROOT_DIR)
2463     {
2464         TRACE( "IOCTL - SUBFUNCTION %d - INVALID DRIVE %c:\n", 
2465                AL_reg(context), 'A' + drive );
2466         SetLastError( ERROR_INVALID_DRIVE );
2467         SET_AX( context, ERROR_INVALID_DRIVE );
2468         SET_CFLAG( context );
2469         return;
2470     }
2471
2472     switch (AL_reg(context))
2473     {
2474     case 0x04: /* READ FROM BLOCK DEVICE CONTROL CHANNEL */
2475     case 0x05: /* WRITE TO BLOCK DEVICE CONTROL CHANNEL */
2476         INT_BARF( context, 0x21 );
2477         break;
2478
2479     case 0x08: /* CHECK IF BLOCK DEVICE REMOVABLE */
2480         TRACE( "IOCTL - CHECK IF BLOCK DEVICE REMOVABLE - %c:\n",
2481                'A' + drive );
2482
2483         if (drivetype == DRIVE_REMOVABLE)
2484             SET_AX( context, 0 ); /* removable */
2485         else
2486             SET_AX( context, 1 ); /* not removable */
2487         break;
2488
2489     case 0x09: /* CHECK IF BLOCK DEVICE REMOTE */
2490         TRACE( "IOCTL - CHECK IF BLOCK DEVICE REMOTE - %c:\n",
2491                'A' + drive );
2492
2493         if (drivetype == DRIVE_REMOTE)
2494             SET_DX( context, (1<<9) | (1<<12) ); /* remote + no direct IO */
2495         else
2496             SET_DX( context, 0 ); /* FIXME: use driver attr here */
2497         break;
2498
2499     case 0x0d: /* GENERIC BLOCK DEVICE REQUEST */
2500         /* Get pointer to IOCTL parameter block */
2501         dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
2502
2503         switch (CX_reg(context))
2504         {
2505         case 0x0841: /* write logical device track */
2506             TRACE( "GENERIC IOCTL - Write logical device track - %c:\n",
2507                    'A' + drive);
2508             {
2509                 WORD head   = *(WORD *)(dataptr+1);
2510                 WORD cyl    = *(WORD *)(dataptr+3);
2511                 WORD sect   = *(WORD *)(dataptr+5);
2512                 WORD nrsect = *(WORD *)(dataptr+7);
2513                 BYTE *data  = CTX_SEG_OFF_TO_LIN(context, *(WORD *)(dataptr+11), *(WORD *)(dataptr+9));
2514                 WORD cyl_cnt, head_cnt, sec_cnt;
2515
2516                 /* FIXME: we're faking some values here */
2517                 if (drive > 1)
2518                 {
2519                     /* cyl_cnt = 0x300;
2520                     head_cnt = 16;
2521                     sec_cnt = 255; */
2522                     SET_AX( context, ERROR_WRITE_FAULT );
2523                     SET_CFLAG(context);
2524                     break;
2525                 }
2526                 else
2527                 { /* floppy */
2528                     cyl_cnt = 80;
2529                     head_cnt = 2;
2530                     sec_cnt = 18;
2531                 }
2532
2533                 if (!DOSVM_RawWrite(drive, INT21_Ioctl_CylHeadSect2Lin(cyl, head, sect, cyl_cnt, head_cnt, sec_cnt), nrsect, data, FALSE))
2534                 {
2535                     SET_AX( context, ERROR_WRITE_FAULT );
2536                     SET_CFLAG(context);
2537                 }
2538             }
2539             break;
2540
2541         case 0x084a: /* lock logical volume */
2542             TRACE( "GENERIC IOCTL - Lock logical volume, level %d mode %d - %c:\n",
2543                    BH_reg(context), DX_reg(context), 'A' + drive );
2544             break;
2545
2546         case 0x0860: /* get device parameters */
2547             /* FIXME: we're faking some values here */
2548             /* used by w4wgrp's winfile */
2549             memset(dataptr, 0, 0x20); /* DOS 6.22 uses 0x20 bytes */
2550             dataptr[0] = 0x04;
2551             dataptr[6] = 0; /* media type */
2552             if (drive > 1)
2553             {
2554                 dataptr[1] = 0x05; /* fixed disk */
2555                 setword(&dataptr[2], 0x01); /* non removable */
2556                 setword(&dataptr[4], 0x300); /* # of cylinders */
2557             }
2558             else
2559             {
2560                 dataptr[1] = 0x07; /* block dev, floppy */
2561                 setword(&dataptr[2], 0x02); /* removable */
2562                 setword(&dataptr[4], 80); /* # of cylinders */
2563             }
2564             CreateBPB(drive, &dataptr[7], TRUE);
2565             RESET_CFLAG(context);
2566             break;
2567
2568         case 0x0861: /* read logical device track */
2569             TRACE( "GENERIC IOCTL - Read logical device track - %c:\n",
2570                    'A' + drive);
2571             {
2572                 WORD head   = *(WORD *)(dataptr+1);
2573                 WORD cyl    = *(WORD *)(dataptr+3);
2574                 WORD sect   = *(WORD *)(dataptr+5);
2575                 WORD nrsect = *(WORD *)(dataptr+7);
2576                 BYTE *data  = CTX_SEG_OFF_TO_LIN(context, *(WORD *)(dataptr+11), *(WORD *)(dataptr+9));
2577                 WORD cyl_cnt, head_cnt, sec_cnt;
2578
2579                 /* FIXME: we're faking some values here */
2580                 if (drive > 1)
2581                 {
2582                     cyl_cnt = 0x300;
2583                     head_cnt = 16;
2584                     sec_cnt = 255;
2585                 }
2586                 else
2587                 { /* floppy */
2588                     cyl_cnt = 80;
2589                     head_cnt = 2;
2590                     sec_cnt = 18;
2591                 }
2592
2593                 if (!DOSVM_RawRead(drive, INT21_Ioctl_CylHeadSect2Lin(cyl, head, sect, cyl_cnt, head_cnt, sec_cnt), nrsect, data, FALSE))
2594                 {
2595                     SET_AX( context, ERROR_READ_FAULT );
2596                     SET_CFLAG(context);
2597                 }
2598             }
2599             break;
2600
2601         case 0x0866: /* get volume serial number */
2602             {
2603                 WCHAR   label[12],fsname[9];
2604                 DWORD   serial;
2605
2606                 drivespec[0] += drive;
2607                 GetVolumeInformationW(drivespec, label, 12, &serial, NULL, NULL, fsname, 9);
2608                 *(WORD*)dataptr = 0;
2609                 memcpy(dataptr+2,&serial,4);
2610                 WideCharToMultiByte(CP_OEMCP, 0, label, 11, (LPSTR)dataptr + 6, 11, NULL, NULL);
2611                 WideCharToMultiByte(CP_OEMCP, 0, fsname, 8, (LPSTR)dataptr + 17, 8, NULL, NULL);
2612             }
2613             break;
2614
2615         case 0x086a: /* unlock logical volume */
2616             TRACE( "GENERIC IOCTL - Logical volume unlocked - %c:\n", 
2617                    'A' + drive );
2618             break;
2619
2620         case 0x086f: /* get drive map information */
2621             memset(dataptr+1, '\0', dataptr[0]-1);
2622             dataptr[1] = dataptr[0];
2623             dataptr[2] = 0x07; /* protected mode driver; no eject; no notification */
2624             dataptr[3] = 0xFF; /* no physical drive */
2625             break;
2626
2627         case 0x0872:
2628             /* Trial and error implementation */
2629             SET_AX( context, drivetype == DRIVE_UNKNOWN ? 0x0f : 0x01 );
2630             SET_CFLAG(context); /* Seems to be set all the time */
2631             break;
2632
2633         default:
2634             INT_BARF( context, 0x21 );            
2635         }
2636         break;
2637
2638     case 0x0e: /* GET LOGICAL DRIVE MAP */
2639         TRACE( "IOCTL - GET LOGICAL DRIVE MAP - %c:\n",
2640                'A' + drive );
2641         /* FIXME: this is not correct if drive has mappings */
2642         SET_AL( context, 0 ); /* drive has no mapping */
2643         break;
2644
2645     case 0x0f: /* SET LOGICAL DRIVE MAP */
2646         TRACE("IOCTL - SET LOGICAL DRIVE MAP for drive %s\n",
2647               INT21_DriveName( BL_reg(context)));
2648         /* FIXME: as of today, we don't support logical drive mapping... */
2649         SET_AL( context, 0 );
2650         break;
2651
2652     case 0x11: /* QUERY GENERIC IOCTL CAPABILITY */
2653     default:
2654         INT_BARF( context, 0x21 );
2655     }
2656 }
2657
2658
2659 /***********************************************************************
2660  *           INT21_IoctlScsiMgrHandler
2661  *
2662  * IOCTL handler for the SCSIMGR device.
2663  */
2664 static void INT21_IoctlScsiMgrHandler( CONTEXT86 *context )
2665 {
2666     switch (AL_reg(context))
2667     {
2668     case 0x00: /* GET DEVICE INFORMATION */
2669         SET_DX( context, 0xc0c0 );
2670         break;
2671
2672     case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
2673         DOSVM_ASPIHandler(context);
2674         break;
2675
2676     case 0x0a: /* CHECK IF HANDLE IS REMOTE */
2677         SET_DX( context, 0 );
2678         break;
2679
2680     case 0x01: /* SET DEVICE INFORMATION */
2681     case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
2682     case 0x06: /* GET INPUT STATUS */
2683     case 0x07: /* GET OUTPUT STATUS */
2684     case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
2685     case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
2686     default:
2687         INT_BARF( context, 0x21 );
2688         break;
2689     }
2690 }
2691
2692
2693 /***********************************************************************
2694  *           INT21_IoctlEMSHandler
2695  *
2696  * IOCTL handler for the EMXXXX0 device.
2697  */
2698 static void INT21_IoctlEMSHandler( CONTEXT86 *context )
2699 {
2700     EMS_Ioctl_Handler(context);
2701 }
2702
2703
2704 /***********************************************************************
2705  *           INT21_IoctlHPScanHandler
2706  *
2707  * IOCTL handler for the HPSCAN device.
2708  */
2709 static void INT21_IoctlHPScanHandler( CONTEXT86 *context )
2710 {
2711     switch (AL_reg(context))
2712     {
2713     case 0x00: /* GET DEVICE INFORMATION */
2714         SET_DX( context, 0xc0c0 );
2715         break;
2716
2717     case 0x0a: /* CHECK IF HANDLE IS REMOTE */
2718         SET_DX( context, 0 );
2719         break;
2720
2721     case 0x01: /* SET DEVICE INFORMATION */
2722     case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
2723     case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
2724     case 0x06: /* GET INPUT STATUS */
2725     case 0x07: /* GET OUTPUT STATUS */
2726     case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
2727     case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
2728     default:
2729         INT_BARF( context, 0x21 );
2730         break;
2731     }
2732 }
2733
2734
2735 /***********************************************************************
2736  *           INT21_Ioctl_Char
2737  *
2738  * Handler for character device IOCTLs.
2739  */
2740 static void INT21_Ioctl_Char( CONTEXT86 *context )
2741 {
2742     int status;
2743     int IsConsoleIOHandle = 0;
2744     IO_STATUS_BLOCK io;
2745     FILE_INTERNAL_INFORMATION info;
2746     HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
2747
2748     status = NtQueryInformationFile( handle, &io, &info, sizeof(info), FileInternalInformation );
2749     if (status)
2750     {
2751         if( VerifyConsoleIoHandle( handle))
2752             IsConsoleIOHandle = 1;
2753         else {
2754             SET_AX( context, RtlNtStatusToDosError(status) );
2755             SET_CFLAG( context );
2756             return;
2757         }
2758     } else {
2759         UINT i;
2760         for (i = 0; i < NB_MAGIC_DEVICES; i++)
2761         {
2762             if (!magic_devices[i].handle) continue;
2763             if (magic_devices[i].index.QuadPart == info.IndexNumber.QuadPart)
2764             {
2765                 /* found it */
2766                 magic_devices[i].ioctl_handler( context );
2767                 return;
2768             }
2769         }
2770     }
2771
2772     /* no magic device found, do default handling */
2773
2774     switch (AL_reg(context))
2775     {
2776     case 0x00: /* GET DEVICE INFORMATION */
2777         TRACE( "IOCTL - GET DEVICE INFORMATION - %d\n", BX_reg(context) );
2778         if (IsConsoleIOHandle || GetFileType(handle) == FILE_TYPE_CHAR)
2779         {
2780             /*
2781              * Returns attribute word in DX: 
2782              *   Bit 14 - Device driver can process IOCTL requests.
2783              *   Bit 13 - Output until busy supported.
2784              *   Bit 11 - Driver supports OPEN/CLOSE calls.
2785              *   Bit  8 - Unknown.
2786              *   Bit  7 - Set (indicates device).
2787              *   Bit  6 - EOF on input.
2788              *   Bit  5 - Raw (binary) mode.
2789              *   Bit  4 - Device is special (uses int29).
2790              *   Bit  3 - Clock device.
2791              *   Bit  2 - NUL device.
2792              *   Bit  1 - Console output device.
2793              *   Bit  0 - Console input device.
2794              */
2795             SET_DX( context, IsConsoleIOHandle ? 0x80c3 : 0x80c0 /* FIXME */ );
2796         }
2797         else
2798         {
2799             /*
2800              * Returns attribute word in DX: 
2801              *   Bit 15    - File is remote.
2802              *   Bit 14    - Don't set file date/time on closing.
2803              *   Bit 11    - Media not removable.
2804              *   Bit  8    - Generate int24 if no disk space on write 
2805              *               or read past end of file
2806              *   Bit  7    - Clear (indicates file).
2807              *   Bit  6    - File has not been written.
2808              *   Bit  5..0 - Drive number (0=A:,...)
2809              *
2810              * FIXME: Should check if file is on remote or removable drive.
2811              * FIXME: Should use drive file is located on (and not current).
2812              */
2813             SET_DX( context, 0x0140 + INT21_GetCurrentDrive() );
2814         }
2815         break;
2816
2817     case 0x0a: /* CHECK IF HANDLE IS REMOTE */
2818         TRACE( "IOCTL - CHECK IF HANDLE IS REMOTE - %d\n", BX_reg(context) );
2819         /*
2820          * Returns attribute word in DX:
2821          *   Bit 15 - Set if remote.
2822          *   Bit 14 - Set if date/time not set on close.
2823          *
2824          * FIXME: Should check if file is on remote drive.
2825          */
2826         SET_DX( context, 0 );
2827         break;
2828
2829     case 0x01: /* SET DEVICE INFORMATION */
2830     case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
2831     case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
2832     case 0x06: /* GET INPUT STATUS */
2833     case 0x07: /* GET OUTPUT STATUS */
2834     case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
2835     case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
2836     default:
2837         INT_BARF( context, 0x21 );
2838         break;
2839     }
2840 }
2841
2842
2843 /***********************************************************************
2844  *           INT21_Ioctl
2845  *
2846  * Handler for function 0x44.
2847  */
2848 static void INT21_Ioctl( CONTEXT86 *context )
2849 {
2850     switch (AL_reg(context))
2851     {
2852     case 0x00:
2853     case 0x01:
2854     case 0x02:
2855     case 0x03:
2856         INT21_Ioctl_Char( context );
2857         break;
2858
2859     case 0x04:
2860     case 0x05:
2861         INT21_Ioctl_Block( context );
2862         break;
2863
2864     case 0x06:
2865     case 0x07:
2866         INT21_Ioctl_Char( context );
2867         break;
2868
2869     case 0x08:
2870     case 0x09:
2871         INT21_Ioctl_Block( context );
2872         break;
2873
2874     case 0x0a:
2875         INT21_Ioctl_Char( context );
2876         break;
2877
2878     case 0x0b: /* SET SHARING RETRY COUNT */
2879         TRACE( "SET SHARING RETRY COUNT: Pause %d, retries %d.\n",
2880                CX_reg(context), DX_reg(context) );
2881         if (!CX_reg(context))
2882         {
2883             SET_AX( context, 1 );
2884             SET_CFLAG( context );
2885         }
2886         else
2887         {
2888             DOSDEV_SetSharingRetry( CX_reg(context), DX_reg(context) );
2889             RESET_CFLAG( context );
2890         }
2891         break;
2892
2893     case 0x0c:
2894         INT21_Ioctl_Char( context );
2895         break;
2896
2897     case 0x0d:
2898     case 0x0e:
2899     case 0x0f:
2900         INT21_Ioctl_Block( context );
2901         break;
2902
2903     case 0x10:
2904         INT21_Ioctl_Char( context );
2905         break;
2906
2907     case 0x11:
2908         INT21_Ioctl_Block( context );
2909         break;
2910
2911     case 0x12: /*  DR DOS - DETERMINE DOS TYPE (OBSOLETE FUNCTION) */
2912         TRACE( "DR DOS - DETERMINE DOS TYPE (OBSOLETE FUNCTION)\n" );
2913         SET_CFLAG(context);        /* Error / This is not DR DOS. */
2914         SET_AX( context, 0x0001 ); /* Invalid function */
2915         break;
2916
2917     case 0x52: /* DR DOS - DETERMINE DOS TYPE */
2918         TRACE( "DR DOS - DETERMINE DOS TYPE\n" );
2919         SET_CFLAG(context);        /* Error / This is not DR DOS. */
2920         SET_AX( context, 0x0001 ); /* Invalid function */
2921         break;
2922
2923     case 0xe0:  /* Sun PC-NFS API */
2924         TRACE( "Sun PC-NFS API\n" );
2925         /* not installed */
2926         break;
2927
2928     default:
2929         INT_BARF( context, 0x21 );
2930     }
2931 }
2932
2933
2934 /***********************************************************************
2935  *           INT21_Fat32
2936  *
2937  * Handler for function 0x73.
2938  */
2939 static BOOL INT21_Fat32( CONTEXT86 *context )
2940 {
2941     switch (AL_reg(context))
2942     {
2943     case 0x02: /* FAT32 - GET EXTENDED DPB */
2944         {
2945             BYTE drive = INT21_MapDrive( DL_reg(context) );
2946             WORD *ptr = CTX_SEG_OFF_TO_LIN(context, 
2947                                            context->SegEs, context->Edi);
2948             INT21_DPB *target = (INT21_DPB*)(ptr + 1);
2949             INT21_DPB *source;
2950
2951             TRACE( "FAT32 - GET EXTENDED DPB %d\n", DL_reg(context) );
2952
2953             if ( CX_reg(context) < sizeof(INT21_DPB) + 2 || *ptr < sizeof(INT21_DPB) )
2954             {
2955                 SetLastError( ERROR_BAD_LENGTH );
2956                 return FALSE;
2957             }
2958
2959             if ( !INT21_FillDrivePB( drive ) )
2960             {
2961                 SetLastError( ERROR_INVALID_DRIVE );
2962                 return FALSE;
2963             }
2964
2965             source = &INT21_GetHeapPointer()->misc_dpb_list[drive];
2966
2967             *ptr = sizeof(INT21_DPB);
2968             *target = *source;
2969
2970             if (LOWORD(context->Esi) != 0xF1A6)
2971             {
2972                 target->driver_header = 0;
2973                 target->next          = 0;
2974             }
2975             else
2976             {
2977                 FIXME( "Caller requested driver and next DPB pointers!\n" );
2978             }
2979         }
2980         break;
2981
2982     case 0x03: /* FAT32 - GET EXTENDED FREE SPACE ON DRIVE */
2983         {
2984             WCHAR dirW[MAX_PATH];
2985             char *dirA = CTX_SEG_OFF_TO_LIN( context,
2986                                              context->SegDs, context->Edx );
2987             BYTE *data = CTX_SEG_OFF_TO_LIN( context, 
2988                                              context->SegEs, context->Edi );
2989             DWORD cluster_sectors;
2990             DWORD sector_bytes;
2991             DWORD free_clusters;
2992             DWORD total_clusters;
2993
2994             TRACE( "FAT32 - GET EXTENDED FREE SPACE ON DRIVE %s\n", dirA );
2995             MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
2996
2997             if (CX_reg(context) < 44)
2998             {
2999                 SetLastError( ERROR_BAD_LENGTH );
3000                 return FALSE;
3001             }
3002
3003             if (!GetDiskFreeSpaceW( dirW, &cluster_sectors, &sector_bytes,
3004                                     &free_clusters, &total_clusters ))
3005                 return FALSE;
3006
3007             *(WORD*) (data +  0) = 44; /* size of structure */
3008             *(WORD*) (data +  2) = 0;  /* version */
3009             *(DWORD*)(data +  4) = cluster_sectors;
3010             *(DWORD*)(data +  8) = sector_bytes;
3011             *(DWORD*)(data + 12) = free_clusters;
3012             *(DWORD*)(data + 16) = total_clusters;
3013
3014             /*
3015              * Below we have free/total sectors and
3016              * free/total allocation units without adjustment
3017              * for compression. We fake both using cluster information.
3018              */
3019             *(DWORD*)(data + 20) = free_clusters * cluster_sectors;
3020             *(DWORD*)(data + 24) = total_clusters * cluster_sectors;
3021             *(DWORD*)(data + 28) = free_clusters;
3022             *(DWORD*)(data + 32) = total_clusters;
3023             
3024             /*
3025              * Between (data + 36) and (data + 43) there
3026              * are eight reserved bytes.
3027              */
3028         }
3029         break;
3030
3031     default:
3032         INT_BARF( context, 0x21 );
3033     }
3034
3035     return TRUE;
3036 }
3037
3038 static void INT21_ConvertFindDataWtoA(WIN32_FIND_DATAA *dataA,
3039                                       const WIN32_FIND_DATAW *dataW)
3040 {
3041     dataA->dwFileAttributes = dataW->dwFileAttributes;
3042     dataA->ftCreationTime   = dataW->ftCreationTime;
3043     dataA->ftLastAccessTime = dataW->ftLastAccessTime;
3044     dataA->ftLastWriteTime  = dataW->ftLastWriteTime;
3045     dataA->nFileSizeHigh    = dataW->nFileSizeHigh;
3046     dataA->nFileSizeLow     = dataW->nFileSizeLow;
3047     WideCharToMultiByte( CP_OEMCP, 0, dataW->cFileName, -1,
3048                          dataA->cFileName, sizeof(dataA->cFileName), NULL, NULL );
3049     WideCharToMultiByte( CP_OEMCP, 0, dataW->cAlternateFileName, -1,
3050                          dataA->cAlternateFileName, sizeof(dataA->cAlternateFileName), NULL, NULL );
3051 }
3052
3053 /***********************************************************************
3054  *           INT21_LongFilename
3055  *
3056  * Handler for function 0x71.
3057  */
3058 static void INT21_LongFilename( CONTEXT86 *context )
3059 {
3060     BOOL bSetDOSExtendedError = FALSE;
3061     WCHAR pathW[MAX_PATH];
3062     char* pathA;
3063
3064     switch (AL_reg(context))
3065     {
3066     case 0x0d: /* RESET DRIVE */
3067         INT_BARF( context, 0x21 );
3068         break;
3069
3070     case 0x39: /* LONG FILENAME - MAKE DIRECTORY */
3071         if (!INT21_CreateDirectory( context ))
3072             bSetDOSExtendedError = TRUE;
3073         break;
3074
3075     case 0x3a: /* LONG FILENAME - REMOVE DIRECTORY */
3076         pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3077
3078         TRACE( "LONG FILENAME - REMOVE DIRECTORY %s\n", pathA);
3079         MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3080         if (!RemoveDirectoryW( pathW )) bSetDOSExtendedError = TRUE;
3081         break;
3082
3083     case 0x3b: /* LONG FILENAME - CHANGE DIRECTORY */
3084         if (!INT21_SetCurrentDirectory( context ))
3085             bSetDOSExtendedError = TRUE;
3086         break;
3087
3088     case 0x41: /* LONG FILENAME - DELETE FILE */
3089         pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3090
3091         TRACE( "LONG FILENAME - DELETE FILE %s\n", pathA );
3092         MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3093
3094         if (!DeleteFileW( pathW )) bSetDOSExtendedError = TRUE;
3095         break;
3096
3097     case 0x43: /* LONG FILENAME - EXTENDED GET/SET FILE ATTRIBUTES */
3098         if (!INT21_FileAttributes( context, BL_reg(context), TRUE ))
3099             bSetDOSExtendedError = TRUE;
3100         break;
3101
3102     case 0x47: /* LONG FILENAME - GET CURRENT DIRECTORY */
3103         if (!INT21_GetCurrentDirectory( context, TRUE ))
3104             bSetDOSExtendedError = TRUE;
3105         break;
3106
3107     case 0x4e: /* LONG FILENAME - FIND FIRST MATCHING FILE */
3108         {
3109             HANDLE              handle;
3110             HGLOBAL16           h16;
3111             WIN32_FIND_DATAW    dataW;
3112             WIN32_FIND_DATAA*   dataA;
3113
3114             pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx);
3115             TRACE(" LONG FILENAME - FIND FIRST MATCHING FILE for %s\n", pathA);
3116
3117             MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3118             handle = FindFirstFileW(pathW, &dataW);
3119
3120             dataA = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi);
3121             if (handle != INVALID_HANDLE_VALUE && 
3122                 (h16 = GlobalAlloc16(GMEM_MOVEABLE, sizeof(handle))))
3123             {
3124                 HANDLE* ptr = GlobalLock16( h16 );
3125                 *ptr = handle;
3126                 GlobalUnlock16( h16 );
3127                 SET_AX( context, h16 );
3128                 INT21_ConvertFindDataWtoA(dataA, &dataW);
3129             }
3130             else
3131             {           
3132                 if (handle != INVALID_HANDLE_VALUE) FindClose(handle);
3133                 SET_AX( context, INVALID_HANDLE_VALUE16);
3134                 bSetDOSExtendedError = TRUE;
3135             }
3136         }
3137         break;
3138
3139     case 0x4f: /* LONG FILENAME - FIND NEXT MATCHING FILE */
3140         {
3141             HGLOBAL16           h16 = BX_reg(context);
3142             HANDLE*             ptr;
3143             WIN32_FIND_DATAW    dataW;
3144             WIN32_FIND_DATAA*   dataA;
3145
3146             TRACE("LONG FILENAME - FIND NEXT MATCHING FILE for handle %d\n",
3147                   BX_reg(context));
3148
3149             dataA = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi);
3150
3151             if (h16 != INVALID_HANDLE_VALUE16 && (ptr = GlobalLock16( h16 )))
3152             {
3153                 if (!FindNextFileW(*ptr, &dataW)) bSetDOSExtendedError = TRUE;
3154                 else INT21_ConvertFindDataWtoA(dataA, &dataW);
3155                 GlobalUnlock16( h16 );
3156             }
3157             else
3158             {
3159                 SetLastError( ERROR_INVALID_HANDLE );
3160                 bSetDOSExtendedError = TRUE;
3161             }
3162         }
3163         break;
3164
3165     case 0x56: /* LONG FILENAME - RENAME FILE */
3166         if (!INT21_RenameFile(context))
3167             bSetDOSExtendedError = TRUE;
3168         break;
3169
3170     case 0x60: /* LONG FILENAME - CONVERT PATH */
3171         {
3172             WCHAR   res[MAX_PATH];
3173
3174             switch (CL_reg(context))
3175             {
3176             case 0x00:  /* "truename" - Canonicalize path */
3177                 /* 
3178                  * FIXME: This is not 100% equal to 0x01 case, 
3179                  *        if you fix this, fix int21 subfunction 0x60, too.
3180                  */
3181
3182             case 0x01:  /* Get short filename or path */
3183                 MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
3184                 if (!GetShortPathNameW(pathW, res, 67))
3185                     bSetDOSExtendedError = TRUE;
3186                 else
3187                 {
3188                     SET_AX( context, 0 );
3189                     WideCharToMultiByte(CP_OEMCP, 0, res, -1, 
3190                                         CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi), 
3191                                         67, NULL, NULL);
3192                 }
3193                 break;
3194             
3195             case 0x02:  /* Get canonical long filename or path */
3196                 MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
3197                 if (!GetFullPathNameW(pathW, 128, res, NULL))
3198                     bSetDOSExtendedError = TRUE;
3199                 else
3200                 {
3201                     SET_AX( context, 0 );
3202                     WideCharToMultiByte(CP_OEMCP, 0, res, -1, 
3203                                         CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi), 
3204                                         128, NULL, NULL);
3205                 }
3206                 break;
3207             default:
3208                 FIXME("Unimplemented long file name function:\n");
3209                 INT_BARF( context, 0x21 );
3210                 SET_CFLAG(context);
3211                 SET_AL( context, 0 );
3212                 break;
3213             }
3214         }
3215         break;
3216
3217     case 0x6c: /* LONG FILENAME - CREATE OR OPEN FILE */
3218         if (!INT21_CreateFile( context, context->Esi, TRUE,
3219                                BX_reg(context), DL_reg(context) ))
3220             bSetDOSExtendedError = TRUE;
3221         break;
3222
3223     case 0xa0: /* LONG FILENAME - GET VOLUME INFORMATION */
3224         {
3225             DWORD filename_len, flags;
3226             WCHAR dstW[8];
3227
3228             pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx);
3229
3230             TRACE("LONG FILENAME - GET VOLUME INFORMATION for drive having root dir '%s'.\n", pathA);
3231             SET_AX( context, 0 );
3232             MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3233             if (!GetVolumeInformationW( pathW, NULL, 0, NULL, &filename_len,
3234                                         &flags, dstW, 8 ))
3235             {
3236                 INT_BARF( context, 0x21 );
3237                 SET_CFLAG(context);
3238                 break;
3239             }
3240             SET_BX( context, flags | 0x4000 ); /* support for LFN functions */
3241             SET_CX( context, filename_len );
3242             SET_DX( context, MAX_PATH ); /* FIXME: which len if DRIVE_SHORT_NAMES ? */
3243             WideCharToMultiByte(CP_OEMCP, 0, dstW, -1, 
3244                                 CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi), 
3245                                 8, NULL, NULL);
3246         }
3247         break;
3248
3249     case 0xa1: /* LONG FILENAME - "FindClose" - TERMINATE DIRECTORY SEARCH */
3250         {
3251             HGLOBAL16 h16 = BX_reg(context);
3252             HANDLE* ptr;
3253
3254             TRACE("LONG FILENAME - FINDCLOSE for handle %d\n",
3255                   BX_reg(context));
3256             if (h16 != INVALID_HANDLE_VALUE16 && (ptr = GlobalLock16( h16 )))
3257             {
3258                 if (!FindClose( *ptr )) bSetDOSExtendedError = TRUE;
3259                 GlobalUnlock16( h16 );
3260                 GlobalFree16( h16 );
3261             }
3262             else
3263             {
3264                 SetLastError( ERROR_INVALID_HANDLE );
3265                 bSetDOSExtendedError = TRUE;
3266             }
3267         }
3268         break;
3269           
3270     case 0xa6: /* LONG FILENAME - GET FILE INFO BY HANDLE */
3271         {
3272             HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
3273             BY_HANDLE_FILE_INFORMATION *info =
3274                 CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3275             
3276             TRACE( "LONG FILENAME - GET FILE INFO BY HANDLE\n" );
3277             
3278             if (!GetFileInformationByHandle(handle, info))
3279                 bSetDOSExtendedError = TRUE;
3280         }
3281         break;
3282
3283     case 0xa7: /* LONG FILENAME - CONVERT TIME */
3284         switch (BL_reg(context))
3285         {
3286         case 0x00: /* FILE TIME TO DOS TIME */
3287             {
3288                 WORD      date, time;
3289                 FILETIME *filetime = CTX_SEG_OFF_TO_LIN(context,
3290                                                         context->SegDs,
3291                                                         context->Esi);
3292
3293                 TRACE( "LONG FILENAME - FILE TIME TO DOS TIME\n" );
3294
3295                 FileTimeToDosDateTime( filetime, &date, &time );
3296
3297                 SET_DX( context, date );
3298                 SET_CX( context, time );
3299
3300                 /*
3301                  * FIXME: BH has number of 10-millisecond units 
3302                  * past time in CX.
3303                  */
3304                 SET_BH( context, 0 );
3305             }
3306             break;
3307
3308         case 0x01: /* DOS TIME TO FILE TIME */
3309             {
3310                 FILETIME *filetime = CTX_SEG_OFF_TO_LIN(context,
3311                                                         context->SegEs,
3312                                                         context->Edi);
3313
3314                 TRACE( "LONG FILENAME - DOS TIME TO FILE TIME\n" );
3315
3316                 /*
3317                  * FIXME: BH has number of 10-millisecond units 
3318                  * past time in CX.
3319                  */
3320                 DosDateTimeToFileTime( DX_reg(context), CX_reg(context),
3321                                        filetime );
3322             }
3323             break;
3324
3325         default:
3326             INT_BARF( context, 0x21 );
3327             break;
3328         }
3329         break;
3330
3331     case 0xa8: /* LONG FILENAME - GENERATE SHORT FILENAME */
3332     case 0xa9: /* LONG FILENAME - SERVER CREATE OR OPEN FILE */
3333     case 0xaa: /* LONG FILENAME - SUBST */
3334     default:
3335         FIXME("Unimplemented long file name function:\n");
3336         INT_BARF( context, 0x21 );
3337         SET_CFLAG(context);
3338         SET_AL( context, 0 );
3339         break;
3340     }
3341
3342     if (bSetDOSExtendedError)
3343     {
3344         SET_AX( context, GetLastError() );
3345         SET_CFLAG( context );
3346     }
3347 }
3348
3349
3350 /***********************************************************************
3351  *           INT21_RenameFile
3352  *
3353  * Handler for:
3354  * - function 0x56
3355  * - subfunction 0x56 of function 0x71
3356  * - subfunction 0xff of function 0x43 (CL == 0x56)
3357  */
3358 static BOOL INT21_RenameFile( CONTEXT86 *context )
3359 {
3360     WCHAR fromW[MAX_PATH];
3361     WCHAR toW[MAX_PATH];
3362     char *fromA = CTX_SEG_OFF_TO_LIN(context, 
3363                                      context->SegDs,context->Edx);
3364     char *toA = CTX_SEG_OFF_TO_LIN(context, 
3365                                    context->SegEs,context->Edi);
3366
3367     TRACE( "RENAME FILE %s to %s\n", fromA, toA );
3368     MultiByteToWideChar(CP_OEMCP, 0, fromA, -1, fromW, MAX_PATH);
3369     MultiByteToWideChar(CP_OEMCP, 0, toA, -1, toW, MAX_PATH);
3370
3371     return MoveFileW( fromW, toW );
3372 }
3373
3374
3375 /***********************************************************************
3376  *           INT21_NetworkFunc
3377  *
3378  * Handler for:
3379  * - function 0x5e
3380  */
3381 static BOOL INT21_NetworkFunc (CONTEXT86 *context)
3382 {
3383     switch (AL_reg(context)) 
3384     {
3385     case 0x00: /* Get machine name. */
3386         {
3387             WCHAR dstW[MAX_COMPUTERNAME_LENGTH + 1];
3388             DWORD s = sizeof(dstW) / sizeof(WCHAR);
3389             int len;
3390
3391             char *dst = CTX_SEG_OFF_TO_LIN (context,context->SegDs,context->Edx);
3392             TRACE("getting machine name to %p\n", dst);
3393             if (!GetComputerNameW(dstW, &s) ||
3394                 !WideCharToMultiByte(CP_OEMCP, 0, dstW, -1, dst, 16, NULL, NULL))
3395             {
3396                 WARN("failed!\n");
3397                 SetLastError( ER_NoNetwork );
3398                 return TRUE;
3399             }
3400             for (len = strlen(dst); len < 15; len++) dst[len] = ' ';
3401             dst[15] = 0;
3402             SET_CH( context, 1 ); /* Valid */
3403             SET_CL( context, 1 ); /* NETbios number??? */
3404             TRACE("returning %s\n", debugstr_an(dst, 16));
3405             return FALSE;
3406         }
3407
3408     default:
3409         SetLastError( ER_NoNetwork );
3410         return TRUE;
3411     }
3412 }
3413
3414 /******************************************************************
3415  *              INT21_GetDiskSerialNumber
3416  *
3417  */
3418 static int INT21_GetDiskSerialNumber( CONTEXT86 *context )
3419 {
3420     BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3421     WCHAR path[] = {'A',':',0}, label[11];
3422     DWORD serial;
3423
3424     path[0] += INT21_MapDrive(BL_reg(context));
3425     if (!GetVolumeInformationW( path, label, 11, &serial, NULL, NULL, NULL, 0))
3426     {
3427         SetLastError( ERROR_INVALID_DRIVE );
3428         return 0;
3429     }
3430
3431     *(WORD *)dataptr = 0;
3432     memcpy(dataptr + 2, &serial, sizeof(DWORD));
3433     WideCharToMultiByte(CP_OEMCP, 0, label, 11, (LPSTR)dataptr + 6, 11, NULL, NULL);
3434     memcpy(dataptr + 17, "FAT16   ", 8);
3435     return 1;
3436 }
3437
3438
3439 /******************************************************************
3440  *              INT21_SetDiskSerialNumber
3441  *
3442  */
3443 static int INT21_SetDiskSerialNumber( CONTEXT86 *context )
3444 {
3445 #if 0
3446     BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3447     int drive = INT21_MapDrive(BL_reg(context));
3448
3449     if (!is_valid_drive(drive))
3450     {
3451         SetLastError( ERROR_INVALID_DRIVE );
3452         return 0;
3453     }
3454
3455     DRIVE_SetSerialNumber( drive, *(DWORD *)(dataptr + 2) );
3456     return 1;
3457 #else
3458     FIXME("Setting drive serial number is no longer supported\n");
3459     SetLastError( ERROR_NOT_SUPPORTED );
3460     return 0;
3461 #endif
3462 }
3463
3464
3465 /******************************************************************
3466  *              INT21_GetFreeDiskSpace
3467  *
3468  */
3469 static int INT21_GetFreeDiskSpace( CONTEXT86 *context )
3470 {
3471     DWORD cluster_sectors, sector_bytes, free_clusters, total_clusters;
3472     WCHAR root[] = {'A',':','\\',0};
3473     const DWORD max_clusters = 0x3d83;
3474     const DWORD max_sectors_per_cluster = 0x7f;
3475     const DWORD max_bytes_per_sector = 0x200;
3476
3477     root[0] += INT21_MapDrive(DL_reg(context));
3478     if (!GetDiskFreeSpaceW( root, &cluster_sectors, &sector_bytes,
3479                             &free_clusters, &total_clusters )) return 0;
3480
3481     /* Some old win31 apps (Lotus SmartSuite 5.1) crap out if there's too
3482      * much disk space, so Windows XP seems to apply the following limits:
3483      *  cluster_sectors <= 0x7f
3484      *  sector size <= 0x200
3485      *  clusters <= 0x3D83
3486      * This means total reported space is limited to about 1GB.
3487      */
3488
3489     /* Make sure bytes-per-sector is in [, max] */
3490     while (sector_bytes > max_bytes_per_sector) {
3491         sector_bytes >>= 1;
3492         free_clusters <<= 1;
3493         total_clusters <<= 1;
3494     }
3495     /* Then make sure sectors-per-cluster is in [max/2, max]. */
3496     while (cluster_sectors <= max_sectors_per_cluster/2) {
3497         cluster_sectors <<= 1;
3498         free_clusters >>= 1;
3499         total_clusters >>= 1;
3500     }
3501     while (cluster_sectors > max_sectors_per_cluster) {
3502         cluster_sectors >>= 1;
3503         free_clusters <<= 1;
3504         total_clusters <<= 1;
3505     }
3506
3507     /* scale up sectors_per_cluster to exactly max_sectors_per_cluster.
3508      * We could skip this, but that would impose an artificially low
3509      * limit on reported disk space.
3510      * To avoid overflow, first apply a preliminary cap on sector count;
3511      * this will not affect the correctness of the final result,
3512      * because if the preliminary cap hits, the final one will, too.
3513      */
3514     if (total_clusters > 4 * max_clusters)
3515         total_clusters = 4 * max_clusters;
3516     if (free_clusters > 4 * max_clusters)
3517         free_clusters = 4 * max_clusters;
3518     if (cluster_sectors < max_sectors_per_cluster) {
3519         free_clusters *= cluster_sectors;
3520         free_clusters /= max_sectors_per_cluster;
3521         total_clusters *= cluster_sectors;
3522         total_clusters /= max_sectors_per_cluster;
3523         cluster_sectors = max_sectors_per_cluster;
3524     }
3525
3526     /* Finally, apply real cluster count cap. */
3527     if (total_clusters > max_clusters)
3528         total_clusters = max_clusters;
3529     if (free_clusters > max_clusters)
3530         free_clusters = max_clusters;
3531
3532     SET_AX( context, cluster_sectors );
3533     SET_BX( context, free_clusters );
3534     SET_CX( context, sector_bytes );
3535     SET_DX( context, total_clusters );
3536     return 1;
3537 }
3538
3539 /******************************************************************
3540  *              INT21_GetDriveAllocInfo
3541  *
3542  */
3543 static int INT21_GetDriveAllocInfo( CONTEXT86 *context, BYTE drive )
3544 {
3545     INT21_DPB  *dpb;
3546
3547     drive = INT21_MapDrive( drive );
3548     if (!INT21_FillDrivePB( drive )) return 0;
3549     dpb = &(INT21_GetHeapPointer()->misc_dpb_list[drive]);
3550     SET_AL( context, dpb->cluster_sectors + 1 );
3551     SET_CX( context, dpb->sector_bytes );
3552     SET_DX( context, dpb->num_clusters1 );
3553
3554     context->SegDs = INT21_GetHeapSelector( context );
3555     SET_BX( context, offsetof( INT21_HEAP, misc_dpb_list[drive].media_ID ) );
3556     return 1;
3557 }
3558
3559 /***********************************************************************
3560  *           INT21_GetExtendedError
3561  */
3562 static void INT21_GetExtendedError( CONTEXT86 *context )
3563 {
3564     BYTE class, action, locus;
3565     WORD error = GetLastError();
3566
3567     switch(error)
3568     {
3569     case ERROR_SUCCESS:
3570         class = action = locus = 0;
3571         break;
3572     case ERROR_DIR_NOT_EMPTY:
3573         class  = EC_Exists;
3574         action = SA_Ignore;
3575         locus  = EL_Disk;
3576         break;
3577     case ERROR_ACCESS_DENIED:
3578         class  = EC_AccessDenied;
3579         action = SA_Abort;
3580         locus  = EL_Disk;
3581         break;
3582     case ERROR_CANNOT_MAKE:
3583         class  = EC_AccessDenied;
3584         action = SA_Abort;
3585         locus  = EL_Unknown;
3586         break;
3587     case ERROR_DISK_FULL:
3588     case ERROR_HANDLE_DISK_FULL:
3589         class  = EC_MediaError;
3590         action = SA_Abort;
3591         locus  = EL_Disk;
3592         break;
3593     case ERROR_FILE_EXISTS:
3594     case ERROR_ALREADY_EXISTS:
3595         class  = EC_Exists;
3596         action = SA_Abort;
3597         locus  = EL_Disk;
3598         break;
3599     case ERROR_FILE_NOT_FOUND:
3600         class  = EC_NotFound;
3601         action = SA_Abort;
3602         locus  = EL_Disk;
3603         break;
3604     case ERROR_GEN_FAILURE:
3605         class  = EC_SystemFailure;
3606         action = SA_Abort;
3607         locus  = EL_Unknown;
3608         break;
3609     case ERROR_INVALID_DRIVE:
3610         class  = EC_MediaError;
3611         action = SA_Abort;
3612         locus  = EL_Disk;
3613         break;
3614     case ERROR_INVALID_HANDLE:
3615         class  = EC_ProgramError;
3616         action = SA_Abort;
3617         locus  = EL_Disk;
3618         break;
3619     case ERROR_LOCK_VIOLATION:
3620         class  = EC_AccessDenied;
3621         action = SA_Abort;
3622         locus  = EL_Disk;
3623         break;
3624     case ERROR_NO_MORE_FILES:
3625         class  = EC_MediaError;
3626         action = SA_Abort;
3627         locus  = EL_Disk;
3628         break;
3629     case ER_NoNetwork:
3630         class  = EC_NotFound;
3631         action = SA_Abort;
3632         locus  = EL_Network;
3633         break;
3634     case ERROR_NOT_ENOUGH_MEMORY:
3635         class  = EC_OutOfResource;
3636         action = SA_Abort;
3637         locus  = EL_Memory;
3638         break;
3639     case ERROR_PATH_NOT_FOUND:
3640         class  = EC_NotFound;
3641         action = SA_Abort;
3642         locus  = EL_Disk;
3643         break;
3644     case ERROR_SEEK:
3645         class  = EC_NotFound;
3646         action = SA_Ignore;
3647         locus  = EL_Disk;
3648         break;
3649     case ERROR_SHARING_VIOLATION:
3650         class  = EC_Temporary;
3651         action = SA_Retry;
3652         locus  = EL_Disk;
3653         break;
3654     case ERROR_TOO_MANY_OPEN_FILES:
3655         class  = EC_ProgramError;
3656         action = SA_Abort;
3657         locus  = EL_Disk;
3658         break;
3659     default:
3660         FIXME("Unknown error %d\n", error );
3661         class  = EC_SystemFailure;
3662         action = SA_Abort;
3663         locus  = EL_Unknown;
3664         break;
3665     }
3666     TRACE("GET EXTENDED ERROR code 0x%02x class 0x%02x action 0x%02x locus %02x\n",
3667            error, class, action, locus );
3668     SET_AX( context, error );
3669     SET_BH( context, class );
3670     SET_BL( context, action );
3671     SET_CH( context, locus );
3672 }
3673
3674 static BOOL INT21_CreateTempFile( CONTEXT86 *context )
3675 {
3676     static int counter = 0;
3677     char *name = CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx );
3678     char *p = name + strlen(name);
3679
3680     /* despite what Ralf Brown says, some programs seem to call without
3681      * ending backslash (DOS accepts that, so we accept it too) */
3682     if ((p == name) || (p[-1] != '\\')) *p++ = '\\';
3683
3684     for (;;)
3685     {
3686         sprintf( p, "wine%04x.%03d", (int)getpid(), counter );
3687         counter = (counter + 1) % 1000;
3688
3689         SET_AX( context, 
3690                 Win32HandleToDosFileHandle( 
3691                     CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
3692                                  FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
3693                                  CREATE_NEW, 0, 0 ) ) );
3694         if (AX_reg(context) != HFILE_ERROR16)
3695         {
3696             TRACE("created %s\n", name );
3697             return TRUE;
3698         }
3699         if (GetLastError() != ERROR_FILE_EXISTS) return FALSE;
3700     }
3701 }
3702
3703 /***********************************************************************
3704  *           DOSFS_ToDosFCBFormat
3705  *
3706  * Convert a file name to DOS FCB format (8+3 chars, padded with blanks),
3707  * expanding wild cards and converting to upper-case in the process.
3708  * File name can be terminated by '\0', '\\' or '/'.
3709  * Return FALSE if the name is not a valid DOS name.
3710  * 'buffer' must be at least 12 characters long.
3711  */
3712 /* Chars we don't want to see in DOS file names */
3713 static BOOL INT21_ToDosFCBFormat( LPCWSTR name, LPWSTR buffer )
3714 {
3715     static const WCHAR invalid_chars[] = {'*','?','<','>','|','\\','"','+','=',',',';','[',']',' ','\345',0};
3716     LPCWSTR p = name;
3717     int i;
3718
3719     /* Check for "." and ".." */
3720     if (*p == '.')
3721     {
3722         p++;
3723         buffer[0] = '.';
3724         for(i = 1; i < 11; i++) buffer[i] = ' ';
3725         buffer[11] = 0;
3726         if (*p == '.')
3727         {
3728             buffer[1] = '.';
3729             p++;
3730         }
3731         return (!*p || (*p == '/') || (*p == '\\'));
3732     }
3733
3734     for (i = 0; i < 8; i++)
3735     {
3736         switch(*p)
3737         {
3738         case '\0':
3739         case '\\':
3740         case '/':
3741         case '.':
3742             buffer[i] = ' ';
3743             break;
3744         case '?':
3745             p++;
3746             /* fall through */
3747         case '*':
3748             buffer[i] = '?';
3749             break;
3750         default:
3751             if (strchrW( invalid_chars, *p )) return FALSE;
3752             buffer[i] = toupperW(*p);
3753             p++;
3754             break;
3755         }
3756     }
3757
3758     if (*p == '*')
3759     {
3760         /* Skip all chars after wildcard up to first dot */
3761         while (*p && (*p != '/') && (*p != '\\') && (*p != '.')) p++;
3762     }
3763     else
3764     {
3765         /* Check if name too long */
3766         if (*p && (*p != '/') && (*p != '\\') && (*p != '.')) return FALSE;
3767     }
3768     if (*p == '.') p++;  /* Skip dot */
3769
3770     for (i = 8; i < 11; i++)
3771     {
3772         switch(*p)
3773         {
3774         case '\0':
3775         case '\\':
3776         case '/':
3777             buffer[i] = ' ';
3778             break;
3779         case '.':
3780             return FALSE;  /* Second extension not allowed */
3781         case '?':
3782             p++;
3783             /* fall through */
3784         case '*':
3785             buffer[i] = '?';
3786             break;
3787         default:
3788             if (strchrW( invalid_chars, *p )) return FALSE;
3789             buffer[i] = toupperW(*p);
3790             p++;
3791             break;
3792         }
3793     }
3794     buffer[11] = '\0';
3795
3796     /* at most 3 character of the extension are processed
3797      * is something behind this ?
3798      */
3799     while (*p == '*' || *p == ' ') p++; /* skip wildcards and spaces */
3800     return (!*p || (*p == '/') || (*p == '\\'));
3801 }
3802
3803 static HANDLE       INT21_FindHandle;
3804 static const WCHAR *INT21_FindPath; /* will point to current dta->fullPath search */
3805
3806 /******************************************************************
3807  *              INT21_FindFirst
3808  */
3809 static int INT21_FindFirst( CONTEXT86 *context )
3810 {
3811     WCHAR *p, *q;
3812     const char *path;
3813     FINDFILE_DTA *dta = (FINDFILE_DTA *)INT21_GetCurrentDTA(context);
3814     WCHAR maskW[12], pathW[MAX_PATH];
3815     static const WCHAR wildcardW[] = {'*','.','*',0};
3816
3817     path = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3818     MultiByteToWideChar(CP_OEMCP, 0, path, -1, pathW, MAX_PATH);
3819
3820     p = strrchrW( pathW, '\\');
3821     q = strrchrW( pathW, '/');
3822     if (q>p) p = q;
3823     if (!p)
3824     {
3825         if (pathW[0] && pathW[1] == ':') p = pathW + 2;
3826         else p = pathW;
3827     }
3828     else p++;
3829
3830     /* Note: terminating NULL in dta->mask overwrites dta->search_attr
3831      *       (doesn't matter as it is set below anyway)
3832      */
3833     if (!INT21_ToDosFCBFormat( p, maskW ))
3834     {
3835         SetLastError( ERROR_FILE_NOT_FOUND );
3836         SET_AX( context, ERROR_FILE_NOT_FOUND );
3837         SET_CFLAG(context);
3838         return 0;
3839     }
3840     WideCharToMultiByte(CP_OEMCP, 0, maskW, 12, dta->mask, sizeof(dta->mask), NULL, NULL);
3841
3842     dta->fullPath = HeapAlloc( GetProcessHeap(), 0, sizeof(wildcardW) + (p - pathW)*sizeof(WCHAR) );
3843     memcpy( dta->fullPath, pathW, (p - pathW) * sizeof(WCHAR) );
3844     memcpy( dta->fullPath + (p - pathW), wildcardW, sizeof(wildcardW) );
3845     /* we must have a fully qualified file name in dta->fullPath
3846      * (we could have a UNC path, but this would lead to some errors later on)
3847      */
3848     dta->drive = toupperW(dta->fullPath[0]) - 'A';
3849     dta->count = 0;
3850     dta->search_attr = CL_reg(context);
3851     return 1;
3852 }
3853
3854 /******************************************************************
3855  *              match_short
3856  *
3857  * Check is a short path name (DTA unicode) matches a mask (FCB ansi)
3858  */
3859 static BOOL match_short(LPCWSTR shortW, LPCSTR maskA)
3860 {
3861     WCHAR mask[11], file[12];
3862     int i;
3863
3864     if (!INT21_ToDosFCBFormat( shortW, file )) return FALSE;
3865     MultiByteToWideChar(CP_OEMCP, 0, maskA, 11, mask, 11);
3866     for (i = 0; i < 11; i++)
3867         if (mask[i] != '?' && mask[i] != file[i]) return FALSE;
3868     return TRUE;
3869 }
3870
3871 static unsigned INT21_FindHelper(LPCWSTR fullPath, unsigned drive, unsigned count, 
3872                                  LPCSTR mask, unsigned search_attr, 
3873                                  WIN32_FIND_DATAW* entry)
3874 {
3875     unsigned ncalls;
3876
3877     if ((search_attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
3878     {
3879         WCHAR path[] = {' ',':',0};
3880
3881         if (count) return 0;
3882         path[0] = drive + 'A';
3883         if (!GetVolumeInformationW(path, entry->cAlternateFileName, 13, NULL, NULL, NULL, NULL, 0)) return 0;
3884         RtlSecondsSince1970ToTime( 0, (LARGE_INTEGER *)&entry->ftCreationTime );
3885         RtlSecondsSince1970ToTime( 0, (LARGE_INTEGER *)&entry->ftLastAccessTime );
3886         RtlSecondsSince1970ToTime( 0, (LARGE_INTEGER *)&entry->ftLastWriteTime );
3887         entry->dwFileAttributes = FA_LABEL;
3888         entry->nFileSizeHigh = entry->nFileSizeLow = 0;
3889         TRACE("returning %s as label\n", debugstr_w(entry->cAlternateFileName));
3890         return 1;
3891     }
3892
3893     if (!INT21_FindHandle || INT21_FindPath != fullPath || count == 0)
3894     {
3895         if (INT21_FindHandle) FindClose(INT21_FindHandle);
3896         INT21_FindHandle = FindFirstFileW(fullPath, entry);
3897         if (INT21_FindHandle == INVALID_HANDLE_VALUE)
3898         {
3899             INT21_FindHandle = 0;
3900             return 0;
3901         }
3902         INT21_FindPath = fullPath;
3903         /* we need to resync search */
3904         ncalls = count;
3905     }
3906     else ncalls = 1;
3907
3908     while (ncalls-- != 0)
3909     {
3910         if (!FindNextFileW(INT21_FindHandle, entry))
3911         {
3912             FindClose(INT21_FindHandle); INT21_FindHandle = 0;
3913             return 0;
3914         }
3915     }
3916     while (count < 0xffff)
3917     {
3918         count++;
3919         /* Check the file attributes, and path */
3920         if (!(entry->dwFileAttributes & ~search_attr) &&
3921             match_short(entry->cAlternateFileName[0] ? entry->cAlternateFileName : entry->cFileName,
3922                         mask))
3923         {
3924             return count;
3925         }
3926         if (!FindNextFileW(INT21_FindHandle, entry))
3927         {
3928             FindClose(INT21_FindHandle); INT21_FindHandle = 0;
3929             return 0;
3930         }
3931     }
3932     WARN("Too many directory entries in %s\n", debugstr_w(fullPath) );
3933     return 0;
3934 }
3935
3936 /******************************************************************
3937  *              INT21_FindNext
3938  */
3939 static int INT21_FindNext( CONTEXT86 *context )
3940 {
3941     FINDFILE_DTA *dta = (FINDFILE_DTA *)INT21_GetCurrentDTA(context);
3942     DWORD attr = dta->search_attr | FA_UNUSED | FA_ARCHIVE | FA_RDONLY;
3943     WIN32_FIND_DATAW entry;
3944     int n;
3945
3946     if (!dta->fullPath) return 0;
3947
3948     n = INT21_FindHelper(dta->fullPath, dta->drive, dta->count, 
3949                          dta->mask, attr, &entry);
3950     if (n)
3951     {
3952         dta->fileattr = entry.dwFileAttributes;
3953         dta->filesize = entry.nFileSizeLow;
3954         FileTimeToDosDateTime( &entry.ftLastWriteTime, &dta->filedate, &dta->filetime );
3955         if (entry.cAlternateFileName[0])
3956             WideCharToMultiByte(CP_OEMCP, 0, entry.cAlternateFileName, -1,
3957                                 dta->filename, 13, NULL, NULL);
3958         else
3959             WideCharToMultiByte(CP_OEMCP, 0, entry.cFileName, -1, dta->filename, 13, NULL, NULL);
3960
3961         if (!memchr(dta->mask,'?',11))
3962         {
3963             /* wildcardless search, release resources in case no findnext will
3964              * be issued, and as a workaround in case file creation messes up
3965              * findnext, as sometimes happens with pkunzip
3966              */
3967             HeapFree( GetProcessHeap(), 0, dta->fullPath );
3968             INT21_FindPath = dta->fullPath = NULL;
3969         }
3970         dta->count = n;
3971         return 1;
3972     }
3973     HeapFree( GetProcessHeap(), 0, dta->fullPath );
3974     INT21_FindPath = dta->fullPath = NULL;
3975     return 0;
3976 }
3977
3978 /* microsoft's programmers should be shot for using CP/M style int21
3979    calls in Windows for Workgroup's winfile.exe */
3980
3981 /******************************************************************
3982  *              INT21_FindFirstFCB
3983  *
3984  */
3985 static int INT21_FindFirstFCB( CONTEXT86 *context )
3986 {
3987     BYTE *fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3988     FINDFILE_FCB *pFCB;
3989     int drive;
3990     WCHAR p[] = {' ',':',};
3991
3992     if (*fcb == 0xff) pFCB = (FINDFILE_FCB *)(fcb + 7);
3993     else pFCB = (FINDFILE_FCB *)fcb;
3994     drive = INT21_MapDrive( pFCB->drive );
3995     if (drive == MAX_DOS_DRIVES) return 0;
3996
3997     p[0] = 'A' + drive;
3998     pFCB->fullPath = HeapAlloc(GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR));
3999     if (!pFCB->fullPath) return 0;
4000     GetLongPathNameW(p, pFCB->fullPath, MAX_PATH);
4001     pFCB->count = 0;
4002     return 1;
4003 }
4004
4005 /******************************************************************
4006  *              INT21_FindNextFCB
4007  *
4008  */
4009 static int INT21_FindNextFCB( CONTEXT86 *context )
4010 {
4011     BYTE *fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
4012     FINDFILE_FCB *pFCB;
4013     LPBYTE pResult = INT21_GetCurrentDTA(context);
4014     DOS_DIRENTRY_LAYOUT *ddl;
4015     WIN32_FIND_DATAW entry;
4016     BYTE attr;
4017     int n;
4018     WCHAR nameW[12];
4019
4020     if (*fcb == 0xff) /* extended FCB ? */
4021     {
4022         attr = fcb[6];
4023         pFCB = (FINDFILE_FCB *)(fcb + 7);
4024     }
4025     else
4026     {
4027         attr = 0;
4028         pFCB = (FINDFILE_FCB *)fcb;
4029     }
4030
4031     if (!pFCB->fullPath) return 0;
4032     n = INT21_FindHelper(pFCB->fullPath, INT21_MapDrive( pFCB->drive ),
4033                          pFCB->count, pFCB->filename, attr, &entry);
4034     if (!n)
4035     {
4036         HeapFree( GetProcessHeap(), 0, pFCB->fullPath );
4037         INT21_FindPath = pFCB->fullPath = NULL;
4038         return 0;
4039     }
4040     pFCB->count += n;
4041
4042     if (*fcb == 0xff)
4043     {
4044         /* place extended FCB header before pResult if called with extended FCB */
4045         *pResult = 0xff;
4046          pResult += 6; /* leave reserved field behind */
4047         *pResult++ = entry.dwFileAttributes;
4048     }
4049     *pResult++ = INT21_MapDrive( pFCB->drive ); /* DOS_DIRENTRY_LAYOUT after current drive number */
4050     ddl = (DOS_DIRENTRY_LAYOUT*)pResult;
4051     ddl->fileattr = entry.dwFileAttributes;
4052     ddl->cluster  = 0;  /* what else? */
4053     ddl->filesize = entry.nFileSizeLow;
4054     memset( ddl->reserved, 0, sizeof(ddl->reserved) );
4055     FileTimeToDosDateTime( &entry.ftLastWriteTime,
4056                            &ddl->filedate, &ddl->filetime );
4057
4058     /* Convert file name to FCB format */
4059     if (entry.cAlternateFileName[0])
4060         INT21_ToDosFCBFormat( entry.cAlternateFileName, nameW );
4061     else
4062         INT21_ToDosFCBFormat( entry.cFileName, nameW );
4063     WideCharToMultiByte(CP_OEMCP, 0, nameW, 11, ddl->filename, 11, NULL, NULL);
4064     return 1;
4065 }
4066
4067
4068 /******************************************************************
4069  *              INT21_ParseFileNameIntoFCB
4070  *
4071  */
4072 static void INT21_ParseFileNameIntoFCB( CONTEXT86 *context )
4073 {
4074     char *filename =
4075         CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi );
4076     char *fcb =
4077         CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi );
4078     char *s;
4079     WCHAR *buffer;
4080     WCHAR fcbW[12];
4081     INT buffer_len, len;
4082
4083     SET_AL( context, 0xff ); /* failed */
4084
4085     TRACE("filename: '%s'\n", filename);
4086
4087     s = filename;
4088     while (*s && (*s != ' ') && (*s != '\r') && (*s != '\n'))
4089         s++;
4090     len = filename - s;
4091
4092     buffer_len = MultiByteToWideChar(CP_OEMCP, 0, filename, len, NULL, 0);
4093     buffer = HeapAlloc( GetProcessHeap(), 0, (buffer_len + 1) * sizeof(WCHAR));
4094     len = MultiByteToWideChar(CP_OEMCP, 0, filename, len, buffer, buffer_len);
4095     buffer[len] = 0;
4096     INT21_ToDosFCBFormat(buffer, fcbW);
4097     HeapFree(GetProcessHeap(), 0, buffer);
4098     WideCharToMultiByte(CP_OEMCP, 0, fcbW, 12, fcb + 1, 12, NULL, NULL);
4099     *fcb = 0;
4100     TRACE("FCB: '%s'\n", fcb + 1);
4101
4102     SET_AL( context, ((strchr(filename, '*')) || (strchr(filename, '$'))) != 0 );
4103
4104     /* point DS:SI to first unparsed character */
4105     SET_SI( context, context->Esi + (int)s - (int)filename );
4106 }
4107
4108 static BOOL     INT21_Dup2(HFILE16 hFile1, HFILE16 hFile2)
4109 {
4110     HFILE16     res = HFILE_ERROR16;
4111     HANDLE      handle, new_handle;
4112 #define DOS_TABLE_SIZE  256
4113     DWORD       map[DOS_TABLE_SIZE / 32];
4114     int         i;
4115
4116     handle = DosFileHandleToWin32Handle(hFile1);
4117     if (handle == INVALID_HANDLE_VALUE)
4118         return FALSE;
4119
4120     _lclose16(hFile2);
4121     /* now loop to allocate the same one... */
4122     memset(map, 0, sizeof(map));
4123     for (i = 0; i < DOS_TABLE_SIZE; i++)
4124     {
4125         if (!DuplicateHandle(GetCurrentProcess(), handle,
4126                              GetCurrentProcess(), &new_handle,
4127                              0, FALSE, DUPLICATE_SAME_ACCESS))
4128         {
4129             res = HFILE_ERROR16;
4130             break;
4131         }
4132         res = Win32HandleToDosFileHandle(new_handle);
4133         if (res == HFILE_ERROR16 || res == hFile2) break;
4134         map[res / 32] |= 1 << (res % 32);
4135     }
4136     /* clean up the allocated slots */
4137     for (i = 0; i < DOS_TABLE_SIZE; i++)
4138     {
4139         if (map[i / 32] & (1 << (i % 32)))
4140             _lclose16((HFILE16)i);
4141     }
4142     return res == hFile2;
4143 }
4144
4145
4146 /***********************************************************************
4147  *           DOSVM_Int21Handler
4148  *
4149  * Interrupt 0x21 handler.
4150  */
4151 void WINAPI DOSVM_Int21Handler( CONTEXT86 *context )
4152 {
4153     BOOL bSetDOSExtendedError = FALSE;
4154
4155     TRACE( "AX=%04x BX=%04x CX=%04x DX=%04x "
4156            "SI=%04x DI=%04x DS=%04x ES=%04x EFL=%08x\n",
4157            AX_reg(context), BX_reg(context), 
4158            CX_reg(context), DX_reg(context),
4159            SI_reg(context), DI_reg(context),
4160            (WORD)context->SegDs, (WORD)context->SegEs,
4161            context->EFlags );
4162
4163    /*
4164     * Extended error is used by (at least) functions 0x2f to 0x62.
4165     * Function 0x59 returns extended error and error should not
4166     * be cleared before handling the function.
4167     */
4168     if (AH_reg(context) >= 0x2f && AH_reg(context) != 0x59) 
4169         SetLastError(0);
4170
4171     RESET_CFLAG(context); /* Not sure if this is a good idea. */
4172
4173     switch(AH_reg(context))
4174     {
4175     case 0x00: /* TERMINATE PROGRAM */
4176         TRACE("TERMINATE PROGRAM\n");
4177         if (DOSVM_IsWin16())
4178             ExitThread( 0 );
4179         else if(ISV86(context))
4180             MZ_Exit( context, FALSE, 0 );
4181         else
4182             ERR( "Called from DOS protected mode\n" );
4183         break;
4184
4185     case 0x01: /* READ CHARACTER FROM STANDARD INPUT, WITH ECHO */
4186         {
4187             BYTE ascii;
4188             TRACE("DIRECT CHARACTER INPUT WITH ECHO\n");
4189             INT21_ReadChar( &ascii, context );
4190             SET_AL( context, ascii );
4191             /*
4192              * FIXME: What to echo when extended keycodes are read?
4193              */
4194             DOSVM_PutChar(AL_reg(context));
4195         }
4196         break;
4197
4198     case 0x02: /* WRITE CHARACTER TO STANDARD OUTPUT */
4199         TRACE("Write Character to Standard Output\n");
4200         DOSVM_PutChar(DL_reg(context));
4201         break;
4202
4203     case 0x03: /* READ CHARACTER FROM STDAUX  */
4204     case 0x04: /* WRITE CHARACTER TO STDAUX */
4205     case 0x05: /* WRITE CHARACTER TO PRINTER */
4206         INT_BARF( context, 0x21 );
4207         break;
4208
4209     case 0x06: /* DIRECT CONSOLE IN/OUTPUT */
4210         if (DL_reg(context) == 0xff) 
4211         {
4212             TRACE("Direct Console Input\n");
4213
4214             if (INT21_ReadChar( NULL, NULL ))
4215             {
4216                 BYTE ascii;
4217                 INT21_ReadChar( &ascii, context );
4218                 SET_AL( context, ascii );
4219                 RESET_ZFLAG( context );
4220             }
4221             else
4222             {
4223                 /* no character available */
4224                 SET_AL( context, 0 );
4225                 SET_ZFLAG( context );
4226             }
4227         } 
4228         else 
4229         {
4230             TRACE("Direct Console Output\n");
4231             DOSVM_PutChar(DL_reg(context));
4232             /*
4233              * At least DOS versions 2.1-7.0 return character 
4234              * that was written in AL register.
4235              */
4236             SET_AL( context, DL_reg(context) );
4237         }
4238         break;
4239
4240     case 0x07: /* DIRECT CHARACTER INPUT WITHOUT ECHO */
4241         {
4242             BYTE ascii;
4243             TRACE("DIRECT CHARACTER INPUT WITHOUT ECHO\n");
4244             INT21_ReadChar( &ascii, context );
4245             SET_AL( context, ascii );
4246         }
4247         break;
4248
4249     case 0x08: /* CHARACTER INPUT WITHOUT ECHO */
4250         {
4251             BYTE ascii;
4252             TRACE("CHARACTER INPUT WITHOUT ECHO\n");
4253             INT21_ReadChar( &ascii, context );
4254             SET_AL( context, ascii );
4255         }
4256         break;
4257
4258     case 0x09: /* WRITE STRING TO STANDARD OUTPUT */
4259         TRACE("WRITE '$'-terminated string from %04X:%04X to stdout\n",
4260               context->SegDs, DX_reg(context) );
4261         {
4262             LPSTR data = CTX_SEG_OFF_TO_LIN( context, 
4263                                              context->SegDs, context->Edx );
4264             LPSTR p = data;
4265             DWORD w;
4266             /*
4267              * Do NOT use strchr() to calculate the string length,
4268              * as '\0' is valid string content, too!
4269              * Maybe we should check for non-'$' strings, but DOS doesn't.
4270              */
4271             while (*p != '$') p++;
4272
4273             if (DOSVM_IsWin16())
4274                 WriteFile( DosFileHandleToWin32Handle(1), 
4275                            data, p - data, &w, NULL );
4276             else
4277                 for(; data != p; data++)
4278                     DOSVM_PutChar( *data );
4279
4280             SET_AL( context, '$' ); /* yes, '$' (0x24) gets returned in AL */
4281         }
4282         break;
4283
4284     case 0x0a: /* BUFFERED INPUT */
4285         {
4286             BYTE *ptr = CTX_SEG_OFF_TO_LIN(context,
4287                                            context->SegDs,
4288                                            context->Edx);
4289             WORD result;
4290
4291             TRACE( "BUFFERED INPUT (size=%d)\n", ptr[0] );
4292
4293             /*
4294              * FIXME: Some documents state that
4295              *        ptr[1] holds number of chars from last input which 
4296              *        may be recalled on entry, other documents do not mention
4297              *        this at all.
4298              */
4299             if (ptr[1])
4300                 TRACE( "Handle old chars in buffer!\n" );
4301
4302             /*
4303              * ptr[0] - capacity (includes terminating CR)
4304              * ptr[1] - characters read (excludes terminating CR)
4305              */
4306             result = INT21_BufferedInput( context, ptr + 2, ptr[0] );
4307             if (result > 0)
4308                 ptr[1] = (BYTE)result - 1;
4309             else
4310                 ptr[1] = 0;
4311         }
4312         break;
4313
4314     case 0x0b: /* GET STDIN STATUS */
4315         TRACE( "GET STDIN STATUS\n" );
4316         {
4317             if (INT21_ReadChar( NULL, NULL ))
4318                 SET_AL( context, 0xff ); /* character available */
4319             else
4320                 SET_AL( context, 0 ); /* no character available */
4321         }
4322         break;
4323
4324     case 0x0c: /* FLUSH BUFFER AND READ STANDARD INPUT */
4325         {
4326             BYTE al = AL_reg(context); /* Input function to execute after flush. */
4327
4328             TRACE( "FLUSH BUFFER AND READ STANDARD INPUT - 0x%02x\n", al );
4329
4330             /* FIXME: buffers are not flushed */
4331
4332             /*
4333              * If AL is one of 0x01, 0x06, 0x07, 0x08, or 0x0a,
4334              * int21 function identified by AL will be called.
4335              */
4336             if(al == 0x01 || al == 0x06 || al == 0x07 || al == 0x08 || al == 0x0a)
4337             {
4338                 SET_AH( context, al );
4339                 DOSVM_Int21Handler( context );
4340             }
4341         }
4342         break;
4343
4344     case 0x0d: /* DISK BUFFER FLUSH */
4345         TRACE("DISK BUFFER FLUSH ignored\n");
4346         break;
4347
4348     case 0x0e: /* SELECT DEFAULT DRIVE */
4349         TRACE( "SELECT DEFAULT DRIVE - %c:\n", 'A' + DL_reg(context) );
4350         INT21_SetCurrentDrive( DL_reg(context) );
4351         SET_AL( context, MAX_DOS_DRIVES );
4352         break;
4353
4354     case 0x0f: /* OPEN FILE USING FCB */
4355         INT21_OpenFileUsingFCB( context );
4356         break;
4357
4358     case 0x10: /* CLOSE FILE USING FCB */
4359         INT21_CloseFileUsingFCB( context );
4360         break;
4361
4362     case 0x11: /* FIND FIRST MATCHING FILE USING FCB */
4363         TRACE("FIND FIRST MATCHING FILE USING FCB %p\n",
4364               CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx));
4365         if (!INT21_FindFirstFCB(context))
4366         {
4367             SET_AL( context, 0xff );
4368             break;
4369         }
4370         /* else fall through */
4371
4372     case 0x12: /* FIND NEXT MATCHING FILE USING FCB */
4373         SET_AL( context, INT21_FindNextFCB(context) ? 0x00 : 0xff );
4374         break;
4375
4376      case 0x13: /* DELETE FILE USING FCB */
4377         INT_BARF( context, 0x21 );
4378         break;
4379
4380     case 0x14: /* SEQUENTIAL READ FROM FCB FILE */
4381         INT21_SequentialReadFromFCB( context );
4382         break;
4383
4384     case 0x15: /* SEQUENTIAL WRITE TO FCB FILE */
4385         INT21_SequentialWriteToFCB( context );
4386         break;
4387
4388     case 0x16: /* CREATE OR TRUNCATE FILE USING FCB */
4389     case 0x17: /* RENAME FILE USING FCB */
4390         INT_BARF( context, 0x21 );
4391         break;
4392
4393     case 0x18: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
4394         SET_AL( context, 0 );
4395         break;
4396
4397     case 0x19: /* GET CURRENT DEFAULT DRIVE */
4398         SET_AL( context, INT21_GetCurrentDrive() );
4399         TRACE( "GET CURRENT DRIVE -> %c:\n", 'A' + AL_reg( context ) );
4400         break;
4401
4402     case 0x1a: /* SET DISK TRANSFER AREA ADDRESS */
4403         TRACE( "SET DISK TRANSFER AREA ADDRESS %04X:%04X\n",
4404                context->SegDs, DX_reg(context) );
4405         {
4406             TDB *task = GlobalLock16( GetCurrentTask() );
4407             task->dta = MAKESEGPTR( context->SegDs, DX_reg(context) );
4408         }
4409         break;
4410
4411     case 0x1b: /* GET ALLOCATION INFORMATION FOR DEFAULT DRIVE */
4412         if (!INT21_GetDriveAllocInfo(context, 0))
4413             SET_AX( context, 0xffff );
4414         break;
4415
4416     case 0x1c: /* GET ALLOCATION INFORMATION FOR SPECIFIC DRIVE */
4417         if (!INT21_GetDriveAllocInfo(context, DL_reg(context)))
4418             SET_AX( context, 0xffff );
4419         break;
4420
4421     case 0x1d: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
4422     case 0x1e: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
4423         SET_AL( context, 0 );
4424         break;
4425
4426     case 0x1f: /* GET DRIVE PARAMETER BLOCK FOR DEFAULT DRIVE */
4427         {
4428             BYTE drive = INT21_MapDrive( 0 ); 
4429             TRACE( "GET DPB FOR DEFAULT DRIVE\n" );
4430
4431             if (INT21_FillDrivePB( drive ))
4432             {
4433                 SET_AL( context, 0x00 ); /* success */
4434                 SET_BX( context, offsetof( INT21_HEAP, misc_dpb_list[drive] ) );
4435                 context->SegDs = INT21_GetHeapSelector( context );
4436             }
4437             else
4438             {
4439                 SET_AL( context, 0xff ); /* invalid or network drive */
4440             }
4441         }
4442         break;
4443
4444     case 0x20: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
4445         SET_AL( context, 0 );
4446         break;
4447
4448     case 0x21: /* READ RANDOM RECORD FROM FCB FILE */
4449         INT21_ReadRandomRecordFromFCB( context );
4450         break;
4451
4452     case 0x22: /* WRITE RANDOM RECORD TO FCB FILE */
4453         INT21_WriteRandomRecordToFCB( context );
4454         break;
4455
4456     case 0x23: /* GET FILE SIZE FOR FCB */
4457     case 0x24: /* SET RANDOM RECORD NUMBER FOR FCB */
4458         INT_BARF( context, 0x21 );
4459         break;
4460
4461     case 0x25: /* SET INTERRUPT VECTOR */
4462         TRACE("SET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
4463         {
4464             FARPROC16 ptr = (FARPROC16)MAKESEGPTR( context->SegDs, DX_reg(context) );
4465             if (!ISV86(context) && DOSVM_IsWin16())
4466                 DOSVM_SetPMHandler16(  AL_reg(context), ptr );
4467             else
4468                 DOSVM_SetRMHandler( AL_reg(context), ptr );
4469         }
4470         break;
4471
4472     case 0x26: /* CREATE NEW PROGRAM SEGMENT PREFIX */
4473         INT_BARF( context, 0x21 );
4474         break;
4475
4476     case 0x27: /* RANDOM BLOCK READ FROM FCB FILE */
4477         INT21_RandomBlockReadFromFCB( context );
4478         break;
4479
4480     case 0x28: /* RANDOM BLOCK WRITE TO FCB FILE */
4481         INT21_RandomBlockWriteToFCB( context );
4482         break;
4483
4484     case 0x29: /* PARSE FILENAME INTO FCB */
4485         INT21_ParseFileNameIntoFCB(context);
4486         break;
4487
4488     case 0x2a: /* GET SYSTEM DATE */
4489         TRACE( "GET SYSTEM DATE\n" );
4490         {
4491             SYSTEMTIME systime;
4492             GetLocalTime( &systime );
4493             SET_CX( context, systime.wYear );
4494             SET_DH( context, systime.wMonth );
4495             SET_DL( context, systime.wDay );
4496             SET_AL( context, systime.wDayOfWeek );
4497         }
4498         break;
4499
4500     case 0x2b: /* SET SYSTEM DATE */
4501         TRACE( "SET SYSTEM DATE\n" );
4502         {
4503             WORD year  = CX_reg(context);
4504             BYTE month = DH_reg(context);
4505             BYTE day   = DL_reg(context);
4506
4507             if (year  >= 1980 && year  <= 2099 &&
4508                 month >= 1    && month <= 12   &&
4509                 day   >= 1    && day   <= 31)
4510             {
4511                 FIXME( "SetSystemDate(%02d/%02d/%04d): not allowed\n",
4512                        day, month, year );
4513                 SET_AL( context, 0 );  /* Let's pretend we succeeded */
4514             }
4515             else
4516             {
4517                 SET_AL( context, 0xff ); /* invalid date */
4518                 TRACE( "SetSystemDate(%02d/%02d/%04d): invalid date\n",
4519                        day, month, year );
4520             }
4521         }
4522         break;
4523
4524     case 0x2c: /* GET SYSTEM TIME */
4525         TRACE( "GET SYSTEM TIME\n" );
4526         {
4527             SYSTEMTIME systime;
4528             GetLocalTime( &systime );
4529             SET_CH( context, systime.wHour );
4530             SET_CL( context, systime.wMinute );
4531             SET_DH( context, systime.wSecond );
4532             SET_DL( context, systime.wMilliseconds / 10 );
4533         }
4534         break;
4535
4536     case 0x2d: /* SET SYSTEM TIME */
4537         if( CH_reg(context) >= 24 || CL_reg(context) >= 60 || DH_reg(context) >= 60 || DL_reg(context) >= 100 ) {
4538             TRACE("SetSystemTime(%02d:%02d:%02d.%02d): wrong time\n",
4539               CH_reg(context), CL_reg(context),
4540               DH_reg(context), DL_reg(context) );
4541             SET_AL( context, 0xFF );
4542         }
4543         else
4544         {
4545             FIXME("SetSystemTime(%02d:%02d:%02d.%02d): not allowed\n",
4546                   CH_reg(context), CL_reg(context),
4547                   DH_reg(context), DL_reg(context) );
4548             SET_AL( context, 0 );  /* Let's pretend we succeeded */
4549         }
4550         break;
4551
4552     case 0x2e: /* SET VERIFY FLAG */
4553         TRACE("SET VERIFY FLAG ignored\n");
4554         /* we cannot change the behaviour anyway, so just ignore it */
4555         break;
4556
4557     case 0x2f: /* GET DISK TRANSFER AREA ADDRESS */
4558         TRACE( "GET DISK TRANSFER AREA ADDRESS\n" );
4559         {
4560             TDB *task = GlobalLock16( GetCurrentTask() );
4561             context->SegEs = SELECTOROF( task->dta );
4562             SET_BX( context, OFFSETOF( task->dta ) );
4563         }
4564         break;
4565
4566     case 0x30: /* GET DOS VERSION */
4567         TRACE( "GET DOS VERSION - %s requested\n",
4568                (AL_reg(context) == 0x00) ? "OEM number" : "version flag" );
4569
4570         if (AL_reg(context) == 0x00)
4571             SET_BH( context, 0xff ); /* OEM number => undefined */
4572         else
4573             SET_BH( context, 0x08 ); /* version flag => DOS is in ROM */
4574
4575         SET_AL( context, HIBYTE(HIWORD(GetVersion16())) ); /* major version */
4576         SET_AH( context, LOBYTE(HIWORD(GetVersion16())) ); /* minor version */
4577
4578         SET_BL( context, 0x12 );     /* 0x123456 is 24-bit Wine's serial # */
4579         SET_CX( context, 0x3456 );
4580         break;
4581
4582     case 0x31: /* TERMINATE AND STAY RESIDENT */
4583         FIXME("TERMINATE AND STAY RESIDENT stub\n");
4584         break;
4585
4586     case 0x32: /* GET DOS DRIVE PARAMETER BLOCK FOR SPECIFIC DRIVE */
4587         {
4588             BYTE drive = INT21_MapDrive( DL_reg(context) );           
4589             TRACE( "GET DPB FOR SPECIFIC DRIVE %d\n", DL_reg(context) );
4590
4591             if (INT21_FillDrivePB( drive ))
4592             {
4593                 SET_AL( context, 0x00 ); /* success */
4594                 SET_DX( context, offsetof( INT21_HEAP, misc_dpb_list[drive] ) );
4595                 context->SegDs = INT21_GetHeapSelector( context );
4596             }
4597             else
4598             {
4599                 SET_AL( context, 0xff ); /* invalid or network drive */
4600             }
4601         }
4602         break;
4603
4604     case 0x33: /* MULTIPLEXED */
4605         switch (AL_reg(context))
4606         {
4607         case 0x00: /* GET CURRENT EXTENDED BREAK STATE */
4608             TRACE("GET CURRENT EXTENDED BREAK STATE\n");
4609             SET_DL( context, DOSCONF_GetConfig()->brk_flag );
4610             break;
4611
4612         case 0x01: /* SET EXTENDED BREAK STATE */
4613             TRACE("SET CURRENT EXTENDED BREAK STATE\n");
4614             DOSCONF_GetConfig()->brk_flag = (DL_reg(context) > 0) ? 1 : 0;
4615             break;
4616
4617         case 0x02: /* GET AND SET EXTENDED CONTROL-BREAK CHECKING STATE*/
4618             TRACE("GET AND SET EXTENDED CONTROL-BREAK CHECKING STATE\n");
4619             /* ugly coding in order to stay reentrant */
4620             if (DL_reg(context))
4621             {
4622                 SET_DL( context, DOSCONF_GetConfig()->brk_flag );
4623                 DOSCONF_GetConfig()->brk_flag = 1;
4624             }
4625             else
4626             {
4627                 SET_DL( context, DOSCONF_GetConfig()->brk_flag );
4628                 DOSCONF_GetConfig()->brk_flag = 0;
4629             }
4630             break;
4631
4632         case 0x05: /* GET BOOT DRIVE */
4633             TRACE("GET BOOT DRIVE\n");
4634             SET_DL( context, 3 );
4635             /* c: is Wine's bootdrive (a: is 1)*/
4636             break;
4637
4638         case 0x06: /* GET TRUE VERSION NUMBER */
4639             TRACE("GET TRUE VERSION NUMBER\n");
4640             SET_BL( context, HIBYTE(HIWORD(GetVersion16())) ); /* major */
4641             SET_BH( context, LOBYTE(HIWORD(GetVersion16())) ); /* minor */
4642             SET_DL( context, 0x00 ); /* revision */
4643             SET_DH( context, 0x08 ); /* DOS is in ROM */
4644             break;
4645
4646         default:
4647             INT_BARF( context, 0x21 );
4648             break;
4649         }
4650         break;
4651
4652     case 0x34: /* GET ADDRESS OF INDOS FLAG */
4653         TRACE( "GET ADDRESS OF INDOS FLAG\n" );
4654         context->SegEs = INT21_GetHeapSelector( context );
4655         SET_BX( context, offsetof(INT21_HEAP, misc_indos) );
4656         break;
4657
4658     case 0x35: /* GET INTERRUPT VECTOR */
4659         TRACE("GET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
4660         {
4661             FARPROC16 addr;
4662             if (!ISV86(context) && DOSVM_IsWin16())
4663                 addr = DOSVM_GetPMHandler16( AL_reg(context) );
4664             else
4665                 addr = DOSVM_GetRMHandler( AL_reg(context) );
4666             context->SegEs = SELECTOROF(addr);
4667             SET_BX( context, OFFSETOF(addr) );
4668         }
4669         break;
4670
4671     case 0x36: /* GET FREE DISK SPACE */
4672         TRACE("GET FREE DISK SPACE FOR DRIVE %s (limited to about 1GB)\n",
4673               INT21_DriveName( DL_reg(context) ));
4674         if (!INT21_GetFreeDiskSpace(context)) SET_AX( context, 0xffff );
4675         break;
4676
4677     case 0x37: /* SWITCHAR */
4678         {
4679             switch (AL_reg(context))
4680             {
4681             case 0x00: /* "SWITCHAR" - GET SWITCH CHARACTER */
4682                 TRACE( "SWITCHAR - GET SWITCH CHARACTER\n" );
4683                 SET_AL( context, 0x00 ); /* success*/
4684                 SET_DL( context, '/' );
4685                 break;
4686             case 0x01: /*"SWITCHAR" - SET SWITCH CHARACTER*/
4687                 FIXME( "SWITCHAR - SET SWITCH CHARACTER: %c\n",
4688                        DL_reg( context ));
4689                 SET_AL( context, 0x00 ); /* success*/
4690                 break;
4691             default:
4692                 INT_BARF( context, 0x21 );
4693                 break;
4694             }
4695         }
4696         break;
4697
4698     case 0x38: /* GET COUNTRY-SPECIFIC INFORMATION */
4699         TRACE( "GET COUNTRY-SPECIFIC INFORMATION\n" );
4700         if (AL_reg(context))
4701         {
4702             WORD country = AL_reg(context);
4703             if (country == 0xff)
4704                 country = BX_reg(context);
4705             if (country != INT21_GetSystemCountryCode()) {
4706                 FIXME( "Requested info on non-default country %04x\n", country );
4707                 SET_AX(context, 2);
4708                 SET_CFLAG(context);
4709             }
4710         }
4711         if(AX_reg(context) != 2 )
4712         {
4713             INT21_FillCountryInformation( CTX_SEG_OFF_TO_LIN(context,
4714                                                              context->SegDs,
4715                                                              context->Edx) );
4716             SET_AX( context, INT21_GetSystemCountryCode() );
4717             SET_BX( context, INT21_GetSystemCountryCode() );
4718             RESET_CFLAG(context);
4719         }
4720         break;
4721
4722     case 0x39: /* "MKDIR" - CREATE SUBDIRECTORY */
4723         if (!INT21_CreateDirectory( context ))
4724             bSetDOSExtendedError = TRUE;
4725         else
4726             RESET_CFLAG(context);
4727         break;
4728
4729     case 0x3a: /* "RMDIR" - REMOVE DIRECTORY */
4730         {
4731             WCHAR dirW[MAX_PATH];
4732             char *dirA = CTX_SEG_OFF_TO_LIN(context,
4733                                             context->SegDs, context->Edx);
4734
4735             TRACE( "REMOVE DIRECTORY %s\n", dirA );
4736
4737             MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
4738
4739             if (!RemoveDirectoryW( dirW ))
4740                 bSetDOSExtendedError = TRUE;
4741             else
4742                 RESET_CFLAG(context);
4743         }
4744         break;
4745
4746     case 0x3b: /* "CHDIR" - SET CURRENT DIRECTORY */
4747         if (!INT21_SetCurrentDirectory( context ))
4748             bSetDOSExtendedError = TRUE;
4749         else
4750             RESET_CFLAG(context);
4751         break;
4752
4753     case 0x3c: /* "CREAT" - CREATE OR TRUNCATE FILE */
4754         if (!INT21_CreateFile( context, context->Edx, FALSE, 
4755                                OF_READWRITE | OF_SHARE_COMPAT, 0x12 ))
4756             bSetDOSExtendedError = TRUE;
4757         else
4758             RESET_CFLAG(context);
4759         break;
4760
4761     case 0x3d: /* "OPEN" - OPEN EXISTING FILE */
4762         if (!INT21_CreateFile( context, context->Edx, FALSE, 
4763                                AL_reg(context), 0x01 ))
4764             bSetDOSExtendedError = TRUE;
4765         else
4766             RESET_CFLAG(context);
4767         break;
4768
4769     case 0x3e: /* "CLOSE" - CLOSE FILE */
4770         TRACE( "CLOSE handle %d\n", BX_reg(context) );
4771         if (_lclose16( BX_reg(context) ) == HFILE_ERROR16)
4772             bSetDOSExtendedError = TRUE;
4773         else
4774             RESET_CFLAG(context);
4775         break;
4776
4777     case 0x3f: /* "READ" - READ FROM FILE OR DEVICE */
4778         TRACE( "READ from %d to %04X:%04X for %d bytes\n",
4779                BX_reg(context),
4780                context->SegDs,
4781                DX_reg(context),
4782                CX_reg(context) );
4783         {
4784             DWORD result;
4785             WORD  count  = CX_reg(context);
4786             BYTE *buffer = CTX_SEG_OFF_TO_LIN( context, 
4787                                                context->SegDs,
4788                                                context->Edx );
4789
4790             /* Some programs pass a count larger than the allocated buffer */
4791             if (DOSVM_IsWin16())
4792             {
4793                 DWORD maxcount = GetSelectorLimit16( context->SegDs )
4794                     - DX_reg(context) + 1;
4795                 if (count > maxcount)
4796                     count = maxcount;
4797             }
4798
4799             /*
4800              * FIXME: Reading from console (BX=1) in DOS mode
4801              *        does not work as it is supposed to work.
4802              */
4803
4804             RESET_CFLAG(context); /* set if error */
4805             if (!DOSVM_IsWin16() && BX_reg(context) == 0)
4806             {
4807                 result = INT21_BufferedInput( context, buffer, count );
4808                 SET_AX( context, (WORD)result );
4809             }
4810             else if (ReadFile( DosFileHandleToWin32Handle(BX_reg(context)),
4811                                buffer, count, &result, NULL ))
4812                 SET_AX( context, (WORD)result );
4813             else
4814                 bSetDOSExtendedError = TRUE;
4815         }
4816         break;
4817
4818     case 0x40:  /* "WRITE" - WRITE TO FILE OR DEVICE */
4819         TRACE( "WRITE from %04X:%04X to handle %d for %d byte\n",
4820                context->SegDs, DX_reg(context),
4821                BX_reg(context), CX_reg(context) );
4822         {
4823             char *ptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
4824
4825             if (!DOSVM_IsWin16() && 
4826                 (BX_reg(context) == 1 || BX_reg(context) == 2))
4827             {
4828                 int i;
4829                 for(i=0; i<CX_reg(context); i++)
4830                     DOSVM_PutChar(ptr[i]);
4831                 SET_AX(context, CX_reg(context));
4832                 RESET_CFLAG(context);
4833             }
4834             else
4835             {
4836                 HFILE handle = (HFILE)DosFileHandleToWin32Handle(BX_reg(context));
4837                 LONG result = _hwrite( handle, ptr, CX_reg(context) );
4838                 if (result == HFILE_ERROR)
4839                     bSetDOSExtendedError = TRUE;
4840                 else
4841                 {
4842                     SET_AX( context, (WORD)result );
4843                     RESET_CFLAG(context);
4844                 }
4845             }
4846         }
4847         break;
4848
4849     case 0x41: /* "UNLINK" - DELETE FILE */
4850         {
4851             WCHAR fileW[MAX_PATH];
4852             char *fileA = CTX_SEG_OFF_TO_LIN(context, 
4853                                              context->SegDs, 
4854                                              context->Edx);
4855
4856             TRACE( "UNLINK %s\n", fileA );
4857             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
4858
4859             if (!DeleteFileW( fileW ))
4860                 bSetDOSExtendedError = TRUE;
4861             else
4862                 RESET_CFLAG(context);
4863         }
4864         break;
4865
4866     case 0x42: /* "LSEEK" - SET CURRENT FILE POSITION */
4867         TRACE( "LSEEK handle %d offset %d from %s\n",
4868                BX_reg(context), 
4869                MAKELONG( DX_reg(context), CX_reg(context) ),
4870                (AL_reg(context) == 0) ? 
4871                "start of file" : ((AL_reg(context) == 1) ? 
4872                                   "current file position" : "end of file") );
4873         {
4874             HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
4875             LONG   offset = MAKELONG( DX_reg(context), CX_reg(context) );
4876             DWORD  status = SetFilePointer( handle, offset, 
4877                                             NULL, AL_reg(context) );
4878             if (status == INVALID_SET_FILE_POINTER)
4879                 bSetDOSExtendedError = TRUE;
4880             else
4881             {
4882                 SET_AX( context, LOWORD(status) );
4883                 SET_DX( context, HIWORD(status) );
4884                 RESET_CFLAG(context);
4885             }
4886         }
4887         break;
4888
4889     case 0x43: /* FILE ATTRIBUTES */
4890         if (!INT21_FileAttributes( context, AL_reg(context), FALSE ))
4891             bSetDOSExtendedError = TRUE;
4892         else
4893             RESET_CFLAG(context);
4894         break;
4895
4896     case 0x44: /* IOCTL */
4897         INT21_Ioctl( context );
4898         break;
4899
4900     case 0x45: /* "DUP" - DUPLICATE FILE HANDLE */
4901         TRACE( "DUPLICATE FILE HANDLE %d\n", BX_reg(context) );
4902         {
4903             HANDLE handle32;
4904             HFILE  handle16 = HFILE_ERROR;
4905
4906             if (DuplicateHandle( GetCurrentProcess(),
4907                                  DosFileHandleToWin32Handle(BX_reg(context)),
4908                                  GetCurrentProcess(), 
4909                                  &handle32,
4910                                  0, TRUE, DUPLICATE_SAME_ACCESS ))
4911                 handle16 = Win32HandleToDosFileHandle(handle32);
4912
4913             if (handle16 == HFILE_ERROR)
4914                 bSetDOSExtendedError = TRUE;
4915             else
4916             {
4917                 SET_AX( context, handle16 );
4918                 RESET_CFLAG(context);
4919             }
4920         }
4921         break;
4922
4923     case 0x46: /* "DUP2", "FORCEDUP" - FORCE DUPLICATE FILE HANDLE */
4924         TRACE( "FORCEDUP - FORCE DUPLICATE FILE HANDLE %d to %d\n",
4925                BX_reg(context), CX_reg(context) );
4926         if (!INT21_Dup2(BX_reg(context), CX_reg(context)))
4927             bSetDOSExtendedError = TRUE;
4928         else
4929             RESET_CFLAG(context);
4930         break;
4931
4932     case 0x47: /* "CWD" - GET CURRENT DIRECTORY */
4933         if (!INT21_GetCurrentDirectory( context, FALSE ))
4934             bSetDOSExtendedError = TRUE;
4935         else
4936             RESET_CFLAG(context);
4937         break;
4938
4939     case 0x48: /* ALLOCATE MEMORY */
4940         TRACE( "ALLOCATE MEMORY for %d paragraphs\n", BX_reg(context) );
4941         {
4942             WORD  selector = 0;
4943             DWORD bytes = (DWORD)BX_reg(context) << 4;
4944
4945             if (!ISV86(context) && DOSVM_IsWin16())
4946             {
4947                 DWORD rv = GlobalDOSAlloc16( bytes );
4948                 selector = LOWORD( rv );
4949             }
4950             else
4951                 DOSMEM_AllocBlock( bytes, &selector );
4952
4953             if (selector)
4954             {
4955                 SET_AX( context, selector );
4956                 RESET_CFLAG(context);
4957             }
4958             else
4959             {
4960                 SET_CFLAG(context);
4961                 SET_AX( context, 0x0008 ); /* insufficient memory */
4962                 SET_BX( context, DOSMEM_Available() >> 4 );
4963             }
4964         }
4965         break;
4966
4967     case 0x49: /* FREE MEMORY */
4968         TRACE( "FREE MEMORY segment %04X\n", context->SegEs );
4969         {
4970             BOOL ok;
4971             
4972             if (!ISV86(context) && DOSVM_IsWin16())
4973             {
4974                 ok = !GlobalDOSFree16( context->SegEs );
4975
4976                 /* If we don't reset ES_reg, we will fail in the relay code */
4977                 if (ok)
4978                     context->SegEs = 0;
4979             }
4980             else
4981                 ok = DOSMEM_FreeBlock( PTR_REAL_TO_LIN(context->SegEs, 0) );
4982
4983             if (!ok)
4984             {
4985                 TRACE("FREE MEMORY failed\n");
4986                 SET_CFLAG(context);
4987                 SET_AX( context, 0x0009 ); /* memory block address invalid */
4988             }
4989         }
4990         break;
4991
4992     case 0x4a: /* RESIZE MEMORY BLOCK */
4993         TRACE( "RESIZE MEMORY segment %04X to %d paragraphs\n",
4994                context->SegEs, BX_reg(context) );
4995         {
4996             DWORD newsize = (DWORD)BX_reg(context) << 4;
4997             
4998             if (!ISV86(context) && DOSVM_IsWin16())
4999             {
5000                 FIXME( "Resize memory block - unsupported under Win16\n" );
5001                 SET_CFLAG(context);
5002             }
5003             else
5004             {
5005                 LPVOID address = (void*)(context->SegEs << 4);
5006                 UINT blocksize = DOSMEM_ResizeBlock( address, newsize, FALSE );
5007
5008                 RESET_CFLAG(context);
5009                 if (blocksize == (UINT)-1)
5010                 {
5011                     SET_CFLAG( context );
5012                     SET_AX( context, 0x0009 ); /* illegal address */
5013                 }
5014                 else if(blocksize != newsize)
5015                 {
5016                     SET_CFLAG( context );
5017                     SET_AX( context, 0x0008 );    /* insufficient memory */
5018                     SET_BX( context, blocksize >> 4 ); /* new block size */
5019                 }
5020             }
5021         }
5022         break;
5023
5024     case 0x4b: /* "EXEC" - LOAD AND/OR EXECUTE PROGRAM */
5025         {
5026             char *program = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
5027             BYTE *paramblk = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Ebx);
5028
5029             TRACE( "EXEC %s\n", program );
5030
5031             RESET_CFLAG(context);
5032             if (DOSVM_IsWin16())
5033             {
5034                 HINSTANCE16 instance = WinExec16( program, SW_NORMAL );
5035                 if (instance < 32)
5036                 {
5037                     SET_CFLAG( context );
5038                     SET_AX( context, instance );
5039                 }
5040             }
5041             else
5042             {
5043                 if (!MZ_Exec( context, program, AL_reg(context), paramblk))
5044                     bSetDOSExtendedError = TRUE;
5045             }
5046         }
5047         break;
5048
5049     case 0x4c: /* "EXIT" - TERMINATE WITH RETURN CODE */
5050         TRACE( "EXIT with return code %d\n", AL_reg(context) );
5051         if (DOSVM_IsWin16())
5052             ExitThread( AL_reg(context) );
5053         else if(ISV86(context))
5054             MZ_Exit( context, FALSE, AL_reg(context) );
5055         else
5056         {
5057             /*
5058              * Exit from DPMI.
5059              */            
5060             ULONG_PTR rv = AL_reg(context);
5061             RaiseException( EXCEPTION_VM86_INTx, 0, 1, &rv );
5062         }
5063         break;
5064
5065     case 0x4d: /* GET RETURN CODE */
5066         TRACE("GET RETURN CODE (ERRORLEVEL)\n");
5067         SET_AX( context, DOSVM_retval );
5068         DOSVM_retval = 0;
5069         break;
5070
5071     case 0x4e: /* "FINDFIRST" - FIND FIRST MATCHING FILE */
5072         TRACE("FINDFIRST mask 0x%04x spec %s\n",CX_reg(context),
5073               (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx));
5074         if (!INT21_FindFirst(context)) break;
5075         /* fall through */
5076
5077     case 0x4f: /* "FINDNEXT" - FIND NEXT MATCHING FILE */
5078         TRACE("FINDNEXT\n");
5079         if (!INT21_FindNext(context))
5080         {
5081             SetLastError( ERROR_NO_MORE_FILES );
5082             SET_AX( context, ERROR_NO_MORE_FILES );
5083             SET_CFLAG(context);
5084         }
5085         else SET_AX( context, 0 );  /* OK */
5086         break;
5087
5088     case 0x50: /* SET CURRENT PROCESS ID (SET PSP ADDRESS) */
5089         TRACE("SET CURRENT PROCESS ID (SET PSP ADDRESS)\n");
5090         DOSVM_psp = BX_reg(context);
5091         break;
5092
5093     case 0x51: /* GET PSP ADDRESS */
5094         INT21_GetPSP( context );
5095         break;
5096
5097     case 0x52: /* "SYSVARS" - GET LIST OF LISTS */
5098         {
5099             SEGPTR ptr = DOSDEV_GetLOL( ISV86(context) || !DOSVM_IsWin16() );
5100             context->SegEs = SELECTOROF(ptr);
5101             SET_BX( context, OFFSETOF(ptr) );
5102         }
5103         break;
5104
5105     case 0x54: /* Get Verify Flag */
5106         TRACE("Get Verify Flag - Not Supported\n");
5107         SET_AL( context, 0x00 );  /* pretend we can tell. 00h = off 01h = on */
5108         break;
5109
5110     case 0x56: /* "RENAME" - RENAME FILE */
5111         if (!INT21_RenameFile( context ))
5112             bSetDOSExtendedError = TRUE;
5113         else
5114             RESET_CFLAG(context);
5115         break;
5116
5117     case 0x57: /* FILE DATE AND TIME */
5118         if (!INT21_FileDateTime( context ))
5119             bSetDOSExtendedError = TRUE;
5120         else
5121             RESET_CFLAG(context);
5122         break;
5123
5124     case 0x58: /* GET OR SET MEMORY ALLOCATION STRATEGY */
5125         switch (AL_reg(context))
5126         {
5127         case 0x00: /* GET MEMORY ALLOCATION STRATEGY */
5128             TRACE( "GET MEMORY ALLOCATION STRATEGY\n" );
5129             SET_AX( context, 0 ); /* low memory first fit */
5130             break;
5131
5132         case 0x01: /* SET ALLOCATION STRATEGY */
5133             TRACE( "SET MEMORY ALLOCATION STRATEGY to %d - ignored\n",
5134                    BL_reg(context) );
5135             break;
5136
5137         case 0x02: /* GET UMB LINK STATE */
5138             TRACE( "GET UMB LINK STATE\n" );
5139             SET_AL( context, 0 ); /* UMBs not part of DOS memory chain */
5140             break;
5141
5142         case 0x03: /* SET UMB LINK STATE */
5143             TRACE( "SET UMB LINK STATE to %d - ignored\n",
5144                    BX_reg(context) );
5145             break;
5146
5147         default:
5148             INT_BARF( context, 0x21 );
5149         }
5150         break;
5151
5152     case 0x59: /* GET EXTENDED ERROR INFO */
5153         INT21_GetExtendedError( context );
5154         break;
5155
5156     case 0x5a: /* CREATE TEMPORARY FILE */
5157         TRACE("CREATE TEMPORARY FILE\n");
5158         bSetDOSExtendedError = !INT21_CreateTempFile(context);
5159         break;
5160
5161     case 0x5b: /* CREATE NEW FILE */ 
5162         if (!INT21_CreateFile( context, context->Edx, FALSE,
5163                                OF_READWRITE | OF_SHARE_COMPAT, 0x10 ))
5164             bSetDOSExtendedError = TRUE;
5165         else
5166             RESET_CFLAG(context);
5167         break;
5168
5169     case 0x5c: /* "FLOCK" - RECORD LOCKING */
5170         {
5171             DWORD  offset = MAKELONG(DX_reg(context), CX_reg(context));
5172             DWORD  length = MAKELONG(DI_reg(context), SI_reg(context));
5173             HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
5174
5175             RESET_CFLAG(context);
5176             switch (AL_reg(context))
5177             {
5178             case 0x00: /* LOCK */
5179                 TRACE( "lock handle %d offset %d length %d\n",
5180                        BX_reg(context), offset, length );
5181                 if (!LockFile( handle, offset, 0, length, 0 ))
5182                     bSetDOSExtendedError = TRUE;
5183                 break;
5184
5185             case 0x01: /* UNLOCK */
5186                 TRACE( "unlock handle %d offset %d length %d\n",
5187                        BX_reg(context), offset, length );
5188                 if (!UnlockFile( handle, offset, 0, length, 0 ))
5189                     bSetDOSExtendedError = TRUE;
5190                 break;
5191
5192             default:
5193                 INT_BARF( context, 0x21 );
5194             }
5195         }
5196         break;
5197
5198     case 0x5d: /* NETWORK 5D */
5199         FIXME( "Network function 5D not implemented.\n" );
5200         SetLastError( ER_NoNetwork );
5201         bSetDOSExtendedError = TRUE;
5202         break;
5203
5204     case 0x5e: /* NETWORK 5E */
5205         bSetDOSExtendedError = INT21_NetworkFunc( context);
5206         break;
5207
5208     case 0x5f: /* NETWORK 5F */
5209         /* FIXME: supporting this would need to 1:
5210          * - implement per drive current directory (as kernel32 doesn't)
5211          * - assign enabled/disabled flag on a per drive basis
5212          */
5213         /* network software not installed */
5214         TRACE("NETWORK function AX=%04x not implemented\n",AX_reg(context));
5215         SetLastError( ER_NoNetwork );
5216         bSetDOSExtendedError = TRUE;
5217         break;
5218
5219     case 0x60: /* "TRUENAME" - CANONICALIZE FILENAME OR PATH */
5220         {
5221             WCHAR       pathW[MAX_PATH], res[MAX_PATH];
5222             /* FIXME: likely to be broken */
5223
5224             TRACE("TRUENAME %s\n",
5225                   (LPCSTR)CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Esi));
5226             MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
5227             if (!GetFullPathNameW( pathW, 128, res, NULL ))
5228                 bSetDOSExtendedError = TRUE;
5229             else
5230             {
5231                 SET_AX( context, 0 );
5232                 WideCharToMultiByte(CP_OEMCP, 0, res, -1, 
5233                                     CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi), 
5234                                     128, NULL, NULL);
5235             }
5236         }
5237         break;
5238
5239     case 0x61: /* UNUSED */
5240         SET_AL( context, 0 );
5241         break;
5242
5243     case 0x62: /* GET PSP ADDRESS */
5244         INT21_GetPSP( context );
5245         break;
5246
5247     case 0x63: /* MISC. LANGUAGE SUPPORT */
5248         switch (AL_reg(context)) {
5249         case 0x00: /* GET DOUBLE BYTE CHARACTER SET LEAD-BYTE TABLE */
5250             TRACE( "GET DOUBLE BYTE CHARACTER SET LEAD-BYTE TABLE\n" );
5251             context->SegDs = INT21_GetHeapSelector( context );
5252             SET_SI( context, offsetof(INT21_HEAP, dbcs_table) );
5253             SET_AL( context, 0 ); /* success */
5254             break;
5255         }
5256         break;
5257
5258     case 0x64: /* OS/2 DOS BOX */
5259         INT_BARF( context, 0x21 );
5260         SET_CFLAG(context);
5261         break;
5262
5263     case 0x65: /* EXTENDED COUNTRY INFORMATION */
5264         INT21_ExtendedCountryInformation( context );
5265         break;
5266
5267     case 0x66: /* GLOBAL CODE PAGE TABLE */
5268         switch (AL_reg(context))
5269         {
5270         case 0x01:
5271             TRACE( "GET GLOBAL CODE PAGE TABLE\n" );
5272             SET_BX( context, GetOEMCP() );
5273             SET_DX( context, GetOEMCP() );
5274             break;
5275         case 0x02:
5276             FIXME( "SET GLOBAL CODE PAGE TABLE, active %d, system %d - ignored\n",
5277                    BX_reg(context), DX_reg(context) );
5278             break;
5279         }
5280         break;
5281
5282     case 0x67: /* SET HANDLE COUNT */
5283         TRACE( "SET HANDLE COUNT to %d\n", BX_reg(context) );
5284         if (SetHandleCount( BX_reg(context) ) < BX_reg(context) )
5285             bSetDOSExtendedError = TRUE;
5286         break;
5287
5288     case 0x68: /* "FFLUSH" - COMMIT FILE */
5289         TRACE( "FFLUSH - handle %d\n", BX_reg(context) );
5290         if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
5291             bSetDOSExtendedError = TRUE;
5292         break;
5293
5294     case 0x69: /* DISK SERIAL NUMBER */
5295         switch (AL_reg(context))
5296         {
5297         case 0x00:
5298             TRACE("GET DISK SERIAL NUMBER for drive %s\n",
5299                   INT21_DriveName(BL_reg(context)));
5300             if (!INT21_GetDiskSerialNumber(context)) bSetDOSExtendedError = TRUE;
5301             else SET_AX( context, 0 );
5302             break;
5303
5304         case 0x01:
5305             TRACE("SET DISK SERIAL NUMBER for drive %s\n",
5306                   INT21_DriveName(BL_reg(context)));
5307             if (!INT21_SetDiskSerialNumber(context)) bSetDOSExtendedError = TRUE;
5308             else SET_AX( context, 1 );
5309             break;
5310         }
5311         break;
5312
5313     case 0x6a: /* COMMIT FILE */
5314         TRACE( "COMMIT FILE - handle %d\n", BX_reg(context) );
5315         if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
5316             bSetDOSExtendedError = TRUE;
5317         break;
5318
5319     case 0x6b: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
5320         SET_AL( context, 0 );
5321         break;
5322
5323     case 0x6c: /* EXTENDED OPEN/CREATE */
5324         if (!INT21_CreateFile( context, context->Esi, TRUE,
5325                                BX_reg(context), DL_reg(context) ))
5326             bSetDOSExtendedError = TRUE;
5327         break;
5328
5329     case 0x70: /* MSDOS 7 - GET/SET INTERNATIONALIZATION INFORMATION */
5330         FIXME( "MS-DOS 7 - GET/SET INTERNATIONALIZATION INFORMATION\n" );
5331         SET_CFLAG( context );
5332         SET_AL( context, 0 );
5333         break;
5334
5335     case 0x71: /* MSDOS 7 - LONG FILENAME FUNCTIONS */
5336         INT21_LongFilename( context );
5337         break;
5338
5339     case 0x73: /* MSDOS7 - FAT32 */
5340         RESET_CFLAG( context );
5341         if (!INT21_Fat32( context ))
5342             bSetDOSExtendedError = TRUE;
5343         break;
5344
5345     case 0xdc: /* CONNECTION SERVICES - GET CONNECTION NUMBER */
5346         TRACE( "CONNECTION SERVICES - GET CONNECTION NUMBER - ignored\n" );
5347         break;
5348
5349     case 0xea: /* NOVELL NETWARE - RETURN SHELL VERSION */
5350         TRACE( "NOVELL NETWARE - RETURN SHELL VERSION - ignored\n" );
5351         break;
5352
5353     case 0xff: /* DOS32 EXTENDER (DOS/4GW) - API */
5354         /* we don't implement a DOS32 extender */
5355         TRACE( "DOS32 EXTENDER API - ignored\n" );
5356         break;
5357
5358     default:
5359         INT_BARF( context, 0x21 );
5360         break;
5361
5362     } /* END OF SWITCH */
5363
5364     /* Set general error condition. */
5365     if (bSetDOSExtendedError)
5366     {
5367         SET_AX( context, GetLastError() );
5368         SET_CFLAG( context );
5369     }
5370
5371     /* Print error code if carry flag is set. */
5372     if (context->EFlags & 0x0001)
5373         TRACE("failed, error %d\n", GetLastError() );
5374
5375     TRACE( "returning: AX=%04x BX=%04x CX=%04x DX=%04x "
5376            "SI=%04x DI=%04x DS=%04x ES=%04x EFL=%08x\n",
5377            AX_reg(context), BX_reg(context), 
5378            CX_reg(context), DX_reg(context), 
5379            SI_reg(context), DI_reg(context),
5380            (WORD)context->SegDs, (WORD)context->SegEs,
5381            context->EFlags );
5382 }