Move get current directory and set current directory int21
[wine] / msdos / 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  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <time.h>
29 #include <fcntl.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #ifdef HAVE_SYS_FILE_H
33 # include <sys/file.h>
34 #endif
35 #include <string.h>
36 #ifdef HAVE_SYS_TIME_H
37 # include <sys/time.h>
38 #endif
39 #include <sys/types.h>
40 #ifdef HAVE_UNISTD_H
41 # include <unistd.h>
42 #endif
43 #ifdef HAVE_UTIME_H
44 # include <utime.h>
45 #endif
46 #include <ctype.h>
47 #include "windef.h"
48 #include "winbase.h"
49 #include "winternl.h"
50 #include "wingdi.h"
51 #include "winuser.h" /* SW_NORMAL */
52 #include "wine/winbase16.h"
53 #include "winerror.h"
54 #include "drive.h"
55 #include "file.h"
56 #include "callback.h"
57 #include "msdos.h"
58 #include "miscemu.h"
59 #include "task.h"
60 #include "wine/unicode.h"
61 #include "wine/debug.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(int21);
64 #if defined(__svr4__) || defined(_SCO_DS)
65 /* SVR4 DOESNT do locking the same way must implement properly */
66 #define LOCK_EX 0
67 #define LOCK_SH  1
68 #define LOCK_NB  8
69 #endif
70
71
72 #define DOS_GET_DRIVE(reg) ((reg) ? (reg) - 1 : DRIVE_GetCurrentDrive())
73
74 /* Define the drive parameter block, as used by int21/1F
75  * and int21/32.  This table can be accessed through the
76  * global 'dpb' pointer, which points into the local dos
77  * heap.
78  */
79 struct DPB
80 {
81     BYTE drive_num;         /* 0=A, etc. */
82     BYTE unit_num;          /* Drive's unit number (?) */
83     WORD sector_size;       /* Sector size in bytes */
84     BYTE high_sector;       /* Highest sector in a cluster */
85     BYTE shift;             /* Shift count (?) */
86     WORD reserved;          /* Number of reserved sectors at start */
87     BYTE num_FAT;           /* Number of FATs */
88     WORD dir_entries;       /* Number of root dir entries */
89     WORD first_data;        /* First data sector */
90     WORD high_cluster;      /* Highest cluster number */
91     WORD sectors_in_FAT;    /* Number of sectors per FAT */
92     WORD start_dir;         /* Starting sector of first dir */
93     DWORD driver_head;      /* Address of device driver header (?) */
94     BYTE media_ID;          /* Media ID */
95     BYTE access_flag;       /* Prev. accessed flag (0=yes,0xFF=no) */
96     DWORD next;             /* Pointer to next DPB in list */
97     WORD free_search;       /* Free cluster search start */
98     WORD free_clusters;     /* Number of free clusters (0xFFFF=unknown) */
99 };
100
101 struct EDPB                     /* FAT32 extended Drive Parameter Block */
102 {                               /* from Ralf Brown's Interrupt List */
103         struct DPB dpb;         /* first 24 bytes = original DPB */
104
105         BYTE edpb_flags;        /* undocumented/unknown flags */
106         DWORD next_edpb;        /* pointer to next EDPB */
107         WORD free_cluster;      /* cluster to start search for free space on write, typically
108                                    the last cluster allocated */
109         WORD clusters_free;     /* number of free clusters on drive or FFFF = unknown */
110         WORD clusters_free_hi;  /* hiword of clusters_free */
111         WORD mirroring_flags;   /* mirroring flags: bit 7 set = do not mirror active FAT */
112                                 /* bits 0-3 = 0-based number of the active FAT */
113         WORD info_sector;       /* sector number of file system info sector, or FFFF for none */
114         WORD spare_boot_sector; /* sector number of backup boot sector, or FFFF for none */
115         DWORD first_cluster;    /* sector number of the first cluster */
116         DWORD max_cluster;      /* sector number of the last cluster */
117         DWORD fat_clusters;     /* number of clusters occupied by FAT */
118         DWORD root_cluster;     /* cluster number of start of root directory */
119         DWORD free_cluster2;    /* same as free_cluster: cluster at which to start
120                                    search for free space when writing */
121
122 };
123
124 DWORD dpbsegptr;
125
126 struct DosHeap {
127         BYTE mediaID;
128         BYTE biosdate[8];
129         struct DPB dpb;
130 };
131 static struct DosHeap *heap;
132 static WORD DosHeapHandle;
133
134 extern char TempDirectory[];
135
136 static BOOL INT21_CreateHeap(void)
137 {
138     if (!(DosHeapHandle = GlobalAlloc16(GMEM_FIXED,sizeof(struct DosHeap))))
139     {
140         WARN("Out of memory\n");
141         return FALSE;
142     }
143     heap = (struct DosHeap *) GlobalLock16(DosHeapHandle);
144     dpbsegptr = MAKESEGPTR(DosHeapHandle,(int)&heap->dpb-(int)heap);
145     strcpy(heap->biosdate, "01/01/80");
146     return TRUE;
147 }
148
149 static BYTE *GetCurrentDTA( CONTEXT86 *context )
150 {
151     TDB *pTask = TASK_GetCurrent();
152
153     /* FIXME: This assumes DTA was set correctly! */
154     return (BYTE *)CTX_SEG_OFF_TO_LIN( context, SELECTOROF(pTask->dta),
155                                                 (DWORD)OFFSETOF(pTask->dta) );
156 }
157
158
159 void CreateBPB(int drive, BYTE *data, BOOL16 limited)
160 /* limited == TRUE is used with INT 0x21/0x440d */
161 {
162         if (drive > 1) {
163                 setword(data, 512);
164                 data[2] = 2;
165                 setword(&data[3], 0);
166                 data[5] = 2;
167                 setword(&data[6], 240);
168                 setword(&data[8], 64000);
169                 data[0x0a] = 0xf8;
170                 setword(&data[0x0b], 40);
171                 setword(&data[0x0d], 56);
172                 setword(&data[0x0f], 2);
173                 setword(&data[0x11], 0);
174                 if (!limited) {
175                     setword(&data[0x1f], 800);
176                     data[0x21] = 5;
177                     setword(&data[0x22], 1);
178                 }
179         } else { /* 1.44mb */
180                 setword(data, 512);
181                 data[2] = 2;
182                 setword(&data[3], 0);
183                 data[5] = 2;
184                 setword(&data[6], 240);
185                 setword(&data[8], 2880);
186                 data[0x0a] = 0xf8;
187                 setword(&data[0x0b], 6);
188                 setword(&data[0x0d], 18);
189                 setword(&data[0x0f], 2);
190                 setword(&data[0x11], 0);
191                 if (!limited) {
192                     setword(&data[0x1f], 80);
193                     data[0x21] = 7;
194                     setword(&data[0x22], 2);
195                 }
196         }
197 }
198
199 static int INT21_GetFreeDiskSpace( CONTEXT86 *context )
200 {
201     DWORD cluster_sectors, sector_bytes, free_clusters, total_clusters;
202     char root[] = "A:\\";
203
204     *root += DOS_GET_DRIVE( DL_reg(context) );
205     if (!GetDiskFreeSpaceA( root, &cluster_sectors, &sector_bytes,
206                               &free_clusters, &total_clusters )) return 0;
207     SET_AX( context, cluster_sectors );
208     SET_BX( context, free_clusters );
209     SET_CX( context, sector_bytes );
210     SET_DX( context, total_clusters );
211     return 1;
212 }
213
214 static int INT21_GetDriveAllocInfo( CONTEXT86 *context )
215 {
216     if (!INT21_GetFreeDiskSpace( context )) return 0;
217     if (!heap && !INT21_CreateHeap()) return 0;
218     heap->mediaID = 0xf0;
219     context->SegDs = DosHeapHandle;
220     SET_BX( context, (int)&heap->mediaID - (int)heap );
221     return 1;
222 }
223
224 static int FillInDrivePB( int drive )
225 {
226         if(!DRIVE_IsValid(drive))
227         {
228             SetLastError( ERROR_INVALID_DRIVE );
229                         return 0;
230         }
231         else if (heap || INT21_CreateHeap())
232         {
233                 /* FIXME: I have no idea what a lot of this information should
234                  * say or whether it even really matters since we're not allowing
235                  * direct block access.  However, some programs seem to depend on
236                  * getting at least _something_ back from here.  The 'next' pointer
237                  * does worry me, though.  Should we have a complete table of
238                  * separate DPBs per drive?  Probably, but I'm lazy. :-)  -CH
239                  */
240                 heap->dpb.drive_num = heap->dpb.unit_num = drive; /*The same?*/
241                 heap->dpb.sector_size = 512;
242                 heap->dpb.high_sector = 1;
243                 heap->dpb.shift = drive < 2 ? 0 : 6; /*6 for HD, 0 for floppy*/
244                 heap->dpb.reserved = 0;
245                 heap->dpb.num_FAT = 1;
246                 heap->dpb.dir_entries = 2;
247                 heap->dpb.first_data = 2;
248                 heap->dpb.high_cluster = 64000;
249                 heap->dpb.sectors_in_FAT = 1;
250                 heap->dpb.start_dir = 1;
251                 heap->dpb.driver_head = 0;
252                 heap->dpb.media_ID = (drive > 1) ? 0xF8 : 0xF0;
253                 heap->dpb.access_flag = 0;
254                 heap->dpb.next = 0;
255                 heap->dpb.free_search = 0;
256                 heap->dpb.free_clusters = 0xFFFF;    /* unknown */
257                                 return 1;
258                 }
259
260                 return 0;
261 }
262
263 static void GetDrivePB( CONTEXT86 *context, int drive )
264 {
265         if (FillInDrivePB( drive ))
266         {
267                 SET_AL( context, 0x00 );
268                 context->SegDs = SELECTOROF(dpbsegptr);
269                 SET_BX( context, OFFSETOF(dpbsegptr) );
270         }
271         else
272         {
273         SET_AX( context, 0x00ff );
274         }
275 }
276
277
278 static BOOL ioctlGenericBlkDevReq( CONTEXT86 *context )
279 {
280         BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
281         int drive = DOS_GET_DRIVE( BL_reg(context) );
282
283         if (!DRIVE_IsValid(drive))
284         {
285             SetLastError( ERROR_FILE_NOT_FOUND );
286             return TRUE;
287         }
288
289         if (CH_reg(context) != 0x08)
290         {
291             INT_BARF( context, 0x21 );
292             return FALSE;
293         }
294
295         switch (CL_reg(context))
296         {
297                 case 0x60: /* get device parameters */
298                            /* used by w4wgrp's winfile */
299                         memset(dataptr, 0, 0x20); /* DOS 6.22 uses 0x20 bytes */
300                         dataptr[0] = 0x04;
301                         dataptr[6] = 0; /* media type */
302                         if (drive > 1)
303                         {
304                                 dataptr[1] = 0x05; /* fixed disk */
305                                 setword(&dataptr[2], 0x01); /* non removable */
306                                 setword(&dataptr[4], 0x300); /* # of cylinders */
307                         }
308                         else
309                         {
310                                 dataptr[1] = 0x07; /* block dev, floppy */
311                                 setword(&dataptr[2], 0x02); /* removable */
312                                 setword(&dataptr[4], 80); /* # of cylinders */
313                         }
314                         CreateBPB(drive, &dataptr[7], TRUE);
315                         RESET_CFLAG(context);
316                         break;
317
318                 case 0x66:/*  get disk serial number */
319                         {
320                                 char    label[12],fsname[9],path[4];
321                                 DWORD   serial;
322
323                                 strcpy(path,"x:\\");path[0]=drive+'A';
324                                 GetVolumeInformationA(
325                                         path,label,12,&serial,NULL,NULL,fsname,9
326                                 );
327                                 *(WORD*)dataptr         = 0;
328                                 memcpy(dataptr+2,&serial,4);
329                                 memcpy(dataptr+6,label  ,11);
330                                 memcpy(dataptr+17,fsname,8);
331                         }
332                         break;
333
334                 case 0x6f:
335                         memset(dataptr+1, '\0', dataptr[0]-1);
336                         dataptr[1] = dataptr[0];
337                         dataptr[2] = 0x07; /* protected mode driver; no eject; no notification */
338                         dataptr[3] = 0xFF; /* no physical drive */
339                         break;
340
341                 case 0x72:
342                         /* Trail on error implementation */
343                         SET_AX( context, GetDriveType16(BL_reg(context)) == DRIVE_UNKNOWN ? 0x0f : 0x01 );
344                         SET_CFLAG(context);     /* Seems to be set all the time */
345                         break;
346
347                 default:
348                         INT_BARF( context, 0x21 );
349         }
350         return FALSE;
351 }
352
353 static void INT21_ParseFileNameIntoFCB( CONTEXT86 *context )
354 {
355     char *filename =
356         CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi );
357     char *fcb =
358         CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi );
359     char *s;
360     WCHAR *buffer;
361     WCHAR fcbW[12];
362     INT buffer_len, len;
363
364     SET_AL( context, 0xff ); /* failed */
365
366     TRACE("filename: '%s'\n", filename);
367
368     s = filename;
369     len = 0;
370     while (*s)
371     {
372         if ((*s != ' ') && (*s != '\r') && (*s != '\n'))
373         {
374             s++;
375             len++;
376         }
377         else
378             break;
379     }
380
381     buffer_len = MultiByteToWideChar(CP_OEMCP, 0, filename, len, NULL, 0);
382     buffer = HeapAlloc( GetProcessHeap(), 0, (buffer_len + 1) * sizeof(WCHAR));
383     len = MultiByteToWideChar(CP_OEMCP, 0, filename, len, buffer, buffer_len);
384     buffer[len] = 0;
385     DOSFS_ToDosFCBFormat(buffer, fcbW);
386     HeapFree(GetProcessHeap(), 0, buffer);
387     WideCharToMultiByte(CP_OEMCP, 0, fcbW, 12, fcb + 1, 12, NULL, NULL);
388     *fcb = 0;
389     TRACE("FCB: '%s'\n", fcb + 1);
390
391     SET_AL( context, ((strchr(filename, '*')) || (strchr(filename, '$'))) != 0 );
392
393     /* point DS:SI to first unparsed character */
394     SET_SI( context, context->Esi + (int)s - (int)filename );
395 }
396
397
398 /* Many calls translate a drive argument like this:
399    drive number (00h = default, 01h = A:, etc)
400    */
401 static char drivestring[]="default";
402
403 char *INT21_DriveName(int drive)
404 {
405
406     if(drive >0)
407       {
408         drivestring[0]= (unsigned char)drive + '@';
409         drivestring[1]=':';
410         drivestring[2]=0;
411       }
412     return drivestring;
413 }
414 static BOOL INT21_CreateFile( CONTEXT86 *context )
415 {
416     SET_AX( context, _lcreat16( CTX_SEG_OFF_TO_LIN(context, context->SegDs,
417                                                    context->Edx ), CX_reg(context) ) );
418     return (AX_reg(context) == (WORD)HFILE_ERROR16);
419 }
420
421 static HFILE16 _lcreat16_uniq( LPCSTR path, INT attr )
422 {
423     /* Mask off all flags not explicitly allowed by the doc */
424     attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
425     return Win32HandleToDosFileHandle( CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
426                                              FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
427                                              CREATE_NEW, attr, 0 ));
428 }
429
430 static void OpenExistingFile( CONTEXT86 *context )
431 {
432     SET_AX( context, _lopen16( CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx),
433                                AL_reg(context) ));
434     if (AX_reg(context) == (WORD)HFILE_ERROR16)
435     {
436         SET_AX( context, GetLastError() );
437         SET_CFLAG(context);
438     }
439 }
440
441 static BOOL INT21_ExtendedOpenCreateFile(CONTEXT86 *context )
442 {
443   BOOL bExtendedError = FALSE;
444   BYTE action = DL_reg(context);
445
446   /* Shuffle arguments to call OpenExistingFile */
447   SET_AL( context, BL_reg(context) );
448   SET_DX( context, SI_reg(context) );
449   /* BX,CX and DX should be preserved */
450   OpenExistingFile(context);
451
452   if ((context->EFlags & 0x0001) == 0) /* File exists */
453   {
454       UINT16    uReturnCX = 0;
455
456       /* Now decide what do do */
457
458       if ((action & 0x07) == 0)
459       {
460           _lclose16( AX_reg(context) );
461           SET_AX( context, 0x0050 );    /*File exists*/
462           SET_CFLAG(context);
463           WARN("extended open/create: failed because file exists \n");
464       }
465       else if ((action & 0x07) == 2)
466       {
467         /* Truncate it, but first check if opened for write */
468         if ((BL_reg(context) & 0x0007)== 0)
469         {
470             _lclose16( AX_reg(context) );
471             WARN("extended open/create: failed, trunc on ro file\n");
472             SET_AX( context, 0x000C );  /*Access code invalid*/
473             SET_CFLAG(context);
474         }
475         else
476         {
477                 TRACE("extended open/create: Closing before truncate\n");
478                 if (_lclose16( AX_reg(context) ))
479                 {
480                    WARN("extended open/create: close before trunc failed\n");
481                    SET_AX( context, 0x0019 );   /*Seek Error*/
482                    SET_CX( context, 0 );
483                    SET_CFLAG(context);
484                 }
485                 /* Shuffle arguments to call CreateFile */
486
487                 TRACE("extended open/create: Truncating\n");
488                 SET_AL( context, BL_reg(context) );
489                 /* CX is still the same */
490                 SET_DX( context, SI_reg(context) );
491                 bExtendedError = INT21_CreateFile(context);
492
493                 if (context->EFlags & 0x0001)   /*no file open, flags set */
494                 {
495                     WARN("extended open/create: trunc failed\n");
496                     return bExtendedError;
497                 }
498                 uReturnCX = 0x3;
499         }
500       }
501       else uReturnCX = 0x1;
502
503       SET_CX( context, uReturnCX );
504   }
505   else /* file does not exist */
506   {
507       RESET_CFLAG(context); /* was set by OpenExistingFile(context) */
508       if ((action & 0xF0)== 0)
509       {
510         SET_CX( context, 0 );
511         SET_CFLAG(context);
512         WARN("extended open/create: failed, file dosen't exist\n");
513       }
514       else
515       {
516         /* Shuffle arguments to call CreateFile */
517         TRACE("extended open/create: Creating\n");
518         SET_AL( context, BL_reg(context) );
519         /* CX should still be the same */
520         SET_DX( context, SI_reg(context) );
521         bExtendedError = INT21_CreateFile(context);
522         if (context->EFlags & 0x0001)  /*no file open, flags set */
523         {
524             WARN("extended open/create: create failed\n");
525             return bExtendedError;
526         }
527         SET_CX( context, 2 );
528       }
529   }
530
531   return bExtendedError;
532 }
533
534
535 static int INT21_FindFirst( CONTEXT86 *context )
536 {
537     char *p;
538     const char *path;
539     DOS_FULL_NAME full_name;
540     FINDFILE_DTA *dta = (FINDFILE_DTA *)GetCurrentDTA(context);
541     WCHAR pathW[MAX_PATH];
542     WCHAR maskW[12];
543
544     path = (const char *)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
545     MultiByteToWideChar(CP_OEMCP, 0, path, -1, pathW, MAX_PATH);
546
547     dta->unixPath = NULL;
548     if (!DOSFS_GetFullName( pathW, FALSE, &full_name ))
549     {
550         SET_AX( context, GetLastError() );
551         SET_CFLAG(context);
552         return 0;
553     }
554     dta->unixPath = HeapAlloc( GetProcessHeap(), 0, strlen(full_name.long_name)+1 );
555     strcpy( dta->unixPath, full_name.long_name );
556     p = strrchr( dta->unixPath, '/' );
557     *p = '\0';
558
559     MultiByteToWideChar(CP_OEMCP, 0, p + 1, -1, pathW, MAX_PATH);
560
561     /* Note: terminating NULL in dta->mask overwrites dta->search_attr
562      *       (doesn't matter as it is set below anyway)
563      */
564     if (!DOSFS_ToDosFCBFormat( pathW, maskW ))
565     {
566         HeapFree( GetProcessHeap(), 0, dta->unixPath );
567         dta->unixPath = NULL;
568         SetLastError( ERROR_FILE_NOT_FOUND );
569         SET_AX( context, ERROR_FILE_NOT_FOUND );
570         SET_CFLAG(context);
571         return 0;
572     }
573     WideCharToMultiByte(CP_OEMCP, 0, maskW, 12, dta->mask, sizeof(dta->mask), NULL, NULL);
574     dta->drive = (path[0] && (path[1] == ':')) ? toupper(path[0]) - 'A'
575                                                : DRIVE_GetCurrentDrive();
576     dta->count = 0;
577     dta->search_attr = CL_reg(context);
578     return 1;
579 }
580
581
582 static int INT21_FindNext( CONTEXT86 *context )
583 {
584     FINDFILE_DTA *dta = (FINDFILE_DTA *)GetCurrentDTA(context);
585     WIN32_FIND_DATAA entry;
586     int count;
587
588     if (!dta->unixPath) return 0;
589     if (!(count = DOSFS_FindNext( dta->unixPath, dta->mask, NULL, dta->drive,
590                                   dta->search_attr, dta->count, &entry )))
591     {
592         HeapFree( GetProcessHeap(), 0, dta->unixPath );
593         dta->unixPath = NULL;
594         return 0;
595     }
596     if ((int)dta->count + count > 0xffff)
597     {
598         WARN("Too many directory entries in %s\n", dta->unixPath );
599         HeapFree( GetProcessHeap(), 0, dta->unixPath );
600         dta->unixPath = NULL;
601         return 0;
602     }
603     dta->count += count;
604     dta->fileattr = entry.dwFileAttributes;
605     dta->filesize = entry.nFileSizeLow;
606     FileTimeToDosDateTime( &entry.ftLastWriteTime,
607                            &dta->filedate, &dta->filetime );
608     strcpy( dta->filename, entry.cAlternateFileName );
609     if (!memchr(dta->mask,'?',11)) {
610         /* wildcardless search, release resources in case no findnext will
611          * be issued, and as a workaround in case file creation messes up
612          * findnext, as sometimes happens with pkunzip */
613         HeapFree( GetProcessHeap(), 0, dta->unixPath );
614         dta->unixPath = NULL;
615     }
616     return 1;
617 }
618
619
620 static BOOL INT21_CreateTempFile( CONTEXT86 *context )
621 {
622     static int counter = 0;
623     char *name = CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx );
624     char *p = name + strlen(name);
625
626     /* despite what Ralf Brown says, some programs seem to call without
627      * ending backslash (DOS accepts that, so we accept it too) */
628     if ((p == name) || (p[-1] != '\\')) *p++ = '\\';
629
630     for (;;)
631     {
632         sprintf( p, "wine%04x.%03d", (int)getpid(), counter );
633         counter = (counter + 1) % 1000;
634
635         SET_AX( context, _lcreat16_uniq( name, 0 ) );
636         if (AX_reg(context) != HFILE_ERROR16)
637         {
638             TRACE("created %s\n", name );
639             return TRUE;
640         }
641         if (GetLastError() != ERROR_FILE_EXISTS) return FALSE;
642     }
643 }
644
645
646 static int INT21_GetDiskSerialNumber( CONTEXT86 *context )
647 {
648     BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
649     int drive = DOS_GET_DRIVE( BL_reg(context) );
650
651     if (!DRIVE_IsValid(drive))
652     {
653         SetLastError( ERROR_INVALID_DRIVE );
654         return 0;
655     }
656
657     *(WORD *)dataptr = 0;
658     *(DWORD *)(dataptr + 2) = DRIVE_GetSerialNumber( drive );
659     memcpy( dataptr + 6, DRIVE_GetLabel( drive ), 11 );
660     strncpy(dataptr + 0x11, "FAT16   ", 8);
661     return 1;
662 }
663
664
665 static int INT21_SetDiskSerialNumber( CONTEXT86 *context )
666 {
667     BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
668     int drive = DOS_GET_DRIVE( BL_reg(context) );
669
670     if (!DRIVE_IsValid(drive))
671     {
672         SetLastError( ERROR_INVALID_DRIVE );
673         return 0;
674     }
675
676     DRIVE_SetSerialNumber( drive, *(DWORD *)(dataptr + 2) );
677     return 1;
678 }
679
680
681 /* microsoft's programmers should be shot for using CP/M style int21
682    calls in Windows for Workgroup's winfile.exe */
683
684 static int INT21_FindFirstFCB( CONTEXT86 *context )
685 {
686     BYTE *fcb = (BYTE *)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
687     FINDFILE_FCB *pFCB;
688     LPCSTR root, cwd;
689     int drive;
690
691     if (*fcb == 0xff) pFCB = (FINDFILE_FCB *)(fcb + 7);
692     else pFCB = (FINDFILE_FCB *)fcb;
693     drive = DOS_GET_DRIVE( pFCB->drive );
694     if (!DRIVE_IsValid( drive )) return 0;
695     root = DRIVE_GetRoot( drive );
696     cwd  = DRIVE_GetUnixCwd( drive );
697     pFCB->unixPath = HeapAlloc( GetProcessHeap(), 0,
698                                 strlen(root)+strlen(cwd)+2 );
699     if (!pFCB->unixPath) return 0;
700     strcpy( pFCB->unixPath, root );
701     strcat( pFCB->unixPath, "/" );
702     strcat( pFCB->unixPath, cwd );
703     pFCB->count = 0;
704     return 1;
705 }
706
707
708 static int INT21_FindNextFCB( CONTEXT86 *context )
709 {
710     BYTE *fcb = (BYTE *)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
711     FINDFILE_FCB *pFCB;
712     DOS_DIRENTRY_LAYOUT *pResult = (DOS_DIRENTRY_LAYOUT *)GetCurrentDTA(context);
713     WIN32_FIND_DATAA entry;
714     BYTE attr;
715     int count;
716
717     if (*fcb == 0xff) /* extended FCB ? */
718     {
719         attr = fcb[6];
720         pFCB = (FINDFILE_FCB *)(fcb + 7);
721     }
722     else
723     {
724         attr = 0;
725         pFCB = (FINDFILE_FCB *)fcb;
726     }
727
728     if (!pFCB->unixPath) return 0;
729     if (!(count = DOSFS_FindNext( pFCB->unixPath, pFCB->filename, NULL,
730                                   DOS_GET_DRIVE( pFCB->drive ), attr,
731                                   pFCB->count, &entry )))
732     {
733         HeapFree( GetProcessHeap(), 0, pFCB->unixPath );
734         pFCB->unixPath = NULL;
735         return 0;
736     }
737     pFCB->count += count;
738
739     if (*fcb == 0xff) { /* place extended FCB header before pResult if called with extended FCB */
740         *(BYTE *)pResult = 0xff;
741         (BYTE *)pResult +=6; /* leave reserved field behind */
742         *(BYTE *)pResult = entry.dwFileAttributes;
743         ((BYTE *)pResult)++;
744     }
745     *(BYTE *)pResult = DOS_GET_DRIVE( pFCB->drive ); /* DOS_DIRENTRY_LAYOUT after current drive number */
746     ((BYTE *)pResult)++;
747     pResult->fileattr = entry.dwFileAttributes;
748     pResult->cluster  = 0;  /* what else? */
749     pResult->filesize = entry.nFileSizeLow;
750     memset( pResult->reserved, 0, sizeof(pResult->reserved) );
751     FileTimeToDosDateTime( &entry.ftLastWriteTime,
752                            &pResult->filedate, &pResult->filetime );
753
754     /* Convert file name to FCB format */
755
756     memset( pResult->filename, ' ', sizeof(pResult->filename) );
757     if (!strcmp( entry.cAlternateFileName, "." )) pResult->filename[0] = '.';
758     else if (!strcmp( entry.cAlternateFileName, ".." ))
759         pResult->filename[0] = pResult->filename[1] = '.';
760     else
761     {
762         char *p = strrchr( entry.cAlternateFileName, '.' );
763         if (p && p[1] && (p != entry.cAlternateFileName))
764         {
765             memcpy( pResult->filename, entry.cAlternateFileName,
766                     min( (p - entry.cAlternateFileName), 8 ) );
767             memcpy( pResult->filename + 8, p + 1, min( strlen(p), 3 ) );
768         }
769         else
770             memcpy( pResult->filename, entry.cAlternateFileName,
771                     min( strlen(entry.cAlternateFileName), 8 ) );
772     }
773     return 1;
774 }
775
776
777 static BOOL
778 INT21_networkfunc (CONTEXT86 *context)
779 {
780      switch (AL_reg(context)) {
781      case 0x00: /* Get machine name. */
782      {
783           char *dst = CTX_SEG_OFF_TO_LIN (context,context->SegDs,context->Edx);
784           TRACE("getting machine name to %p\n", dst);
785           if (gethostname (dst, 15))
786           {
787                WARN("failed!\n");
788                SetLastError( ER_NoNetwork );
789                return TRUE;
790           } else {
791                int len = strlen (dst);
792                while (len < 15)
793                     dst[len++] = ' ';
794                dst[15] = 0;
795                SET_CH( context, 1 ); /* Valid */
796                SET_CL( context, 1 ); /* NETbios number??? */
797                TRACE("returning %s\n", debugstr_an (dst, 16));
798                return FALSE;
799           }
800      }
801
802      default:
803           SetLastError( ER_NoNetwork );
804           return TRUE;
805      }
806 }
807
808
809 /***********************************************************************
810  *           INT_Int21Handler
811  */
812 void WINAPI INT_Int21Handler( CONTEXT86 *context )
813 {
814     BOOL        bSetDOSExtendedError = FALSE;
815
816     switch(AH_reg(context))
817     {
818     case 0x11: /* FIND FIRST MATCHING FILE USING FCB */
819         TRACE("FIND FIRST MATCHING FILE USING FCB %p\n",
820               CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx));
821         if (!INT21_FindFirstFCB(context))
822         {
823             SET_AL( context, 0xff );
824             break;
825         }
826         /* else fall through */
827
828     case 0x12: /* FIND NEXT MATCHING FILE USING FCB */
829         SET_AL( context, INT21_FindNextFCB(context) ? 0x00 : 0xff );
830         break;
831
832     case 0x1b: /* GET ALLOCATION INFORMATION FOR DEFAULT DRIVE */
833         SET_DL( context, 0 );
834         if (!INT21_GetDriveAllocInfo(context)) SET_AX( context, 0xffff );
835         break;
836
837     case 0x1c: /* GET ALLOCATION INFORMATION FOR SPECIFIC DRIVE */
838         if (!INT21_GetDriveAllocInfo(context)) SET_AX( context, 0xffff );
839         break;
840
841     case 0x1f: /* GET DRIVE PARAMETER BLOCK FOR DEFAULT DRIVE */
842         GetDrivePB(context, DRIVE_GetCurrentDrive());
843         break;
844
845     case 0x29: /* PARSE FILENAME INTO FCB */
846         INT21_ParseFileNameIntoFCB(context);
847         break;
848
849     case 0x32: /* GET DOS DRIVE PARAMETER BLOCK FOR SPECIFIC DRIVE */
850         TRACE("GET DOS DRIVE PARAMETER BLOCK FOR DRIVE %s\n",
851               INT21_DriveName( DL_reg(context)));
852         GetDrivePB(context, DOS_GET_DRIVE( DL_reg(context) ) );
853         break;
854
855     case 0x36: /* GET FREE DISK SPACE */
856         TRACE("GET FREE DISK SPACE FOR DRIVE %s\n",
857               INT21_DriveName( DL_reg(context)));
858         if (!INT21_GetFreeDiskSpace(context)) SET_AX( context, 0xffff );
859         break;
860
861     case 0x3c: /* "CREAT" - CREATE OR TRUNCATE FILE */
862         TRACE("CREAT flag 0x%02x %s\n",CX_reg(context),
863               (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx));
864         bSetDOSExtendedError = INT21_CreateFile( context );
865         break;
866
867     case 0x3d: /* "OPEN" - OPEN EXISTING FILE */
868         TRACE("OPEN mode 0x%02x %s\n",AL_reg(context),
869               (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx));
870         OpenExistingFile(context);
871         break;
872
873     case 0x44: /* IOCTL */
874         switch (AL_reg(context))
875         {
876         case 0x0d:
877             TRACE("IOCTL - GENERIC BLOCK DEVICE REQUEST %s\n",
878                   INT21_DriveName( BL_reg(context)));
879             bSetDOSExtendedError = ioctlGenericBlkDevReq(context);
880             break;
881
882         case 0x0F:   /* Set logical drive mapping */
883             {
884             int drive;
885             TRACE("IOCTL - SET LOGICAL DRIVE MAP for drive %s\n",
886                   INT21_DriveName( BL_reg(context)));
887             drive = DOS_GET_DRIVE ( BL_reg(context) );
888             if ( ! DRIVE_SetLogicalMapping ( drive, drive+1 ) )
889             {
890                 SET_CFLAG(context);
891                 SET_AX( context, 0x000F );  /* invalid drive */
892             }
893             break;
894             }
895         }
896         break;
897
898     case 0x4e: /* "FINDFIRST" - FIND FIRST MATCHING FILE */
899         TRACE("FINDFIRST mask 0x%04x spec %s\n",CX_reg(context),
900               (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx));
901         if (!INT21_FindFirst(context)) break;
902         /* fall through */
903
904     case 0x4f: /* "FINDNEXT" - FIND NEXT MATCHING FILE */
905         TRACE("FINDNEXT\n");
906         if (!INT21_FindNext(context))
907         {
908             SetLastError( ERROR_NO_MORE_FILES );
909             SET_AX( context, ERROR_NO_MORE_FILES );
910             SET_CFLAG(context);
911         }
912         else SET_AX( context, 0 );  /* OK */
913         break;
914
915     case 0x5a: /* CREATE TEMPORARY FILE */
916         TRACE("CREATE TEMPORARY FILE\n");
917         bSetDOSExtendedError = !INT21_CreateTempFile(context);
918         break;
919
920     case 0x5b: /* CREATE NEW FILE */
921         TRACE("CREATE NEW FILE 0x%02x for %s\n", CX_reg(context),
922               (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx));
923         SET_AX( context,
924                _lcreat16_uniq( CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx),
925                                CX_reg(context) ));
926         bSetDOSExtendedError = (AX_reg(context) != 0);
927         break;
928
929     case 0x5e:
930         bSetDOSExtendedError = INT21_networkfunc (context);
931         break;
932
933     case 0x5f: /* NETWORK */
934         switch (AL_reg(context))
935         {
936         case 0x07: /* ENABLE DRIVE */
937             TRACE("ENABLE DRIVE %c:\n",(DL_reg(context)+'A'));
938             if (!DRIVE_Enable( DL_reg(context) ))
939             {
940                 SetLastError( ERROR_INVALID_DRIVE );
941                 bSetDOSExtendedError = TRUE;
942             }
943             break;
944
945         case 0x08: /* DISABLE DRIVE */
946             TRACE("DISABLE DRIVE %c:\n",(DL_reg(context)+'A'));
947             if (!DRIVE_Disable( DL_reg(context) ))
948             {
949                 SetLastError( ERROR_INVALID_DRIVE );
950                 bSetDOSExtendedError = TRUE;
951             }
952             break;
953
954         default:
955             /* network software not installed */
956             TRACE("NETWORK function AX=%04x not implemented\n",AX_reg(context));
957             SetLastError( ER_NoNetwork );
958             bSetDOSExtendedError = TRUE;
959             break;
960         }
961         break;
962
963     case 0x60: /* "TRUENAME" - CANONICALIZE FILENAME OR PATH */
964         TRACE("TRUENAME %s\n",
965               (LPCSTR)CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Esi));
966         {
967             if (!GetFullPathNameA( CTX_SEG_OFF_TO_LIN(context, context->SegDs,
968                                                         context->Esi), 128,
969                                      CTX_SEG_OFF_TO_LIN(context, context->SegEs,
970                                                         context->Edi),NULL))
971                 bSetDOSExtendedError = TRUE;
972             else SET_AX( context, 0 );
973         }
974         break;
975
976     case 0x69: /* DISK SERIAL NUMBER */
977         switch (AL_reg(context))
978         {
979         case 0x00:
980             TRACE("GET DISK SERIAL NUMBER for drive %s\n",
981                   INT21_DriveName(BL_reg(context)));
982             if (!INT21_GetDiskSerialNumber(context)) bSetDOSExtendedError = TRUE;
983             else SET_AX( context, 0 );
984             break;
985
986         case 0x01:
987             TRACE("SET DISK SERIAL NUMBER for drive %s\n",
988                   INT21_DriveName(BL_reg(context)));
989             if (!INT21_SetDiskSerialNumber(context)) bSetDOSExtendedError = TRUE;
990             else SET_AX( context, 1 );
991             break;
992         }
993         break;
994
995     case 0x6C: /* Extended Open/Create*/
996         TRACE("EXTENDED OPEN/CREATE %s\n",
997               (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edi));
998         bSetDOSExtendedError = INT21_ExtendedOpenCreateFile(context);
999         break;
1000
1001     case 0x71: /* MS-DOS 7 (Windows95) - LONG FILENAME FUNCTIONS */
1002         switch(AL_reg(context))
1003         {
1004         case 0x4e:  /* Find first file */
1005             TRACE(" LONG FILENAME - FIND FIRST MATCHING FILE for %s\n",
1006                   (LPCSTR)CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx));
1007             /* FIXME: use attributes in CX */
1008             SET_AX( context, FindFirstFile16(
1009                         CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx),
1010                         (WIN32_FIND_DATAA *)CTX_SEG_OFF_TO_LIN(context, context->SegEs,
1011                                                                context->Edi)));
1012             if (AX_reg(context) == INVALID_HANDLE_VALUE16)
1013                 bSetDOSExtendedError = TRUE;
1014             break;
1015         case 0x4f:  /* Find next file */
1016             TRACE("LONG FILENAME - FIND NEXT MATCHING FILE for handle %d\n",
1017                   BX_reg(context));
1018             if (!FindNextFile16( BX_reg(context),
1019                     (WIN32_FIND_DATAA *)CTX_SEG_OFF_TO_LIN(context, context->SegEs,
1020                                                              context->Edi)))
1021                 bSetDOSExtendedError = TRUE;
1022             break;
1023         case 0xa0:
1024             {
1025                 LPCSTR driveroot = (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs,context->Edx);
1026                 LPSTR buffer = (LPSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegEs,context->Edi);
1027                 DWORD filename_len, flags;
1028
1029                 TRACE("LONG FILENAME - GET VOLUME INFORMATION for drive having root dir '%s'.\n", driveroot);
1030                 SET_AX( context, 0 );
1031                 if (!GetVolumeInformationA( driveroot, NULL, 0, NULL, &filename_len,
1032                                             &flags, buffer, 8 ))
1033                 {
1034                     INT_BARF( context, 0x21 );
1035                     SET_CFLAG(context);
1036                     break;
1037                 }
1038                 SET_BX( context, flags | 0x4000 ); /* support for LFN functions */
1039                 SET_CX( context, filename_len );
1040                 SET_DX( context, MAX_PATH ); /* FIXME: which len if DRIVE_SHORT_NAMES ? */
1041             }
1042             break;
1043         case 0xa1:  /* Find close */
1044             TRACE("LONG FILENAME - FINDCLOSE for handle %d\n",
1045                   BX_reg(context));
1046             bSetDOSExtendedError = (!FindClose16( BX_reg(context) ));
1047             break;
1048         case 0x60:
1049           switch(CL_reg(context))
1050           {
1051             case 0x01:  /* Get short filename or path */
1052               if (!GetShortPathNameA
1053                   ( CTX_SEG_OFF_TO_LIN(context, context->SegDs,
1054                                        context->Esi),
1055                     CTX_SEG_OFF_TO_LIN(context, context->SegEs,
1056                                        context->Edi), 67))
1057                 bSetDOSExtendedError = TRUE;
1058               else SET_AX( context, 0 );
1059               break;
1060             case 0x02:  /* Get canonical long filename or path */
1061               if (!GetFullPathNameA
1062                   ( CTX_SEG_OFF_TO_LIN(context, context->SegDs,
1063                                        context->Esi), 128,
1064                     CTX_SEG_OFF_TO_LIN(context, context->SegEs,
1065                                        context->Edi),NULL))
1066                 bSetDOSExtendedError = TRUE;
1067               else SET_AX( context, 0 );
1068               break;
1069             default:
1070               FIXME("Unimplemented long file name function:\n");
1071               INT_BARF( context, 0x21 );
1072               SET_CFLAG(context);
1073               SET_AL( context, 0 );
1074               break;
1075           }
1076           break;
1077         case 0x6c:  /* Create or open file */
1078             TRACE("LONG FILENAME - CREATE OR OPEN FILE %s\n",
1079                  (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Esi));
1080           /* translate Dos 7 action to Dos 6 action */
1081             bSetDOSExtendedError = INT21_ExtendedOpenCreateFile(context);
1082             break;
1083
1084         default:
1085             FIXME("Unimplemented long file name function:\n");
1086             INT_BARF( context, 0x21 );
1087             SET_CFLAG(context);
1088             SET_AL( context, 0 );
1089             break;
1090         }
1091         break;
1092
1093
1094     case 0x73: /* MULTIPLEXED: Win95 OSR2/Win98 FAT32 calls */
1095         TRACE("windows95 function AX %04x\n",
1096                     AX_reg(context));
1097
1098         switch (AL_reg(context))
1099                 {
1100                 case 0x02:      /* Get Extended Drive Parameter Block for specific drive */
1101                                 /* ES:DI points to word with length of data (should be 0x3d) */
1102                         {
1103                                 WORD *buffer;
1104                                 struct EDPB *edpb;
1105                             DWORD cluster_sectors, sector_bytes, free_clusters, total_clusters;
1106                             char root[] = "A:\\";
1107
1108                                 buffer = (WORD *)CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi);
1109
1110                                 TRACE("Get Extended DPB: linear buffer address is %p\n", buffer);
1111
1112                                 /* validate passed-in buffer lengths */
1113                                 if ((*buffer != 0x3d) || (context->Ecx != 0x3f))
1114                                 {
1115                                         WARN("Get Extended DPB: buffer lengths incorrect\n");
1116                                         WARN("CX = %lx, buffer[0] = %x\n", context->Ecx, *buffer);
1117                                         SET_CFLAG(context);
1118                                         SET_AL( context, 0x18 );                /* bad buffer length */
1119                                 }
1120
1121                                 /* buffer checks out */
1122                                 buffer++;               /* skip over length word now */
1123                                 if (FillInDrivePB( DX_reg(context) ) )
1124                                 {
1125                                         edpb = (struct EDPB *)buffer;
1126
1127                                         /* copy down the old-style DPB portion first */
1128                                         memcpy(&edpb->dpb, &heap->dpb, sizeof(struct DPB));
1129
1130                                         /* now fill in the extended entries */
1131                                         edpb->edpb_flags = 0;
1132                                         edpb->next_edpb = 0;
1133                                         edpb->free_cluster = edpb->free_cluster2 = 0;
1134
1135                                         /* determine free disk space */
1136                                     *root += DOS_GET_DRIVE( DX_reg(context) );
1137                                     GetDiskFreeSpaceA( root, &cluster_sectors, &sector_bytes,
1138                               &free_clusters, &total_clusters );
1139
1140                                         edpb->clusters_free = (free_clusters&0xffff);
1141
1142                                         edpb->clusters_free_hi = free_clusters >> 16;
1143                                         edpb->mirroring_flags = 0;
1144                                         edpb->info_sector = 0xffff;
1145                                         edpb->spare_boot_sector = 0xffff;
1146                                         edpb->first_cluster = 0;
1147                                         edpb->max_cluster = total_clusters;
1148                                         edpb->fat_clusters = 32;        /* made-up value */
1149                                         edpb->root_cluster = 0;
1150
1151                                         RESET_CFLAG(context);   /* clear carry */
1152                                         SET_AX( context, 0 );
1153                                 }
1154                                 else
1155                                 {
1156                                     SET_AX( context, 0x00ff );
1157                                     SET_CFLAG(context);
1158                                 }
1159                         }
1160                         break;
1161
1162                 case 0x03:      /* Get Extended free space on drive */
1163                 case 0x04:  /* Set DPB for formatting */
1164                 case 0x05:  /* extended absolute disk read/write */
1165                         FIXME("Unimplemented FAT32 int32 function %04x\n", AX_reg(context));
1166                         SET_CFLAG(context);
1167                         SET_AL( context, 0 );
1168                         break;
1169                 }
1170
1171                 break;
1172
1173     default:
1174         INT_BARF( context, 0x21 );
1175         break;
1176
1177     } /* END OF SWITCH */
1178
1179     if( bSetDOSExtendedError )          /* set general error condition */
1180     {
1181         SET_AX( context, GetLastError() );
1182         SET_CFLAG(context);
1183     }
1184 }