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