int21.c 116 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 23
 *
 * 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
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24 25 26 27 28 29
 */

#include "config.h"

#include "windef.h"
#include "winbase.h"
30
#include "winternl.h"
31 32 33 34
#include "wine/winbase16.h"
#include "dosexe.h"
#include "miscemu.h"
#include "msdos.h"
35
#include "file.h"
36
#include "task.h"
37
#include "winerror.h"
38
#include "winuser.h"
39
#include "wine/unicode.h"
40
#include "wine/debug.h"
41

42 43 44 45 46
/*
 * FIXME: Delete this reference when all int21 code has been moved to winedos.
 */
extern void WINAPI INT_Int21Handler( CONTEXT86 *context );

47 48 49 50 51
/*
 * Forward declarations.
 */
static BOOL INT21_RenameFile( CONTEXT86 *context );

52
WINE_DEFAULT_DEBUG_CHANNEL(int21);
53

54

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#include "pshpack1.h"

/*
 * 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 */

    BYTE misc_indos;                 /* Interrupt 21 nesting flag */
} INT21_HEAP;


90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
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];
};

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
#include "poppack.h"


/***********************************************************************
 *           INT21_GetCurrentDrive
 *
 * Return current drive using scheme (0=A:, 1=B:, 2=C:, ...) or
 * MAX_DOS_DRIVES on error.
 */
static BYTE INT21_GetCurrentDrive()
{
    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)
150 151 152 153 154 155 156 157 158 159
    {
        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;

160
        return drive - 1;
161 162
    }

163 164 165
    return INT21_GetCurrentDrive();
}

166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
/***********************************************************************
 *           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" );
}


183 184 185 186 187 188
/***********************************************************************
 *           INT21_ReadChar
 *
 * Reads a character from the standard input.
 * Extended keycodes will be returned as two separate characters.
 */
189
static BOOL INT21_ReadChar( BYTE *input, CONTEXT86 *waitctx )
190 191 192 193 194 195 196
{
    static BYTE pending_scan = 0;

    if (pending_scan)
    {
        if (input)
            *input = pending_scan;
197
        if (waitctx)
198 199 200 201 202 203 204
            pending_scan = 0;
        return TRUE;
    }
    else
    {
        BYTE ascii;
        BYTE scan;
205
        if (!DOSVM_Int16ReadChar( &ascii, &scan, waitctx ))
206 207 208 209
            return FALSE;

        if (input)
            *input = ascii;
210
        if (waitctx && !ascii)
211 212 213 214 215 216
            pending_scan = scan;
        return TRUE;
    }
}


217 218 219 220 221
/***********************************************************************
 *           INT21_GetSystemCountryCode
 *
 * Return DOS country code for default system locale.
 */
222
static WORD INT21_GetSystemCountryCode( void )
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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
{
    /*
     * 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.
 */
static void INT21_FillHeap( INT21_HEAP *heap )
{
    static const char terminators[] = "\"\\./[]:|<>+=;,";
    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);
    strcpy( heap->filename_illegal_table, terminators );

    heap->filename_reserved1 = 0x01;
    heap->filename_lowest = 0;           /* FIXME: correct value? */
    heap->filename_highest = 0xff;       /* FIXME: correct value? */
    heap->filename_reserved2 = 0x00;    
    heap->filename_exclude_first = 0x00; /* FIXME: correct value? */
    heap->filename_exclude_last = 0x00;  /* FIXME: correct value? */
    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;
}


/***********************************************************************
 *           INT21_GetHeapSelector
 *
 * Get segment/selector for DOS heap (INT21_HEAP).
 * Creates and initializes heap on first call.
 */
static WORD INT21_GetHeapSelector( CONTEXT86 *context )
{
    static WORD heap_segment = 0;
    static WORD heap_selector = 0;
    static BOOL heap_initialized = FALSE;

    if (!heap_initialized)
    {
        INT21_HEAP *ptr = DOSVM_AllocDataUMB( sizeof(INT21_HEAP), 
                                              &heap_segment,
                                              &heap_selector );
        INT21_FillHeap( ptr );
        heap_initialized = TRUE;
    }

    if (!ISV86(context) && DOSVM_IsWin16())
        return heap_selector;
    else
        return heap_segment;
}


383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 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 488 489 490 491 492 493 494 495 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
/***********************************************************************
 *           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);
    BYTE   new_drive = INT21_MapDrive( DL_reg(context) );
    BYTE   old_drive = INT21_GetCurrentDrive();
    WCHAR  pathW[MAX_PATH];
    char   pathA[MAX_PATH];
    WCHAR *ptr = pathW;

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

    if (new_drive == MAX_DOS_DRIVES)
    {        
        SetLastError(ERROR_INVALID_DRIVE);
        return FALSE;
    }
    
    /*
     * Grab current directory.
     */

    INT21_SetCurrentDrive( new_drive );
    if (!GetCurrentDirectoryW( MAX_PATH, pathW ))
    {        
        INT21_SetCurrentDrive( old_drive );
        return FALSE;
    }
    INT21_SetCurrentDrive( old_drive );

    /*
     * 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;
    }

    TRACE( "%c:=%s\n", 'A' + new_drive, pathA );

    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];
    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);
    result = SetCurrentDirectoryW( dirW );

    /* This function must not change current drive. */
    INT21_SetCurrentDrive( drive );

    return result;
}


521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 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 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 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 647 648 649 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 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
/***********************************************************************
 *           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);

        if (dosAttributes & FILE_ATTRIBUTE_LABEL)
        {
            /*
             * 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);

    winHandle = CreateFileW( pathW, winAccess, winSharing, NULL, 
                             winMode, winAttributes, 0 );

    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;
    }

    /*
     * 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;
}


724 725 726
/***********************************************************************
 *           INT21_BufferedInput
 *
727 728
 * Handler for function 0x0a and reading from console using
 * function 0x3f.
729 730
 *
 * Reads a string of characters from standard input until
731 732 733
 * enter key is pressed. Returns either number of characters 
 * read from console including terminating CR or 
 * zero if capacity was zero.
734
 */
735
static WORD INT21_BufferedInput( CONTEXT86 *context, BYTE *ptr, WORD capacity )
736
{
737
    BYTE length = 0;
738 739 740 741 742

    /*
     * Return immediately if capacity is zero.
     */
    if (capacity == 0)
743
        return 0;
744 745 746 747 748 749

    while(TRUE)
    {
        BYTE ascii;
        BYTE scan;

750
        DOSVM_Int16ReadChar( &ascii, &scan, context );
751 752 753 754 755 756 757 758

        if (ascii == '\r' || ascii == '\n')
        {
            /*
             * FIXME: What should be echoed here?
             */
            DOSVM_PutChar( '\r' );
            DOSVM_PutChar( '\n' );
759 760
            ptr[length] = '\r';
            return length + 1;
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
        }

        /*
         * FIXME: This function is supposed to support
         *        DOS editing keys...
         */

        /*
         * 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 );
776
            ptr[length] = ascii;
777 778 779 780 781 782
            length++;
        }
    }
}


783 784 785 786
/***********************************************************************
 *           INT21_GetCurrentDTA
 */
static BYTE *INT21_GetCurrentDTA( CONTEXT86 *context )
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
{
    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;
831
    file_path[0] = 'A' + INT21_MapDrive( fcb->drive_number );
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924

    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) {
925
        TRACE("_lclose16(%d) failed\n", fcb->file_number);
926 927 928 929 930 931 932 933 934 935
        AL_result = 0xff; /* failed */
    } else {
        TRACE("successful closed file %d\n", fcb->file_number);
        AL_result = 0x00; /* successful */
    } /* if */
    SET_AL(context, AL_result);
}


/***********************************************************************
936
 *           INT21_SequentialReadFromFCB
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
 *
 * 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.
 */
957
static void INT21_SequentialReadFromFCB( CONTEXT86 *context )
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
{
    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 {
987
            disk_transfer_area = INT21_GetCurrentDTA(context);
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
            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);
}


/***********************************************************************
1018
 *           INT21_SequentialWriteToFCB
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
 *
 * 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. 
 */
1037
static void INT21_SequentialWriteToFCB( CONTEXT86 *context )
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
{
    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 {
1067
            disk_transfer_area = INT21_GetCurrentDTA(context);
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 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 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
            bytes_written = _lwrite((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
            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 {
1143
            disk_transfer_area = INT21_GetCurrentDTA(context);
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
            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 {
1216
            disk_transfer_area = INT21_GetCurrentDTA(context);
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 1256 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
            bytes_written = _lwrite((HFILE) handle, disk_transfer_area, fcb->logical_record_size);
            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 {
1296
            disk_transfer_area = INT21_GetCurrentDTA(context);
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 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
            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 {
1387
            disk_transfer_area = INT21_GetCurrentDTA(context);
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
            records_requested = CX_reg(context);
            bytes_requested = (UINT) records_requested * fcb->logical_record_size;
            bytes_written = _lwrite((HFILE) handle, disk_transfer_area, bytes_requested);
            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);
}


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 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
/***********************************************************************
 *           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;
}


1456 1457 1458 1459 1460 1461 1462 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 1492 1493 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 1568 1569 1570 1571 1572 1573 1574 1575 1576
/***********************************************************************
 *           INT21_ExtendedCountryInformation
 *
 * Handler for function 0x65.
 */
static void INT21_ExtendedCountryInformation( CONTEXT86 *context )
{
    BYTE *dataptr = CTX_SEG_OFF_TO_LIN( context, context->SegEs, context->Edi );

    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 */
        INT21_FillCountryInformation( dataptr + 7 );
        SET_CX( context, 41 ); /* Size of returned info */
        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");
        _strupr( (LPSTR)CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx) );
        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;
    }
}


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 1641 1642 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 1721 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 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
/***********************************************************************
 *           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 );
        if (result == -1)
            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;
}


1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 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 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 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 1921 1922 1923 1924 1925 1926 1927
/***********************************************************************
 *           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;
}


1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
/***********************************************************************
 *           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 );
}


1948 1949 1950 1951 1952 1953 1954
/***********************************************************************
 *           INT21_Ioctl_Block
 *
 * Handler for block device IOCTLs.
 */
static void INT21_Ioctl_Block( CONTEXT86 *context )
{
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 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 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 2039 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
    BYTE *dataptr;
    BYTE  drive = INT21_MapDrive( BL_reg(context) );
    WCHAR drivespec[4] = {'A', ':', '\\', 0};
    UINT  drivetype;

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

    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 */
        /* Get pointer to IOCTL parameter block. */
        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);
            {
                WORD head   = *(WORD *)dataptr+1;
                WORD cyl    = *(WORD *)dataptr+3;
                WORD sect   = *(WORD *)dataptr+5;
                WORD nrsect = *(WORD *)dataptr+7;
                BYTE *data  =  (BYTE *)dataptr+9; /* FIXME: is this correct? */

                if (!DOSVM_RawWrite(drive, head*cyl*sect, nrsect, data, FALSE))
                {
                    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 */
            INT_Int21Handler( context );
            break;

        case 0x0861: /* read logical device track */
            TRACE( "GENERIC IOCTL - Read logical device track - %c:\n",
                   'A' + drive);
            {
                WORD head   = *(WORD *)dataptr+1;
                WORD cyl    = *(WORD *)dataptr+3;
                WORD sect   = *(WORD *)dataptr+5;
                WORD nrsect = *(WORD *)dataptr+7;
                BYTE *data  =  (BYTE *)dataptr+9; /* FIXME: is this correct? */

                if (!DOSVM_RawRead(drive, head*cyl*sect, nrsect, data, FALSE))
                {
                    SET_AX( context, ERROR_READ_FAULT );
                    SET_CFLAG(context);
                }
            }
            break;

        case 0x0866: /* get volume serial number */
            INT_Int21Handler( context );
            break;

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

        case 0x086f: /* get drive map information */
            INT_Int21Handler( context );
            break;

        case 0x0872:
            INT_Int21Handler( context );
            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 */
        INT_Int21Handler( context );
        break;

    case 0x11: /* QUERY GENERIC IOCTL CAPABILITY */
    default:
        INT_BARF( context, 0x21 );
    }
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
}


/***********************************************************************
 *           INT21_Ioctl_Char
 *
 * Handler for character device IOCTLs.
 */
static void INT21_Ioctl_Char( CONTEXT86 *context )
{
    static const WCHAR emmxxxx0W[] = {'E','M','M','X','X','X','X','0',0};
    static const WCHAR scsimgrW[] = {'S','C','S','I','M','G','R','$',0};

    HANDLE handle = DosFileHandleToWin32Handle(BX_reg(context));
    const DOS_DEVICE *dev = DOSFS_GetDeviceByHandle(handle);

    if (dev && !strcmpiW( dev->name, emmxxxx0W )) 
    {
        EMS_Ioctl_Handler(context);
        return;
    }

    if (dev && !strcmpiW( dev->name, scsimgrW ) && AL_reg(context) == 2)
    {
        DOSVM_ASPIHandler(context);
        return;
    }

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
    switch (AL_reg(context))
    {
    case 0x00: /* GET DEVICE INFORMATION */
        TRACE( "IOCTL - GET DEVICE INFORMATION - %d\n", BX_reg(context) );
        if (dev)
        {
            /*
             * 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.
             *   Bit  1 - Standard output.
             *   Bit  0 - Standard input.
             */
            SET_DX( context, dev->flags );
        }
        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 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 */
        INT_BARF( context, 0x21 );
        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;

    case 0x0c: /* GENERIC CHARACTER DEVICE REQUEST */
    case 0x10: /* QUERY GENERIC IOCTL CAPABILITY */
    default:
        INT_BARF( context, 0x21 );
    }
2184 2185 2186
}


2187 2188
/***********************************************************************
 *           INT21_Ioctl
2189 2190
 *
 * Handler for function 0x44.
2191 2192
 */
static void INT21_Ioctl( CONTEXT86 *context )
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 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
    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
        {
            DOSMEM_LOL()->sharing_retry_delay = CX_reg(context);
            if (DX_reg(context))
                DOSMEM_LOL()->sharing_retry_count = DX_reg(context);
            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 );
    }
2277
}
2278

2279

2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
/***********************************************************************
 *           INT21_LongFilename
 *
 * Handler for function 0x71.
 */
static void INT21_LongFilename( CONTEXT86 *context )
{
    BOOL bSetDOSExtendedError = FALSE;

    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 */
2300
        INT_BARF( context, 0x21 );
2301 2302
        break;

2303 2304 2305 2306 2307
    case 0x39: /* LONG FILENAME - MAKE DIRECTORY */
        if (!INT21_CreateDirectory( context ))
            bSetDOSExtendedError = TRUE;
        break;

2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
    case 0x3a: /* LONG FILENAME - REMOVE DIRECTORY */
        {
            WCHAR dirW[MAX_PATH];
            char *dirA = CTX_SEG_OFF_TO_LIN(context,
                                            context->SegDs, context->Edx);

            TRACE( "LONG FILENAME - REMOVE DIRECTORY %s\n", dirA );
            MultiByteToWideChar(CP_OEMCP, 0, dirA, -1, dirW, MAX_PATH);

            if (!RemoveDirectoryW( dirW ))
                bSetDOSExtendedError = TRUE;
        }
        break;

    case 0x3b: /* LONG FILENAME - CHANGE DIRECTORY */
2323 2324
        if (!INT21_SetCurrentDirectory( context ))
            bSetDOSExtendedError = TRUE;
2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
        break;

    case 0x41: /* LONG FILENAME - DELETE FILE */
        {
            WCHAR fileW[MAX_PATH];
            char *fileA = CTX_SEG_OFF_TO_LIN(context, 
                                             context->SegDs, context->Edx);

            TRACE( "LONG FILENAME - DELETE FILE %s\n", fileA );
            MultiByteToWideChar(CP_OEMCP, 0, fileA, -1, fileW, MAX_PATH);

            if (!DeleteFileW( fileW ))
                bSetDOSExtendedError = TRUE;
        }
        break;

    case 0x43: /* LONG FILENAME - EXTENDED GET/SET FILE ATTRIBUTES */
2342 2343 2344 2345
        if (!INT21_FileAttributes( context, BL_reg(context), TRUE ))
            bSetDOSExtendedError = TRUE;
        break;

2346
    case 0x47: /* LONG FILENAME - GET CURRENT DIRECTORY */
2347 2348 2349 2350
        if (!INT21_GetCurrentDirectory( context, TRUE ))
            bSetDOSExtendedError = TRUE;
        break;

2351 2352 2353 2354 2355 2356
    case 0x4e: /* LONG FILENAME - FIND FIRST MATCHING FILE */
    case 0x4f: /* LONG FILENAME - FIND NEXT MATCHING FILE */
        INT_Int21Handler( context );
        break;

    case 0x56: /* LONG FILENAME - RENAME FILE */
2357 2358
        if (!INT21_RenameFile(context))
            bSetDOSExtendedError = TRUE;
2359 2360 2361
        break;

    case 0x60: /* LONG FILENAME - CONVERT PATH */
2362 2363 2364
        INT_Int21Handler( context );
        break;

2365
    case 0x6c: /* LONG FILENAME - CREATE OR OPEN FILE */
2366 2367 2368 2369 2370
        if (!INT21_CreateFile( context, context->Esi, TRUE,
                               BX_reg(context), DL_reg(context) ))
            bSetDOSExtendedError = TRUE;
        break;

2371 2372
    case 0xa0: /* LONG FILENAME - GET VOLUME INFORMATION */
    case 0xa1: /* LONG FILENAME - "FindClose" - TERMINATE DIRECTORY SEARCH */
2373 2374 2375
        INT_Int21Handler( context );
        break;

2376
    case 0xa6: /* LONG FILENAME - GET FILE INFO BY HANDLE */
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
        {
            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;

2389
    case 0xa7: /* LONG FILENAME - CONVERT TIME */
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 2432 2433 2434 2435 2436
        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;

2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
    case 0xa8: /* LONG FILENAME - GENERATE SHORT FILENAME */
    case 0xa9: /* LONG FILENAME - SERVER CREATE OR OPEN FILE */
    case 0xaa: /* LONG FILENAME - SUBST */
    default:
        INT_BARF( context, 0x21 );
    }

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


2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
/***********************************************************************
 *           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 );
}


2477
/***********************************************************************
2478
 *           INT21_GetExtendedError
2479
 */
2480
static void INT21_GetExtendedError( CONTEXT86 *context )
2481
{
2482 2483
    BYTE class, action, locus;
    WORD error = GetLastError();
2484

2485
    switch(error)
2486
    {
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
    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;
    case ER_GeneralFailure:
        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 );
}
2591

2592

2593
/***********************************************************************
2594
 *           DOSVM_Int21Handler
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
 *
 * 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. */
2619

2620 2621 2622 2623
    switch(AH_reg(context))
    {
    case 0x00: /* TERMINATE PROGRAM */
        TRACE("TERMINATE PROGRAM\n");
2624 2625 2626 2627
        if (DOSVM_IsWin16())
            ExitThread( 0 );
        else
            MZ_Exit( context, FALSE, 0 );
2628 2629 2630
        break;

    case 0x01: /* READ CHARACTER FROM STANDARD INPUT, WITH ECHO */
2631 2632 2633
        {
            BYTE ascii;
            TRACE("DIRECT CHARACTER INPUT WITH ECHO\n");
2634
            INT21_ReadChar( &ascii, context );
2635
            SET_AL( context, ascii );
2636 2637 2638
            /*
             * FIXME: What to echo when extended keycodes are read?
             */
2639 2640
            DOSVM_PutChar(AL_reg(context));
        }
2641
        break;
2642 2643 2644

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

2648 2649 2650 2651 2652 2653
    case 0x03: /* READ CHARACTER FROM STDAUX  */
    case 0x04: /* WRITE CHARACTER TO STDAUX */
    case 0x05: /* WRITE CHARACTER TO PRINTER */
        INT_BARF( context, 0x21 );
        break;

2654
    case 0x06: /* DIRECT CONSOLE IN/OUTPUT */
2655 2656
        if (DL_reg(context) == 0xff) 
        {
2657
            TRACE("Direct Console Input\n");
2658

2659
            if (INT21_ReadChar( NULL, NULL ))
2660
            {
2661
                BYTE ascii;
2662
                INT21_ReadChar( &ascii, context );
2663 2664 2665 2666 2667 2668 2669 2670
                SET_AL( context, ascii );
                RESET_ZFLAG( context );
            }
            else
            {
                /* no character available */
                SET_AL( context, 0 );
                SET_ZFLAG( context );
2671
            }
2672 2673 2674
        } 
        else 
        {
2675
            TRACE("Direct Console Output\n");
2676
            DOSVM_PutChar(DL_reg(context));
2677 2678 2679 2680 2681
            /*
             * At least DOS versions 2.1-7.0 return character 
             * that was written in AL register.
             */
            SET_AL( context, DL_reg(context) );
2682 2683 2684 2685
        }
        break;

    case 0x07: /* DIRECT CHARACTER INPUT WITHOUT ECHO */
2686 2687 2688
        {
            BYTE ascii;
            TRACE("DIRECT CHARACTER INPUT WITHOUT ECHO\n");
2689
            INT21_ReadChar( &ascii, context );
2690 2691
            SET_AL( context, ascii );
        }
2692 2693 2694
        break;

    case 0x08: /* CHARACTER INPUT WITHOUT ECHO */
2695 2696 2697
        {
            BYTE ascii;
            TRACE("CHARACTER INPUT WITHOUT ECHO\n");
2698
            INT21_ReadChar( &ascii, context );
2699 2700 2701 2702 2703
            SET_AL( context, ascii );
        }
        break;

    case 0x09: /* WRITE STRING TO STANDARD OUTPUT */
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
        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;

            /*
             * 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), 
                           data, p - data, 0, 0 );
            else
                for(; data != p; data++)
                    DOSVM_PutChar( *data );

            SET_AL( context, '$' ); /* yes, '$' (0x24) gets returned in AL */
        }
2727 2728 2729
        break;

    case 0x0a: /* BUFFERED INPUT */
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
        {
            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;
        }
2757 2758 2759
        break;

    case 0x0b: /* GET STDIN STATUS */
2760
        TRACE( "GET STDIN STATUS\n" );
2761
        {
2762
            if (INT21_ReadChar( NULL, NULL ))
2763
                SET_AL( context, 0xff ); /* character available */
Nog's avatar
Nog committed
2764
            else
2765
                SET_AL( context, 0 ); /* no character available */
2766 2767 2768
        }
        break;

2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
    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 */
2794 2795 2796
        TRACE( "SELECT DEFAULT DRIVE - %c:\n", 'A' + DL_reg(context) );
        INT21_SetCurrentDrive( DL_reg(context) );
        SET_AL( context, MAX_DOS_DRIVES );
2797 2798 2799
        break;

    case 0x0f: /* OPEN FILE USING FCB */
2800 2801 2802
        INT21_OpenFileUsingFCB( context );
        break;

2803
    case 0x10: /* CLOSE FILE USING FCB */
2804
        INT21_CloseFileUsingFCB( context );
2805 2806 2807 2808 2809 2810 2811
        break;

    case 0x11: /* FIND FIRST MATCHING FILE USING FCB */
    case 0x12: /* FIND NEXT MATCHING FILE USING FCB */
        INT_Int21Handler( context );
        break;

2812
    case 0x13: /* DELETE FILE USING FCB */
2813 2814 2815
        INT_BARF( context, 0x21 );
        break;

2816
    case 0x14: /* SEQUENTIAL READ FROM FCB FILE */
2817
        INT21_SequentialReadFromFCB( context );
2818 2819
        break;

2820
    case 0x15: /* SEQUENTIAL WRITE TO FCB FILE */
2821
        INT21_SequentialWriteToFCB( context );
2822 2823
        break;

2824 2825
    case 0x16: /* CREATE OR TRUNCATE FILE USING FCB */
    case 0x17: /* RENAME FILE USING FCB */
2826
        INT_BARF( context, 0x21 );
2827 2828 2829 2830 2831 2832 2833
        break;

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

    case 0x19: /* GET CURRENT DEFAULT DRIVE */
2834 2835
        SET_AL( context, INT21_GetCurrentDrive() );
        TRACE( "GET CURRENT DRIVE -> %c:\n", 'A' + AL_reg( context ) );
2836 2837
        break;

2838
    case 0x1a: /* SET DISK TRANSFER AREA ADDRESS */
2839 2840 2841 2842 2843 2844 2845 2846 2847
        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 */
2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
    case 0x1c: /* GET ALLOCATION INFORMATION FOR SPECIFIC DRIVE */
        INT_Int21Handler( context );
        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 */
        INT_Int21Handler( context );
        break;

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

    case 0x21: /* READ RANDOM RECORD FROM FCB FILE */
2866 2867 2868
        INT21_ReadRandomRecordFromFCB( context );
        break;

2869
    case 0x22: /* WRITE RANDOM RECORD TO FCB FILE */
2870 2871 2872
        INT21_WriteRandomRecordToFCB( context );
        break;

2873 2874 2875 2876 2877
    case 0x23: /* GET FILE SIZE FOR FCB */
    case 0x24: /* SET RANDOM RECORD NUMBER FOR FCB */
        INT_BARF( context, 0x21 );
        break;

2878
    case 0x25: /* SET INTERRUPT VECTOR */
2879 2880 2881
        TRACE("SET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
        {
            FARPROC16 ptr = (FARPROC16)MAKESEGPTR( context->SegDs, DX_reg(context) );
2882
            if (!ISV86(context) && DOSVM_IsWin16())
2883 2884 2885 2886 2887 2888 2889
                DOSVM_SetPMHandler16(  AL_reg(context), ptr );
            else
                DOSVM_SetRMHandler( AL_reg(context), ptr );
        }
        break;

    case 0x26: /* CREATE NEW PROGRAM SEGMENT PREFIX */
2890 2891 2892
        INT_BARF( context, 0x21 );
        break;

2893
    case 0x27: /* RANDOM BLOCK READ FROM FCB FILE */
2894 2895 2896
        INT21_RandomBlockReadFromFCB( context );
        break;

2897
    case 0x28: /* RANDOM BLOCK WRITE TO FCB FILE */
2898
        INT21_RandomBlockWriteToFCB( context );
2899 2900 2901 2902 2903 2904
        break;

    case 0x29: /* PARSE FILENAME INTO FCB */
        INT_Int21Handler( context );
        break;

2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916
    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;

2917
    case 0x2b: /* SET SYSTEM DATE */
2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
        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 */
            }
        }
2937 2938 2939
        break;

    case 0x2c: /* GET SYSTEM TIME */
2940 2941 2942 2943
        TRACE( "GET SYSTEM TIME\n" );
        {
            SYSTEMTIME systime;
            GetLocalTime( &systime );
2944 2945
            SET_CH( context, systime.wHour );
            SET_CL( context, systime.wMinute );
2946 2947 2948
            SET_DH( context, systime.wSecond );
            SET_DL( context, systime.wMilliseconds / 10 );
        }
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
        break;

    case 0x2d: /* SET SYSTEM TIME */
        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 */
        break;

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

2963 2964 2965 2966 2967 2968 2969
    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 ) );
        }
2970 2971
        break;

2972 2973 2974 2975 2976 2977 2978 2979 2980
    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 */

2981 2982 2983 2984
        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 # */
2985 2986 2987
        SET_CX( context, 0x3456 );
        break;

2988 2989 2990 2991 2992 2993
    case 0x31: /* TERMINATE AND STAY RESIDENT */
        FIXME("TERMINATE AND STAY RESIDENT stub\n");
        break;

    case 0x32: /* GET DOS DRIVE PARAMETER BLOCK FOR SPECIFIC DRIVE */
        INT_Int21Handler( context );
2994 2995
        break;

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 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
    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;

3044 3045 3046 3047 3048 3049
    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;

3050 3051 3052
    case 0x35: /* GET INTERRUPT VECTOR */
        TRACE("GET INTERRUPT VECTOR 0x%02x\n",AL_reg(context));
        {
3053
            FARPROC16 addr;
3054
            if (!ISV86(context) && DOSVM_IsWin16())
3055 3056 3057
                addr = DOSVM_GetPMHandler16( AL_reg(context) );
            else
                addr = DOSVM_GetRMHandler( AL_reg(context) );
3058
            context->SegEs = SELECTOROF(addr);
3059
            SET_BX( context, OFFSETOF(addr) );
3060 3061 3062
        }
        break;

3063 3064 3065 3066
    case 0x36: /* GET FREE DISK SPACE */
        INT_Int21Handler( context );
        break;

3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087
    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;

3088
    case 0x38: /* GET COUNTRY-SPECIFIC INFORMATION */
3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
        TRACE( "GET COUNTRY-SPECIFIC INFORMATION\n" );
        if (AL_reg(context)) 
        {
            WORD country = AL_reg(context);
            if (country == 0xff)
                country = BX_reg(context);
            if (country != INT21_GetSystemCountryCode())
                FIXME( "Requested info on non-default country %04x\n", country );
        }
        INT21_FillCountryInformation( CTX_SEG_OFF_TO_LIN(context, 
                                                         context->SegDs, 
                                                         context->Edx) );
        SET_AX( context, INT21_GetSystemCountryCode() );
        SET_BX( context, INT21_GetSystemCountryCode() );
3103 3104 3105
        break;

    case 0x39: /* "MKDIR" - CREATE SUBDIRECTORY */
3106 3107
        if (!INT21_CreateDirectory( context ))
            bSetDOSExtendedError = TRUE;
3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
        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;
        }
        break;

3125
    case 0x3b: /* "CHDIR" - SET CURRENT DIRECTORY */
3126 3127 3128 3129
        if (!INT21_SetCurrentDirectory( context ))
            bSetDOSExtendedError = TRUE;
        break;

3130
    case 0x3c: /* "CREAT" - CREATE OR TRUNCATE FILE */
3131 3132 3133 3134 3135
        if (!INT21_CreateFile( context, context->Edx, FALSE, 
                               OF_READWRITE | OF_SHARE_COMPAT, 0x12 ))
            bSetDOSExtendedError = TRUE;
        break;

3136
    case 0x3d: /* "OPEN" - OPEN EXISTING FILE */
3137 3138 3139
        if (!INT21_CreateFile( context, context->Edx, FALSE, 
                               AL_reg(context), 0x01 ))
            bSetDOSExtendedError = TRUE;
3140 3141
        break;

3142
    case 0x3e: /* "CLOSE" - CLOSE FILE */
3143 3144 3145 3146 3147
        TRACE( "CLOSE handle %d\n", BX_reg(context) );
        if (_lclose16( BX_reg(context) ) == HFILE_ERROR16)
            bSetDOSExtendedError = TRUE;
        break;

3148
    case 0x3f: /* "READ" - READ FROM FILE OR DEVICE */
3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
        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())
            {
                WORD maxcount = GetSelectorLimit16( context->SegDs )
                    - 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.
             */

3175 3176 3177 3178 3179 3180 3181
            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 ))
3182 3183 3184 3185
                SET_AX( context, (WORD)result );
            else
                bSetDOSExtendedError = TRUE;
        }
3186 3187 3188
        break;

    case 0x40:  /* "WRITE" - WRITE TO FILE OR DEVICE */
3189 3190 3191 3192 3193
        TRACE( "WRITE from %04lX:%04X to handle %d for %d byte\n",
               context->SegDs, DX_reg(context),
               BX_reg(context), CX_reg(context) );
        {
            BYTE *ptr = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
3194

3195 3196
            if (!DOSVM_IsWin16() && 
                (BX_reg(context) == 1 || BX_reg(context) == 2))
3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
            {
                int i;
                for(i=0; i<CX_reg(context); i++)
                    DOSVM_PutChar(ptr[i]);
                SET_AX(context, CX_reg(context));
            }
            else
            {
                HFILE handle = (HFILE)DosFileHandleToWin32Handle(BX_reg(context));
                LONG result = _hwrite( handle, ptr, CX_reg(context) );
                if (result == HFILE_ERROR)
                    bSetDOSExtendedError = TRUE;
                else
                    SET_AX( context, (WORD)result );
            }
        }
3213 3214
        break;

3215
    case 0x41: /* "UNLINK" - DELETE FILE */
3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229
        {
            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;
        }
        break;

3230
    case 0x42: /* "LSEEK" - SET CURRENT FILE POSITION */
3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
        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) );
            }
        }
        break;

3252
    case 0x43: /* FILE ATTRIBUTES */
3253 3254
        if (!INT21_FileAttributes( context, AL_reg(context), FALSE ))
            bSetDOSExtendedError = TRUE;
3255 3256
        break;

3257
    case 0x44: /* IOCTL */
3258 3259 3260 3261
        INT21_Ioctl( context );
        break;

    case 0x45: /* "DUP" - DUPLICATE FILE HANDLE */
3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
        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
                SET_AX( context, handle16 );
        }
        break;

3281
    case 0x46: /* "DUP2", "FORCEDUP" - FORCE DUPLICATE FILE HANDLE */
3282 3283 3284 3285 3286 3287
        TRACE( "FORCEDUP - FORCE DUPLICATE FILE HANDLE %d to %d\n",
               BX_reg(context), CX_reg(context) );
        if (FILE_Dup2( BX_reg(context), CX_reg(context) ) == HFILE_ERROR16)
            bSetDOSExtendedError = TRUE;
        break;

3288
    case 0x47: /* "CWD" - GET CURRENT DIRECTORY */
3289 3290
        if (!INT21_GetCurrentDirectory( context, FALSE ))
            bSetDOSExtendedError = TRUE;
3291 3292
        break;

3293
    case 0x48: /* ALLOCATE MEMORY */
3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
        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
                DOSMEM_GetBlock( bytes, &selector );
               
            if (selector)
                SET_AX( context, selector );
            else
            {
                SET_CFLAG(context);
                SET_AX( context, 0x0008 ); /* insufficient memory */
                SET_BX( context, DOSMEM_Available() >> 4 );
            }
        }
	break;

3318
    case 0x49: /* FREE MEMORY */
3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342
        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
                ok = DOSMEM_FreeBlock( (void*)((DWORD)context->SegEs << 4) );

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

3343
    case 0x4a: /* RESIZE MEMORY BLOCK */
3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
        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" );
            }
            else
            {
                LPVOID address = (void*)((DWORD)context->SegEs << 4);
                UINT blocksize = DOSMEM_ResizeBlock( address, newsize, FALSE );

                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 */
                }
            }
        }
3371 3372 3373 3374
        break;

    case 0x4b: /* "EXEC" - LOAD AND/OR EXECUTE PROGRAM */
        {
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393
            BYTE *program = CTX_SEG_OFF_TO_LIN(context, context->SegDs, context->Edx);
            BYTE *paramblk = CTX_SEG_OFF_TO_LIN(context, context->SegEs, context->Ebx);

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

            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;
            }
3394 3395 3396 3397
        }
        break;

    case 0x4c: /* "EXIT" - TERMINATE WITH RETURN CODE */
3398 3399 3400 3401 3402
        TRACE( "EXIT with return code %d\n", AL_reg(context) );
        if (DOSVM_IsWin16())
            ExitThread( AL_reg(context) );
        else
            MZ_Exit( context, FALSE, AL_reg(context) );
3403 3404 3405 3406
        break;

    case 0x4d: /* GET RETURN CODE */
        TRACE("GET RETURN CODE (ERRORLEVEL)\n");
3407
        SET_AX( context, DOSVM_retval );
3408 3409 3410
        DOSVM_retval = 0;
        break;

3411 3412 3413 3414 3415
    case 0x4e: /* "FINDFIRST" - FIND FIRST MATCHING FILE */
    case 0x4f: /* "FINDNEXT" - FIND NEXT MATCHING FILE */
        INT_Int21Handler( context );
        break;

3416 3417 3418 3419 3420 3421
    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 */
3422
        INT21_GetPSP( context );
3423 3424 3425
        break;

    case 0x52: /* "SYSVARS" - GET LIST OF LISTS */
3426
        if (!ISV86(context) && DOSVM_IsWin16())
3427
        {
3428 3429 3430
            SEGPTR ptr = DOSMEM_LOL()->wine_pm_lol;
            context->SegEs = SELECTOROF(ptr);
            SET_BX( context, OFFSETOF(ptr) );
3431 3432
        }
        else
3433
        {
3434 3435 3436
            SEGPTR ptr = DOSMEM_LOL()->wine_rm_lol;
            context->SegEs = SELECTOROF(ptr);
            SET_BX( context, OFFSETOF(ptr) );
3437 3438 3439
        }
        break;

3440 3441 3442 3443 3444 3445
    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 */
3446 3447
        if (!INT21_RenameFile( context ))
            bSetDOSExtendedError = TRUE;
3448 3449
        break;

3450 3451 3452 3453 3454
    case 0x57: /* FILE DATE AND TIME */
        if (!INT21_FileDateTime( context ))
            bSetDOSExtendedError = TRUE;
        break;

3455 3456 3457
    case 0x58: /* GET OR SET MEMORY ALLOCATION STRATEGY */
        switch (AL_reg(context))
        {
3458 3459 3460
        case 0x00: /* GET MEMORY ALLOCATION STRATEGY */
            TRACE( "GET MEMORY ALLOCATION STRATEGY\n" );
            SET_AX( context, 0 ); /* low memory first fit */
3461 3462 3463
            break;

        case 0x01: /* SET ALLOCATION STRATEGY */
3464
            TRACE( "SET MEMORY ALLOCATION STRATEGY to %d - ignored\n",
3465 3466 3467
                   BL_reg(context) );
            break;

3468 3469 3470 3471 3472 3473 3474 3475 3476 3477
        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;

3478 3479 3480 3481 3482
        default:
            INT_BARF( context, 0x21 );
        }
        break;

3483 3484 3485 3486 3487
    case 0x59: /* GET EXTENDED ERROR INFO */
        INT21_GetExtendedError( context );
        break;

    case 0x5a: /* CREATE TEMPORARY FILE */
3488 3489
        INT_Int21Handler( context );
        break;
3490

3491 3492 3493 3494 3495 3496
    case 0x5b: /* CREATE NEW FILE */ 
        if (!INT21_CreateFile( context, context->Edx, FALSE,
                               OF_READWRITE | OF_SHARE_COMPAT, 0x10 ))
            bSetDOSExtendedError = TRUE;
        break;

3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523
    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));

            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;
3524

3525
    case 0x5d: /* NETWORK 5D */
3526 3527 3528 3529 3530
        FIXME( "Network function 5D not implemented.\n" );
        SetLastError( ER_NoNetwork );
        bSetDOSExtendedError = TRUE;
        break;

3531 3532 3533 3534 3535 3536
    case 0x5e: /* NETWORK 5E */
    case 0x5f: /* NETWORK 5F */
    case 0x60: /* "TRUENAME" - CANONICALIZE FILENAME OR PATH */
        INT_Int21Handler( context );
        break;

3537 3538 3539 3540
    case 0x61: /* UNUSED */
        SET_AL( context, 0 );
        break;

3541
    case 0x62: /* GET PSP ADDRESS */
3542
        INT21_GetPSP( context );
3543 3544
        break;

3545
    case 0x63: /* MISC. LANGUAGE SUPPORT */
3546 3547 3548 3549 3550 3551 3552 3553
        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;
        }
3554 3555
        break;

3556
    case 0x64: /* OS/2 DOS BOX */
3557 3558 3559 3560
        INT_BARF( context, 0x21 );
        SET_CFLAG(context);
    	break;

3561 3562 3563 3564
    case 0x65: /* EXTENDED COUNTRY INFORMATION */
        INT21_ExtendedCountryInformation( context );
        break;

3565
    case 0x66: /* GLOBAL CODE PAGE TABLE */
3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577
        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;
        }
3578 3579
        break;

3580
    case 0x67: /* SET HANDLE COUNT */
3581 3582 3583 3584 3585
        TRACE( "SET HANDLE COUNT to %d\n", BX_reg(context) );
        if (SetHandleCount( BX_reg(context) ) < BX_reg(context) )
            bSetDOSExtendedError = TRUE;
        break;

3586
    case 0x68: /* "FFLUSH" - COMMIT FILE */
3587 3588 3589 3590 3591
        TRACE( "FFLUSH - handle %d\n", BX_reg(context) );
        if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
            bSetDOSExtendedError = TRUE;
        break;

3592 3593 3594 3595
    case 0x69: /* DISK SERIAL NUMBER */
        INT_Int21Handler( context );
        break;

3596 3597 3598 3599 3600 3601
    case 0x6a: /* COMMIT FILE */
        TRACE( "COMMIT FILE - handle %d\n", BX_reg(context) );
        if (!FlushFileBuffers( DosFileHandleToWin32Handle(BX_reg(context)) ))
            bSetDOSExtendedError = TRUE;
        break;

3602 3603 3604 3605 3606
    case 0x6b: /* NULL FUNCTION FOR CP/M COMPATIBILITY */
        SET_AL( context, 0 );
        break;

    case 0x6c: /* EXTENDED OPEN/CREATE */
3607 3608 3609
        if (!INT21_CreateFile( context, context->Esi, TRUE,
                               BX_reg(context), DL_reg(context) ))
            bSetDOSExtendedError = TRUE;
3610 3611 3612 3613 3614 3615 3616 3617 3618
        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 */
3619
        INT21_LongFilename( context );
3620 3621 3622 3623 3624 3625
        break;

    case 0x73: /* MSDOS7 - FAT32 */
        INT_Int21Handler( context );
        break;

3626
    case 0xdc: /* CONNECTION SERVICES - GET CONNECTION NUMBER */
3627 3628 3629
        TRACE( "CONNECTION SERVICES - GET CONNECTION NUMBER - ignored\n" );
        break;

3630
    case 0xea: /* NOVELL NETWARE - RETURN SHELL VERSION */
3631
        TRACE( "NOVELL NETWARE - RETURN SHELL VERSION - ignored\n" );
3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644
        break;

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

    } /* END OF SWITCH */

    /* Set general error condition. */
    if (bSetDOSExtendedError)
    {
        SET_AX( context, GetLastError() );
        SET_CFLAG( context );
3645
    }
3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657

    /* 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 );
3658
}