From 4b0466f37bb5ee1d63144fb1431519ebb7ceeac7 Mon Sep 17 00:00:00 2001 From: Justin Ethier Date: Mon, 19 Nov 2018 17:09:17 -0500 Subject: [PATCH] Use alloca for any allocations with let/local-vars This prevents situations where local variables are allocated within local scope blocks and then are assigned to pointers. This is necessary as those locals are not guaranteed to remain on the stack once the block ends, so the pointer can easily point to random memory, leading to GC corruption and/or undefined behavior. --- scheme/cyclone/cgen.sld | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/scheme/cyclone/cgen.sld b/scheme/cyclone/cgen.sld index 5b9f9f3f..a3c40b0b 100644 --- a/scheme/cyclone/cgen.sld +++ b/scheme/cyclone/cgen.sld @@ -652,11 +652,17 @@ (and (> len 0) (equal? end (substring str (- len 1) len))))) +(define *use-alloca* #f) + +(define (set-use-alloca! v) + (set! *use-alloca* v)) + ;; Use alloca() for stack allocations? (define (alloca? ast-id) - (let ((adbf:fnc (adb:get/default ast-id #f))) - (and adbf:fnc - (adbf:calls-self? adbf:fnc)))) + (or *use-alloca* + (let ((adbf:fnc (adb:get/default ast-id #f))) + (and adbf:fnc + (adbf:calls-self? adbf:fnc))))) ;; c-compile-prim : prim-exp -> string -> string (define (c-compile-prim p cont ast-id) @@ -1194,9 +1200,11 @@ (body (caddr exp)) (vexps (foldr (lambda (var/val acc) + (set-use-alloca! #t) ;; Force alloca to ensure safe c stack allocs ;; Join expressions; based on c:append (let ((cp1 (c-compile-exp (cadr var/val) append-preamble cont ast-id trace cps?)) (cp2 acc)) + (set-use-alloca! #f) ;; Revert flag (c-code/vars (let ((cp1-body (c:body cp1))) (string-append cp1-body ";" (c:body cp2)))