Cast time_t to long for printing.
[wine] / dlls / winedos / int21.c
1 /*
2  * DOS interrupt 21h handler
3  *
4  * Copyright 1993, 1994 Erik Bos
5  * Copyright 1996 Alexandre Julliard
6  * Copyright 1997 Andreas Mohr
7  * Copyright 1998 Uwe Bonnes
8  * Copyright 1998, 1999 Ove Kaaven
9  * Copyright 2003 Thomas Mertes
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25
26 #include "config.h"
27
28 #include <stdarg.h>
29
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winreg.h"
33 #include "winternl.h"
34 #include "wine/winbase16.h"
35 #include "dosexe.h"
36 #include "miscemu.h"
37 #include "msdos.h"
38 #include "file.h"
39 #include "task.h"
40 #include "winerror.h"
41 #include "winuser.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44 #include "wine/exception.h"
45
46 /*
47  * FIXME: Delete this reference when all int21 code has been moved to winedos.
48  */
49 extern void WINAPI INT_Int21Handler( CONTEXT86 *context );
50
51 /*
52  * Forward declarations.
53  */
54 static BOOL INT21_RenameFile( CONTEXT86 *context );
55
56 WINE_DEFAULT_DEBUG_CHANNEL(int21);
57
58
59 #include "pshpack1.h"
60
61 /*
62  * Structure for DOS data that can be accessed directly from applications.
63  * Real and protected mode pointers will be returned to this structure so
64  * the structure must be correctly packed.
65  */
66 typedef struct _INT21_HEAP {
67     WORD uppercase_size;             /* Size of the following table in bytes */
68     BYTE uppercase_table[128];       /* Uppercase equivalents of chars from 0x80 to 0xff. */
69
70     WORD lowercase_size;             /* Size of the following table in bytes */
71     BYTE lowercase_table[256];       /* Lowercase equivalents of chars from 0x00 to 0xff. */
72
73     WORD collating_size;             /* Size of the following table in bytes */
74     BYTE collating_table[256];       /* Values used to sort characters from 0x00 to 0xff. */
75
76     WORD filename_size;              /* Size of the following filename data in bytes */
77     BYTE filename_reserved1;         /* 0x01 for MS-DOS 3.30-6.00 */
78     BYTE filename_lowest;            /* Lowest permissible character value for filename */
79     BYTE filename_highest;           /* Highest permissible character value for filename */
80     BYTE filename_reserved2;         /* 0x00 for MS-DOS 3.30-6.00 */
81     BYTE filename_exclude_first;     /* First illegal character in permissible range */
82     BYTE filename_exclude_last;      /* Last illegal character in permissible range */
83     BYTE filename_reserved3;         /* 0x02 for MS-DOS 3.30-6.00 */
84     BYTE filename_illegal_size;      /* Number of terminators in the following table */
85     BYTE filename_illegal_table[16]; /* Characters which terminate a filename */
86
87     WORD dbcs_size;                  /* Number of valid ranges in the following table */
88     BYTE dbcs_table[16];             /* Start/end bytes for N ranges and 00/00 as terminator */
89
90     BYTE misc_indos;                 /* Interrupt 21 nesting flag */
91 } INT21_HEAP;
92
93
94 struct FCB {
95     BYTE  drive_number;
96     CHAR  file_name[8];
97     CHAR  file_extension[3];
98     WORD  current_block_number;
99     WORD  logical_record_size;
100     DWORD file_size;
101     WORD  date_of_last_write;
102     WORD  time_of_last_write;
103     BYTE  file_number;
104     BYTE  attributes;
105     WORD  starting_cluster;
106     WORD  sequence_number;
107     BYTE  file_attributes;
108     BYTE  unused;
109     BYTE  record_within_current_block;
110     BYTE  random_access_record_number[4];
111 };
112
113
114 struct XFCB {
115     BYTE  xfcb_signature;
116     BYTE  reserved[5];
117     BYTE  xfcb_file_attribute;
118     BYTE  fcb[37];
119 };
120
121 #include "poppack.h"
122
123
124 /***********************************************************************
125  *           INT21_GetCurrentDrive
126  *
127  * Return current drive using scheme (0=A:, 1=B:, 2=C:, ...) or
128  * MAX_DOS_DRIVES on error.
129  */
130 static BYTE INT21_GetCurrentDrive()
131 {
132     WCHAR current_directory[MAX_PATH];
133
134     if (!GetCurrentDirectoryW( MAX_PATH, current_directory ) ||
135         current_directory[1] != ':')
136     {
137         TRACE( "Failed to get current drive.\n" );
138         return MAX_DOS_DRIVES;
139     }
140
141     return toupperW( current_directory[0] ) - 'A';
142 }
143
144
145 /***********************************************************************
146  *           INT21_MapDrive
147  *
148  * Convert drive number from scheme (0=default, 1=A:, 2=B:, ...) into
149  * scheme (0=A:, 1=B:, 2=C:, ...) or MAX_DOS_DRIVES on error.
150  */
151 static BYTE INT21_MapDrive( BYTE drive )
152 {
153     if (drive)
154     {
155         WCHAR drivespec[3] = {'A', ':', 0};
156         UINT  drivetype;
157
158         drivespec[0] += drive - 1;
159         drivetype = GetDriveTypeW( drivespec );
160
161         if (drivetype == DRIVE_UNKNOWN || drivetype == DRIVE_NO_ROOT_DIR)
162             return MAX_DOS_DRIVES;
163
164         return drive - 1;
165     }
166
167     return INT21_GetCurrentDrive();
168 }
169
170
171 /***********************************************************************
172  *           INT21_SetCurrentDrive
173  *
174  * Set current drive. Uses scheme (0=A:, 1=B:, 2=C:, ...).
175  */
176 static void INT21_SetCurrentDrive( BYTE drive )
177 {
178     WCHAR drivespec[3] = {'A', ':', 0};
179
180     drivespec[0] += drive;
181
182     if (!SetCurrentDirectoryW( drivespec ))
183         TRACE( "Failed to set current drive.\n" );
184 }
185
186
187 /***********************************************************************
188  *           INT21_ReadChar
189  *
190  * Reads a character from the standard input.
191  * Extended keycodes will be returned as two separate characters.
192  */
193 static BOOL INT21_ReadChar( BYTE *input, CONTEXT86 *waitctx )
194 {
195     static BYTE pending_scan = 0;
196
197     if (pending_scan)
198     {
199         if (input)
200             *input = pending_scan;
201         if (waitctx)
202             pending_scan = 0;
203         return TRUE;
204     }
205     else
206     {
207         BYTE ascii;
208         BYTE scan;
209         if (!DOSVM_Int16ReadChar( &ascii, &scan, waitctx ))
210             return FALSE;
211
212         if (input)
213             *input = ascii;
214         if (waitctx && !ascii)
215             pending_scan = scan;
216         return TRUE;
217     }
218 }
219
220
221 /***********************************************************************
222  *           INT21_GetSystemCountryCode
223  *
224  * Return DOS country code for default system locale.
225  */
226 static WORD INT21_GetSystemCountryCode( void )
227 {
228     /*
229      * FIXME: Determine country code. We should probably use
230      *        DOSCONF structure for that.
231      */
232     return GetSystemDefaultLangID();
233 }
234
235
236 /***********************************************************************
237  *           INT21_FillCountryInformation
238  *
239  * Fill 34-byte buffer with country information data using
240  * default system locale.
241  */
242 static void INT21_FillCountryInformation( BYTE *buffer )
243 {
244     /* 00 - WORD: date format
245      *          00 = mm/dd/yy
246      *          01 = dd/mm/yy
247      *          02 = yy/mm/dd
248      */
249     *(WORD*)(buffer + 0) = 0; /* FIXME: Get from locale */
250
251     /* 02 - BYTE[5]: ASCIIZ currency symbol string */
252     buffer[2] = '$'; /* FIXME: Get from locale */
253     buffer[3] = 0;
254
255     /* 07 - BYTE[2]: ASCIIZ thousands separator */
256     buffer[7] = 0; /* FIXME: Get from locale */
257     buffer[8] = 0;
258
259     /* 09 - BYTE[2]: ASCIIZ decimal separator */
260     buffer[9]  = '.'; /* FIXME: Get from locale */
261     buffer[10] = 0;
262
263     /* 11 - BYTE[2]: ASCIIZ date separator */
264     buffer[11] = '/'; /* FIXME: Get from locale */
265     buffer[12] = 0;
266
267     /* 13 - BYTE[2]: ASCIIZ time separator */
268     buffer[13] = ':'; /* FIXME: Get from locale */
269     buffer[14] = 0;
270
271     /* 15 - BYTE: Currency format
272      *          bit 2 = set if currency symbol replaces decimal point
273      *          bit 1 = number of spaces between value and currency symbol
274      *          bit 0 = 0 if currency symbol precedes value
275      *                  1 if currency symbol follows value
276      */
277     buffer[15] = 0; /* FIXME: Get from locale */
278
279     /* 16 - BYTE: Number of digits after decimal in currency */
280     buffer[16] = 0; /* FIXME: Get from locale */
281
282     /* 17 - BYTE: Time format
283      *          bit 0 = 0 if 12-hour clock
284      *                  1 if 24-hour clock
285      */
286     buffer[17] = 1; /* FIXME: Get from locale */
287
288     /* 18 - DWORD: Address of case map routine */
289     *(DWORD*)(buffer + 18) = 0; /* FIXME: ptr to case map routine */
290
291     /* 22 - BYTE[2]: ASCIIZ data-list separator */
292     buffer[22] = ','; /* FIXME: Get from locale */
293     buffer[23] = 0;
294
295     /* 24 - BYTE[10]: Reserved */
296     memset( buffer + 24, 0, 10 );
297 }
298
299
300 /***********************************************************************
301  *           INT21_FillHeap
302  *
303  * Initialize DOS heap.
304  */
305 static void INT21_FillHeap( INT21_HEAP *heap )
306 {
307     static const char terminators[] = "\"\\./[]:|<>+=;,";
308     int i;
309
310     /*
311      * Uppercase table.
312      */
313     heap->uppercase_size = 128;
314     for (i = 0; i < 128; i++) 
315         heap->uppercase_table[i] = toupper( 128 + i );
316
317     /*
318      * Lowercase table.
319      */
320     heap->lowercase_size = 256;
321     for (i = 0; i < 256; i++) 
322         heap->lowercase_table[i] = tolower( i );
323     
324     /*
325      * Collating table.
326      */
327     heap->collating_size = 256;
328     for (i = 0; i < 256; i++) 
329         heap->collating_table[i] = i;
330
331     /*
332      * Filename table.
333      */
334     heap->filename_size = 8 + strlen(terminators);
335     heap->filename_illegal_size = strlen(terminators);
336     strcpy( heap->filename_illegal_table, terminators );
337
338     heap->filename_reserved1 = 0x01;
339     heap->filename_lowest = 0;           /* FIXME: correct value? */
340     heap->filename_highest = 0xff;       /* FIXME: correct value? */
341     heap->filename_reserved2 = 0x00;    
342     heap->filename_exclude_first = 0x00; /* FIXME: correct value? */
343     heap->filename_exclude_last = 0x00;  /* FIXME: correct value? */
344     heap->filename_reserved3 = 0x02;
345
346     /*
347      * DBCS lead byte table. This table is empty.
348      */
349     heap->dbcs_size = 0;
350     memset( heap->dbcs_table, 0, sizeof(heap->dbcs_table) );
351
352     /*
353      * Initialize InDos flag.
354      */
355     heap->misc_indos = 0;
356 }
357
358
359 /***********************************************************************
360  *           INT21_GetHeapSelector
361  *
362  * Get segment/selector for DOS heap (INT21_HEAP).
363  * Creates and initializes heap on first call.
364  */
365 static WORD INT21_GetHeapSelector( CONTEXT86 *context )
366 {
367     static WORD heap_segment = 0;
368     static WORD heap_selector = 0;
369     static BOOL heap_initialized = FALSE;
370
371     if (!heap_initialized)
372     {
373         INT21_HEAP *ptr = DOSVM_AllocDataUMB( sizeof(INT21_HEAP), 
374                                               &heap_segment,
375                                               &heap_selector );
376         INT21_FillHeap( ptr );
377         heap_initialized = TRUE;
378     }
379
380     if (!ISV86(context) && DOSVM_IsWin16())
381         return heap_selector;
382     else
383         return heap_segment;
384 }
385
386
387 /***********************************************************************
388  *           INT21_GetCurrentDirectory
389  *
390  * Handler for:
391  * - function 0x47
392  * - subfunction 0x47 of function 0x71
393  */
394 static BOOL INT21_GetCurrentDirectory( CONTEXT86 *context, BOOL islong )
395 {
396     char  *buffer = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi);
397     BYTE   new_drive = INT21_MapDrive( DL_reg(context) );
398     BYTE   old_drive = INT21_GetCurrentDrive();
399     WCHAR  pathW[MAX_PATH];
400     char   pathA[MAX_PATH];
401     WCHAR *ptr = pathW;
402
403     TRACE( "drive %d\n", DL_reg(context) );
404
405     if (new_drive == MAX_DOS_DRIVES)
406     {        
407         SetLastError(ERROR_INVALID_DRIVE);
408         return FALSE;
409     }
410     
411     /*
412      * Grab current directory.
413      */
414
415     INT21_SetCurrentDrive( new_drive );
416     if (!GetCurrentDirectoryW( MAX_PATH, pathW ))
417     {        
418         INT21_SetCurrentDrive( old_drive );
419         return FALSE;
420     }
421     INT21_SetCurrentDrive( old_drive );
422
423     /*
424      * Convert into short format.
425      */
426
427     if (!islong)
428     {
429         DWORD result = GetShortPathNameW( pathW, pathW, MAX_PATH );
430         if (!result)
431             return FALSE;
432         if (result > MAX_PATH)
433         {
434             WARN( "Short path too long!\n" );
435             SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
436             return FALSE;
437         }
438     }
439
440     /*
441      * The returned pathname does not include 
442      * the drive letter, colon or leading backslash.
443      */
444
445     if (ptr[0] == '\\')
446     {
447         /*
448          * FIXME: We should probably just strip host part from name...
449          */
450         FIXME( "UNC names are not supported.\n" );
451         SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
452         return FALSE;
453     }
454     else if (!ptr[0] || ptr[1] != ':' || ptr[2] != '\\')
455     {
456         WARN( "Path is neither UNC nor DOS path: %s\n",
457               wine_dbgstr_w(ptr) );
458         SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
459         return FALSE;
460     }
461     else
462     {
463         /* Remove drive letter, colon and leading backslash. */
464         ptr += 3;
465     }
466
467     /*
468      * Convert into OEM string.
469      */
470     
471     if (!WideCharToMultiByte(CP_OEMCP, 0, ptr, -1, pathA, 
472                              MAX_PATH, NULL, NULL))
473     {
474         WARN( "Cannot convert path!\n" );
475         SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
476         return FALSE;
477     }
478
479     /*
480      * Success.
481      */
482
483     if (!islong)
484     {
485         /* Undocumented success code. */
486         SET_AX( context, 0x0100 );
487         
488         /* Truncate buffer to 64 bytes. */
489         pathA[63] = 0;
490     }
491
492     TRACE( "%c:=%s\n", 'A' + new_drive, pathA );
493
494     strcpy( buffer, pathA );
495     return TRUE;
496 }
497
498
499 /***********************************************************************
500  *           INT21_SetCurrentDirectory
501  *
502  * Handler for:
503  * - function 0x3b
504  * - subfunction 0x3b of function 0x71
505  */
506 static BOOL INT21_SetCurrentDirectory( CONTEXT86 *context )
507 {
508     WCHAR dirW[MAX_PATH];
509     char *dirA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
510     BYTE  drive = INT21_GetCurrentDrive();
511     BOOL  result;
512
513     TRACE( "SET CURRENT DIRECTORY %s\n", dirA );
514
515     MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
516     result = SetCurrentDirectoryW( dirW );
517
518     /* This function must not change current drive. */
519     INT21_SetCurrentDrive( drive );
520
521     return result;
522 }
523
524
525 /***********************************************************************
526  *           INT21_CreateFile
527  *
528  * Handler for:
529  * - function 0x3c
530  * - function 0x3d
531  * - function 0x5b
532  * - function 0x6c
533  * - subfunction 0x6c of function 0x71
534  */
535 static BOOL INT21_CreateFile( CONTEXT86 *context, 
536                               DWORD      pathSegOff,
537                               BOOL       returnStatus,
538                               WORD       dosAccessShare,
539                               BYTE       dosAction )
540 {
541     WORD   dosStatus;
542     char  *pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, pathSegOff);
543     WCHAR  pathW[MAX_PATH];   
544     DWORD  winAccess;
545     DWORD  winAttributes;
546     HANDLE winHandle;
547     DWORD  winMode;
548     DWORD  winSharing;
549
550     TRACE( "CreateFile called: function=%02x, action=%02x, access/share=%04x, "
551            "create flags=%04x, file=%s.\n",
552            AH_reg(context), dosAction, dosAccessShare, CX_reg(context), pathA );
553
554     /*
555      * Application tried to create/open a file whose name 
556      * ends with a backslash. This is not allowed.
557      *
558      * FIXME: This needs to be validated, especially the return value.
559      */
560     if (pathA[strlen(pathA) - 1] == '/')
561     {
562         SetLastError( ERROR_FILE_NOT_FOUND );
563         return FALSE;
564     }
565
566     /*
567      * Convert DOS action flags into Win32 creation disposition parameter.
568      */ 
569     switch(dosAction)
570     {
571     case 0x01:
572         winMode = OPEN_EXISTING;
573         break;
574     case 0x02:
575         winMode = TRUNCATE_EXISTING;
576         break;
577     case 0x10:
578         winMode = CREATE_NEW;
579         break;
580     case 0x11:
581         winMode = OPEN_ALWAYS;
582         break;
583     case 0x12:
584         winMode = CREATE_ALWAYS;
585         break;
586     default:
587         SetLastError( ERROR_INVALID_PARAMETER );
588         return FALSE;
589     }
590
591     /*
592      * Convert DOS access/share flags into Win32 desired access parameter.
593      */ 
594     switch(dosAccessShare & 0x07)
595     {
596     case OF_READ:
597         winAccess = GENERIC_READ;
598         break;
599     case OF_WRITE:
600         winAccess = GENERIC_WRITE;
601         break;
602     case OF_READWRITE:
603         winAccess = GENERIC_READ | GENERIC_WRITE;
604         break;
605     case 0x04:
606         /*
607          * Read-only, do not modify file's last-access time (DOS7).
608          *
609          * FIXME: How to prevent modification of last-access time?
610          */
611         winAccess = GENERIC_READ;
612         break;
613     default:
614         winAccess = 0;
615     }
616
617     /*
618      * Convert DOS access/share flags into Win32 share mode parameter.
619      */ 
620     switch(dosAccessShare & 0x70)
621     {
622     case OF_SHARE_EXCLUSIVE:  
623         winSharing = 0; 
624         break;
625     case OF_SHARE_DENY_WRITE: 
626         winSharing = FILE_SHARE_READ; 
627         break;
628     case OF_SHARE_DENY_READ:  
629         winSharing = FILE_SHARE_WRITE; 
630         break;
631     case OF_SHARE_DENY_NONE:
632     case OF_SHARE_COMPAT:
633     default:
634         winSharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
635     }
636
637     /*
638      * FIXME: Bit (dosAccessShare & 0x80) represents inheritance.
639      *        What to do with this bit?
640      * FIXME: Bits in the high byte of dosAccessShare are not supported.
641      *        See both function 0x6c and subfunction 0x6c of function 0x71 for
642      *        definition of these bits.
643      */
644
645     /*
646      * Convert DOS create attributes into Win32 flags and attributes parameter.
647      */
648     if (winMode == OPEN_EXISTING || winMode == TRUNCATE_EXISTING)
649     {
650         winAttributes = 0;
651     }
652     else
653     {        
654         WORD dosAttributes = CX_reg(context);
655
656         if (dosAttributes & FILE_ATTRIBUTE_LABEL)
657         {
658             /*
659              * Application tried to create volume label entry.
660              * This is difficult to support so we do not allow it.
661              *
662              * FIXME: If volume does not already have a label, 
663              *        this function is supposed to succeed.
664              */
665             SetLastError( ERROR_ACCESS_DENIED );
666             return TRUE;
667         }
668
669         winAttributes = dosAttributes & 
670             (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | 
671              FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE);
672     }
673
674     /*
675      * Open the file.
676      */
677     MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
678
679     winHandle = CreateFileW( pathW, winAccess, winSharing, NULL, 
680                              winMode, winAttributes, 0 );
681
682     if (winHandle == INVALID_HANDLE_VALUE)
683         return FALSE;
684
685     /*
686      * Determine DOS file status.
687      *
688      * 1 = file opened
689      * 2 = file created
690      * 3 = file replaced
691      */
692     switch(winMode)
693     {
694     case OPEN_EXISTING:
695         dosStatus = 1;
696         break;
697     case TRUNCATE_EXISTING:
698         dosStatus = 3; 
699         break;
700     case CREATE_NEW:
701         dosStatus = 2;
702         break;
703     case OPEN_ALWAYS:
704         dosStatus = (GetLastError() == ERROR_ALREADY_EXISTS) ? 1 : 2;
705         break;
706     case CREATE_ALWAYS:
707         dosStatus = (GetLastError() == ERROR_ALREADY_EXISTS) ? 3 : 2;
708         break;
709     default:
710         dosStatus = 0;
711     }
712
713     /*
714      * Return DOS file handle and DOS status.
715      */
716     SET_AX( context, Win32HandleToDosFileHandle(winHandle) );
717
718     if (returnStatus)
719         SET_CX( context, dosStatus );
720
721     TRACE( "CreateFile finished: handle=%d, status=%d.\n", 
722            AX_reg(context), dosStatus );
723
724     return TRUE;
725 }
726
727
728 /***********************************************************************
729  *           INT21_BufferedInput
730  *
731  * Handler for function 0x0a and reading from console using
732  * function 0x3f.
733  *
734  * Reads a string of characters from standard input until
735  * enter key is pressed. Returns either number of characters 
736  * read from console including terminating CR or 
737  * zero if capacity was zero.
738  */
739 static WORD INT21_BufferedInput( CONTEXT86 *context, BYTE *ptr, WORD capacity )
740 {
741     BYTE length = 0;
742
743     /*
744      * Return immediately if capacity is zero.
745      */
746     if (capacity == 0)
747         return 0;
748
749     while(TRUE)
750     {
751         BYTE ascii;
752         BYTE scan;
753
754         DOSVM_Int16ReadChar( &ascii, &scan, context );
755
756         if (ascii == '\r' || ascii == '\n')
757         {
758             /*
759              * FIXME: What should be echoed here?
760              */
761             DOSVM_PutChar( '\r' );
762             DOSVM_PutChar( '\n' );
763             ptr[length] = '\r';
764             return length + 1;
765         }
766
767         /*
768          * FIXME: This function is supposed to support
769          *        DOS editing keys...
770          */
771
772         /*
773          * If the buffer becomes filled to within one byte of
774          * capacity, DOS rejects all further characters up to,
775          * but not including, the terminating carriage return.
776          */
777         if (ascii != 0 && length < capacity-1)
778         {
779             DOSVM_PutChar( ascii );
780             ptr[length] = ascii;
781             length++;
782         }
783     }
784 }
785
786
787 /***********************************************************************
788  *           INT21_GetCurrentDTA
789  */
790 static BYTE *INT21_GetCurrentDTA( CONTEXT86 *context )
791 {
792     TDB *pTask = GlobalLock16(GetCurrentTask());
793
794     /* FIXME: This assumes DTA was set correctly! */
795     return (BYTE *)CTX_SEG_OFF_TO_LIN( context, SELECTOROF(pTask->dta),
796                                                 (DWORD)OFFSETOF(pTask->dta) );
797 }
798
799
800 /***********************************************************************
801  *           INT21_OpenFileUsingFCB
802  *
803  * Handler for function 0x0f.
804  *
805  * PARAMS
806  *  DX:DX [I/O] File control block (FCB or XFCB) of unopened file
807  *
808  * RETURNS (in AL)
809  *  0x00: successful
810  *  0xff: failed
811  *
812  * NOTES
813  *  Opens a FCB file for read/write in compatibility mode. Upon calling
814  *  the FCB must have the drive_number, file_name, and file_extension
815  *  fields filled and all other bytes cleared.
816  */
817 static void INT21_OpenFileUsingFCB( CONTEXT86 *context )
818 {
819     struct FCB *fcb;
820     struct XFCB *xfcb;
821     char file_path[16];
822     char *pos;
823     HANDLE handle;
824     HFILE16 hfile16;
825     BY_HANDLE_FILE_INFORMATION info;
826     BYTE AL_result;
827
828     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
829     if (fcb->drive_number == 0xff) {
830         xfcb = (struct XFCB *) fcb;
831         fcb = (struct FCB *) xfcb->fcb;
832     } /* if */
833
834     AL_result = 0;
835     file_path[0] = 'A' + INT21_MapDrive( fcb->drive_number );
836
837     if (AL_result == 0) {
838         file_path[1] = ':';
839         pos = &file_path[2];
840         memcpy(pos, fcb->file_name, 8);
841         pos[8] = ' ';
842         pos[9] = '\0';
843         pos = strchr(pos, ' ');
844         *pos = '.';
845         pos++;
846         memcpy(pos, fcb->file_extension, 3);
847         pos[3] = ' ';
848         pos[4] = '\0';
849         pos = strchr(pos, ' ');
850         *pos = '\0';
851
852         handle = (HANDLE) _lopen(file_path, OF_READWRITE);
853         if (handle == INVALID_HANDLE_VALUE) {
854             TRACE("_lopen(\"%s\") failed: INVALID_HANDLE_VALUE\n", file_path);
855             AL_result = 0xff; /* failed */
856         } else {
857             hfile16 = Win32HandleToDosFileHandle(handle);
858             if (hfile16 == HFILE_ERROR16) {
859                 TRACE("Win32HandleToDosFileHandle(%p) failed: HFILE_ERROR\n", handle);
860                 CloseHandle(handle);
861                 AL_result = 0xff; /* failed */
862             } else if (hfile16 > 255) {
863                 TRACE("hfile16 (=%d) larger than 255 for \"%s\"\n", hfile16, file_path);
864                 _lclose16(hfile16);
865                 AL_result = 0xff; /* failed */
866             } else {
867                 if (!GetFileInformationByHandle(handle, &info)) {
868                     TRACE("GetFileInformationByHandle(%d, %p) for \"%s\" failed\n",
869                           hfile16, handle, file_path);
870                     _lclose16(hfile16);
871                     AL_result = 0xff; /* failed */
872                 } else {
873                     fcb->drive_number = file_path[0] - 'A' + 1;
874                     fcb->current_block_number = 0;
875                     fcb->logical_record_size = 128;
876                     fcb->file_size = info.nFileSizeLow;
877                     FileTimeToDosDateTime(&info.ftLastWriteTime,
878                         &fcb->date_of_last_write, &fcb->time_of_last_write);
879                     fcb->file_number = hfile16;
880                     fcb->attributes = 0xc2;
881                     fcb->starting_cluster = 0; /* don't know correct init value */
882                     fcb->sequence_number = 0; /* don't know correct init value */
883                     fcb->file_attributes = info.dwFileAttributes;
884                     /* The following fields are not initialized */
885                     /* by the native function: */
886                     /* unused */
887                     /* record_within_current_block */
888                     /* random_access_record_number */
889
890                     TRACE("successful opened file \"%s\" as %d (handle %p)\n",
891                           file_path, hfile16, handle);
892                     AL_result = 0x00; /* successful */
893                 } /* if */
894             } /* if */
895         } /* if */
896     } /* if */
897     SET_AL(context, AL_result);
898 }
899
900
901 /***********************************************************************
902  *           INT21_CloseFileUsingFCB
903  *
904  * Handler for function 0x10.
905  *
906  * PARAMS
907  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
908  *
909  * RETURNS (in AL)
910  *  0x00: successful
911  *  0xff: failed
912  *
913  * NOTES
914  *  Closes a FCB file.
915  */
916 static void INT21_CloseFileUsingFCB( CONTEXT86 *context )
917 {
918     struct FCB *fcb;
919     struct XFCB *xfcb;
920     BYTE AL_result;
921
922     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
923     if (fcb->drive_number == 0xff) {
924         xfcb = (struct XFCB *) fcb;
925         fcb = (struct FCB *) xfcb->fcb;
926     } /* if */
927
928     if (_lclose16((HFILE16) fcb->file_number) != 0) {
929         TRACE("_lclose16(%d) failed\n", fcb->file_number);
930         AL_result = 0xff; /* failed */
931     } else {
932         TRACE("successful closed file %d\n", fcb->file_number);
933         AL_result = 0x00; /* successful */
934     } /* if */
935     SET_AL(context, AL_result);
936 }
937
938
939 /***********************************************************************
940  *           INT21_SequentialReadFromFCB
941  *
942  * Handler for function 0x14.
943  *
944  * PARAMS
945  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
946  *
947  * RETURNS (in AL)
948  *  0: successful
949  *  1: end of file, no data read
950  *  2: segment wrap in DTA, no data read (not returned now)
951  *  3: end of file, partial record read
952  *
953  * NOTES
954  *  Reads a record with the size FCB->logical_record_size from the FCB
955  *  to the disk transfer area. The position of the record is specified
956  *  with FCB->current_block_number and FCB->record_within_current_block.
957  *  Then FCB->current_block_number and FCB->record_within_current_block
958  *  are updated to point to the next record. If a partial record is
959  *  read, it is filled with zeros up to the FCB->logical_record_size.
960  */
961 static void INT21_SequentialReadFromFCB( CONTEXT86 *context )
962 {
963     struct FCB *fcb;
964     struct XFCB *xfcb;
965     HANDLE handle;
966     DWORD record_number;
967     long position;
968     BYTE *disk_transfer_area;
969     UINT bytes_read;
970     BYTE AL_result;
971
972     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
973     if (fcb->drive_number == 0xff) {
974         xfcb = (struct XFCB *) fcb;
975         fcb = (struct FCB *) xfcb->fcb;
976     } /* if */
977
978     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
979     if (handle == INVALID_HANDLE_VALUE) {
980         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
981             fcb->file_number);
982         AL_result = 0x01; /* end of file, no data read */
983     } else {
984         record_number = 128 * fcb->current_block_number + fcb->record_within_current_block;
985         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
986         if (position != record_number * fcb->logical_record_size) {
987             TRACE("seek(%d, %ld, 0) failed with %ld\n",
988                   fcb->file_number, record_number * fcb->logical_record_size, position);
989             AL_result = 0x01; /* end of file, no data read */
990         } else {
991             disk_transfer_area = INT21_GetCurrentDTA(context);
992             bytes_read = _lread((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
993             if (bytes_read != fcb->logical_record_size) {
994                 TRACE("_lread(%d, %p, %d) failed with %d\n",
995                       fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_read);
996                 if (bytes_read == 0) {
997                     AL_result = 0x01; /* end of file, no data read */
998                 } else {
999                     memset(&disk_transfer_area[bytes_read], 0, fcb->logical_record_size - bytes_read);
1000                     AL_result = 0x03; /* end of file, partial record read */
1001                 } /* if */
1002             } else {
1003                 TRACE("successful read %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
1004                     bytes_read, record_number, position, fcb->file_number, handle);
1005                 AL_result = 0x00; /* successful */
1006             } /* if */
1007         } /* if */
1008     } /* if */
1009     if (AL_result == 0x00 || AL_result == 0x03) {
1010         if (fcb->record_within_current_block == 127) {
1011             fcb->record_within_current_block = 0;
1012             fcb->current_block_number++;
1013         } else {
1014             fcb->record_within_current_block++;
1015         } /* if */
1016     } /* if */
1017     SET_AL(context, AL_result);
1018 }
1019
1020
1021 /***********************************************************************
1022  *           INT21_SequentialWriteToFCB
1023  *
1024  * Handler for function 0x15.
1025  *
1026  * PARAMS
1027  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1028  *
1029  * RETURNS (in AL)
1030  *  0: successful
1031  *  1: disk full
1032  *  2: segment wrap in DTA (not returned now)
1033  *
1034  * NOTES
1035  *  Writes a record with the size FCB->logical_record_size from the disk
1036  *  transfer area to the FCB. The position of the record is specified
1037  *  with FCB->current_block_number and FCB->record_within_current_block.
1038  *  Then FCB->current_block_number and FCB->record_within_current_block
1039  *  are updated to point to the next record. 
1040  */
1041 static void INT21_SequentialWriteToFCB( CONTEXT86 *context )
1042 {
1043     struct FCB *fcb;
1044     struct XFCB *xfcb;
1045     HANDLE handle;
1046     DWORD record_number;
1047     long position;
1048     BYTE *disk_transfer_area;
1049     UINT bytes_written;
1050     BYTE AL_result;
1051
1052     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1053     if (fcb->drive_number == 0xff) {
1054         xfcb = (struct XFCB *) fcb;
1055         fcb = (struct FCB *) xfcb->fcb;
1056     } /* if */
1057
1058     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1059     if (handle == INVALID_HANDLE_VALUE) {
1060         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1061             fcb->file_number);
1062         AL_result = 0x01; /* disk full */
1063     } else {
1064         record_number = 128 * fcb->current_block_number + fcb->record_within_current_block;
1065         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1066         if (position != record_number * fcb->logical_record_size) {
1067             TRACE("seek(%d, %ld, 0) failed with %ld\n",
1068                   fcb->file_number, record_number * fcb->logical_record_size, position);
1069             AL_result = 0x01; /* disk full */
1070         } else {
1071             disk_transfer_area = INT21_GetCurrentDTA(context);
1072             bytes_written = _lwrite((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
1073             if (bytes_written != fcb->logical_record_size) {
1074                 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1075                       fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_written);
1076                 AL_result = 0x01; /* disk full */
1077             } else {
1078                 TRACE("successful written %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
1079                     bytes_written, record_number, position, fcb->file_number, handle);
1080                 AL_result = 0x00; /* successful */
1081             } /* if */
1082         } /* if */
1083     } /* if */
1084     if (AL_result == 0x00) {
1085         if (fcb->record_within_current_block == 127) {
1086             fcb->record_within_current_block = 0;
1087             fcb->current_block_number++;
1088         } else {
1089             fcb->record_within_current_block++;
1090         } /* if */
1091     } /* if */
1092     SET_AL(context, AL_result);
1093 }
1094
1095
1096 /***********************************************************************
1097  *           INT21_ReadRandomRecordFromFCB
1098  *
1099  * Handler for function 0x21.
1100  *
1101  * PARAMS
1102  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1103  *
1104  * RETURNS (in AL)
1105  *  0: successful
1106  *  1: end of file, no data read
1107  *  2: segment wrap in DTA, no data read (not returned now)
1108  *  3: end of file, partial record read
1109  *
1110  * NOTES
1111  *  Reads a record with the size FCB->logical_record_size from
1112  *  the FCB to the disk transfer area. The position of the record
1113  *  is specified with FCB->random_access_record_number. The
1114  *  FCB->random_access_record_number is not updated. If a partial record
1115  *  is read, it is filled with zeros up to the FCB->logical_record_size.
1116  */
1117 static void INT21_ReadRandomRecordFromFCB( CONTEXT86 *context )
1118 {
1119     struct FCB *fcb;
1120     struct XFCB *xfcb;
1121     HANDLE handle;
1122     DWORD record_number;
1123     long position;
1124     BYTE *disk_transfer_area;
1125     UINT bytes_read;
1126     BYTE AL_result;
1127
1128     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1129     if (fcb->drive_number == 0xff) {
1130         xfcb = (struct XFCB *) fcb;
1131         fcb = (struct FCB *) xfcb->fcb;
1132     } /* if */
1133
1134     memcpy(&record_number, fcb->random_access_record_number, 4);
1135     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1136     if (handle == INVALID_HANDLE_VALUE) {
1137         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1138             fcb->file_number);
1139         AL_result = 0x01; /* end of file, no data read */
1140     } else {
1141         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1142         if (position != record_number * fcb->logical_record_size) {
1143             TRACE("seek(%d, %ld, 0) failed with %ld\n",
1144                   fcb->file_number, record_number * fcb->logical_record_size, position);
1145             AL_result = 0x01; /* end of file, no data read */
1146         } else {
1147             disk_transfer_area = INT21_GetCurrentDTA(context);
1148             bytes_read = _lread((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
1149             if (bytes_read != fcb->logical_record_size) {
1150                 TRACE("_lread(%d, %p, %d) failed with %d\n",
1151                       fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_read);
1152                 if (bytes_read == 0) {
1153                     AL_result = 0x01; /* end of file, no data read */
1154                 } else {
1155                     memset(&disk_transfer_area[bytes_read], 0, fcb->logical_record_size - bytes_read);
1156                     AL_result = 0x03; /* end of file, partial record read */
1157                 } /* if */
1158             } else {
1159                 TRACE("successful read %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
1160                     bytes_read, record_number, position, fcb->file_number, handle);
1161                 AL_result = 0x00; /* successful */
1162             } /* if */
1163         } /* if */
1164     } /* if */
1165     fcb->current_block_number = record_number / 128;
1166     fcb->record_within_current_block = record_number % 128;
1167     SET_AL(context, AL_result);
1168 }
1169
1170
1171 /***********************************************************************
1172  *           INT21_WriteRandomRecordToFCB
1173  *
1174  * Handler for function 0x22.
1175  *
1176  * PARAMS
1177  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1178  *
1179  * RETURNS (in AL)
1180  *  0: successful
1181  *  1: disk full
1182  *  2: segment wrap in DTA (not returned now)
1183  *
1184  * NOTES
1185  *  Writes a record with the size FCB->logical_record_size from
1186  *  the disk transfer area to the FCB. The position of the record
1187  *  is specified with FCB->random_access_record_number. The
1188  *  FCB->random_access_record_number is not updated.
1189  */
1190 static void INT21_WriteRandomRecordToFCB( CONTEXT86 *context )
1191 {
1192     struct FCB *fcb;
1193     struct XFCB *xfcb;
1194     HANDLE handle;
1195     DWORD record_number;
1196     long position;
1197     BYTE *disk_transfer_area;
1198     UINT bytes_written;
1199     BYTE AL_result;
1200
1201     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1202     if (fcb->drive_number == 0xff) {
1203         xfcb = (struct XFCB *) fcb;
1204         fcb = (struct FCB *) xfcb->fcb;
1205     } /* if */
1206
1207     memcpy(&record_number, fcb->random_access_record_number, 4);
1208     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1209     if (handle == INVALID_HANDLE_VALUE) {
1210         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1211             fcb->file_number);
1212         AL_result = 0x01; /* disk full */
1213     } else {
1214         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1215         if (position != record_number * fcb->logical_record_size) {
1216             TRACE("seek(%d, %ld, 0) failed with %ld\n",
1217                   fcb->file_number, record_number * fcb->logical_record_size, position);
1218             AL_result = 0x01; /* disk full */
1219         } else {
1220             disk_transfer_area = INT21_GetCurrentDTA(context);
1221             bytes_written = _lwrite((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
1222             if (bytes_written != fcb->logical_record_size) {
1223                 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1224                       fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_written);
1225                 AL_result = 0x01; /* disk full */
1226             } else {
1227                 TRACE("successful written %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
1228                     bytes_written, record_number, position, fcb->file_number, handle);
1229                 AL_result = 0x00; /* successful */
1230             } /* if */
1231         } /* if */
1232     } /* if */
1233     fcb->current_block_number = record_number / 128;
1234     fcb->record_within_current_block = record_number % 128;
1235     SET_AL(context, AL_result);
1236 }
1237
1238
1239 /***********************************************************************
1240  *           INT21_RandomBlockReadFromFCB
1241  *
1242  * Handler for function 0x27.
1243  *
1244  * PARAMS
1245  *  CX    [I/O] Number of records to read
1246  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1247  *
1248  * RETURNS (in AL)
1249  *  0: successful
1250  *  1: end of file, no data read
1251  *  2: segment wrap in DTA, no data read (not returned now)
1252  *  3: end of file, partial record read
1253  *
1254  * NOTES
1255  *  Reads several records with the size FCB->logical_record_size from
1256  *  the FCB to the disk transfer area. The number of records to be
1257  *  read is specified in the CX register. The position of the first
1258  *  record is specified with FCB->random_access_record_number. The
1259  *  FCB->random_access_record_number, the FCB->current_block_number
1260  *  and FCB->record_within_current_block are updated to point to the
1261  *  next record after the records read. If a partial record is read,
1262  *  it is filled with zeros up to the FCB->logical_record_size. The
1263  *  CX register is set to the number of successfully read records.
1264  */
1265 static void INT21_RandomBlockReadFromFCB( CONTEXT86 *context )
1266 {
1267     struct FCB *fcb;
1268     struct XFCB *xfcb;
1269     HANDLE handle;
1270     DWORD record_number;
1271     long position;
1272     BYTE *disk_transfer_area;
1273     UINT records_requested;
1274     UINT bytes_requested;
1275     UINT bytes_read;
1276     UINT records_read;
1277     BYTE AL_result;
1278
1279     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1280     if (fcb->drive_number == 0xff) {
1281         xfcb = (struct XFCB *) fcb;
1282         fcb = (struct FCB *) xfcb->fcb;
1283     } /* if */
1284
1285     memcpy(&record_number, fcb->random_access_record_number, 4);
1286     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1287     if (handle == INVALID_HANDLE_VALUE) {
1288         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1289             fcb->file_number);
1290         records_read = 0;
1291         AL_result = 0x01; /* end of file, no data read */
1292     } else {
1293         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1294         if (position != record_number * fcb->logical_record_size) {
1295             TRACE("seek(%d, %ld, 0) failed with %ld\n",
1296                   fcb->file_number, record_number * fcb->logical_record_size, position);
1297             records_read = 0;
1298             AL_result = 0x01; /* end of file, no data read */
1299         } else {
1300             disk_transfer_area = INT21_GetCurrentDTA(context);
1301             records_requested = CX_reg(context);
1302             bytes_requested = (UINT) records_requested * fcb->logical_record_size;
1303             bytes_read = _lread((HFILE) handle, disk_transfer_area, bytes_requested);
1304             if (bytes_read != bytes_requested) {
1305                 TRACE("_lread(%d, %p, %d) failed with %d\n",
1306                       fcb->file_number, disk_transfer_area, bytes_requested, bytes_read);
1307                 records_read = bytes_read / fcb->logical_record_size;
1308                 if (bytes_read % fcb->logical_record_size == 0) {
1309                     AL_result = 0x01; /* end of file, no data read */
1310                 } else {
1311                     records_read++;
1312                     memset(&disk_transfer_area[bytes_read], 0, records_read * fcb->logical_record_size - bytes_read);
1313                     AL_result = 0x03; /* end of file, partial record read */
1314                 } /* if */
1315             } else {
1316                 TRACE("successful read %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
1317                     bytes_read, record_number, position, fcb->file_number, handle);
1318                 records_read = records_requested;
1319                 AL_result = 0x00; /* successful */
1320             } /* if */
1321         } /* if */
1322     } /* if */
1323     record_number += records_read;
1324     memcpy(fcb->random_access_record_number, &record_number, 4);
1325     fcb->current_block_number = record_number / 128;
1326     fcb->record_within_current_block = record_number % 128;
1327     SET_CX(context, records_read);
1328     SET_AL(context, AL_result);
1329 }
1330
1331
1332 /***********************************************************************
1333  *           INT21_RandomBlockWriteToFCB
1334  *
1335  * Handler for function 0x28.
1336  *
1337  * PARAMS
1338  *  CX    [I/O] Number of records to write
1339  *  DX:DX [I/O] File control block (FCB or XFCB) of open file
1340  *
1341  * RETURNS (in AL)
1342  *  0: successful
1343  *  1: disk full
1344  *  2: segment wrap in DTA (not returned now)
1345  *
1346  * NOTES
1347  *  Writes several records with the size FCB->logical_record_size from
1348  *  the disk transfer area to the FCB. The number of records to be
1349  *  written is specified in the CX register. The position of the first
1350  *  record is specified with FCB->random_access_record_number. The
1351  *  FCB->random_access_record_number, the FCB->current_block_number
1352  *  and FCB->record_within_current_block are updated to point to the
1353  *  next record after the records written. The CX register is set to
1354  *  the number of successfully written records.
1355  */
1356 static void INT21_RandomBlockWriteToFCB( CONTEXT86 *context )
1357 {
1358     struct FCB *fcb;
1359     struct XFCB *xfcb;
1360     HANDLE handle;
1361     DWORD record_number;
1362     long position;
1363     BYTE *disk_transfer_area;
1364     UINT records_requested;
1365     UINT bytes_requested;
1366     UINT bytes_written;
1367     UINT records_written;
1368     BYTE AL_result;
1369
1370     fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
1371     if (fcb->drive_number == 0xff) {
1372         xfcb = (struct XFCB *) fcb;
1373         fcb = (struct FCB *) xfcb->fcb;
1374     } /* if */
1375
1376     memcpy(&record_number, fcb->random_access_record_number, 4);
1377     handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
1378     if (handle == INVALID_HANDLE_VALUE) {
1379         TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
1380             fcb->file_number);
1381         records_written = 0;
1382         AL_result = 0x01; /* disk full */
1383     } else {
1384         position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
1385         if (position != record_number * fcb->logical_record_size) {
1386             TRACE("seek(%d, %ld, 0) failed with %ld\n",
1387                   fcb->file_number, record_number * fcb->logical_record_size, position);
1388             records_written = 0;
1389             AL_result = 0x01; /* disk full */
1390         } else {
1391             disk_transfer_area = INT21_GetCurrentDTA(context);
1392             records_requested = CX_reg(context);
1393             bytes_requested = (UINT) records_requested * fcb->logical_record_size;
1394             bytes_written = _lwrite((HFILE) handle, disk_transfer_area, bytes_requested);
1395             if (bytes_written != bytes_requested) {
1396                 TRACE("_lwrite(%d, %p, %d) failed with %d\n",
1397                       fcb->file_number, disk_transfer_area, bytes_requested, bytes_written);
1398                 records_written = bytes_written / fcb->logical_record_size;
1399                 AL_result = 0x01; /* disk full */
1400             } else {
1401                 TRACE("successful write %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
1402                     bytes_written, record_number, position, fcb->file_number, handle);
1403                 records_written = records_requested;
1404                 AL_result = 0x00; /* successful */
1405             } /* if */
1406         } /* if */
1407     } /* if */
1408     record_number += records_written;
1409     memcpy(fcb->random_access_record_number, &record_number, 4);
1410     fcb->current_block_number = record_number / 128;
1411     fcb->record_within_current_block = record_number % 128;
1412     SET_CX(context, records_written);
1413     SET_AL(context, AL_result);
1414 }
1415
1416
1417 /***********************************************************************
1418  *           INT21_CreateDirectory
1419  *
1420  * Handler for:
1421  * - function 0x39
1422  * - subfunction 0x39 of function 0x71
1423  * - subfunction 0xff of function 0x43 (CL == 0x39)
1424  */
1425 static BOOL INT21_CreateDirectory( CONTEXT86 *context )
1426 {
1427     WCHAR dirW[MAX_PATH];
1428     char *dirA = CTX_SEG_OFF_TO_LIN(context,
1429                                     context->SegDs, 
1430                                     context->Edx);
1431
1432     TRACE( "CREATE DIRECTORY %s\n", dirA );
1433
1434     MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
1435
1436     if (CreateDirectoryW(dirW, NULL))
1437         return TRUE;
1438
1439     /*
1440      * FIXME: CreateDirectory's LastErrors will clash with the ones
1441      *        used by DOS. AH=39 only returns 3 (path not found) and 
1442      *        5 (access denied), while CreateDirectory return several
1443      *        ones. Remap some of them. -Marcus
1444      */
1445     switch (GetLastError()) 
1446     {
1447     case ERROR_ALREADY_EXISTS:
1448     case ERROR_FILENAME_EXCED_RANGE:
1449     case ERROR_DISK_FULL:
1450         SetLastError(ERROR_ACCESS_DENIED);
1451         break;
1452     default: 
1453         break;
1454     }
1455
1456     return FALSE;
1457 }
1458
1459
1460 /***********************************************************************
1461  *           INT21_ExtendedCountryInformation
1462  *
1463  * Handler for function 0x65.
1464  */
1465 static void INT21_ExtendedCountryInformation( CONTEXT86 *context )
1466 {
1467     BYTE *dataptr = CTX_SEG_OFF_TO_LIN( context, context->SegEs, context->Edi );
1468
1469     TRACE( "GET EXTENDED COUNTRY INFORMATION, subfunction %02x\n",
1470            AL_reg(context) );
1471
1472     /*
1473      * Check subfunctions that are passed country and code page.
1474      */
1475     if (AL_reg(context) >= 0x01 && AL_reg(context) <= 0x07)
1476     {
1477         WORD country = DX_reg(context);
1478         WORD codepage = BX_reg(context);
1479
1480         if (country != 0xffff && country != INT21_GetSystemCountryCode())
1481             FIXME( "Requested info on non-default country %04x\n", country );
1482
1483         if (codepage != 0xffff && codepage != GetOEMCP())
1484             FIXME( "Requested info on non-default code page %04x\n", codepage );
1485     }
1486
1487     switch (AL_reg(context)) {
1488     case 0x00: /* SET GENERAL INTERNATIONALIZATION INFO */
1489         INT_BARF( context, 0x21 );
1490         SET_CFLAG( context );
1491         break;
1492
1493     case 0x01: /* GET GENERAL INTERNATIONALIZATION INFO */
1494         TRACE( "Get general internationalization info\n" );
1495         dataptr[0] = 0x01; /* Info ID */
1496         *(WORD*)(dataptr+1) = 38; /* Size of the following info */
1497         *(WORD*)(dataptr+3) = INT21_GetSystemCountryCode(); /* Country ID */
1498         *(WORD*)(dataptr+5) = GetOEMCP(); /* Code page */
1499         INT21_FillCountryInformation( dataptr + 7 );
1500         SET_CX( context, 41 ); /* Size of returned info */
1501         break;
1502         
1503     case 0x02: /* GET POINTER TO UPPERCASE TABLE */
1504     case 0x04: /* GET POINTER TO FILENAME UPPERCASE TABLE */
1505         TRACE( "Get pointer to uppercase table\n" );
1506         dataptr[0] = AL_reg(context); /* Info ID */
1507         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1508                                            offsetof(INT21_HEAP, uppercase_size) );
1509         SET_CX( context, 5 ); /* Size of returned info */
1510         break;
1511
1512     case 0x03: /* GET POINTER TO LOWERCASE TABLE */
1513         TRACE( "Get pointer to lowercase table\n" );
1514         dataptr[0] = 0x03; /* Info ID */
1515         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1516                                            offsetof(INT21_HEAP, lowercase_size) );
1517         SET_CX( context, 5 ); /* Size of returned info */
1518         break;
1519
1520     case 0x05: /* GET POINTER TO FILENAME TERMINATOR TABLE */
1521         TRACE("Get pointer to filename terminator table\n");
1522         dataptr[0] = 0x05; /* Info ID */
1523         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1524                                            offsetof(INT21_HEAP, filename_size) );
1525         SET_CX( context, 5 ); /* Size of returned info */
1526         break;
1527
1528     case 0x06: /* GET POINTER TO COLLATING SEQUENCE TABLE */
1529         TRACE("Get pointer to collating sequence table\n");
1530         dataptr[0] = 0x06; /* Info ID */
1531         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1532                                            offsetof(INT21_HEAP, collating_size) );
1533         SET_CX( context, 5 ); /* Size of returned info */
1534         break;
1535
1536     case 0x07: /* GET POINTER TO DBCS LEAD BYTE TABLE */
1537         TRACE("Get pointer to DBCS lead byte table\n");
1538         dataptr[0] = 0x07; /* Info ID */
1539         *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
1540                                            offsetof(INT21_HEAP, dbcs_size) );
1541         SET_CX( context, 5 ); /* Size of returned info */
1542         break;
1543
1544     case 0x20: /* CAPITALIZE CHARACTER */
1545     case 0xa0: /* CAPITALIZE FILENAME CHARACTER */
1546         TRACE("Convert char to uppercase\n");
1547         SET_DL( context, toupper(DL_reg(context)) );
1548         break;
1549
1550     case 0x21: /* CAPITALIZE STRING */
1551     case 0xa1: /* CAPITALIZE COUNTED FILENAME STRING */
1552         TRACE("Convert string to uppercase with length\n");
1553         {
1554             char *ptr = (char *)CTX_SEG_OFF_TO_LIN( context,
1555                                                     context->SegDs,
1556                                                     context->Edx );
1557             WORD len = CX_reg(context);
1558             while (len--) { *ptr = toupper(*ptr); ptr++; }
1559         }
1560         break;
1561
1562     case 0x22: /* CAPITALIZE ASCIIZ STRING */
1563     case 0xa2: /* CAPITALIZE ASCIIZ FILENAME */
1564         TRACE("Convert ASCIIZ string to uppercase\n");
1565         _strupr( (LPSTR)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx) );
1566         break;
1567
1568     case 0x23: /* DETERMINE IF CHARACTER REPRESENTS YES/NO RESPONSE */
1569         INT_BARF( context, 0x21 );
1570         SET_CFLAG( context );
1571         break;
1572
1573     default:
1574         INT_BARF( context, 0x21 );
1575         SET_CFLAG(context);
1576         break;
1577     }
1578 }
1579
1580
1581 /***********************************************************************
1582  *           INT21_FileAttributes
1583  *
1584  * Handler for:
1585  * - function 0x43
1586  * - subfunction 0x43 of function 0x71
1587  */
1588 static BOOL INT21_FileAttributes( CONTEXT86 *context, 
1589                                   BYTE       subfunction,
1590                                   BOOL       islong )
1591 {
1592     WCHAR fileW[MAX_PATH];
1593     char *fileA = CTX_SEG_OFF_TO_LIN(context, 
1594                                      context->SegDs, 
1595                                      context->Edx);
1596     HANDLE   handle;
1597     BOOL     status;
1598     FILETIME filetime;
1599     DWORD    result;
1600     WORD     date, time;
1601
1602     switch (subfunction)
1603     {
1604     case 0x00: /* GET FILE ATTRIBUTES */
1605         TRACE( "GET FILE ATTRIBUTES for %s\n", fileA );
1606         MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
1607
1608         result = GetFileAttributesW( fileW );
1609         if (result == -1)
1610             return FALSE;
1611         else
1612         {
1613             SET_CX( context, (WORD)result );
1614             if (!islong)
1615                 SET_AX( context, (WORD)result ); /* DR DOS */
1616         }
1617         break;
1618
1619     case 0x01: /* SET FILE ATTRIBUTES */
1620         TRACE( "SET FILE ATTRIBUTES 0x%02x for %s\n", 
1621                CX_reg(context), fileA );
1622         MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
1623
1624         if (!SetFileAttributesW( fileW, CX_reg(context) ))
1625             return FALSE;
1626         break;
1627
1628     case 0x02: /* GET COMPRESSED FILE SIZE */
1629         TRACE( "GET COMPRESSED FILE SIZE for %s\n", fileA );
1630         MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
1631
1632         result = GetCompressedFileSizeW( fileW, NULL );
1633         if (result == INVALID_FILE_SIZE)
1634             return FALSE;
1635         else
1636         {
1637             SET_AX( context, LOWORD(result) );
1638             SET_DX( context, HIWORD(result) );
1639         }
1640         break;
1641
1642     case 0x03: /* SET FILE LAST-WRITTEN DATE AND TIME */
1643         if (!islong)
1644             INT_BARF( context, 0x21 );
1645         else
1646         {
1647             TRACE( "SET FILE LAST-WRITTEN DATE AND TIME, file %s\n", fileA );
1648             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
1649
1650             handle = CreateFileW( fileW, GENERIC_WRITE, 
1651                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
1652                                   NULL, OPEN_EXISTING, 0, 0 );
1653             if (handle == INVALID_HANDLE_VALUE)
1654                 return FALSE;
1655
1656             DosDateTimeToFileTime( DI_reg(context), 
1657                                    CX_reg(context),
1658                                    &filetime );
1659             status = SetFileTime( handle, NULL, NULL, &filetime );
1660
1661             CloseHandle( handle );
1662             return status;
1663         }
1664         break;
1665
1666     case 0x04: /* GET FILE LAST-WRITTEN DATE AND TIME */
1667         if (!islong)
1668             INT_BARF( context, 0x21 );
1669         else
1670         {
1671             TRACE( "GET FILE LAST-WRITTEN DATE AND TIME, file %s\n", fileA );
1672             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
1673
1674             handle = CreateFileW( fileW, GENERIC_READ, 
1675                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
1676                                   NULL, OPEN_EXISTING, 0, 0 );
1677             if (handle == INVALID_HANDLE_VALUE)
1678                 return FALSE;
1679
1680             status = GetFileTime( handle, NULL, NULL, &filetime );
1681             if (status)
1682             {
1683                 FileTimeToDosDateTime( &filetime, &date, &time );
1684                 SET_DI( context, date );
1685                 SET_CX( context, time );
1686             }
1687
1688             CloseHandle( handle );
1689             return status;
1690         }
1691         break;
1692
1693     case 0x05: /* SET FILE LAST ACCESS DATE */
1694         if (!islong)
1695             INT_BARF( context, 0x21 );
1696         else
1697         {
1698             TRACE( "SET FILE LAST ACCESS DATE, file %s\n", fileA );
1699             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
1700
1701             handle = CreateFileW( fileW, GENERIC_WRITE, 
1702                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
1703                                   NULL, OPEN_EXISTING, 0, 0 );
1704             if (handle == INVALID_HANDLE_VALUE)
1705                 return FALSE;
1706
1707             DosDateTimeToFileTime( DI_reg(context), 
1708                                    0,
1709                                    &filetime );
1710             status = SetFileTime( handle, NULL, &filetime, NULL );
1711
1712             CloseHandle( handle );
1713             return status;
1714         }
1715         break;
1716
1717     case 0x06: /* GET FILE LAST ACCESS DATE */
1718         if (!islong)
1719             INT_BARF( context, 0x21 );
1720         else
1721         {
1722             TRACE( "GET FILE LAST ACCESS DATE, file %s\n", fileA );
1723             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
1724
1725             handle = CreateFileW( fileW, GENERIC_READ, 
1726                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
1727                                   NULL, OPEN_EXISTING, 0, 0 );
1728             if (handle == INVALID_HANDLE_VALUE)
1729                 return FALSE;
1730
1731             status = GetFileTime( handle, NULL, &filetime, NULL );
1732             if (status)
1733             {
1734                 FileTimeToDosDateTime( &filetime, &date, NULL );
1735                 SET_DI( context, date );
1736             }
1737
1738             CloseHandle( handle );
1739             return status;
1740         }
1741         break;
1742
1743     case 0x07: /* SET FILE CREATION DATE AND TIME */
1744         if (!islong)
1745             INT_BARF( context, 0x21 );
1746         else
1747         {
1748             TRACE( "SET FILE CREATION DATE AND TIME, file %s\n", fileA );
1749
1750             handle = CreateFileW( fileW, GENERIC_WRITE,
1751                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
1752                                   NULL, OPEN_EXISTING, 0, 0 );
1753             if (handle == INVALID_HANDLE_VALUE)
1754                 return FALSE;
1755             
1756             /*
1757              * FIXME: SI has number of 10-millisecond units past time in CX.
1758              */
1759             DosDateTimeToFileTime( DI_reg(context),
1760                                    CX_reg(context),
1761                                    &filetime );
1762             status = SetFileTime( handle, &filetime, NULL, NULL );
1763
1764             CloseHandle( handle );
1765             return status;
1766         }
1767         break;
1768
1769     case 0x08: /* GET FILE CREATION DATE AND TIME */
1770         if (!islong)
1771             INT_BARF( context, 0x21 );
1772         else
1773         {
1774             TRACE( "GET FILE CREATION DATE AND TIME, handle %d\n",
1775                    BX_reg(context) );
1776
1777             handle = CreateFileW( fileW, GENERIC_READ, 
1778                                   FILE_SHARE_READ | FILE_SHARE_WRITE, 
1779                                   NULL, OPEN_EXISTING, 0, 0 );
1780             if (handle == INVALID_HANDLE_VALUE)
1781                 return FALSE;
1782
1783             status = GetFileTime( handle, &filetime, NULL, NULL );
1784             if (status)
1785             {            
1786                 FileTimeToDosDateTime( &filetime, &date, &time );
1787                 SET_DI( context, date );
1788                 SET_CX( context, time );
1789                 /*
1790                  * FIXME: SI has number of 10-millisecond units past 
1791                  *        time in CX.
1792                  */
1793                 SET_SI( context, 0 );
1794             }
1795
1796             CloseHandle(handle);
1797             return status;
1798         }
1799         break;
1800
1801     case 0xff: /* EXTENDED-LENGTH FILENAME OPERATIONS */
1802         if (islong || context->Ebp != 0x5053)
1803             INT_BARF( context, 0x21 );
1804         else
1805         {
1806             switch(CL_reg(context))
1807             {
1808             case 0x39:
1809                 if (!INT21_CreateDirectory( context ))
1810                     return FALSE;
1811                 break;
1812
1813             case 0x56:
1814                 if (!INT21_RenameFile( context ))
1815                     return FALSE;
1816                 break;
1817
1818             default:
1819                 INT_BARF( context, 0x21 );
1820             }
1821         }
1822         break;
1823
1824     default:
1825         INT_BARF( context, 0x21 );
1826     }
1827
1828     return TRUE;
1829 }
1830
1831
1832 /***********************************************************************
1833  *           INT21_FileDateTime
1834  *
1835  * Handler for function 0x57.
1836  */
1837 static BOOL INT21_FileDateTime( CONTEXT86 *context )
1838 {
1839     HANDLE   handle = DosFileHandleToWin32Handle(BX_reg(context));
1840     FILETIME filetime;
1841     WORD     date, time;
1842
1843     switch (AL_reg(context)) {
1844     case 0x00:  /* Get last-written stamp */
1845         TRACE( "GET FILE LAST-WRITTEN DATE AND TIME, handle %d\n",
1846                BX_reg(context) );
1847         {
1848             if (!GetFileTime( handle, NULL, NULL, &filetime ))
1849                 return FALSE;
1850             FileTimeToDosDateTime( &filetime, &date, &time );
1851             SET_DX( context, date );
1852             SET_CX( context, time );
1853             break;
1854         }
1855
1856     case 0x01:  /* Set last-written stamp */
1857         TRACE( "SET FILE LAST-WRITTEN DATE AND TIME, handle %d\n",
1858                BX_reg(context) );
1859         {
1860             DosDateTimeToFileTime( DX_reg(context), 
1861                                    CX_reg(context),
1862                                    &filetime );
1863             if (!SetFileTime( handle, NULL, NULL, &filetime ))
1864                 return FALSE;
1865             break;
1866         }
1867
1868     case 0x04:  /* Get last access stamp, DOS 7 */
1869         TRACE( "GET FILE LAST ACCESS DATE AND TIME, handle %d\n",
1870                BX_reg(context) );
1871         {
1872             if (!GetFileTime( handle, NULL, &filetime, NULL ))
1873                 return FALSE;
1874             FileTimeToDosDateTime( &filetime, &date, &time );
1875             SET_DX( context, date );
1876             SET_CX( context, time );
1877             break;
1878         }
1879
1880     case 0x05:  /* Set last access stamp, DOS 7 */
1881         TRACE( "SET FILE LAST ACCESS DATE AND TIME, handle %d\n",
1882                BX_reg(context) );
1883         {
1884             DosDateTimeToFileTime( DX_reg(context), 
1885                                    CX_reg(context),
1886                                    &filetime );
1887             if (!SetFileTime( handle, NULL, &filetime, NULL ))
1888                 return FALSE;
1889             break;
1890         }
1891
1892     case 0x06:  /* Get creation stamp, DOS 7 */
1893         TRACE( "GET FILE CREATION DATE AND TIME, handle %d\n",
1894                BX_reg(context) );
1895         {
1896             if (!GetFileTime( handle, &filetime, NULL, NULL ))
1897                 return FALSE;
1898             FileTimeToDosDateTime( &filetime, &date, &time );
1899             SET_DX( context, date );
1900             SET_CX( context, time );
1901             /*
1902              * FIXME: SI has number of 10-millisecond units past time in CX.
1903              */
1904             SET_SI( context, 0 );
1905             break;
1906         }
1907
1908     case 0x07:  /* Set creation stamp, DOS 7 */
1909         TRACE( "SET FILE CREATION DATE AND TIME, handle %d\n",
1910                BX_reg(context) );
1911         {
1912             /*
1913              * FIXME: SI has number of 10-millisecond units past time in CX.
1914              */
1915             DosDateTimeToFileTime( DX_reg(context), 
1916                                    CX_reg(context),
1917                                    &filetime );
1918             if (!SetFileTime( handle, &filetime, NULL, NULL ))
1919                 return FALSE;
1920             break;
1921         }
1922
1923     default:
1924         INT_BARF( context, 0x21 );
1925         break;
1926     }
1927
1928     return TRUE;
1929 }
1930
1931
1932 /***********************************************************************
1933  *           INT21_GetPSP
1934  *
1935  * Handler for functions 0x51 and 0x62.
1936  */
1937 static void INT21_GetPSP( CONTEXT86 *context )
1938 {
1939     TRACE( "GET CURRENT PSP ADDRESS (%02x)\n", AH_reg(context) );
1940
1941     /*
1942      * FIXME: should we return the original DOS PSP upon
1943      *        Windows startup ? 
1944      */
1945     if (!ISV86(context) && DOSVM_IsWin16())
1946         SET_BX( context, LOWORD(GetCurrentPDB16()) );
1947     else
1948         SET_BX( context, DOSVM_psp );
1949 }
1950
1951
1952 /***********************************************************************
1953  *           INT21_Ioctl_Block
1954  *
1955  * Handler for block device IOCTLs.
1956  */
1957 static void INT21_Ioctl_Block( CONTEXT86 *context )
1958 {
1959     BYTE *dataptr;
1960     BYTE  drive = INT21_MapDrive( BL_reg(context) );
1961     WCHAR drivespec[4] = {'A', ':', '\\', 0};
1962     UINT  drivetype;
1963
1964     drivespec[0] += drive;
1965     drivetype = GetDriveTypeW( drivespec );
1966
1967     RESET_CFLAG(context);
1968     if (drivetype == DRIVE_UNKNOWN || drivetype == DRIVE_NO_ROOT_DIR)
1969     {
1970         TRACE( "IOCTL - SUBFUNCTION %d - INVALID DRIVE %c:\n", 
1971                AL_reg(context), 'A' + drive );
1972         SetLastError( ERROR_INVALID_DRIVE );
1973         SET_AX( context, ERROR_INVALID_DRIVE );
1974         SET_CFLAG( context );
1975         return;
1976     }
1977
1978     switch (AL_reg(context))
1979     {
1980     case 0x04: /* READ FROM BLOCK DEVICE CONTROL CHANNEL */
1981     case 0x05: /* WRITE TO BLOCK DEVICE CONTROL CHANNEL */
1982         INT_BARF( context, 0x21 );
1983         break;
1984
1985     case 0x08: /* CHECK IF BLOCK DEVICE REMOVABLE */
1986         TRACE( "IOCTL - CHECK IF BLOCK DEVICE REMOVABLE - %c:\n",
1987                'A' + drive );
1988
1989         if (drivetype == DRIVE_REMOVABLE)
1990             SET_AX( context, 0 ); /* removable */
1991         else
1992             SET_AX( context, 1 ); /* not removable */
1993         break;
1994
1995     case 0x09: /* CHECK IF BLOCK DEVICE REMOTE */
1996         TRACE( "IOCTL - CHECK IF BLOCK DEVICE REMOTE - %c:\n",
1997                'A' + drive );
1998
1999         if (drivetype == DRIVE_REMOTE)
2000             SET_DX( context, (1<<9) | (1<<12) ); /* remote + no direct IO */
2001         else
2002             SET_DX( context, 0 ); /* FIXME: use driver attr here */
2003         break;
2004
2005     case 0x0d: /* GENERIC BLOCK DEVICE REQUEST */
2006         /* Get pointer to IOCTL parameter block. */
2007         dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
2008
2009         switch (CX_reg(context))
2010         {
2011         case 0x0841: /* write logical device track */
2012             TRACE( "GENERIC IOCTL - Write logical device track - %c:\n",
2013                    'A' + drive);
2014             {
2015                 WORD head   = *(WORD *)dataptr+1;
2016                 WORD cyl    = *(WORD *)dataptr+3;
2017                 WORD sect   = *(WORD *)dataptr+5;
2018                 WORD nrsect = *(WORD *)dataptr+7;
2019                 BYTE *data  =  (BYTE *)dataptr+9; /* FIXME: is this correct? */
2020
2021                 if (!DOSVM_RawWrite(drive, head*cyl*sect, nrsect, data, FALSE))
2022                 {
2023                     SET_AX( context, ERROR_WRITE_FAULT );
2024                     SET_CFLAG(context);
2025                 }
2026             }
2027             break;
2028
2029         case 0x084a: /* lock logical volume */
2030             TRACE( "GENERIC IOCTL - Lock logical volume, level %d mode %d - %c:\n",
2031                    BH_reg(context), DX_reg(context), 'A' + drive );
2032             break;
2033
2034         case 0x0860: /* get device parameters */
2035             INT_Int21Handler( context );
2036             break;
2037
2038         case 0x0861: /* read logical device track */
2039             TRACE( "GENERIC IOCTL - Read logical device track - %c:\n",
2040                    'A' + drive);
2041             {
2042                 WORD head   = *(WORD *)dataptr+1;
2043                 WORD cyl    = *(WORD *)dataptr+3;
2044                 WORD sect   = *(WORD *)dataptr+5;
2045                 WORD nrsect = *(WORD *)dataptr+7;
2046                 BYTE *data  =  (BYTE *)dataptr+9; /* FIXME: is this correct? */
2047
2048                 if (!DOSVM_RawRead(drive, head*cyl*sect, nrsect, data, FALSE))
2049                 {
2050                     SET_AX( context, ERROR_READ_FAULT );
2051                     SET_CFLAG(context);
2052                 }
2053             }
2054             break;
2055
2056         case 0x0866: /* get volume serial number */
2057             INT_Int21Handler( context );
2058             break;
2059
2060         case 0x086a: /* unlock logical volume */
2061             TRACE( "GENERIC IOCTL - Logical volume unlocked - %c:\n", 
2062                    'A' + drive );
2063             break;
2064
2065         case 0x086f: /* get drive map information */
2066             INT_Int21Handler( context );
2067             break;
2068
2069         case 0x0872:
2070             INT_Int21Handler( context );
2071             break;
2072
2073         default:
2074             INT_BARF( context, 0x21 );            
2075         }
2076         break;
2077
2078     case 0x0e: /* GET LOGICAL DRIVE MAP */
2079         TRACE( "IOCTL - GET LOGICAL DRIVE MAP - %c:\n",
2080                'A' + drive );
2081         /* FIXME: this is not correct if drive has mappings */
2082         SET_AL( context, 0 ); /* drive has no mapping */
2083         break;
2084
2085     case 0x0f: /* SET LOGICAL DRIVE MAP */
2086         INT_Int21Handler( context );
2087         break;
2088
2089     case 0x11: /* QUERY GENERIC IOCTL CAPABILITY */
2090     default:
2091         INT_BARF( context, 0x21 );
2092     }
2093 }
2094
2095
2096 /***********************************************************************
2097  *           INT21_Ioctl_Char
2098  *
2099  * Handler for character device IOCTLs.
2100  */
2101 static void INT21_Ioctl_Char( CONTEXT86 *context )
2102 {
2103     static const WCHAR emmxxxx0W[] = {'E','M','M','X','X','X','X','0',0};
2104     static const WCHAR scsimgrW[] = {'S','C','S','I','M','G','R','$',0};
2105
2106     HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
2107     const DOS_DEVICE *dev = DOSFS_GetDeviceByHandle(handle);
2108
2109     if (dev && !strcmpiW( dev->name, emmxxxx0W )) 
2110     {
2111         EMS_Ioctl_Handler(context);
2112         return;
2113     }
2114
2115     if (dev && !strcmpiW( dev->name, scsimgrW ) && AL_reg(context) == 2)
2116     {
2117         DOSVM_ASPIHandler(context);
2118         return;
2119     }
2120
2121     switch (AL_reg(context))
2122     {
2123     case 0x00: /* GET DEVICE INFORMATION */
2124         TRACE( "IOCTL - GET DEVICE INFORMATION - %d\n", BX_reg(context) );
2125         if (dev)
2126         {
2127             /*
2128              * Returns attribute word in DX: 
2129              *   Bit 14 - Device driver can process IOCTL requests.
2130              *   Bit 13 - Output until busy supported.
2131              *   Bit 11 - Driver supports OPEN/CLOSE calls.
2132              *   Bit  8 - Unknown.
2133              *   Bit  7 - Set (indicates device).
2134              *   Bit  6 - EOF on input.
2135              *   Bit  5 - Raw (binary) mode.
2136              *   Bit  4 - Device is special (uses int29).
2137              *   Bit  3 - Clock device.
2138              *   Bit  2 - NUL device.
2139              *   Bit  1 - Standard output.
2140              *   Bit  0 - Standard input.
2141              */
2142             SET_DX( context, dev->flags );
2143         }
2144         else
2145         {
2146             /*
2147              * Returns attribute word in DX: 
2148              *   Bit 15    - File is remote.
2149              *   Bit 14    - Don't set file date/time on closing.
2150              *   Bit 11    - Media not removable.
2151              *   Bit  8    - Generate int24 if no disk space on write 
2152              *               or read past end of file
2153              *   Bit  7    - Clear (indicates file).
2154              *   Bit  6    - File has not been written.
2155              *   Bit  5..0 - Drive number (0=A:,...)
2156              *
2157              * FIXME: Should check if file is on remote or removable drive.
2158              * FIXME: Should use drive file is located on (and not current).
2159              */
2160             SET_DX( context, 0x0140 + INT21_GetCurrentDrive() );
2161         }
2162         break;
2163
2164     case 0x01: /* SET DEVICE INFORMATION */
2165     case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
2166     case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
2167     case 0x06: /* GET INPUT STATUS */
2168     case 0x07: /* GET OUTPUT STATUS */
2169         INT_BARF( context, 0x21 );
2170         break;
2171
2172     case 0x0a: /* CHECK IF HANDLE IS REMOTE */
2173         TRACE( "IOCTL - CHECK IF HANDLE IS REMOTE - %d\n", BX_reg(context) );
2174         /*
2175          * Returns attribute word in DX:
2176          *   Bit 15 - Set if remote.
2177          *   Bit 14 - Set if date/time not set on close.
2178          *
2179          * FIXME: Should check if file is on remote drive.
2180          */
2181         SET_DX( context, 0 );
2182         break;
2183
2184     case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
2185     case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
2186     default:
2187         INT_BARF( context, 0x21 );
2188     }
2189 }
2190
2191
2192 /***********************************************************************
2193  *           INT21_Ioctl
2194  *
2195  * Handler for function 0x44.
2196  */
2197 static void INT21_Ioctl( CONTEXT86 *context )
2198 {
2199     switch (AL_reg(context))
2200     {
2201     case 0x00:
2202     case 0x01:
2203     case 0x02:
2204     case 0x03:
2205         INT21_Ioctl_Char( context );
2206         break;
2207
2208     case 0x04:
2209     case 0x05:
2210         INT21_Ioctl_Block( context );
2211         break;
2212
2213     case 0x06:
2214     case 0x07:
2215         INT21_Ioctl_Char( context );
2216         break;
2217
2218     case 0x08:
2219     case 0x09:
2220         INT21_Ioctl_Block( context );
2221         break;
2222
2223     case 0x0a:
2224         INT21_Ioctl_Char( context );
2225         break;
2226
2227     case 0x0b: /* SET SHARING RETRY COUNT */
2228         TRACE( "SET SHARING RETRY COUNT: Pause %d, retries %d.\n",
2229                CX_reg(context), DX_reg(context) );
2230         if (!CX_reg(context))
2231         {
2232             SET_AX( context, 1 );
2233             SET_CFLAG( context );
2234         }
2235         else
2236         {
2237             DOSMEM_LOL()->sharing_retry_delay = CX_reg(context);
2238             if (DX_reg(context))
2239                 DOSMEM_LOL()->sharing_retry_count = DX_reg(context);
2240             RESET_CFLAG( context );
2241         }
2242         break;
2243
2244     case 0x0c:
2245         INT21_Ioctl_Char( context );
2246         break;
2247
2248     case 0x0d:
2249     case 0x0e:
2250     case 0x0f:
2251         INT21_Ioctl_Block( context );
2252         break;
2253
2254     case 0x10:
2255         INT21_Ioctl_Char( context );
2256         break;
2257
2258     case 0x11:
2259         INT21_Ioctl_Block( context );
2260         break;
2261
2262     case 0x12: /*  DR DOS - DETERMINE DOS TYPE (OBSOLETE FUNCTION) */
2263         TRACE( "DR DOS - DETERMINE DOS TYPE (OBSOLETE FUNCTION)\n" );
2264         SET_CFLAG(context);        /* Error / This is not DR DOS. */
2265         SET_AX( context, 0x0001 ); /* Invalid function */
2266         break;
2267
2268     case 0x52: /* DR DOS - DETERMINE DOS TYPE */
2269         TRACE( "DR DOS - DETERMINE DOS TYPE\n" );
2270         SET_CFLAG(context);        /* Error / This is not DR DOS. */
2271         SET_AX( context, 0x0001 ); /* Invalid function */
2272         break;
2273
2274     case 0xe0:  /* Sun PC-NFS API */
2275         TRACE( "Sun PC-NFS API\n" );
2276         /* not installed */
2277         break;
2278
2279     default:
2280         INT_BARF( context, 0x21 );
2281     }
2282 }
2283
2284
2285 /***********************************************************************
2286  *           INT21_LongFilename
2287  *
2288  * Handler for function 0x71.
2289  */
2290 static void INT21_LongFilename( CONTEXT86 *context )
2291 {
2292     BOOL bSetDOSExtendedError = FALSE;
2293
2294     if (HIBYTE(HIWORD(GetVersion16())) < 0x07)
2295     {
2296         TRACE( "LONG FILENAME - functions supported only under DOS7\n" );
2297         SET_CFLAG( context );
2298         SET_AL( context, 0 );
2299         return;
2300     }
2301
2302     switch (AL_reg(context))
2303     {
2304     case 0x0d: /* RESET DRIVE */
2305         INT_BARF( context, 0x21 );
2306         break;
2307
2308     case 0x39: /* LONG FILENAME - MAKE DIRECTORY */
2309         if (!INT21_CreateDirectory( context ))
2310             bSetDOSExtendedError = TRUE;
2311         break;
2312
2313     case 0x3a: /* LONG FILENAME - REMOVE DIRECTORY */
2314         {
2315             WCHAR dirW[MAX_PATH];
2316             char *dirA = CTX_SEG_OFF_TO_LIN(context,
2317                                             context->SegDs, context->Edx);
2318
2319             TRACE( "LONG FILENAME - REMOVE DIRECTORY %s\n", dirA );
2320             MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
2321
2322             if (!RemoveDirectoryW( dirW ))
2323                 bSetDOSExtendedError = TRUE;
2324         }
2325         break;
2326
2327     case 0x3b: /* LONG FILENAME - CHANGE DIRECTORY */
2328         if (!INT21_SetCurrentDirectory( context ))
2329             bSetDOSExtendedError = TRUE;
2330         break;
2331
2332     case 0x41: /* LONG FILENAME - DELETE FILE */
2333         {
2334             WCHAR fileW[MAX_PATH];
2335             char *fileA = CTX_SEG_OFF_TO_LIN(context, 
2336                                              context->SegDs, context->Edx);
2337
2338             TRACE( "LONG FILENAME - DELETE FILE %s\n", fileA );
2339             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
2340
2341             if (!DeleteFileW( fileW ))
2342                 bSetDOSExtendedError = TRUE;
2343         }
2344         break;
2345
2346     case 0x43: /* LONG FILENAME - EXTENDED GET/SET FILE ATTRIBUTES */
2347         if (!INT21_FileAttributes( context, BL_reg(context), TRUE ))
2348             bSetDOSExtendedError = TRUE;
2349         break;
2350
2351     case 0x47: /* LONG FILENAME - GET CURRENT DIRECTORY */
2352         if (!INT21_GetCurrentDirectory( context, TRUE ))
2353             bSetDOSExtendedError = TRUE;
2354         break;
2355
2356     case 0x4e: /* LONG FILENAME - FIND FIRST MATCHING FILE */
2357     case 0x4f: /* LONG FILENAME - FIND NEXT MATCHING FILE */
2358         INT_Int21Handler( context );
2359         break;
2360
2361     case 0x56: /* LONG FILENAME - RENAME FILE */
2362         if (!INT21_RenameFile(context))
2363             bSetDOSExtendedError = TRUE;
2364         break;
2365
2366     case 0x60: /* LONG FILENAME - CONVERT PATH */
2367         INT_Int21Handler( context );
2368         break;
2369
2370     case 0x6c: /* LONG FILENAME - CREATE OR OPEN FILE */
2371         if (!INT21_CreateFile( context, context->Esi, TRUE,
2372                                BX_reg(context), DL_reg(context) ))
2373             bSetDOSExtendedError = TRUE;
2374         break;
2375
2376     case 0xa0: /* LONG FILENAME - GET VOLUME INFORMATION */
2377     case 0xa1: /* LONG FILENAME - "FindClose" - TERMINATE DIRECTORY SEARCH */
2378         INT_Int21Handler( context );
2379         break;
2380
2381     case 0xa6: /* LONG FILENAME - GET FILE INFO BY HANDLE */
2382         {
2383             HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
2384             BY_HANDLE_FILE_INFORMATION *info =
2385                 CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
2386             
2387             TRACE( "LONG FILENAME - GET FILE INFO BY HANDLE\n" );
2388             
2389             if (!GetFileInformationByHandle(handle, info))
2390                 bSetDOSExtendedError = TRUE;
2391         }
2392         break;
2393
2394     case 0xa7: /* LONG FILENAME - CONVERT TIME */
2395         switch (BL_reg(context))
2396         {
2397         case 0x00: /* FILE TIME TO DOS TIME */
2398             {
2399                 WORD      date, time;
2400                 FILETIME *filetime = CTX_SEG_OFF_TO_LIN(context,
2401                                                         context->SegDs,
2402                                                         context->Esi);
2403
2404                 TRACE( "LONG FILENAME - FILE TIME TO DOS TIME\n" );
2405
2406                 FileTimeToDosDateTime( filetime, &date, &time );
2407
2408                 SET_DX( context, date );
2409                 SET_CX( context, time );
2410
2411                 /*
2412                  * FIXME: BH has number of 10-millisecond units 
2413                  * past time in CX.
2414                  */
2415                 SET_BH( context, 0 );
2416             }
2417             break;
2418
2419         case 0x01: /* DOS TIME TO FILE TIME */
2420             {
2421                 FILETIME *filetime = CTX_SEG_OFF_TO_LIN(context,
2422                                                         context->SegEs,
2423                                                         context->Edi);
2424
2425                 TRACE( "LONG FILENAME - DOS TIME TO FILE TIME\n" );
2426
2427                 /*
2428                  * FIXME: BH has number of 10-millisecond units 
2429                  * past time in CX.
2430                  */
2431                 DosDateTimeToFileTime( DX_reg(context), CX_reg(context),
2432                                        filetime );
2433             }
2434             break;
2435
2436         default:
2437             INT_BARF( context, 0x21 );
2438             break;
2439         }
2440         break;
2441
2442     case 0xa8: /* LONG FILENAME - GENERATE SHORT FILENAME */
2443     case 0xa9: /* LONG FILENAME - SERVER CREATE OR OPEN FILE */
2444     case 0xaa: /* LONG FILENAME - SUBST */
2445     default:
2446         INT_BARF( context, 0x21 );
2447     }
2448
2449     if (bSetDOSExtendedError)
2450     {
2451         SET_AX( context, GetLastError() );
2452         SET_CFLAG( context );
2453     }
2454 }
2455
2456
2457 /***********************************************************************
2458  *           INT21_RenameFile
2459  *
2460  * Handler for:
2461  * - function 0x56
2462  * - subfunction 0x56 of function 0x71
2463  * - subfunction 0xff of function 0x43 (CL == 0x56)
2464  */
2465 static BOOL INT21_RenameFile( CONTEXT86 *context )
2466 {
2467     WCHAR fromW[MAX_PATH];
2468     WCHAR toW[MAX_PATH];
2469     char *fromA = CTX_SEG_OFF_TO_LIN(context, 
2470                                      context->SegDs,context->Edx);
2471     char *toA = CTX_SEG_OFF_TO_LIN(context, 
2472                                    context->SegEs,context->Edi);
2473
2474     TRACE( "RENAME FILE %s to %s\n", fromA, toA );
2475     MultiByteToWideChar(CP_OEMCP, 0, fromA, -1, fromW, MAX_PATH);
2476     MultiByteToWideChar(CP_OEMCP, 0, toA, -1, toW, MAX_PATH);
2477
2478     return MoveFileW( fromW, toW );
2479 }
2480
2481
2482 /***********************************************************************
2483  *           INT21_GetExtendedError
2484  */
2485 static void INT21_GetExtendedError( CONTEXT86 *context )
2486 {
2487     BYTE class, action, locus;
2488     WORD error = GetLastError();
2489
2490     switch(error)
2491     {
2492     case ERROR_SUCCESS:
2493         class = action = locus = 0;
2494         break;
2495     case ERROR_DIR_NOT_EMPTY:
2496         class  = EC_Exists;
2497         action = SA_Ignore;
2498         locus  = EL_Disk;
2499         break;
2500     case ERROR_ACCESS_DENIED:
2501         class  = EC_AccessDenied;
2502         action = SA_Abort;
2503         locus  = EL_Disk;
2504         break;
2505     case ERROR_CANNOT_MAKE:
2506         class  = EC_AccessDenied;
2507         action = SA_Abort;
2508         locus  = EL_Unknown;
2509         break;
2510     case ERROR_DISK_FULL:
2511     case ERROR_HANDLE_DISK_FULL:
2512         class  = EC_MediaError;
2513         action = SA_Abort;
2514         locus  = EL_Disk;
2515         break;
2516     case ERROR_FILE_EXISTS:
2517     case ERROR_ALREADY_EXISTS:
2518         class  = EC_Exists;
2519         action = SA_Abort;
2520         locus  = EL_Disk;
2521         break;
2522     case ERROR_FILE_NOT_FOUND:
2523         class  = EC_NotFound;
2524         action = SA_Abort;
2525         locus  = EL_Disk;
2526         break;
2527     case ER_GeneralFailure:
2528         class  = EC_SystemFailure;
2529         action = SA_Abort;
2530         locus  = EL_Unknown;
2531         break;
2532     case ERROR_INVALID_DRIVE:
2533         class  = EC_MediaError;
2534         action = SA_Abort;
2535         locus  = EL_Disk;
2536         break;
2537     case ERROR_INVALID_HANDLE:
2538         class  = EC_ProgramError;
2539         action = SA_Abort;
2540         locus  = EL_Disk;
2541         break;
2542     case ERROR_LOCK_VIOLATION:
2543         class  = EC_AccessDenied;
2544         action = SA_Abort;
2545         locus  = EL_Disk;
2546         break;
2547     case ERROR_NO_MORE_FILES:
2548         class  = EC_MediaError;
2549         action = SA_Abort;
2550         locus  = EL_Disk;
2551         break;
2552     case ER_NoNetwork:
2553         class  = EC_NotFound;
2554         action = SA_Abort;
2555         locus  = EL_Network;
2556         break;
2557     case ERROR_NOT_ENOUGH_MEMORY:
2558         class  = EC_OutOfResource;
2559         action = SA_Abort;
2560         locus  = EL_Memory;
2561         break;
2562     case ERROR_PATH_NOT_FOUND:
2563         class  = EC_NotFound;
2564         action = SA_Abort;
2565         locus  = EL_Disk;
2566         break;
2567     case ERROR_SEEK:
2568         class  = EC_NotFound;
2569         action = SA_Ignore;
2570         locus  = EL_Disk;
2571         break;
2572     case ERROR_SHARING_VIOLATION:
2573         class  = EC_Temporary;
2574         action = SA_Retry;
2575         locus  = EL_Disk;
2576         break;
2577     case ERROR_TOO_MANY_OPEN_FILES:
2578         class  = EC_ProgramError;
2579         action = SA_Abort;
2580         locus  = EL_Disk;
2581         break;
2582     default:
2583         FIXME("Unknown error %d\n", error );
2584         class  = EC_SystemFailure;
2585         action = SA_Abort;
2586         locus  = EL_Unknown;
2587         break;
2588     }
2589     TRACE("GET EXTENDED ERROR code 0x%02x class 0x%02x action 0x%02x locus %02x\n",
2590            error, class, action, locus );
2591     SET_AX( context, error );
2592     SET_BH( context, class );
2593     SET_BL( context, action );
2594     SET_CH( context, locus );
2595 }
2596
2597
2598 /***********************************************************************
2599  *           DOSVM_Int21Handler
2600  *
2601  * Interrupt 0x21 handler.
2602  */
2603 void WINAPI DOSVM_Int21Handler( CONTEXT86 *context )
2604 {
2605     BOOL bSetDOSExtendedError = FALSE;
2606
2607     TRACE( "AX=%04x BX=%04x CX=%04x DX=%04x "
2608            "SI=%04x DI=%04x DS=%04x ES=%04x EFL=%08lx\n",
2609            AX_reg(context), BX_reg(context), 
2610            CX_reg(context), DX_reg(context),
2611            SI_reg(context), DI_reg(context),
2612            (WORD)context->SegDs, (WORD)context->SegEs,
2613            context->EFlags );
2614
2615    /*
2616     * Extended error is used by (at least) functions 0x2f to 0x62.
2617     * Function 0x59 returns extended error and error should not
2618     * be cleared before handling the function.
2619     */
2620     if (AH_reg(context) >= 0x2f && AH_reg(context) != 0x59) 
2621         SetLastError(0);
2622
2623     RESET_CFLAG(context); /* Not sure if this is a good idea. */
2624
2625     switch(AH_reg(context))
2626     {
2627     case 0x00: /* TERMINATE PROGRAM */
2628         TRACE("TERMINATE PROGRAM\n");
2629         if (DOSVM_IsWin16())
2630             ExitThread( 0 );
2631         else if(ISV86(context))
2632             MZ_Exit( context, FALSE, 0 );
2633         else
2634             ERR( "Called from DOS protected mode\n" );
2635         break;
2636
2637     case 0x01: /* READ CHARACTER FROM STANDARD INPUT, WITH ECHO */
2638         {
2639             BYTE ascii;
2640             TRACE("DIRECT CHARACTER INPUT WITH ECHO\n");
2641             INT21_ReadChar( &ascii, context );
2642             SET_AL( context, ascii );
2643             /*
2644              * FIXME: What to echo when extended keycodes are read?
2645              */
2646             DOSVM_PutChar(AL_reg(context));
2647         }
2648         break;
2649
2650     case 0x02: /* WRITE CHARACTER TO STANDARD OUTPUT */
2651         TRACE("Write Character to Standard Output\n");
2652         DOSVM_PutChar(DL_reg(context));
2653         break;
2654
2655     case 0x03: /* READ CHARACTER FROM STDAUX  */
2656     case 0x04: /* WRITE CHARACTER TO STDAUX */
2657     case 0x05: /* WRITE CHARACTER TO PRINTER */
2658         INT_BARF( context, 0x21 );
2659         break;
2660
2661     case 0x06: /* DIRECT CONSOLE IN/OUTPUT */
2662         if (DL_reg(context) == 0xff) 
2663         {
2664             TRACE("Direct Console Input\n");
2665
2666             if (INT21_ReadChar( NULL, NULL ))
2667             {
2668                 BYTE ascii;
2669                 INT21_ReadChar( &ascii, context );
2670                 SET_AL( context, ascii );
2671                 RESET_ZFLAG( context );
2672             }
2673             else
2674             {
2675                 /* no character available */
2676                 SET_AL( context, 0 );
2677                 SET_ZFLAG( context );
2678             }
2679         } 
2680         else 
2681         {
2682             TRACE("Direct Console Output\n");
2683             DOSVM_PutChar(DL_reg(context));
2684             /*
2685              * At least DOS versions 2.1-7.0 return character 
2686              * that was written in AL register.
2687              */
2688             SET_AL( context, DL_reg(context) );
2689         }
2690         break;
2691
2692     case 0x07: /* DIRECT CHARACTER INPUT WITHOUT ECHO */
2693         {
2694             BYTE ascii;
2695             TRACE("DIRECT CHARACTER INPUT WITHOUT ECHO\n");
2696             INT21_ReadChar( &ascii, context );
2697             SET_AL( context, ascii );
2698         }
2699         break;
2700
2701     case 0x08: /* CHARACTER INPUT WITHOUT ECHO */
2702         {
2703             BYTE ascii;
2704             TRACE("CHARACTER INPUT WITHOUT ECHO\n");
2705             INT21_ReadChar( &ascii, context );
2706             SET_AL( context, ascii );
2707         }
2708         break;
2709
2710     case 0x09: /* WRITE STRING TO STANDARD OUTPUT */
2711         TRACE("WRITE '$'-terminated string from %04lX:%04X to stdout\n",
2712               context->SegDs, DX_reg(context) );
2713         {
2714             LPSTR data = CTX_SEG_OFF_TO_LIN( context, 
2715                                              context->SegDs, context->Edx );
2716             LPSTR p = data;
2717
2718             /*
2719              * Do NOT use strchr() to calculate the string length,
2720              * as '\0' is valid string content, too!
2721              * Maybe we should check for non-'$' strings, but DOS doesn't.
2722              */
2723             while (*p != '$') p++;
2724
2725             if (DOSVM_IsWin16())
2726                 WriteFile( DosFileHandleToWin32Handle(1), 
2727                            data, p - data, 0, 0 );
2728             else
2729                 for(; data != p; data++)
2730                     DOSVM_PutChar( *data );
2731
2732             SET_AL( context, '$' ); /* yes, '$' (0x24) gets returned in AL */
2733         }
2734         break;
2735
2736     case 0x0a: /* BUFFERED INPUT */
2737         {
2738             BYTE *ptr = CTX_SEG_OFF_TO_LIN(context,
2739                                            context->SegDs,
2740                                            context->Edx);
2741             WORD result;
2742
2743             TRACE( "BUFFERED INPUT (size=%d)\n", ptr[0] );
2744
2745             /*
2746              * FIXME: Some documents state that
2747              *        ptr[1] holds number of chars from last input which 
2748              *        may be recalled on entry, other documents do not mention
2749              *        this at all.
2750              */
2751             if (ptr[1])
2752                 TRACE( "Handle old chars in buffer!\n" );
2753
2754             /*
2755              * ptr[0] - capacity (includes terminating CR)
2756              * ptr[1] - characters read (excludes terminating CR)
2757              */
2758             result = INT21_BufferedInput( context, ptr + 2, ptr[0] );
2759             if (result > 0)
2760                 ptr[1] = (BYTE)result - 1;
2761             else
2762                 ptr[1] = 0;
2763         }
2764         break;
2765
2766     case 0x0b: /* GET STDIN STATUS */
2767         TRACE( "GET STDIN STATUS\n" );
2768         {
2769             if (INT21_ReadChar( NULL, NULL ))
2770                 SET_AL( context, 0xff ); /* character available */
2771             else
2772                 SET_AL( context, 0 ); /* no character available */
2773         }
2774         break;
2775
2776     case 0x0c: /* FLUSH BUFFER AND READ STANDARD INPUT */
2777         {
2778             BYTE al = AL_reg(context); /* Input function to execute after flush. */
2779
2780             TRACE( "FLUSH BUFFER AND READ STANDARD INPUT - 0x%02x\n", al );
2781
2782             /* FIXME: buffers are not flushed */
2783
2784             /*
2785              * If AL is one of 0x01, 0x06, 0x07, 0x08, or 0x0a,
2786              * int21 function identified by AL will be called.
2787              */
2788             if(al == 0x01 || al == 0x06 || al == 0x07 || al == 0x08 || al == 0x0a)
2789             {
2790                 SET_AH( context, al );
2791                 DOSVM_Int21Handler( context );
2792             }
2793         }
2794         break;
2795
2796     case 0x0d: /* DISK BUFFER FLUSH */
2797         TRACE("DISK BUFFER FLUSH ignored\n");
2798         break;
2799
2800     case 0x0e: /* SELECT DEFAULT DRIVE */
2801         TRACE( "SELECT DEFAULT DRIVE - %c:\n", 'A' + DL_reg(context) );
2802         INT21_SetCurrentDrive( DL_reg(context) );
2803         SET_AL( context, MAX_DOS_DRIVES );
2804         break;
2805
2806     case 0x0f: /* OPEN FILE USING FCB */
2807         INT21_OpenFileUsingFCB( context );
2808         break;
2809
2810     case 0x10: /* CLOSE FILE USING FCB */
2811         INT21_CloseFileUsingFCB( context );
2812         break;
2813
2814     case 0x11: /* FIND FIRST MATCHING FILE USING FCB */
2815     case 0x12: /* FIND NEXT MATCHING FILE USING FCB */
2816         INT_Int21Handler( context );
2817         break;
2818
2819     case 0x13: /* DELETE FILE USING FCB */
2820         INT_BARF( context, 0x21 );
2821         break;
2822
2823     case 0x14: /* SEQUENTIAL READ FROM FCB FILE */
2824         INT21_SequentialReadFromFCB( context );
2825         break;
2826
2827     case 0x15: /* SEQUENTIAL WRITE TO FCB FILE */
2828         INT21_SequentialWriteToFCB( context );
2829         break;
2830
2831     case 0x16: /* CREATE OR TRUNCATE FILE USING FCB */
2832     case 0x17: /* RENAME FILE USING FCB */
2833         INT_BARF( context, 0x21 );
2834         break;
2835
2836     case 0x18: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
2837         SET_AL( context, 0 );
2838         break;
2839
2840     case 0x19: /* GET CURRENT DEFAULT DRIVE */
2841         SET_AL( context, INT21_GetCurrentDrive() );
2842         TRACE( "GET CURRENT DRIVE -> %c:\n", 'A' + AL_reg( context ) );
2843         break;
2844
2845     case 0x1a: /* SET DISK TRANSFER AREA ADDRESS */
2846         TRACE( "SET DISK TRANSFER AREA ADDRESS %04lX:%04X\n",
2847                context->SegDs, DX_reg(context) );
2848         {
2849             TDB *task = GlobalLock16( GetCurrentTask() );
2850             task->dta = MAKESEGPTR( context->SegDs, DX_reg(context) );
2851         }
2852         break;
2853
2854     case 0x1b: /* GET ALLOCATION INFORMATION FOR DEFAULT DRIVE */
2855     case 0x1c: /* GET ALLOCATION INFORMATION FOR SPECIFIC DRIVE */
2856         INT_Int21Handler( context );
2857         break;
2858
2859     case 0x1d: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
2860     case 0x1e: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
2861         SET_AL( context, 0 );
2862         break;
2863
2864     case 0x1f: /* GET DRIVE PARAMETER BLOCK FOR DEFAULT DRIVE */
2865         INT_Int21Handler( context );
2866         break;
2867
2868     case 0x20: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
2869         SET_AL( context, 0 );
2870         break;
2871
2872     case 0x21: /* READ RANDOM RECORD FROM FCB FILE */
2873         INT21_ReadRandomRecordFromFCB( context );
2874         break;
2875
2876     case 0x22: /* WRITE RANDOM RECORD TO FCB FILE */
2877         INT21_WriteRandomRecordToFCB( context );
2878         break;
2879
2880     case 0x23: /* GET FILE SIZE FOR FCB */
2881     case 0x24: /* SET RANDOM RECORD NUMBER FOR FCB */
2882         INT_BARF( context, 0x21 );
2883         break;
2884
2885     case 0x25: /* SET INTERRUPT VECTOR */
2886         TRACE("SET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
2887         {
2888             FARPROC16 ptr = (FARPROC16)MAKESEGPTR( context->SegDs, DX_reg(context) );
2889             if (!ISV86(context) && DOSVM_IsWin16())
2890                 DOSVM_SetPMHandler16(  AL_reg(context), ptr );
2891             else
2892                 DOSVM_SetRMHandler( AL_reg(context), ptr );
2893         }
2894         break;
2895
2896     case 0x26: /* CREATE NEW PROGRAM SEGMENT PREFIX */
2897         INT_BARF( context, 0x21 );
2898         break;
2899
2900     case 0x27: /* RANDOM BLOCK READ FROM FCB FILE */
2901         INT21_RandomBlockReadFromFCB( context );
2902         break;
2903
2904     case 0x28: /* RANDOM BLOCK WRITE TO FCB FILE */
2905         INT21_RandomBlockWriteToFCB( context );
2906         break;
2907
2908     case 0x29: /* PARSE FILENAME INTO FCB */
2909         INT_Int21Handler( context );
2910         break;
2911
2912     case 0x2a: /* GET SYSTEM DATE */
2913         TRACE( "GET SYSTEM DATE\n" );
2914         {
2915             SYSTEMTIME systime;
2916             GetLocalTime( &systime );
2917             SET_CX( context, systime.wYear );
2918             SET_DH( context, systime.wMonth );
2919             SET_DL( context, systime.wDay );
2920             SET_AL( context, systime.wDayOfWeek );
2921         }
2922         break;
2923
2924     case 0x2b: /* SET SYSTEM DATE */
2925         TRACE( "SET SYSTEM DATE\n" );
2926         {
2927             WORD year  = CX_reg(context);
2928             BYTE month = DH_reg(context);
2929             BYTE day   = DL_reg(context);
2930
2931             if (year  >= 1980 && year  <= 2099 &&
2932                 month >= 1    && month <= 12   &&
2933                 day   >= 1    && day   <= 31)
2934             {
2935                 FIXME( "SetSystemDate(%02d/%02d/%04d): not allowed\n",
2936                        day, month, year );
2937                 SET_AL( context, 0 );  /* Let's pretend we succeeded */
2938             }
2939             else
2940             {
2941                 SET_AL( context, 0xff ); /* invalid date */
2942                 TRACE( "SetSystemDate(%02d/%02d/%04d): invalid date\n",
2943                        day, month, year );
2944             }
2945         }
2946         break;
2947
2948     case 0x2c: /* GET SYSTEM TIME */
2949         TRACE( "GET SYSTEM TIME\n" );
2950         {
2951             SYSTEMTIME systime;
2952             GetLocalTime( &systime );
2953             SET_CH( context, systime.wHour );
2954             SET_CL( context, systime.wMinute );
2955             SET_DH( context, systime.wSecond );
2956             SET_DL( context, systime.wMilliseconds / 10 );
2957         }
2958         break;
2959
2960     case 0x2d: /* SET SYSTEM TIME */
2961         if( CH_reg(context) >= 24 || CL_reg(context) >= 60 || DH_reg(context) >= 60 || DL_reg(context) >= 100 ) {
2962             TRACE("SetSystemTime(%02d:%02d:%02d.%02d): wrong time\n",
2963               CH_reg(context), CL_reg(context),
2964               DH_reg(context), DL_reg(context) );
2965             SET_AL( context, 0xFF );
2966         }
2967         else
2968         {
2969             FIXME("SetSystemTime(%02d:%02d:%02d.%02d): not allowed\n",
2970                   CH_reg(context), CL_reg(context),
2971                   DH_reg(context), DL_reg(context) );
2972             SET_AL( context, 0 );  /* Let's pretend we succeeded */
2973         }
2974         break;
2975
2976     case 0x2e: /* SET VERIFY FLAG */
2977         TRACE("SET VERIFY FLAG ignored\n");
2978         /* we cannot change the behaviour anyway, so just ignore it */
2979         break;
2980
2981     case 0x2f: /* GET DISK TRANSFER AREA ADDRESS */
2982         TRACE( "GET DISK TRANSFER AREA ADDRESS\n" );
2983         {
2984             TDB *task = GlobalLock16( GetCurrentTask() );
2985             context->SegEs = SELECTOROF( task->dta );
2986             SET_BX( context, OFFSETOF( task->dta ) );
2987         }
2988         break;
2989
2990     case 0x30: /* GET DOS VERSION */
2991         TRACE( "GET DOS VERSION - %s requested\n",
2992                (AL_reg(context) == 0x00) ? "OEM number" : "version flag" );
2993
2994         if (AL_reg(context) == 0x00)
2995             SET_BH( context, 0xff ); /* OEM number => undefined */
2996         else
2997             SET_BH( context, 0x08 ); /* version flag => DOS is in ROM */
2998
2999         SET_AL( context, HIBYTE(HIWORD(GetVersion16())) ); /* major version */
3000         SET_AH( context, LOBYTE(HIWORD(GetVersion16())) ); /* minor version */
3001
3002         SET_BL( context, 0x12 );     /* 0x123456 is 24-bit Wine's serial # */
3003         SET_CX( context, 0x3456 );
3004         break;
3005
3006     case 0x31: /* TERMINATE AND STAY RESIDENT */
3007         FIXME("TERMINATE AND STAY RESIDENT stub\n");
3008         break;
3009
3010     case 0x32: /* GET DOS DRIVE PARAMETER BLOCK FOR SPECIFIC DRIVE */
3011         INT_Int21Handler( context );
3012         break;
3013
3014     case 0x33: /* MULTIPLEXED */
3015         switch (AL_reg(context))
3016         {
3017         case 0x00: /* GET CURRENT EXTENDED BREAK STATE */
3018             TRACE("GET CURRENT EXTENDED BREAK STATE\n");
3019             SET_DL( context, DOSCONF_GetConfig()->brk_flag );
3020             break;
3021
3022         case 0x01: /* SET EXTENDED BREAK STATE */
3023             TRACE("SET CURRENT EXTENDED BREAK STATE\n");
3024             DOSCONF_GetConfig()->brk_flag = (DL_reg(context) > 0) ? 1 : 0;
3025             break;
3026
3027         case 0x02: /* GET AND SET EXTENDED CONTROL-BREAK CHECKING STATE*/
3028             TRACE("GET AND SET EXTENDED CONTROL-BREAK CHECKING STATE\n");
3029             /* ugly coding in order to stay reentrant */
3030             if (DL_reg(context))
3031             {
3032                 SET_DL( context, DOSCONF_GetConfig()->brk_flag );
3033                 DOSCONF_GetConfig()->brk_flag = 1;
3034             }
3035             else
3036             {
3037                 SET_DL( context, DOSCONF_GetConfig()->brk_flag );
3038                 DOSCONF_GetConfig()->brk_flag = 0;
3039             }
3040             break;
3041
3042         case 0x05: /* GET BOOT DRIVE */
3043             TRACE("GET BOOT DRIVE\n");
3044             SET_DL( context, 3 );
3045             /* c: is Wine's bootdrive (a: is 1)*/
3046             break;
3047
3048         case 0x06: /* GET TRUE VERSION NUMBER */
3049             TRACE("GET TRUE VERSION NUMBER\n");
3050             SET_BL( context, HIBYTE(HIWORD(GetVersion16())) ); /* major */
3051             SET_BH( context, LOBYTE(HIWORD(GetVersion16())) ); /* minor */
3052             SET_DL( context, 0x00 ); /* revision */
3053             SET_DH( context, 0x08 ); /* DOS is in ROM */
3054             break;
3055
3056         default:
3057             INT_BARF( context, 0x21 );
3058             break;
3059         }
3060         break;
3061
3062     case 0x34: /* GET ADDRESS OF INDOS FLAG */
3063         TRACE( "GET ADDRESS OF INDOS FLAG\n" );
3064         context->SegEs = INT21_GetHeapSelector( context );
3065         SET_BX( context, offsetof(INT21_HEAP, misc_indos) );
3066         break;
3067
3068     case 0x35: /* GET INTERRUPT VECTOR */
3069         TRACE("GET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
3070         {
3071             FARPROC16 addr;
3072             if (!ISV86(context) && DOSVM_IsWin16())
3073                 addr = DOSVM_GetPMHandler16( AL_reg(context) );
3074             else
3075                 addr = DOSVM_GetRMHandler( AL_reg(context) );
3076             context->SegEs = SELECTOROF(addr);
3077             SET_BX( context, OFFSETOF(addr) );
3078         }
3079         break;
3080
3081     case 0x36: /* GET FREE DISK SPACE */
3082         INT_Int21Handler( context );
3083         break;
3084
3085     case 0x37: /* SWITCHAR */
3086         {
3087             switch (AL_reg(context))
3088             {
3089             case 0x00: /* "SWITCHAR" - GET SWITCH CHARACTER */
3090                 TRACE( "SWITCHAR - GET SWITCH CHARACTER\n" );
3091                 SET_AL( context, 0x00 ); /* success*/
3092                 SET_DL( context, '/' );
3093                 break;
3094             case 0x01: /*"SWITCHAR" - SET SWITCH CHARACTER*/
3095                 FIXME( "SWITCHAR - SET SWITCH CHARACTER: %c\n",
3096                        DL_reg( context ));
3097                 SET_AL( context, 0x00 ); /* success*/
3098                 break;
3099             default:
3100                 INT_BARF( context, 0x21 );
3101                 break;
3102             }
3103         }
3104         break;
3105
3106     case 0x38: /* GET COUNTRY-SPECIFIC INFORMATION */
3107         TRACE( "GET COUNTRY-SPECIFIC INFORMATION\n" );
3108         if (AL_reg(context))
3109         {
3110             WORD country = AL_reg(context);
3111             if (country == 0xff)
3112                 country = BX_reg(context);
3113             if (country != INT21_GetSystemCountryCode()) {
3114                 FIXME( "Requested info on non-default country %04x\n", country );
3115                 SET_AX(context, 2);
3116                 SET_CFLAG(context);
3117             }
3118         }
3119         if(AX_reg(context) != 2 )
3120         {
3121             INT21_FillCountryInformation( CTX_SEG_OFF_TO_LIN(context,
3122                                                              context->SegDs,
3123                                                              context->Edx) );
3124             SET_AX( context, INT21_GetSystemCountryCode() );
3125             SET_BX( context, INT21_GetSystemCountryCode() );
3126             RESET_CFLAG(context);
3127         }
3128         break;
3129
3130     case 0x39: /* "MKDIR" - CREATE SUBDIRECTORY */
3131         if (!INT21_CreateDirectory( context ))
3132             bSetDOSExtendedError = TRUE;
3133         else
3134             RESET_CFLAG(context);
3135         break;
3136
3137     case 0x3a: /* "RMDIR" - REMOVE DIRECTORY */
3138         {
3139             WCHAR dirW[MAX_PATH];
3140             char *dirA = CTX_SEG_OFF_TO_LIN(context,
3141                                             context->SegDs, context->Edx);
3142
3143             TRACE( "REMOVE DIRECTORY %s\n", dirA );
3144
3145             MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
3146
3147             if (!RemoveDirectoryW( dirW ))
3148                 bSetDOSExtendedError = TRUE;
3149             else
3150                 RESET_CFLAG(context);
3151         }
3152         break;
3153
3154     case 0x3b: /* "CHDIR" - SET CURRENT DIRECTORY */
3155         if (!INT21_SetCurrentDirectory( context ))
3156             bSetDOSExtendedError = TRUE;
3157         else
3158             RESET_CFLAG(context);
3159         break;
3160
3161     case 0x3c: /* "CREAT" - CREATE OR TRUNCATE FILE */
3162         if (!INT21_CreateFile( context, context->Edx, FALSE, 
3163                                OF_READWRITE | OF_SHARE_COMPAT, 0x12 ))
3164             bSetDOSExtendedError = TRUE;
3165         else
3166             RESET_CFLAG(context);
3167         break;
3168
3169     case 0x3d: /* "OPEN" - OPEN EXISTING FILE */
3170         if (!INT21_CreateFile( context, context->Edx, FALSE, 
3171                                AL_reg(context), 0x01 ))
3172             bSetDOSExtendedError = TRUE;
3173         else
3174             RESET_CFLAG(context);
3175         break;
3176
3177     case 0x3e: /* "CLOSE" - CLOSE FILE */
3178         TRACE( "CLOSE handle %d\n", BX_reg(context) );
3179         if (_lclose16( BX_reg(context) ) == HFILE_ERROR16)
3180             bSetDOSExtendedError = TRUE;
3181         else
3182             RESET_CFLAG(context);
3183         break;
3184
3185     case 0x3f: /* "READ" - READ FROM FILE OR DEVICE */
3186         TRACE( "READ from %d to %04lX:%04X for %d bytes\n",
3187                BX_reg(context),
3188                context->SegDs,
3189                DX_reg(context),
3190                CX_reg(context) );
3191         {
3192             DWORD result;
3193             WORD  count  = CX_reg(context);
3194             BYTE *buffer = CTX_SEG_OFF_TO_LIN( context, 
3195                                                context->SegDs,
3196                                                context->Edx );
3197
3198             /* Some programs pass a count larger than the allocated buffer */
3199             if (DOSVM_IsWin16())
3200             {
3201                 WORD maxcount = GetSelectorLimit16( context->SegDs )
3202                     - DX_reg(context) + 1;
3203                 if (count > maxcount)
3204                     count = maxcount;
3205             }
3206
3207             /*
3208              * FIXME: Reading from console (BX=1) in DOS mode
3209              *        does not work as it is supposed to work.
3210              */
3211
3212             RESET_CFLAG(context); /* set if error */
3213             if (!DOSVM_IsWin16() && BX_reg(context) == 0)
3214             {
3215                 result = INT21_BufferedInput( context, buffer, count );
3216                 SET_AX( context, (WORD)result );
3217             }
3218             else if (ReadFile( DosFileHandleToWin32Handle(BX_reg(context)),
3219                                buffer, count, &result, NULL ))
3220                 SET_AX( context, (WORD)result );
3221             else
3222                 bSetDOSExtendedError = TRUE;
3223         }
3224         break;
3225
3226     case 0x40:  /* "WRITE" - WRITE TO FILE OR DEVICE */
3227         TRACE( "WRITE from %04lX:%04X to handle %d for %d byte\n",
3228                context->SegDs, DX_reg(context),
3229                BX_reg(context), CX_reg(context) );
3230         {
3231             BYTE *ptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3232
3233             if (!DOSVM_IsWin16() && 
3234                 (BX_reg(context) == 1 || BX_reg(context) == 2))
3235             {
3236                 int i;
3237                 for(i=0; i<CX_reg(context); i++)
3238                     DOSVM_PutChar(ptr[i]);
3239                 SET_AX(context, CX_reg(context));
3240                 RESET_CFLAG(context);
3241             }
3242             else
3243             {
3244                 HFILE handle = (HFILE)DosFileHandleToWin32Handle(BX_reg(context));
3245                 LONG result = _hwrite( handle, ptr, CX_reg(context) );
3246                 if (result == HFILE_ERROR)
3247                     bSetDOSExtendedError = TRUE;
3248                 else
3249                 {
3250                     SET_AX( context, (WORD)result );
3251                     RESET_CFLAG(context);
3252                 }
3253             }
3254         }
3255         break;
3256
3257     case 0x41: /* "UNLINK" - DELETE FILE */
3258         {
3259             WCHAR fileW[MAX_PATH];
3260             char *fileA = CTX_SEG_OFF_TO_LIN(context, 
3261                                              context->SegDs, 
3262                                              context->Edx);
3263
3264             TRACE( "UNLINK %s\n", fileA );
3265             MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);
3266
3267             if (!DeleteFileW( fileW ))
3268                 bSetDOSExtendedError = TRUE;
3269             else
3270                 RESET_CFLAG(context);
3271         }
3272         break;
3273
3274     case 0x42: /* "LSEEK" - SET CURRENT FILE POSITION */
3275         TRACE( "LSEEK handle %d offset %ld from %s\n",
3276                BX_reg(context), 
3277                MAKELONG( DX_reg(context), CX_reg(context) ),
3278                (AL_reg(context) == 0) ? 
3279                "start of file" : ((AL_reg(context) == 1) ? 
3280                                   "current file position" : "end of file") );
3281         {
3282             HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
3283             LONG   offset = MAKELONG( DX_reg(context), CX_reg(context) );
3284             DWORD  status = SetFilePointer( handle, offset, 
3285                                             NULL, AL_reg(context) );
3286             if (status == INVALID_SET_FILE_POINTER)
3287                 bSetDOSExtendedError = TRUE;
3288             else
3289             {
3290                 SET_AX( context, LOWORD(status) );
3291                 SET_DX( context, HIWORD(status) );
3292                 RESET_CFLAG(context);
3293             }
3294         }
3295         break;
3296
3297     case 0x43: /* FILE ATTRIBUTES */
3298         if (!INT21_FileAttributes( context, AL_reg(context), FALSE ))
3299             bSetDOSExtendedError = TRUE;
3300         else
3301             RESET_CFLAG(context);
3302         break;
3303
3304     case 0x44: /* IOCTL */
3305         INT21_Ioctl( context );
3306         break;
3307
3308     case 0x45: /* "DUP" - DUPLICATE FILE HANDLE */
3309         TRACE( "DUPLICATE FILE HANDLE %d\n", BX_reg(context) );
3310         {
3311             HANDLE handle32;
3312             HFILE  handle16 = HFILE_ERROR;
3313
3314             if (DuplicateHandle( GetCurrentProcess(),
3315                                  DosFileHandleToWin32Handle(BX_reg(context)),
3316                                  GetCurrentProcess(), 
3317                                  &handle32,
3318                                  0, TRUE, DUPLICATE_SAME_ACCESS ))
3319                 handle16 = Win32HandleToDosFileHandle(handle32);
3320
3321             if (handle16 == HFILE_ERROR)
3322                 bSetDOSExtendedError = TRUE;
3323             else
3324             {
3325                 SET_AX( context, handle16 );
3326                 RESET_CFLAG(context);
3327             }
3328         }
3329         break;
3330
3331     case 0x46: /* "DUP2", "FORCEDUP" - FORCE DUPLICATE FILE HANDLE */
3332         TRACE( "FORCEDUP - FORCE DUPLICATE FILE HANDLE %d to %d\n",
3333                BX_reg(context), CX_reg(context) );
3334         if (FILE_Dup2( BX_reg(context), CX_reg(context) ) == HFILE_ERROR16)
3335             bSetDOSExtendedError = TRUE;
3336         else
3337             RESET_CFLAG(context);
3338         break;
3339
3340     case 0x47: /* "CWD" - GET CURRENT DIRECTORY */
3341         if (!INT21_GetCurrentDirectory( context, FALSE ))
3342             bSetDOSExtendedError = TRUE;
3343         else
3344             RESET_CFLAG(context);
3345         break;
3346
3347     case 0x48: /* ALLOCATE MEMORY */
3348         TRACE( "ALLOCATE MEMORY for %d paragraphs\n", BX_reg(context) );
3349         {
3350             WORD  selector = 0;
3351             DWORD bytes = (DWORD)BX_reg(context) << 4;
3352
3353             if (!ISV86(context) && DOSVM_IsWin16())
3354             {
3355                 DWORD rv = GlobalDOSAlloc16( bytes );
3356                 selector = LOWORD( rv );
3357             }
3358             else
3359                 DOSMEM_GetBlock( bytes, &selector );
3360
3361             if (selector)
3362             {
3363                 SET_AX( context, selector );
3364                 RESET_CFLAG(context);
3365             }
3366             else
3367             {
3368                 SET_CFLAG(context);
3369                 SET_AX( context, 0x0008 ); /* insufficient memory */
3370                 SET_BX( context, DOSMEM_Available() >> 4 );
3371             }
3372         }
3373         break;
3374
3375     case 0x49: /* FREE MEMORY */
3376         TRACE( "FREE MEMORY segment %04lX\n", context->SegEs );
3377         {
3378             BOOL ok;
3379             
3380             if (!ISV86(context) && DOSVM_IsWin16())
3381             {
3382                 ok = !GlobalDOSFree16( context->SegEs );
3383
3384                 /* If we don't reset ES_reg, we will fail in the relay code */
3385                 if (ok)
3386                     context->SegEs = 0;
3387             }
3388             else
3389                 ok = DOSMEM_FreeBlock( (void*)((DWORD)context->SegEs << 4) );
3390
3391             if (!ok)
3392             {
3393                 TRACE("FREE MEMORY failed\n");
3394                 SET_CFLAG(context);
3395                 SET_AX( context, 0x0009 ); /* memory block address invalid */
3396             }
3397         }
3398         break;
3399
3400     case 0x4a: /* RESIZE MEMORY BLOCK */
3401         TRACE( "RESIZE MEMORY segment %04lX to %d paragraphs\n", 
3402                context->SegEs, BX_reg(context) );
3403         {
3404             DWORD newsize = (DWORD)BX_reg(context) << 4;
3405             
3406             if (!ISV86(context) && DOSVM_IsWin16())
3407             {
3408                 FIXME( "Resize memory block - unsupported under Win16\n" );
3409                 SET_CFLAG(context);
3410             }
3411             else
3412             {
3413                 LPVOID address = (void*)((DWORD)context->SegEs << 4);
3414                 UINT blocksize = DOSMEM_ResizeBlock( address, newsize, FALSE );
3415
3416                 RESET_CFLAG(context);
3417                 if (blocksize == (UINT)-1)
3418                 {
3419                     SET_CFLAG( context );
3420                     SET_AX( context, 0x0009 ); /* illegal address */
3421                 }
3422                 else if(blocksize != newsize)
3423                 {
3424                     SET_CFLAG( context );
3425                     SET_AX( context, 0x0008 );    /* insufficient memory */
3426                     SET_BX( context, blocksize >> 4 ); /* new block size */
3427                 }
3428             }
3429         }
3430         break;
3431
3432     case 0x4b: /* "EXEC" - LOAD AND/OR EXECUTE PROGRAM */
3433         {
3434             BYTE *program = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3435             BYTE *paramblk = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Ebx);
3436
3437             TRACE( "EXEC %s\n", program );
3438
3439             RESET_CFLAG(context);
3440             if (DOSVM_IsWin16())
3441             {
3442                 HINSTANCE16 instance = WinExec16( program, SW_NORMAL );
3443                 if (instance < 32)
3444                 {
3445                     SET_CFLAG( context );
3446                     SET_AX( context, instance );
3447                 }
3448             }
3449             else
3450             {
3451                 if (!MZ_Exec( context, program, AL_reg(context), paramblk))
3452                     bSetDOSExtendedError = TRUE;
3453             }
3454         }
3455         break;
3456
3457     case 0x4c: /* "EXIT" - TERMINATE WITH RETURN CODE */
3458         TRACE( "EXIT with return code %d\n", AL_reg(context) );
3459         if (DOSVM_IsWin16())
3460             ExitThread( AL_reg(context) );
3461         else if(ISV86(context))
3462             MZ_Exit( context, FALSE, AL_reg(context) );
3463         else
3464         {
3465             /*
3466              * Exit from DPMI.
3467              */            
3468             DWORD rv = AL_reg(context);
3469             RaiseException( EXCEPTION_VM86_INTx, 0, 1, &rv );
3470         }
3471         break;
3472
3473     case 0x4d: /* GET RETURN CODE */
3474         TRACE("GET RETURN CODE (ERRORLEVEL)\n");
3475         SET_AX( context, DOSVM_retval );
3476         DOSVM_retval = 0;
3477         break;
3478
3479     case 0x4e: /* "FINDFIRST" - FIND FIRST MATCHING FILE */
3480     case 0x4f: /* "FINDNEXT" - FIND NEXT MATCHING FILE */
3481         INT_Int21Handler( context );
3482         break;
3483
3484     case 0x50: /* SET CURRENT PROCESS ID (SET PSP ADDRESS) */
3485         TRACE("SET CURRENT PROCESS ID (SET PSP ADDRESS)\n");
3486         DOSVM_psp = BX_reg(context);
3487         break;
3488
3489     case 0x51: /* GET PSP ADDRESS */
3490         INT21_GetPSP( context );
3491         break;
3492
3493     case 0x52: /* "SYSVARS" - GET LIST OF LISTS */
3494         if (!ISV86(context) && DOSVM_IsWin16())
3495         {
3496             SEGPTR ptr = DOSMEM_LOL()->wine_pm_lol;
3497             context->SegEs = SELECTOROF(ptr);
3498             SET_BX( context, OFFSETOF(ptr) );
3499         }
3500         else
3501         {
3502             SEGPTR ptr = DOSMEM_LOL()->wine_rm_lol;
3503             context->SegEs = SELECTOROF(ptr);
3504             SET_BX( context, OFFSETOF(ptr) );
3505         }
3506         break;
3507
3508     case 0x54: /* Get Verify Flag */
3509         TRACE("Get Verify Flag - Not Supported\n");
3510         SET_AL( context, 0x00 );  /* pretend we can tell. 00h = off 01h = on */
3511         break;
3512
3513     case 0x56: /* "RENAME" - RENAME FILE */
3514         if (!INT21_RenameFile( context ))
3515             bSetDOSExtendedError = TRUE;
3516         else
3517             RESET_CFLAG(context);
3518         break;
3519
3520     case 0x57: /* FILE DATE AND TIME */
3521         if (!INT21_FileDateTime( context ))
3522             bSetDOSExtendedError = TRUE;
3523         else
3524             RESET_CFLAG(context);
3525         break;
3526
3527     case 0x58: /* GET OR SET MEMORY ALLOCATION STRATEGY */
3528         switch (AL_reg(context))
3529         {
3530         case 0x00: /* GET MEMORY ALLOCATION STRATEGY */
3531             TRACE( "GET MEMORY ALLOCATION STRATEGY\n" );
3532             SET_AX( context, 0 ); /* low memory first fit */
3533             break;
3534
3535         case 0x01: /* SET ALLOCATION STRATEGY */
3536             TRACE( "SET MEMORY ALLOCATION STRATEGY to %d - ignored\n",
3537                    BL_reg(context) );
3538             break;
3539
3540         case 0x02: /* GET UMB LINK STATE */
3541             TRACE( "GET UMB LINK STATE\n" );
3542             SET_AL( context, 0 ); /* UMBs not part of DOS memory chain */
3543             break;
3544
3545         case 0x03: /* SET UMB LINK STATE */
3546             TRACE( "SET UMB LINK STATE to %d - ignored\n",
3547                    BX_reg(context) );
3548             break;
3549
3550         default:
3551             INT_BARF( context, 0x21 );
3552         }
3553         break;
3554
3555     case 0x59: /* GET EXTENDED ERROR INFO */
3556         INT21_GetExtendedError( context );
3557         break;
3558
3559     case 0x5a: /* CREATE TEMPORARY FILE */
3560         INT_Int21Handler( context );
3561         break;
3562
3563     case 0x5b: /* CREATE NEW FILE */ 
3564         if (!INT21_CreateFile( context, context->Edx, FALSE,
3565                                OF_READWRITE | OF_SHARE_COMPAT, 0x10 ))
3566             bSetDOSExtendedError = TRUE;
3567         else
3568             RESET_CFLAG(context);
3569         break;
3570
3571     case 0x5c: /* "FLOCK" - RECORD LOCKING */
3572         {
3573             DWORD  offset = MAKELONG(DX_reg(context), CX_reg(context));
3574             DWORD  length = MAKELONG(DI_reg(context), SI_reg(context));
3575             HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
3576
3577             RESET_CFLAG(context);
3578             switch (AL_reg(context))
3579             {
3580             case 0x00: /* LOCK */
3581                 TRACE( "lock handle %d offset %ld length %ld\n",
3582                        BX_reg(context), offset, length );
3583                 if (!LockFile( handle, offset, 0, length, 0 ))
3584                     bSetDOSExtendedError = TRUE;
3585                 break;
3586
3587             case 0x01: /* UNLOCK */
3588                 TRACE( "unlock handle %d offset %ld length %ld\n",
3589                        BX_reg(context), offset, length );
3590                 if (!UnlockFile( handle, offset, 0, length, 0 ))
3591                     bSetDOSExtendedError = TRUE;
3592                 break;
3593
3594             default:
3595                 INT_BARF( context, 0x21 );
3596             }
3597         }
3598         break;
3599
3600     case 0x5d: /* NETWORK 5D */
3601         FIXME( "Network function 5D not implemented.\n" );
3602         SetLastError( ER_NoNetwork );
3603         bSetDOSExtendedError = TRUE;
3604         break;
3605
3606     case 0x5e: /* NETWORK 5E */
3607     case 0x5f: /* NETWORK 5F */
3608     case 0x60: /* "TRUENAME" - CANONICALIZE FILENAME OR PATH */
3609         INT_Int21Handler( context );
3610         break;
3611
3612     case 0x61: /* UNUSED */
3613         SET_AL( context, 0 );
3614         break;
3615
3616     case 0x62: /* GET PSP ADDRESS */
3617         INT21_GetPSP( context );
3618         break;
3619
3620     case 0x63: /* MISC. LANGUAGE SUPPORT */
3621         switch (AL_reg(context)) {
3622         case 0x00: /* GET DOUBLE BYTE CHARACTER SET LEAD-BYTE TABLE */
3623             TRACE( "GET DOUBLE BYTE CHARACTER SET LEAD-BYTE TABLE\n" );
3624             context->SegDs = INT21_GetHeapSelector( context );
3625             SET_SI( context, offsetof(INT21_HEAP, dbcs_table) );
3626             SET_AL( context, 0 ); /* success */
3627             break;
3628         }
3629         break;
3630
3631     case 0x64: /* OS/2 DOS BOX */
3632         INT_BARF( context, 0x21 );
3633         SET_CFLAG(context);
3634         break;
3635
3636     case 0x65: /* EXTENDED COUNTRY INFORMATION */
3637         INT21_ExtendedCountryInformation( context );
3638         break;
3639
3640     case 0x66: /* GLOBAL CODE PAGE TABLE */
3641         switch (AL_reg(context))
3642         {
3643         case 0x01:
3644             TRACE( "GET GLOBAL CODE PAGE TABLE\n" );
3645             SET_BX( context, GetOEMCP() );
3646             SET_DX( context, GetOEMCP() );
3647             break;
3648         case 0x02:
3649             FIXME( "SET GLOBAL CODE PAGE TABLE, active %d, system %d - ignored\n",
3650                    BX_reg(context), DX_reg(context) );
3651             break;
3652         }
3653         break;
3654
3655     case 0x67: /* SET HANDLE COUNT */
3656         TRACE( "SET HANDLE COUNT to %d\n", BX_reg(context) );
3657         if (SetHandleCount( BX_reg(context) ) < BX_reg(context) )
3658             bSetDOSExtendedError = TRUE;
3659         break;
3660
3661     case 0x68: /* "FFLUSH" - COMMIT FILE */
3662         TRACE( "FFLUSH - handle %d\n", BX_reg(context) );
3663         if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
3664             bSetDOSExtendedError = TRUE;
3665         break;
3666
3667     case 0x69: /* DISK SERIAL NUMBER */
3668         INT_Int21Handler( context );
3669         break;
3670
3671     case 0x6a: /* COMMIT FILE */
3672         TRACE( "COMMIT FILE - handle %d\n", BX_reg(context) );
3673         if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
3674             bSetDOSExtendedError = TRUE;
3675         break;
3676
3677     case 0x6b: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
3678         SET_AL( context, 0 );
3679         break;
3680
3681     case 0x6c: /* EXTENDED OPEN/CREATE */
3682         if (!INT21_CreateFile( context, context->Esi, TRUE,
3683                                BX_reg(context), DL_reg(context) ))
3684             bSetDOSExtendedError = TRUE;
3685         break;
3686
3687     case 0x70: /* MSDOS 7 - GET/SET INTERNATIONALIZATION INFORMATION */
3688         FIXME( "MS-DOS 7 - GET/SET INTERNATIONALIZATION INFORMATION\n" );
3689         SET_CFLAG( context );
3690         SET_AL( context, 0 );
3691         break;
3692
3693     case 0x71: /* MSDOS 7 - LONG FILENAME FUNCTIONS */
3694         INT21_LongFilename( context );
3695         break;
3696
3697     case 0x73: /* MSDOS7 - FAT32 */
3698         INT_Int21Handler( context );
3699         break;
3700
3701     case 0xdc: /* CONNECTION SERVICES - GET CONNECTION NUMBER */
3702         TRACE( "CONNECTION SERVICES - GET CONNECTION NUMBER - ignored\n" );
3703         break;
3704
3705     case 0xea: /* NOVELL NETWARE - RETURN SHELL VERSION */
3706         TRACE( "NOVELL NETWARE - RETURN SHELL VERSION - ignored\n" );
3707         break;
3708
3709     case 0xff: /* DOS32 EXTENDER (DOS/4GW) - API */
3710         /* we don't implement a DOS32 extender */
3711         TRACE( "DOS32 EXTENDER API - ignored\n" );
3712         break;
3713
3714     default:
3715         INT_BARF( context, 0x21 );
3716         break;
3717
3718     } /* END OF SWITCH */
3719
3720     /* Set general error condition. */
3721     if (bSetDOSExtendedError)
3722     {
3723         SET_AX( context, GetLastError() );
3724         SET_CFLAG( context );
3725     }
3726
3727     /* Print error code if carry flag is set. */
3728     if (context->EFlags & 0x0001)
3729         TRACE("failed, error %ld\n", GetLastError() );
3730
3731     TRACE( "returning: AX=%04x BX=%04x CX=%04x DX=%04x "
3732            "SI=%04x DI=%04x DS=%04x ES=%04x EFL=%08lx\n",
3733            AX_reg(context), BX_reg(context), 
3734            CX_reg(context), DX_reg(context), 
3735            SI_reg(context), DI_reg(context),
3736            (WORD)context->SegDs, (WORD)context->SegEs,
3737            context->EFlags );
3738 }