source: libcfa/src/concurrency/coroutine.cfa

Last change on this file was cce0807, checked in by caparson <caparson@…>, 12 months ago

Fixed non-local ehm memory leak that occurs when a coroutine is deleted while suspended in a catchresume handler

  • Property mode set to 100644
File size: 13.6 KB
RevLine 
[6a3d2e7]1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
[75a17f1]7// coroutine.c --
[6a3d2e7]8//
9// Author           : Thierry Delisle
10// Created On       : Mon Nov 28 12:27:26 2016
[6b0b624]11// Last Modified By : Peter A. Buhr
[60f69f0]12// Last Modified On : Mon Sep 18 21:47:12 2023
13// Update Count     : 25
[6a3d2e7]14//
15
[2026bb6]16#define __cforall_thread__
17
[58b6d1b]18#include "coroutine.hfa"
[bd98b58]19
[6a3d2e7]20#include <stddef.h>
21#include <malloc.h>
22#include <errno.h>
23#include <string.h>
24#include <unistd.h>
[ada0246d]25#include <sys/mman.h>                                                                   // mprotect
[76e069f]26#include <unwind.h>
[6a3d2e7]27
[708ae38]28#include "kernel/private.hfa"
[c960331]29#include "exception.hfa"
[3318dff]30#include "exception.h"
[bfcf6b9]31#include "math.hfa"
[6a3d2e7]32
[97229d6]33#define CFA_COROUTINE_USE_MMAP 0
34
[6a3d2e7]35#define __CFA_INVOKE_PRIVATE__
36#include "invoke.h"
37
[76e069f]38extern "C" {
[e84ab3d]39        void _CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct coroutine$ *) __attribute__ ((__noreturn__));
[b2f6113]40        static void _CtxCoroutine_UnwindCleanup(_Unwind_Reason_Code, struct _Unwind_Exception *) __attribute__ ((__noreturn__));
41        static void _CtxCoroutine_UnwindCleanup(_Unwind_Reason_Code, struct _Unwind_Exception *) {
42                abort();
43        }
[f019069]44
45        extern void CtxRet( struct __stack_context_t * to ) asm ("CtxRet") __attribute__ ((__noreturn__));
[76e069f]46}
47
[1c01c58]48//-----------------------------------------------------------------------------
[fd54fef]49forall(T &)
[c18bf9e]50void copy(CoroutineCancelled(T) * dst, CoroutineCancelled(T) * src) libcfa_public {
[342be43]51        dst->virtual_table = src->virtual_table;
[1c01c58]52        dst->the_coroutine = src->the_coroutine;
53        dst->the_exception = src->the_exception;
54}
55
[fd54fef]56forall(T &)
[c18bf9e]57const char * msg(CoroutineCancelled(T) *) libcfa_public {
[1c01c58]58        return "CoroutineCancelled(...)";
59}
60
61// This code should not be inlined. It is the error path on resume.
[fd54fef]62forall(T & | is_coroutine(T))
[b583113]63void __cfaehm_cancelled_coroutine(
[c3b9d639]64                T & cor, coroutine$ * desc, EHM_DEFAULT_VTABLE(CoroutineCancelled(T)) ) libcfa_public {
[1c01c58]65        verify( desc->cancellation );
66        desc->state = Cancelled;
[342be43]67        exception_t * except = __cfaehm_cancellation_exception( desc->cancellation );
[1c01c58]68
[69c5c00]69        // TODO: Remove explitate vtable set once trac#186 is fixed.
[b583113]70        CoroutineCancelled(T) except;
71        except.virtual_table = &_default_vtable;
[1c01c58]72        except.the_coroutine = &cor;
73        except.the_exception = except;
[ecfd758]74        // Why does this need a cast?
[b583113]75        throwResume (CoroutineCancelled(T) &)except;
[1c01c58]76
77        except->virtual_table->free( except );
78        free( desc->cancellation );
79        desc->cancellation = 0p;
80}
81
[23edb61]82// helper for popping from coroutine's ehm buffer
83inline nonlocal_exception * pop_ehm_head( coroutine$ * this ) {
84    lock( this->ehm_state.buffer_lock __cfaabi_dbg_ctx2 );
85    nonlocal_exception * nl_ex = pop_head( this->ehm_state.ehm_buffer );
86    unlock( this->ehm_state.buffer_lock );
87    return nl_ex;
88}
89
[6a3d2e7]90//-----------------------------------------------------------------------------
91// Global state variables
92
93// minimum feasible stack size in bytes
[290553a]94static const size_t MinStackSize = 1000;
[b2f6113]95extern size_t __page_size;                              // architecture pagesize HACK, should go in proper runtime singleton
[dd92fe9]96extern int __map_prot;
[b2f6113]97
98void __stack_prepare( __stack_info_t * this, size_t create_size );
[c18bf9e]99static void __stack_clean  ( __stack_info_t * this );
[6a3d2e7]100
101//-----------------------------------------------------------------------------
102// Coroutine ctors and dtors
[b2f6113]103void ?{}( __stack_info_t & this, void * storage, size_t storageSize ) {
104        this.storage   = (__stack_t *)storage;
105
106        // Did we get a piece of storage ?
107        if (this.storage || storageSize != 0) {
108                // We either got a piece of storage or the user asked for a specific size
109                // Immediately create the stack
110                // (This is slightly unintuitive that non-default sized coroutines create are eagerly created
111                // but it avoids that all coroutines carry an unnecessary size)
112                verify( storageSize != 0 );
113                __stack_prepare( &this, storageSize );
114        }
[6a3d2e7]115}
116
[b2f6113]117void ^?{}(__stack_info_t & this) {
[8c01e1b]118        bool userStack = ((intptr_t)this.storage & 0x1) != 0;
119        if ( ! userStack && this.storage ) {
[bfcf6b9]120                __stack_clean( &this );
[b2f6113]121        }
[6a3d2e7]122}
123
[c18bf9e]124void ?{}( coroutine$ & this, const char name[], void * storage, size_t storageSize ) libcfa_public with( this ) {
[524627e]125        (this.context){0p, 0p};
[b2f6113]126        (this.stack){storage, storageSize};
127        this.name = name;
128        state = Start;
[524627e]129        starter = 0p;
130        last = 0p;
131        cancellation = 0p;
[2fe64ba]132    ehm_state.ehm_buffer{};
133    ehm_state.buffer_lock{};
134    ehm_state.ehm_enabled = false;
[6a3d2e7]135}
136
[c18bf9e]137void ^?{}(coroutine$& this) libcfa_public {
[23edb61]138    // handle any leftover pending non-local exceptions
139    nonlocal_exception * nl_ex = pop_ehm_head( &this );
140    unsigned unhandled_ex = 0;
141   
142    // if any leftover exceptions handle
143    while ( nl_ex != 0p ){
144        unhandled_ex++;
145        free( nl_ex->the_exception );
146        free( nl_ex );
147        nl_ex = pop_ehm_head( &this );
148    }
149
150    #ifdef __CFA_DEBUG__
151    if ( unhandled_ex > 0 )
152        printf( "Warning: Coroutine %p exited with %u pending nonlocal exceptions.\n", &this, unhandled_ex );
153    #endif
154
[3623f9d]155        if(this.state != Halted && this.state != Start && this.state != Primed) {
[e84ab3d]156                coroutine$ * src = active_coroutine();
157                coroutine$ * dst = &this;
[b2f6113]158
159                struct _Unwind_Exception storage;
160                storage.exception_class = -1;
161                storage.exception_cleanup = _CtxCoroutine_UnwindCleanup;
162                this.cancellation = &storage;
163                this.last = src;
164
165                // not resuming self ?
166                if ( src == dst ) {
167                        abort( "Attempt by coroutine %.256s (%p) to terminate itself.\n", src->name, src );
168                }
169
[ac2b598]170                $ctx_switch( src, dst );
[b2f6113]171        }
[76e069f]172}
[6a3d2e7]173
174// Part of the Public API
175// Not inline since only ever called once per coroutine
[c3b9d639]176forall(T & | is_coroutine(T) | { EHM_DEFAULT_VTABLE(CoroutineCancelled(T)); })
[c18bf9e]177void prime(T& cor) libcfa_public {
[e84ab3d]178        coroutine$* this = get_coroutine(cor);
[b2f6113]179        assert(this->state == Start);
[6a3d2e7]180
[b2f6113]181        this->state = Primed;
182        resume(cor);
[6a3d2e7]183}
184
[c18bf9e]185static [void *, size_t] __stack_alloc( size_t storageSize ) {
[0030ada3]186        const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
[b2f6113]187        assert(__page_size != 0l);
188        size_t size = libCeiling( storageSize, 16 ) + stack_data_size;
[bfcf6b9]189        size = ceiling(size, __page_size);
[b2f6113]190
191        // If we are running debug, we also need to allocate a guardpage to catch stack overflows.
192        void * storage;
[97229d6]193        #if CFA_COROUTINE_USE_MMAP
194                storage = mmap(0p, size + __page_size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
195                if(storage == ((void*)-1)) {
196                        abort( "coroutine stack creation : internal error, mmap failure, error(%d) %s.", errno, strerror( errno ) );
197                }
198                if ( mprotect( storage, __page_size, PROT_NONE ) == -1 ) {
199                        abort( "coroutine stack creation : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
200                } // if
201                storage = (void *)(((intptr_t)storage) + __page_size);
202        #else
203                __cfaabi_dbg_debug_do(
204                        storage = memalign( __page_size, size + __page_size );
205                );
206                __cfaabi_dbg_no_debug_do(
207                        storage = (void*)malloc(size);
208                );
209
210                __cfaabi_dbg_debug_do(
211                        if ( mprotect( storage, __page_size, PROT_NONE ) == -1 ) {
212                                abort( "__stack_alloc : internal error, mprotect failure, error(%d) %s.", (int)errno, strerror( (int)errno ) );
213                        }
214                        storage = (void *)(((intptr_t)storage) + __page_size);
215                );
216        #endif
217        __cfaabi_dbg_print_safe("Kernel : Created stack %p of size %zu\n", storage, size);
[b2f6113]218
219        verify( ((intptr_t)storage & (libAlign() - 1)) == 0ul );
220        return [storage, size];
221}
[6a3d2e7]222
[c18bf9e]223static void __stack_clean  ( __stack_info_t * this ) {
[bfcf6b9]224        void * storage = this->storage->limit;
225
[97229d6]226        #if CFA_COROUTINE_USE_MMAP
[85ac70e8]227                size_t size = ((intptr_t)this->storage->base) - ((intptr_t)this->storage->limit) + sizeof(__stack_t);
[97229d6]228                storage = (void *)(((intptr_t)storage) - __page_size);
229                if(munmap(storage, size + __page_size) == -1) {
230                        abort( "coroutine stack destruction : internal error, munmap failure, error(%d) %s.", errno, strerror( errno ) );
231                }
232        #else
233                __cfaabi_dbg_debug_do(
234                        storage = (char*)(storage) - __page_size;
[dd92fe9]235                        if ( mprotect( storage, __page_size, __map_prot ) == -1 ) {
[97229d6]236                                abort( "(coStack_t *)%p.^?{}() : internal error, mprotect failure, error(%d) %s.", &this, errno, strerror( errno ) );
237                        }
238                );
239
240                free( storage );
241        #endif
242        __cfaabi_dbg_print_safe("Kernel : Deleting stack %p\n", storage);
[bfcf6b9]243}
244
[c18bf9e]245void __stack_prepare( __stack_info_t * this, size_t create_size ) libcfa_public {
[0030ada3]246        const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
[b2f6113]247        bool userStack;
248        void * storage;
249        size_t size;
250        if ( !this->storage ) {
251                userStack = false;
252                [storage, size] = __stack_alloc( create_size );
253        } else {
254                userStack = true;
[69a61d2]255                __cfaabi_dbg_print_safe("Kernel : stack obj %p using user stack %p(%zd bytes)\n", this, this->storage, (intptr_t)this->storage->limit - (intptr_t)this->storage->base);
[b2f6113]256
257                // The stack must be aligned, advance the pointer to the next align data
258                storage = (void*)libCeiling( (intptr_t)this->storage, libAlign());
259
260                // The size needs to be shrinked to fit all the extra data structure and be aligned
261                ptrdiff_t diff = (intptr_t)storage - (intptr_t)this->storage;
262                size = libFloor(create_size - stack_data_size - diff, libAlign());
263        } // if
[9b0c3ec5]264        assertf( size >= MinStackSize, "Stack size %zd provides less than minimum of %zd bytes for a stack.", size, MinStackSize );
[b2f6113]265
[bfcf6b9]266        this->storage = (__stack_t *)((intptr_t)storage + size - sizeof(__stack_t));
[b2f6113]267        this->storage->limit = storage;
[bfcf6b9]268        this->storage->base  = (void*)((intptr_t)storage + size - sizeof(__stack_t));
[1c01c58]269        this->storage->exception_context.top_resume = 0p;
270        this->storage->exception_context.current_exception = 0p;
[ffe2fad]271        __attribute__((may_alias)) intptr_t * istorage = (intptr_t*)&this->storage;
272        *istorage |= userStack ? 0x1 : 0x0;
[6a3d2e7]273}
274
[0c92c9f]275// We need to call suspend from invoke.c, so we expose this wrapper that
276// is not inline (We can't inline Cforall in C)
277extern "C" {
[e84ab3d]278        void __cfactx_cor_leave( struct coroutine$ * src ) {
279                coroutine$ * starter = src->cancellation != 0 ? src->last : src->starter;
[b2f6113]280
281                src->state = Halted;
282
283                assertf( starter != 0,
284                        "Attempt to suspend/leave coroutine \"%.256s\" (%p) that has never been resumed.\n"
285                        "Possible cause is a suspend executed in a member called by a coroutine user rather than by the coroutine main.",
286                        src->name, src );
287                assertf( starter->state != Halted,
288                        "Attempt by coroutine \"%.256s\" (%p) to suspend/leave back to terminated coroutine \"%.256s\" (%p).\n"
289                        "Possible cause is terminated coroutine's main routine has already returned.",
290                        src->name, src, starter->name, starter );
291
[ac2b598]292                $ctx_switch( src, starter );
[b2f6113]293        }
[09f357ec]294
[e84ab3d]295        struct coroutine$ * __cfactx_cor_finish(void) {
296                struct coroutine$ * cor = active_coroutine();
[09f357ec]297
[ab5baab]298                // get the active thread once
[e84ab3d]299                thread$ * athrd = active_thread();
[ab5baab]300
301                /* paranoid */ verify( athrd->corctx_flag );
302                athrd->corctx_flag = false;
303
[09f357ec]304                if(cor->state == Primed) {
[427854b]305                        __cfactx_suspend();
[09f357ec]306                }
307
308                cor->state = Active;
309
310                return cor;
311        }
[0c92c9f]312}
313
[2fe64ba]314
315////////////////////////////////////////////////////////////////////////////////////////////////////
316// non local ehm routines
317
[3318dff]318void defaultResumeAtHandler( exception_t * except ) {
319    __cfaehm_allocate_exception( except );
320    __cfaehm_begin_unwind( (void(*)(exception_t *))defaultTerminationHandler );
321}
322
[cce0807]323struct ehm_cleanup {
324        exception_t * ex;
325};
326
327void ^?{}( ehm_cleanup & this ) { free( this.ex ); }
328
[c34bb1f]329bool poll( coroutine$ * cor ) libcfa_public {
330    nonlocal_exception * nl_ex = pop_ehm_head( cor );
331
332    // if no exceptions return false
333    if ( nl_ex == 0p ) return false;
334   
335    // otherwise loop and throwResume all pending exceptions
336    while ( nl_ex != 0p ){
[cce0807]337                ehm_cleanup ex_holder{ nl_ex->the_exception };
[c34bb1f]338        free( nl_ex );
[cce0807]339        __cfaehm_throw_resume( ex_holder.ex , defaultResumeAtHandler );
[3318dff]340       
[c34bb1f]341        nl_ex = pop_ehm_head( cor );
342    }
343   
344    return true;
345}
346
347bool poll() libcfa_public { return poll( active_coroutine() ); }
[147a137]348void enable_ehm() libcfa_public { active_coroutine()->ehm_state.ehm_enabled = true; }
349void disable_ehm() libcfa_public { active_coroutine()->ehm_state.ehm_enabled = false; }
350bool checked_poll() libcfa_public { return active_coroutine()->ehm_state.ehm_enabled ? poll( active_coroutine() ) : false; }
[3318dff]351coroutine$ * resumer() libcfa_public { return active_coroutine()->last; }
[4269d1b]352coroutine$ * first_resumer() libcfa_public { return active_coroutine()->starter; }
[c34bb1f]353
[2fe64ba]354// user facing ehm operations
355forall(T & | is_coroutine(T)) {
356    // enable/disable non-local exceptions
357    void enable_ehm( T & cor ) libcfa_public { get_coroutine( cor )->ehm_state.ehm_enabled = true; }
358    void disable_ehm( T & cor ) libcfa_public { get_coroutine( cor )->ehm_state.ehm_enabled = false; }
359
360    // poll for non-local exceptions
[c34bb1f]361    bool poll( T & cor ) libcfa_public { return poll( get_coroutine( cor ) ); }
[2fe64ba]362
363    // poll iff nonlocal ehm is enabled
364    bool checked_poll( T & cor ) libcfa_public { return get_coroutine( cor )->ehm_state.ehm_enabled ? poll( cor ) : false; }
[c3e510b]365
366    coroutine$ * resumer( T & cor ) libcfa_public { return get_coroutine( cor )->last; }
[4269d1b]367    coroutine$ * first_resumer( T & cor ) libcfa_public { return get_coroutine( cor )->starter; }
[2fe64ba]368}
369
370// resume non local exception at receiver (i.e. enqueue in ehm buffer)
[3318dff]371forall(exceptT *, T & | ehm_resume_at( exceptT, T ))
[60f69f0]372void resumeAt( T & receiver, exceptT & ex ) libcfa_public {
[2fe64ba]373    coroutine$ * cor = get_coroutine( receiver );
374    nonlocal_exception * nl_ex = alloc();
[3318dff]375    exceptT * ex_copy = alloc();
376    memcpy( ex_copy, &ex, sizeof(exceptT) );
377    (*nl_ex){ (exception_t *)ex_copy };
[2fe64ba]378    lock( cor->ehm_state.buffer_lock __cfaabi_dbg_ctx2 );
379    append( cor->ehm_state.ehm_buffer, nl_ex );
380    unlock( cor->ehm_state.buffer_lock );
381}
382
[3318dff]383forall(exceptT * | { void $throwResume(exceptT &); })
[c3e510b]384void resumeAt( coroutine$ * receiver, exceptT & ex ) libcfa_public {
385    nonlocal_exception * nl_ex = alloc();
[3318dff]386    exceptT * ex_copy = alloc();
387    memcpy( ex_copy, &ex, sizeof(exceptT) );
388    (*nl_ex){ (exception_t *)ex_copy };
[c3e510b]389    lock( receiver->ehm_state.buffer_lock __cfaabi_dbg_ctx2 );
390    append( receiver->ehm_state.ehm_buffer, nl_ex );
391    unlock( receiver->ehm_state.buffer_lock );
392}
393
[6a3d2e7]394// Local Variables: //
395// mode: c //
396// tab-width: 4 //
[4aa2fb2]397// End: //
Note: See TracBrowser for help on using the repository browser.