Welcome to mirror list, hosted at ThFree Co, Russian Federation.

cxa_personality.cpp « src « libcxxabi - github.com/llvm/llvm-project.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6fd570278de4492e4bfcade36e6b660a87384fac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//===------------------------- cxa_exception.cpp --------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//  
//  This file implements the "Exception Handling APIs"
//  http://www.codesourcery.com/public/cxx-abi/abi-eh.html
//  http://www.intel.com/design/itanium/downloads/245358.htm
//  
//===----------------------------------------------------------------------===//

#include "unwind.h"
#include "cxa_exception.hpp"
#include <typeinfo>
#include <stdlib.h>
#include <assert.h>

namespace __cxxabiv1
{

extern "C"
{

// private API

// Heavily borrowed from llvm/examples/ExceptionDemo/ExceptionDemo.cpp

// DWARF Constants
enum
{
    DW_EH_PE_absptr   = 0x00,
    DW_EH_PE_uleb128  = 0x01,
    DW_EH_PE_udata2   = 0x02,
    DW_EH_PE_udata4   = 0x03,
    DW_EH_PE_udata8   = 0x04,
    DW_EH_PE_sleb128  = 0x09,
    DW_EH_PE_sdata2   = 0x0A,
    DW_EH_PE_sdata4   = 0x0B,
    DW_EH_PE_sdata8   = 0x0C,
    DW_EH_PE_pcrel    = 0x10,
    DW_EH_PE_textrel  = 0x20,
    DW_EH_PE_datarel  = 0x30,
    DW_EH_PE_funcrel  = 0x40,
    DW_EH_PE_aligned  = 0x50,
    DW_EH_PE_indirect = 0x80,
    DW_EH_PE_omit     = 0xFF
};

/// Read a uleb128 encoded value and advance pointer 
/// See Variable Length Data Appendix C in: 
/// @link http://dwarfstd.org/Dwarf4.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static
uintptr_t
readULEB128(const uint8_t** data)
{
    uintptr_t result = 0;
    uintptr_t shift = 0;
    unsigned char byte;
    const uint8_t *p = *data;
    do
    {
        byte = *p++;
        result |= static_cast<uintptr_t>(byte & 0x7F) << shift;
        shift += 7;
    } while (byte & 0x80);
    *data = p;
    return result;
}

/// Read a sleb128 encoded value and advance pointer 
/// See Variable Length Data Applendix C in: 
/// @link http://dwarfstd.org/Dwarf4.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @returns decoded value
static
uintptr_t
readSLEB128(const uint8_t** data)
{
    uintptr_t result = 0;
    uintptr_t shift = 0;
    unsigned char byte;
    const uint8_t *p = *data;
    do
    {
        byte = *p++;
        result |= static_cast<uintptr_t>(byte & 0x7F) << shift;
        shift += 7;
    } while (byte & 0x80);
    *data = p;
    if ((byte & 0x40) && (shift < (sizeof(result) << 3)))
        result |= static_cast<uintptr_t>(~0) << shift;
    return result;
}

/// Read a pointer encoded value and advance pointer 
/// See Variable Length Data in: 
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// @param data reference variable holding memory pointer to decode from
/// @param encoding dwarf encoding type
/// @returns decoded value
static
uintptr_t
readEncodedPointer(const uint8_t** data, uint8_t encoding)
{
// TODO:  Not quite rgiht.  This should be able to read a 0 from the TType table
//                          and not dereference it.  Pasted in temporayr workaround
// TODO:  Sometimes this is clearly not always reading an encoded pointer, for
//        example a length in the call site table.  Needs new name?
    uintptr_t result = 0;
    const uint8_t* p = *data;
    if (encoding == DW_EH_PE_omit) 
        return result;
    // first get value 
    switch (encoding & 0x0F)
    {
    case DW_EH_PE_absptr:
        result = *((uintptr_t*)p);
        p += sizeof(uintptr_t);
        break;
    case DW_EH_PE_uleb128:
        result = readULEB128(&p);
        break;
    case DW_EH_PE_sleb128:
        result = readSLEB128(&p);
        break;
    case DW_EH_PE_udata2:
        result = *((uint16_t*)p);
        p += sizeof(uint16_t);
        break;
    case DW_EH_PE_udata4:
        result = *((uint32_t*)p);
        p += sizeof(uint32_t);
        break;
    case DW_EH_PE_udata8:
        result = *((uint64_t*)p);
        p += sizeof(uint64_t);
        break;
    case DW_EH_PE_sdata2:
        result = *((int16_t*)p);
        p += sizeof(int16_t);
        break;
    case DW_EH_PE_sdata4:
        result = *((int32_t*)p);
        p += sizeof(int32_t);
        break;
    case DW_EH_PE_sdata8:
        result = *((int64_t*)p);
        p += sizeof(int64_t);
        break;
    default:
        // not supported 
        abort();
        break;
    }
    // then add relative offset 
    switch (encoding & 0x70)
    {
    case DW_EH_PE_absptr:
        // do nothing 
        break;
    case DW_EH_PE_pcrel:
        if (result)
            result += (uintptr_t)(*data);
        break;
    case DW_EH_PE_textrel:
    case DW_EH_PE_datarel:
    case DW_EH_PE_funcrel:
    case DW_EH_PE_aligned:
    default:
        // not supported 
        abort();
        break;
    }
    // then apply indirection 
    if (result && (encoding & DW_EH_PE_indirect))
        result = *((uintptr_t*)result);
    *data = p;
    return result;
}

static
const uint8_t*
getTTypeEntry(int64_t typeOffset, const uint8_t* classInfo, uint8_t ttypeEncoding)
{
    switch (ttypeEncoding & 0x0F)
    {
    case DW_EH_PE_absptr:
        typeOffset *= sizeof(void*);
        break;
    case DW_EH_PE_udata2:
    case DW_EH_PE_sdata2:
        typeOffset *= 2;
        break;
    case DW_EH_PE_udata4:
    case DW_EH_PE_sdata4:
        typeOffset *= 4;
        break;
    case DW_EH_PE_udata8:
    case DW_EH_PE_sdata8:
        typeOffset *= 8;
        break;
    }
    return classInfo - typeOffset;
}

/// Deals with Dwarf actions matching our type infos 
/// (OurExceptionType_t instances). Returns whether or not a dwarf emitted 
/// action matches the supplied exception type. If such a match succeeds, 
/// the handlerSwitchValue will be set with > 0 index value. Only 
/// corresponding llvm.eh.selector type info arguments, cleanup arguments 
/// are supported. Filters are not supported.
/// See Variable Length Data in: 
/// @link http://dwarfstd.org/Dwarf3.pdf @unlink
/// Also see @link http://refspecs.freestandards.org/abi-eh-1.21.html @unlink
/// @param classInfo our array of type info pointers (to globals)
/// @param actionEntry index into above type info array or 0 (clean up). 
///        We do not support filters.
/// @param exceptionObject thrown _Unwind_Exception instance.
/// @returns whether or not a type info was found. False is returned if only
///          a cleanup was found
static
bool
handleActionValue(const uint8_t* classInfo, uintptr_t actionEntry,
                  _Unwind_Exception* exceptionObject, uint8_t ttypeEncoding)
{
    __cxa_exception* excp = (__cxa_exception*)(exceptionObject+1) - 1;
    const std::type_info* excpType = excp->exceptionType;
    const uint8_t* actionPos = (uint8_t*)actionEntry;
    while (true)
    {
        // Each emitted dwarf action corresponds to a 2 tuple of
        // type info address offset, and action offset to the next
        // emitted action.
        const uint8_t* SactionPos = actionPos;
        int64_t typeOffset = readSLEB128(&actionPos);
        const uint8_t* tempActionPos = actionPos;
        int64_t actionOffset = readSLEB128(&tempActionPos);
        if (typeOffset > 0)  // a catch handler
        {
            const uint8_t* TTypeEntry = getTTypeEntry(typeOffset, classInfo,
                                                      ttypeEncoding);
            const std::type_info* catchType =
                       (const std::type_info*)readEncodedPointer(&TTypeEntry,
                                                                 ttypeEncoding);
            // catchType == 0 -> catch (...)
            if (catchType == 0 || excpType == catchType)
            {
                excp->handlerSwitchValue = typeOffset;
                excp->actionRecord = SactionPos;
                return true;
            }
        }
        else if (typeOffset < 0)  // an exception spec
        {
        }
        else  // typeOffset == 0  // a clean up
        {
        }
        if (actionOffset == 0)
            break;
        actionPos += actionOffset;
    }
    return false;
}

// Return true if there is a handler and false otherwise
// cache handlerSwitchValue, actionRecord, languageSpecificData,
//    catchTemp and adjustedPtr here.
static
bool
contains_handler(_Unwind_Exception* exceptionObject, _Unwind_Context* context)
{
    __cxa_exception* excp = (__cxa_exception*)(exceptionObject+1) - 1;
    const uint8_t* lsda = (const uint8_t*)_Unwind_GetLanguageSpecificData(context);
    excp->languageSpecificData = lsda;
    // set adjustedPtr!  __cxa_get_exception_ptr and __cxa_begin_catch use it.
    // TODO:  Put it where it is supposed to be and adjust it properly
    excp->adjustedPtr = exceptionObject+1;
    if (lsda)
    {
        // Get the current instruction pointer and offset it before next
        // instruction in the current frame which threw the exception.
        uintptr_t pc = _Unwind_GetIP(context) - 1;
        // Get beginning current frame's code (as defined by the 
        // emitted dwarf code)
        uintptr_t funcStart = _Unwind_GetRegionStart(context);
        uintptr_t pcOffset = pc - funcStart;
        const uint8_t* classInfo = NULL;
        // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
        //       dwarf emission
        // Parse LSDA header.
        uint8_t lpStartEncoding = *lsda++;
        if (lpStartEncoding != DW_EH_PE_omit)
            (void)readEncodedPointer(&lsda, lpStartEncoding); 
        uint8_t ttypeEncoding = *lsda++;
        // TODO:  preflight ttypeEncoding here and return error if there's a problem
        if (ttypeEncoding != DW_EH_PE_omit)
        {
            // Calculate type info locations in emitted dwarf code which
            // were flagged by type info arguments to llvm.eh.selector
            // intrinsic
            uintptr_t classInfoOffset = readULEB128(&lsda);
            classInfo = lsda + classInfoOffset;
        }
        // Walk call-site table looking for range that 
        // includes current PC. 
        uint8_t callSiteEncoding = *lsda++;
        uint32_t callSiteTableLength = readULEB128(&lsda);
        const uint8_t* callSiteTableStart = lsda;
        const uint8_t* callSiteTableEnd = callSiteTableStart + callSiteTableLength;
        const uint8_t* actionTableStart = callSiteTableEnd;
        const uint8_t* callSitePtr = callSiteTableStart;
        while (callSitePtr < callSiteTableEnd)
        {
            uintptr_t start = readEncodedPointer(&callSitePtr, callSiteEncoding);
            uintptr_t length = readEncodedPointer(&callSitePtr, callSiteEncoding);
            uintptr_t landingPad = readEncodedPointer(&callSitePtr, callSiteEncoding);
            // Note: Action value
            uintptr_t actionEntry = readULEB128(&callSitePtr);
            if (landingPad == 0)
                continue; // no landing pad for this entry
            if (actionEntry)
                actionEntry += ((uintptr_t)actionTableStart) - 1;
            if ((start <= pcOffset) && (pcOffset < (start + length)))
            {
                excp->catchTemp = (void*)(funcStart + landingPad);
                if (actionEntry)
                    return handleActionValue(classInfo, 
                                             actionEntry, 
                                             exceptionObject,
                                             ttypeEncoding);
                // Note: Only non-clean up handlers are marked as
                //       found. Otherwise the clean up handlers will be 
                //       re-found and executed during the clean up 
                //       phase.
                return true;  //?
            }
        }
        // Not found, need to properly terminate
    }
    return false;
}

static
_Unwind_Reason_Code
transfer_control_to_landing_pad(_Unwind_Exception* exceptionObject,
                                _Unwind_Context* context)
{
    __cxa_exception* excp = (__cxa_exception*)(exceptionObject+1) - 1;
    _Unwind_SetGR(context, __builtin_eh_return_data_regno(0), (uintptr_t)exceptionObject);
    _Unwind_SetGR(context, __builtin_eh_return_data_regno(1), excp->handlerSwitchValue);
    _Unwind_SetIP(context, (uintptr_t)excp->catchTemp);
    return _URC_INSTALL_CONTEXT;
}

static
_Unwind_Reason_Code
perform_cleanup(_Unwind_Exception* exceptionObject, _Unwind_Context* context)
{
    __cxa_exception* excp = (__cxa_exception*)(exceptionObject+1) - 1;
    _Unwind_SetGR(context, __builtin_eh_return_data_regno(0), (uintptr_t)exceptionObject);
    _Unwind_SetGR(context, __builtin_eh_return_data_regno(1), 0);
    _Unwind_SetIP(context, (uintptr_t)excp->catchTemp);
    return _URC_INSTALL_CONTEXT;
}

// public API

// Requires:  version == 1
//            actions == _UA_SEARCH_PHASE, or
//                    == _UA_CLEANUP_PHASE, or
//                    == _UA_CLEANUP_PHASE | _UA_HANDLER_FRAME, or
//                    == _UA_CLEANUP_PHASE | _UA_FORCE_UNWIND
//            exceptionObject != nullptr
//            context != nullptr
_Unwind_Reason_Code
__gxx_personality_v0(int version, _Unwind_Action actions, uint64_t exceptionClass,
                     _Unwind_Exception* exceptionObject, _Unwind_Context* context)
{
    if (version == 1 && exceptionObject != 0 && context != 0)
    {
        bool native_exception = (exceptionClass & 0xFFFFFF00) == 0x432B2B00;
        bool force_unwind = actions & _UA_FORCE_UNWIND;
        if (native_exception && !force_unwind)
        {
            if (actions & _UA_SEARCH_PHASE)
            {
                if (actions & _UA_CLEANUP_PHASE)
                    return _URC_FATAL_PHASE1_ERROR;
                if (contains_handler(exceptionObject, context))
                    return _URC_HANDLER_FOUND;
                return _URC_CONTINUE_UNWIND;
            }
            if (actions & _UA_CLEANUP_PHASE)
            {
                if (actions & _UA_HANDLER_FRAME)
                {
                    // return _URC_INSTALL_CONTEXT or _URC_FATAL_PHASE2_ERROR
                    return transfer_control_to_landing_pad(exceptionObject, context);
                }
                // return _URC_CONTINUE_UNWIND or _URC_FATAL_PHASE2_ERROR
                return perform_cleanup(exceptionObject, context);
            }
        }
        else // foreign exception or force_unwind
        {
            if (actions & _UA_SEARCH_PHASE)
            {
                if (actions & _UA_CLEANUP_PHASE)
                    return _URC_FATAL_PHASE1_ERROR;
                return _URC_CONTINUE_UNWIND;
            }
            if (actions & _UA_CLEANUP_PHASE)
            {
                if (actions & _UA_HANDLER_FRAME)
                    return _URC_FATAL_PHASE2_ERROR;
                // return _URC_CONTINUE_UNWIND or _URC_FATAL_PHASE2_ERROR
                return perform_cleanup(exceptionObject, context);
            }
        }
    }
    return _URC_FATAL_PHASE1_ERROR;
}

}  // extern "C"

}  // __cxxabiv1