int21.c 171 KB
Newer Older
1 2
/*
 * DOS interrupt 21h handler
3 4 5 6 7 8
 *
 * Copyright 1993, 1994 Erik Bos
 * Copyright 1996 Alexandre Julliard
 * Copyright 1997 Andreas Mohr
 * Copyright 1998 Uwe Bonnes
 * Copyright 1998, 1999 Ove Kaaven
9
 * Copyright 2003 Thomas Mertes
10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
23
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 25 26
 */

#include "config.h"
Steven Edwards's avatar
Steven Edwards committed
27
#include "wine/port.h"
28

29
#include <stdarg.h>
30
#include <stdio.h>
31 32 33
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
34 35 36
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
37

38 39
#include "windef.h"
#include "winbase.h"
40
#include "winreg.h"
41
#include "winternl.h"
42 43
#include "wine/winbase16.h"
#include "dosexe.h"
44
#include "winerror.h"
45
#include "winuser.h"
46
#include "wine/unicode.h"
47
#include "wine/server.h"
48
#include "wine/debug.h"
49
#include "wine/exception.h"
50

51
BOOL    WINAPI VerifyConsoleIoHandle(HANDLE);
52
/*
53 54 55
 * Note:
 * - Most of the file related functions are wrong. NT's kernel32
 *   doesn't maintain a per drive current directory, while DOS does. 
56 57
 *   We should in fact keep track in here of those per drive
 *   directories, and use this info while dealing with partial paths
58 59 60
 *   (drive defined, but only relative paths). This could even be
 *   created as an array of CDS (there should be an entry for that in
 *   the LOL)
61 62
 */

63 64 65 66 67
/*
 * Forward declarations.
 */
static BOOL INT21_RenameFile( CONTEXT86 *context );

68
WINE_DEFAULT_DEBUG_CHANNEL(int21);
69

70

71 72
#include "pshpack1.h"

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
/*
 * Extended Drive Parameter Block.
 * This structure is compatible with standard DOS4+ DPB and 
 * extended DOS7 DPB.
 */
typedef struct _INT21_DPB {
    BYTE   drive;                /* 00 drive number (0=A, ...) */
    BYTE   unit;                 /* 01 unit number within device driver */
    WORD   sector_bytes;         /* 02 bytes per sector */
    BYTE   cluster_sectors;      /* 04 highest sector number within a cluster */
    BYTE   shift;                /* 05 shift count to convert clusters into sectors */
    WORD   num_reserved;         /* 06 reserved sectors at beginning of drive */
    BYTE   num_FAT;              /* 08 number of FATs */
    WORD   num_root_entries;     /* 09 number of root directory entries */
    WORD   first_data_sector;    /* 0b number of first sector containing user data */
    WORD   num_clusters1;        /* 0d highest cluster number (number of data clusters + 1) */
    WORD   sectors_per_FAT;      /* 0f number of sectors per FAT */
    WORD   first_dir_sector;     /* 11 sector number of first directory sector */
    SEGPTR driver_header;        /* 13 address of device driver header */
    BYTE   media_ID;             /* 17 media ID byte */
    BYTE   access_flag;          /* 18 0x00 if disk accessed, 0xff if not */
    SEGPTR next;                 /* 19 pointer to next DPB */
    WORD   search_cluster1;      /* 1d cluster at which to start search for free space */
    WORD   free_clusters_lo;     /* 1f number of free clusters on drive or 0xffff if unknown */
    WORD   free_clusters_hi;     /* 21 hiword of clusters_free */
    WORD   mirroring_flags;      /* 23 active FAT/mirroring flags */
    WORD   info_sector;          /* 25 sector number of file system info sector or 0xffff for none */
    WORD   spare_boot_sector;    /* 27 sector number of backup boot sector or 0xffff for none */
    DWORD  first_cluster_sector; /* 29 sector number of the first cluster */
    DWORD  num_clusters2;        /* 2d maximum cluster number */
    DWORD  fat_clusters;         /* 31 number of clusters occupied by FAT */
    DWORD  root_cluster;         /* 35 cluster number of start of root directory */
    DWORD  search_cluster2;      /* 39 cluster at which to start searching for free space */
} INT21_DPB;


109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
/*
 * Structure for DOS data that can be accessed directly from applications.
 * Real and protected mode pointers will be returned to this structure so
 * the structure must be correctly packed.
 */
typedef struct _INT21_HEAP {
    WORD uppercase_size;             /* Size of the following table in bytes */
    BYTE uppercase_table[128];       /* Uppercase equivalents of chars from 0x80 to 0xff. */

    WORD lowercase_size;             /* Size of the following table in bytes */
    BYTE lowercase_table[256];       /* Lowercase equivalents of chars from 0x00 to 0xff. */

    WORD collating_size;             /* Size of the following table in bytes */
    BYTE collating_table[256];       /* Values used to sort characters from 0x00 to 0xff. */

    WORD filename_size;              /* Size of the following filename data in bytes */
    BYTE filename_reserved1;         /* 0x01 for MS-DOS 3.30-6.00 */
    BYTE filename_lowest;            /* Lowest permissible character value for filename */
    BYTE filename_highest;           /* Highest permissible character value for filename */
    BYTE filename_reserved2;         /* 0x00 for MS-DOS 3.30-6.00 */
    BYTE filename_exclude_first;     /* First illegal character in permissible range */
    BYTE filename_exclude_last;      /* Last illegal character in permissible range */
    BYTE filename_reserved3;         /* 0x02 for MS-DOS 3.30-6.00 */
    BYTE filename_illegal_size;      /* Number of terminators in the following table */
    BYTE filename_illegal_table[16]; /* Characters which terminate a filename */

    WORD dbcs_size;                  /* Number of valid ranges in the following table */
    BYTE dbcs_table[16];             /* Start/end bytes for N ranges and 00/00 as terminator */

138 139 140 141 142
    BYTE      misc_indos;                    /* Interrupt 21 nesting flag */
    WORD      misc_segment;                  /* Real mode segment for INT21_HEAP */
    WORD      misc_selector;                 /* Protected mode selector for INT21_HEAP */
    INT21_DPB misc_dpb_list[MAX_DOS_DRIVES]; /* Drive parameter blocks for all drives */

143 144 145
} INT21_HEAP;


146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
struct FCB {
    BYTE  drive_number;
    CHAR  file_name[8];
    CHAR  file_extension[3];
    WORD  current_block_number;
    WORD  logical_record_size;
    DWORD file_size;
    WORD  date_of_last_write;
    WORD  time_of_last_write;
    BYTE  file_number;
    BYTE  attributes;
    WORD  starting_cluster;
    WORD  sequence_number;
    BYTE  file_attributes;
    BYTE  unused;
    BYTE  record_within_current_block;
    BYTE  random_access_record_number[4];
};


struct XFCB {
    BYTE  xfcb_signature;
    BYTE  reserved[5];
    BYTE  xfcb_file_attribute;
    BYTE  fcb[37];
};

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
/* DTA layout for FindFirst/FindNext */
typedef struct
{
    BYTE   drive;        /* 00 drive letter */
    char   mask[11];     /* 01 search template */
    BYTE   search_attr;  /* 0c search attributes */
    WORD   count;        /* 0d entry count within directory */
    WORD   cluster;      /* 0f cluster of parent directory */
    WCHAR *fullPath;     /* 11 full path (was: reserved) */
    BYTE   fileattr;     /* 15 file attributes */
    WORD   filetime;     /* 16 file time */
    WORD   filedate;     /* 18 file date */
    DWORD  filesize;     /* 1a file size */
    char   filename[13]; /* 1e file name + extension */
} FINDFILE_DTA;

/* FCB layout for FindFirstFCB/FindNextFCB */
typedef struct
{
    BYTE   drive;                /* 00 drive letter */
    char   filename[11];         /* 01 filename 8+3 format */
    int    count;                /* 0c entry count (was: reserved) */
    WCHAR *fullPath;             /* 10 full path (was: reserved) */
} FINDFILE_FCB;

/* DOS directory entry for FindFirstFCB/FindNextFCB */
typedef struct
{
    char   filename[11];         /* 00 filename 8+3 format */
    BYTE   fileattr;             /* 0b file attributes */
    BYTE   reserved[10];         /* 0c reserved */
    WORD   filetime;             /* 16 file time */
    WORD   filedate;             /* 18 file date */
    WORD   cluster;              /* 1a file first cluster */
    DWORD  filesize;             /* 1c file size */
} DOS_DIRENTRY_LAYOUT;

210 211
#include "poppack.h"

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
/* dos file attributes */
#define FA_NORMAL    0x00        /* Normal file, no attributes */
#define FA_RDONLY    0x01        /* Read only attribute */
#define FA_HIDDEN    0x02        /* Hidden file */
#define FA_SYSTEM    0x04        /* System file */
#define FA_LABEL     0x08        /* Volume label */
#define FA_DIRECTORY 0x10        /* Directory */
#define FA_ARCHIVE   0x20        /* Archive */
#define FA_UNUSED    0x40        /* Unused */

/* Error codes */
#define ER_NoNetwork         0x49

/* Error classes */
#define EC_OutOfResource     0x01
#define EC_Temporary         0x02
#define EC_AccessDenied      0x03
#define EC_InternalError     0x04
#define EC_HardwareFailure   0x05
#define EC_SystemFailure     0x06
#define EC_ProgramError      0x07
#define EC_NotFound          0x08
#define EC_MediaError        0x0b
#define EC_Exists            0x0c
#define EC_Unknown           0x0d

/* Suggested actions */
#define SA_Retry             0x01
#define SA_DelayedRetry      0x02
#define SA_Abort             0x04
#define SA_Ignore            0x06
#define SA_Ask4Retry         0x07

/* Error locus */
#define EL_Unknown           0x01
#define EL_Disk              0x02
#define EL_Network           0x03
#define EL_Serial            0x04
#define EL_Memory            0x05

252 253 254 255 256 257 258 259 260 261 262 263 264
/* BIOS Keyboard Scancodes */
#define KEY_LEFT        0x4B
#define KEY_RIGHT       0x4D
#define KEY_UP          0x48
#define KEY_DOWN        0x50
#define KEY_IC          0x52 /* insert char */
#define KEY_DC          0x53 /* delete char */
#define KEY_BACKSPACE   0x0E
#define KEY_HOME        0x47
#define KEY_END         0x4F
#define KEY_NPAGE       0x49
#define KEY_PPAGE       0x51

265

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
struct magic_device
{
    WCHAR  name[10];
    HANDLE handle;
    dev_t  dev;
    ino_t  ino;
    void (*ioctl_handler)(CONTEXT86 *);
};

static void INT21_IoctlScsiMgrHandler( CONTEXT86 * );
static void INT21_IoctlEMSHandler( CONTEXT86 * );
static void INT21_IoctlHPScanHandler( CONTEXT86 * );

static struct magic_device magic_devices[] =
{
    { {'s','c','s','i','m','g','r','$',0}, NULL, 0, 0, INT21_IoctlScsiMgrHandler },
    { {'e','m','m','x','x','x','x','0',0}, NULL, 0, 0, INT21_IoctlEMSHandler },
    { {'h','p','s','c','a','n',0},         NULL, 0, 0, INT21_IoctlHPScanHandler },
};

#define NB_MAGIC_DEVICES  (sizeof(magic_devices)/sizeof(magic_devices[0]))


289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
/* Many calls translate a drive argument like this:
   drive number (00h = default, 01h = A:, etc)
   */
/******************************************************************
 *		INT21_DriveName
 *
 * Many calls translate a drive argument like this:
 * drive number (00h = default, 01h = A:, etc)
 */
static const char *INT21_DriveName(int drive)
{
    if (drive > 0) 
    {
        if (drive <= 26) return wine_dbg_sprintf("%c:", 'A' + drive - 1);
        else return wine_dbg_sprintf( "<Bad drive: %d>", drive);
    }
    return "default";
}

308 309 310 311 312 313
/***********************************************************************
 *           INT21_GetCurrentDrive
 *
 * Return current drive using scheme (0=A:, 1=B:, 2=C:, ...) or
 * MAX_DOS_DRIVES on error.
 */
314
static BYTE INT21_GetCurrentDrive(void)
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
{
    WCHAR current_directory[MAX_PATH];

    if (!GetCurrentDirectoryW( MAX_PATH, current_directory ) ||
        current_directory[1] != ':')
    {
        TRACE( "Failed to get current drive.\n" );
        return MAX_DOS_DRIVES;
    }

    return toupperW( current_directory[0] ) - 'A';
}


/***********************************************************************
 *           INT21_MapDrive
 *
 * Convert drive number from scheme (0=default, 1=A:, 2=B:, ...) into
 * scheme (0=A:, 1=B:, 2=C:, ...) or MAX_DOS_DRIVES on error.
 */
static BYTE INT21_MapDrive( BYTE drive )
{
    if (drive)
338 339 340 341 342 343 344 345 346 347
    {
        WCHAR drivespec[3] = {'A', ':', 0};
        UINT  drivetype;

        drivespec[0] += drive - 1;
        drivetype = GetDriveTypeW( drivespec );

        if (drivetype == DRIVE_UNKNOWN || drivetype == DRIVE_NO_ROOT_DIR)
            return MAX_DOS_DRIVES;

348
        return drive - 1;
349 350
    }

351 352 353
    return INT21_GetCurrentDrive();
}

354

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
/***********************************************************************
 *           INT21_SetCurrentDrive
 *
 * Set current drive. Uses scheme (0=A:, 1=B:, 2=C:, ...).
 */
static void INT21_SetCurrentDrive( BYTE drive )
{
    WCHAR drivespec[3] = {'A', ':', 0};

    drivespec[0] += drive;

    if (!SetCurrentDirectoryW( drivespec ))
        TRACE( "Failed to set current drive.\n" );
}


371 372 373 374 375 376
/***********************************************************************
 *           INT21_ReadChar
 *
 * Reads a character from the standard input.
 * Extended keycodes will be returned as two separate characters.
 */
377
static BOOL INT21_ReadChar( BYTE *input, CONTEXT86 *waitctx )
378 379 380 381 382 383 384
{
    static BYTE pending_scan = 0;

    if (pending_scan)
    {
        if (input)
            *input = pending_scan;
385
        if (waitctx)
386 387 388 389 390 391 392
            pending_scan = 0;
        return TRUE;
    }
    else
    {
        BYTE ascii;
        BYTE scan;
393
        if (!DOSVM_Int16ReadChar( &ascii, &scan, waitctx ))
394 395 396 397
            return FALSE;

        if (input)
            *input = ascii;
398
        if (waitctx && !ascii)
399 400 401 402 403 404
            pending_scan = scan;
        return TRUE;
    }
}


405 406 407 408 409
/***********************************************************************
 *           INT21_GetSystemCountryCode
 *
 * Return DOS country code for default system locale.
 */
410
static WORD INT21_GetSystemCountryCode( void )
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
{
    /*
     * FIXME: Determine country code. We should probably use
     *        DOSCONF structure for that.
     */
    return GetSystemDefaultLangID();
}


/***********************************************************************
 *           INT21_FillCountryInformation
 *
 * Fill 34-byte buffer with country information data using
 * default system locale.
 */
static void INT21_FillCountryInformation( BYTE *buffer )
{
    /* 00 - WORD: date format
     *          00 = mm/dd/yy
     *          01 = dd/mm/yy
     *          02 = yy/mm/dd
     */
    *(WORD*)(buffer + 0) = 0; /* FIXME: Get from locale */

    /* 02 - BYTE[5]: ASCIIZ currency symbol string */
    buffer[2] = '$'; /* FIXME: Get from locale */
    buffer[3] = 0;

    /* 07 - BYTE[2]: ASCIIZ thousands separator */
    buffer[7] = 0; /* FIXME: Get from locale */
    buffer[8] = 0;

    /* 09 - BYTE[2]: ASCIIZ decimal separator */
    buffer[9]  = '.'; /* FIXME: Get from locale */
    buffer[10] = 0;

    /* 11 - BYTE[2]: ASCIIZ date separator */
    buffer[11] = '/'; /* FIXME: Get from locale */
    buffer[12] = 0;

    /* 13 - BYTE[2]: ASCIIZ time separator */
    buffer[13] = ':'; /* FIXME: Get from locale */
    buffer[14] = 0;

    /* 15 - BYTE: Currency format
     *          bit 2 = set if currency symbol replaces decimal point
     *          bit 1 = number of spaces between value and currency symbol
     *          bit 0 = 0 if currency symbol precedes value
     *                  1 if currency symbol follows value
     */
    buffer[15] = 0; /* FIXME: Get from locale */

    /* 16 - BYTE: Number of digits after decimal in currency */
    buffer[16] = 0; /* FIXME: Get from locale */

    /* 17 - BYTE: Time format
     *          bit 0 = 0 if 12-hour clock
     *                  1 if 24-hour clock
     */
    buffer[17] = 1; /* FIXME: Get from locale */

    /* 18 - DWORD: Address of case map routine */
    *(DWORD*)(buffer + 18) = 0; /* FIXME: ptr to case map routine */

    /* 22 - BYTE[2]: ASCIIZ data-list separator */
    buffer[22] = ','; /* FIXME: Get from locale */
    buffer[23] = 0;

    /* 24 - BYTE[10]: Reserved */
    memset( buffer + 24, 0, 10 );
}


/***********************************************************************
 *           INT21_FillHeap
 *
 * Initialize DOS heap.
488 489 490 491
 *
 * Filename Terminator Table of w2k DE NTVDM:
 * 16 00 01 00 FF 00 00 20-02 0E 2E 22 2F 5C 5B 5D  ....... ..."/\[]
 * 3A 7C 3C 3E 2B 3D 3B 2C-00                       :|<>+=;,
492 493 494
 */
static void INT21_FillHeap( INT21_HEAP *heap )
{
495
    static const char terminators[] = ".\"/\\[]:|<>+=;,";
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
    int i;

    /*
     * Uppercase table.
     */
    heap->uppercase_size = 128;
    for (i = 0; i < 128; i++) 
        heap->uppercase_table[i] = toupper( 128 + i );

    /*
     * Lowercase table.
     */
    heap->lowercase_size = 256;
    for (i = 0; i < 256; i++) 
        heap->lowercase_table[i] = tolower( i );
    
    /*
     * Collating table.
     */
    heap->collating_size = 256;
    for (i = 0; i < 256; i++) 
        heap->collating_table[i] = i;

    /*
     * Filename table.
     */
    heap->filename_size = 8 + strlen(terminators);
    heap->filename_illegal_size = strlen(terminators);
524
    memcpy( heap->filename_illegal_table, terminators, heap->filename_illegal_size );
525 526

    heap->filename_reserved1 = 0x01;
527 528
    heap->filename_lowest = 0x00;
    heap->filename_highest = 0xff;
529
    heap->filename_reserved2 = 0x00;    
530 531
    heap->filename_exclude_first = 0x00;
    heap->filename_exclude_last = 0x20;
532 533 534 535 536 537 538 539 540 541 542 543
    heap->filename_reserved3 = 0x02;

    /*
     * DBCS lead byte table. This table is empty.
     */
    heap->dbcs_size = 0;
    memset( heap->dbcs_table, 0, sizeof(heap->dbcs_table) );

    /*
     * Initialize InDos flag.
     */
    heap->misc_indos = 0;
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576

    /*
     * FIXME: Should drive parameter blocks (DPB) be
     *        initialized here and linked to DOS LOL?
     */
}


/***********************************************************************
 *           INT21_GetHeapPointer
 *
 * Get pointer for DOS heap (INT21_HEAP).
 * Creates and initializes heap on first call.
 */
static INT21_HEAP *INT21_GetHeapPointer( void )
{
    static INT21_HEAP *heap_pointer = NULL;

    if (!heap_pointer)
    {
        WORD heap_segment;
        WORD heap_selector;

        heap_pointer = DOSVM_AllocDataUMB( sizeof(INT21_HEAP), 
                                           &heap_segment,
                                           &heap_selector );

        heap_pointer->misc_segment  = heap_segment;
        heap_pointer->misc_selector = heap_selector;
        INT21_FillHeap( heap_pointer );
    }

    return heap_pointer;
577 578 579 580 581 582 583 584 585 586 587
}


/***********************************************************************
 *           INT21_GetHeapSelector
 *
 * Get segment/selector for DOS heap (INT21_HEAP).
 * Creates and initializes heap on first call.
 */
static WORD INT21_GetHeapSelector( CONTEXT86 *context )
{
588 589 590 591 592 593 594 595
    INT21_HEAP *heap = INT21_GetHeapPointer();

    if (!ISV86(context) && DOSVM_IsWin16())
        return heap->misc_selector;
    else
        return heap->misc_segment;
}

596

597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
/***********************************************************************
 *           INT21_FillDrivePB
 *
 * Fill DOS heap drive parameter block for the specified drive.
 * Return TRUE if drive was valid and there were
 * no errors while reading drive information.
 */
static BOOL INT21_FillDrivePB( BYTE drive )
{
    WCHAR       drivespec[3] = {'A', ':', 0};
    INT21_HEAP *heap = INT21_GetHeapPointer();
    INT21_DPB  *dpb;
    UINT        drivetype;
    DWORD       cluster_sectors;
    DWORD       sector_bytes;
    DWORD       free_clusters;
    DWORD       total_clusters;

    if (drive >= MAX_DOS_DRIVES)
        return FALSE;

    dpb = &heap->misc_dpb_list[drive];
    drivespec[0] += drive;
    drivetype = GetDriveTypeW( drivespec );

    /*
     * FIXME: Does this check work correctly with floppy/cdrom drives?
     */
    if (drivetype == DRIVE_NO_ROOT_DIR || drivetype == DRIVE_UNKNOWN)
        return FALSE;

    /*
     * FIXME: Does this check work correctly with floppy/cdrom drives?
     */
    if (!GetDiskFreeSpaceW( drivespec, &cluster_sectors, &sector_bytes,
                            &free_clusters, &total_clusters ))
        return FALSE;

    /*
     * FIXME: Most of the values listed below are incorrect.
     *        All values should be validated.
     */
 
    dpb->drive           = drive;
    dpb->unit            = 0;
    dpb->sector_bytes    = sector_bytes;
    dpb->cluster_sectors = cluster_sectors - 1;

    dpb->shift = 0;
    while (cluster_sectors > 1)
647
    {
648 649
        cluster_sectors /= 2;
        dpb->shift++;
650 651
    }

652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    dpb->num_reserved         = 0;
    dpb->num_FAT              = 1;
    dpb->num_root_entries     = 2;
    dpb->first_data_sector    = 2;
    dpb->num_clusters1        = total_clusters;
    dpb->sectors_per_FAT      = 1;
    dpb->first_dir_sector     = 1;
    dpb->driver_header        = 0;
    dpb->media_ID             = (drivetype == DRIVE_FIXED) ? 0xF8 : 0xF0;
    dpb->access_flag          = 0;
    dpb->next                 = 0;
    dpb->search_cluster1      = 0;
    dpb->free_clusters_lo     = LOWORD(free_clusters);
    dpb->free_clusters_hi     = HIWORD(free_clusters);
    dpb->mirroring_flags      = 0;
    dpb->info_sector          = 0xffff;
    dpb->spare_boot_sector    = 0xffff;
    dpb->first_cluster_sector = 0;
    dpb->num_clusters2        = total_clusters;
    dpb->fat_clusters         = 32;
    dpb->root_cluster         = 0;
    dpb->search_cluster2      = 0;

    return TRUE;
676 677 678
}


679 680 681 682 683 684 685 686 687 688
/***********************************************************************
 *           INT21_GetCurrentDirectory
 *
 * Handler for:
 * - function 0x47
 * - subfunction 0x47 of function 0x71
 */
static BOOL INT21_GetCurrentDirectory( CONTEXT86 *context, BOOL islong )
{
    char  *buffer = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi);
689
    BYTE   drive = INT21_MapDrive( DL_reg(context) );
690 691 692 693 694 695
    WCHAR  pathW[MAX_PATH];
    char   pathA[MAX_PATH];
    WCHAR *ptr = pathW;

    TRACE( "drive %d\n", DL_reg(context) );

696 697
    if (drive == MAX_DOS_DRIVES)
    {
698 699 700 701 702 703 704 705
        SetLastError(ERROR_INVALID_DRIVE);
        return FALSE;
    }
    
    /*
     * Grab current directory.
     */

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    if (!GetCurrentDirectoryW( MAX_PATH, pathW )) return FALSE;

    if (toupperW(pathW[0]) - 'A' != drive || pathW[1] != ':')
    {
        /* cwd is not on the requested drive, get the environment string instead */

        WCHAR env_var[4];

        env_var[0] = '=';
        env_var[1] = 'A' + drive;
        env_var[2] = ':';
        env_var[3] = 0;
        if (!GetEnvironmentVariableW( env_var, pathW, MAX_PATH ))
        {
            /* return empty path */
            buffer[0] = 0;
            return TRUE;
        }
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
    }

    /*
     * Convert into short format.
     */

    if (!islong)
    {
        DWORD result = GetShortPathNameW( pathW, pathW, MAX_PATH );
        if (!result)
            return FALSE;
        if (result > MAX_PATH)
        {
            WARN( "Short path too long!\n" );
            SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
            return FALSE;
        }
    }

    /*
     * The returned pathname does not include 
     * the drive letter, colon or leading backslash.
     */

    if (ptr[0] == '\\')
    {
        /*
         * FIXME: We should probably just strip host part from name...
         */
        FIXME( "UNC names are not supported.\n" );
        SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
        return FALSE;
    }
    else if (!ptr[0] || ptr[1] != ':' || ptr[2] != '\\')
    {
        WARN( "Path is neither UNC nor DOS path: %s\n",
              wine_dbgstr_w(ptr) );
        SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
        return FALSE;
    }
    else
    {
        /* Remove drive letter, colon and leading backslash. */
        ptr += 3;
    }

    /*
     * Convert into OEM string.
     */
    
    if (!WideCharToMultiByte(CP_OEMCP, 0, ptr, -1, pathA, 
                             MAX_PATH, NULL, NULL))
    {
        WARN( "Cannot convert path!\n" );
        SetLastError(ERROR_NETWORK_BUSY); /* Internal Wine error. */
        return FALSE;
    }

    /*
     * Success.
     */

    if (!islong)
    {
        /* Undocumented success code. */
        SET_AX( context, 0x0100 );
        
        /* Truncate buffer to 64 bytes. */
        pathA[63] = 0;
    }

795
    TRACE( "%c:=%s\n", 'A' + drive, pathA );
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811

    strcpy( buffer, pathA );
    return TRUE;
}


/***********************************************************************
 *           INT21_SetCurrentDirectory
 *
 * Handler for:
 * - function 0x3b
 * - subfunction 0x3b of function 0x71
 */
static BOOL INT21_SetCurrentDirectory( CONTEXT86 *context )
{
    WCHAR dirW[MAX_PATH];
812
    WCHAR env_var[4];
813
    DWORD attr;
814 815 816 817 818 819 820
    char *dirA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    BYTE  drive = INT21_GetCurrentDrive();
    BOOL  result;

    TRACE( "SET CURRENT DIRECTORY %s\n", dirA );

    MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);
821 822
    if (!GetFullPathNameW( dirW, MAX_PATH, dirW, NULL )) return FALSE;

823 824 825 826 827 828 829
    attr = GetFileAttributesW( dirW );
    if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
    {
        SetLastError( ERROR_PATH_NOT_FOUND );
        return FALSE;
    }

830 831 832 833 834
    env_var[0] = '=';
    env_var[1] = dirW[0];
    env_var[2] = ':';
    env_var[3] = 0;
    result = SetEnvironmentVariableW( env_var, dirW );
835

836 837
    /* only set current directory if on the current drive */
    if (result && (toupperW(dirW[0]) - 'A' == drive)) result = SetCurrentDirectoryW( dirW );
838 839 840 841

    return result;
}

842 843 844 845 846 847 848 849
/***********************************************************************
 *           INT21_CreateMagicDeviceHandle
 *
 * Create a dummy file handle for a "magic" device.
 */
static HANDLE INT21_CreateMagicDeviceHandle( LPCWSTR name )
{
    const char *dir = wine_get_server_dir();
850 851 852 853 854 855 856 857 858 859 860
    int len;
    HANDLE ret;
    NTSTATUS status;
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;
    IO_STATUS_BLOCK io;

    len = MultiByteToWideChar( CP_UNIXCP, 0, dir, -1, NULL, 0 );
    nameW.Length = (len + 1 + strlenW( name )) * sizeof(WCHAR);
    nameW.MaximumLength = nameW.Length + sizeof(WCHAR);
    if (!(nameW.Buffer = HeapAlloc( GetProcessHeap(), 0, nameW.Length )))
861 862 863 864
    {
        SetLastError( ERROR_NOT_ENOUGH_MEMORY );
        return 0;
    }
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
    MultiByteToWideChar( CP_UNIXCP, 0, dir, -1, nameW.Buffer, len );
    nameW.Buffer[len-1] = '/';
    strcpyW( nameW.Buffer + len, name );

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.Attributes = 0;
    attr.ObjectName = &nameW;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;

    status = NtCreateFile( &ret, GENERIC_READ|GENERIC_WRITE, &attr, &io, NULL, 0,
                           FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN_IF,
                           FILE_SYNCHRONOUS_IO_ALERT, NULL, 0 );
    if (status)
880
    {
881 882
        ret = 0;
        SetLastError( RtlNtStatusToDosError(status) );
883
    }
884
    RtlFreeUnicodeString( &nameW );
885 886 887 888 889 890 891 892 893 894 895
    return ret;
}


/***********************************************************************
 *           INT21_OpenMagicDevice
 *
 * Open a file handle for "magic" devices like EMMXXXX0.
 */
static HANDLE INT21_OpenMagicDevice( LPCWSTR name, DWORD access )
{
896
    unsigned int i;
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
    const WCHAR *p;
    HANDLE handle;

    if (name[0] && (name[1] == ':')) name += 2;
    if ((p = strrchrW( name, '/' ))) name = p + 1;
    if ((p = strrchrW( name, '\\' ))) name = p + 1;

    for (i = 0; i < NB_MAGIC_DEVICES; i++)
    {
        int len = strlenW( magic_devices[i].name );
        if (!strncmpiW( magic_devices[i].name, name, len ) &&
            (!name[len] || name[len] == '.' || name[len] == ':')) break;
    }
    if (i == NB_MAGIC_DEVICES) return 0;

    if (!magic_devices[i].handle) /* need to open it */
    {
        int fd;
        struct stat st;

        if (!(handle = INT21_CreateMagicDeviceHandle( magic_devices[i].name ))) return 0;
918
        wine_server_handle_to_fd( handle, 0, &fd, NULL );
919 920 921 922 923 924 925 926 927 928 929
        fstat( fd, &st );
        wine_server_release_fd( handle, fd );
        magic_devices[i].dev = st.st_dev;
        magic_devices[i].ino = st.st_ino;
        magic_devices[i].handle = handle;
    }
    if (!DuplicateHandle( GetCurrentProcess(), magic_devices[i].handle,
                          GetCurrentProcess(), &handle, access, FALSE, 0 )) handle = 0;
    return handle;
}

930

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
/***********************************************************************
 *           INT21_CreateFile
 *
 * Handler for:
 * - function 0x3c
 * - function 0x3d
 * - function 0x5b
 * - function 0x6c
 * - subfunction 0x6c of function 0x71
 */
static BOOL INT21_CreateFile( CONTEXT86 *context, 
                              DWORD      pathSegOff,
                              BOOL       returnStatus,
                              WORD       dosAccessShare,
                              BYTE       dosAction )
{
    WORD   dosStatus;
    char  *pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, pathSegOff);
    WCHAR  pathW[MAX_PATH];   
    DWORD  winAccess;
    DWORD  winAttributes;
    HANDLE winHandle;
    DWORD  winMode;
    DWORD  winSharing;

    TRACE( "CreateFile called: function=%02x, action=%02x, access/share=%04x, "
           "create flags=%04x, file=%s.\n",
           AH_reg(context), dosAction, dosAccessShare, CX_reg(context), pathA );

    /*
     * Application tried to create/open a file whose name 
     * ends with a backslash. This is not allowed.
     *
     * FIXME: This needs to be validated, especially the return value.
     */
    if (pathA[strlen(pathA) - 1] == '/')
    {
        SetLastError( ERROR_FILE_NOT_FOUND );
        return FALSE;
    }

    /*
     * Convert DOS action flags into Win32 creation disposition parameter.
     */ 
    switch(dosAction)
    {
    case 0x01:
        winMode = OPEN_EXISTING;
        break;
    case 0x02:
        winMode = TRUNCATE_EXISTING;
        break;
    case 0x10:
        winMode = CREATE_NEW;
        break;
    case 0x11:
        winMode = OPEN_ALWAYS;
        break;
    case 0x12:
        winMode = CREATE_ALWAYS;
        break;
    default:
        SetLastError( ERROR_INVALID_PARAMETER );
        return FALSE;
    }

    /*
     * Convert DOS access/share flags into Win32 desired access parameter.
     */ 
    switch(dosAccessShare & 0x07)
    {
    case OF_READ:
        winAccess = GENERIC_READ;
        break;
    case OF_WRITE:
        winAccess = GENERIC_WRITE;
        break;
    case OF_READWRITE:
        winAccess = GENERIC_READ | GENERIC_WRITE;
        break;
    case 0x04:
        /*
         * Read-only, do not modify file's last-access time (DOS7).
         *
         * FIXME: How to prevent modification of last-access time?
         */
        winAccess = GENERIC_READ;
        break;
    default:
        winAccess = 0;
    }

    /*
     * Convert DOS access/share flags into Win32 share mode parameter.
     */ 
    switch(dosAccessShare & 0x70)
    {
    case OF_SHARE_EXCLUSIVE:  
        winSharing = 0; 
        break;
    case OF_SHARE_DENY_WRITE: 
        winSharing = FILE_SHARE_READ; 
        break;
    case OF_SHARE_DENY_READ:  
        winSharing = FILE_SHARE_WRITE; 
        break;
    case OF_SHARE_DENY_NONE:
    case OF_SHARE_COMPAT:
    default:
        winSharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
    }

    /*
     * FIXME: Bit (dosAccessShare & 0x80) represents inheritance.
     *        What to do with this bit?
     * FIXME: Bits in the high byte of dosAccessShare are not supported.
     *        See both function 0x6c and subfunction 0x6c of function 0x71 for
     *        definition of these bits.
     */

    /*
     * Convert DOS create attributes into Win32 flags and attributes parameter.
     */
    if (winMode == OPEN_EXISTING || winMode == TRUNCATE_EXISTING)
    {
        winAttributes = 0;
    }
    else
    {        
        WORD dosAttributes = CX_reg(context);

1062
        if (dosAttributes & FA_LABEL)
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        {
            /*
             * Application tried to create volume label entry.
             * This is difficult to support so we do not allow it.
             *
             * FIXME: If volume does not already have a label, 
             *        this function is supposed to succeed.
             */
            SetLastError( ERROR_ACCESS_DENIED );
            return TRUE;
        }

        winAttributes = dosAttributes & 
            (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | 
             FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_ARCHIVE);
    }

    /*
     * Open the file.
     */
    MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);

1085
    if ((winHandle = INT21_OpenMagicDevice( pathW, winAccess )))
1086 1087
    {
        dosStatus = 1;
1088 1089 1090 1091 1092
    }
    else
    {
        winHandle = CreateFileW( pathW, winAccess, winSharing, NULL,
                                 winMode, winAttributes, 0 );
1093 1094 1095 1096 1097 1098
        /* DOS allows to open files on a CDROM R/W */
        if( winHandle == INVALID_HANDLE_VALUE &&
                GetLastError()== ERROR_WRITE_PROTECT) {
            winHandle = CreateFileW( pathW, winAccess & ~GENERIC_WRITE,
                    winSharing, NULL, winMode, winAttributes, 0 );
        }
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

        if (winHandle == INVALID_HANDLE_VALUE)
            return FALSE;

        /*
         * Determine DOS file status.
         *
         * 1 = file opened
         * 2 = file created
         * 3 = file replaced
         */
        switch(winMode)
        {
        case OPEN_EXISTING:
            dosStatus = 1;
            break;
        case TRUNCATE_EXISTING:
            dosStatus = 3;
            break;
        case CREATE_NEW:
            dosStatus = 2;
            break;
        case OPEN_ALWAYS:
            dosStatus = (GetLastError() == ERROR_ALREADY_EXISTS) ? 1 : 2;
            break;
        case CREATE_ALWAYS:
            dosStatus = (GetLastError() == ERROR_ALREADY_EXISTS) ? 3 : 2;
            break;
        default:
            dosStatus = 0;
        }
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    }

    /*
     * Return DOS file handle and DOS status.
     */
    SET_AX( context, Win32HandleToDosFileHandle(winHandle) );

    if (returnStatus)
        SET_CX( context, dosStatus );

    TRACE( "CreateFile finished: handle=%d, status=%d.\n", 
           AX_reg(context), dosStatus );

    return TRUE;
}


1147 1148 1149
/***********************************************************************
 *           INT21_BufferedInput
 *
1150 1151
 * Handler for function 0x0a and reading from console using
 * function 0x3f.
1152 1153
 *
 * Reads a string of characters from standard input until
1154 1155 1156
 * enter key is pressed. Returns either number of characters 
 * read from console including terminating CR or 
 * zero if capacity was zero.
1157
 */
1158
static WORD INT21_BufferedInput( CONTEXT86 *context, BYTE *ptr, WORD capacity )
1159
{
1160
    BYTE length = 0;
1161 1162 1163 1164 1165

    /*
     * Return immediately if capacity is zero.
     */
    if (capacity == 0)
1166
        return 0;
1167 1168 1169 1170 1171 1172

    while(TRUE)
    {
        BYTE ascii;
        BYTE scan;

1173
        DOSVM_Int16ReadChar( &ascii, &scan, context );
1174 1175 1176

        if (ascii == '\r' || ascii == '\n')
        {
1177 1178
            ptr[length] = '\r';
            return length + 1;
1179 1180 1181
        }

        /*
1182 1183
         * DOS handles only backspace and KEY_LEFT
         *        perhaps we should do more
1184
         */
1185 1186 1187 1188 1189 1190 1191
        if (ascii == '\b' || scan == KEY_LEFT)
        {
            if (length==0) continue;
            DOSVM_PutChar( '\b' );
            length--;
            continue;
        }
1192 1193 1194 1195 1196 1197 1198 1199 1200

        /*
         * If the buffer becomes filled to within one byte of
         * capacity, DOS rejects all further characters up to,
         * but not including, the terminating carriage return.
         */
        if (ascii != 0 && length < capacity-1)
        {
            DOSVM_PutChar( ascii );
1201
            ptr[length] = ascii;
1202 1203 1204 1205 1206 1207
            length++;
        }
    }
}


1208 1209 1210 1211
/***********************************************************************
 *           INT21_GetCurrentDTA
 */
static BYTE *INT21_GetCurrentDTA( CONTEXT86 *context )
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
{
    TDB *pTask = GlobalLock16(GetCurrentTask());

    /* FIXME: This assumes DTA was set correctly! */
    return (BYTE *)CTX_SEG_OFF_TO_LIN( context, SELECTOROF(pTask->dta),
                                                (DWORD)OFFSETOF(pTask->dta) );
}


/***********************************************************************
 *           INT21_OpenFileUsingFCB
 *
 * Handler for function 0x0f.
 *
 * PARAMS
 *  DX:DX [I/O] File control block (FCB or XFCB) of unopened file
 *
 * RETURNS (in AL)
 *  0x00: successful
 *  0xff: failed
 *
 * NOTES
 *  Opens a FCB file for read/write in compatibility mode. Upon calling
 *  the FCB must have the drive_number, file_name, and file_extension
 *  fields filled and all other bytes cleared.
 */
static void INT21_OpenFileUsingFCB( CONTEXT86 *context )
{
    struct FCB *fcb;
    struct XFCB *xfcb;
    char file_path[16];
    char *pos;
    HANDLE handle;
    HFILE16 hfile16;
    BY_HANDLE_FILE_INFORMATION info;
    BYTE AL_result;

    fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    if (fcb->drive_number == 0xff) {
        xfcb = (struct XFCB *) fcb;
        fcb = (struct FCB *) xfcb->fcb;
    } /* if */

    AL_result = 0;
1256
    file_path[0] = 'A' + INT21_MapDrive( fcb->drive_number );
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

    if (AL_result == 0) {
        file_path[1] = ':';
        pos = &file_path[2];
        memcpy(pos, fcb->file_name, 8);
        pos[8] = ' ';
        pos[9] = '\0';
        pos = strchr(pos, ' ');
        *pos = '.';
        pos++;
        memcpy(pos, fcb->file_extension, 3);
        pos[3] = ' ';
        pos[4] = '\0';
        pos = strchr(pos, ' ');
        *pos = '\0';

        handle = (HANDLE) _lopen(file_path, OF_READWRITE);
        if (handle == INVALID_HANDLE_VALUE) {
            TRACE("_lopen(\"%s\") failed: INVALID_HANDLE_VALUE\n", file_path);
            AL_result = 0xff; /* failed */
        } else {
            hfile16 = Win32HandleToDosFileHandle(handle);
            if (hfile16 == HFILE_ERROR16) {
                TRACE("Win32HandleToDosFileHandle(%p) failed: HFILE_ERROR\n", handle);
                CloseHandle(handle);
                AL_result = 0xff; /* failed */
            } else if (hfile16 > 255) {
                TRACE("hfile16 (=%d) larger than 255 for \"%s\"\n", hfile16, file_path);
                _lclose16(hfile16);
                AL_result = 0xff; /* failed */
            } else {
                if (!GetFileInformationByHandle(handle, &info)) {
                    TRACE("GetFileInformationByHandle(%d, %p) for \"%s\" failed\n",
                          hfile16, handle, file_path);
                    _lclose16(hfile16);
                    AL_result = 0xff; /* failed */
                } else {
                    fcb->drive_number = file_path[0] - 'A' + 1;
                    fcb->current_block_number = 0;
                    fcb->logical_record_size = 128;
                    fcb->file_size = info.nFileSizeLow;
                    FileTimeToDosDateTime(&info.ftLastWriteTime,
                        &fcb->date_of_last_write, &fcb->time_of_last_write);
                    fcb->file_number = hfile16;
                    fcb->attributes = 0xc2;
                    fcb->starting_cluster = 0; /* don't know correct init value */
                    fcb->sequence_number = 0; /* don't know correct init value */
                    fcb->file_attributes = info.dwFileAttributes;
                    /* The following fields are not initialized */
                    /* by the native function: */
                    /* unused */
                    /* record_within_current_block */
                    /* random_access_record_number */

                    TRACE("successful opened file \"%s\" as %d (handle %p)\n",
                          file_path, hfile16, handle);
                    AL_result = 0x00; /* successful */
                } /* if */
            } /* if */
        } /* if */
    } /* if */
    SET_AL(context, AL_result);
}


/***********************************************************************
 *           INT21_CloseFileUsingFCB
 *
 * Handler for function 0x10.
 *
 * PARAMS
 *  DX:DX [I/O] File control block (FCB or XFCB) of open file
 *
 * RETURNS (in AL)
 *  0x00: successful
 *  0xff: failed
 *
 * NOTES
 *  Closes a FCB file.
 */
static void INT21_CloseFileUsingFCB( CONTEXT86 *context )
{
    struct FCB *fcb;
    struct XFCB *xfcb;
    BYTE AL_result;

    fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    if (fcb->drive_number == 0xff) {
        xfcb = (struct XFCB *) fcb;
        fcb = (struct FCB *) xfcb->fcb;
    } /* if */

    if (_lclose16((HFILE16) fcb->file_number) != 0) {
1350
        TRACE("_lclose16(%d) failed\n", fcb->file_number);
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        AL_result = 0xff; /* failed */
    } else {
        TRACE("successful closed file %d\n", fcb->file_number);
        AL_result = 0x00; /* successful */
    } /* if */
    SET_AL(context, AL_result);
}


/***********************************************************************
1361
 *           INT21_SequentialReadFromFCB
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
 *
 * Handler for function 0x14.
 *
 * PARAMS
 *  DX:DX [I/O] File control block (FCB or XFCB) of open file
 *
 * RETURNS (in AL)
 *  0: successful
 *  1: end of file, no data read
 *  2: segment wrap in DTA, no data read (not returned now)
 *  3: end of file, partial record read
 *
 * NOTES
 *  Reads a record with the size FCB->logical_record_size from the FCB
 *  to the disk transfer area. The position of the record is specified
 *  with FCB->current_block_number and FCB->record_within_current_block.
 *  Then FCB->current_block_number and FCB->record_within_current_block
 *  are updated to point to the next record. If a partial record is
 *  read, it is filled with zeros up to the FCB->logical_record_size.
 */
1382
static void INT21_SequentialReadFromFCB( CONTEXT86 *context )
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
{
    struct FCB *fcb;
    struct XFCB *xfcb;
    HANDLE handle;
    DWORD record_number;
    long position;
    BYTE *disk_transfer_area;
    UINT bytes_read;
    BYTE AL_result;

    fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    if (fcb->drive_number == 0xff) {
        xfcb = (struct XFCB *) fcb;
        fcb = (struct FCB *) xfcb->fcb;
    } /* if */

    handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
    if (handle == INVALID_HANDLE_VALUE) {
        TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
            fcb->file_number);
        AL_result = 0x01; /* end of file, no data read */
    } else {
        record_number = 128 * fcb->current_block_number + fcb->record_within_current_block;
        position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
        if (position != record_number * fcb->logical_record_size) {
            TRACE("seek(%d, %ld, 0) failed with %ld\n",
                  fcb->file_number, record_number * fcb->logical_record_size, position);
            AL_result = 0x01; /* end of file, no data read */
        } else {
1412
            disk_transfer_area = INT21_GetCurrentDTA(context);
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
            bytes_read = _lread((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
            if (bytes_read != fcb->logical_record_size) {
                TRACE("_lread(%d, %p, %d) failed with %d\n",
                      fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_read);
                if (bytes_read == 0) {
                    AL_result = 0x01; /* end of file, no data read */
                } else {
                    memset(&disk_transfer_area[bytes_read], 0, fcb->logical_record_size - bytes_read);
                    AL_result = 0x03; /* end of file, partial record read */
                } /* if */
            } else {
                TRACE("successful read %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
                    bytes_read, record_number, position, fcb->file_number, handle);
                AL_result = 0x00; /* successful */
            } /* if */
        } /* if */
    } /* if */
    if (AL_result == 0x00 || AL_result == 0x03) {
        if (fcb->record_within_current_block == 127) {
            fcb->record_within_current_block = 0;
            fcb->current_block_number++;
        } else {
            fcb->record_within_current_block++;
        } /* if */
    } /* if */
    SET_AL(context, AL_result);
}


/***********************************************************************
1443
 *           INT21_SequentialWriteToFCB
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
 *
 * Handler for function 0x15.
 *
 * PARAMS
 *  DX:DX [I/O] File control block (FCB or XFCB) of open file
 *
 * RETURNS (in AL)
 *  0: successful
 *  1: disk full
 *  2: segment wrap in DTA (not returned now)
 *
 * NOTES
 *  Writes a record with the size FCB->logical_record_size from the disk
 *  transfer area to the FCB. The position of the record is specified
 *  with FCB->current_block_number and FCB->record_within_current_block.
 *  Then FCB->current_block_number and FCB->record_within_current_block
 *  are updated to point to the next record. 
 */
1462
static void INT21_SequentialWriteToFCB( CONTEXT86 *context )
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
{
    struct FCB *fcb;
    struct XFCB *xfcb;
    HANDLE handle;
    DWORD record_number;
    long position;
    BYTE *disk_transfer_area;
    UINT bytes_written;
    BYTE AL_result;

    fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    if (fcb->drive_number == 0xff) {
        xfcb = (struct XFCB *) fcb;
        fcb = (struct FCB *) xfcb->fcb;
    } /* if */

    handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
    if (handle == INVALID_HANDLE_VALUE) {
        TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
            fcb->file_number);
        AL_result = 0x01; /* disk full */
    } else {
        record_number = 128 * fcb->current_block_number + fcb->record_within_current_block;
        position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
        if (position != record_number * fcb->logical_record_size) {
            TRACE("seek(%d, %ld, 0) failed with %ld\n",
                  fcb->file_number, record_number * fcb->logical_record_size, position);
            AL_result = 0x01; /* disk full */
        } else {
1492
            disk_transfer_area = INT21_GetCurrentDTA(context);
1493
            bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, fcb->logical_record_size);
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
            if (bytes_written != fcb->logical_record_size) {
                TRACE("_lwrite(%d, %p, %d) failed with %d\n",
                      fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_written);
                AL_result = 0x01; /* disk full */
            } else {
                TRACE("successful written %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
                    bytes_written, record_number, position, fcb->file_number, handle);
                AL_result = 0x00; /* successful */
            } /* if */
        } /* if */
    } /* if */
    if (AL_result == 0x00) {
        if (fcb->record_within_current_block == 127) {
            fcb->record_within_current_block = 0;
            fcb->current_block_number++;
        } else {
            fcb->record_within_current_block++;
        } /* if */
    } /* if */
    SET_AL(context, AL_result);
}


/***********************************************************************
 *           INT21_ReadRandomRecordFromFCB
 *
 * Handler for function 0x21.
 *
 * PARAMS
 *  DX:DX [I/O] File control block (FCB or XFCB) of open file
 *
 * RETURNS (in AL)
 *  0: successful
 *  1: end of file, no data read
 *  2: segment wrap in DTA, no data read (not returned now)
 *  3: end of file, partial record read
 *
 * NOTES
 *  Reads a record with the size FCB->logical_record_size from
 *  the FCB to the disk transfer area. The position of the record
 *  is specified with FCB->random_access_record_number. The
 *  FCB->random_access_record_number is not updated. If a partial record
 *  is read, it is filled with zeros up to the FCB->logical_record_size.
 */
static void INT21_ReadRandomRecordFromFCB( CONTEXT86 *context )
{
    struct FCB *fcb;
    struct XFCB *xfcb;
    HANDLE handle;
    DWORD record_number;
    long position;
    BYTE *disk_transfer_area;
    UINT bytes_read;
    BYTE AL_result;

    fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    if (fcb->drive_number == 0xff) {
        xfcb = (struct XFCB *) fcb;
        fcb = (struct FCB *) xfcb->fcb;
    } /* if */

    memcpy(&record_number, fcb->random_access_record_number, 4);
    handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
    if (handle == INVALID_HANDLE_VALUE) {
        TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
            fcb->file_number);
        AL_result = 0x01; /* end of file, no data read */
    } else {
        position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
        if (position != record_number * fcb->logical_record_size) {
            TRACE("seek(%d, %ld, 0) failed with %ld\n",
                  fcb->file_number, record_number * fcb->logical_record_size, position);
            AL_result = 0x01; /* end of file, no data read */
        } else {
1568
            disk_transfer_area = INT21_GetCurrentDTA(context);
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
            bytes_read = _lread((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
            if (bytes_read != fcb->logical_record_size) {
                TRACE("_lread(%d, %p, %d) failed with %d\n",
                      fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_read);
                if (bytes_read == 0) {
                    AL_result = 0x01; /* end of file, no data read */
                } else {
                    memset(&disk_transfer_area[bytes_read], 0, fcb->logical_record_size - bytes_read);
                    AL_result = 0x03; /* end of file, partial record read */
                } /* if */
            } else {
                TRACE("successful read %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
                    bytes_read, record_number, position, fcb->file_number, handle);
                AL_result = 0x00; /* successful */
            } /* if */
        } /* if */
    } /* if */
    fcb->current_block_number = record_number / 128;
    fcb->record_within_current_block = record_number % 128;
    SET_AL(context, AL_result);
}


/***********************************************************************
 *           INT21_WriteRandomRecordToFCB
 *
 * Handler for function 0x22.
 *
 * PARAMS
 *  DX:DX [I/O] File control block (FCB or XFCB) of open file
 *
 * RETURNS (in AL)
 *  0: successful
 *  1: disk full
 *  2: segment wrap in DTA (not returned now)
 *
 * NOTES
 *  Writes a record with the size FCB->logical_record_size from
 *  the disk transfer area to the FCB. The position of the record
 *  is specified with FCB->random_access_record_number. The
 *  FCB->random_access_record_number is not updated.
 */
static void INT21_WriteRandomRecordToFCB( CONTEXT86 *context )
{
    struct FCB *fcb;
    struct XFCB *xfcb;
    HANDLE handle;
    DWORD record_number;
    long position;
    BYTE *disk_transfer_area;
    UINT bytes_written;
    BYTE AL_result;

    fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    if (fcb->drive_number == 0xff) {
        xfcb = (struct XFCB *) fcb;
        fcb = (struct FCB *) xfcb->fcb;
    } /* if */

    memcpy(&record_number, fcb->random_access_record_number, 4);
    handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
    if (handle == INVALID_HANDLE_VALUE) {
        TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
            fcb->file_number);
        AL_result = 0x01; /* disk full */
    } else {
        position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
        if (position != record_number * fcb->logical_record_size) {
            TRACE("seek(%d, %ld, 0) failed with %ld\n",
                  fcb->file_number, record_number * fcb->logical_record_size, position);
            AL_result = 0x01; /* disk full */
        } else {
1641
            disk_transfer_area = INT21_GetCurrentDTA(context);
1642
            bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, fcb->logical_record_size);
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
            if (bytes_written != fcb->logical_record_size) {
                TRACE("_lwrite(%d, %p, %d) failed with %d\n",
                      fcb->file_number, disk_transfer_area, fcb->logical_record_size, bytes_written);
                AL_result = 0x01; /* disk full */
            } else {
                TRACE("successful written %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
                    bytes_written, record_number, position, fcb->file_number, handle);
                AL_result = 0x00; /* successful */
            } /* if */
        } /* if */
    } /* if */
    fcb->current_block_number = record_number / 128;
    fcb->record_within_current_block = record_number % 128;
    SET_AL(context, AL_result);
}


/***********************************************************************
 *           INT21_RandomBlockReadFromFCB
 *
 * Handler for function 0x27.
 *
 * PARAMS
 *  CX    [I/O] Number of records to read
 *  DX:DX [I/O] File control block (FCB or XFCB) of open file
 *
 * RETURNS (in AL)
 *  0: successful
 *  1: end of file, no data read
 *  2: segment wrap in DTA, no data read (not returned now)
 *  3: end of file, partial record read
 *
 * NOTES
 *  Reads several records with the size FCB->logical_record_size from
 *  the FCB to the disk transfer area. The number of records to be
 *  read is specified in the CX register. The position of the first
 *  record is specified with FCB->random_access_record_number. The
 *  FCB->random_access_record_number, the FCB->current_block_number
 *  and FCB->record_within_current_block are updated to point to the
 *  next record after the records read. If a partial record is read,
 *  it is filled with zeros up to the FCB->logical_record_size. The
 *  CX register is set to the number of successfully read records.
 */
static void INT21_RandomBlockReadFromFCB( CONTEXT86 *context )
{
    struct FCB *fcb;
    struct XFCB *xfcb;
    HANDLE handle;
    DWORD record_number;
    long position;
    BYTE *disk_transfer_area;
    UINT records_requested;
    UINT bytes_requested;
    UINT bytes_read;
    UINT records_read;
    BYTE AL_result;

    fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    if (fcb->drive_number == 0xff) {
        xfcb = (struct XFCB *) fcb;
        fcb = (struct FCB *) xfcb->fcb;
    } /* if */

    memcpy(&record_number, fcb->random_access_record_number, 4);
    handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
    if (handle == INVALID_HANDLE_VALUE) {
        TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
            fcb->file_number);
        records_read = 0;
        AL_result = 0x01; /* end of file, no data read */
    } else {
        position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
        if (position != record_number * fcb->logical_record_size) {
            TRACE("seek(%d, %ld, 0) failed with %ld\n",
                  fcb->file_number, record_number * fcb->logical_record_size, position);
            records_read = 0;
            AL_result = 0x01; /* end of file, no data read */
        } else {
1721
            disk_transfer_area = INT21_GetCurrentDTA(context);
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
            records_requested = CX_reg(context);
            bytes_requested = (UINT) records_requested * fcb->logical_record_size;
            bytes_read = _lread((HFILE) handle, disk_transfer_area, bytes_requested);
            if (bytes_read != bytes_requested) {
                TRACE("_lread(%d, %p, %d) failed with %d\n",
                      fcb->file_number, disk_transfer_area, bytes_requested, bytes_read);
                records_read = bytes_read / fcb->logical_record_size;
                if (bytes_read % fcb->logical_record_size == 0) {
                    AL_result = 0x01; /* end of file, no data read */
                } else {
                    records_read++;
                    memset(&disk_transfer_area[bytes_read], 0, records_read * fcb->logical_record_size - bytes_read);
                    AL_result = 0x03; /* end of file, partial record read */
                } /* if */
            } else {
                TRACE("successful read %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
                    bytes_read, record_number, position, fcb->file_number, handle);
                records_read = records_requested;
                AL_result = 0x00; /* successful */
            } /* if */
        } /* if */
    } /* if */
    record_number += records_read;
    memcpy(fcb->random_access_record_number, &record_number, 4);
    fcb->current_block_number = record_number / 128;
    fcb->record_within_current_block = record_number % 128;
    SET_CX(context, records_read);
    SET_AL(context, AL_result);
}


/***********************************************************************
 *           INT21_RandomBlockWriteToFCB
 *
 * Handler for function 0x28.
 *
 * PARAMS
 *  CX    [I/O] Number of records to write
 *  DX:DX [I/O] File control block (FCB or XFCB) of open file
 *
 * RETURNS (in AL)
 *  0: successful
 *  1: disk full
 *  2: segment wrap in DTA (not returned now)
 *
 * NOTES
 *  Writes several records with the size FCB->logical_record_size from
 *  the disk transfer area to the FCB. The number of records to be
 *  written is specified in the CX register. The position of the first
 *  record is specified with FCB->random_access_record_number. The
 *  FCB->random_access_record_number, the FCB->current_block_number
 *  and FCB->record_within_current_block are updated to point to the
 *  next record after the records written. The CX register is set to
 *  the number of successfully written records.
 */
static void INT21_RandomBlockWriteToFCB( CONTEXT86 *context )
{
    struct FCB *fcb;
    struct XFCB *xfcb;
    HANDLE handle;
    DWORD record_number;
    long position;
    BYTE *disk_transfer_area;
    UINT records_requested;
    UINT bytes_requested;
    UINT bytes_written;
    UINT records_written;
    BYTE AL_result;

    fcb = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    if (fcb->drive_number == 0xff) {
        xfcb = (struct XFCB *) fcb;
        fcb = (struct FCB *) xfcb->fcb;
    } /* if */

    memcpy(&record_number, fcb->random_access_record_number, 4);
    handle = DosFileHandleToWin32Handle((HFILE16) fcb->file_number);
    if (handle == INVALID_HANDLE_VALUE) {
        TRACE("DosFileHandleToWin32Handle(%d) failed: INVALID_HANDLE_VALUE\n",
            fcb->file_number);
        records_written = 0;
        AL_result = 0x01; /* disk full */
    } else {
        position = SetFilePointer(handle, record_number * fcb->logical_record_size, NULL, 0);
        if (position != record_number * fcb->logical_record_size) {
            TRACE("seek(%d, %ld, 0) failed with %ld\n",
                  fcb->file_number, record_number * fcb->logical_record_size, position);
            records_written = 0;
            AL_result = 0x01; /* disk full */
        } else {
1812
            disk_transfer_area = INT21_GetCurrentDTA(context);
1813 1814
            records_requested = CX_reg(context);
            bytes_requested = (UINT) records_requested * fcb->logical_record_size;
1815
            bytes_written = _lwrite((HFILE) handle, (LPCSTR)disk_transfer_area, bytes_requested);
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
            if (bytes_written != bytes_requested) {
                TRACE("_lwrite(%d, %p, %d) failed with %d\n",
                      fcb->file_number, disk_transfer_area, bytes_requested, bytes_written);
                records_written = bytes_written / fcb->logical_record_size;
                AL_result = 0x01; /* disk full */
            } else {
                TRACE("successful write %d bytes from record %ld (position %ld) of file %d (handle %p)\n",
                    bytes_written, record_number, position, fcb->file_number, handle);
                records_written = records_requested;
                AL_result = 0x00; /* successful */
            } /* if */
        } /* if */
    } /* if */
    record_number += records_written;
    memcpy(fcb->random_access_record_number, &record_number, 4);
    fcb->current_block_number = record_number / 128;
    fcb->record_within_current_block = record_number % 128;
    SET_CX(context, records_written);
    SET_AL(context, AL_result);
}


1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
/***********************************************************************
 *           INT21_CreateDirectory
 *
 * Handler for:
 * - function 0x39
 * - subfunction 0x39 of function 0x71
 * - subfunction 0xff of function 0x43 (CL == 0x39)
 */
static BOOL INT21_CreateDirectory( CONTEXT86 *context )
{
    WCHAR dirW[MAX_PATH];
    char *dirA = CTX_SEG_OFF_TO_LIN(context,
                                    context->SegDs, 
                                    context->Edx);

    TRACE( "CREATE DIRECTORY %s\n", dirA );

    MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);

    if (CreateDirectoryW(dirW, NULL))
        return TRUE;

    /*
     * FIXME: CreateDirectory's LastErrors will clash with the ones
     *        used by DOS. AH=39 only returns 3 (path not found) and 
     *        5 (access denied), while CreateDirectory return several
     *        ones. Remap some of them. -Marcus
     */
    switch (GetLastError()) 
    {
    case ERROR_ALREADY_EXISTS:
    case ERROR_FILENAME_EXCED_RANGE:
    case ERROR_DISK_FULL:
        SetLastError(ERROR_ACCESS_DENIED);
        break;
    default: 
        break;
    }

    return FALSE;
}


1881 1882 1883 1884 1885 1886 1887 1888
/***********************************************************************
 *           INT21_ExtendedCountryInformation
 *
 * Handler for function 0x65.
 */
static void INT21_ExtendedCountryInformation( CONTEXT86 *context )
{
    BYTE *dataptr = CTX_SEG_OFF_TO_LIN( context, context->SegEs, context->Edi );
1889 1890
    BYTE buffsize = CX_reg (context);
    
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
    TRACE( "GET EXTENDED COUNTRY INFORMATION, subfunction %02x\n",
           AL_reg(context) );

    /*
     * Check subfunctions that are passed country and code page.
     */
    if (AL_reg(context) >= 0x01 && AL_reg(context) <= 0x07)
    {
        WORD country = DX_reg(context);
        WORD codepage = BX_reg(context);

        if (country != 0xffff && country != INT21_GetSystemCountryCode())
            FIXME( "Requested info on non-default country %04x\n", country );

        if (codepage != 0xffff && codepage != GetOEMCP())
            FIXME( "Requested info on non-default code page %04x\n", codepage );
    }

    switch (AL_reg(context)) {
    case 0x00: /* SET GENERAL INTERNATIONALIZATION INFO */
        INT_BARF( context, 0x21 );
        SET_CFLAG( context );
        break;

    case 0x01: /* GET GENERAL INTERNATIONALIZATION INFO */
        TRACE( "Get general internationalization info\n" );
        dataptr[0] = 0x01; /* Info ID */
        *(WORD*)(dataptr+1) = 38; /* Size of the following info */
        *(WORD*)(dataptr+3) = INT21_GetSystemCountryCode(); /* Country ID */
        *(WORD*)(dataptr+5) = GetOEMCP(); /* Code page */
1921 1922 1923 1924 1925 1926 1927
        /* FIXME: fill buffer partially up to buffsize bytes*/
        if (buffsize >= 0x29){
            INT21_FillCountryInformation( dataptr + 7 );
            SET_CX( context, 0x29 ); /* Size of returned info */
        }else{
            SET_CX( context, 0x07 ); /* Size of returned info */        
        }
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
        break;
        
    case 0x02: /* GET POINTER TO UPPERCASE TABLE */
    case 0x04: /* GET POINTER TO FILENAME UPPERCASE TABLE */
        TRACE( "Get pointer to uppercase table\n" );
        dataptr[0] = AL_reg(context); /* Info ID */
        *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
                                           offsetof(INT21_HEAP, uppercase_size) );
        SET_CX( context, 5 ); /* Size of returned info */
        break;

    case 0x03: /* GET POINTER TO LOWERCASE TABLE */
        TRACE( "Get pointer to lowercase table\n" );
        dataptr[0] = 0x03; /* Info ID */
        *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
                                           offsetof(INT21_HEAP, lowercase_size) );
        SET_CX( context, 5 ); /* Size of returned info */
        break;

    case 0x05: /* GET POINTER TO FILENAME TERMINATOR TABLE */
        TRACE("Get pointer to filename terminator table\n");
        dataptr[0] = 0x05; /* Info ID */
        *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
                                           offsetof(INT21_HEAP, filename_size) );
        SET_CX( context, 5 ); /* Size of returned info */
        break;

    case 0x06: /* GET POINTER TO COLLATING SEQUENCE TABLE */
        TRACE("Get pointer to collating sequence table\n");
        dataptr[0] = 0x06; /* Info ID */
        *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
                                           offsetof(INT21_HEAP, collating_size) );
        SET_CX( context, 5 ); /* Size of returned info */
        break;

    case 0x07: /* GET POINTER TO DBCS LEAD BYTE TABLE */
        TRACE("Get pointer to DBCS lead byte table\n");
        dataptr[0] = 0x07; /* Info ID */
        *(DWORD*)(dataptr+1) = MAKESEGPTR( INT21_GetHeapSelector( context ),
                                           offsetof(INT21_HEAP, dbcs_size) );
        SET_CX( context, 5 ); /* Size of returned info */
        break;

    case 0x20: /* CAPITALIZE CHARACTER */
    case 0xa0: /* CAPITALIZE FILENAME CHARACTER */
        TRACE("Convert char to uppercase\n");
        SET_DL( context, toupper(DL_reg(context)) );
        break;

    case 0x21: /* CAPITALIZE STRING */
    case 0xa1: /* CAPITALIZE COUNTED FILENAME STRING */
        TRACE("Convert string to uppercase with length\n");
        {
            char *ptr = (char *)CTX_SEG_OFF_TO_LIN( context,
                                                    context->SegDs,
                                                    context->Edx );
            WORD len = CX_reg(context);
            while (len--) { *ptr = toupper(*ptr); ptr++; }
        }
        break;

    case 0x22: /* CAPITALIZE ASCIIZ STRING */
    case 0xa2: /* CAPITALIZE ASCIIZ FILENAME */
        TRACE("Convert ASCIIZ string to uppercase\n");
1992 1993 1994 1995
        {
            char *p = CTX_SEG_OFF_TO_LIN( context, context->SegDs, context->Edx );
            for ( ; *p; p++) *p = toupper(*p);
        }
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
        break;

    case 0x23: /* DETERMINE IF CHARACTER REPRESENTS YES/NO RESPONSE */
        INT_BARF( context, 0x21 );
        SET_CFLAG( context );
        break;

    default:
        INT_BARF( context, 0x21 );
        SET_CFLAG(context);
        break;
    }
}


2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
/***********************************************************************
 *           INT21_FileAttributes
 *
 * Handler for:
 * - function 0x43
 * - subfunction 0x43 of function 0x71
 */
static BOOL INT21_FileAttributes( CONTEXT86 *context, 
                                  BYTE       subfunction,
                                  BOOL       islong )
{
    WCHAR fileW[MAX_PATH];
    char *fileA = CTX_SEG_OFF_TO_LIN(context, 
                                     context->SegDs, 
                                     context->Edx);
    HANDLE   handle;
    BOOL     status;
    FILETIME filetime;
    DWORD    result;
    WORD     date, time;

    switch (subfunction)
    {
    case 0x00: /* GET FILE ATTRIBUTES */
        TRACE( "GET FILE ATTRIBUTES for %s\n", fileA );
        MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

        result = GetFileAttributesW( fileW );
2039
        if (result == INVALID_FILE_ATTRIBUTES)
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
            return FALSE;
        else
        {
            SET_CX( context, (WORD)result );
            if (!islong)
                SET_AX( context, (WORD)result ); /* DR DOS */
        }
        break;

    case 0x01: /* SET FILE ATTRIBUTES */
        TRACE( "SET FILE ATTRIBUTES 0x%02x for %s\n", 
               CX_reg(context), fileA );
        MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

        if (!SetFileAttributesW( fileW, CX_reg(context) ))
            return FALSE;
        break;

    case 0x02: /* GET COMPRESSED FILE SIZE */
        TRACE( "GET COMPRESSED FILE SIZE for %s\n", fileA );
        MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

        result = GetCompressedFileSizeW( fileW, NULL );
        if (result == INVALID_FILE_SIZE)
            return FALSE;
        else
        {
            SET_AX( context, LOWORD(result) );
            SET_DX( context, HIWORD(result) );
        }
        break;

    case 0x03: /* SET FILE LAST-WRITTEN DATE AND TIME */
        if (!islong)
            INT_BARF( context, 0x21 );
        else
        {
            TRACE( "SET FILE LAST-WRITTEN DATE AND TIME, file %s\n", fileA );
            MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

            handle = CreateFileW( fileW, GENERIC_WRITE, 
                                  FILE_SHARE_READ | FILE_SHARE_WRITE, 
                                  NULL, OPEN_EXISTING, 0, 0 );
            if (handle == INVALID_HANDLE_VALUE)
                return FALSE;

            DosDateTimeToFileTime( DI_reg(context), 
                                   CX_reg(context),
                                   &filetime );
            status = SetFileTime( handle, NULL, NULL, &filetime );

            CloseHandle( handle );
            return status;
        }
        break;

    case 0x04: /* GET FILE LAST-WRITTEN DATE AND TIME */
        if (!islong)
            INT_BARF( context, 0x21 );
        else
        {
            TRACE( "GET FILE LAST-WRITTEN DATE AND TIME, file %s\n", fileA );
            MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

            handle = CreateFileW( fileW, GENERIC_READ, 
                                  FILE_SHARE_READ | FILE_SHARE_WRITE, 
                                  NULL, OPEN_EXISTING, 0, 0 );
            if (handle == INVALID_HANDLE_VALUE)
                return FALSE;

            status = GetFileTime( handle, NULL, NULL, &filetime );
            if (status)
            {
                FileTimeToDosDateTime( &filetime, &date, &time );
                SET_DI( context, date );
                SET_CX( context, time );
            }

            CloseHandle( handle );
            return status;
        }
        break;

    case 0x05: /* SET FILE LAST ACCESS DATE */
        if (!islong)
            INT_BARF( context, 0x21 );
        else
        {
            TRACE( "SET FILE LAST ACCESS DATE, file %s\n", fileA );
            MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

            handle = CreateFileW( fileW, GENERIC_WRITE, 
                                  FILE_SHARE_READ | FILE_SHARE_WRITE, 
                                  NULL, OPEN_EXISTING, 0, 0 );
            if (handle == INVALID_HANDLE_VALUE)
                return FALSE;

            DosDateTimeToFileTime( DI_reg(context), 
                                   0,
                                   &filetime );
            status = SetFileTime( handle, NULL, &filetime, NULL );

            CloseHandle( handle );
            return status;
        }
        break;

    case 0x06: /* GET FILE LAST ACCESS DATE */
        if (!islong)
            INT_BARF( context, 0x21 );
        else
        {
            TRACE( "GET FILE LAST ACCESS DATE, file %s\n", fileA );
            MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

            handle = CreateFileW( fileW, GENERIC_READ, 
                                  FILE_SHARE_READ | FILE_SHARE_WRITE, 
                                  NULL, OPEN_EXISTING, 0, 0 );
            if (handle == INVALID_HANDLE_VALUE)
                return FALSE;

            status = GetFileTime( handle, NULL, &filetime, NULL );
            if (status)
            {
                FileTimeToDosDateTime( &filetime, &date, NULL );
                SET_DI( context, date );
            }

            CloseHandle( handle );
            return status;
        }
        break;

    case 0x07: /* SET FILE CREATION DATE AND TIME */
        if (!islong)
            INT_BARF( context, 0x21 );
        else
        {
            TRACE( "SET FILE CREATION DATE AND TIME, file %s\n", fileA );

            handle = CreateFileW( fileW, GENERIC_WRITE,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE, 
                                  NULL, OPEN_EXISTING, 0, 0 );
            if (handle == INVALID_HANDLE_VALUE)
                return FALSE;
            
            /*
             * FIXME: SI has number of 10-millisecond units past time in CX.
             */
            DosDateTimeToFileTime( DI_reg(context),
                                   CX_reg(context),
                                   &filetime );
            status = SetFileTime( handle, &filetime, NULL, NULL );

            CloseHandle( handle );
            return status;
        }
        break;

    case 0x08: /* GET FILE CREATION DATE AND TIME */
        if (!islong)
            INT_BARF( context, 0x21 );
        else
        {
            TRACE( "GET FILE CREATION DATE AND TIME, handle %d\n",
                   BX_reg(context) );

            handle = CreateFileW( fileW, GENERIC_READ, 
                                  FILE_SHARE_READ | FILE_SHARE_WRITE, 
                                  NULL, OPEN_EXISTING, 0, 0 );
            if (handle == INVALID_HANDLE_VALUE)
                return FALSE;

            status = GetFileTime( handle, &filetime, NULL, NULL );
            if (status)
            {            
                FileTimeToDosDateTime( &filetime, &date, &time );
                SET_DI( context, date );
                SET_CX( context, time );
                /*
                 * FIXME: SI has number of 10-millisecond units past 
                 *        time in CX.
                 */
                SET_SI( context, 0 );
            }

            CloseHandle(handle);
            return status;
        }
        break;

    case 0xff: /* EXTENDED-LENGTH FILENAME OPERATIONS */
        if (islong || context->Ebp != 0x5053)
            INT_BARF( context, 0x21 );
        else
        {
            switch(CL_reg(context))
            {
            case 0x39:
                if (!INT21_CreateDirectory( context ))
                    return FALSE;
                break;

            case 0x56:
                if (!INT21_RenameFile( context ))
                    return FALSE;
                break;

            default:
                INT_BARF( context, 0x21 );
            }
        }
        break;

    default:
        INT_BARF( context, 0x21 );
    }

    return TRUE;
}


2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
/***********************************************************************
 *           INT21_FileDateTime
 *
 * Handler for function 0x57.
 */
static BOOL INT21_FileDateTime( CONTEXT86 *context )
{
    HANDLE   handle = DosFileHandleToWin32Handle(BX_reg(context));
    FILETIME filetime;
    WORD     date, time;

    switch (AL_reg(context)) {
    case 0x00:  /* Get last-written stamp */
        TRACE( "GET FILE LAST-WRITTEN DATE AND TIME, handle %d\n",
               BX_reg(context) );
        {
            if (!GetFileTime( handle, NULL, NULL, &filetime ))
                return FALSE;
            FileTimeToDosDateTime( &filetime, &date, &time );
            SET_DX( context, date );
            SET_CX( context, time );
            break;
        }

    case 0x01:  /* Set last-written stamp */
        TRACE( "SET FILE LAST-WRITTEN DATE AND TIME, handle %d\n",
               BX_reg(context) );
        {
            DosDateTimeToFileTime( DX_reg(context), 
                                   CX_reg(context),
                                   &filetime );
            if (!SetFileTime( handle, NULL, NULL, &filetime ))
                return FALSE;
            break;
        }

    case 0x04:  /* Get last access stamp, DOS 7 */
        TRACE( "GET FILE LAST ACCESS DATE AND TIME, handle %d\n",
               BX_reg(context) );
        {
            if (!GetFileTime( handle, NULL, &filetime, NULL ))
                return FALSE;
            FileTimeToDosDateTime( &filetime, &date, &time );
            SET_DX( context, date );
            SET_CX( context, time );
            break;
        }

    case 0x05:  /* Set last access stamp, DOS 7 */
        TRACE( "SET FILE LAST ACCESS DATE AND TIME, handle %d\n",
               BX_reg(context) );
        {
            DosDateTimeToFileTime( DX_reg(context), 
                                   CX_reg(context),
                                   &filetime );
            if (!SetFileTime( handle, NULL, &filetime, NULL ))
                return FALSE;
            break;
        }

    case 0x06:  /* Get creation stamp, DOS 7 */
        TRACE( "GET FILE CREATION DATE AND TIME, handle %d\n",
               BX_reg(context) );
        {
            if (!GetFileTime( handle, &filetime, NULL, NULL ))
                return FALSE;
            FileTimeToDosDateTime( &filetime, &date, &time );
            SET_DX( context, date );
            SET_CX( context, time );
            /*
             * FIXME: SI has number of 10-millisecond units past time in CX.
             */
            SET_SI( context, 0 );
            break;
        }

    case 0x07:  /* Set creation stamp, DOS 7 */
        TRACE( "SET FILE CREATION DATE AND TIME, handle %d\n",
               BX_reg(context) );
        {
            /*
             * FIXME: SI has number of 10-millisecond units past time in CX.
             */
            DosDateTimeToFileTime( DX_reg(context), 
                                   CX_reg(context),
                                   &filetime );
            if (!SetFileTime( handle, &filetime, NULL, NULL ))
                return FALSE;
            break;
        }

    default:
        INT_BARF( context, 0x21 );
        break;
    }

    return TRUE;
}


2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
/***********************************************************************
 *           INT21_GetPSP
 *
 * Handler for functions 0x51 and 0x62.
 */
static void INT21_GetPSP( CONTEXT86 *context )
{
    TRACE( "GET CURRENT PSP ADDRESS (%02x)\n", AH_reg(context) );

    /*
     * FIXME: should we return the original DOS PSP upon
     *        Windows startup ? 
     */
    if (!ISV86(context) && DOSVM_IsWin16())
        SET_BX( context, LOWORD(GetCurrentPDB16()) );
    else
        SET_BX( context, DOSVM_psp );
}

2381 2382 2383 2384 2385 2386
static inline void setword( BYTE *ptr, WORD w )
{
    ptr[0] = (BYTE)w;
    ptr[1] = (BYTE)(w >> 8);
}

2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
static void CreateBPB(int drive, BYTE *data, BOOL16 limited)
/* limited == TRUE is used with INT 0x21/0x440d */
{
    /* FIXME: we're forcing some values without checking that those are valid */
    if (drive > 1) 
    {
        setword(data, 512);
        data[2] = 2;
        setword(&data[3], 0);
        data[5] = 2;
        setword(&data[6], 240);
        setword(&data[8], 64000);
        data[0x0a] = 0xf8;
        setword(&data[0x0b], 40);
        setword(&data[0x0d], 56);
        setword(&data[0x0f], 2);
        setword(&data[0x11], 0);
        if (!limited) 
        {
            setword(&data[0x1f], 800);
            data[0x21] = 5;
            setword(&data[0x22], 1);
        }
    }
    else
    { /* 1.44mb */
        setword(data, 512);
        data[2] = 2;
        setword(&data[3], 0);
        data[5] = 2;
        setword(&data[6], 240);
        setword(&data[8], 2880);
        data[0x0a] = 0xf8;
        setword(&data[0x0b], 6);
        setword(&data[0x0d], 18);
        setword(&data[0x0f], 2);
        setword(&data[0x11], 0);
        if (!limited) 
        {
            setword(&data[0x1f], 80);
            data[0x21] = 7;
            setword(&data[0x22], 2);
        }
    }
}
2432

2433 2434 2435 2436 2437 2438
inline DWORD INT21_Ioctl_CylHeadSect2Lin(DWORD cyl, WORD head, WORD sec, WORD cyl_cnt, WORD head_cnt, WORD sec_cnt)
{
    DWORD res = (cyl * head_cnt*sec_cnt + head * sec_cnt + sec);
    return res;
}

2439 2440 2441 2442 2443 2444 2445
/***********************************************************************
 *           INT21_Ioctl_Block
 *
 * Handler for block device IOCTLs.
 */
static void INT21_Ioctl_Block( CONTEXT86 *context )
{
2446 2447 2448 2449 2450 2451 2452 2453
    BYTE *dataptr;
    BYTE  drive = INT21_MapDrive( BL_reg(context) );
    WCHAR drivespec[4] = {'A', ':', '\\', 0};
    UINT  drivetype;

    drivespec[0] += drive;
    drivetype = GetDriveTypeW( drivespec );

2454
    RESET_CFLAG(context);
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
    if (drivetype == DRIVE_UNKNOWN || drivetype == DRIVE_NO_ROOT_DIR)
    {
        TRACE( "IOCTL - SUBFUNCTION %d - INVALID DRIVE %c:\n", 
               AL_reg(context), 'A' + drive );
        SetLastError( ERROR_INVALID_DRIVE );
        SET_AX( context, ERROR_INVALID_DRIVE );
        SET_CFLAG( context );
        return;
    }

    switch (AL_reg(context))
    {
    case 0x04: /* READ FROM BLOCK DEVICE CONTROL CHANNEL */
    case 0x05: /* WRITE TO BLOCK DEVICE CONTROL CHANNEL */
        INT_BARF( context, 0x21 );
        break;

    case 0x08: /* CHECK IF BLOCK DEVICE REMOVABLE */
        TRACE( "IOCTL - CHECK IF BLOCK DEVICE REMOVABLE - %c:\n",
               'A' + drive );

        if (drivetype == DRIVE_REMOVABLE)
            SET_AX( context, 0 ); /* removable */
        else
            SET_AX( context, 1 ); /* not removable */
        break;

    case 0x09: /* CHECK IF BLOCK DEVICE REMOTE */
        TRACE( "IOCTL - CHECK IF BLOCK DEVICE REMOTE - %c:\n",
               'A' + drive );

        if (drivetype == DRIVE_REMOTE)
            SET_DX( context, (1<<9) | (1<<12) ); /* remote + no direct IO */
        else
            SET_DX( context, 0 ); /* FIXME: use driver attr here */
        break;

    case 0x0d: /* GENERIC BLOCK DEVICE REQUEST */
2493
        /* Get pointer to IOCTL parameter block */
2494 2495 2496 2497 2498 2499 2500 2501
        dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);

        switch (CX_reg(context))
        {
        case 0x0841: /* write logical device track */
            TRACE( "GENERIC IOCTL - Write logical device track - %c:\n",
                   'A' + drive);
            {
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
                WORD head   = *(WORD *)(dataptr+1);
                WORD cyl    = *(WORD *)(dataptr+3);
                WORD sect   = *(WORD *)(dataptr+5);
                WORD nrsect = *(WORD *)(dataptr+7);
                BYTE *data  = CTX_SEG_OFF_TO_LIN(context, *(WORD *)(dataptr+11), *(WORD *)(dataptr+9));
                WORD cyl_cnt, head_cnt, sec_cnt;

                /* FIXME: we're faking some values here */
                if (drive > 1)
                {
                    /* cyl_cnt = 0x300;
                    head_cnt = 16;
                    sec_cnt = 255; */
                    SET_AX( context, ERROR_WRITE_FAULT );
                    SET_CFLAG(context);
                    break;
                }
                else
                { /* floppy */
                    cyl_cnt = 80;
                    head_cnt = 2;
                    sec_cnt = 18;
                }
2525

2526
                if (!DOSVM_RawWrite(drive, INT21_Ioctl_CylHeadSect2Lin(cyl, head, sect, cyl_cnt, head_cnt, sec_cnt), nrsect, data, FALSE))
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
                {
                    SET_AX( context, ERROR_WRITE_FAULT );
                    SET_CFLAG(context);
                }
            }
            break;

        case 0x084a: /* lock logical volume */
            TRACE( "GENERIC IOCTL - Lock logical volume, level %d mode %d - %c:\n",
                   BH_reg(context), DX_reg(context), 'A' + drive );
            break;

        case 0x0860: /* get device parameters */
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558
            /* FIXME: we're faking some values here */
            /* used by w4wgrp's winfile */
            memset(dataptr, 0, 0x20); /* DOS 6.22 uses 0x20 bytes */
            dataptr[0] = 0x04;
            dataptr[6] = 0; /* media type */
            if (drive > 1)
            {
                dataptr[1] = 0x05; /* fixed disk */
                setword(&dataptr[2], 0x01); /* non removable */
                setword(&dataptr[4], 0x300); /* # of cylinders */
            }
            else
            {
                dataptr[1] = 0x07; /* block dev, floppy */
                setword(&dataptr[2], 0x02); /* removable */
                setword(&dataptr[4], 80); /* # of cylinders */
            }
            CreateBPB(drive, &dataptr[7], TRUE);
            RESET_CFLAG(context);
2559 2560 2561 2562 2563 2564
            break;

        case 0x0861: /* read logical device track */
            TRACE( "GENERIC IOCTL - Read logical device track - %c:\n",
                   'A' + drive);
            {
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
                WORD head   = *(WORD *)(dataptr+1);
                WORD cyl    = *(WORD *)(dataptr+3);
                WORD sect   = *(WORD *)(dataptr+5);
                WORD nrsect = *(WORD *)(dataptr+7);
                BYTE *data  = CTX_SEG_OFF_TO_LIN(context, *(WORD *)(dataptr+11), *(WORD *)(dataptr+9));
                WORD cyl_cnt, head_cnt, sec_cnt;

                /* FIXME: we're faking some values here */
                if (drive > 1)
                {
                    cyl_cnt = 0x300;
                    head_cnt = 16;
                    sec_cnt = 255;
                }
                else
                { /* floppy */
                    cyl_cnt = 80;
                    head_cnt = 2;
                    sec_cnt = 18;
                }
2585

2586
                if (!DOSVM_RawRead(drive, INT21_Ioctl_CylHeadSect2Lin(cyl, head, sect, cyl_cnt, head_cnt, sec_cnt), nrsect, data, FALSE))
2587 2588 2589 2590 2591 2592 2593 2594
                {
                    SET_AX( context, ERROR_READ_FAULT );
                    SET_CFLAG(context);
                }
            }
            break;

        case 0x0866: /* get volume serial number */
2595 2596 2597 2598 2599 2600 2601 2602
            {
                WCHAR	label[12],fsname[9];
                DWORD	serial;

                drivespec[0] += drive;
                GetVolumeInformationW(drivespec, label, 12, &serial, NULL, NULL, fsname, 9);
                *(WORD*)dataptr	= 0;
                memcpy(dataptr+2,&serial,4);
2603 2604
                WideCharToMultiByte(CP_OEMCP, 0, label, 11, (LPSTR)dataptr + 6, 11, NULL, NULL);
                WideCharToMultiByte(CP_OEMCP, 0, fsname, 8, (LPSTR)dataptr + 17, 8, NULL, NULL);
2605
            }
2606 2607 2608 2609 2610 2611 2612 2613
            break;

        case 0x086a: /* unlock logical volume */
            TRACE( "GENERIC IOCTL - Logical volume unlocked - %c:\n", 
                   'A' + drive );
            break;

        case 0x086f: /* get drive map information */
2614 2615 2616 2617
            memset(dataptr+1, '\0', dataptr[0]-1);
            dataptr[1] = dataptr[0];
            dataptr[2] = 0x07; /* protected mode driver; no eject; no notification */
            dataptr[3] = 0xFF; /* no physical drive */
2618 2619 2620
            break;

        case 0x0872:
2621
            /* Trial and error implementation */
2622 2623
            SET_AX( context, drivetype == DRIVE_UNKNOWN ? 0x0f : 0x01 );
            SET_CFLAG(context);	/* Seems to be set all the time */
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
            break;

        default:
            INT_BARF( context, 0x21 );            
        }
        break;

    case 0x0e: /* GET LOGICAL DRIVE MAP */
        TRACE( "IOCTL - GET LOGICAL DRIVE MAP - %c:\n",
               'A' + drive );
        /* FIXME: this is not correct if drive has mappings */
        SET_AL( context, 0 ); /* drive has no mapping */
        break;

    case 0x0f: /* SET LOGICAL DRIVE MAP */
2639 2640 2641 2642
        TRACE("IOCTL - SET LOGICAL DRIVE MAP for drive %s\n",
              INT21_DriveName( BL_reg(context)));
        /* FIXME: as of today, we don't support logical drive mapping... */
        SET_AL( context, 0 );
2643 2644 2645 2646 2647 2648
        break;

    case 0x11: /* QUERY GENERIC IOCTL CAPABILITY */
    default:
        INT_BARF( context, 0x21 );
    }
2649 2650 2651
}


2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
/***********************************************************************
 *           INT21_IoctlScsiMgrHandler
 *
 * IOCTL handler for the SCSIMGR device.
 */
static void INT21_IoctlScsiMgrHandler( CONTEXT86 *context )
{
    switch (AL_reg(context))
    {
    case 0x00: /* GET DEVICE INFORMATION */
        SET_DX( context, 0xc0c0 );
        break;

    case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
        DOSVM_ASPIHandler(context);
        break;

    case 0x0a: /* CHECK IF HANDLE IS REMOTE */
        SET_DX( context, 0 );
        break;

    case 0x01: /* SET DEVICE INFORMATION */
    case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
    case 0x06: /* GET INPUT STATUS */
    case 0x07: /* GET OUTPUT STATUS */
    case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
    case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
    default:
        INT_BARF( context, 0x21 );
        break;
    }
}


/***********************************************************************
 *           INT21_IoctlEMSHandler
 *
 * IOCTL handler for the EMXXXX0 device.
 */
static void INT21_IoctlEMSHandler( CONTEXT86 *context )
{
    EMS_Ioctl_Handler(context);
}


/***********************************************************************
 *           INT21_IoctlHPScanHandler
 *
 * IOCTL handler for the HPSCAN device.
 */
static void INT21_IoctlHPScanHandler( CONTEXT86 *context )
{
    switch (AL_reg(context))
    {
    case 0x00: /* GET DEVICE INFORMATION */
        SET_DX( context, 0xc0c0 );
        break;

    case 0x0a: /* CHECK IF HANDLE IS REMOTE */
        SET_DX( context, 0 );
        break;

    case 0x01: /* SET DEVICE INFORMATION */
    case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
    case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
    case 0x06: /* GET INPUT STATUS */
    case 0x07: /* GET OUTPUT STATUS */
    case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
    case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
    default:
        INT_BARF( context, 0x21 );
        break;
    }
}


2728 2729 2730 2731 2732 2733 2734
/***********************************************************************
 *           INT21_Ioctl_Char
 *
 * Handler for character device IOCTLs.
 */
static void INT21_Ioctl_Char( CONTEXT86 *context )
{
2735 2736
    struct stat st;
    int status, i, fd;
2737
    int IsConsoleIOHandle = 0;
2738 2739
    HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));

2740
    status = wine_server_handle_to_fd( handle, 0, &fd, NULL );
2741
    if (status)
2742
    {
2743 2744 2745 2746 2747
        if( VerifyConsoleIoHandle( handle))
            IsConsoleIOHandle = 1;
        else {
            SET_AX( context, RtlNtStatusToDosError(status) );
            SET_CFLAG( context );
2748 2749
            return;
        }
2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
    } else {
        fstat( fd, &st );
        IsConsoleIOHandle = isatty( fd);
        wine_server_release_fd( handle, fd );
        for (i = 0; i < NB_MAGIC_DEVICES; i++)
        {
            if (!magic_devices[i].handle) continue;
            if (magic_devices[i].dev == st.st_dev &&
                    magic_devices[i].ino == st.st_ino)
            {
                /* found it */
                magic_devices[i].ioctl_handler( context );
                return;
            }
        }
2765 2766
    }

2767 2768
    /* no magic device found, do default handling */

2769 2770 2771 2772
    switch (AL_reg(context))
    {
    case 0x00: /* GET DEVICE INFORMATION */
        TRACE( "IOCTL - GET DEVICE INFORMATION - %d\n", BX_reg(context) );
2773
        if (IsConsoleIOHandle || S_ISCHR(st.st_mode))
2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786
        {
            /*
             * Returns attribute word in DX: 
             *   Bit 14 - Device driver can process IOCTL requests.
             *   Bit 13 - Output until busy supported.
             *   Bit 11 - Driver supports OPEN/CLOSE calls.
             *   Bit  8 - Unknown.
             *   Bit  7 - Set (indicates device).
             *   Bit  6 - EOF on input.
             *   Bit  5 - Raw (binary) mode.
             *   Bit  4 - Device is special (uses int29).
             *   Bit  3 - Clock device.
             *   Bit  2 - NUL device.
2787 2788
             *   Bit  1 - Console output device.
             *   Bit  0 - Console input device.
2789
             */
2790
            SET_DX( context, IsConsoleIOHandle ? 0x80c3 : 0x80c0 /* FIXME */ );
2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
        }
        else
        {
            /*
             * Returns attribute word in DX: 
             *   Bit 15    - File is remote.
             *   Bit 14    - Don't set file date/time on closing.
             *   Bit 11    - Media not removable.
             *   Bit  8    - Generate int24 if no disk space on write 
             *               or read past end of file
             *   Bit  7    - Clear (indicates file).
             *   Bit  6    - File has not been written.
             *   Bit  5..0 - Drive number (0=A:,...)
             *
             * FIXME: Should check if file is on remote or removable drive.
             * FIXME: Should use drive file is located on (and not current).
             */
            SET_DX( context, 0x0140 + INT21_GetCurrentDrive() );
        }
        break;

    case 0x0a: /* CHECK IF HANDLE IS REMOTE */
        TRACE( "IOCTL - CHECK IF HANDLE IS REMOTE - %d\n", BX_reg(context) );
        /*
         * Returns attribute word in DX:
         *   Bit 15 - Set if remote.
         *   Bit 14 - Set if date/time not set on close.
         *
         * FIXME: Should check if file is on remote drive.
         */
        SET_DX( context, 0 );
        break;

2824 2825 2826 2827 2828
    case 0x01: /* SET DEVICE INFORMATION */
    case 0x02: /* READ FROM CHARACTER DEVICE CONTROL CHANNEL */
    case 0x03: /* WRITE TO CHARACTER DEVICE CONTROL CHANNEL */
    case 0x06: /* GET INPUT STATUS */
    case 0x07: /* GET OUTPUT STATUS */
2829 2830 2831 2832
    case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
    case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
    default:
        INT_BARF( context, 0x21 );
2833
        break;
2834
    }
2835 2836 2837
}


2838 2839
/***********************************************************************
 *           INT21_Ioctl
2840 2841
 *
 * Handler for function 0x44.
2842 2843
 */
static void INT21_Ioctl( CONTEXT86 *context )
2844
{
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
    switch (AL_reg(context))
    {
    case 0x00:
    case 0x01:
    case 0x02:
    case 0x03:
        INT21_Ioctl_Char( context );
        break;

    case 0x04:
    case 0x05:
        INT21_Ioctl_Block( context );
        break;

    case 0x06:
    case 0x07:
        INT21_Ioctl_Char( context );
        break;

    case 0x08:
    case 0x09:
        INT21_Ioctl_Block( context );
        break;

    case 0x0a:
        INT21_Ioctl_Char( context );
        break;

    case 0x0b: /* SET SHARING RETRY COUNT */
        TRACE( "SET SHARING RETRY COUNT: Pause %d, retries %d.\n",
               CX_reg(context), DX_reg(context) );
        if (!CX_reg(context))
        {
            SET_AX( context, 1 );
            SET_CFLAG( context );
        }
        else
        {
2883
            DOSDEV_SetSharingRetry( CX_reg(context), DX_reg(context) );
2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
            RESET_CFLAG( context );
        }
        break;

    case 0x0c:
        INT21_Ioctl_Char( context );
        break;

    case 0x0d:
    case 0x0e:
    case 0x0f:
        INT21_Ioctl_Block( context );
        break;

    case 0x10:
        INT21_Ioctl_Char( context );
        break;

    case 0x11:
        INT21_Ioctl_Block( context );
        break;

    case 0x12: /*  DR DOS - DETERMINE DOS TYPE (OBSOLETE FUNCTION) */
        TRACE( "DR DOS - DETERMINE DOS TYPE (OBSOLETE FUNCTION)\n" );
        SET_CFLAG(context);        /* Error / This is not DR DOS. */
        SET_AX( context, 0x0001 ); /* Invalid function */
        break;

    case 0x52: /* DR DOS - DETERMINE DOS TYPE */
        TRACE( "DR DOS - DETERMINE DOS TYPE\n" );
        SET_CFLAG(context);        /* Error / This is not DR DOS. */
        SET_AX( context, 0x0001 ); /* Invalid function */
        break;

    case 0xe0:  /* Sun PC-NFS API */
        TRACE( "Sun PC-NFS API\n" );
        /* not installed */
        break;

    default:
        INT_BARF( context, 0x21 );
    }
2926
}
2927

2928

2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
/***********************************************************************
 *           INT21_Fat32
 *
 * Handler for function 0x73.
 */
static BOOL INT21_Fat32( CONTEXT86 *context )
{
    switch (AL_reg(context))
    {
    case 0x02: /* FAT32 - GET EXTENDED DPB */
        {
            BYTE drive = INT21_MapDrive( DL_reg(context) );
            WORD *ptr = CTX_SEG_OFF_TO_LIN(context, 
                                           context->SegEs, context->Edi);
            INT21_DPB *target = (INT21_DPB*)(ptr + 1);
            INT21_DPB *source;

            TRACE( "FAT32 - GET EXTENDED DPB %d\n", DL_reg(context) );

            if ( CX_reg(context) < sizeof(INT21_DPB) + 2 || *ptr < sizeof(INT21_DPB) )
            {
                SetLastError( ERROR_BAD_LENGTH );
                return FALSE;
            }

            if ( !INT21_FillDrivePB( drive ) )
            {
                SetLastError( ERROR_INVALID_DRIVE );
                return FALSE;
            }

            source = &INT21_GetHeapPointer()->misc_dpb_list[drive];

            *ptr = sizeof(INT21_DPB);
            memcpy( target, source, sizeof(INT21_DPB));

            if (LOWORD(context->Esi) != 0xF1A6)
            {
                target->driver_header = 0;
                target->next          = 0;
            }
            else
            {
                FIXME( "Caller requested driver and next DPB pointers!\n" );
            }
        }
        break;

2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025
    case 0x03: /* FAT32 - GET EXTENDED FREE SPACE ON DRIVE */
        {
            WCHAR dirW[MAX_PATH];
            char *dirA = CTX_SEG_OFF_TO_LIN( context,
                                             context->SegDs, context->Edx );
            BYTE *data = CTX_SEG_OFF_TO_LIN( context, 
                                             context->SegEs, context->Edi );
            DWORD cluster_sectors;
            DWORD sector_bytes;
            DWORD free_clusters;
            DWORD total_clusters;

            TRACE( "FAT32 - GET EXTENDED FREE SPACE ON DRIVE %s\n", dirA );
            MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);

            if (CX_reg(context) < 44)
            {
                SetLastError( ERROR_BAD_LENGTH );
                return FALSE;
            }

            if (!GetDiskFreeSpaceW( dirW, &cluster_sectors, &sector_bytes,
                                    &free_clusters, &total_clusters ))
                return FALSE;

            *(WORD*) (data +  0) = 44; /* size of structure */
            *(WORD*) (data +  2) = 0;  /* version */
            *(DWORD*)(data +  4) = cluster_sectors;
            *(DWORD*)(data +  8) = sector_bytes;
            *(DWORD*)(data + 12) = free_clusters;
            *(DWORD*)(data + 16) = total_clusters;

            /*
             * Below we have free/total sectors and
             * free/total allocation units without adjustment
             * for compression. We fake both using cluster information.
             */
            *(DWORD*)(data + 20) = free_clusters * cluster_sectors;
            *(DWORD*)(data + 24) = total_clusters * cluster_sectors;
            *(DWORD*)(data + 28) = free_clusters;
            *(DWORD*)(data + 32) = total_clusters;
            
            /*
             * Between (data + 36) and (data + 43) there
             * are eight reserved bytes.
             */
        }
        break;

3026 3027 3028 3029 3030 3031 3032
    default:
        INT_BARF( context, 0x21 );
    }

    return TRUE;
}

3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046
static void INT21_ConvertFindDataWtoA(WIN32_FIND_DATAA *dataA,
                                      const WIN32_FIND_DATAW *dataW)
{
    dataA->dwFileAttributes = dataW->dwFileAttributes;
    dataA->ftCreationTime   = dataW->ftCreationTime;
    dataA->ftLastAccessTime = dataW->ftLastAccessTime;
    dataA->ftLastWriteTime  = dataW->ftLastWriteTime;
    dataA->nFileSizeHigh    = dataW->nFileSizeHigh;
    dataA->nFileSizeLow     = dataW->nFileSizeLow;
    WideCharToMultiByte( CP_OEMCP, 0, dataW->cFileName, -1,
                         dataA->cFileName, sizeof(dataA->cFileName), NULL, NULL );
    WideCharToMultiByte( CP_OEMCP, 0, dataW->cAlternateFileName, -1,
                         dataA->cAlternateFileName, sizeof(dataA->cAlternateFileName), NULL, NULL );
}
3047

3048 3049 3050 3051 3052 3053 3054 3055
/***********************************************************************
 *           INT21_LongFilename
 *
 * Handler for function 0x71.
 */
static void INT21_LongFilename( CONTEXT86 *context )
{
    BOOL bSetDOSExtendedError = FALSE;
3056 3057
    WCHAR pathW[MAX_PATH];
    char* pathA;
3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069

    if (HIBYTE(HIWORD(GetVersion16())) < 0x07)
    {
        TRACE( "LONG FILENAME - functions supported only under DOS7\n" );
        SET_CFLAG( context );
        SET_AL( context, 0 );
        return;
    }

    switch (AL_reg(context))
    {
    case 0x0d: /* RESET DRIVE */
3070
        INT_BARF( context, 0x21 );
3071 3072
        break;

3073 3074 3075 3076 3077
    case 0x39: /* LONG FILENAME - MAKE DIRECTORY */
        if (!INT21_CreateDirectory( context ))
            bSetDOSExtendedError = TRUE;
        break;

3078
    case 0x3a: /* LONG FILENAME - REMOVE DIRECTORY */
3079
        pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3080

3081 3082 3083
        TRACE( "LONG FILENAME - REMOVE DIRECTORY %s\n", pathA);
        MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
        if (!RemoveDirectoryW( pathW )) bSetDOSExtendedError = TRUE;
3084 3085 3086
        break;

    case 0x3b: /* LONG FILENAME - CHANGE DIRECTORY */
3087 3088
        if (!INT21_SetCurrentDirectory( context ))
            bSetDOSExtendedError = TRUE;
3089 3090 3091
        break;

    case 0x41: /* LONG FILENAME - DELETE FILE */
3092
        pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3093

3094 3095
        TRACE( "LONG FILENAME - DELETE FILE %s\n", pathA );
        MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
3096

3097
        if (!DeleteFileW( pathW )) bSetDOSExtendedError = TRUE;
3098 3099 3100
        break;

    case 0x43: /* LONG FILENAME - EXTENDED GET/SET FILE ATTRIBUTES */
3101 3102 3103 3104
        if (!INT21_FileAttributes( context, BL_reg(context), TRUE ))
            bSetDOSExtendedError = TRUE;
        break;

3105
    case 0x47: /* LONG FILENAME - GET CURRENT DIRECTORY */
3106 3107 3108 3109
        if (!INT21_GetCurrentDirectory( context, TRUE ))
            bSetDOSExtendedError = TRUE;
        break;

3110
    case 0x4e: /* LONG FILENAME - FIND FIRST MATCHING FILE */
3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
        {
            HANDLE              handle;
            HGLOBAL16           h16;
            WIN32_FIND_DATAW    dataW;
            WIN32_FIND_DATAA*   dataA;

            pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx);
            TRACE(" LONG FILENAME - FIND FIRST MATCHING FILE for %s\n", pathA);

            MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
            handle = FindFirstFileW(pathW, &dataW);
            
            dataA = (WIN32_FIND_DATAA *)CTX_SEG_OFF_TO_LIN(context, context->SegEs,
                                                           context->Edi);
            if (handle != INVALID_HANDLE_VALUE && 
                (h16 = GlobalAlloc16(GMEM_MOVEABLE, sizeof(handle))))
            {
                HANDLE* ptr = GlobalLock16( h16 );
                *ptr = handle;
                GlobalUnlock16( h16 );
                SET_AX( context, h16 );
                INT21_ConvertFindDataWtoA(dataA, &dataW);
            }
            else
            {           
                if (handle != INVALID_HANDLE_VALUE) FindClose(handle);
                SET_AX( context, INVALID_HANDLE_VALUE16);
                bSetDOSExtendedError = TRUE;
            }
        }
        break;

3143
    case 0x4f: /* LONG FILENAME - FIND NEXT MATCHING FILE */
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167
        {
            HGLOBAL16           h16 = BX_reg(context);
            HANDLE*             ptr;
            WIN32_FIND_DATAW    dataW;
            WIN32_FIND_DATAA*   dataA;

            TRACE("LONG FILENAME - FIND NEXT MATCHING FILE for handle %d\n",
                  BX_reg(context));

            dataA = (WIN32_FIND_DATAA *)CTX_SEG_OFF_TO_LIN(context, context->SegEs,
                                                           context->Edi);

            if (h16 != INVALID_HANDLE_VALUE16 && (ptr = GlobalLock16( h16 )))
            {
                if (!FindNextFileW(*ptr, &dataW)) bSetDOSExtendedError = TRUE;
                else INT21_ConvertFindDataWtoA(dataA, &dataW);
                GlobalUnlock16( h16 );
            }
            else
            {
                SetLastError( ERROR_INVALID_HANDLE );
                bSetDOSExtendedError = TRUE;
            }
        }
3168 3169 3170
        break;

    case 0x56: /* LONG FILENAME - RENAME FILE */
3171 3172
        if (!INT21_RenameFile(context))
            bSetDOSExtendedError = TRUE;
3173 3174 3175
        break;

    case 0x60: /* LONG FILENAME - CONVERT PATH */
3176 3177 3178 3179 3180
        {
            WCHAR   res[MAX_PATH];

            switch (CL_reg(context))
            {
3181 3182 3183 3184 3185 3186
            case 0x00:  /* "truename" - Canonicalize path */
                /* 
                 * FIXME: This is not 100% equal to 0x01 case, 
                 *        if you fix this, fix int21 subfunction 0x60, too.
                 */

3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219
            case 0x01:  /* Get short filename or path */
                MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
                if (!GetShortPathNameW(pathW, res, 67))
                    bSetDOSExtendedError = TRUE;
                else
                {
                    SET_AX( context, 0 );
                    WideCharToMultiByte(CP_OEMCP, 0, res, -1, 
                                        CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi), 
                                        67, NULL, NULL);
                }
                break;
	    
            case 0x02:  /* Get canonical long filename or path */
                MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
                if (!GetFullPathNameW(pathW, 128, res, NULL))
                    bSetDOSExtendedError = TRUE;
                else
                {
                    SET_AX( context, 0 );
                    WideCharToMultiByte(CP_OEMCP, 0, res, -1, 
                                        CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi), 
                                        128, NULL, NULL);
                }
                break;
            default:
                FIXME("Unimplemented long file name function:\n");
                INT_BARF( context, 0x21 );
                SET_CFLAG(context);
                SET_AL( context, 0 );
                break;
            }
        }
3220 3221
        break;

3222
    case 0x6c: /* LONG FILENAME - CREATE OR OPEN FILE */
3223 3224 3225 3226 3227
        if (!INT21_CreateFile( context, context->Esi, TRUE,
                               BX_reg(context), DL_reg(context) ))
            bSetDOSExtendedError = TRUE;
        break;

3228
    case 0xa0: /* LONG FILENAME - GET VOLUME INFORMATION */
3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
        {
            DWORD filename_len, flags;
            WCHAR dstW[8];

            pathA = CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Edx);

            TRACE("LONG FILENAME - GET VOLUME INFORMATION for drive having root dir '%s'.\n", pathA);
            SET_AX( context, 0 );
            MultiByteToWideChar(CP_OEMCP, 0, pathA, -1, pathW, MAX_PATH);
            if (!GetVolumeInformationW( pathW, NULL, 0, NULL, &filename_len,
                                        &flags, dstW, 8 ))
            {
                INT_BARF( context, 0x21 );
                SET_CFLAG(context);
                break;
            }
            SET_BX( context, flags | 0x4000 ); /* support for LFN functions */
            SET_CX( context, filename_len );
            SET_DX( context, MAX_PATH ); /* FIXME: which len if DRIVE_SHORT_NAMES ? */
            WideCharToMultiByte(CP_OEMCP, 0, dstW, -1, 
                                CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi), 
                                8, NULL, NULL);
        }
3252 3253
        break;

3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
    case 0xa1: /* LONG FILENAME - "FindClose" - TERMINATE DIRECTORY SEARCH */
        {
            HGLOBAL16 h16 = BX_reg(context);
            HANDLE* ptr;

            TRACE("LONG FILENAME - FINDCLOSE for handle %d\n",
                  BX_reg(context));
            if (h16 != INVALID_HANDLE_VALUE16 && (ptr = GlobalLock16( h16 )))
            {
                if (!FindClose( *ptr )) bSetDOSExtendedError = TRUE;
                GlobalUnlock16( h16 );
                GlobalFree16( h16 );
            }
            else
            {
                SetLastError( ERROR_INVALID_HANDLE );
                bSetDOSExtendedError = TRUE;
            }
        }
        break;
          
3275
    case 0xa6: /* LONG FILENAME - GET FILE INFO BY HANDLE */
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
        {
            HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
            BY_HANDLE_FILE_INFORMATION *info =
                CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
            
            TRACE( "LONG FILENAME - GET FILE INFO BY HANDLE\n" );
            
            if (!GetFileInformationByHandle(handle, info))
                bSetDOSExtendedError = TRUE;
        }
        break;

3288
    case 0xa7: /* LONG FILENAME - CONVERT TIME */
3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335
        switch (BL_reg(context))
        {
        case 0x00: /* FILE TIME TO DOS TIME */
            {
                WORD      date, time;
                FILETIME *filetime = CTX_SEG_OFF_TO_LIN(context,
                                                        context->SegDs,
                                                        context->Esi);

                TRACE( "LONG FILENAME - FILE TIME TO DOS TIME\n" );

                FileTimeToDosDateTime( filetime, &date, &time );

                SET_DX( context, date );
                SET_CX( context, time );

                /*
                 * FIXME: BH has number of 10-millisecond units 
                 * past time in CX.
                 */
                SET_BH( context, 0 );
            }
            break;

        case 0x01: /* DOS TIME TO FILE TIME */
            {
                FILETIME *filetime = CTX_SEG_OFF_TO_LIN(context,
                                                        context->SegEs,
                                                        context->Edi);

                TRACE( "LONG FILENAME - DOS TIME TO FILE TIME\n" );

                /*
                 * FIXME: BH has number of 10-millisecond units 
                 * past time in CX.
                 */
                DosDateTimeToFileTime( DX_reg(context), CX_reg(context),
                                       filetime );
            }
            break;

        default:
            INT_BARF( context, 0x21 );
            break;
        }
        break;

3336 3337 3338 3339
    case 0xa8: /* LONG FILENAME - GENERATE SHORT FILENAME */
    case 0xa9: /* LONG FILENAME - SERVER CREATE OR OPEN FILE */
    case 0xaa: /* LONG FILENAME - SUBST */
    default:
3340
        FIXME("Unimplemented long file name function:\n");
3341
        INT_BARF( context, 0x21 );
3342 3343 3344
        SET_CFLAG(context);
        SET_AL( context, 0 );
        break;
3345 3346 3347 3348 3349 3350 3351 3352 3353 3354
    }

    if (bSetDOSExtendedError)
    {
        SET_AX( context, GetLastError() );
        SET_CFLAG( context );
    }
}


3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379
/***********************************************************************
 *           INT21_RenameFile
 *
 * Handler for:
 * - function 0x56
 * - subfunction 0x56 of function 0x71
 * - subfunction 0xff of function 0x43 (CL == 0x56)
 */
static BOOL INT21_RenameFile( CONTEXT86 *context )
{
    WCHAR fromW[MAX_PATH];
    WCHAR toW[MAX_PATH];
    char *fromA = CTX_SEG_OFF_TO_LIN(context, 
                                     context->SegDs,context->Edx);
    char *toA = CTX_SEG_OFF_TO_LIN(context, 
                                   context->SegEs,context->Edi);

    TRACE( "RENAME FILE %s to %s\n", fromA, toA );
    MultiByteToWideChar(CP_OEMCP, 0, fromA, -1, fromW, MAX_PATH);
    MultiByteToWideChar(CP_OEMCP, 0, toA, -1, toW, MAX_PATH);

    return MoveFileW( fromW, toW );
}


3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
/***********************************************************************
 *           INT21_NetworkFunc
 *
 * Handler for:
 * - function 0x5e
 */
static BOOL INT21_NetworkFunc (CONTEXT86 *context)
{
    switch (AL_reg(context)) 
    {
    case 0x00: /* Get machine name. */
        {
            WCHAR dstW[MAX_COMPUTERNAME_LENGTH + 1];
            DWORD s = sizeof(dstW) / sizeof(WCHAR);
            int len;

            char *dst = CTX_SEG_OFF_TO_LIN (context,context->SegDs,context->Edx);
            TRACE("getting machine name to %p\n", dst);
            if (!GetComputerNameW(dstW, &s) ||
                !WideCharToMultiByte(CP_OEMCP, 0, dstW, -1, dst, 16, NULL, NULL))
            {
                WARN("failed!\n");
                SetLastError( ER_NoNetwork );
                return TRUE;
            }
            for (len = strlen(dst); len < 15; len++) dst[len] = ' ';
            dst[15] = 0;
            SET_CH( context, 1 ); /* Valid */
            SET_CL( context, 1 ); /* NETbios number??? */
            TRACE("returning %s\n", debugstr_an(dst, 16));
            return FALSE;
        }

    default:
        SetLastError( ER_NoNetwork );
        return TRUE;
    }
}

/******************************************************************
 *		INT21_GetDiskSerialNumber
 *
 */
static int INT21_GetDiskSerialNumber( CONTEXT86 *context )
{
    BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    WCHAR path[] = {'A',':',0}, label[11];
    DWORD serial;

    path[0] += INT21_MapDrive(BL_reg(context));
    if (!GetVolumeInformationW( path, label, 11, &serial, NULL, NULL, NULL, 0))
    {
        SetLastError( ERROR_INVALID_DRIVE );
        return 0;
    }

    *(WORD *)dataptr = 0;
    memcpy(dataptr + 2, &serial, sizeof(DWORD));
3438
    WideCharToMultiByte(CP_OEMCP, 0, label, 11, (LPSTR)dataptr + 6, 11, NULL, NULL);
3439
    memcpy(dataptr + 17, "FAT16   ", 8);
3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
    return 1;
}


/******************************************************************
 *		INT21_SetDiskSerialNumber
 *
 */
static int INT21_SetDiskSerialNumber( CONTEXT86 *context )
{
#if 0
    BYTE *dataptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    int drive = INT21_MapDrive(BL_reg(context));

    if (!is_valid_drive(drive))
    {
        SetLastError( ERROR_INVALID_DRIVE );
        return 0;
    }

    DRIVE_SetSerialNumber( drive, *(DWORD *)(dataptr + 2) );
    return 1;
#else
    FIXME("Setting drive serial number is no longer supported\n");
    SetLastError( ERROR_NOT_SUPPORTED );
    return 0;
#endif
}


/******************************************************************
 *		INT21_GetFreeDiskSpace
 *
 */
static int INT21_GetFreeDiskSpace( CONTEXT86 *context )
{
    DWORD cluster_sectors, sector_bytes, free_clusters, total_clusters;
    WCHAR root[] = {'A',':','\\',0};

3479
    root[0] += INT21_MapDrive(DL_reg(context));
3480 3481
    if (!GetDiskFreeSpaceW( root, &cluster_sectors, &sector_bytes,
                            &free_clusters, &total_clusters )) return 0;
3482 3483 3484 3485 3486 3487
    /* make sure that the number of clusters fits in a 16 bits value */
    while( total_clusters & 0xffff0000) {
        cluster_sectors <<= 1;
        free_clusters >>= 1;
        total_clusters >>= 1;
    }
3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
    SET_AX( context, cluster_sectors );
    SET_BX( context, free_clusters );
    SET_CX( context, sector_bytes );
    SET_DX( context, total_clusters );
    return 1;
}

/******************************************************************
 *		INT21_GetDriveAllocInfo
 *
 */
3499
static int INT21_GetDriveAllocInfo( CONTEXT86 *context, BYTE drive )
3500 3501 3502
{
    INT21_DPB  *dpb;

3503
    drive = INT21_MapDrive( drive );
3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514
    if (!INT21_FillDrivePB( drive )) return 0;
    dpb = &(INT21_GetHeapPointer()->misc_dpb_list[drive]);
    SET_AL( context, dpb->cluster_sectors + 1 );
    SET_CX( context, dpb->sector_bytes );
    SET_DX( context, dpb->num_clusters1 );

    context->SegDs = INT21_GetHeapSelector( context );
    SET_BX( context, offsetof( INT21_HEAP, misc_dpb_list[drive].media_ID ) );
    return 1;
}

3515
/***********************************************************************
3516
 *           INT21_GetExtendedError
3517
 */
3518
static void INT21_GetExtendedError( CONTEXT86 *context )
3519
{
3520 3521
    BYTE class, action, locus;
    WORD error = GetLastError();
3522

3523
    switch(error)
3524
    {
3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559
    case ERROR_SUCCESS:
        class = action = locus = 0;
        break;
    case ERROR_DIR_NOT_EMPTY:
        class  = EC_Exists;
        action = SA_Ignore;
        locus  = EL_Disk;
        break;
    case ERROR_ACCESS_DENIED:
        class  = EC_AccessDenied;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    case ERROR_CANNOT_MAKE:
        class  = EC_AccessDenied;
        action = SA_Abort;
        locus  = EL_Unknown;
        break;
    case ERROR_DISK_FULL:
    case ERROR_HANDLE_DISK_FULL:
        class  = EC_MediaError;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    case ERROR_FILE_EXISTS:
    case ERROR_ALREADY_EXISTS:
        class  = EC_Exists;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    case ERROR_FILE_NOT_FOUND:
        class  = EC_NotFound;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
3560
    case ERROR_GEN_FAILURE:
3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628
        class  = EC_SystemFailure;
        action = SA_Abort;
        locus  = EL_Unknown;
        break;
    case ERROR_INVALID_DRIVE:
        class  = EC_MediaError;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    case ERROR_INVALID_HANDLE:
        class  = EC_ProgramError;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    case ERROR_LOCK_VIOLATION:
        class  = EC_AccessDenied;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    case ERROR_NO_MORE_FILES:
        class  = EC_MediaError;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    case ER_NoNetwork:
        class  = EC_NotFound;
        action = SA_Abort;
        locus  = EL_Network;
        break;
    case ERROR_NOT_ENOUGH_MEMORY:
        class  = EC_OutOfResource;
        action = SA_Abort;
        locus  = EL_Memory;
        break;
    case ERROR_PATH_NOT_FOUND:
        class  = EC_NotFound;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    case ERROR_SEEK:
        class  = EC_NotFound;
        action = SA_Ignore;
        locus  = EL_Disk;
        break;
    case ERROR_SHARING_VIOLATION:
        class  = EC_Temporary;
        action = SA_Retry;
        locus  = EL_Disk;
        break;
    case ERROR_TOO_MANY_OPEN_FILES:
        class  = EC_ProgramError;
        action = SA_Abort;
        locus  = EL_Disk;
        break;
    default:
        FIXME("Unknown error %d\n", error );
        class  = EC_SystemFailure;
        action = SA_Abort;
        locus  = EL_Unknown;
        break;
    }
    TRACE("GET EXTENDED ERROR code 0x%02x class 0x%02x action 0x%02x locus %02x\n",
           error, class, action, locus );
    SET_AX( context, error );
    SET_BH( context, class );
    SET_BL( context, action );
    SET_CH( context, locus );
}
3629

3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670
static BOOL INT21_CreateTempFile( CONTEXT86 *context )
{
    static int counter = 0;
    char *name = CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx );
    char *p = name + strlen(name);

    /* despite what Ralf Brown says, some programs seem to call without
     * ending backslash (DOS accepts that, so we accept it too) */
    if ((p == name) || (p[-1] != '\\')) *p++ = '\\';

    for (;;)
    {
        sprintf( p, "wine%04x.%03d", (int)getpid(), counter );
        counter = (counter + 1) % 1000;

        SET_AX( context, 
                Win32HandleToDosFileHandle( 
                    CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
                                 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                                 CREATE_NEW, 0, 0 ) ) );
        if (AX_reg(context) != HFILE_ERROR16)
        {
            TRACE("created %s\n", name );
            return TRUE;
        }
        if (GetLastError() != ERROR_FILE_EXISTS) return FALSE;
    }
}

/***********************************************************************
 *           DOSFS_ToDosFCBFormat
 *
 * Convert a file name to DOS FCB format (8+3 chars, padded with blanks),
 * expanding wild cards and converting to upper-case in the process.
 * File name can be terminated by '\0', '\\' or '/'.
 * Return FALSE if the name is not a valid DOS name.
 * 'buffer' must be at least 12 characters long.
 */
/* Chars we don't want to see in DOS file names */
static BOOL INT21_ToDosFCBFormat( LPCWSTR name, LPWSTR buffer )
{
3671
    static const WCHAR invalid_chars[] = {'*','?','<','>','|','\\','"','+','=',',',';','[',']',' ','\345',0};
3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706
    LPCWSTR p = name;
    int i;

    /* Check for "." and ".." */
    if (*p == '.')
    {
        p++;
        buffer[0] = '.';
        for(i = 1; i < 11; i++) buffer[i] = ' ';
        buffer[11] = 0;
        if (*p == '.')
        {
            buffer[1] = '.';
            p++;
        }
        return (!*p || (*p == '/') || (*p == '\\'));
    }

    for (i = 0; i < 8; i++)
    {
        switch(*p)
        {
        case '\0':
        case '\\':
        case '/':
        case '.':
            buffer[i] = ' ';
            break;
        case '?':
            p++;
            /* fall through */
        case '*':
            buffer[i] = '?';
            break;
        default:
3707
            if (strchrW( invalid_chars, *p )) return FALSE;
3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
            buffer[i] = toupperW(*p);
            p++;
            break;
        }
    }

    if (*p == '*')
    {
        /* Skip all chars after wildcard up to first dot */
        while (*p && (*p != '/') && (*p != '\\') && (*p != '.')) p++;
    }
    else
    {
        /* Check if name too long */
        if (*p && (*p != '/') && (*p != '\\') && (*p != '.')) return FALSE;
    }
    if (*p == '.') p++;  /* Skip dot */

    for (i = 8; i < 11; i++)
    {
        switch(*p)
        {
        case '\0':
        case '\\':
        case '/':
            buffer[i] = ' ';
            break;
        case '.':
            return FALSE;  /* Second extension not allowed */
        case '?':
            p++;
            /* fall through */
        case '*':
            buffer[i] = '?';
            break;
        default:
3744
            if (strchrW( invalid_chars, *p )) return FALSE;
3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
            buffer[i] = toupperW(*p);
            p++;
            break;
        }
    }
    buffer[11] = '\0';

    /* at most 3 character of the extension are processed
     * is something behind this ?
     */
    while (*p == '*' || *p == ' ') p++; /* skip wildcards and spaces */
3756
    return (!*p || (*p == '/') || (*p == '\\'));
3757 3758 3759 3760 3761 3762 3763 3764 3765 3766
}

static HANDLE       INT21_FindHandle;
static const WCHAR *INT21_FindPath; /* will point to current dta->fullPath search */

/******************************************************************
 *		INT21_FindFirst
 */
static int INT21_FindFirst( CONTEXT86 *context )
{
3767
    WCHAR *p, *q;
3768 3769 3770
    const char *path;
    FINDFILE_DTA *dta = (FINDFILE_DTA *)INT21_GetCurrentDTA(context);
    WCHAR maskW[12], pathW[MAX_PATH];
3771
    static const WCHAR wildcardW[] = {'*','.','*',0};
3772 3773 3774 3775

    path = (const char *)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    MultiByteToWideChar(CP_OEMCP, 0, path, -1, pathW, MAX_PATH);

3776
    p = strrchrW( pathW, '\\');
3777 3778
    q = strrchrW( pathW, '/');
    if (q>p) p = q;
3779
    if (!p)
3780
    {
3781 3782
        if (pathW[0] && pathW[1] == ':') p = pathW + 2;
        else p = pathW;
3783
    }
3784
    else p++;
3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796

    /* Note: terminating NULL in dta->mask overwrites dta->search_attr
     *       (doesn't matter as it is set below anyway)
     */
    if (!INT21_ToDosFCBFormat( p, maskW ))
    {
        SetLastError( ERROR_FILE_NOT_FOUND );
        SET_AX( context, ERROR_FILE_NOT_FOUND );
        SET_CFLAG(context);
        return 0;
    }
    WideCharToMultiByte(CP_OEMCP, 0, maskW, 12, dta->mask, sizeof(dta->mask), NULL, NULL);
3797 3798 3799 3800

    dta->fullPath = HeapAlloc( GetProcessHeap(), 0, sizeof(wildcardW) + (p - pathW)*sizeof(WCHAR) );
    memcpy( dta->fullPath, pathW, (p - pathW) * sizeof(WCHAR) );
    memcpy( dta->fullPath + (p - pathW), wildcardW, sizeof(wildcardW) );
3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
    /* we must have a fully qualified file name in dta->fullPath
     * (we could have a UNC path, but this would lead to some errors later on)
     */
    dta->drive = toupperW(dta->fullPath[0]) - 'A';
    dta->count = 0;
    dta->search_attr = CL_reg(context);
    return 1;
}

/******************************************************************
 *		match_short
 *
 * Check is a short path name (DTA unicode) matches a mask (FCB ansi)
 */
static BOOL match_short(LPCWSTR shortW, LPCSTR maskA)
{
3817 3818
    WCHAR mask[11], file[12];
    int i;
3819

3820 3821 3822 3823
    if (!INT21_ToDosFCBFormat( shortW, file )) return FALSE;
    MultiByteToWideChar(CP_OEMCP, 0, maskA, 11, mask, 11);
    for (i = 0; i < 11; i++)
        if (mask[i] != '?' && mask[i] != file[i]) return FALSE;
3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
    return TRUE;
}

static unsigned INT21_FindHelper(LPCWSTR fullPath, unsigned drive, unsigned count, 
                                 LPCSTR mask, unsigned search_attr, 
                                 WIN32_FIND_DATAW* entry)
{
    unsigned ncalls;

    if ((search_attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
    {
        WCHAR path[] = {' ',':',0};

        if (count) return 0;
        path[0] = drive + 'A';
        if (!GetVolumeInformationW(path, entry->cAlternateFileName, 13, NULL, NULL, NULL, NULL, 0)) return 0;
        RtlSecondsSince1970ToTime( (time_t)0, (LARGE_INTEGER *)&entry->ftCreationTime );
        RtlSecondsSince1970ToTime( (time_t)0, (LARGE_INTEGER *)&entry->ftLastAccessTime );
        RtlSecondsSince1970ToTime( (time_t)0, (LARGE_INTEGER *)&entry->ftLastWriteTime );
3843
        entry->dwFileAttributes = FA_LABEL;
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876
        entry->nFileSizeHigh = entry->nFileSizeLow = 0;
        TRACE("returning %s as label\n", debugstr_w(entry->cAlternateFileName));
        return 1;
    }

    if (!INT21_FindHandle || INT21_FindPath != fullPath || count == 0)
    {
        if (INT21_FindHandle) FindClose(INT21_FindHandle);
        INT21_FindHandle = FindFirstFileW(fullPath, entry);
        if (INT21_FindHandle == INVALID_HANDLE_VALUE)
        {
            INT21_FindHandle = 0;
            return 0;
        }
        INT21_FindPath = fullPath;
        /* we need to resync search */
        ncalls = count;
    }
    else ncalls = 1;

    while (ncalls-- != 0)
    {
        if (!FindNextFileW(INT21_FindHandle, entry))
        {
            FindClose(INT21_FindHandle); INT21_FindHandle = 0;
            return 0;
        }
    }
    while (count < 0xffff)
    {
        count++;
        /* Check the file attributes, and path */
        if (!(entry->dwFileAttributes & ~search_attr) &&
3877 3878
            match_short(entry->cAlternateFileName[0] ? entry->cAlternateFileName : entry->cFileName,
                        mask))
3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910
        {
            return count;
        }
        if (!FindNextFileW(INT21_FindHandle, entry))
        {
            FindClose(INT21_FindHandle); INT21_FindHandle = 0;
            return 0;
        }
    }
    WARN("Too many directory entries in %s\n", debugstr_w(fullPath) );
    return 0;
}

/******************************************************************
 *		INT21_FindNext
 */
static int INT21_FindNext( CONTEXT86 *context )
{
    FINDFILE_DTA *dta = (FINDFILE_DTA *)INT21_GetCurrentDTA(context);
    DWORD attr = dta->search_attr | FA_UNUSED | FA_ARCHIVE | FA_RDONLY;
    WIN32_FIND_DATAW entry;
    int n;

    if (!dta->fullPath) return 0;

    n = INT21_FindHelper(dta->fullPath, dta->drive, dta->count, 
                         dta->mask, attr, &entry);
    if (n)
    {
        dta->fileattr = entry.dwFileAttributes;
        dta->filesize = entry.nFileSizeLow;
        FileTimeToDosDateTime( &entry.ftLastWriteTime, &dta->filedate, &dta->filetime );
3911 3912 3913 3914 3915 3916
        if (entry.cAlternateFileName[0])
            WideCharToMultiByte(CP_OEMCP, 0, entry.cAlternateFileName, -1,
                                dta->filename, 13, NULL, NULL);
        else
            WideCharToMultiByte(CP_OEMCP, 0, entry.cFileName, -1, dta->filename, 13, NULL, NULL);

3917 3918 3919 3920 3921 3922 3923 3924 3925
        if (!memchr(dta->mask,'?',11))
        {
            /* wildcardless search, release resources in case no findnext will
             * be issued, and as a workaround in case file creation messes up
             * findnext, as sometimes happens with pkunzip
             */
            HeapFree( GetProcessHeap(), 0, dta->fullPath );
            INT21_FindPath = dta->fullPath = NULL;
        }
3926
        dta->count = n;
3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968
        return 1;
    }
    HeapFree( GetProcessHeap(), 0, dta->fullPath );
    INT21_FindPath = dta->fullPath = NULL;
    return 0;
}

/* microsoft's programmers should be shot for using CP/M style int21
   calls in Windows for Workgroup's winfile.exe */

/******************************************************************
 *		INT21_FindFirstFCB
 *
 */
static int INT21_FindFirstFCB( CONTEXT86 *context )
{
    BYTE *fcb = (BYTE *)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    FINDFILE_FCB *pFCB;
    int drive;
    WCHAR p[] = {' ',':',};

    if (*fcb == 0xff) pFCB = (FINDFILE_FCB *)(fcb + 7);
    else pFCB = (FINDFILE_FCB *)fcb;
    drive = INT21_MapDrive( pFCB->drive );
    if (drive == MAX_DOS_DRIVES) return 0;

    p[0] = 'A' + drive;
    pFCB->fullPath = HeapAlloc(GetProcessHeap(), 0, MAX_PATH * sizeof(WCHAR));
    if (!pFCB->fullPath) return 0;
    GetLongPathNameW(p, pFCB->fullPath, MAX_PATH);
    pFCB->count = 0;
    return 1;
}

/******************************************************************
 *		INT21_FindNextFCB
 *
 */
static int INT21_FindNextFCB( CONTEXT86 *context )
{
    BYTE *fcb = (BYTE *)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
    FINDFILE_FCB *pFCB;
3969 3970
    LPBYTE pResult = INT21_GetCurrentDTA(context);
    DOS_DIRENTRY_LAYOUT *ddl;
3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
    WIN32_FIND_DATAW entry;
    BYTE attr;
    int n;
    WCHAR nameW[12];

    if (*fcb == 0xff) /* extended FCB ? */
    {
        attr = fcb[6];
        pFCB = (FINDFILE_FCB *)(fcb + 7);
    }
    else
    {
        attr = 0;
        pFCB = (FINDFILE_FCB *)fcb;
    }

    if (!pFCB->fullPath) return 0;
    n = INT21_FindHelper(pFCB->fullPath, INT21_MapDrive( pFCB->drive ),
                         pFCB->count, pFCB->filename, attr, &entry);
    if (!n)
    {
        HeapFree( GetProcessHeap(), 0, pFCB->fullPath );
        INT21_FindPath = pFCB->fullPath = NULL;
        return 0;
    }
    pFCB->count += n;

    if (*fcb == 0xff)
    {
        /* place extended FCB header before pResult if called with extended FCB */
4001 4002 4003 4004 4005 4006 4007 4008 4009 4010
	*pResult = 0xff;
	 pResult += 6; /* leave reserved field behind */
	*pResult++ = entry.dwFileAttributes;
    }
    *pResult++ = INT21_MapDrive( pFCB->drive ); /* DOS_DIRENTRY_LAYOUT after current drive number */
    ddl = (DOS_DIRENTRY_LAYOUT*)pResult;
    ddl->fileattr = entry.dwFileAttributes;
    ddl->cluster  = 0;  /* what else? */
    ddl->filesize = entry.nFileSizeLow;
    memset( ddl->reserved, 0, sizeof(ddl->reserved) );
4011
    FileTimeToDosDateTime( &entry.ftLastWriteTime,
4012
                           &ddl->filedate, &ddl->filetime );
4013 4014

    /* Convert file name to FCB format */
4015 4016 4017 4018
    if (entry.cAlternateFileName[0])
        INT21_ToDosFCBFormat( entry.cAlternateFileName, nameW );
    else
        INT21_ToDosFCBFormat( entry.cFileName, nameW );
4019
    WideCharToMultiByte(CP_OEMCP, 0, nameW, 11, ddl->filename, 11, NULL, NULL);
4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062
    return 1;
}


/******************************************************************
 *		INT21_ParseFileNameIntoFCB
 *
 */
static void INT21_ParseFileNameIntoFCB( CONTEXT86 *context )
{
    char *filename =
        CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi );
    char *fcb =
        CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi );
    char *s;
    WCHAR *buffer;
    WCHAR fcbW[12];
    INT buffer_len, len;

    SET_AL( context, 0xff ); /* failed */

    TRACE("filename: '%s'\n", filename);

    s = filename;
    while (*s && (*s != ' ') && (*s != '\r') && (*s != '\n'))
        s++;
    len = filename - s;

    buffer_len = MultiByteToWideChar(CP_OEMCP, 0, filename, len, NULL, 0);
    buffer = HeapAlloc( GetProcessHeap(), 0, (buffer_len + 1) * sizeof(WCHAR));
    len = MultiByteToWideChar(CP_OEMCP, 0, filename, len, buffer, buffer_len);
    buffer[len] = 0;
    INT21_ToDosFCBFormat(buffer, fcbW);
    HeapFree(GetProcessHeap(), 0, buffer);
    WideCharToMultiByte(CP_OEMCP, 0, fcbW, 12, fcb + 1, 12, NULL, NULL);
    *fcb = 0;
    TRACE("FCB: '%s'\n", fcb + 1);

    SET_AL( context, ((strchr(filename, '*')) || (strchr(filename, '$'))) != 0 );

    /* point DS:SI to first unparsed character */
    SET_SI( context, context->Esi + (int)s - (int)filename );
}
4063

4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101
static BOOL     INT21_Dup2(HFILE16 hFile1, HFILE16 hFile2)
{
    HFILE16     res = HFILE_ERROR16;
    HANDLE      handle, new_handle;
#define DOS_TABLE_SIZE  256
    DWORD       map[DOS_TABLE_SIZE / 32];
    int         i;

    handle = DosFileHandleToWin32Handle(hFile1);
    if (handle == INVALID_HANDLE_VALUE)
        return FALSE;

    _lclose16(hFile2);
    /* now loop to allocate the same one... */
    memset(map, 0, sizeof(map));
    for (i = 0; i < DOS_TABLE_SIZE; i++)
    {
        if (!DuplicateHandle(GetCurrentProcess(), handle,
                             GetCurrentProcess(), &new_handle,
                             0, FALSE, DUPLICATE_SAME_ACCESS))
        {
            res = HFILE_ERROR16;
            break;
        }
        res = Win32HandleToDosFileHandle(new_handle);
        if (res == HFILE_ERROR16 || res == hFile2) break;
        map[res / 32] |= 1 << (res % 32);
    }
    /* clean up the allocated slots */
    for (i = 0; i < DOS_TABLE_SIZE; i++)
    {
        if (map[i / 32] & (1 << (i % 32)))
            _lclose16((HFILE16)i);
    }
    return res == hFile2;
}


4102
/***********************************************************************
4103
 *           DOSVM_Int21Handler
4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
 *
 * Interrupt 0x21 handler.
 */
void WINAPI DOSVM_Int21Handler( CONTEXT86 *context )
{
    BOOL bSetDOSExtendedError = FALSE;

    TRACE( "AX=%04x BX=%04x CX=%04x DX=%04x "
           "SI=%04x DI=%04x DS=%04x ES=%04x EFL=%08lx\n",
           AX_reg(context), BX_reg(context), 
           CX_reg(context), DX_reg(context),
           SI_reg(context), DI_reg(context),
           (WORD)context->SegDs, (WORD)context->SegEs,
           context->EFlags );

   /*
    * Extended error is used by (at least) functions 0x2f to 0x62.
    * Function 0x59 returns extended error and error should not
    * be cleared before handling the function.
    */
    if (AH_reg(context) >= 0x2f && AH_reg(context) != 0x59) 
        SetLastError(0);

    RESET_CFLAG(context); /* Not sure if this is a good idea. */
4128

4129 4130 4131 4132
    switch(AH_reg(context))
    {
    case 0x00: /* TERMINATE PROGRAM */
        TRACE("TERMINATE PROGRAM\n");
4133 4134
        if (DOSVM_IsWin16())
            ExitThread( 0 );
4135
        else if(ISV86(context))
4136
            MZ_Exit( context, FALSE, 0 );
4137 4138
        else
            ERR( "Called from DOS protected mode\n" );
4139 4140 4141
        break;

    case 0x01: /* READ CHARACTER FROM STANDARD INPUT, WITH ECHO */
4142 4143 4144
        {
            BYTE ascii;
            TRACE("DIRECT CHARACTER INPUT WITH ECHO\n");
4145
            INT21_ReadChar( &ascii, context );
4146
            SET_AL( context, ascii );
4147 4148 4149
            /*
             * FIXME: What to echo when extended keycodes are read?
             */
4150 4151
            DOSVM_PutChar(AL_reg(context));
        }
4152
        break;
4153 4154 4155

    case 0x02: /* WRITE CHARACTER TO STANDARD OUTPUT */
        TRACE("Write Character to Standard Output\n");
4156
        DOSVM_PutChar(DL_reg(context));
4157 4158
        break;

4159 4160 4161 4162 4163 4164
    case 0x03: /* READ CHARACTER FROM STDAUX  */
    case 0x04: /* WRITE CHARACTER TO STDAUX */
    case 0x05: /* WRITE CHARACTER TO PRINTER */
        INT_BARF( context, 0x21 );
        break;

4165
    case 0x06: /* DIRECT CONSOLE IN/OUTPUT */
4166 4167
        if (DL_reg(context) == 0xff) 
        {
4168
            TRACE("Direct Console Input\n");
4169

4170
            if (INT21_ReadChar( NULL, NULL ))
4171
            {
4172
                BYTE ascii;
4173
                INT21_ReadChar( &ascii, context );
4174 4175 4176 4177 4178 4179 4180 4181
                SET_AL( context, ascii );
                RESET_ZFLAG( context );
            }
            else
            {
                /* no character available */
                SET_AL( context, 0 );
                SET_ZFLAG( context );
4182
            }
4183 4184 4185
        } 
        else 
        {
4186
            TRACE("Direct Console Output\n");
4187
            DOSVM_PutChar(DL_reg(context));
4188 4189 4190 4191 4192
            /*
             * At least DOS versions 2.1-7.0 return character 
             * that was written in AL register.
             */
            SET_AL( context, DL_reg(context) );
4193 4194 4195 4196
        }
        break;

    case 0x07: /* DIRECT CHARACTER INPUT WITHOUT ECHO */
4197 4198 4199
        {
            BYTE ascii;
            TRACE("DIRECT CHARACTER INPUT WITHOUT ECHO\n");
4200
            INT21_ReadChar( &ascii, context );
4201 4202
            SET_AL( context, ascii );
        }
4203 4204 4205
        break;

    case 0x08: /* CHARACTER INPUT WITHOUT ECHO */
4206 4207 4208
        {
            BYTE ascii;
            TRACE("CHARACTER INPUT WITHOUT ECHO\n");
4209
            INT21_ReadChar( &ascii, context );
4210 4211 4212 4213 4214
            SET_AL( context, ascii );
        }
        break;

    case 0x09: /* WRITE STRING TO STANDARD OUTPUT */
4215 4216 4217 4218 4219 4220
        TRACE("WRITE '$'-terminated string from %04lX:%04X to stdout\n",
	      context->SegDs, DX_reg(context) );
        {
            LPSTR data = CTX_SEG_OFF_TO_LIN( context, 
                                             context->SegDs, context->Edx );
            LPSTR p = data;
4221
            DWORD w;
4222 4223 4224 4225 4226 4227 4228 4229 4230
            /*
             * Do NOT use strchr() to calculate the string length,
             * as '\0' is valid string content, too!
             * Maybe we should check for non-'$' strings, but DOS doesn't.
             */
            while (*p != '$') p++;

            if (DOSVM_IsWin16())
                WriteFile( DosFileHandleToWin32Handle(1), 
4231
                           data, p - data, &w, NULL );
4232 4233 4234 4235 4236 4237
            else
                for(; data != p; data++)
                    DOSVM_PutChar( *data );

            SET_AL( context, '$' ); /* yes, '$' (0x24) gets returned in AL */
        }
4238 4239 4240
        break;

    case 0x0a: /* BUFFERED INPUT */
4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267
        {
            BYTE *ptr = CTX_SEG_OFF_TO_LIN(context,
                                           context->SegDs,
                                           context->Edx);
            WORD result;

            TRACE( "BUFFERED INPUT (size=%d)\n", ptr[0] );

            /*
             * FIXME: Some documents state that
             *        ptr[1] holds number of chars from last input which 
             *        may be recalled on entry, other documents do not mention
             *        this at all.
             */
            if (ptr[1])
                TRACE( "Handle old chars in buffer!\n" );

            /*
             * ptr[0] - capacity (includes terminating CR)
             * ptr[1] - characters read (excludes terminating CR)
             */
            result = INT21_BufferedInput( context, ptr + 2, ptr[0] );
            if (result > 0)
                ptr[1] = (BYTE)result - 1;
            else
                ptr[1] = 0;
        }
4268 4269 4270
        break;

    case 0x0b: /* GET STDIN STATUS */
4271
        TRACE( "GET STDIN STATUS\n" );
4272
        {
4273
            if (INT21_ReadChar( NULL, NULL ))
4274
                SET_AL( context, 0xff ); /* character available */
Nog's avatar
Nog committed
4275
            else
4276
                SET_AL( context, 0 ); /* no character available */
4277 4278 4279
        }
        break;

4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304
    case 0x0c: /* FLUSH BUFFER AND READ STANDARD INPUT */
        {
            BYTE al = AL_reg(context); /* Input function to execute after flush. */

            TRACE( "FLUSH BUFFER AND READ STANDARD INPUT - 0x%02x\n", al );

            /* FIXME: buffers are not flushed */

            /*
             * If AL is one of 0x01, 0x06, 0x07, 0x08, or 0x0a,
             * int21 function identified by AL will be called.
             */
            if(al == 0x01 || al == 0x06 || al == 0x07 || al == 0x08 || al == 0x0a)
            {
                SET_AH( context, al );
                DOSVM_Int21Handler( context );
            }
        }
        break;

    case 0x0d: /* DISK BUFFER FLUSH */
        TRACE("DISK BUFFER FLUSH ignored\n");
        break;

    case 0x0e: /* SELECT DEFAULT DRIVE */
4305 4306 4307
        TRACE( "SELECT DEFAULT DRIVE - %c:\n", 'A' + DL_reg(context) );
        INT21_SetCurrentDrive( DL_reg(context) );
        SET_AL( context, MAX_DOS_DRIVES );
4308 4309 4310
        break;

    case 0x0f: /* OPEN FILE USING FCB */
4311 4312 4313
        INT21_OpenFileUsingFCB( context );
        break;

4314
    case 0x10: /* CLOSE FILE USING FCB */
4315
        INT21_CloseFileUsingFCB( context );
4316 4317 4318
        break;

    case 0x11: /* FIND FIRST MATCHING FILE USING FCB */
4319 4320 4321 4322 4323 4324 4325 4326 4327
	TRACE("FIND FIRST MATCHING FILE USING FCB %p\n",
	      CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx));
        if (!INT21_FindFirstFCB(context))
        {
            SET_AL( context, 0xff );
            break;
        }
        /* else fall through */

4328
    case 0x12: /* FIND NEXT MATCHING FILE USING FCB */
4329
        SET_AL( context, INT21_FindNextFCB(context) ? 0x00 : 0xff );
4330 4331
        break;

4332
     case 0x13: /* DELETE FILE USING FCB */
4333 4334 4335
        INT_BARF( context, 0x21 );
        break;

4336
    case 0x14: /* SEQUENTIAL READ FROM FCB FILE */
4337
        INT21_SequentialReadFromFCB( context );
4338 4339
        break;

4340
    case 0x15: /* SEQUENTIAL WRITE TO FCB FILE */
4341
        INT21_SequentialWriteToFCB( context );
4342 4343
        break;

4344 4345
    case 0x16: /* CREATE OR TRUNCATE FILE USING FCB */
    case 0x17: /* RENAME FILE USING FCB */
4346
        INT_BARF( context, 0x21 );
4347 4348 4349 4350 4351 4352 4353
        break;

    case 0x18: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
        SET_AL( context, 0 );
        break;

    case 0x19: /* GET CURRENT DEFAULT DRIVE */
4354 4355
        SET_AL( context, INT21_GetCurrentDrive() );
        TRACE( "GET CURRENT DRIVE -> %c:\n", 'A' + AL_reg( context ) );
4356 4357
        break;

4358
    case 0x1a: /* SET DISK TRANSFER AREA ADDRESS */
4359 4360 4361 4362 4363 4364 4365 4366 4367
        TRACE( "SET DISK TRANSFER AREA ADDRESS %04lX:%04X\n",
               context->SegDs, DX_reg(context) );
        {
            TDB *task = GlobalLock16( GetCurrentTask() );
            task->dta = MAKESEGPTR( context->SegDs, DX_reg(context) );
        }
        break;

    case 0x1b: /* GET ALLOCATION INFORMATION FOR DEFAULT DRIVE */
4368 4369 4370 4371
        if (!INT21_GetDriveAllocInfo(context, 0))
            SET_AX( context, 0xffff );
        break;

4372
    case 0x1c: /* GET ALLOCATION INFORMATION FOR SPECIFIC DRIVE */
4373 4374
        if (!INT21_GetDriveAllocInfo(context, DL_reg(context)))
            SET_AX( context, 0xffff );
4375 4376 4377 4378 4379 4380 4381 4382
        break;

    case 0x1d: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
    case 0x1e: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
        SET_AL( context, 0 );
        break;

    case 0x1f: /* GET DRIVE PARAMETER BLOCK FOR DEFAULT DRIVE */
4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
        {
            BYTE drive = INT21_MapDrive( 0 ); 
            TRACE( "GET DPB FOR DEFAULT DRIVE\n" );

            if (INT21_FillDrivePB( drive ))
            {
                SET_AL( context, 0x00 ); /* success */
                SET_BX( context, offsetof( INT21_HEAP, misc_dpb_list[drive] ) );
                context->SegDs = INT21_GetHeapSelector( context );
            }
            else
            {
                SET_AL( context, 0xff ); /* invalid or network drive */
            }
        }
4398 4399 4400 4401 4402 4403 4404
        break;

    case 0x20: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
        SET_AL( context, 0 );
        break;

    case 0x21: /* READ RANDOM RECORD FROM FCB FILE */
4405 4406 4407
        INT21_ReadRandomRecordFromFCB( context );
        break;

4408
    case 0x22: /* WRITE RANDOM RECORD TO FCB FILE */
4409 4410 4411
        INT21_WriteRandomRecordToFCB( context );
        break;

4412 4413 4414 4415 4416
    case 0x23: /* GET FILE SIZE FOR FCB */
    case 0x24: /* SET RANDOM RECORD NUMBER FOR FCB */
        INT_BARF( context, 0x21 );
        break;

4417
    case 0x25: /* SET INTERRUPT VECTOR */
4418 4419 4420
        TRACE("SET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
        {
            FARPROC16 ptr = (FARPROC16)MAKESEGPTR( context->SegDs, DX_reg(context) );
4421
            if (!ISV86(context) && DOSVM_IsWin16())
4422 4423 4424 4425 4426 4427 4428
                DOSVM_SetPMHandler16(  AL_reg(context), ptr );
            else
                DOSVM_SetRMHandler( AL_reg(context), ptr );
        }
        break;

    case 0x26: /* CREATE NEW PROGRAM SEGMENT PREFIX */
4429 4430 4431
        INT_BARF( context, 0x21 );
        break;

4432
    case 0x27: /* RANDOM BLOCK READ FROM FCB FILE */
4433 4434 4435
        INT21_RandomBlockReadFromFCB( context );
        break;

4436
    case 0x28: /* RANDOM BLOCK WRITE TO FCB FILE */
4437
        INT21_RandomBlockWriteToFCB( context );
4438 4439 4440
        break;

    case 0x29: /* PARSE FILENAME INTO FCB */
4441
        INT21_ParseFileNameIntoFCB(context);
4442 4443
        break;

4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455
    case 0x2a: /* GET SYSTEM DATE */
        TRACE( "GET SYSTEM DATE\n" );
        {
            SYSTEMTIME systime;
            GetLocalTime( &systime );
            SET_CX( context, systime.wYear );
            SET_DH( context, systime.wMonth );
            SET_DL( context, systime.wDay );
            SET_AL( context, systime.wDayOfWeek );
        }
        break;

4456
    case 0x2b: /* SET SYSTEM DATE */
4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473
        TRACE( "SET SYSTEM DATE\n" );
        {
            WORD year  = CX_reg(context);
            BYTE month = DH_reg(context);
            BYTE day   = DL_reg(context);

            if (year  >= 1980 && year  <= 2099 &&
                month >= 1    && month <= 12   &&
                day   >= 1    && day   <= 31)
            {
                FIXME( "SetSystemDate(%02d/%02d/%04d): not allowed\n",
                       day, month, year );
                SET_AL( context, 0 );  /* Let's pretend we succeeded */
            }
            else
            {
                SET_AL( context, 0xff ); /* invalid date */
4474 4475
                TRACE( "SetSystemDate(%02d/%02d/%04d): invalid date\n",
                       day, month, year );
4476 4477
            }
        }
4478 4479 4480
        break;

    case 0x2c: /* GET SYSTEM TIME */
4481 4482 4483 4484
        TRACE( "GET SYSTEM TIME\n" );
        {
            SYSTEMTIME systime;
            GetLocalTime( &systime );
4485 4486
            SET_CH( context, systime.wHour );
            SET_CL( context, systime.wMinute );
4487 4488 4489
            SET_DH( context, systime.wSecond );
            SET_DL( context, systime.wMilliseconds / 10 );
        }
4490 4491 4492
        break;

    case 0x2d: /* SET SYSTEM TIME */
4493 4494
        if( CH_reg(context) >= 24 || CL_reg(context) >= 60 || DH_reg(context) >= 60 || DL_reg(context) >= 100 ) {
            TRACE("SetSystemTime(%02d:%02d:%02d.%02d): wrong time\n",
4495 4496
              CH_reg(context), CL_reg(context),
              DH_reg(context), DL_reg(context) );
4497 4498 4499 4500 4501 4502 4503 4504 4505
            SET_AL( context, 0xFF );
        }
        else
        {
            FIXME("SetSystemTime(%02d:%02d:%02d.%02d): not allowed\n",
                  CH_reg(context), CL_reg(context),
                  DH_reg(context), DL_reg(context) );
            SET_AL( context, 0 );  /* Let's pretend we succeeded */
        }
4506 4507 4508 4509 4510 4511 4512
        break;

    case 0x2e: /* SET VERIFY FLAG */
        TRACE("SET VERIFY FLAG ignored\n");
        /* we cannot change the behaviour anyway, so just ignore it */
        break;

4513 4514 4515 4516 4517 4518 4519
    case 0x2f: /* GET DISK TRANSFER AREA ADDRESS */
        TRACE( "GET DISK TRANSFER AREA ADDRESS\n" );
        {
            TDB *task = GlobalLock16( GetCurrentTask() );
            context->SegEs = SELECTOROF( task->dta );
            SET_BX( context, OFFSETOF( task->dta ) );
        }
4520 4521
        break;

4522 4523 4524 4525 4526 4527 4528 4529 4530
    case 0x30: /* GET DOS VERSION */
        TRACE( "GET DOS VERSION - %s requested\n",
               (AL_reg(context) == 0x00) ? "OEM number" : "version flag" );

        if (AL_reg(context) == 0x00)
            SET_BH( context, 0xff ); /* OEM number => undefined */
        else
            SET_BH( context, 0x08 ); /* version flag => DOS is in ROM */

4531 4532 4533 4534
        SET_AL( context, HIBYTE(HIWORD(GetVersion16())) ); /* major version */
        SET_AH( context, LOBYTE(HIWORD(GetVersion16())) ); /* minor version */

        SET_BL( context, 0x12 );     /* 0x123456 is 24-bit Wine's serial # */
4535 4536 4537
        SET_CX( context, 0x3456 );
        break;

4538 4539 4540 4541 4542
    case 0x31: /* TERMINATE AND STAY RESIDENT */
        FIXME("TERMINATE AND STAY RESIDENT stub\n");
        break;

    case 0x32: /* GET DOS DRIVE PARAMETER BLOCK FOR SPECIFIC DRIVE */
4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557
        {
            BYTE drive = INT21_MapDrive( DL_reg(context) );           
            TRACE( "GET DPB FOR SPECIFIC DRIVE %d\n", DL_reg(context) );

            if (INT21_FillDrivePB( drive ))
            {
                SET_AL( context, 0x00 ); /* success */
                SET_DX( context, offsetof( INT21_HEAP, misc_dpb_list[drive] ) );
                context->SegDs = INT21_GetHeapSelector( context );
            }
            else
            {
                SET_AL( context, 0xff ); /* invalid or network drive */
            }
        }
4558 4559
        break;

4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607
    case 0x33: /* MULTIPLEXED */
        switch (AL_reg(context))
        {
        case 0x00: /* GET CURRENT EXTENDED BREAK STATE */
            TRACE("GET CURRENT EXTENDED BREAK STATE\n");
            SET_DL( context, DOSCONF_GetConfig()->brk_flag );
            break;

        case 0x01: /* SET EXTENDED BREAK STATE */
            TRACE("SET CURRENT EXTENDED BREAK STATE\n");
            DOSCONF_GetConfig()->brk_flag = (DL_reg(context) > 0) ? 1 : 0;
            break;

        case 0x02: /* GET AND SET EXTENDED CONTROL-BREAK CHECKING STATE*/
            TRACE("GET AND SET EXTENDED CONTROL-BREAK CHECKING STATE\n");
            /* ugly coding in order to stay reentrant */
            if (DL_reg(context))
            {
                SET_DL( context, DOSCONF_GetConfig()->brk_flag );
                DOSCONF_GetConfig()->brk_flag = 1;
            }
            else
            {
                SET_DL( context, DOSCONF_GetConfig()->brk_flag );
                DOSCONF_GetConfig()->brk_flag = 0;
            }
            break;

        case 0x05: /* GET BOOT DRIVE */
            TRACE("GET BOOT DRIVE\n");
            SET_DL( context, 3 );
            /* c: is Wine's bootdrive (a: is 1)*/
            break;

        case 0x06: /* GET TRUE VERSION NUMBER */
            TRACE("GET TRUE VERSION NUMBER\n");
            SET_BL( context, HIBYTE(HIWORD(GetVersion16())) ); /* major */
            SET_BH( context, LOBYTE(HIWORD(GetVersion16())) ); /* minor */
            SET_DL( context, 0x00 ); /* revision */
            SET_DH( context, 0x08 ); /* DOS is in ROM */
            break;

        default:
            INT_BARF( context, 0x21 );
            break;
        }
        break;

4608 4609 4610 4611 4612 4613
    case 0x34: /* GET ADDRESS OF INDOS FLAG */
        TRACE( "GET ADDRESS OF INDOS FLAG\n" );
        context->SegEs = INT21_GetHeapSelector( context );
        SET_BX( context, offsetof(INT21_HEAP, misc_indos) );
        break;

4614 4615 4616
    case 0x35: /* GET INTERRUPT VECTOR */
        TRACE("GET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
        {
4617
            FARPROC16 addr;
4618
            if (!ISV86(context) && DOSVM_IsWin16())
4619 4620 4621
                addr = DOSVM_GetPMHandler16( AL_reg(context) );
            else
                addr = DOSVM_GetRMHandler( AL_reg(context) );
4622
            context->SegEs = SELECTOROF(addr);
4623
            SET_BX( context, OFFSETOF(addr) );
4624 4625 4626
        }
        break;

4627
    case 0x36: /* GET FREE DISK SPACE */
4628 4629 4630
	TRACE("GET FREE DISK SPACE FOR DRIVE %s\n",
	      INT21_DriveName( DL_reg(context) ));
        if (!INT21_GetFreeDiskSpace(context)) SET_AX( context, 0xffff );
4631 4632
        break;

4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653
    case 0x37: /* SWITCHAR */
        {
            switch (AL_reg(context))
            {
            case 0x00: /* "SWITCHAR" - GET SWITCH CHARACTER */
                TRACE( "SWITCHAR - GET SWITCH CHARACTER\n" );
                SET_AL( context, 0x00 ); /* success*/
                SET_DL( context, '/' );
                break;
            case 0x01: /*"SWITCHAR" - SET SWITCH CHARACTER*/
                FIXME( "SWITCHAR - SET SWITCH CHARACTER: %c\n",
                       DL_reg( context ));
                SET_AL( context, 0x00 ); /* success*/
                break;
            default:
                INT_BARF( context, 0x21 );
                break;
            }
	}
	break;

4654
    case 0x38: /* GET COUNTRY-SPECIFIC INFORMATION */
4655
        TRACE( "GET COUNTRY-SPECIFIC INFORMATION\n" );
4656
        if (AL_reg(context))
4657 4658 4659 4660
        {
            WORD country = AL_reg(context);
            if (country == 0xff)
                country = BX_reg(context);
4661
            if (country != INT21_GetSystemCountryCode()) {
4662
                FIXME( "Requested info on non-default country %04x\n", country );
4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674
                SET_AX(context, 2);
                SET_CFLAG(context);
            }
        }
        if(AX_reg(context) != 2 )
        {
            INT21_FillCountryInformation( CTX_SEG_OFF_TO_LIN(context,
                                                             context->SegDs,
                                                             context->Edx) );
            SET_AX( context, INT21_GetSystemCountryCode() );
            SET_BX( context, INT21_GetSystemCountryCode() );
            RESET_CFLAG(context);
4675
        }
4676 4677 4678
        break;

    case 0x39: /* "MKDIR" - CREATE SUBDIRECTORY */
4679 4680
        if (!INT21_CreateDirectory( context ))
            bSetDOSExtendedError = TRUE;
4681 4682
        else
            RESET_CFLAG(context);
4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696
        break;

    case 0x3a: /* "RMDIR" - REMOVE DIRECTORY */
        {
            WCHAR dirW[MAX_PATH];
            char *dirA = CTX_SEG_OFF_TO_LIN(context,
                                            context->SegDs, context->Edx);

            TRACE( "REMOVE DIRECTORY %s\n", dirA );

            MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);

            if (!RemoveDirectoryW( dirW ))
                bSetDOSExtendedError = TRUE;
4697 4698
            else
                RESET_CFLAG(context);
4699 4700 4701
        }
        break;

4702
    case 0x3b: /* "CHDIR" - SET CURRENT DIRECTORY */
4703 4704
        if (!INT21_SetCurrentDirectory( context ))
            bSetDOSExtendedError = TRUE;
4705 4706
        else
            RESET_CFLAG(context);
4707 4708
        break;

4709
    case 0x3c: /* "CREAT" - CREATE OR TRUNCATE FILE */
4710 4711 4712
        if (!INT21_CreateFile( context, context->Edx, FALSE, 
                               OF_READWRITE | OF_SHARE_COMPAT, 0x12 ))
            bSetDOSExtendedError = TRUE;
4713 4714
        else
            RESET_CFLAG(context);
4715 4716
        break;

4717
    case 0x3d: /* "OPEN" - OPEN EXISTING FILE */
4718 4719 4720
        if (!INT21_CreateFile( context, context->Edx, FALSE, 
                               AL_reg(context), 0x01 ))
            bSetDOSExtendedError = TRUE;
4721 4722
        else
            RESET_CFLAG(context);
4723 4724
        break;

4725
    case 0x3e: /* "CLOSE" - CLOSE FILE */
4726 4727 4728
        TRACE( "CLOSE handle %d\n", BX_reg(context) );
        if (_lclose16( BX_reg(context) ) == HFILE_ERROR16)
            bSetDOSExtendedError = TRUE;
4729 4730
        else
            RESET_CFLAG(context);
4731 4732
        break;

4733
    case 0x3f: /* "READ" - READ FROM FILE OR DEVICE */
4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748
        TRACE( "READ from %d to %04lX:%04X for %d bytes\n",
               BX_reg(context),
               context->SegDs,
               DX_reg(context),
               CX_reg(context) );
        {
            DWORD result;
            WORD  count  = CX_reg(context);
            BYTE *buffer = CTX_SEG_OFF_TO_LIN( context, 
                                               context->SegDs,
                                               context->Edx );

            /* Some programs pass a count larger than the allocated buffer */
            if (DOSVM_IsWin16())
            {
4749
                DWORD maxcount = GetSelectorLimit16( context->SegDs )
4750 4751 4752 4753 4754 4755 4756 4757 4758 4759
                    - DX_reg(context) + 1;
                if (count > maxcount)
                    count = maxcount;
            }

            /*
             * FIXME: Reading from console (BX=1) in DOS mode
             *        does not work as it is supposed to work.
             */

4760
            RESET_CFLAG(context); /* set if error */
4761 4762 4763 4764 4765 4766 4767
            if (!DOSVM_IsWin16() && BX_reg(context) == 0)
            {
                result = INT21_BufferedInput( context, buffer, count );
                SET_AX( context, (WORD)result );
            }
            else if (ReadFile( DosFileHandleToWin32Handle(BX_reg(context)),
                               buffer, count, &result, NULL ))
4768 4769 4770 4771
                SET_AX( context, (WORD)result );
            else
                bSetDOSExtendedError = TRUE;
        }
4772 4773 4774
        break;

    case 0x40:  /* "WRITE" - WRITE TO FILE OR DEVICE */
4775 4776 4777 4778
        TRACE( "WRITE from %04lX:%04X to handle %d for %d byte\n",
               context->SegDs, DX_reg(context),
               BX_reg(context), CX_reg(context) );
        {
4779
            char *ptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
4780

4781 4782
            if (!DOSVM_IsWin16() && 
                (BX_reg(context) == 1 || BX_reg(context) == 2))
4783 4784 4785 4786 4787
            {
                int i;
                for(i=0; i<CX_reg(context); i++)
                    DOSVM_PutChar(ptr[i]);
                SET_AX(context, CX_reg(context));
4788
                RESET_CFLAG(context);
4789 4790 4791 4792 4793 4794 4795 4796
            }
            else
            {
                HFILE handle = (HFILE)DosFileHandleToWin32Handle(BX_reg(context));
                LONG result = _hwrite( handle, ptr, CX_reg(context) );
                if (result == HFILE_ERROR)
                    bSetDOSExtendedError = TRUE;
                else
4797
                {
4798
                    SET_AX( context, (WORD)result );
4799 4800
                    RESET_CFLAG(context);
                }
4801 4802
            }
        }
4803 4804
        break;

4805
    case 0x41: /* "UNLINK" - DELETE FILE */
4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816
        {
            WCHAR fileW[MAX_PATH];
            char *fileA = CTX_SEG_OFF_TO_LIN(context, 
                                             context->SegDs, 
                                             context->Edx);

            TRACE( "UNLINK %s\n", fileA );
            MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

            if (!DeleteFileW( fileW ))
                bSetDOSExtendedError = TRUE;
4817 4818
            else
                RESET_CFLAG(context);
4819 4820 4821
        }
        break;

4822
    case 0x42: /* "LSEEK" - SET CURRENT FILE POSITION */
4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839
        TRACE( "LSEEK handle %d offset %ld from %s\n",
               BX_reg(context), 
               MAKELONG( DX_reg(context), CX_reg(context) ),
               (AL_reg(context) == 0) ? 
               "start of file" : ((AL_reg(context) == 1) ? 
                                  "current file position" : "end of file") );
        {
            HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
            LONG   offset = MAKELONG( DX_reg(context), CX_reg(context) );
            DWORD  status = SetFilePointer( handle, offset, 
                                            NULL, AL_reg(context) );
            if (status == INVALID_SET_FILE_POINTER)
                bSetDOSExtendedError = TRUE;
            else
            {
                SET_AX( context, LOWORD(status) );
                SET_DX( context, HIWORD(status) );
4840
                RESET_CFLAG(context);
4841 4842 4843 4844
            }
        }
        break;

4845
    case 0x43: /* FILE ATTRIBUTES */
4846 4847
        if (!INT21_FileAttributes( context, AL_reg(context), FALSE ))
            bSetDOSExtendedError = TRUE;
4848 4849
        else
            RESET_CFLAG(context);
4850 4851
        break;

4852
    case 0x44: /* IOCTL */
4853 4854 4855 4856
        INT21_Ioctl( context );
        break;

    case 0x45: /* "DUP" - DUPLICATE FILE HANDLE */
4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871
        TRACE( "DUPLICATE FILE HANDLE %d\n", BX_reg(context) );
        {
            HANDLE handle32;
            HFILE  handle16 = HFILE_ERROR;

            if (DuplicateHandle( GetCurrentProcess(),
                                 DosFileHandleToWin32Handle(BX_reg(context)),
                                 GetCurrentProcess(), 
                                 &handle32,
                                 0, TRUE, DUPLICATE_SAME_ACCESS ))
                handle16 = Win32HandleToDosFileHandle(handle32);

            if (handle16 == HFILE_ERROR)
                bSetDOSExtendedError = TRUE;
            else
4872
            {
4873
                SET_AX( context, handle16 );
4874 4875
                RESET_CFLAG(context);
            }
4876 4877 4878
        }
        break;

4879
    case 0x46: /* "DUP2", "FORCEDUP" - FORCE DUPLICATE FILE HANDLE */
4880 4881
        TRACE( "FORCEDUP - FORCE DUPLICATE FILE HANDLE %d to %d\n",
               BX_reg(context), CX_reg(context) );
4882
        if (!INT21_Dup2(BX_reg(context), CX_reg(context)))
4883
            bSetDOSExtendedError = TRUE;
4884 4885
        else
            RESET_CFLAG(context);
4886 4887
        break;

4888
    case 0x47: /* "CWD" - GET CURRENT DIRECTORY */
4889 4890
        if (!INT21_GetCurrentDirectory( context, FALSE ))
            bSetDOSExtendedError = TRUE;
4891 4892
        else
            RESET_CFLAG(context);
4893 4894
        break;

4895
    case 0x48: /* ALLOCATE MEMORY */
4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906
        TRACE( "ALLOCATE MEMORY for %d paragraphs\n", BX_reg(context) );
        {
            WORD  selector = 0;
            DWORD bytes = (DWORD)BX_reg(context) << 4;

            if (!ISV86(context) && DOSVM_IsWin16())
            {
                DWORD rv = GlobalDOSAlloc16( bytes );
                selector = LOWORD( rv );
            }
            else
4907
                DOSMEM_AllocBlock( bytes, &selector );
4908

4909
            if (selector)
4910
            {
4911
                SET_AX( context, selector );
4912 4913
                RESET_CFLAG(context);
            }
4914 4915 4916 4917 4918 4919 4920 4921 4922
            else
            {
                SET_CFLAG(context);
                SET_AX( context, 0x0008 ); /* insufficient memory */
                SET_BX( context, DOSMEM_Available() >> 4 );
            }
        }
	break;

4923
    case 0x49: /* FREE MEMORY */
4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936
        TRACE( "FREE MEMORY segment %04lX\n", context->SegEs );
        {
            BOOL ok;
            
            if (!ISV86(context) && DOSVM_IsWin16())
            {
                ok = !GlobalDOSFree16( context->SegEs );

                /* If we don't reset ES_reg, we will fail in the relay code */
                if (ok)
                    context->SegEs = 0;
            }
            else
4937
                ok = DOSMEM_FreeBlock( PTR_REAL_TO_LIN(context->SegEs, 0) );
4938 4939 4940 4941 4942 4943 4944 4945 4946 4947

            if (!ok)
            {
                TRACE("FREE MEMORY failed\n");
                SET_CFLAG(context);
                SET_AX( context, 0x0009 ); /* memory block address invalid */
            }
	}
        break;

4948
    case 0x4a: /* RESIZE MEMORY BLOCK */
4949 4950 4951 4952 4953 4954 4955 4956
        TRACE( "RESIZE MEMORY segment %04lX to %d paragraphs\n", 
               context->SegEs, BX_reg(context) );
        {
            DWORD newsize = (DWORD)BX_reg(context) << 4;
            
            if (!ISV86(context) && DOSVM_IsWin16())
            {
                FIXME( "Resize memory block - unsupported under Win16\n" );
4957
                SET_CFLAG(context);
4958 4959 4960 4961 4962 4963
            }
            else
            {
                LPVOID address = (void*)((DWORD)context->SegEs << 4);
                UINT blocksize = DOSMEM_ResizeBlock( address, newsize, FALSE );

4964
                RESET_CFLAG(context);
4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977
                if (blocksize == (UINT)-1)
                {
                    SET_CFLAG( context );
                    SET_AX( context, 0x0009 ); /* illegal address */
                }
                else if(blocksize != newsize)
                {
                    SET_CFLAG( context );
                    SET_AX( context, 0x0008 );    /* insufficient memory */
                    SET_BX( context, blocksize >> 4 ); /* new block size */
                }
            }
        }
4978 4979 4980 4981
        break;

    case 0x4b: /* "EXEC" - LOAD AND/OR EXECUTE PROGRAM */
        {
4982
            char *program = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
4983 4984 4985 4986
            BYTE *paramblk = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Ebx);

            TRACE( "EXEC %s\n", program );

4987
            RESET_CFLAG(context);
4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001
            if (DOSVM_IsWin16())
            {
                HINSTANCE16 instance = WinExec16( program, SW_NORMAL );
                if (instance < 32)
                {
                    SET_CFLAG( context );
                    SET_AX( context, instance );
                }
            }
            else
            {
                if (!MZ_Exec( context, program, AL_reg(context), paramblk))
                    bSetDOSExtendedError = TRUE;
            }
5002 5003 5004 5005
        }
        break;

    case 0x4c: /* "EXIT" - TERMINATE WITH RETURN CODE */
5006 5007 5008
        TRACE( "EXIT with return code %d\n", AL_reg(context) );
        if (DOSVM_IsWin16())
            ExitThread( AL_reg(context) );
5009
        else if(ISV86(context))
5010
            MZ_Exit( context, FALSE, AL_reg(context) );
5011 5012 5013 5014 5015 5016 5017 5018
        else
        {
            /*
             * Exit from DPMI.
             */            
            DWORD rv = AL_reg(context);
            RaiseException( EXCEPTION_VM86_INTx, 0, 1, &rv );
        }
5019 5020 5021 5022
        break;

    case 0x4d: /* GET RETURN CODE */
        TRACE("GET RETURN CODE (ERRORLEVEL)\n");
5023
        SET_AX( context, DOSVM_retval );
5024 5025 5026
        DOSVM_retval = 0;
        break;

5027
    case 0x4e: /* "FINDFIRST" - FIND FIRST MATCHING FILE */
5028 5029 5030 5031 5032
        TRACE("FINDFIRST mask 0x%04x spec %s\n",CX_reg(context),
	      (LPCSTR)CTX_SEG_OFF_TO_LIN(context,  context->SegDs, context->Edx));
        if (!INT21_FindFirst(context)) break;
        /* fall through */

5033
    case 0x4f: /* "FINDNEXT" - FIND NEXT MATCHING FILE */
5034 5035 5036 5037 5038 5039 5040 5041
        TRACE("FINDNEXT\n");
        if (!INT21_FindNext(context))
        {
            SetLastError( ERROR_NO_MORE_FILES );
            SET_AX( context, ERROR_NO_MORE_FILES );
            SET_CFLAG(context);
        }
        else SET_AX( context, 0 );  /* OK */
5042 5043
        break;

5044 5045 5046 5047 5048 5049
    case 0x50: /* SET CURRENT PROCESS ID (SET PSP ADDRESS) */
        TRACE("SET CURRENT PROCESS ID (SET PSP ADDRESS)\n");
        DOSVM_psp = BX_reg(context);
        break;

    case 0x51: /* GET PSP ADDRESS */
5050
        INT21_GetPSP( context );
5051 5052 5053 5054
        break;

    case 0x52: /* "SYSVARS" - GET LIST OF LISTS */
        {
5055
            SEGPTR ptr = DOSDEV_GetLOL( ISV86(context) || !DOSVM_IsWin16() );
5056 5057
            context->SegEs = SELECTOROF(ptr);
            SET_BX( context, OFFSETOF(ptr) );
5058 5059 5060
        }
        break;

5061 5062 5063 5064 5065 5066
    case 0x54: /* Get Verify Flag */
        TRACE("Get Verify Flag - Not Supported\n");
        SET_AL( context, 0x00 );  /* pretend we can tell. 00h = off 01h = on */
        break;

    case 0x56: /* "RENAME" - RENAME FILE */
5067 5068
        if (!INT21_RenameFile( context ))
            bSetDOSExtendedError = TRUE;
5069 5070
        else
            RESET_CFLAG(context);
5071 5072
        break;

5073 5074 5075
    case 0x57: /* FILE DATE AND TIME */
        if (!INT21_FileDateTime( context ))
            bSetDOSExtendedError = TRUE;
5076 5077
        else
            RESET_CFLAG(context);
5078 5079
        break;

5080 5081 5082
    case 0x58: /* GET OR SET MEMORY ALLOCATION STRATEGY */
        switch (AL_reg(context))
        {
5083 5084 5085
        case 0x00: /* GET MEMORY ALLOCATION STRATEGY */
            TRACE( "GET MEMORY ALLOCATION STRATEGY\n" );
            SET_AX( context, 0 ); /* low memory first fit */
5086 5087 5088
            break;

        case 0x01: /* SET ALLOCATION STRATEGY */
5089
            TRACE( "SET MEMORY ALLOCATION STRATEGY to %d - ignored\n",
5090 5091 5092
                   BL_reg(context) );
            break;

5093 5094 5095 5096 5097 5098 5099 5100 5101 5102
        case 0x02: /* GET UMB LINK STATE */
            TRACE( "GET UMB LINK STATE\n" );
            SET_AL( context, 0 ); /* UMBs not part of DOS memory chain */
            break;

        case 0x03: /* SET UMB LINK STATE */
            TRACE( "SET UMB LINK STATE to %d - ignored\n",
                   BX_reg(context) );
            break;

5103 5104 5105 5106 5107
        default:
            INT_BARF( context, 0x21 );
        }
        break;

5108 5109 5110 5111 5112
    case 0x59: /* GET EXTENDED ERROR INFO */
        INT21_GetExtendedError( context );
        break;

    case 0x5a: /* CREATE TEMPORARY FILE */
5113 5114
        TRACE("CREATE TEMPORARY FILE\n");
        bSetDOSExtendedError = !INT21_CreateTempFile(context);
5115
        break;
5116

5117 5118 5119 5120
    case 0x5b: /* CREATE NEW FILE */ 
        if (!INT21_CreateFile( context, context->Edx, FALSE,
                               OF_READWRITE | OF_SHARE_COMPAT, 0x10 ))
            bSetDOSExtendedError = TRUE;
5121 5122
        else
            RESET_CFLAG(context);
5123 5124
        break;

5125 5126 5127 5128 5129 5130
    case 0x5c: /* "FLOCK" - RECORD LOCKING */
        {
            DWORD  offset = MAKELONG(DX_reg(context), CX_reg(context));
            DWORD  length = MAKELONG(DI_reg(context), SI_reg(context));
            HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));

5131
            RESET_CFLAG(context);
5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152
            switch (AL_reg(context))
            {
            case 0x00: /* LOCK */
                TRACE( "lock handle %d offset %ld length %ld\n",
                       BX_reg(context), offset, length );
                if (!LockFile( handle, offset, 0, length, 0 ))
                    bSetDOSExtendedError = TRUE;
                break;

            case 0x01: /* UNLOCK */
                TRACE( "unlock handle %d offset %ld length %ld\n",
                       BX_reg(context), offset, length );
                if (!UnlockFile( handle, offset, 0, length, 0 ))
                    bSetDOSExtendedError = TRUE;
                break;

            default:
                INT_BARF( context, 0x21 );
            }
        }
        break;
5153

5154
    case 0x5d: /* NETWORK 5D */
5155 5156 5157 5158 5159
        FIXME( "Network function 5D not implemented.\n" );
        SetLastError( ER_NoNetwork );
        bSetDOSExtendedError = TRUE;
        break;

5160
    case 0x5e: /* NETWORK 5E */
5161 5162 5163
        bSetDOSExtendedError = INT21_NetworkFunc( context);
        break;

5164
    case 0x5f: /* NETWORK 5F */
5165 5166 5167 5168 5169 5170 5171 5172 5173 5174
        /* FIXME: supporting this would need to 1:
         * - implement per drive current directory (as kernel32 doesn't)
         * - assign enabled/disabled flag on a per drive basis
         */
        /* network software not installed */
        TRACE("NETWORK function AX=%04x not implemented\n",AX_reg(context));
        SetLastError( ER_NoNetwork );
        bSetDOSExtendedError = TRUE;
        break;

5175
    case 0x60: /* "TRUENAME" - CANONICALIZE FILENAME OR PATH */
5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
        {
            WCHAR       pathW[MAX_PATH], res[MAX_PATH];
            /* FIXME: likely to be broken */

            TRACE("TRUENAME %s\n",
                  (LPCSTR)CTX_SEG_OFF_TO_LIN(context, context->SegDs,context->Esi));
            MultiByteToWideChar(CP_OEMCP, 0, CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Esi), -1, pathW, MAX_PATH);
            if (!GetFullPathNameW( pathW, 128, res, NULL ))
		bSetDOSExtendedError = TRUE;
            else
            {
                SET_AX( context, 0 );
                WideCharToMultiByte(CP_OEMCP, 0, res, -1, 
                                    CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Edi), 
                                    128, NULL, NULL);
            }
        }
5193 5194
        break;

5195 5196 5197 5198
    case 0x61: /* UNUSED */
        SET_AL( context, 0 );
        break;

5199
    case 0x62: /* GET PSP ADDRESS */
5200
        INT21_GetPSP( context );
5201 5202
        break;

5203
    case 0x63: /* MISC. LANGUAGE SUPPORT */
5204 5205 5206 5207 5208 5209 5210 5211
        switch (AL_reg(context)) {
        case 0x00: /* GET DOUBLE BYTE CHARACTER SET LEAD-BYTE TABLE */
            TRACE( "GET DOUBLE BYTE CHARACTER SET LEAD-BYTE TABLE\n" );
            context->SegDs = INT21_GetHeapSelector( context );
            SET_SI( context, offsetof(INT21_HEAP, dbcs_table) );
            SET_AL( context, 0 ); /* success */
            break;
        }
5212 5213
        break;

5214
    case 0x64: /* OS/2 DOS BOX */
5215 5216 5217 5218
        INT_BARF( context, 0x21 );
        SET_CFLAG(context);
    	break;

5219 5220 5221 5222
    case 0x65: /* EXTENDED COUNTRY INFORMATION */
        INT21_ExtendedCountryInformation( context );
        break;

5223
    case 0x66: /* GLOBAL CODE PAGE TABLE */
5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235
        switch (AL_reg(context))
        {
        case 0x01:
            TRACE( "GET GLOBAL CODE PAGE TABLE\n" );
            SET_BX( context, GetOEMCP() );
            SET_DX( context, GetOEMCP() );
            break;
        case 0x02:
            FIXME( "SET GLOBAL CODE PAGE TABLE, active %d, system %d - ignored\n",
                   BX_reg(context), DX_reg(context) );
            break;
        }
5236 5237
        break;

5238
    case 0x67: /* SET HANDLE COUNT */
5239 5240 5241 5242 5243
        TRACE( "SET HANDLE COUNT to %d\n", BX_reg(context) );
        if (SetHandleCount( BX_reg(context) ) < BX_reg(context) )
            bSetDOSExtendedError = TRUE;
        break;

5244
    case 0x68: /* "FFLUSH" - COMMIT FILE */
5245 5246 5247 5248 5249
        TRACE( "FFLUSH - handle %d\n", BX_reg(context) );
        if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
            bSetDOSExtendedError = TRUE;
        break;

5250
    case 0x69: /* DISK SERIAL NUMBER */
5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266
        switch (AL_reg(context))
        {
        case 0x00:
	    TRACE("GET DISK SERIAL NUMBER for drive %s\n",
		  INT21_DriveName(BL_reg(context)));
            if (!INT21_GetDiskSerialNumber(context)) bSetDOSExtendedError = TRUE;
            else SET_AX( context, 0 );
            break;

        case 0x01:
	    TRACE("SET DISK SERIAL NUMBER for drive %s\n",
		  INT21_DriveName(BL_reg(context)));
            if (!INT21_SetDiskSerialNumber(context)) bSetDOSExtendedError = TRUE;
            else SET_AX( context, 1 );
            break;
        }
5267 5268
        break;

5269 5270 5271 5272 5273 5274
    case 0x6a: /* COMMIT FILE */
        TRACE( "COMMIT FILE - handle %d\n", BX_reg(context) );
        if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
            bSetDOSExtendedError = TRUE;
        break;

5275 5276 5277 5278 5279
    case 0x6b: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
        SET_AL( context, 0 );
        break;

    case 0x6c: /* EXTENDED OPEN/CREATE */
5280 5281 5282
        if (!INT21_CreateFile( context, context->Esi, TRUE,
                               BX_reg(context), DL_reg(context) ))
            bSetDOSExtendedError = TRUE;
5283 5284 5285 5286 5287 5288 5289 5290 5291
        break;

    case 0x70: /* MSDOS 7 - GET/SET INTERNATIONALIZATION INFORMATION */
        FIXME( "MS-DOS 7 - GET/SET INTERNATIONALIZATION INFORMATION\n" );
        SET_CFLAG( context );
        SET_AL( context, 0 );
        break;

    case 0x71: /* MSDOS 7 - LONG FILENAME FUNCTIONS */
5292
        INT21_LongFilename( context );
5293 5294 5295
        break;

    case 0x73: /* MSDOS7 - FAT32 */
5296
        RESET_CFLAG( context );
5297 5298
        if (!INT21_Fat32( context ))
            bSetDOSExtendedError = TRUE;
5299 5300
        break;

5301
    case 0xdc: /* CONNECTION SERVICES - GET CONNECTION NUMBER */
5302 5303 5304
        TRACE( "CONNECTION SERVICES - GET CONNECTION NUMBER - ignored\n" );
        break;

5305
    case 0xea: /* NOVELL NETWARE - RETURN SHELL VERSION */
5306
        TRACE( "NOVELL NETWARE - RETURN SHELL VERSION - ignored\n" );
5307 5308
        break;

5309 5310 5311 5312 5313
    case 0xff: /* DOS32 EXTENDER (DOS/4GW) - API */
	/* we don't implement a DOS32 extender */
        TRACE( "DOS32 EXTENDER API - ignored\n" );
        break;

5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324
    default:
        INT_BARF( context, 0x21 );
        break;

    } /* END OF SWITCH */

    /* Set general error condition. */
    if (bSetDOSExtendedError)
    {
        SET_AX( context, GetLastError() );
        SET_CFLAG( context );
5325
    }
5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337

    /* Print error code if carry flag is set. */
    if (context->EFlags & 0x0001)
        TRACE("failed, error %ld\n", GetLastError() );

    TRACE( "returning: AX=%04x BX=%04x CX=%04x DX=%04x "
           "SI=%04x DI=%04x DS=%04x ES=%04x EFL=%08lx\n",
           AX_reg(context), BX_reg(context), 
           CX_reg(context), DX_reg(context), 
           SI_reg(context), DI_reg(context),
           (WORD)context->SegDs, (WORD)context->SegEs,
           context->EFlags );
5338
}