int31.c 48.1 KB
Newer Older
1 2 3 4
/*
 * DPMI 0.9 emulation
 *
 * Copyright 1995 Alexandre Julliard
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * 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
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20 21
 */

#include "config.h"
22
#include "wine/port.h"
23

24 25
#include <stdarg.h>

26
#include "windef.h"
27
#include "winbase.h"
28
#include "winternl.h"
29
#include "wine/winbase16.h"
30
#include "wownt32.h"
31
#include "kernel16_private.h"
32 33
#include "dosexe.h"

34
#include "excpt.h"
35
#include "wine/debug.h"
36
#include "wine/exception.h"
37

38
WINE_DEFAULT_DEBUG_CHANNEL(int31);
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

/* Structure for real-mode callbacks */
typedef struct
{
    DWORD edi;
    DWORD esi;
    DWORD ebp;
    DWORD reserved;
    DWORD ebx;
    DWORD edx;
    DWORD ecx;
    DWORD eax;
    WORD  fl;
    WORD  es;
    WORD  ds;
    WORD  fs;
    WORD  gs;
    WORD  ip;
    WORD  cs;
    WORD  sp;
    WORD  ss;
} REALMODECALL;

typedef struct tagRMCB {
    DWORD address;
    DWORD proc_ofs,proc_sel;
    DWORD regs_ofs,regs_sel;
    struct tagRMCB *next;
} RMCB;

static RMCB *FirstRMCB = NULL;
static WORD dpmi_flag;
71
static void* lastvalloced = NULL;
72
static BYTE DPMI_retval;
73

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
#include "pshpack1.h"

typedef struct {
 WORD Handle;
 DWORD Offset;
} MOVEOFS;

typedef struct {
 DWORD Length;
 MOVEOFS Source;
 MOVEOFS Dest;
} MOVESTRUCT;

#include "poppack.h"

89 90 91 92 93
/**********************************************************************
 *          DOSVM_IsDos32
 * 
 * Return TRUE if we are in 32-bit protected mode DOS process.
 */
94
BOOL DOSVM_IsDos32(void)
95
{
96
  return (dpmi_flag & 1) != 0;
97 98 99
}


100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
/**********************************************************************
 *          alloc_pm_selector
 *
 * Allocate a 64k sized selector corresponding to a real mode segment.
 */
static WORD alloc_pm_selector( WORD seg, unsigned char flags )
{
    WORD sel = wine_ldt_alloc_entries( 1 );

    if (sel)
    {
        LDT_ENTRY entry;
        wine_ldt_set_base( &entry, (void *)(seg << 4) );
        wine_ldt_set_limit( &entry, 0xffff );
        wine_ldt_set_flags( &entry, flags );
        wine_ldt_set_entry( sel, &entry );
    }
    return sel;
}


121 122 123 124 125 126
/**********************************************************************
 *          dpmi_exception_handler
 *
 * Handle EXCEPTION_VM86_STI exceptions generated
 * when there are pending asynchronous events.
 */
127
static LONG WINAPI dpmi_exception_handler(EXCEPTION_POINTERS *eptr)
128
{
129 130
    EXCEPTION_RECORD *rec = eptr->ExceptionRecord;
    CONTEXT *context = eptr->ContextRecord;
131 132 133 134 135 136 137 138

    if (rec->ExceptionCode == EXCEPTION_VM86_STI)
    {
        if (ISV86(context))
            ERR( "Real mode STI caught by protected mode handler!\n" );
        DOSVM_SendQueuedEvents(context);
        return EXCEPTION_CONTINUE_EXECUTION;
    }
139 140 141 142 143 144 145 146
    else if (rec->ExceptionCode == EXCEPTION_VM86_INTx)
    {
        if (ISV86(context))
            ERR( "Real mode INTx caught by protected mode handler!\n" );
        DPMI_retval = (BYTE)rec->ExceptionInformation[0];
        return EXCEPTION_EXECUTE_HANDLER;
    }

147 148 149 150
    return EXCEPTION_CONTINUE_SEARCH;
}


151 152 153
/**********************************************************************
 *	    INT_GetRealModeContext
 */
154
static void INT_GetRealModeContext( REALMODECALL *call, CONTEXT *context )
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
{
    context->Eax    = call->eax;
    context->Ebx    = call->ebx;
    context->Ecx    = call->ecx;
    context->Edx    = call->edx;
    context->Esi    = call->esi;
    context->Edi    = call->edi;
    context->Ebp    = call->ebp;
    context->EFlags = call->fl | V86_FLAG;
    context->Eip    = call->ip;
    context->Esp    = call->sp;
    context->SegCs  = call->cs;
    context->SegDs  = call->ds;
    context->SegEs  = call->es;
    context->SegFs  = call->fs;
    context->SegGs  = call->gs;
    context->SegSs  = call->ss;
}


/**********************************************************************
 *	    INT_SetRealModeContext
 */
178
static void INT_SetRealModeContext( REALMODECALL *call, CONTEXT *context )
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
{
    call->eax = context->Eax;
    call->ebx = context->Ebx;
    call->ecx = context->Ecx;
    call->edx = context->Edx;
    call->esi = context->Esi;
    call->edi = context->Edi;
    call->ebp = context->Ebp;
    call->fl  = LOWORD(context->EFlags);
    call->ip  = LOWORD(context->Eip);
    call->sp  = LOWORD(context->Esp);
    call->cs  = context->SegCs;
    call->ds  = context->SegDs;
    call->es  = context->SegEs;
    call->fs  = context->SegFs;
    call->gs  = context->SegGs;
    call->ss  = context->SegSs;
}

198 199
/**********************************************************************
 *          DPMI_xalloc
Austin English's avatar
Austin English committed
200
 * special virtualalloc, allocates linearly monoton growing memory.
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
 * (the usual VirtualAlloc does not satisfy that restriction)
 */
static LPVOID DPMI_xalloc( DWORD len ) 
{
    LPVOID  ret;
    LPVOID  oldlastv = lastvalloced;

    if (lastvalloced) 
    {
        int xflag = 0;

        ret = NULL;
        while (!ret) 
        {
            ret = VirtualAlloc( lastvalloced, len,
                                MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE );
            if (!ret)
                lastvalloced = (char *) lastvalloced + 0x10000;

            /* we failed to allocate one in the first round.
             * try non-linear
             */
            if (!xflag && (lastvalloced<oldlastv)) 
            { 
                /* wrapped */
226
                FIXME( "failed to allocate linearly growing memory (%u bytes), "
227 228 229 230 231 232 233 234 235 236 237
                       "using non-linear growing...\n", len );
                xflag++;
            }

            /* if we even fail to allocate something in the next
             * round, return NULL
             */
            if ((xflag==1) && (lastvalloced >= oldlastv))
                xflag++;

            if ((xflag==2) && (lastvalloced < oldlastv)) {
238
                FIXME( "failed to allocate any memory of %u bytes!\n", len );
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
                return NULL;
            }
        }
    } 
    else
    {
        ret = VirtualAlloc( NULL, len, 
                            MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE );
    }

    lastvalloced = (LPVOID)(((DWORD)ret+len+0xffff)&~0xffff);
    return ret;
}

/**********************************************************************
 *          DPMI_xfree
 */
static void DPMI_xfree( LPVOID ptr ) 
{
    VirtualFree( ptr, 0, MEM_RELEASE );
}

/**********************************************************************
 *          DPMI_xrealloc
 *
 * FIXME: perhaps we could grow this mapped area... 
 */
266
static LPVOID DPMI_xrealloc( LPVOID ptr, DWORD newsize )
267 268 269
{
    MEMORY_BASIC_INFORMATION        mbi;

270
    if (ptr)
271
    {
272 273 274
        LPVOID newptr;

        if (!VirtualQuery(ptr,&mbi,sizeof(mbi)))
275 276 277 278 279
        {
            FIXME( "realloc of DPMI_xallocd region %p?\n", ptr );
            return NULL;
        }

280
        if (mbi.State == MEM_FREE)
281 282 283 284 285 286 287 288 289 290 291
        {
            FIXME( "realloc of DPMI_xallocd region %p?\n", ptr );
            return NULL;
        }

        /* We do not shrink allocated memory. most reallocs
         * only do grows anyway
         */
        if (newsize <= mbi.RegionSize)
            return ptr;

292 293 294 295
        newptr = DPMI_xalloc( newsize );
        if (!newptr)
            return NULL;

296 297
        memcpy( newptr, ptr, mbi.RegionSize );
        DPMI_xfree( ptr );
298 299

        return newptr;
300 301
    }

302
    return DPMI_xalloc( newsize );
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

void DPMI_CallRMCB32(RMCB *rmcb, UINT16 ss, DWORD esp, UINT16*es, DWORD*edi)
#if 0 /* original code, which early gccs puke on */
{
    int _clobber;
    __asm__ __volatile__(
        "pushl %%ebp\n"
        "pushl %%ebx\n"
        "pushl %%es\n"
        "pushl %%ds\n"
        "pushfl\n"
        "mov %7,%%es\n"
        "mov %5,%%ds\n"
        ".byte 0x36, 0xff, 0x18\n" /* lcall *%ss:(%eax) */
        "popl %%ds\n"
        "mov %%es,%0\n"
        "popl %%es\n"
        "popl %%ebx\n"
        "popl %%ebp\n"
    : "=d" (*es), "=D" (*edi), "=S" (_clobber), "=a" (_clobber), "=c" (_clobber)
    : "0" (ss), "2" (esp),
      "4" (rmcb->regs_sel), "1" (rmcb->regs_ofs),
      "3" (&rmcb->proc_ofs) );
}
#else /* code generated by a gcc new enough */
;
__ASM_GLOBAL_FUNC(DPMI_CallRMCB32,
    "pushl %ebp\n\t"
333 334
    __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
    __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
335
    "movl %esp,%ebp\n\t"
336
    __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
337
    "pushl %edi\n\t"
338
    __ASM_CFI(".cfi_rel_offset %edi,-4\n\t")
339
    "pushl %esi\n\t"
340
    __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    "movl 0x8(%ebp),%eax\n\t"
    "movl 0x10(%ebp),%esi\n\t"
    "movl 0xc(%ebp),%edx\n\t"
    "movl 0x10(%eax),%ecx\n\t"
    "movl 0xc(%eax),%edi\n\t"
    "addl $0x4,%eax\n\t"
    "pushl %ebp\n\t"
    "pushl %ebx\n\t"
    "pushl %es\n\t"
    "pushl %ds\n\t"
    "pushfl\n\t"
    "mov %cx,%es\n\t"
    "mov %dx,%ds\n\t"
    ".byte 0x36, 0xff, 0x18\n\t" /* lcall *%ss:(%eax) */
    "popl %ds\n\t"
    "mov %es,%dx\n\t"
    "popl %es\n\t"
    "popl %ebx\n\t"
    "popl %ebp\n\t"
    "movl 0x14(%ebp),%eax\n\t"
    "movw %dx,(%eax)\n\t"
    "movl 0x18(%ebp),%edx\n\t"
    "movl %edi,(%edx)\n\t"
    "popl %esi\n\t"
365
    __ASM_CFI(".cfi_same_value %esi\n\t")
366
    "popl %edi\n\t"
367
    __ASM_CFI(".cfi_same_value %edi\n\t")
368
    "leave\n\t"
369 370
    __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
    __ASM_CFI(".cfi_same_value %ebp\n\t")
371 372 373 374 375 376 377 378
    "ret")
#endif

/**********************************************************************
 *	    DPMI_CallRMCBProc
 *
 * This routine does the hard work of calling a callback procedure.
 */
379
static void DPMI_CallRMCBProc( CONTEXT *context, RMCB *rmcb, WORD flag )
380
{
381
    DWORD old_vif = get_vm86_teb_info()->dpmi_vif;
382 383

    /* Disable virtual interrupts. */
384
    get_vm86_teb_info()->dpmi_vif = 0;
385

386
    if (wine_ldt_is_system( rmcb->proc_sel )) {
387 388
        /* Wine-internal RMCB, call directly */
        ((RMCBPROC)rmcb->proc_ofs)(context);
389
    } else __TRY {
390 391 392 393
        UINT16 ss,es;
        DWORD esp,edi;

        INT_SetRealModeContext(MapSL(MAKESEGPTR( rmcb->regs_sel, rmcb->regs_ofs )), context);
394
        ss = alloc_pm_selector( context->SegSs, WINE_LDT_FLAGS_DATA );
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
        esp = context->Esp;

        FIXME("untested!\n");

        /* The called proc ends with an IRET, and takes these parameters:
         * DS:ESI = pointer to real-mode SS:SP
         * ES:EDI = pointer to real-mode call structure
         * It returns:
         * ES:EDI = pointer to real-mode call structure (may be a copy)
         * It is the proc's responsibility to change the return CS:IP in the
         * real-mode call structure. */
        if (flag & 1) {
            /* 32-bit DPMI client */
            DPMI_CallRMCB32(rmcb, ss, esp, &es, &edi);
        } else {
            /* 16-bit DPMI client */
411
            CONTEXT ctx = *context;
412 413 414 415 416 417 418
            ctx.SegCs = rmcb->proc_sel;
            ctx.Eip   = rmcb->proc_ofs;
            ctx.SegDs = ss;
            ctx.Esi   = esp;
            ctx.SegEs = rmcb->regs_sel;
            ctx.Edi   = rmcb->regs_ofs;
            /* FIXME: I'm pretty sure this isn't right - should push flags first */
419
            WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&ctx );
420 421 422
            es = ctx.SegEs;
            edi = ctx.Edi;
        }
423
        wine_ldt_free_entries( ss, 1 );
424
        INT_GetRealModeContext( MapSL( MAKESEGPTR( es, edi )), context);
425
    } __EXCEPT(dpmi_exception_handler) { } __ENDTRY
426

427
    /* Restore virtual interrupt flag. */
428
    get_vm86_teb_info()->dpmi_vif = old_vif;
429 430 431 432 433 434 435 436
}


/**********************************************************************
 *	    DPMI_CallRMProc
 *
 * This routine does the hard work of calling a real mode procedure.
 */
437
int DPMI_CallRMProc( CONTEXT *context, LPWORD stack, int args, int iret )
438 439 440 441 442 443 444
{
    LPWORD stack16;
    LPVOID addr = NULL; /* avoid gcc warning */
    RMCB *CurrRMCB;
    int alloc = 0, already = 0;
    BYTE *code;

445
    TRACE("EAX=%08x EBX=%08x ECX=%08x EDX=%08x\n",
446
                 context->Eax, context->Ebx, context->Ecx, context->Edx );
447
    TRACE("ESI=%08x EDI=%08x ES=%04x DS=%04x CS:IP=%04x:%04x, %d WORD arguments, %s\n",
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
                 context->Esi, context->Edi, context->SegEs, context->SegDs,
                 context->SegCs, LOWORD(context->Eip), args, iret?"IRET":"FAR" );

callrmproc_again:

/* there might be some code that just jumps to RMCBs or the like,
   in which case following the jumps here might get us to a shortcut */
    code = CTX_SEG_OFF_TO_LIN(context, context->SegCs, context->Eip);
    switch (*code) {
    case 0xe9: /* JMP NEAR */
      context->Eip += 3 + *(WORD *)(code+1);
      /* yeah, I know these gotos don't look good... */
      goto callrmproc_again;
    case 0xea: /* JMP FAR */
      context->Eip = *(WORD *)(code+1);
      context->SegCs = *(WORD *)(code+3);
      /* ...but since the label is there anyway... */
      goto callrmproc_again;
    case 0xeb: /* JMP SHORT */
      context->Eip += 2 + *(signed char *)(code+1);
      /* ...because of other gotos below, so... */
      goto callrmproc_again;
    }

/* shortcut for chaining to internal interrupt handlers */
    if ((context->SegCs == 0xF000) && iret)
    {
475
        DOSVM_CallBuiltinHandler( context, LOWORD(context->Eip)/4 );
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
        return 0;
    }

/* shortcut for RMCBs */
    CurrRMCB = FirstRMCB;

    while (CurrRMCB && (HIWORD(CurrRMCB->address) != context->SegCs))
        CurrRMCB = CurrRMCB->next;

    if (!CurrRMCB && !MZ_Current())
    {
        FIXME("DPMI real-mode call using DOS VM task system, not fully tested!\n");
        TRACE("creating VM86 task\n");
        MZ_AllocDPMITask();
    }
    if (!already) {
        if (!context->SegSs) {
            alloc = 1; /* allocate default stack */
494
            stack16 = addr = DOSMEM_AllocBlock( 64, (UINT16 *)&(context->SegSs) );
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
            context->Esp = 64-2;
            stack16 += 32-1;
            if (!addr) {
                ERR("could not allocate default stack\n");
                return 1;
            }
        } else {
            stack16 = CTX_SEG_OFF_TO_LIN(context, context->SegSs, context->Esp);
        }
        context->Esp -= (args + (iret?1:0)) * sizeof(WORD);
        stack16 -= args;
        if (args) memcpy(stack16, stack, args*sizeof(WORD) );
        /* push flags if iret */
        if (iret) {
            stack16--; args++;
            *stack16 = LOWORD(context->EFlags);
        }
        /* push return address (return to interrupt wrapper) */
513
        *(--stack16) = DOSVM_dpmi_segments->wrap_seg;
514 515 516 517 518 519 520 521 522 523
        *(--stack16) = 0;
        /* adjust stack */
        context->Esp -= 2*sizeof(WORD);
        already = 1;
    }

    if (CurrRMCB) {
        /* RMCB call, invoke protected-mode handler directly */
        DPMI_CallRMCBProc(context, CurrRMCB, dpmi_flag);
        /* check if we returned to where we thought we would */
524
        if ((context->SegCs != DOSVM_dpmi_segments->wrap_seg) ||
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
            (LOWORD(context->Eip) != 0)) {
            /* we need to continue at different address in real-mode space,
               so we need to set it all up for real mode again */
            goto callrmproc_again;
        }
    } else {
        TRACE("entering real mode...\n");
        DOSVM_Enter( context );
        TRACE("returned from real-mode call\n");
    }
    if (alloc) DOSMEM_FreeBlock( addr );
    return 0;
}


/**********************************************************************
541
 *	    CallRMInt
542
 */
543
static void DOSVM_CallRMInt( CONTEXT *context )
544
{
545
    CONTEXT realmode_ctx;
546
    FARPROC16 rm_int = DOSVM_GetRMHandler( BL_reg(context) );
547 548 549
    REALMODECALL *call = CTX_SEG_OFF_TO_LIN( context, 
                                             context->SegEs, 
                                             context->Edi );
550 551 552 553 554 555 556 557 558 559 560 561 562
    INT_GetRealModeContext( call, &realmode_ctx );

    /* we need to check if a real-mode program has hooked the interrupt */
    if (HIWORD(rm_int)!=0xF000) {
        /* yup, which means we need to switch to real mode... */
        realmode_ctx.SegCs = HIWORD(rm_int);
        realmode_ctx.Eip   = LOWORD(rm_int);
        if (DPMI_CallRMProc( &realmode_ctx, NULL, 0, TRUE))
          SET_CFLAG(context);
    } else {
        RESET_CFLAG(context);
        /* use the IP we have instead of BL_reg, in case some apps
           decide to move interrupts around for whatever reason... */
563
        DOSVM_CallBuiltinHandler( &realmode_ctx, LOWORD(rm_int)/4 );
564 565 566 567 568 569
    }
    INT_SetRealModeContext( call, &realmode_ctx );
}


/**********************************************************************
570
 *	    CallRMProc
571
 */
572
static void DOSVM_CallRMProc( CONTEXT *context, int iret )
573
{
574 575 576
    REALMODECALL *p = CTX_SEG_OFF_TO_LIN( context, 
                                          context->SegEs, 
                                          context->Edi );
577
    CONTEXT context16;
578

579
    TRACE("RealModeCall: EAX=%08x EBX=%08x ECX=%08x EDX=%08x\n",
580
          p->eax, p->ebx, p->ecx, p->edx);
581
    TRACE("              ESI=%08x EDI=%08x ES=%04x DS=%04x CS:IP=%04x:%04x, %d WORD arguments, %s\n",
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
          p->esi, p->edi, p->es, p->ds, p->cs, p->ip, CX_reg(context), iret?"IRET":"FAR" );

    if (!(p->cs) && !(p->ip)) { /* remove this check
                                   if Int21/6501 case map function
                                   has been implemented */
        SET_CFLAG(context);
        return;
     }
    INT_GetRealModeContext(p, &context16);
    DPMI_CallRMProc( &context16, ((LPWORD)MapSL(MAKESEGPTR(context->SegSs, LOWORD(context->Esp))))+3,
                     CX_reg(context), iret );
    INT_SetRealModeContext(p, &context16);
}


/* (see dosmem.c, function DOSMEM_InitDPMI) */
598
static void StartPM( CONTEXT *context )
599 600
{
    UINT16 cs, ss, ds, es;
601
    CONTEXT pm_ctx;
602 603 604 605 606 607 608 609
    DWORD psp_ofs = (DWORD)(DOSVM_psp<<4);
    PDB16 *psp = (PDB16 *)psp_ofs;
    HANDLE16 env_seg = psp->environment;
    unsigned char selflags = WINE_LDT_FLAGS_DATA;

    RESET_CFLAG(context);
    dpmi_flag = AX_reg(context);
/* our mode switch wrapper have placed the desired CS into DX */
610
    cs = alloc_pm_selector( context->Edx, WINE_LDT_FLAGS_CODE );
611 612 613 614 615
/* due to a flaw in some CPUs (at least mine), it is best to mark stack segments as 32-bit if they
   can be used in 32-bit code. Otherwise, these CPUs may not set the high word of esp during a
   ring transition (from kernel code) to the 16-bit stack, and this causes trouble if executing
   32-bit code using this stack. */
    if (dpmi_flag & 1) selflags |= WINE_LDT_FLAGS_32BIT;
616
    ss = alloc_pm_selector( context->SegSs, selflags );
617 618
/* do the same for the data segments, just in case */
    if (context->SegDs == context->SegSs) ds = ss;
619 620
    else ds = alloc_pm_selector( context->SegDs, selflags );
    es = alloc_pm_selector( DOSVM_psp, selflags );
621
/* convert environment pointer, as the spec says, but we're a bit lazy about the size here... */
622
    psp->environment = alloc_pm_selector( env_seg, WINE_LDT_FLAGS_DATA );
623 624

    pm_ctx = *context;
625
    pm_ctx.SegCs = DOSVM_dpmi_segments->dpmi_sel;
626 627 628 629 630
/* our mode switch wrapper expects the new CS in DX, and the new SS in AX */
    pm_ctx.Eax   = ss;
    pm_ctx.Edx   = cs;
    pm_ctx.SegDs = ds;
    pm_ctx.SegEs = es;
631 632
    pm_ctx.SegFs = wine_get_fs();
    pm_ctx.SegGs = wine_get_gs();
633
    pm_ctx.EFlags &= ~V86_FLAG;
634

635 636
    TRACE("DOS program is now entering %d-bit protected mode\n", 
          DOSVM_IsDos32() ? 32 : 16);
637 638 639

    __TRY 
    {
640
        WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&pm_ctx );
641 642 643 644 645
    } 
    __EXCEPT(dpmi_exception_handler) 
    { 
    } 
    __ENDTRY
646

647 648 649
    TRACE( "Protected mode DOS program is terminating\n" );

    /*
650
     * FIXME: Instead of calling DOSVM_Exit, we should release all
651 652 653
     *        allocated protected mode resources and call MZ_Exit
     *        using real mode context. See DPMI specification.
     */
654
    DOSVM_Exit( DPMI_retval );
655

656
#if 0
657
    wine_ldt_free_entries( psp->environment, 1 );
658
    psp->environment = env_seg;
659 660 661 662
    wine_ldt_free_entries(es,1);
    if (ds != ss) wine_ldt_free_entries(ds,1);
    wine_ldt_free_entries(ss,1);
    wine_ldt_free_entries(cs,1);
663
#endif
664 665 666 667 668 669 670 671 672
}

static RMCB *DPMI_AllocRMCB( void )
{
    RMCB *NewRMCB = HeapAlloc(GetProcessHeap(), 0, sizeof(RMCB));
    UINT16 uParagraph;

    if (NewRMCB)
    {
673
	LPVOID RMCBmem = DOSMEM_AllocBlock(4, &uParagraph);
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
	LPBYTE p = RMCBmem;

	*p++ = 0xcd; /* RMCB: */
	*p++ = 0x31; /* int $0x31 */
/* it is the called procedure's task to change the return CS:EIP
   the DPMI 0.9 spec states that if it doesn't, it will be called again */
	*p++ = 0xeb;
	*p++ = 0xfc; /* jmp RMCB */
	NewRMCB->address = MAKELONG(0, uParagraph);
	NewRMCB->next = FirstRMCB;
	FirstRMCB = NewRMCB;
    }
    return NewRMCB;
}


690
FARPROC16 DPMI_AllocInternalRMCB( RMCBPROC proc )
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
{
    RMCB *NewRMCB = DPMI_AllocRMCB();

    if (NewRMCB) {
        NewRMCB->proc_ofs = (DWORD)proc;
        NewRMCB->proc_sel = 0;
        NewRMCB->regs_ofs = 0;
        NewRMCB->regs_sel = 0;
        return (FARPROC16)(NewRMCB->address);
    }
    return NULL;
}


static int DPMI_FreeRMCB( DWORD address )
{
    RMCB *CurrRMCB = FirstRMCB;
    RMCB *PrevRMCB = NULL;

    while (CurrRMCB && (CurrRMCB->address != address))
    {
	PrevRMCB = CurrRMCB;
	CurrRMCB = CurrRMCB->next;
    }
    if (CurrRMCB)
    {
	if (PrevRMCB)
	PrevRMCB->next = CurrRMCB->next;
	    else
	FirstRMCB = CurrRMCB->next;
721
	DOSMEM_FreeBlock(PTR_REAL_TO_LIN(SELECTOROF(CurrRMCB->address),OFFSETOF(CurrRMCB->address)));
722 723 724 725 726 727 728
	HeapFree(GetProcessHeap(), 0, CurrRMCB);
	return 0;
    }
    return 1;
}


729
/**********************************************************************
730
 *	    DOSVM_RawModeSwitchHandler
731 732 733
 *
 * DPMI Raw Mode Switch handler
 */
734
void WINAPI DOSVM_RawModeSwitchHandler( CONTEXT *context )
735
{
736
  CONTEXT rm_ctx;
737 738 739 740
  int ret;

  /* initialize real-mode context as per spec */
  memset(&rm_ctx, 0, sizeof(rm_ctx));
741 742 743 744 745 746 747
  rm_ctx.SegDs  = AX_reg(context);
  rm_ctx.SegEs  = CX_reg(context);
  rm_ctx.SegSs  = DX_reg(context);
  rm_ctx.Esp    = context->Ebx;
  rm_ctx.SegCs  = SI_reg(context);
  rm_ctx.Eip    = context->Edi;
  rm_ctx.Ebp    = context->Ebp;
748 749
  rm_ctx.SegFs  = 0;
  rm_ctx.SegGs  = 0;
750 751

  /* Copy interrupt state. */
752
  if (get_vm86_teb_info()->dpmi_vif)
753 754 755
      rm_ctx.EFlags = V86_FLAG | VIF_MASK;
  else
      rm_ctx.EFlags = V86_FLAG;
756 757

  /* enter real mode again */
758
  TRACE("re-entering real mode at %04x:%04x\n",rm_ctx.SegCs,rm_ctx.Eip);
759 760 761 762 763
  ret = DOSVM_Enter( &rm_ctx );
  /* when the real-mode stuff call its mode switch address,
     DOSVM_Enter will return and we will continue here */

  if (ret<0) {
764
    ERR("Sync lost!\n");
765 766 767 768 769
    /* if the sync was lost, there's no way to recover */
    ExitProcess(1);
  }

  /* alter protected-mode context as per spec */
770 771 772 773 774 775 776 777 778
  context->SegDs   = LOWORD(rm_ctx.Eax);
  context->SegEs   = LOWORD(rm_ctx.Ecx);
  context->SegSs   = LOWORD(rm_ctx.Edx);
  context->Esp     = rm_ctx.Ebx;
  context->SegCs   = LOWORD(rm_ctx.Esi);
  context->Eip     = rm_ctx.Edi;
  context->Ebp     = rm_ctx.Ebp;
  context->SegFs   = 0;
  context->SegGs   = 0;
779

780 781
  /* Copy interrupt state. */
  if (rm_ctx.EFlags & VIF_MASK)
782
      get_vm86_teb_info()->dpmi_vif = 1;
783
  else
784
      get_vm86_teb_info()->dpmi_vif = 0;
785

786
  /* Return to new address and hope that we didn't mess up */
787
  TRACE("re-entering protected mode at %04x:%08x\n",
788
      context->SegCs, context->Eip);
789 790 791 792
}


/**********************************************************************
793
 *	    AllocRMCB
794
 */
795
static void DOSVM_AllocRMCB( CONTEXT *context )
796 797 798 799 800 801 802
{
    RMCB *NewRMCB = DPMI_AllocRMCB();

    TRACE("Function to call: %04x:%04x\n", (WORD)context->SegDs, SI_reg(context) );

    if (NewRMCB)
    {
803
       NewRMCB->proc_ofs = DOSVM_IsDos32() ? context->Esi : LOWORD(context->Esi);
804
	NewRMCB->proc_sel = context->SegDs;
805
       NewRMCB->regs_ofs = DOSVM_IsDos32() ? context->Edi : LOWORD(context->Edi);
806
	NewRMCB->regs_sel = context->SegEs;
807 808
	SET_CX( context, HIWORD(NewRMCB->address) );
	SET_DX( context, LOWORD(NewRMCB->address) );
809 810 811
    }
    else
    {
812
	SET_AX( context, 0x8015 ); /* callback unavailable */
813 814 815 816 817 818
	SET_CFLAG(context);
    }
}


/**********************************************************************
819
 *	    FreeRMCB
820
 */
821
static void DOSVM_FreeRMCB( CONTEXT *context )
822 823 824 825 826
{
    FIXME("callback address: %04x:%04x\n",
          CX_reg(context), DX_reg(context));

    if (DPMI_FreeRMCB(MAKELONG(DX_reg(context), CX_reg(context)))) {
827
	SET_AX( context, 0x8024 ); /* invalid callback address */
828 829 830 831
	SET_CFLAG(context);
    }
}

832

833 834 835 836 837 838 839 840 841
static BYTE * XMS_Offset( MOVEOFS *ofs )
{
    if (ofs->Handle) return (BYTE*)GlobalLock16(ofs->Handle)+ofs->Offset;
    else return PTR_REAL_TO_LIN(SELECTOROF(ofs->Offset),OFFSETOF(ofs->Offset));
}

/**********************************************************************
 *	    XMS_Handler
 */
842
static void XMS_Handler( CONTEXT *context )
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
{
    switch(AH_reg(context))
    {
    case 0x00:   /* Get XMS version number */
        TRACE("get XMS version number\n");
        SET_AX( context, 0x0200 ); /* 2.0 */
        SET_BX( context, 0x0000 ); /* internal revision */
        SET_DX( context, 0x0001 ); /* HMA exists */
        break;
    case 0x08:   /* Query Free Extended Memory */
    {
        MEMORYSTATUS status;

        TRACE("query free extended memory\n");
        GlobalMemoryStatus( &status );
        SET_DX( context, status.dwAvailVirtual >> 10 );
        SET_AX( context, status.dwAvailVirtual >> 10 );
        TRACE("returning largest %dK, total %dK\n", AX_reg(context), DX_reg(context));
    }
    break;
    case 0x09:   /* Allocate Extended Memory Block */
        TRACE("allocate extended memory block (%dK)\n",
            DX_reg(context));
	SET_DX( context, GlobalAlloc16(GMEM_MOVEABLE, (DWORD)DX_reg(context)<<10) );
	SET_AX( context, DX_reg(context) ? 1 : 0 );
	if (!DX_reg(context)) SET_BL( context, 0xA0 ); /* out of memory */
	break;
    case 0x0a:   /* Free Extended Memory Block */
	TRACE("free extended memory block %04x\n",DX_reg(context));
       if(!DX_reg(context) || GlobalFree16(DX_reg(context))) {
         SET_AX( context, 0 );    /* failure */
         SET_BL( context, 0xa2 ); /* invalid handle */
       } else
         SET_AX( context, 1 );    /* success */
	break;
    case 0x0b:   /* Move Extended Memory Block */
    {
	MOVESTRUCT*move=CTX_SEG_OFF_TO_LIN(context,
	    context->SegDs,context->Esi);
        BYTE*src,*dst;
        TRACE("move extended memory block\n");
        src=XMS_Offset(&move->Source);
        dst=XMS_Offset(&move->Dest);
	memcpy(dst,src,move->Length);
	if (move->Source.Handle) GlobalUnlock16(move->Source.Handle);
	if (move->Dest.Handle) GlobalUnlock16(move->Dest.Handle);
	break;
    }
    case 0x88:   /* Query Any Free Extended Memory */
    {
        MEMORYSTATUS status;
        SYSTEM_INFO  info;

        TRACE("query any free extended memory\n");

        GlobalMemoryStatus( &status );
        GetSystemInfo( &info );
        context->Eax = status.dwAvailVirtual >> 10;
        context->Edx = status.dwAvailVirtual >> 10;
        context->Ecx = (DWORD)info.lpMaximumApplicationAddress;
        SET_BL( context, 0 ); /* No errors. */

        TRACE("returning largest %dK, total %dK, highest 0x%x\n",
              context->Eax, context->Edx, context->Ecx);
    }
    break;
    default:
        INT_BARF( context, 0x31 );
        SET_AX( context, 0x0000 ); /* failure */
        SET_BL( context, 0x80 );   /* function not implemented */
        break;
    }
}


918
/**********************************************************************
919
 *         DOSVM_CheckWrappers
920
 *
921
 * Check if this was really a wrapper call instead of an interrupt.
922
 */
923
BOOL DOSVM_CheckWrappers( CONTEXT *context )
924
{
925
    if (context->SegCs==DOSVM_dpmi_segments->dpmi_seg) {
926 927
        /* This is the protected mode switch */
        StartPM(context);
928
        return TRUE;
929
    }
930
    else if (context->SegCs==DOSVM_dpmi_segments->xms_seg)
931 932 933
    {
        /* This is the XMS driver entry point */
        XMS_Handler(context);
934
        return TRUE;
935 936 937 938 939 940 941 942 943 944 945 946
    }
    else
    {
        /* Check for RMCB */
        RMCB *CurrRMCB = FirstRMCB;

        while (CurrRMCB && (HIWORD(CurrRMCB->address) != context->SegCs))
            CurrRMCB = CurrRMCB->next;

        if (CurrRMCB) {
            /* RMCB call, propagate to protected-mode handler */
            DPMI_CallRMCBProc(context, CurrRMCB, dpmi_flag);
947
            return TRUE;
948 949 950
        }
    }

951 952 953 954
    return FALSE;
}

/**********************************************************************
955
 *         DOSVM_Int31Handler
956 957 958
 *
 * Handler for int 31h (DPMI).
 */
959
void WINAPI DOSVM_Int31Handler( CONTEXT *context )
960 961 962 963
{
    RESET_CFLAG(context);
    switch(AX_reg(context))
    {
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    case 0x0000:  /* Allocate LDT descriptors */
        TRACE( "allocate LDT descriptors (%d)\n", CX_reg(context) );
        {
            WORD sel =  AllocSelectorArray16( CX_reg(context) );
            if(!sel) 
            {
               TRACE( "failed\n" );
               SET_AX( context, 0x8011 ); /* descriptor unavailable */
               SET_CFLAG( context );
            } 
            else 
            { 
                TRACE( "success, array starts at 0x%04x\n", sel );
                SET_AX( context, sel );      
            }
        }
        break;

    case 0x0001:  /* Free LDT descriptor */
        TRACE( "free LDT descriptor (0x%04x)\n", BX_reg(context) );
        if (FreeSelector16( BX_reg(context) ))
        {
            SET_AX( context, 0x8022 );  /* invalid selector */
            SET_CFLAG( context );
        }
        else
        {
            /* If a segment register contains the selector being freed, */
            /* set it to zero. */
            if (!((context->SegDs^BX_reg(context)) & ~3)) context->SegDs = 0;
            if (!((context->SegEs^BX_reg(context)) & ~3)) context->SegEs = 0;
            if (!((context->SegFs^BX_reg(context)) & ~3)) context->SegFs = 0;
            if (!((context->SegGs^BX_reg(context)) & ~3)) context->SegGs = 0;
        }
        break;

    case 0x0002:  /* Real mode segment to descriptor */
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        TRACE( "real mode segment to descriptor (0x%04x)\n", BX_reg(context) );
        {
            WORD entryPoint = 0;  /* KERNEL entry point for descriptor */
            switch(BX_reg(context))
            {
            case 0x0000: entryPoint = 183; break;  /* __0000H */
            case 0x0040: entryPoint = 193; break;  /* __0040H */
            case 0xa000: entryPoint = 174; break;  /* __A000H */
            case 0xb000: entryPoint = 181; break;  /* __B000H */
            case 0xb800: entryPoint = 182; break;  /* __B800H */
            case 0xc000: entryPoint = 195; break;  /* __C000H */
            case 0xd000: entryPoint = 179; break;  /* __D000H */
            case 0xe000: entryPoint = 190; break;  /* __E000H */
            case 0xf000: entryPoint = 194; break;  /* __F000H */
            default:
1016 1017 1018
                FIXME("Real mode segment (%x) to descriptor: no longer supported\n",
                      BX_reg(context));
                SET_CFLAG( context );
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
                break;
            }
            if (entryPoint)
            {
                FARPROC16 proc = GetProcAddress16( GetModuleHandle16( "KERNEL" ),
                                                   (LPCSTR)(ULONG_PTR)entryPoint );
                SET_AX( context, LOWORD(proc) );
            }
        }
        break;

1030
    case 0x0003:  /* Get next selector increment */
1031 1032 1033 1034
        TRACE("get selector increment (__AHINCR)\n");
        context->Eax = __AHINCR;
        break;

1035
    case 0x0004:  /* Lock selector (not supported) */
1036 1037 1038 1039
        FIXME("lock selector not supported\n");
        context->Eax = 0;  /* FIXME: is this a correct return value? */
        break;

1040
    case 0x0005:  /* Unlock selector (not supported) */
1041 1042 1043 1044
        FIXME("unlock selector not supported\n");
        context->Eax = 0;  /* FIXME: is this a correct return value? */
        break;

1045
    case 0x0006:  /* Get selector base address */
1046 1047
        TRACE( "get selector base address (0x%04x)\n", BX_reg(context) );
        {
1048
            LDT_ENTRY entry;
1049
            WORD sel = BX_reg(context);
1050 1051
            wine_ldt_get_entry( sel, &entry );
            if (wine_ldt_is_empty(&entry))
1052 1053 1054 1055 1056 1057
            {
                context->Eax = 0x8022;  /* invalid selector */
                SET_CFLAG(context);
            }
            else
            {
1058
                void *base = wine_ldt_get_base(&entry);
1059 1060 1061 1062 1063 1064
                SET_CX( context, HIWORD(base) );
                SET_DX( context, LOWORD(base) );
            }
        }
        break;

1065
    case 0x0007:  /* Set selector base address */
1066 1067 1068
        {
            DWORD base = MAKELONG( DX_reg(context), CX_reg(context) );
            WORD  sel = BX_reg(context);
1069
            TRACE( "set selector base address (0x%04x,0x%08x)\n", sel, base );
1070 1071 1072

            /* check if Win16 app wants to access lower 64K of DOS memory */
            if (base < 0x10000 && DOSVM_IsWin16())
1073
                DOSMEM_MapDosLayout();
1074 1075 1076

            SetSelectorBase( sel, base );
        }
1077 1078
        break;

1079 1080
    case 0x0008:  /* Set selector limit */
        {
1081
            DWORD limit = MAKELONG( DX_reg(context), CX_reg(context) );
1082
            TRACE( "set selector limit (0x%04x,0x%08x)\n",
1083 1084 1085 1086 1087 1088
                   BX_reg(context), limit );
            SetSelectorLimit16( BX_reg(context), limit );
        }
        break;

    case 0x0009:  /* Set selector access rights */
1089 1090 1091 1092 1093
        TRACE( "set selector access rights(0x%04x,0x%04x)\n",
               BX_reg(context), CX_reg(context) );
        SelectorAccessRights16( BX_reg(context), 1, CX_reg(context) );
        break;

1094
    case 0x000a:  /* Allocate selector alias */
1095
        TRACE( "allocate selector alias (0x%04x)\n", BX_reg(context) );
1096 1097
        SET_AX( context, AllocCStoDSAlias16( BX_reg(context) ) );
        if (!AX_reg(context))
1098 1099 1100 1101 1102 1103
        {
            SET_AX( context, 0x8011 );  /* descriptor unavailable */
            SET_CFLAG(context);
        }
        break;

1104
    case 0x000b:  /* Get descriptor */
1105 1106
        TRACE( "get descriptor (0x%04x)\n", BX_reg(context) );
        {
1107 1108
            LDT_ENTRY *entry = CTX_SEG_OFF_TO_LIN( context, context->SegEs,
                                                   context->Edi );
1109 1110 1111 1112
            wine_ldt_get_entry( BX_reg(context), entry );
        }
        break;

1113
    case 0x000c:  /* Set descriptor */
1114 1115
        TRACE( "set descriptor (0x%04x)\n", BX_reg(context) );
        {
1116 1117
            LDT_ENTRY *entry = CTX_SEG_OFF_TO_LIN( context, context->SegEs,
                                                   context->Edi );
1118 1119 1120 1121
            wine_ldt_set_entry( BX_reg(context), entry );
        }
        break;

1122
    case 0x000d:  /* Allocate specific LDT descriptor */
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
        FIXME( "allocate descriptor (0x%04x), stub!\n", BX_reg(context) );
        SET_AX( context, 0x8011 ); /* descriptor unavailable */
        SET_CFLAG( context );
        break;

    case 0x000e:  /* Get Multiple Descriptors (1.0) */
        FIXME( "get multiple descriptors - unimplemented\n" );
        break;

    case 0x000f:  /* Set Multiple Descriptors (1.0) */
        FIXME( "set multiple descriptors - unimplemented\n" );
        break;

1136
    case 0x0100:  /* Allocate DOS memory block */
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
        TRACE( "allocate DOS memory block (0x%x paragraphs)\n", BX_reg(context) );
        {
            DWORD dw = GlobalDOSAlloc16( (DWORD)BX_reg(context) << 4 );
            if (dw) {
                SET_AX( context, HIWORD(dw) );
                SET_DX( context, LOWORD(dw) );
            } else {
                SET_AX( context, 0x0008 ); /* insufficient memory */
                SET_BX( context, DOSMEM_Available() >> 4 );
                SET_CFLAG(context);
            }
            break;
        }

1151
    case 0x0101:  /* Free DOS memory block */
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
        TRACE( "free DOS memory block (0x%04x)\n", DX_reg(context) );
        {
            WORD error = GlobalDOSFree16( DX_reg(context) );
            if (error) {
                SET_AX( context, 0x0009 ); /* memory block address invalid */
                SET_CFLAG( context );
            }
        }
        break;

    case 0x0102: /* Resize DOS Memory Block */
        FIXME( "resize DOS memory block (0x%04x, 0x%x paragraphs) - unimplemented\n", 
               DX_reg(context), BX_reg(context) );
1165 1166 1167
        break;

    case 0x0200: /* get real mode interrupt vector */
1168
        TRACE( "get realmode interrupt vector (0x%02x)\n",
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
               BL_reg(context) );
        {
            FARPROC16 proc = DOSVM_GetRMHandler( BL_reg(context) );
            SET_CX( context, SELECTOROF(proc) );
            SET_DX( context, OFFSETOF(proc) );
        }
        break;

    case 0x0201: /* set real mode interrupt vector */
        TRACE( "set realmode interrupt vector (0x%02x, 0x%04x:0x%04x)\n", 
               BL_reg(context), CX_reg(context), DX_reg(context) );
        DOSVM_SetRMHandler( BL_reg(context), 
                            (FARPROC16)MAKESEGPTR(CX_reg(context), DX_reg(context)) );
1182 1183 1184 1185 1186
        break;

    case 0x0202:  /* Get Processor Exception Handler Vector */
        FIXME( "Get Processor Exception Handler Vector (0x%02x)\n",
               BL_reg(context) );
1187 1188
        if (DOSVM_IsDos32()) 
        {
1189 1190
            SET_CX( context, 0 );
            context->Edx = 0;
1191 1192 1193
        } 
        else 
        {
1194 1195 1196 1197 1198 1199 1200
            SET_CX( context, 0 );
            SET_DX( context, 0 );
        }
        break;

    case 0x0203:  /* Set Processor Exception Handler Vector */
         FIXME( "Set Processor Exception Handler Vector (0x%02x)\n",
1201
                BL_reg(context) );
1202 1203
         break;

1204 1205
    case 0x0204:  /* Get protected mode interrupt vector */
        TRACE("get protected mode interrupt handler (0x%02x)\n",
1206 1207 1208
              BL_reg(context));
        if (DOSVM_IsDos32()) 
        {
1209 1210 1211
            FARPROC48 handler = DOSVM_GetPMHandler48( BL_reg(context) );
            SET_CX( context, handler.selector );
            context->Edx = handler.offset;
1212 1213 1214
        } 
        else 
        {
1215 1216 1217 1218 1219 1220 1221
            FARPROC16 handler = DOSVM_GetPMHandler16( BL_reg(context) );
            SET_CX( context, SELECTOROF(handler) );
            SET_DX( context, OFFSETOF(handler) );
        }
        break;

    case 0x0205:  /* Set protected mode interrupt vector */
1222
        TRACE("set protected mode interrupt handler (0x%02x,0x%04x:0x%08x)\n",
1223 1224 1225
              BL_reg(context), CX_reg(context), context->Edx);
        if (DOSVM_IsDos32()) 
        {
1226 1227 1228 1229
            FARPROC48 handler;
            handler.selector = CX_reg(context);
            handler.offset = context->Edx;
            DOSVM_SetPMHandler48( BL_reg(context), handler );
1230 1231 1232
        } 
        else 
        {
1233 1234 1235 1236 1237 1238
            FARPROC16 handler;
            handler = (FARPROC16)MAKESEGPTR( CX_reg(context), DX_reg(context)); 
            DOSVM_SetPMHandler16( BL_reg(context), handler );
        }
        break;

1239
    case 0x0300:  /* Simulate real mode interrupt */
1240
        TRACE( "Simulate real mode interrupt %02x.\n", BL_reg(context));
1241 1242 1243 1244
        DOSVM_CallRMInt( context );
        break;

    case 0x0301:  /* Call real mode procedure with far return */
1245
        TRACE( "Call real mode procedure with far return.\n" );
1246 1247 1248 1249
        DOSVM_CallRMProc( context, FALSE );
        break;

    case 0x0302:  /* Call real mode procedure with interrupt return */
1250
        TRACE( "Call real mode procedure with interrupt return.\n" );
1251 1252 1253 1254
        DOSVM_CallRMProc( context, TRUE );
        break;

    case 0x0303:  /* Allocate Real Mode Callback Address */
1255
        TRACE( "Allocate real mode callback address.\n" );
1256 1257 1258 1259
        DOSVM_AllocRMCB( context );
        break;

    case 0x0304:  /* Free Real Mode Callback Address */
1260
        TRACE( "Free real mode callback address.\n" );
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
        DOSVM_FreeRMCB( context );
        break;

    case 0x0305:  /* Get State Save/Restore Addresses */
        TRACE("get state save/restore addresses\n");
        /* we probably won't need this kind of state saving */
        SET_AX( context, 0 );

        /* real mode: just point to the lret */
        SET_BX( context, DOSVM_dpmi_segments->wrap_seg );
        SET_CX( context, 2 );

        /* protected mode: don't have any handler yet... */
        /* FIXME: Use DI in 16-bit DPMI and EDI in 32-bit DPMI */
        FIXME("no protected-mode dummy state save/restore handler yet\n");
        SET_SI( context, 0 );
        context->Edi = 0;
        break;

    case 0x0306:  /* Get Raw Mode Switch Addresses */
        TRACE("get raw mode switch addresses\n");

        /* real mode, point to standard DPMI return wrapper */
        SET_BX( context, DOSVM_dpmi_segments->wrap_seg );
        SET_CX( context, 0 );

        /* protected mode, point to DPMI call wrapper */
        /* FIXME: Use DI in 16-bit DPMI and EDI in 32-bit DPMI */
        /* FIXME: Doesn't work in DPMI32... */
        SET_SI( context, DOSVM_dpmi_segments->dpmi_sel );
        context->Edi = 8; /* offset of the INT 0x31 call */
        break;

    case 0x0400:  /* Get DPMI version */
        TRACE("get DPMI version\n");
        {
            SYSTEM_INFO si;

            GetSystemInfo(&si);
            SET_AX( context, 0x005a );  /* DPMI version 0.90 */
            SET_BX( context, 0x0005 );  /* Flags: 32-bit, virtual memory */
            SET_CL( context, si.wProcessorLevel );
1303
            SET_DX( context, 0x0870 );  /* Master/slave interrupt controller base */
1304 1305 1306
        }
        break;

1307 1308 1309 1310
    case 0x0401:  /* Get DPMI Capabilities (1.0) */
        FIXME( "get dpmi capabilities - unimplemented\n");
        break;

1311
    case 0x0500:  /* Get free memory information */
1312 1313
        TRACE("get free memory information\n");
        {
1314
            MEMORYSTATUS status;
1315 1316 1317 1318

            /* the layout is just the same as MEMMANINFO, but without
             * the dwSize entry.
             */
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
            struct
            {
                DWORD dwLargestFreeBlock;
                DWORD dwMaxPagesAvailable;
                DWORD dwMaxPagesLockable;
                DWORD dwTotalLinearSpace;
                DWORD dwTotalUnlockedPages;
                DWORD dwFreePages;
                DWORD dwTotalPages;
                DWORD dwFreeLinearSpace;
                DWORD dwSwapFilePages;
                WORD  wPageSize;
            } *info = CTX_SEG_OFF_TO_LIN( context, context->SegEs, context->Edi );

            GlobalMemoryStatus( &status );
            info->wPageSize            = getpagesize();
            info->dwLargestFreeBlock   = status.dwAvailVirtual;
            info->dwMaxPagesAvailable  = info->dwLargestFreeBlock / info->wPageSize;
            info->dwMaxPagesLockable   = info->dwMaxPagesAvailable;
            info->dwTotalLinearSpace   = status.dwTotalVirtual / info->wPageSize;
            info->dwTotalUnlockedPages = info->dwTotalLinearSpace;
            info->dwFreePages          = info->dwMaxPagesAvailable;
            info->dwTotalPages         = info->dwTotalLinearSpace;
            info->dwFreeLinearSpace    = info->dwMaxPagesAvailable;
            info->dwSwapFilePages      = status.dwTotalPageFile / info->wPageSize;
1344 1345 1346
            break;
        }

1347
    case 0x0501:  /* Allocate memory block */
1348 1349 1350 1351
        {
            DWORD size = MAKELONG( CX_reg(context), BX_reg(context) );
            BYTE *ptr;

1352
            TRACE( "allocate memory block (%u bytes)\n", size );
1353

1354
            ptr = DPMI_xalloc( size );
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
            if (!ptr)
            {
                SET_AX( context, 0x8012 );  /* linear memory not available */
                SET_CFLAG(context);
            } 
            else 
            {
                SET_BX( context, HIWORD(ptr) );
                SET_CX( context, LOWORD(ptr) );
                SET_SI( context, HIWORD(ptr) );
                SET_DI( context, LOWORD(ptr) );
            }
            break;
        }

1370
    case 0x0502:  /* Free memory block */
1371 1372
        {
            DWORD handle = MAKELONG( DI_reg(context), SI_reg(context) );
1373
            TRACE( "free memory block (0x%08x)\n", handle );
1374 1375 1376 1377
            DPMI_xfree( (void *)handle );
        }
        break;

1378
    case 0x0503:  /* Resize memory block */
1379 1380 1381 1382 1383
        {
            DWORD size = MAKELONG( CX_reg(context), BX_reg(context) );
            DWORD handle = MAKELONG( DI_reg(context), SI_reg(context) );
            BYTE *ptr;

1384
            TRACE( "resize memory block (0x%08x, %u bytes)\n", handle, size );
1385

1386
            ptr = DPMI_xrealloc( (void *)handle, size );
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
            if (!ptr)
            {
                SET_AX( context, 0x8012 );  /* linear memory not available */
                SET_CFLAG(context);
            } else {
                SET_BX( context, HIWORD(ptr) );
                SET_CX( context, LOWORD(ptr) );
                SET_SI( context, HIWORD(ptr) );
                SET_DI( context, LOWORD(ptr) );
            }
        }
1398 1399 1400
        break;

    case 0x0507:  /* Set page attributes (1.0) */
1401
        FIXME( "set page attributes - unimplemented\n" );
1402 1403 1404
        break;  /* Just ignore it */

    case 0x0600:  /* Lock linear region */
1405 1406
        TRACE( "lock linear region - ignored (no paging)\n" );
        break;
1407 1408

    case 0x0601:  /* Unlock linear region */
1409 1410
        TRACE( "unlock linear region - ignored (no paging)\n" );
        break;
1411

1412 1413 1414
    case 0x0602:  /* Mark real mode region as pageable */
        TRACE( "mark real mode region as pageable - ignored (no paging)\n" );
        break;
1415

1416 1417 1418
    case 0x0603:  /* Relock real mode region */
        TRACE( "relock real mode region - ignored (no paging)\n" );
        break;
1419 1420 1421 1422 1423 1424 1425

    case 0x0604:  /* Get page size */
        TRACE("get pagesize\n");
        SET_BX( context, HIWORD(getpagesize()) );
        SET_CX( context, LOWORD(getpagesize()) );
        break;

1426 1427 1428 1429 1430 1431 1432 1433
    case 0x0700: /* Mark pages as paging candidates */
        TRACE( "mark pages as paging candidates - ignored (no paging)\n" );
        break;

    case 0x0701: /* Discard pages */
        TRACE( "discard pages - ignored (no paging)\n" );
        break;

1434
    case 0x0702:  /* Mark page as demand-paging candidate */
1435 1436
        TRACE( "mark page as demand-paging candidate - ignored (no paging)\n" );
        break;
1437 1438

    case 0x0703:  /* Discard page contents */
1439 1440
        TRACE( "discard page contents - ignored (no paging)\n" );
        break;
1441 1442

    case 0x0800:  /* Physical address mapping */
1443
        FIXME( "physical address mapping (0x%08x) - unimplemented\n",
1444
               MAKELONG(CX_reg(context),BX_reg(context)) );
1445 1446
        break;

1447
    case 0x0900:  /* Get and Disable Virtual Interrupt State */
1448
        TRACE( "Get and Disable Virtual Interrupt State: %d\n",
1449 1450 1451
               get_vm86_teb_info()->dpmi_vif );
        SET_AL( context, get_vm86_teb_info()->dpmi_vif ? 1 : 0 );
        get_vm86_teb_info()->dpmi_vif = 0;
1452 1453 1454
        break;

    case 0x0901:  /* Get and Enable Virtual Interrupt State */
1455
        TRACE( "Get and Enable Virtual Interrupt State: %d\n",
1456 1457 1458
               get_vm86_teb_info()->dpmi_vif );
        SET_AL( context, get_vm86_teb_info()->dpmi_vif ? 1 : 0 );
        get_vm86_teb_info()->dpmi_vif = 1;
1459 1460 1461
        break;

    case 0x0902:  /* Get Virtual Interrupt State */
1462
        TRACE( "Get Virtual Interrupt State: %d\n",
1463 1464
               get_vm86_teb_info()->dpmi_vif );
        SET_AL( context, get_vm86_teb_info()->dpmi_vif ? 1 : 0 );
1465 1466
        break;

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
    case 0x0e00:  /* Get Coprocessor Status (1.0) */
        /*
         * Return status in AX bits:
         * B0    - MPv (MP bit in the virtual MSW/CR0)
         *         0 = numeric coprocessor is disabled for this client
         *         1 = numeric coprocessor is enabled for this client
         * B1    - EMv (EM bit in the virtual MSW/CR0)
         *         0 = client is not emulating coprocessor instructions
         *         1 = client is emulating coprocessor instructions
         * B2    - MPr (MP bit from the actual MSW/CR0)
         *         0 = numeric coprocessor is not present
         *         1 = numeric coprocessor is present
         * B3    - EMr (EM bit from the actual MSW/CR0)
         *         0 = host is not emulating coprocessor instructions
         *         1 = host is emulating coprocessor instructions
         * B4-B7 - coprocessor type
         *         00H = no coprocessor
         *         02H = 80287
         *         03H = 80387
         *         04H = 80486 with numeric coprocessor
         *         05H-0FH = reserved for future numeric processors
         */
        TRACE( "Get Coprocessor Status\n" );
        SET_AX( context, 69 ); /* 486, coprocessor present and enabled */ 
        break;

    case 0x0e01: /* Set Coprocessor Emulation (1.0) */
        /*
         * See function 0x0e00.
         * BX bit B0 is new value for MPv.
         * BX bit B1 is new value for EMv.
         */
        if (BX_reg(context) != 1)
            FIXME( "Set Coprocessor Emulation to %d - unimplemented\n", 
                   BX_reg(context) );
        else
            TRACE( "Set Coprocessor Emulation - ignored\n" );
        break;

1506 1507 1508 1509 1510
    default:
        INT_BARF( context, 0x31 );
        SET_AX( context, 0x8001 );  /* unsupported function */
        SET_CFLAG(context);
        break;
1511
    }  
1512
}