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 33
#include <stdarg.h>

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

40
#include "cppexcept.h"
41 42 43

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

44 45
WINE_DEFAULT_DEBUG_CHANNEL(seh);

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

51 52 53 54
/* call a function with a given ebp */
inline static void *call_ebp_func( void *func, void *ebp )
{
    void *ret;
55 56 57 58 59 60 61 62 63
    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" );
64 65 66 67 68 69 70 71 72 73
    return ret;
}

/* call a copy constructor */
inline static void call_copy_ctor( void *func, void *this, void *src, int has_vbase )
{
    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"
74
                             : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
75 76
    else
        __asm__ __volatile__("pushl %2; call *%0"
77
                             : : "r" (func), "c" (this), "r" (src) : "eax", "edx", "memory" );
78 79 80 81 82
}

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

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

94
static inline void dump_type( const cxx_type_info *type )
95
{
96
    TRACE( "flags %x type %p %s offsets %d,%d,%d size %d copy ctor %p\n",
97 98 99
             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 );
100 101
}

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

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

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

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

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

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

        if (!catchblock->type_info) return type;   /* catch(...) matches any type */
        if (catchblock->type_info != type->type_info)
        {
157
            if (strcmp( catchblock->type_info->mangled, type->type_info->mangled )) continue;
158 159 160 161 162 163 164 165 166 167 168 169 170 171
        }
        /* 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,
172
                            const catchblock_info *catchblock, const cxx_type_info *type )
173 174 175
{
    void **dest_ptr;

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

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

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

225 226 227
/* exception frame for nested exceptions in catch block */
struct catch_func_nested_frame
{
228 229 230
    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 */
231
    const cxx_function_descr     *descr;     /* descriptor of parent exception */
232
    int                           trylevel;  /* current try level */
233
    EXCEPTION_RECORD             *rec;       /* rec associated with frame */
234 235 236
};

/* handler for exceptions happening while calling a catch function */
237 238
static DWORD catch_function_nested_handler( EXCEPTION_RECORD *rec, EXCEPTION_REGISTRATION_RECORD *frame,
                                            CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **dispatcher )
239 240 241 242 243 244 245 246
{
    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;
    }
247 248 249 250

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

    if(rec->ExceptionCode == CXX_EXCEPTION)
251
    {
252
        PEXCEPTION_RECORD prev_rec = nested_frame->rec;
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        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 );
        }
270
    }
271 272 273 274

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

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

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

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

        /* got a try block */
        for (j = 0; j < tryblock->catchblock_count; j++)
        {
301
            const catchblock_info *catchblock = &tryblock->catchblock[j];
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
            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");
            }
319 320

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

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

            /* 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;
336
            nested_frame.rec = rec;
337 338 339

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

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

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


/*********************************************************************
 *		cxx_frame_handler
 *
 * Implementation of __CxxFrameHandler.
 */
359 360
DWORD CDECL cxx_frame_handler( PEXCEPTION_RECORD rec, cxx_exception_frame* frame,
                               PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch,
361 362
                               const cxx_function_descr *descr,
                               EXCEPTION_REGISTRATION_RECORD* nested_frame,
363
                               int nested_trylevel )
364 365 366 367 368 369 370 371 372 373
{
    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))
    {
374
        if (descr->unwind_count && !nested_trylevel) cxx_local_unwind( frame, descr, -1 );
375 376 377 378
        return ExceptionContinueSearch;
    }
    if (!descr->tryblock_count) return ExceptionContinueSearch;

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

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

390 391 392 393 394
        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 );
395
            dump_function_descr( descr );
396 397 398
        }
    }
    else
399
    {
400
        exc_type = NULL;
401
        TRACE("handling C exception code %x  rec %p frame %p trylevel %d descr %p nested_frame %p\n",
402
              rec->ExceptionCode,  rec, frame, frame->trylevel, descr, nested_frame );
403 404
    }

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


/*********************************************************************
 *		__CxxFrameHandler (MSVCRT.@)
 */
413 414
extern DWORD CDECL __CxxFrameHandler( PEXCEPTION_RECORD rec, EXCEPTION_REGISTRATION_RECORD* frame,
                                      PCONTEXT context, EXCEPTION_REGISTRATION_RECORD** dispatch );
415 416 417 418 419 420 421 422 423 424 425
__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"
                   "ret" );
426

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

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

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

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

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

/*********************************************************************
 *		__CxxDetectRethrow (MSVCRT.@)
 */
460
BOOL CDECL __CxxDetectRethrow(PEXCEPTION_POINTERS ptrs)
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
{
  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.@)
 */
483
unsigned int CDECL __CxxQueryExceptionSize(void)
484 485 486
{
  return sizeof(cxx_exception_type);
}