Subject: bug#16060: Attempt to mutate a literal pair results in segfault (master)

From: Jean Abou Samra <[email-masked]>
Date: Thu, 20 Jul 2023 00:13:47 +0200

This is still happening with Guile 3.0, but only at -O2, not at -O1.

$ cat x.scm 
(set-car! '(1 . 2) 3)

$ guild3.0 compile -O1 x.scm
wrote `/home/jean/.cache/guile/ccache/3.0-LE-8-4.5/home/jean/tmp/x.scm.go'

$ guile3.0 x.scm
Backtrace:
In ice-9/boot-9.scm:
  1752:10  6 (with-exception-handler _ _ #:unwind? _ # _)
In unknown file:
           5 (apply-smob/0 #<thunk 7f72df6e0f60>)
In ice-9/boot-9.scm:
    724:2  4 (call-with-prompt ("prompt") #<procedure 7f72df6e7ee0 …> …)
In ice-9/eval.scm:
    619:8  3 (_ #(#(#<directory (guile-user) 7f72df6d9c80>)))
In ice-9/boot-9.scm:
   2835:4  2 (save-module-excursion #<procedure 7f72df6c7150 at ice-…>)
  4380:12  1 (_)
In x.scm:
      1:0  0 (_)

x.scm:1:0: In procedure set-car!: Wrong type argument in position 1 (expecting
mutable pair): (1 . 2)

$ guild3.0 compile -O2 x.scm
wrote `/home/jean/.cache/guile/ccache/3.0-LE-8-4.5/home/jean/tmp/x.scm.go'

$ guile3.0 x.scm
Segmentation fault (core dumped)

I found that module/language/cps/lower-primcalls.scm contains:

;; precondition: pair is mutable pair
(define-primcall-lowerer (set-car! cps k src #f (pair val))
  (with-cps cps
    (build-term
      ($continue k src
        ($primcall 'scm-set!/immediate '(pair . 0) (pair val))))))

which bypasses the check that the scm_set_car_x and scm_set_cdr_x
functions do.

I wonder if instead of checking the pair beforehand, Guile could just
do the set-c(a|d)r! anyway. Could the problem with mmapped bytecode
just be solved by adding PROT_WRITE to the mmap flags? (Or are there
maybe thread-safety problems?)