cppexcept.c 18 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * msvcrt C++ exception handling
 *
 * Copyright 2002 Alexandre Julliard
 *
 * 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 22 23 24 25 26 27 28
 *
 * NOTES
 * A good reference is the article "How a C++ compiler implements
 * exception handling" by Vishal Kochhar, available on
 * www.thecodeproject.com.
 */

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

29 30 31 32
#include <stdarg.h>

#include "windef.h"
#include "winbase.h"
33
#include "winternl.h"
34 35
#include "msvcrt.h"
#include "wine/exception.h"
36
#include "excpt.h"
37 38
#include "wine/debug.h"

39
#include "cppexcept.h"
40 41 42

#ifdef __i386__  /* CxxFrameHandler is not supported on non-i386 */

43 44
WINE_DEFAULT_DEBUG_CHANNEL(seh);

45 46
DWORD CDECL cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
                               PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
47 48
                               const cxx_function_descr *descr,
                               EXCEPTION_REGISTRATION_RECORD* nested_frame, int nested_trylevel );
49

50
/* call a function with a given ebp */
51
static inline void *call_ebp_func( void *func, void *ebp )
52 53
{
    void *ret;
54 55 56 57 58 59 60 61 62
    int dummy;
    __asm__ __volatile__ ("pushl %%ebx\n\t"
                          "pushl %%ebp\n\t"
                          "movl %4,%%ebp\n\t"
                          "call *%%eax\n\t"
                          "popl %%ebp\n\t"
                          "popl %%ebx"
                          : "=a" (ret), "=S" (dummy), "=D" (dummy)
                          : "0" (func), "1" (ebp) : "ecx", "edx", "memory" );
63 64 65 66
    return ret;
}

/* call a copy constructor */
67
static inline void call_copy_ctor( void *func, void *this, void *src, int has_vbase )
68 69 70 71 72
{
    TRACE( "calling copy ctor %p object %p src %p\n", func, this, src );
    if (has_vbase)
        /* in that case copy ctor takes an extra bool indicating whether to copy the base class */
        __asm__ __volatile__("pushl $1; pushl %2; call *%0"
73
                             : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
74 75
    else
        __asm__ __volatile__("pushl %2; call *%0"
76
                             : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
77 78 79
}

/* call the destructor of the exception object */
80
static inline void call_dtor( void *func, void *object )
81
{
82
    __asm__ __volatile__("call *%0" : : "r" (func), "c" (object) : "eax", "edx", "memory" );
83 84
}

85
/* continue execution to the specified address after exception is caught */
86
static inline void DECLSPEC_NORETURN continue_after_catch( cxx_exception_frame* frame, void *addr )
87 88 89 90 91 92
{
    __asm__ __volatile__("movl -4(%0),%%esp; leal 12(%0),%%ebp; jmp *%1"
                         : : "r" (frame), "a" (addr) );
    for (;;) ; /* unreached */
}

93
static inline void dump_type( const cxx_type_info *type )
94
{
95
    TRACE( "flags %x type %p %s offsets %d,%d,%d size %d copy ctor %p\n",
96 97 98
             type->flags, type->type_info, dbgstr_type_info(type->type_info),
             type->offsets.this_offset, type->offsets.vbase_descr, type->offsets.vbase_offset,
             type->size, type->copy_ctor );
99 100
}

101
static void dump_exception_type( const cxx_exception_type *type )
102
{
103
    UINT i;
104

105
    TRACE( "flags %x destr %p handler %p type info %p\n",
106 107 108
             type->flags, type->destructor, type->custom_handler, type->type_info_table );
    for (i = 0; i < type->type_info_table->count; i++)
    {
109
        TRACE( "    %d: ", i );
110 111 112 113
        dump_type( type->type_info_table->info[i] );
    }
}

114
static void dump_function_descr( const cxx_function_descr *descr )
115
{
116 117
    UINT i;
    int j;
118

119 120
    TRACE( "magic %x\n", descr->magic );
    TRACE( "unwind table: %p %d\n", descr->unwind_table, descr->unwind_count );
121 122
    for (i = 0; i < descr->unwind_count; i++)
    {
123
        TRACE( "    %d: prev %d func %p\n", i,
124 125
                 descr->unwind_table[i].prev, descr->unwind_table[i].handler );
    }
126
    TRACE( "try table: %p %d\n", descr->tryblock, descr->tryblock_count );
127 128
    for (i = 0; i < descr->tryblock_count; i++)
    {
129
        TRACE( "    %d: start %d end %d catchlevel %d catch %p %d\n", i,
130 131 132 133 134
                 descr->tryblock[i].start_level, descr->tryblock[i].end_level,
                 descr->tryblock[i].catch_level, descr->tryblock[i].catchblock,
                 descr->tryblock[i].catchblock_count );
        for (j = 0; j < descr->tryblock[i].catchblock_count; j++)
        {
135
            const catchblock_info *ptr = &descr->tryblock[i].catchblock[j];
136
            TRACE( "        %d: flags %x offset %d handler %p type %p %s\n",
137 138
                     j, ptr->flags, ptr->offset, ptr->handler,
                     ptr->type_info, dbgstr_type_info( ptr->type_info ) );
139 140 141 142 143
        }
    }
}

/* check if the exception type is caught by a given catch block, and return the type that matched */
144 145
static const cxx_type_info *find_caught_type( cxx_exception_type *exc_type,
                                              const catchblock_info *catchblock )
146 147 148 149 150
{
    UINT i;

    for (i = 0; i < exc_type->type_info_table->count; i++)
    {
151
        const cxx_type_info *type = exc_type->type_info_table->info[i];
152 153 154 155

        if (!catchblock->type_info) return type;   /* catch(...) matches any type */
        if (catchblock->type_info != type->type_info)
        {
156
            if (strcmp( catchblock->type_info->mangled, type->type_info->mangled )) continue;
157 158 159 160 161 162 163 164 165 166 167 168 169 170
        }
        /* type is the same, now check the flags */
        if ((exc_type->flags & TYPE_FLAG_CONST) &&
            !(catchblock->flags & TYPE_FLAG_CONST)) continue;
        if ((exc_type->flags & TYPE_FLAG_VOLATILE) &&
            !(catchblock->flags & TYPE_FLAG_VOLATILE)) continue;
        return type;  /* it matched */
    }
    return NULL;
}


/* copy the exception object where the catch block wants it */
static void copy_exception( void *object, cxx_exception_frame *frame,
171
                            const catchblock_info *catchblock, const cxx_type_info *type )
172 173 174
{
    void **dest_ptr;

175
    if (!catchblock->type_info || !catchblock->type_info->mangled[0]) return;
176 177 178 179 180
    if (!catchblock->offset) return;
    dest_ptr = (void **)((char *)&frame->ebp + catchblock->offset);

    if (catchblock->flags & TYPE_FLAG_REFERENCE)
    {
181
        *dest_ptr = get_this_pointer( &type->offsets, object );
182 183 184 185 186
    }
    else if (type->flags & CLASS_IS_SIMPLE_TYPE)
    {
        memmove( dest_ptr, object, type->size );
        /* if it is a pointer, adjust it */
187
        if (type->size == sizeof(void *)) *dest_ptr = get_this_pointer( &type->offsets, *dest_ptr );
188 189 190 191
    }
    else  /* copy the object */
    {
        if (type->copy_ctor)
192
            call_copy_ctor( type->copy_ctor, dest_ptr, get_this_pointer(&type->offsets,object),
193 194
                            (type->flags & CLASS_HAS_VIRTUAL_BASE_CLASS) );
        else
195
            memmove( dest_ptr, get_this_pointer(&type->offsets,object), type->size );
196 197 198 199
    }
}

/* unwind the local function up to a given trylevel */
200
static void cxx_local_unwind( cxx_exception_frame* frame, const cxx_function_descr *descr, int last_level)
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
{
    void (*handler)();
    int trylevel = frame->trylevel;

    while (trylevel != last_level)
    {
        if (trylevel < 0 || trylevel >= descr->unwind_count)
        {
            ERR( "invalid trylevel %d\n", trylevel );
            MSVCRT_terminate();
        }
        handler = descr->unwind_table[trylevel].handler;
        if (handler)
        {
            TRACE( "calling unwind handler %p trylevel %d last %d ebp %p\n",
                   handler, trylevel, last_level, &frame->ebp );
            call_ebp_func( handler, &frame->ebp );
        }
        trylevel = descr->unwind_table[trylevel].prev;
    }
    frame->trylevel = last_level;
}

224 225 226
/* exception frame for nested exceptions in catch block */
struct catch_func_nested_frame
{
227 228 229
    EXCEPTION_REGISTRATION_RECORD frame;     /* standard exception frame */
    EXCEPTION_RECORD             *prev_rec;  /* previous record to restore in thread data */
    cxx_exception_frame          *cxx_frame; /* frame of parent exception */
230
    const cxx_function_descr     *descr;     /* descriptor of parent exception */
231
    int                           trylevel;  /* current try level */
232
    EXCEPTION_RECORD             *rec;       /* rec associated with frame */
233 234 235
};

/* handler for exceptions happening while calling a catch function */
236 237
static DWORD catch_function_nested_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
                                            CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
238 239 240 241 242 243 244 245
{
    struct catch_func_nested_frame *nested_frame = (struct catch_func_nested_frame *)frame;

    if (rec->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
    {
        msvcrt_get_thread_data()->exc_record = nested_frame->prev_rec;
        return ExceptionContinueSearch;
    }
246 247 248 249

    TRACE( "got nested exception in catch function\n" );

    if(rec->ExceptionCode == CXX_EXCEPTION)
250
    {
251
        PEXCEPTION_RECORD prev_rec = nested_frame->rec;
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        if(rec->ExceptionInformation[1] == 0 && rec->ExceptionInformation[2] == 0)
        {
            /* exception was rethrown */
            rec->ExceptionInformation[1] = prev_rec->ExceptionInformation[1];
            rec->ExceptionInformation[2] = prev_rec->ExceptionInformation[2];
            TRACE("detect rethrow: re-propagate: obj: %lx, type: %lx\n",
                    rec->ExceptionInformation[1], rec->ExceptionInformation[2]);
        }
        else {
            /* new exception in exception handler, destroy old */
            void *object = (void*)prev_rec->ExceptionInformation[1];
            cxx_exception_type *info = (cxx_exception_type*) prev_rec->ExceptionInformation[2];
            TRACE("detect threw new exception in catch block - destroy old(obj: %p type: %p)\n",
                    object, info);
            if(info && info->destructor)
                call_dtor( info->destructor, object );
        }
269
    }
270 271 272 273

    return cxx_frame_handler( rec, nested_frame->cxx_frame, context,
                              NULL, nested_frame->descr, &nested_frame->frame,
                              nested_frame->trylevel );
274 275
}

276 277
/* find and call the appropriate catch block for an exception */
/* returns the address to continue execution to after the catch block was called */
278
static inline void call_catch_block( PEXCEPTION_RECORD rec, cxx_exception_frame *frame,
279
                                     const cxx_function_descr *descr, int nested_trylevel,
280
                                     cxx_exception_type *info )
281
{
282 283
    UINT i;
    int j;
284
    void *addr, *object = (void *)rec->ExceptionInformation[1];
285 286
    struct catch_func_nested_frame nested_frame;
    int trylevel = frame->trylevel;
287
    thread_data_t *thread_data = msvcrt_get_thread_data();
288
    DWORD save_esp = ((DWORD*)frame)[-1];
289 290 291

    for (i = 0; i < descr->tryblock_count; i++)
    {
292
        const tryblock_info *tryblock = &descr->tryblock[i];
293 294 295 296 297 298 299

        if (trylevel < tryblock->start_level) continue;
        if (trylevel > tryblock->end_level) continue;

        /* got a try block */
        for (j = 0; j < tryblock->catchblock_count; j++)
        {
300
            const catchblock_info *catchblock = &tryblock->catchblock[j];
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
            if(info)
            {
                const cxx_type_info *type = find_caught_type( info, catchblock );
                if (!type) continue;

                TRACE( "matched type %p in tryblock %d catchblock %d\n", type, i, j );

                /* copy the exception to its destination on the stack */
                copy_exception( object, frame, catchblock, type );
            }
            else
            {
                /* no CXX_EXCEPTION only proceed with a catch(...) block*/
                if(catchblock->type_info)
                    continue;
                TRACE("found catch(...) block\n");
            }
318 319

            /* unwind the stack */
320
            RtlUnwind( frame, 0, rec, 0 );
321 322 323 324
            cxx_local_unwind( frame, descr, tryblock->start_level );
            frame->trylevel = tryblock->end_level + 1;

            /* call the catch block */
325 326
            TRACE( "calling catch block %p addr %p ebp %p\n",
                   catchblock, catchblock->handler, &frame->ebp );
327 328 329 330 331 332 333 334

            /* setup an exception block for nested exceptions */

            nested_frame.frame.Handler = catch_function_nested_handler;
            nested_frame.prev_rec  = thread_data->exc_record;
            nested_frame.cxx_frame = frame;
            nested_frame.descr     = descr;
            nested_frame.trylevel  = nested_trylevel + 1;
335
            nested_frame.rec = rec;
336 337 338

            __wine_push_frame( &nested_frame.frame );
            thread_data->exc_record = rec;
339
            addr = call_ebp_func( catchblock->handler, &frame->ebp );
340 341 342
            thread_data->exc_record = nested_frame.prev_rec;
            __wine_pop_frame( &nested_frame.frame );

343
            ((DWORD*)frame)[-1] = save_esp;
344
            if (info && info->destructor) call_dtor( info->destructor, object );
345
            TRACE( "done, continuing at %p\n", addr );
346

347
            continue_after_catch( frame, addr );
348 349 350 351 352 353 354 355 356 357
        }
    }
}


/*********************************************************************
 *		cxx_frame_handler
 *
 * Implementation of __CxxFrameHandler.
 */
358 359
DWORD CDECL cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
                               PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
360 361
                               const cxx_function_descr *descr,
                               EXCEPTION_REGISTRATION_RECORD* nested_frame,
362
                               int nested_trylevel )
363 364 365 366 367 368 369 370 371 372
{
    cxx_exception_type *exc_type;

    if (descr->magic != CXX_FRAME_MAGIC)
    {
        ERR( "invalid frame magic %x\n", descr->magic );
        return ExceptionContinueSearch;
    }
    if (rec->ExceptionFlags & (EH_UNWINDING|EH_EXIT_UNWIND))
    {
373
        if (descr->unwind_count && !nested_trylevel) cxx_local_unwind( frame, descr, -1 );
374 375 376 377
        return ExceptionContinueSearch;
    }
    if (!descr->tryblock_count) return ExceptionContinueSearch;

378
    if(rec->ExceptionCode == CXX_EXCEPTION)
379 380
    {
        exc_type = (cxx_exception_type *)rec->ExceptionInformation[2];
381

382 383 384
        if (rec->ExceptionInformation[0] > CXX_FRAME_MAGIC &&
                exc_type->custom_handler)
        {
385
            return exc_type->custom_handler( rec, frame, context, dispatch,
386 387
                                         descr, nested_trylevel, nested_frame, 0 );
        }
388

389 390 391 392 393
        if (TRACE_ON(seh))
        {
            TRACE("handling C++ exception rec %p frame %p trylevel %d descr %p nested_frame %p\n",
                  rec, frame, frame->trylevel, descr, nested_frame );
            dump_exception_type( exc_type );
394
            dump_function_descr( descr );
395 396 397
        }
    }
    else
398
    {
399
        exc_type = NULL;
400
        TRACE("handling C exception code %x  rec %p frame %p trylevel %d descr %p nested_frame %p\n",
401
              rec->ExceptionCode,  rec, frame, frame->trylevel, descr, nested_frame );
402 403
    }

404 405
    call_catch_block( rec, frame, descr, frame->trylevel, exc_type );
    return ExceptionContinueSearch;
406 407 408 409 410 411
}


/*********************************************************************
 *		__CxxFrameHandler (MSVCRT.@)
 */
412 413
extern DWORD CDECL __CxxFrameHandler( PEXCEPTION_RECORD rec, EXCEPTION_REGISTRATION_RECORD* frame,
                                      PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch );
414 415 416 417 418 419 420 421 422 423
__ASM_GLOBAL_FUNC( __CxxFrameHandler,
                   "pushl $0\n\t"        /* nested_trylevel */
                   "pushl $0\n\t"        /* nested_frame */
                   "pushl %eax\n\t"      /* descr */
                   "pushl 28(%esp)\n\t"  /* dispatch */
                   "pushl 28(%esp)\n\t"  /* context */
                   "pushl 28(%esp)\n\t"  /* frame */
                   "pushl 28(%esp)\n\t"  /* rec */
                   "call " __ASM_NAME("cxx_frame_handler") "\n\t"
                   "add $28,%esp\n\t"
424
                   "ret" )
425

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

/*********************************************************************
 *		__CxxLongjmpUnwind (MSVCRT.@)
 *
 * Callback meant to be used as UnwindFunc for setjmp/longjmp.
 */
void __stdcall __CxxLongjmpUnwind( const struct MSVCRT___JUMP_BUFFER *buf )
{
    cxx_exception_frame *frame = (cxx_exception_frame *)buf->Registration;
    const cxx_function_descr *descr = (const cxx_function_descr *)buf->UnwindData[0];

    TRACE( "unwinding frame %p descr %p trylevel %ld\n", frame, descr, buf->TryLevel );
    cxx_local_unwind( frame, descr, buf->TryLevel );
}

441 442 443 444 445
#endif  /* __i386__ */

/*********************************************************************
 *		_CxxThrowException (MSVCRT.@)
 */
446
void CDECL _CxxThrowException( exception *object, const cxx_exception_type *type )
447
{
448
    ULONG_PTR args[3];
449 450

    args[0] = CXX_FRAME_MAGIC;
451 452
    args[1] = (ULONG_PTR)object;
    args[2] = (ULONG_PTR)type;
453 454
    RaiseException( CXX_EXCEPTION, EH_NONCONTINUABLE, 3, args );
}
455 456 457 458

/*********************************************************************
 *		__CxxDetectRethrow (MSVCRT.@)
 */
459
BOOL CDECL __CxxDetectRethrow(PEXCEPTION_POINTERS ptrs)
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
{
  PEXCEPTION_RECORD rec;

  if (!ptrs)
    return FALSE;

  rec = ptrs->ExceptionRecord;

  if (rec->ExceptionCode == CXX_EXCEPTION &&
      rec->NumberParameters == 3 &&
      rec->ExceptionInformation[0] == CXX_FRAME_MAGIC &&
      rec->ExceptionInformation[2])
  {
    ptrs->ExceptionRecord = msvcrt_get_thread_data()->exc_record;
    return TRUE;
  }
  return (msvcrt_get_thread_data()->exc_record == rec);
}

/*********************************************************************
 *		__CxxQueryExceptionSize (MSVCRT.@)
 */
482
unsigned int CDECL __CxxQueryExceptionSize(void)
483 484 485
{
  return sizeof(cxx_exception_type);
}