commit 2991442aef1cf020ffde43673433ee97ef322a53 from: Russ Cox date: Tue Dec 15 05:06:03 2020 UTC libthread: fix use after free of first thread in each proc This was causing sporadic but frequent crashes at startup in 9pserve on the new M1 Macs, correctly diagnosing a use-after-free. commit - a012d174336358f997ddcb0099c0b01499b053e4 commit + 2991442aef1cf020ffde43673433ee97ef322a53 blob - 902942d9afcb69204dc32545c3524a28eb424f9a blob + 65e651949b2fe0e783ab745f5f11f70ad11b4d39 --- src/libthread/thread.c +++ src/libthread/thread.c @@ -411,7 +411,14 @@ Top: p->nthread--; /*print("nthread %d\n", p->nthread); */ _threadstkfree(t->stk, t->stksize); - free(t); + /* + * Cannot free p->thread0 yet: it is used for the + * context switches back to the scheduler. + * Instead, we will free it at the end of this function. + * But all the other threads can be freed now. + */ + if(t != p->thread0) + free(t); } for(;;){ @@ -490,6 +497,7 @@ Out: unlock(&threadnproclock); unlock(&p->lock); _threadsetproc(nil); + free(p->thread0); free(p); _threadpexit(); }