From cc1cbe64a5953004c80b0da3026748ee3061bca0 Mon Sep 17 00:00:00 2001 From: Xavier Del Campo Romero Date: Sat, 31 Oct 2026 13:52:42 +0100 Subject: Use read-only references for complex types This fixes a double-free error in constructs such as: types mystruct struct dummy int end myalias alias pointer to mystruct --- src/prc1/parse.h | 11 +++++++++-- src/prc1/sym.c | 2 +- src/prc1/type.c | 33 ++++++++++++--------------------- 3 files changed, 22 insertions(+), 24 deletions(-) diff --git a/src/prc1/parse.h b/src/prc1/parse.h index 8b61d78..f0ae691 100644 --- a/src/prc1/parse.h +++ b/src/prc1/parse.h @@ -52,8 +52,15 @@ struct type enum ttype {U, S, C, P, T, PTR, ARY, BUILTIN} type; const struct tk *tk; size_t sz, align; - int sign; - struct type *child, *next; + int sign, readonly; + + union + { + const struct type *ro; + struct type *rw; + } child; + + struct type *next; union { diff --git a/src/prc1/sym.c b/src/prc1/sym.c index 3ba2937..e63e680 100644 --- a/src/prc1/sym.c +++ b/src/prc1/sym.c @@ -381,7 +381,7 @@ static const struct type *genlittype(struct prv *p) { .type = ARY, .u.ary.etc = 1, - .child = bytedup + .child.rw = bytedup }; if (!(ret = type_insert(p, t))) diff --git a/src/prc1/type.c b/src/prc1/type.c index cdd8f72..fbb332b 100644 --- a/src/prc1/type.c +++ b/src/prc1/type.c @@ -82,8 +82,8 @@ void type_lfree(struct type *t) { if (t) { - if (t->child) - type_lfree(t->child); + if (t->child.rw && !t->readonly) + type_lfree(t->child.rw); type_free(t); } @@ -154,7 +154,7 @@ char *type_name(const struct type *t) return NULL; } - t = t->child; + t = t->child.ro; } return ret; @@ -200,10 +200,10 @@ static void queue(struct prv *p, struct type *t) p->t = t; else { - while (tt->child) - tt = tt->child; + while (tt->child.rw) + tt = tt->child.rw; - tt->child = t; + tt->child.rw = t; } p->stk = p->tk; @@ -343,7 +343,7 @@ static int aryeq(const struct type *a, const struct type *b) static int eq(const struct type *a, const struct type *b) { - for (; a && b; a = a->child, b = b->child) + for (; a && b; a = a->child.ro, b = b->child.ro) if (a->type != b->type) return 0; else if (a->type == ARY && !aryeq(a, b)) @@ -391,26 +391,17 @@ static int t(const struct lex *l, struct prv *p) } else if (tt) { - struct type *nt = malloc(sizeof *nt); + while (tt->child.rw) + tt = tt->child.rw; - if (!nt) - { - perror("malloc(3)"); - return -1; - } - - *nt = *t; - - while (tt->child) - tt = tt->child; - - tt->child = nt; + tt->child.ro = t; + tt->readonly = 1; tt = p->t; /* array size still undecided */ if (tt->type == ARY && !tt->sz) { - tt->sz = tt->u.ary.n * nt->sz; + tt->sz = tt->u.ary.n * t->sz; tt->align = t->align; } -- cgit v1.2.3