summaryrefslogtreecommitdiff
path: root/module/ice-9/sandbox.scm
blob: 601485ccecae52be860b2ac4ffe2daca6011c44c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
;;; Sandboxed evaluation of Scheme code

;;; Copyright (C) 2017, 2018 Free Software Foundation, Inc.

;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;; 
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;;; Lesser General Public License for more details.
;;;; 
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

;;; Commentary:
;;; 
;;; Code:

(define-module (ice-9 sandbox)
  #:use-module (ice-9 match)
  #:use-module ((ice-9 threads) #:select (current-thread))
  #:use-module (system vm vm)
  #:export (call-with-time-limit
            call-with-allocation-limit
            call-with-time-and-allocation-limits

            eval-in-sandbox
            make-sandbox-module

            alist-bindings
            array-bindings
            bit-bindings
            bitvector-bindings
            char-bindings
            char-set-bindings
            clock-bindings
            core-bindings
            error-bindings
            fluid-bindings
            hash-bindings
            iteration-bindings
            keyword-bindings
            list-bindings
            macro-bindings
            nil-bindings
            number-bindings
            pair-bindings
            predicate-bindings
            procedure-bindings
            promise-bindings
            prompt-bindings
            regexp-bindings
            sort-bindings
            srfi-4-bindings
            string-bindings
            symbol-bindings
            unspecified-bindings
            variable-bindings
            vector-bindings
            version-bindings

            mutating-alist-bindings
            mutating-array-bindings
            mutating-bitvector-bindings
            mutating-fluid-bindings
            mutating-hash-bindings
            mutating-list-bindings
            mutating-pair-bindings
            mutating-sort-bindings
            mutating-srfi-4-bindings
            mutating-string-bindings
            mutating-variable-bindings
            mutating-vector-bindings

            all-pure-bindings
            all-pure-and-impure-bindings))


(define (call-with-time-limit limit thunk limit-reached)
  "Call @var{thunk}, but cancel it if @var{limit} seconds of wall-clock
time have elapsed.  If the computation is cancelled, call
@var{limit-reached} in tail position.  @var{thunk} must not disable
interrupts or prevent an abort via a @code{dynamic-wind} unwind
handler."
  ;; FIXME: use separate thread instead of sigalrm.  If rounded limit is
  ;; <= 0, make it 1 usec to signal immediately.
  (let ((limit-usecs (max (inexact->exact (round (* limit 1e6))) 1))
        (prev-sigalarm-handler #f)
        (tag (make-prompt-tag)))
    (call-with-prompt tag
      (lambda ()
        (dynamic-wind
          (lambda ()
            (set! prev-sigalarm-handler
              (sigaction SIGALRM (lambda (sig)
                                   ;; If signal handling is delayed
                                   ;; until after prompt, no worries;
                                   ;; the success path won the race.
                                   (false-if-exception
                                    (abort-to-prompt tag)))))
            (setitimer ITIMER_REAL 0 0 0 limit-usecs))
          thunk
          (lambda ()
            (setitimer ITIMER_REAL 0 0 0 0)
            (match prev-sigalarm-handler
              ((handler . flags)
               (sigaction SIGALRM handler flags))))))
      (lambda (k)
        (limit-reached)))))

(define (call-with-allocation-limit limit thunk limit-reached)
  "Call @var{thunk}, but cancel it if @var{limit} bytes have been
allocated.  If the computation is cancelled, call @var{limit-reached} in
tail position.  @var{thunk} must not disable interrupts or prevent an
abort via a @code{dynamic-wind} unwind handler.

This limit applies to both stack and heap allocation.  The computation
will not be aborted before @var{limit} bytes have been allocated, but
for the heap allocation limit, the check may be postponed until the next
garbage collection.

Note that as a current shortcoming, the heap size limit applies to all
threads; concurrent allocation by other unrelated threads counts towards
the allocation limit."
  (define (bytes-allocated) (assq-ref (gc-stats) 'heap-total-allocated))
  (let ((zero (bytes-allocated))
        (tag (make-prompt-tag))
        (thread (current-thread)))
    (define (check-allocation)
      (when (< limit (- (bytes-allocated) zero))
        (system-async-mark (lambda ()
                             (false-if-exception (abort-to-prompt tag)))
                           thread)))
    (call-with-prompt tag
      (lambda ()
        (dynamic-wind
          (lambda ()
            (add-hook! after-gc-hook check-allocation))
          (lambda ()
            (call-with-stack-overflow-handler
             ;; The limit is in "words", which used to be 4 or 8 but now
             ;; is always 8 bytes.
             (max (floor/ limit 8) 1)
             thunk
             (lambda () (abort-to-prompt tag))))
          (lambda ()
            (remove-hook! after-gc-hook check-allocation))))
      (lambda (k)
        (limit-reached)))))

(define (call-with-time-and-allocation-limits time-limit allocation-limit
                                              thunk)
  "Invoke @var{thunk} in a dynamic extent in which its execution is
limited to @var{time-limit} seconds of wall-clock time, and its
allocation to @var{allocation-limit} bytes.  @var{thunk} must not
disable interrupts or prevent an abort via a @code{dynamic-wind} unwind
handler.

If successful, return all values produced by invoking @var{thunk}.  Any
uncaught exception thrown by the thunk will propagate out.  If the time
or allocation limit is exceeded, an exception will be thrown to the
@code{limit-exceeded} key."
  (call-with-time-limit
   time-limit
   (lambda ()
     (call-with-allocation-limit
      allocation-limit
      thunk
      (lambda ()
        (scm-error 'limit-exceeded "with-resource-limits"
                   "Allocation limit exceeded" '() #f))))
   (lambda ()
     (scm-error 'limit-exceeded "with-resource-limits"
                "Time limit exceeded" '() #f))))

(define (sever-module! m)
  "Remove @var{m} from its container module."
  (match (module-name m)
    ((head ... tail)
     (let ((parent (resolve-module head #f)))
       (unless (eq? m (module-ref-submodule parent tail))
         (error "can't sever module?"))
       (hashq-remove! (module-submodules parent) tail)))))

;; bindings := module-binding-list ...
;; module-binding-list := interface-name import ...
;; import := name | (exported-name . imported-name)
;; name := symbol
(define (make-sandbox-module bindings)
  "Return a fresh module that only contains @var{bindings}.

The @var{bindings} should be given as a list of import sets.  One import
set is a list whose car names an interface, like @code{(ice-9 q)}, and
whose cdr is a list of imports.  An import is either a bare symbol or a
pair of @code{(@var{out} . @var{in})}, where @var{out} and @var{in} are
both symbols and denote the name under which a binding is exported from
the module, and the name under which to make the binding available,
respectively."
  (let ((m (make-fresh-user-module)))
    (purify-module! m)
    (module-use-interfaces! m
                            (map (match-lambda
                                   ((mod-name . bindings)
                                    (resolve-interface mod-name
                                                       #:select bindings)))
                                 bindings))
    m))

(define* (eval-in-sandbox exp #:key
                          (time-limit 0.1)
                          (allocation-limit #e10e6)
                          (bindings all-pure-bindings)
                          (module (make-sandbox-module bindings))
                          (sever-module? #t))
  "Evaluate the Scheme expression @var{exp} within an isolated
\"sandbox\".  Limit its execution to @var{time-limit} seconds of
wall-clock time, and limit its allocation to @var{allocation-limit}
bytes.

The evaluation will occur in @var{module}, which defaults to the result
of calling @code{make-sandbox-module} on @var{bindings}, which itself
defaults to @code{all-pure-bindings}.  This is the core of the
sandbox: creating a scope for the expression that is @dfn{safe}.

A safe sandbox module has two characteristics.  Firstly, it will not
allow the expression being evaluated to avoid being cancelled due to
time or allocation limits.  This ensures that the expression terminates
in a timely fashion.

Secondly, a safe sandbox module will prevent the evaluation from
receiving information from previous evaluations, or from affecting
future evaluations.  All combinations of binding sets exported by
@code{(ice-9 sandbox)} form safe sandbox modules.

The @var{bindings} should be given as a list of import sets.  One import
set is a list whose car names an interface, like @code{(ice-9 q)}, and
whose cdr is a list of imports.  An import is either a bare symbol or a
pair of @code{(@var{out} . @var{in})}, where @var{out} and @var{in} are
both symbols and denote the name under which a binding is exported from
the module, and the name under which to make the binding available,
respectively.  Note that @var{bindings} is only used as an input to the
default initializer for the @var{module} argument; if you pass
@code{#:module}, @var{bindings} is unused.  If @var{sever-module?} is
true (the default), the module will be unlinked from the global module
tree after the evaluation returns, to allow @var{mod} to be
garbage-collected.

If successful, return all values produced by @var{exp}.  Any uncaught
exception thrown by the expression will propagate out.  If the time or
allocation limit is exceeded, an exception will be thrown to the
@code{limit-exceeded} key."
  (dynamic-wind
    (lambda () #t)
    (lambda ()
      (call-with-time-and-allocation-limits
       time-limit allocation-limit
       (lambda ()
         (eval exp module))))
    (lambda () (when sever-module? (sever-module! module)))))


;; An evaluation-sandboxing facility is safe if:
;;
;;  (1) every evaluation will terminate in a timely manner
;;
;;  (2) no evaluation can affect future evaluations
;;
;; For (1), we impose a user-controllable time limit on the evaluation,
;; in wall-clock time.  When that limit is reached, Guile schedules an
;; asynchronous interrupt in the sandbox that aborts the computation.
;; For this to work, the sandboxed evaluation must not disable
;; interrupts, and it must not prevent timely aborts via malicious "out"
;; guards in dynamic-wind thunks.
;;
;; The sandbox also has an allocation limit that uses a similar cancel
;; mechanism, but this limit is less precise as it only runs at
;; garbage-collection time.
;;
;; The sandbox sets the allocation limit as the stack limit as well.
;;
;; For (2), the only way an evaluation can affect future evaluations is
;; if it causes a side-effect outside its sandbox.  That side effect
;; could change the way the host or future sandboxed evaluations
;; operate, or it could leak information to future evaluations.
;;
;; One means of information leakage would be the file system.  Although
;; one can imagine "safe" ways to access a file system, in practice we
;; just prevent all access to this and other operating system facilities
;; by not exposing the Guile primitives that access the file system,
;; connect to networking hosts, etc.  If we chose our set of bindings
;; correctly and it is impossible to access host values other than those
;; given to the evaluation, then we have succeeded in granting only a
;; limited set of capabilities to the guest.
;;
;; To prevent information leakage we also limit other information about
;; the host, like its hostname or the Guile build information.
;;
;; The guest must also not have the capability to mutate a location used
;; by the host or by future sandboxed evaluations.  Either you expose no
;; primitives to the evaluation that can mutate locations, or you expose
;; no mutable locations.  In this sandbox we opt for a combination of
;; the two, though the selection of bindings is up to the user.  "set!"
;; is always excluded, as Guile doesn't have a nice way to prevent set!
;; on imported bindings.  But variable-set! is included, as no set of
;; bindings from this module includes a variable or a capability to a
;; variable.  It's possible though to build sandbox modules with no
;; mutating primitives.  As far as we know, all possible combinations of
;; the binding sets listed below are safe.
;;
(define core-bindings
  '(((guile)
     else => _ ...
     and
     begin
     apply
     call-with-values
     values
     case
     case-lambda
     case-lambda*
     cond
     define
     define*
     define-values
     do
     if
     lambda
     lambda*
     let
     let*
     letrec
     letrec*
     or
     quasiquote
     quote
     ;; Can't allow mutation to globals.
     ;; set!
     unless
     unquote
     unquote-splicing
     when
     while
     λ)))

(define macro-bindings
  '(((guile)
     bound-identifier=?
     ;; Although these have "current" in their name, they are lexically
     ;; scoped, not dynamically scoped.
     current-filename
     current-source-location
     datum->syntax
     define-macro
     define-syntax
     define-syntax-parameter
     define-syntax-rule
     defmacro
     free-identifier=?
     generate-temporaries
     gensym
     identifier-syntax
     identifier?
     let-syntax
     letrec-syntax
     macroexpand
     macroexpanded?
     quasisyntax
     start-stack
     syntax
     syntax->datum
     syntax-case
     syntax-error
     syntax-parameterize
     syntax-rules
     syntax-source
     syntax-violation
     unsyntax
     unsyntax-splicing
     with-ellipsis
     with-syntax
     make-variable-transformer)))

(define iteration-bindings
  '(((guile)
     compose
     for-each
     identity
     iota
     map
     map-in-order
     const
     noop)))

(define clock-bindings
  '(((guile)
     get-internal-real-time
     internal-time-units-per-second
     sleep
     usleep)))

(define procedure-bindings
  '(((guile)
     procedure-documentation
     procedure-minimum-arity
     procedure-name
     procedure?
     thunk?)))

(define version-bindings
  '(((guile)
     effective-version
     major-version
     micro-version
     minor-version
     version
     version-matches?)))

(define nil-bindings
  '(((guile)
     nil?)))

(define unspecified-bindings
  '(((guile)
     unspecified?
     *unspecified*)))

(define predicate-bindings
  '(((guile)
     ->bool
     and-map
     and=>
     boolean?
     eq?
     equal?
     eqv?
     negate
     not
     or-map)))

;; The current ports (current-input-port et al) are dynamically scoped,
;; which is a footgun from a sandboxing perspective.  It's too easy for
;; a procedure that is the result of a sandboxed evaluation to be later
;; invoked in a different context and thereby be implicitly granted
;; capabilities to whatever port is then current.  This is compounded by
;; the fact that most Scheme i/o primitives allow the port to be omitted
;; and thereby default to whatever's current.  For now, sadly, we avoid
;; exposing any i/o primitive to the sandbox.
#;
(define i/o-bindings
  '(((guile)
     display
     eof-object?
     force-output
     format
     make-soft-port
     newline
     read
     simple-format
     write
     write-char)
    ((ice-9 ports)
     %make-void-port
     char-ready?
     ;; Note that these are mutable parameters.
     current-error-port
     current-input-port
     current-output-port
     current-warning-port
     drain-input
     eof-object?
     file-position
     force-output
     ftell
     input-port?
     output-port?
     peek-char
     port-closed?
     port-column
     port-conversion-strategy
     port-encoding
     port-filename
     port-line
     port-mode
     port?
     read-char
     the-eof-object
     ;; We don't provide open-output-string because it needs
     ;; get-output-string, and get-output-string provides a generic
     ;; capability on any output string port.  For consistency then we
     ;; don't provide open-input-string either; call-with-input-string
     ;; is sufficient.
     call-with-input-string
     call-with-output-string
     with-error-to-port
     with-error-to-string
     with-input-from-port
     with-input-from-string
     with-output-to-port
     with-output-to-string)))

;; If two evaluations are called with the same input port, unread-char
;; and unread-string can use a port as a mutable channel to pass
;; information from one to the other.
#;
(define mutating-i/o-bindings
  '(((guile)
     set-port-encoding!)
    ((ice-9 ports)
     close-input-port
     close-output-port
     close-port
     file-set-position
     seek
     set-port-column!
     set-port-conversion-strategy!
     set-port-encoding!
     set-port-filename!
     set-port-line!
     setvbuf
     unread-char
     unread-string)))

(define error-bindings
  '(((guile)
     error
     throw
     with-throw-handler
     catch
     ;; false-if-exception can cause i/o if the #:warning arg is passed.
     ;; false-if-exception

     ;; See notes on i/o-bindings.
     ;; peek
     ;; pk
     ;; print-exception
     ;; warn
     strerror
     scm-error
     )))

;; FIXME: Currently we can't expose anything that works on the current
;; module to the sandbox.  It could be that the sandboxed evaluation
;; returns a procedure, and that procedure may later be invoked in a
;; different context with a different current-module and it is unlikely
;; that the later caller will consider themselves as granting a
;; capability on whatever module is then current.  Likewise export (and
;; by extension, define-public and the like) also operate on the current
;; module.
;;
;; It could be that we could expose a statically scoped eval to the
;; sandbox.
#;
(define eval-bindings
  '(((guile)
     current-module
     module-name
     module?
     define-once
     define-private
     define-public
     defined?
     export
     defmacro-public
     ;; FIXME: single-arg eval?
     eval
     primitive-eval
     eval-string
     self-evaluating?
     ;; Can we?
     set-current-module)))

(define sort-bindings
  '(((guile)
     sort
     sorted?
     stable-sort
     sort-list)))

;; These can only form part of a safe binding set if no mutable pair or
;; vector is exposed to the sandbox.
(define mutating-sort-bindings
  '(((guile)
     sort!
     stable-sort!
     sort-list!
     restricted-vector-sort!)))

(define regexp-bindings
  '(((guile)
     make-regexp
     regexp-exec
     regexp/basic
     regexp/extended
     regexp/icase
     regexp/newline
     regexp/notbol
     regexp/noteol
     regexp?)))

(define alist-bindings
  '(((guile)
     acons
     assoc
     assoc-ref
     assq
     assq-ref
     assv
     assv-ref
     sloppy-assoc
     sloppy-assq
     sloppy-assv)))

;; These can only form part of a safe binding set if no mutable pair
;; is exposed to the sandbox.  Unfortunately all charsets in Guile are
;; mutable, currently, including the built-in charsets, so we can't
;; expose these primitives.
(define mutating-alist-bindings
  '(((guile)
     assoc-remove!
     assoc-set!
     assq-remove!
     assq-set!
     assv-remove!
     assv-set!)))

(define number-bindings
  '(((guile)
     *
     +
     -
     /
     1+
     1-
     <
     <=
     =
     >
     >=
     abs
     acos
     acosh
     angle
     asin
     asinh
     atan
     atanh
     ceiling
     ceiling-quotient
     ceiling-remainder
     ceiling/
     centered-quotient
     centered-remainder
     centered/
     complex?
     cos
     cosh
     denominator
     euclidean-quotient
     euclidean-remainder
     euclidean/
     even?
     exact->inexact
     exact-integer-sqrt
     exact-integer?
     exact?
     exp
     expt
     finite?
     floor
     floor-quotient
     floor-remainder
     floor/
     gcd
     imag-part
     inf
     inf?
     integer-expt
     integer-length
     integer?
     lcm
     log
     log10
     magnitude
     make-polar
     make-rectangular
     max
     min
     modulo
     modulo-expt
     most-negative-fixnum
     most-positive-fixnum
     nan
     nan?
     negative?
     numerator
     odd?
     positive?
     quotient
     rational?
     rationalize
     real-part
     real?
     remainder
     round
     round-quotient
     round-remainder
     round/
     sin
     sinh
     sqrt
     tan
     tanh
     truncate
     truncate-quotient
     truncate-remainder
     truncate/
     zero?
     number?
     number->string
     string->number)))

(define char-set-bindings
  '(((guile)
     ->char-set
     char-set
     char-set->list
     char-set->string
     char-set-adjoin
     char-set-any
     char-set-complement
     char-set-contains?
     char-set-copy
     char-set-count
     char-set-cursor
     char-set-cursor-next
     char-set-delete
     char-set-diff+intersection
     char-set-difference
     char-set-every
     char-set-filter
     char-set-fold
     char-set-for-each
     char-set-hash
     char-set-intersection
     char-set-map
     char-set-ref
     char-set-size
     char-set-unfold
     char-set-union
     char-set-xor
     char-set:ascii
     char-set:blank
     char-set:designated
     char-set:digit
     char-set:empty
     char-set:full
     char-set:graphic
     char-set:hex-digit
     char-set:iso-control
     char-set:letter
     char-set:letter+digit
     char-set:lower-case
     char-set:printing
     char-set:punctuation
     char-set:symbol
     char-set:title-case
     char-set:upper-case
     char-set:whitespace
     char-set<=
     char-set=
     char-set?
     end-of-char-set?
     list->char-set
     string->char-set
     ucs-range->char-set)))

;; These can only form part of a safe binding set if no mutable char-set
;; is exposed to the sandbox.  Unfortunately all charsets in Guile are
;; mutable, currently, including the built-in charsets, so we can't
;; expose these primitives.
#;
(define mutating-char-set-bindings
  '(((guile)
     char-set-adjoin!
     char-set-complement!
     char-set-delete!
     char-set-diff+intersection!
     char-set-difference!
     char-set-filter!
     char-set-intersection!
     char-set-unfold!
     char-set-union!
     char-set-xor!
     list->char-set!
     string->char-set!
     ucs-range->char-set!)))

(define array-bindings
  '(((guile)
     array->list
     array-cell-ref
     array-contents
     array-dimensions
     array-equal?
     array-for-each
     array-in-bounds?
     array-length
     array-rank
     array-ref
     array-shape
     array-slice
     array-slice-for-each
     array-slice-for-each-in-order
     array-type
     array-type-code
     array?
     list->array
     list->typed-array
     make-array
     make-shared-array
     make-typed-array
     shared-array-increments
     shared-array-offset
     shared-array-root
     transpose-array
     typed-array?)))

;; These can only form part of a safe binding set if no mutable vector,
;; bitvector, bytevector, srfi-4 vector, or array is exposed to the
;; sandbox.
(define mutating-array-bindings
  '(((guile)
     array-cell-set!
     array-copy!
     array-copy-in-order!
     array-fill!
     array-index-map!
     array-map!
     array-map-in-order!
     array-set!)))

(define hash-bindings
  '(((guile)
     doubly-weak-hash-table?
     hash
     hash-count
     hash-fold
     hash-for-each
     hash-for-each-handle
     hash-get-handle
     hash-map->list
     hash-ref
     hash-table?
     hashq
     hashq-get-handle
     hashq-ref
     hashv
     hashv-get-handle
     hashv-ref
     hashx-get-handle
     hashx-ref
     make-doubly-weak-hash-table
     make-hash-table
     make-weak-key-hash-table
     make-weak-value-hash-table
     weak-key-hash-table?
     weak-value-hash-table?)))

;; These can only form part of a safe binding set if no hash table is
;; exposed to the sandbox.
(define mutating-hash-bindings
  '(((guile)
     hash-clear!
     hash-create-handle!
     hash-remove!
     hash-set!
     hashq-create-handle!
     hashq-remove!
     hashq-set!
     hashv-create-handle!
     hashv-remove!
     hashv-set!
     hashx-create-handle!
     hashx-remove!
     hashx-set!)))

(define variable-bindings
  '(((guile)
     make-undefined-variable
     make-variable
     variable-bound?
     variable-ref
     variable?)))

;; These can only form part of a safe binding set if no mutable variable
;; is exposed to the sandbox; this applies particularly to variables
;; that are module bindings.
(define mutating-variable-bindings
  '(((guile)
     variable-set!
     variable-unset!)))

(define string-bindings
  '(((guile)
     absolute-file-name?
     file-name-separator-string
     file-name-separator?
     in-vicinity
     basename
     dirname

     list->string
     make-string
     object->string
     reverse-list->string
     string
     string->list
     string-any
     string-any-c-code
     string-append
     string-append/shared
     string-capitalize
     string-ci<
     string-ci<=
     string-ci<=?
     string-ci<>
     string-ci<?
     string-ci=
     string-ci=?
     string-ci>
     string-ci>=
     string-ci>=?
     string-ci>?
     string-compare
     string-compare-ci
     string-concatenate
     string-concatenate-reverse
     string-concatenate-reverse/shared
     string-concatenate/shared
     string-contains
     string-contains-ci
     string-copy
     string-count
     string-delete
     string-downcase
     string-drop
     string-drop-right
     string-every
     string-every-c-code
     string-filter
     string-fold
     string-fold-right
     string-for-each
     string-for-each-index
     string-hash
     string-hash-ci
     string-index
     string-index-right
     string-join
     string-length
     string-map
     string-normalize-nfc
     string-normalize-nfd
     string-normalize-nfkc
     string-normalize-nfkd
     string-null?
     string-pad
     string-pad-right
     string-prefix-ci?
     string-prefix-length
     string-prefix-length-ci
     string-prefix?
     string-ref
     string-replace
     string-reverse
     string-rindex
     string-skip
     string-skip-right
     string-split
     string-suffix-ci?
     string-suffix-length
     string-suffix-length-ci
     string-suffix?
     string-tabulate
     string-take
     string-take-right
     string-titlecase
     string-tokenize
     string-trim
     string-trim-both
     string-trim-right
     string-unfold
     string-unfold-right
     string-upcase
     string-utf8-length
     string<
     string<=
     string<=?
     string<>
     string<?
     string=
     string=?
     string>
     string>=
     string>=?
     string>?
     string?
     substring
     substring/copy
     substring/read-only
     substring/shared
     xsubstring)))

;; These can only form part of a safe binding set if no mutable string
;; is exposed to the sandbox.
(define mutating-string-bindings
  '(((guile)
     string-capitalize!
     string-copy!
     string-downcase!
     string-fill!
     string-map!
     string-reverse!
     string-set!
     string-titlecase!
     string-upcase!
     string-xcopy!
     substring-fill!
     substring-move!)))

(define symbol-bindings
  '(((guile)
     string->symbol
     string-ci->symbol
     symbol->string
     list->symbol
     make-symbol
     symbol
     symbol-append
     symbol-hash
     symbol-interned?
     symbol?)))

(define keyword-bindings
  '(((guile)
     keyword?
     keyword->symbol
     symbol->keyword)))

;; These can only form part of a safe binding set if no valid prompt tag
;; is ever exposed to the sandbox, or can be constructed by the sandbox.
(define prompt-bindings
  '(((guile)
     abort-to-prompt
     abort-to-prompt*
     call-with-prompt
     make-prompt-tag)))

(define bit-bindings
  '(((guile)
     ash
     round-ash
     logand
     logcount
     logior
     lognot
     logtest
     logxor
     logbit?)))

(define bitvector-bindings
  '(((guile)
     bitvector-count
     bitvector-position
     bitvector-count-bits
     bit-extract
     bitvector
     bitvector->list
     bitvector-length
     bitvector-bit-set?
     bitvector-bit-clear?
     bitvector?
     list->bitvector
     make-bitvector)))

;; These can only form part of a safe binding set if no mutable
;; bitvector is exposed to the sandbox.
(define mutating-bitvector-bindings
  '(((guile)
     bitvector-clear-bit!
     bitvector-clear-bits!
     bitvector-set-all-bits!
     bitvector-clear-all-bits!
     bitvector-flip-all-bits!
     bitvector-set-bit!
     bitvector-set-bits!)))

(define fluid-bindings
  '(((guile)
     fluid-bound?
     fluid-ref
     ;; fluid-ref* could escape the sandbox and is not allowed.
     fluid-thread-local?
     fluid?
     make-fluid
     make-thread-local-fluid
     make-unbound-fluid
     with-fluid*
     with-fluids
     with-fluids*
     make-parameter
     parameter?
     parameterize)))

;; These can only form part of a safe binding set if no fluid is
;; directly exposed to the sandbox.
(define mutating-fluid-bindings
  '(((guile)
     fluid-set!
     fluid-unset!
     fluid->parameter)))

(define char-bindings
  '(((guile)
     char-alphabetic?
     char-ci<=?
     char-ci<?
     char-ci=?
     char-ci>=?
     char-ci>?
     char-downcase
     char-general-category
     char-is-both?
     char-lower-case?
     char-numeric?
     char-titlecase
     char-upcase
     char-upper-case?
     char-whitespace?
     char<=?
     char<?
     char=?
     char>=?
     char>?
     char?
     char->integer
     integer->char)))

(define list-bindings
  '(((guile)
     list
     list-cdr-ref
     list-copy
     list-head
     list-index
     list-ref
     list-tail
     list?
     null?
     make-list
     append
     delete
     delq
     delv
     filter
     length
     member
     memq
     memv
     merge
     reverse)))

;; These can only form part of a safe binding set if no mutable
;; pair is exposed to the sandbox.
(define mutating-list-bindings
  '(((guile)
     list-cdr-set!
     list-set!
     append!
     delete!
     delete1!
     delq!
     delq1!
     delv!
     delv1!
     filter!
     merge!
     reverse!)))

(define pair-bindings
  '(((guile)
     last-pair
     pair?
     caaaar
     caaadr
     caaar
     caadar
     caaddr
     caadr
     caar
     cadaar
     cadadr
     cadar
     caddar
     cadddr
     caddr
     cadr
     car
     cdaaar
     cdaadr
     cdaar
     cdadar
     cdaddr
     cdadr
     cdar
     cddaar
     cddadr
     cddar
     cdddar
     cddddr
     cdddr
     cddr
     cdr
     cons
     cons*)))

;; These can only form part of a safe binding set if no mutable
;; pair is exposed to the sandbox.
(define mutating-pair-bindings
  '(((guile)
     set-car!
     set-cdr!)))

(define vector-bindings
  '(((guile)
     list->vector
     make-vector
     vector
     vector->list
     vector-copy
     vector-length
     vector-ref
     vector?)))

;; These can only form part of a safe binding set if no mutable
;; vector is exposed to the sandbox.
(define mutating-vector-bindings
  '(((guile)
     vector-fill!
     vector-move-left!
     vector-move-right!
     vector-set!)))

(define promise-bindings
  '(((guile)
     force
     delay
     make-promise
     promise?)))

(define srfi-4-bindings
  '(((srfi srfi-4)
     f32vector
     f32vector->list
     f32vector-length
     f32vector-ref
     f32vector?
     f64vector
     f64vector->list
     f64vector-length
     f64vector-ref
     f64vector?
     list->f32vector
     list->f64vector
     list->s16vector
     list->s32vector
     list->s64vector
     list->s8vector
     list->u16vector
     list->u32vector
     list->u64vector
     list->u8vector
     make-f32vector
     make-f64vector
     make-s16vector
     make-s32vector
     make-s64vector
     make-s8vector
     make-u16vector
     make-u32vector
     make-u64vector
     make-u8vector
     s16vector
     s16vector->list
     s16vector-length
     s16vector-ref
     s16vector?
     s32vector
     s32vector->list
     s32vector-length
     s32vector-ref
     s32vector?
     s64vector
     s64vector->list
     s64vector-length
     s64vector-ref
     s64vector?
     s8vector
     s8vector->list
     s8vector-length
     s8vector-ref
     s8vector?
     u16vector
     u16vector->list
     u16vector-length
     u16vector-ref
     u16vector?
     u32vector
     u32vector->list
     u32vector-length
     u32vector-ref
     u32vector?
     u64vector
     u64vector->list
     u64vector-length
     u64vector-ref
     u64vector?
     u8vector
     u8vector->list
     u8vector-length
     u8vector-ref
     u8vector?)))

;; These can only form part of a safe binding set if no mutable
;; bytevector is exposed to the sandbox.
(define mutating-srfi-4-bindings
  '(((srfi srfi-4)
     f32vector-set!
     f64vector-set!
     s16vector-set!
     s32vector-set!
     s64vector-set!
     s8vector-set!
     u16vector-set!
     u32vector-set!
     u64vector-set!
     u8vector-set!)))

(define all-pure-bindings
  (append alist-bindings
          array-bindings
          bit-bindings
          bitvector-bindings
          char-bindings
          char-set-bindings
          clock-bindings
          core-bindings
          error-bindings
          fluid-bindings
          hash-bindings
          iteration-bindings
          keyword-bindings
          list-bindings
          macro-bindings
          nil-bindings
          number-bindings
          pair-bindings
          predicate-bindings
          procedure-bindings
          promise-bindings
          prompt-bindings
          regexp-bindings
          sort-bindings
          srfi-4-bindings
          string-bindings
          symbol-bindings
          unspecified-bindings
          variable-bindings
          vector-bindings
          version-bindings))


(define all-pure-and-impure-bindings
  (append all-pure-bindings
          mutating-alist-bindings
          mutating-array-bindings
          mutating-bitvector-bindings
          mutating-fluid-bindings
          mutating-hash-bindings
          mutating-list-bindings
          mutating-pair-bindings
          mutating-sort-bindings
          mutating-srfi-4-bindings
          mutating-string-bindings
          mutating-variable-bindings
          mutating-vector-bindings))