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