Inherit FP modes for new threads on Windows.
[sbcl.git] / tests / threads.impure.lisp
1 ;;;; miscellaneous tests of thread stuff
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; While most of SBCL is derived from the CMU CL system, the test
7 ;;;; files (like this one) were written from scratch after the fork
8 ;;;; from CMU CL.
9 ;;;
10 ;;;; This software is in the public domain and is provided with
11 ;;;; absoluely no warranty. See the COPYING and CREDITS files for
12 ;;;; more information.
13
14 ; WHITE-BOX TESTS
15
16 (in-package "SB-THREAD")
17 (use-package :test-util)
18 (use-package "ASSERTOID")
19
20 (setf sb-unix::*on-dangerous-wait* :error)
21
22 (defun wait-for-threads (threads)
23   (mapc (lambda (thread) (sb-thread:join-thread thread :default nil)) threads)
24   (assert (not (some #'sb-thread:thread-alive-p threads))))
25
26 (with-test (:name (:threads :trivia))
27   (assert (eql 1 (length (list-all-threads))))
28
29   (assert (eq *current-thread*
30               (find (thread-name *current-thread*) (list-all-threads)
31                     :key #'thread-name :test #'equal)))
32
33   (assert (thread-alive-p *current-thread*)))
34
35 (with-test (:name (:with-mutex :basics))
36   (let ((mutex (make-mutex)))
37     (with-mutex (mutex)
38       mutex)))
39
40 (sb-alien:define-alien-routine "check_deferrables_blocked_or_lose"
41     void
42   (where sb-alien:unsigned-long))
43 (sb-alien:define-alien-routine "check_deferrables_unblocked_or_lose"
44     void
45   (where sb-alien:unsigned-long))
46
47 (with-test (:name (:interrupt-thread :basics :no-unwinding))
48   (let ((a 0))
49     (interrupt-thread *current-thread* (lambda () (setq a 1)))
50     (assert (eql a 1))))
51
52 (with-test (:name (:interrupt-thread :deferrables-blocked))
53   (sb-thread:interrupt-thread sb-thread:*current-thread*
54                               (lambda ()
55                                 (check-deferrables-blocked-or-lose 0))))
56
57 (with-test (:name (:interrupt-thread :deferrables-unblocked))
58   (sb-thread:interrupt-thread sb-thread:*current-thread*
59                               (lambda ()
60                                 (with-interrupts
61                                   (check-deferrables-unblocked-or-lose 0)))))
62
63 (with-test (:name (:interrupt-thread :nlx))
64   (catch 'xxx
65     (sb-thread:interrupt-thread sb-thread:*current-thread*
66                                 (lambda ()
67                                   (check-deferrables-blocked-or-lose 0)
68                                   (throw 'xxx nil))))
69   (check-deferrables-unblocked-or-lose 0))
70
71 #-sb-thread (sb-ext:exit :code 104)
72
73 ;;;; Now the real tests...
74
75 (with-test (:name (:with-mutex :timeout))
76   (let ((m (make-mutex)))
77     (with-mutex (m)
78       (assert (null (join-thread (make-thread
79                                   (lambda ()
80                                     (with-mutex (m :timeout 0.1)
81                                       t)))))))
82     (assert (join-thread (make-thread
83                           (lambda ()
84                             (with-mutex (m :timeout 0.1)
85                               t)))))))
86
87 (with-test (:name (:interrupt-thread :deferrables-unblocked-by-lock))
88   (let ((lock (sb-thread::make-mutex))
89         (thread (make-join-thread (lambda ()
90                                     (loop (sleep 1))))))
91     (sb-thread::grab-mutex lock)
92     (sb-thread:interrupt-thread thread
93                                 (lambda ()
94                                   (check-deferrables-blocked-or-lose 0)
95                                   (sb-thread::grab-mutex lock)
96                                   (check-deferrables-unblocked-or-lose 0)
97                                   (sb-thread:abort-thread)))
98     (sleep 3)
99     (sb-thread::release-mutex lock)))
100
101 ;;; compare-and-swap
102
103 (defmacro defincf (name accessor &rest args)
104   `(defun ,name (x)
105      (let* ((old (,accessor x ,@args))
106          (new (1+ old)))
107     (loop until (eq old (sb-ext:compare-and-swap (,accessor x ,@args) old new))
108        do (setf old (,accessor x ,@args)
109                 new (1+ old)))
110     new)))
111
112 (defstruct cas-struct (slot 0))
113
114 (defincf incf-car car)
115 (defincf incf-cdr cdr)
116 (defincf incf-slot cas-struct-slot)
117 (defincf incf-symbol-value symbol-value)
118 (defincf incf-svref/1 svref 1)
119 (defincf incf-svref/0 svref 0)
120
121 (defmacro def-test-cas (name init incf op)
122   `(with-test (:name ,name)
123      (flet ((,name (n)
124               (declare (fixnum n))
125               (let* ((x ,init)
126                      (run nil)
127                      (threads
128                       (loop repeat 10
129                             collect (sb-thread:make-thread
130                                      (lambda ()
131                                        (loop until run
132                                              do (sb-thread:thread-yield))
133                                        (loop repeat n do (,incf x)))))))
134                 (setf run t)
135                 (dolist (th threads)
136                   (sb-thread:join-thread th))
137                 (assert (= (,op x) (* 10 n))))))
138        (,name 200000))))
139
140 (def-test-cas test-cas-car (cons 0 nil) incf-car car)
141 (def-test-cas test-cas-cdr (cons nil 0) incf-cdr cdr)
142 (def-test-cas test-cas-slot (make-cas-struct) incf-slot cas-struct-slot)
143 (def-test-cas test-cas-value (let ((x '.x.))
144                                (set x 0)
145                                x)
146   incf-symbol-value symbol-value)
147 (def-test-cas test-cas-svref/0 (vector 0 nil) incf-svref/0 (lambda (x)
148                                                              (svref x 0)))
149 (def-test-cas test-cas-svref/1 (vector nil 0) incf-svref/1 (lambda (x)
150                                                              (svref x 1)))
151 (format t "~&compare-and-swap tests done~%")
152
153 (with-test (:name (:threads :more-trivia)))
154 (let ((old-threads (list-all-threads))
155       (thread (make-thread (lambda ()
156                              (assert (find *current-thread* *all-threads*))
157                              (sleep 2))))
158       (new-threads (list-all-threads)))
159   (assert (thread-alive-p thread))
160   (assert (eq thread (first new-threads)))
161   (assert (= (1+ (length old-threads)) (length new-threads)))
162   (sleep 3)
163   (assert (not (thread-alive-p thread))))
164
165 (with-test (:name (:join-thread :nlx :default))
166   (let ((sym (gensym)))
167     (assert (eq sym (join-thread (make-thread (lambda () (sb-thread:abort-thread)))
168                                  :default sym)))))
169
170 (with-test (:name (:join-thread :nlx :error))
171   (raises-error? (join-thread (make-thread (lambda () (sb-thread:abort-thread))))
172                  join-thread-error))
173
174 (with-test (:name (:join-thread :multiple-values))
175   (assert (equal '(1 2 3)
176                  (multiple-value-list
177                   (join-thread (make-thread (lambda () (values 1 2 3))))))))
178
179 ;;; We had appalling scaling properties for a while.  Make sure they
180 ;;; don't reappear.
181 (defun scaling-test (function &optional (nthreads 5))
182   "Execute FUNCTION with NTHREADS lurking to slow it down."
183   (let ((queue (sb-thread:make-waitqueue))
184         (mutex (sb-thread:make-mutex)))
185     ;; Start NTHREADS idle threads.
186     (dotimes (i nthreads)
187       (make-join-thread (lambda ()
188                           (with-mutex (mutex)
189                             (sb-thread:condition-wait queue mutex))
190                           (sb-thread:abort-thread))))
191     (let ((start-time (get-internal-run-time)))
192       (funcall function)
193       (prog1 (- (get-internal-run-time) start-time)
194         (sb-thread:condition-broadcast queue)))))
195 (defun fact (n)
196   "A function that does work with the CPU."
197   (if (zerop n) 1 (* n (fact (1- n)))))
198
199 (with-test (:name :lurking-threads)
200   (let ((work (lambda () (fact 15000))))
201     (let ((zero (scaling-test work 0))
202           (four (scaling-test work 4)))
203       ;; a slightly weak assertion, but good enough for starters.
204       (assert (< four (* 1.5 zero))))))
205
206 ;;; For one of the interupt-thread tests, we want a foreign function
207 ;;; that does not make syscalls
208
209 #-win32
210 (progn
211   (with-open-file (o "threads-foreign.c" :direction :output :if-exists :supersede)
212     (format o "void loop_forever() { while(1) ; }~%"))
213   (sb-ext:run-program "/bin/sh"
214                       '("run-compiler.sh" "-sbcl-pic" "-sbcl-shared"
215                         "-o" "threads-foreign.so" "threads-foreign.c"))
216   (sb-alien:load-shared-object (truename "threads-foreign.so"))
217   (sb-alien:define-alien-routine loop-forever sb-alien:void)
218   (delete-file "threads-foreign.c"))
219
220 ;;; elementary "can we get a lock and release it again"
221 (with-test (:name (:mutex :basics))
222   (let ((l (make-mutex :name "foo"))
223         (p *current-thread*))
224     (assert (eql (mutex-value l) nil) nil "1")
225     (sb-thread:grab-mutex l)
226     (assert (eql (mutex-value l) p) nil "3")
227     (sb-thread:release-mutex l)
228     (assert (eql (mutex-value l) nil) nil "5")))
229
230 (with-test (:name (:with-recursive-lock :basics))
231   (labels ((ours-p (value)
232              (eq *current-thread* value)))
233     (let ((l (make-mutex :name "rec")))
234       (assert (eql (mutex-value l) nil) nil "1")
235       (sb-thread:with-recursive-lock (l)
236         (assert (ours-p (mutex-value l)) nil "3")
237         (sb-thread:with-recursive-lock (l)
238           (assert (ours-p (mutex-value l)) nil "4"))
239         (assert (ours-p (mutex-value l)) nil "5"))
240       (assert (eql (mutex-value l) nil) nil "6"))))
241
242 (with-test (:name (:with-recursive-lock :wait-p))
243   (let ((m (make-mutex)))
244     (with-mutex (m)
245       (assert (null (join-thread (make-thread
246                                   (lambda ()
247                                     (with-recursive-lock (m :wait-p nil)
248                                       t)))))))
249     (assert (join-thread (make-thread
250                           (lambda ()
251                             (with-recursive-lock (m :wait-p nil)
252                               t)))))))
253
254 (with-test (:name (:with-recursive-lock :wait-p :recursive))
255   (let ((m (make-mutex)))
256     (assert (join-thread (make-thread
257                           (lambda ()
258                             (with-recursive-lock (m :wait-p nil)
259                               (with-recursive-lock (m :wait-p nil)
260                                 t))))))))
261
262 (with-test (:name (:with-recursive-lock :timeout))
263   (let ((m (make-mutex)))
264     (with-mutex (m)
265       (assert (null (join-thread (make-thread
266                                   (lambda ()
267                                     (with-recursive-lock (m :timeout 0.1)
268                                       t)))))))
269     (assert (join-thread (make-thread
270                           (lambda ()
271                             (with-recursive-lock (m :timeout 0.1)
272                               t)))))))
273
274 (with-test (:name (:with-recursive-lock :timeout :recursive))
275   (let ((m (make-mutex)))
276     (assert (join-thread (make-thread
277                           (lambda ()
278                             (with-recursive-lock (m :timeout 0.1)
279                               (with-recursive-lock (m :timeout 0.1)
280                                 t))))))))
281
282 (with-test (:name (:mutex :nesting-mutex-and-recursive-lock))
283   (let ((l (make-mutex :name "a mutex")))
284     (with-mutex (l)
285       (with-recursive-lock (l)))))
286
287 ;; test that SLEEP actually sleeps for at least the given time, even
288 ;; if interrupted by another thread exiting/a gc/anything
289 (with-test (:name (:sleep :continue-sleeping-after-interrupt))
290   (let ((start-time (get-universal-time)))
291     (make-join-thread (lambda () (sleep 1) (sb-ext:gc :full t)))
292     (sleep 5)
293     (assert (>= (get-universal-time) (+ 5 start-time)))))
294
295
296 (with-test (:name (:condition-wait :basics-1))
297   (let ((queue (make-waitqueue :name "queue"))
298         (lock (make-mutex :name "lock"))
299         (n 0))
300     (labels ((in-new-thread ()
301                (with-mutex (lock)
302                  (assert (eql (mutex-value lock) *current-thread*))
303                  (format t "~A got mutex~%" *current-thread*)
304                  ;; now drop it and sleep
305                  (condition-wait queue lock)
306                  ;; after waking we should have the lock again
307                  (assert (eql (mutex-value lock) *current-thread*))
308                  (assert (eql n 1))
309                  (decf n))))
310       (make-join-thread #'in-new-thread)
311       (sleep 2)            ; give it  a chance to start
312       ;; check the lock is free while it's asleep
313       (format t "parent thread ~A~%" *current-thread*)
314       (assert (eql (mutex-value lock) nil))
315       (with-mutex (lock)
316         (incf n)
317         (condition-notify queue))
318       (sleep 1))))
319
320 (with-test (:name (:condition-wait :basics-2))
321   (let ((queue (make-waitqueue :name "queue"))
322         (lock (make-mutex :name "lock")))
323     (labels ((ours-p (value)
324                (eq *current-thread* value))
325              (in-new-thread ()
326                (with-recursive-lock (lock)
327                  (assert (ours-p (mutex-value lock)))
328                  (format t "~A got mutex~%" (mutex-value lock))
329                  ;; now drop it and sleep
330                  (condition-wait queue lock)
331                  ;; after waking we should have the lock again
332                  (format t "woken, ~A got mutex~%" (mutex-value lock))
333                  (assert (ours-p (mutex-value lock))))))
334       (make-join-thread #'in-new-thread)
335       (sleep 2)            ; give it  a chance to start
336       ;; check the lock is free while it's asleep
337       (format t "parent thread ~A~%" *current-thread*)
338       (assert (eql (mutex-value lock) nil))
339       (with-recursive-lock (lock)
340         (condition-notify queue))
341       (sleep 1))))
342
343 (with-test (:name (:mutex :contention))
344   (let ((mutex (make-mutex :name "contended")))
345     (labels ((run ()
346                (let ((me *current-thread*))
347                  (dotimes (i 100)
348                    (with-mutex (mutex)
349                      (sleep .03)
350                      (assert (eql (mutex-value mutex) me)))
351                    (assert (not (eql (mutex-value mutex) me))))
352                  (format t "done ~A~%" *current-thread*))))
353       (let ((kid1 (make-thread #'run))
354             (kid2 (make-thread #'run)))
355         (format t "contention ~A ~A~%" kid1 kid2)
356         (wait-for-threads (list kid1 kid2))))))
357
358 ;;; GRAB-MUTEX
359
360 (with-test (:name (:grab-mutex :waitp nil))
361   (let ((m (make-mutex)))
362     (with-mutex (m)
363       (assert (null (join-thread (make-thread
364                                   #'(lambda ()
365                                       (grab-mutex m :waitp nil)))))))))
366
367 (with-test (:name (:grab-mutex :timeout :acquisition-fail))
368   (let ((m (make-mutex))
369         (w (make-semaphore)))
370     (with-mutex (m)
371       (let ((th (make-thread
372                  #'(lambda ()
373                      (prog1
374                          (grab-mutex m :timeout 0.1)
375                        (signal-semaphore w))))))
376         ;; Wait for it to -- otherwise the detect the deadlock chain
377         ;; from JOIN-THREAD.
378         (wait-on-semaphore w)
379         (assert (null (join-thread th)))))))
380
381 (with-test (:name (:grab-mutex :timeout :acquisition-success))
382   (let ((m (make-mutex))
383         (child))
384     (with-mutex (m)
385       (setq child (make-thread #'(lambda () (grab-mutex m :timeout 1.0))))
386       (sleep 0.2))
387     (assert (eq (join-thread child) 't))))
388
389 (with-test (:name (:grab-mutex :timeout+deadline))
390   (let ((m (make-mutex))
391         (w (make-semaphore)))
392     (with-mutex (m)
393       (let ((th (make-thread #'(lambda ()
394                                  (sb-sys:with-deadline (:seconds 0.0)
395                                    (handler-case
396                                        (grab-mutex m :timeout 0.0)
397                                      (sb-sys:deadline-timeout ()
398                                        (signal-semaphore w)
399                                        :deadline)))))))
400         (wait-on-semaphore w)
401         (assert (eq (join-thread th) :deadline))))))
402
403 (with-test (:name (:grab-mutex :waitp+deadline))
404   (let ((m (make-mutex)))
405     (with-mutex (m)
406       (assert (eq (join-thread
407                    (make-thread #'(lambda ()
408                                     (sb-sys:with-deadline (:seconds 0.0)
409                                       (handler-case
410                                           (grab-mutex m :waitp nil)
411                                         (sb-sys:deadline-timeout ()
412                                           :deadline))))))
413                   'nil)))))
414
415 ;;; semaphores
416
417 (defmacro raises-timeout-p (&body body)
418   `(handler-case (progn (progn ,@body) nil)
419     (sb-ext:timeout () t)))
420
421 (with-test (:name (:semaphore :wait-forever))
422   (let ((sem (make-semaphore :count 0)))
423     (assert (raises-timeout-p
424               (sb-ext:with-timeout 0.1
425                 (wait-on-semaphore sem))))))
426
427 (with-test (:name (:semaphore :initial-count))
428   (let ((sem (make-semaphore :count 1)))
429     (sb-ext:with-timeout 0.1
430       (wait-on-semaphore sem))))
431
432 (with-test (:name (:semaphore :wait-then-signal))
433   (let ((sem (make-semaphore))
434         (signalled-p nil))
435     (make-join-thread (lambda ()
436                         (sleep 0.1)
437                         (setq signalled-p t)
438                         (signal-semaphore sem)))
439     (wait-on-semaphore sem)
440     (assert signalled-p)))
441
442 (with-test (:name (:semaphore :signal-then-wait))
443   (let ((sem (make-semaphore))
444         (signalled-p nil))
445     (make-join-thread (lambda ()
446                         (signal-semaphore sem)
447                         (setq signalled-p t)))
448     (loop until signalled-p)
449     (wait-on-semaphore sem)
450     (assert signalled-p)))
451
452 (defun test-semaphore-multiple-signals (wait-on-semaphore)
453   (let* ((sem (make-semaphore :count 5))
454          (threads (loop repeat 20 collecting
455                         (make-join-thread (lambda ()
456                                             (funcall wait-on-semaphore sem))))))
457     (flet ((count-live-threads ()
458              (count-if #'thread-alive-p threads)))
459       (sleep 0.5)
460       (assert (= 15 (count-live-threads)))
461       (signal-semaphore sem 10)
462       (sleep 0.5)
463       (assert (= 5 (count-live-threads)))
464       (signal-semaphore sem 3)
465       (sleep 0.5)
466       (assert (= 2 (count-live-threads)))
467       (signal-semaphore sem 4)
468       (sleep 0.5)
469       (assert (= 0 (count-live-threads))))))
470
471 (with-test (:name (:semaphore :multiple-signals))
472   (test-semaphore-multiple-signals #'wait-on-semaphore))
473
474 (with-test (:name (:try-semaphore :trivial-fail))
475   (assert (eq (try-semaphore (make-semaphore :count 0)) 'nil)))
476
477 (with-test (:name (:try-semaphore :trivial-success))
478   (let ((sem (make-semaphore :count 1)))
479     (assert (try-semaphore sem))
480     (assert (zerop (semaphore-count sem)))))
481
482 (with-test (:name (:try-semaphore :trivial-fail :n>1))
483   (assert (eq (try-semaphore (make-semaphore :count 1) 2) 'nil)))
484
485 (with-test (:name (:try-semaphore :trivial-success :n>1))
486   (let ((sem (make-semaphore :count 10)))
487     (assert (try-semaphore sem 5))
488     (assert (try-semaphore sem 5))
489     (assert (zerop (semaphore-count sem)))))
490
491 (with-test (:name (:try-semaphore :emulate-wait-on-semaphore))
492   (flet ((busy-wait-on-semaphore (sem)
493            (loop until (try-semaphore sem) do (sleep 0.001))))
494     (test-semaphore-multiple-signals #'busy-wait-on-semaphore)))
495
496 ;;; Here we test that interrupting TRY-SEMAPHORE does not leave a
497 ;;; semaphore in a bad state.
498 (with-test (:name (:try-semaphore :interrupt-safe))
499   (flet ((make-threads (count fn)
500            (loop repeat count collect (make-thread fn)))
501          (kill-thread (thread)
502            (when (thread-alive-p thread)
503              (ignore-errors (terminate-thread thread))))
504          (count-live-threads (threads)
505            (count-if #'thread-alive-p threads)))
506     ;; WAITERS will already be waiting on the semaphore while
507     ;; threads-being-interrupted will perform TRY-SEMAPHORE on that
508     ;; semaphore, and MORE-WAITERS are new threads trying to wait on
509     ;; the semaphore during the interruption-fire.
510     (let* ((sem (make-semaphore :count 100))
511            (waiters (make-threads 20 #'(lambda ()
512                                          (wait-on-semaphore sem))))
513            (triers  (make-threads 40 #'(lambda ()
514                                          (sleep (random 0.01))
515                                          (try-semaphore sem (1+ (random 5))))))
516            (more-waiters
517             (loop repeat 10
518                   do (kill-thread (nth (random 40) triers))
519                   collect (make-thread #'(lambda () (wait-on-semaphore sem)))
520                   do (kill-thread (nth (random 40) triers)))))
521       (sleep 0.5)
522       ;; Now ensure that the waiting threads will all be waked up,
523       ;; i.e. that the semaphore is still working.
524       (loop repeat (+ (count-live-threads waiters)
525                       (count-live-threads more-waiters))
526             do (signal-semaphore sem))
527       (sleep 0.5)
528       (assert (zerop (count-live-threads triers)))
529       (assert (zerop (count-live-threads waiters)))
530       (assert (zerop (count-live-threads more-waiters))))))
531
532
533
534 (format t "~&semaphore tests done~%")
535
536 (defun test-interrupt (function-to-interrupt &optional quit-p)
537   (let ((child  (make-kill-thread function-to-interrupt)))
538     ;;(format t "gdb ./src/runtime/sbcl ~A~%attach ~A~%" child child)
539     (sleep 2)
540     (format t "interrupting child ~A~%" child)
541     (interrupt-thread child
542                       (lambda ()
543                         (format t "child pid ~A~%" *current-thread*)
544                         (when quit-p (abort-thread))))
545     (sleep 1)
546     child))
547
548 ;; separate tests for (a) interrupting Lisp code, (b) C code, (c) a syscall,
549 ;; (d) waiting on a lock, (e) some code which we hope is likely to be
550 ;; in pseudo-atomic
551
552 (with-test (:name (:interrupt-thread :more-basics))
553   (let ((child (test-interrupt (lambda () (loop)))))
554     (terminate-thread child)))
555
556 (with-test (:name (:interrupt-thread :interrupt-foreign-loop)
557                   ;; This feature is explicitly unsupported on Win32.
558                   :skipped-on :win32)
559   (test-interrupt #'loop-forever :quit))
560
561 (with-test (:name (:interrupt-thread :interrupt-sleep))
562   (let ((child (test-interrupt (lambda () (loop (sleep 2000))))))
563     (terminate-thread child)
564     (wait-for-threads (list child))))
565
566 (with-test (:name (:interrupt-thread :interrupt-mutex-acquisition))
567   (let ((lock (make-mutex :name "loctite"))
568         child)
569     (with-mutex (lock)
570       (setf child (test-interrupt
571                    (lambda ()
572                      (with-mutex (lock)
573                        (assert (eql (mutex-value lock) *current-thread*)))
574                      (assert (not (eql (mutex-value lock) *current-thread*)))
575                      (sleep 10))))
576       ;;hold onto lock for long enough that child can't get it immediately
577       (sleep 5)
578       (interrupt-thread child (lambda () (format t "l ~A~%" (mutex-value lock))))
579       (format t "parent releasing lock~%"))
580     (terminate-thread child)
581     (wait-for-threads (list child))))
582
583 (format t "~&locking test done~%")
584
585 (defun alloc-stuff () (copy-list '(1 2 3 4 5)))
586
587 (with-test (:name (:interrupt-thread :interrupt-consing-child))
588   (let ((thread (make-thread (lambda () (loop (alloc-stuff))))))
589     (let ((killers
590            (loop repeat 4 collect
591                  (sb-thread:make-thread
592                   (lambda ()
593                     (loop repeat 25 do
594                           (sleep (random 0.1d0))
595                           (princ ".")
596                           (force-output)
597                           (sb-thread:interrupt-thread thread (lambda ()))))))))
598       (wait-for-threads killers)
599       (sb-thread:terminate-thread thread)
600       (wait-for-threads (list thread))))
601   (sb-ext:gc :full t))
602
603 (format t "~&multi interrupt test done~%")
604
605 #+(or x86 x86-64) ;; x86oid-only, see internal commentary.
606 (with-test (:name (:interrupt-thread :interrupt-consing-child :again))
607   (let ((c (make-thread (lambda () (loop (alloc-stuff))))))
608     ;; NB this only works on x86: other ports don't have a symbol for
609     ;; pseudo-atomic atomicity
610     (dotimes (i 100)
611       (sleep (random 0.1d0))
612       (interrupt-thread c
613                         (lambda ()
614                           (princ ".") (force-output)
615                           (assert (thread-alive-p *current-thread*))
616                           (assert
617                            (not (logbitp 0 SB-KERNEL:*PSEUDO-ATOMIC-BITS*))))))
618     (terminate-thread c)
619     (wait-for-threads (list c))))
620
621 (format t "~&interrupt test done~%")
622
623 (defstruct counter (n 0 :type sb-vm:word))
624 (defvar *interrupt-counter* (make-counter))
625
626 (declaim (notinline check-interrupt-count))
627 (defun check-interrupt-count (i)
628   (declare (optimize (debug 1) (speed 1)))
629   ;; This used to lose if eflags were not restored after an interrupt.
630   (unless (typep i 'fixnum)
631     (error "!!!!!!!!!!!")))
632
633 (with-test (:name (:interrupt-thread :interrupt-ATOMIC-INCF))
634   (let ((c (make-thread
635             (lambda ()
636               (handler-bind ((error #'(lambda (cond)
637                                         (princ cond)
638                                         (sb-debug:backtrace
639                                          most-positive-fixnum))))
640                 (loop (check-interrupt-count
641                        (counter-n *interrupt-counter*))))))))
642     (let ((func (lambda ()
643                   (princ ".")
644                   (force-output)
645                   (sb-ext:atomic-incf (counter-n *interrupt-counter*)))))
646       (setf (counter-n *interrupt-counter*) 0)
647       (dotimes (i 100)
648         (sleep (random 0.1d0))
649         (interrupt-thread c func))
650       (loop until (= (counter-n *interrupt-counter*) 100) do (sleep 0.1))
651       (terminate-thread c)
652       (wait-for-threads (list c)))))
653
654 (format t "~&interrupt count test done~%")
655
656 (defvar *runningp* nil)
657
658 (with-test (:name (:interrupt-thread :no-nesting))
659   (let ((thread (sb-thread:make-thread
660                  (lambda ()
661                    (catch 'xxx
662                      (loop))))))
663     (declare (special runningp))
664     (sleep 0.2)
665     (sb-thread:interrupt-thread thread
666                                 (lambda ()
667                                     (let ((*runningp* t))
668                                       (sleep 1))))
669     (sleep 0.2)
670     (sb-thread:interrupt-thread thread
671                                 (lambda ()
672                                   (throw 'xxx *runningp*)))
673     (assert (not (sb-thread:join-thread thread)))))
674
675 (with-test (:name (:interrupt-thread :nesting))
676   (let ((thread (sb-thread:make-thread
677                  (lambda ()
678                    (catch 'xxx
679                      (loop))))))
680     (declare (special runningp))
681     (sleep 0.2)
682     (sb-thread:interrupt-thread thread
683                                 (lambda ()
684                                   (let ((*runningp* t))
685                                     (sb-sys:with-interrupts
686                                       (sleep 1)))))
687     (sleep 0.2)
688     (sb-thread:interrupt-thread thread
689                                 (lambda ()
690                                   (throw 'xxx *runningp*)))
691     (assert (sb-thread:join-thread thread))))
692
693 (with-test (:name (:two-threads-running-gc))
694   (let (a-done b-done)
695     (make-join-thread (lambda ()
696                         (dotimes (i 100)
697                           (sb-ext:gc) (princ "\\") (force-output))
698                         (setf a-done t)))
699     (make-join-thread (lambda ()
700                         (dotimes (i 25)
701                           (sb-ext:gc :full t)
702                           (princ "/") (force-output))
703                         (setf b-done t)))
704     (loop
705       (when (and a-done b-done) (return))
706       (sleep 1))))
707
708 (terpri)
709
710 (defun waste (&optional (n 100000))
711   (loop repeat n do (make-string 16384)))
712
713 (with-test (:name (:one-thread-runs-gc-while-other-conses))
714   (loop for i below 100 do
715         (princ "!")
716         (force-output)
717         (make-join-thread
718          #'(lambda ()
719              (waste)))
720         (waste)
721         (sb-ext:gc)))
722
723 (terpri)
724
725 (defparameter *aaa* nil)
726 (with-test (:name (:one-thread-runs-gc-while-other-conses :again))
727   (loop for i below 100 do
728         (princ "!")
729         (force-output)
730         (make-join-thread
731          #'(lambda ()
732              (let ((*aaa* (waste)))
733                (waste))))
734         (let ((*aaa* (waste)))
735           (waste))
736         (sb-ext:gc)))
737
738 (format t "~&gc test done~%")
739
740 ;; this used to deadlock on session-lock
741 (with-test (:name (:no-session-deadlock))
742   (make-join-thread (lambda () (sb-ext:gc))))
743
744 (defun exercise-syscall (fn reference-errno)
745   (make-kill-thread
746    (lambda ()
747      (loop do
748           (funcall fn)
749           (let ((errno (sb-unix::get-errno)))
750             (sleep (random 0.1d0))
751             (unless (eql errno reference-errno)
752               (format t "Got errno: ~A (~A) instead of ~A~%"
753                       errno
754                       (sb-unix::strerror)
755                       reference-errno)
756               (force-output)
757               (abort-thread)))))))
758
759 ;; (nanosleep -1 0) does not fail on FreeBSD
760 (with-test (:name (:exercising-concurrent-syscalls) :fails-on :win32)
761   (let* (#-freebsd
762          (nanosleep-errno (progn
763                             (sb-unix:nanosleep -1 0)
764                             (sb-unix::get-errno)))
765          (open-errno (progn
766                        (open "no-such-file"
767                              :if-does-not-exist nil)
768                        (sb-unix::get-errno)))
769          (threads
770           (list
771            #-freebsd
772            (exercise-syscall (lambda () (sb-unix:nanosleep -1 0)) nanosleep-errno)
773            (exercise-syscall (lambda () (open "no-such-file"
774                                               :if-does-not-exist nil))
775                              open-errno)
776            (make-join-thread (lambda () (loop (sb-ext:gc) (sleep 1)))))))
777     (sleep 10)
778     (princ "terminating threads")
779     (dolist (thread threads)
780       (sb-thread:terminate-thread thread))))
781
782 (format t "~&errno test done~%")
783
784 (with-test (:name :all-threads-have-abort-restart)
785   (loop repeat 100 do
786         (let ((thread (make-kill-thread (lambda () (sleep 0.1)))))
787           (sb-thread:interrupt-thread
788            thread
789            (lambda ()
790              (assert (find-restart 'abort)))))))
791
792 (sb-ext:gc :full t)
793
794 (format t "~&thread startup sigmask test done~%")
795
796 (with-test (:name (:debugger-no-hang-on-session-lock-if-interrupted)
797                   :fails-on :win32)
798   #+win32 (error "user would have to touch a key interactively to proceed")
799   (sb-debug::enable-debugger)
800   (let* ((main-thread *current-thread*)
801          (interruptor-thread
802           (make-thread (lambda ()
803                          (sleep 2)
804                          (interrupt-thread main-thread
805                                            (lambda ()
806                                              (with-interrupts
807                                                (break))))
808                          (sleep 2)
809                          (interrupt-thread main-thread #'continue))
810                        :name "interruptor")))
811     (with-session-lock (*session*)
812       (sleep 3))
813     (loop while (thread-alive-p interruptor-thread))))
814
815 (format t "~&session lock test done~%")
816
817 ;; expose thread creation races by exiting quickly
818 (with-test (:name (:no-thread-creation-race :light))
819   (make-join-thread (lambda ())))
820
821 (with-test (:name (:no-thread-creation-race :heavy))
822   (loop repeat 20 do
823         (wait-for-threads
824          (loop for i below 100 collect
825                (sb-thread:make-thread (lambda ()))))))
826
827 (format t "~&creation test done~%")
828
829 ;; interrupt handlers are per-thread with pthreads, make sure the
830 ;; handler installed in one thread is global
831 (with-test (:name (:global-interrupt-handler))
832   (make-join-thread
833    (lambda ()
834      (sb-ext:run-program "sleep" '("1") :search t :wait nil))))
835
836 ;;;; Binding stack safety
837
838 (defparameter *x* nil)
839 (defparameter *n-gcs-requested* 0)
840 (defparameter *n-gcs-done* 0)
841
842 (let ((counter 0))
843   (defun make-something-big ()
844     (let ((x (make-string 32000)))
845       (incf counter)
846       (let ((counter counter))
847         (sb-ext:finalize x (lambda () (format t " ~S" counter)
848                                    (force-output)))))))
849
850 (defmacro wait-for-gc ()
851   `(progn
852      (incf *n-gcs-requested*)
853      (loop while (< *n-gcs-done* *n-gcs-requested*))))
854
855 (defun send-gc ()
856   (loop until (< *n-gcs-done* *n-gcs-requested*))
857   (format t "G")
858   (force-output)
859   (sb-ext:gc)
860   (incf *n-gcs-done*))
861
862 #+(or x86 x86-64) ;the only platforms with a *binding-stack-pointer* variable
863 (defun exercise-binding ()
864   (loop
865    (let ((*x* (make-something-big)))
866      (let ((*x* 42))
867        ;; at this point the binding stack looks like this:
868        ;; NO-TLS-VALUE-MARKER, *x*, SOMETHING, *x*
869        t))
870    (wait-for-gc)
871    ;; sig_stop_for_gc_handler binds FREE_INTERRUPT_CONTEXT_INDEX. By
872    ;; now SOMETHING is gc'ed and the binding stack looks like this: 0,
873    ;; 0, SOMETHING, 0 (because the symbol slots are zeroed on
874    ;; unbinding but values are not).
875    (let ((*x* nil)
876          (binding-pointer-delta (ash 2 (- sb-vm:word-shift sb-vm:n-fixnum-tag-bits))))
877      ;; bump bsp as if a BIND had just started
878      (incf sb-vm::*binding-stack-pointer* binding-pointer-delta)
879      (wait-for-gc)
880      (decf sb-vm::*binding-stack-pointer* binding-pointer-delta))))
881
882 #+(or x86 x86-64) ;the only platforms with a *binding-stack-pointer* variable
883 (with-test (:name (:binding-stack-gc-safety))
884   (let (threads)
885     (unwind-protect
886          (progn
887            (push (make-kill-thread #'exercise-binding) threads)
888            (push (make-kill-thread (lambda ()
889                                      (loop
890                                       (sleep 0.1)
891                                       (send-gc))))
892                  threads)
893            (sleep 4))
894       (mapc #'sb-thread:terminate-thread threads))))
895
896 (format t "~&binding test done~%")
897
898 ;;; HASH TABLES
899
900 (defvar *errors* nil)
901
902 (defun oops (e)
903   (setf *errors* e)
904   (format t "~&oops: ~A in ~S~%" e *current-thread*)
905   (sb-debug:backtrace)
906   (catch 'done))
907
908 (with-test (:name (:unsynchronized-hash-table)
909                   ;; FIXME: This test occasionally eats out craploads
910                   ;; of heap instead of expected error early. Not 100%
911                   ;; sure if it would finish as expected, but since it
912                   ;; hits swap on my system I'm not likely to find out
913                   ;; soon. Disabling for now. -- nikodemus
914             :skipped-on :sbcl)
915   ;; We expect a (probable) error here: parellel readers and writers
916   ;; on a hash-table are not expected to work -- but we also don't
917   ;; expect this to corrupt the image.
918   (let* ((hash (make-hash-table))
919          (*errors* nil)
920          (threads (list (make-kill-thread
921                          (lambda ()
922                            (catch 'done
923                              (handler-bind ((serious-condition 'oops))
924                                (loop
925                                  ;;(princ "1") (force-output)
926                                  (setf (gethash (random 100) hash) 'h)))))
927                          :name "writer")
928                         (make-kill-thread
929                          (lambda ()
930                            (catch 'done
931                              (handler-bind ((serious-condition 'oops))
932                                (loop
933                                  ;;(princ "2") (force-output)
934                                  (remhash (random 100) hash)))))
935                          :name "reader")
936                         (make-kill-thread
937                          (lambda ()
938                            (catch 'done
939                              (handler-bind ((serious-condition 'oops))
940                                (loop
941                                  (sleep (random 1.0))
942                                  (sb-ext:gc :full t)))))
943                          :name "collector"))))
944     (unwind-protect
945          (sleep 10)
946       (mapc #'sb-thread:terminate-thread threads))))
947
948 (format t "~&unsynchronized hash table test done~%")
949
950 (with-test (:name (:synchronized-hash-table))
951   (let* ((hash (make-hash-table :synchronized t))
952          (*errors* nil)
953          (threads (list (make-join-thread
954                          (lambda ()
955                            (catch 'done
956                              (handler-bind ((serious-condition 'oops))
957                                (loop
958                                  ;;(princ "1") (force-output)
959                                  (setf (gethash (random 100) hash) 'h)))))
960                          :name "writer")
961                         (make-join-thread
962                          (lambda ()
963                            (catch 'done
964                              (handler-bind ((serious-condition 'oops))
965                                (loop
966                                  ;;(princ "2") (force-output)
967                                  (remhash (random 100) hash)))))
968                          :name "reader")
969                         (make-join-thread
970                          (lambda ()
971                            (catch 'done
972                              (handler-bind ((serious-condition 'oops))
973                                (loop
974                                  (sleep (random 1.0))
975                                  (sb-ext:gc :full t)))))
976                          :name "collector"))))
977     (unwind-protect
978          (sleep 10)
979       (mapc #'sb-thread:terminate-thread threads))
980     (assert (not *errors*))))
981
982 (format t "~&synchronized hash table test done~%")
983
984 (with-test (:name (:hash-table-parallel-readers))
985   (let ((hash (make-hash-table))
986         (*errors* nil))
987     (loop repeat 50
988           do (setf (gethash (random 100) hash) 'xxx))
989     (let ((threads (list (make-kill-thread
990                           (lambda ()
991                             (catch 'done
992                               (handler-bind ((serious-condition 'oops))
993                                 (loop
994                                       until (eq t (gethash (random 100) hash))))))
995                           :name "reader 1")
996                          (make-kill-thread
997                           (lambda ()
998                             (catch 'done
999                               (handler-bind ((serious-condition 'oops))
1000                                 (loop
1001                                       until (eq t (gethash (random 100) hash))))))
1002                           :name "reader 2")
1003                          (make-kill-thread
1004                           (lambda ()
1005                             (catch 'done
1006                               (handler-bind ((serious-condition 'oops))
1007                                 (loop
1008                                       until (eq t (gethash (random 100) hash))))))
1009                           :name "reader 3")
1010                          (make-kill-thread
1011                           (lambda ()
1012                             (catch 'done
1013                               (handler-bind ((serious-condition 'oops))
1014                                (loop
1015                                  (sleep (random 1.0))
1016                                  (sb-ext:gc :full t)))))
1017                           :name "collector"))))
1018       (unwind-protect
1019            (sleep 10)
1020         (mapc #'sb-thread:terminate-thread threads))
1021       (assert (not *errors*)))))
1022
1023 (format t "~&multiple reader hash table test done~%")
1024
1025 (with-test (:name (:hash-table-single-accessor-parallel-gc))
1026   (let ((hash (make-hash-table))
1027         (*errors* nil))
1028     (let ((threads (list (make-kill-thread
1029                           (lambda ()
1030                             (handler-bind ((serious-condition 'oops))
1031                               (loop
1032                                 (let ((n (random 100)))
1033                                   (if (gethash n hash)
1034                                       (remhash n hash)
1035                                       (setf (gethash n hash) 'h))))))
1036                           :name "accessor")
1037                          (make-kill-thread
1038                           (lambda ()
1039                             (handler-bind ((serious-condition 'oops))
1040                               (loop
1041                                 (sleep (random 1.0))
1042                                 (sb-ext:gc :full t))))
1043                           :name "collector"))))
1044       (unwind-protect
1045            (sleep 10)
1046         (mapc #'sb-thread:terminate-thread threads))
1047       (assert (not *errors*)))))
1048
1049 (format t "~&single accessor hash table test~%")
1050
1051 #|  ;; a cll post from eric marsden
1052 | (defun crash ()
1053 |   (setq *debugger-hook*
1054 |         (lambda (condition old-debugger-hook)
1055 |           (debug:backtrace 10)
1056 |           (unix:unix-exit 2)))
1057 |   #+live-dangerously
1058 |   (mp::start-sigalrm-yield)
1059 |   (flet ((roomy () (loop (with-output-to-string (*standard-output*) (room)))))
1060 |     (mp:make-process #'roomy)
1061 |     (mp:make-process #'roomy)))
1062 |#
1063
1064 (with-test (:name (:condition-variable :notify-multiple))
1065   (flet ((tester (notify-fun)
1066            (let ((queue (make-waitqueue :name "queue"))
1067                  (lock (make-mutex :name "lock"))
1068                  (data nil))
1069              (labels ((test (x)
1070                         (loop
1071                            (with-mutex (lock)
1072                              (format t "condition-wait ~a~%" x)
1073                              (force-output)
1074                              (condition-wait queue lock)
1075                              (format t "woke up ~a~%" x)
1076                              (force-output)
1077                              (push x data)))))
1078                (let ((threads (loop for x from 1 to 10
1079                                     collect
1080                                     (let ((x x))
1081                                       (make-kill-thread (lambda ()
1082                                                           (test x)))))))
1083                  (sleep 5)
1084                  (with-mutex (lock)
1085                    (funcall notify-fun queue))
1086                  (sleep 5)
1087                  (mapcar #'terminate-thread threads)
1088                  ;; Check that all threads woke up at least once
1089                  (assert (= (length (remove-duplicates data)) 10)))))))
1090     (tester (lambda (queue)
1091               (format t "~&(condition-notify queue 10)~%")
1092               (force-output)
1093               (condition-notify queue 10)))
1094     (tester (lambda (queue)
1095               (format t "~&(condition-broadcast queue)~%")
1096               (force-output)
1097               (condition-broadcast queue)))))
1098
1099 (format t "waitqueue wakeup tests done~%")
1100
1101 ;;; Make sure that a deadline handler is not invoked twice in a row in
1102 ;;; CONDITION-WAIT. See LP #512914 for a detailed explanation.
1103 ;;;
1104 (with-test (:name (:condition-wait :deadlines :LP-512914))
1105   (let ((n 2)                      ; was empirically enough to trigger the bug
1106         (mutex (sb-thread:make-mutex))
1107         (waitq (sb-thread:make-waitqueue))
1108         (threads nil)
1109         (deadline-handler-run-twice? nil))
1110     (dotimes (i n)
1111       (let ((child
1112               (sb-thread:make-thread
1113                #'(lambda ()
1114                    (handler-bind
1115                        ((sb-sys:deadline-timeout
1116                           (let ((already? nil))
1117                             #'(lambda (c)
1118                                 (when already?
1119                                   (setq deadline-handler-run-twice? t))
1120                                 (setq already? t)
1121                                 (sleep 0.2)
1122                                 (sb-thread:condition-broadcast waitq)
1123                                 (sb-sys:defer-deadline 10.0 c)))))
1124                      (sb-sys:with-deadline (:seconds 0.1)
1125                        (sb-thread:with-mutex (mutex)
1126                          (sb-thread:condition-wait waitq mutex))))))))
1127         (push child threads)))
1128     (mapc #'sb-thread:join-thread threads)
1129     (assert (not deadline-handler-run-twice?))))
1130
1131 (with-test (:name (:condition-wait :signal-deadline-with-interrupts-enabled))
1132   (let ((mutex (sb-thread:make-mutex))
1133         (waitq (sb-thread:make-waitqueue))
1134         (A-holds? :unknown)
1135         (B-holds? :unknown)
1136         (A-interrupts-enabled? :unknown)
1137         (B-interrupts-enabled? :unknown)
1138         (A)
1139         (B))
1140     ;; W.L.O.G., we assume that A is executed first...
1141     (setq A (sb-thread:make-thread
1142              #'(lambda ()
1143                  (handler-bind
1144                      ((sb-sys:deadline-timeout
1145                        #'(lambda (c)
1146                            ;; We came here through the call to DECODE-TIMEOUT
1147                            ;; in CONDITION-WAIT; hence both here are supposed
1148                            ;; to evaluate to T.
1149                            (setq A-holds? (sb-thread:holding-mutex-p mutex))
1150                            (setq A-interrupts-enabled?
1151                                  sb-sys:*interrupts-enabled*)
1152                            (sleep 0.2)
1153                            (sb-thread:condition-broadcast waitq)
1154                            (sb-sys:defer-deadline 10.0 c))))
1155                    (sb-sys:with-deadline (:seconds 0.1)
1156                      (sb-thread:with-mutex (mutex)
1157                        (sb-thread:condition-wait waitq mutex)))))
1158              :name "A"))
1159     (setq B (sb-thread:make-thread
1160              #'(lambda ()
1161                  (thread-yield)
1162                  (handler-bind
1163                      ((sb-sys:deadline-timeout
1164                        #'(lambda (c)
1165                            ;; We came here through the call to DECODE-TIMEOUT
1166                            ;; in CONDITION-WAIT (contended case of
1167                            ;; reaquiring the mutex) - so the former will
1168                            ;; be NIL, but interrupts should still be enabled.
1169                            (setq B-holds? (sb-thread:holding-mutex-p mutex))
1170                            (setq B-interrupts-enabled?
1171                                  sb-sys:*interrupts-enabled*)
1172                            (sleep 0.2)
1173                            (sb-thread:condition-broadcast waitq)
1174                            (sb-sys:defer-deadline 10.0 c))))
1175                    (sb-sys:with-deadline (:seconds 0.1)
1176                      (sb-thread:with-mutex (mutex)
1177                        (sb-thread:condition-wait waitq mutex)))))
1178              :name "B"))
1179     (sb-thread:join-thread A)
1180     (sb-thread:join-thread B)
1181     (let ((A-result (list A-holds? A-interrupts-enabled?))
1182           (B-result (list B-holds? B-interrupts-enabled?)))
1183       ;; We also check some subtle behaviour w.r.t. whether a deadline
1184       ;; handler in CONDITION-WAIT got the mutex, or not. This is most
1185       ;; probably very internal behaviour (so user should not depend
1186       ;; on it) -- I added the testing here just to manifest current
1187       ;; behaviour.
1188       (cond ((equal A-result '(t t)) (assert (equal B-result '(nil t))))
1189             ((equal B-result '(t t)) (assert (equal A-result '(nil t))))
1190             (t
1191              (error "Failure: fell through wit A: ~S, B: ~S"
1192                     A-result
1193                     B-result))))))
1194
1195 (with-test (:name (:mutex :finalization))
1196   (let ((a nil))
1197     (dotimes (i 500000)
1198       (setf a (make-mutex)))))
1199
1200 (format t "mutex finalization test done~%")
1201
1202 ;;; Check that INFO is thread-safe, at least when we're just doing reads.
1203
1204 (let* ((symbols (loop repeat 10000 collect (gensym)))
1205        (functions (loop for (symbol . rest) on symbols
1206                         for next = (car rest)
1207                         for fun = (let ((next next))
1208                                     (lambda (n)
1209                                       (if next
1210                                           (funcall next (1- n))
1211                                           n)))
1212                         do (setf (symbol-function symbol) fun)
1213                         collect fun)))
1214   (defun infodb-test ()
1215     (funcall (car functions) 9999)))
1216
1217 (with-test (:name (:infodb :read))
1218   (let* ((ok t)
1219          (threads (loop for i from 0 to 10
1220                         collect (sb-thread:make-thread
1221                                  (lambda ()
1222                                    (dotimes (j 100)
1223                                      (write-char #\-)
1224                                      (finish-output)
1225                                      (let ((n (infodb-test)))
1226                                        (unless (zerop n)
1227                                          (setf ok nil)
1228                                          (format t "N != 0 (~A)~%" n)
1229                                          (abort-thread)))))))))
1230     (wait-for-threads threads)
1231     (assert ok)))
1232
1233 (format t "infodb test done~%")
1234
1235 (with-test (:name :backtrace)
1236   ;; Printing backtraces from several threads at once used to hang the
1237   ;; whole SBCL process (discovered by accident due to a timer.impure
1238   ;; test misbehaving). The cause was that packages weren't even
1239   ;; thread-safe for only doing FIND-SYMBOL, and while printing
1240   ;; backtraces a loot of symbol lookups need to be done due to
1241   ;; *PRINT-ESCAPE*.
1242   (let* ((threads (loop repeat 10
1243                         collect (sb-thread:make-thread
1244                                  (lambda ()
1245                                    (dotimes (i 1000)
1246                                      (with-output-to-string (*debug-io*)
1247                                        (sb-debug::backtrace 10))))))))
1248     (wait-for-threads threads)))
1249
1250 (format t "backtrace test done~%")
1251
1252 (format t "~&starting gc deadlock test: WARNING: THIS TEST WILL HANG ON FAILURE!~%")
1253
1254 (with-test (:name :gc-deadlock)
1255   ;; Prior to 0.9.16.46 thread exit potentially deadlocked the
1256   ;; GC due to *all-threads-lock* and session lock. On earlier
1257   ;; versions and at least on one specific box this test is good enough
1258   ;; to catch that typically well before the 1500th iteration.
1259   (loop
1260      with i = 0
1261      with n = 3000
1262      while (< i n)
1263      do
1264        (incf i)
1265        (when (zerop (mod i 100))
1266          (write-char #\.)
1267          (force-output))
1268        (handler-case
1269            (if (oddp i)
1270                (make-join-thread
1271                 (lambda ()
1272                   (sleep (random 0.001)))
1273                 :name (format nil "SLEEP-~D" i))
1274                (make-join-thread
1275                 (lambda ()
1276                   ;; KLUDGE: what we are doing here is explicit,
1277                   ;; but the same can happen because of a regular
1278                   ;; MAKE-THREAD or LIST-ALL-THREADS, and various
1279                   ;; session functions.
1280                   (sb-thread::with-all-threads-lock
1281                     (sb-thread::with-session-lock (sb-thread::*session*)
1282                       (sb-ext:gc))))
1283                 :name (format nil "GC-~D" i)))
1284          (error (e)
1285            (format t "~%error creating thread ~D: ~A -- backing off for retry~%" i e)
1286            (sleep 0.1)
1287            (incf i)))))
1288
1289 (format t "~&gc deadlock test done~%")
1290 \f
1291 (let ((count (make-array 8 :initial-element 0)))
1292   (defun closure-one ()
1293     (declare (optimize safety))
1294     (values (incf (aref count 0)) (incf (aref count 1))
1295             (incf (aref count 2)) (incf (aref count 3))
1296             (incf (aref count 4)) (incf (aref count 5))
1297             (incf (aref count 6)) (incf (aref count 7))))
1298   (defun no-optimizing-away-closure-one ()
1299     (setf count (make-array 8 :initial-element 0))))
1300
1301 (defstruct box
1302   (count 0))
1303
1304 (let ((one (make-box))
1305       (two (make-box))
1306       (three (make-box)))
1307   (defun closure-two ()
1308     (declare (optimize safety))
1309     (values (incf (box-count one)) (incf (box-count two)) (incf (box-count three))))
1310   (defun no-optimizing-away-closure-two ()
1311     (setf one (make-box)
1312           two (make-box)
1313           three (make-box))))
1314
1315 ;;; PowerPC safepoint builds occasionally hang or busy-loop (or
1316 ;;; sometimes run out of memory) in the following test.  For developers
1317 ;;; interested in debugging this combination of features, it might be
1318 ;;; fruitful to concentrate their efforts around this test...
1319
1320 (with-test (:name (:funcallable-instances)
1321                   :skipped-on '(and :sb-safepoint
1322                                     (not :c-stack-is-control-stack)))
1323   ;; the funcallable-instance implementation used not to be threadsafe
1324   ;; against setting the funcallable-instance function to a closure
1325   ;; (because the code and lexenv were set separately).
1326   (let ((fun (sb-kernel:%make-funcallable-instance 0))
1327         (condition nil))
1328     (setf (sb-kernel:funcallable-instance-fun fun) #'closure-one)
1329     (flet ((changer ()
1330              (loop (setf (sb-kernel:funcallable-instance-fun fun) #'closure-one)
1331                    (setf (sb-kernel:funcallable-instance-fun fun) #'closure-two)))
1332            (test ()
1333              (handler-case (loop (funcall fun))
1334                (serious-condition (c) (setf condition c)))))
1335       (let ((changer (make-thread #'changer))
1336             (test (make-thread #'test)))
1337         (handler-case
1338             (progn
1339               ;; The two closures above are fairly carefully crafted
1340               ;; so that if given the wrong lexenv they will tend to
1341               ;; do some serious damage, but it is of course difficult
1342               ;; to predict where the various bits and pieces will be
1343               ;; allocated.  Five seconds failed fairly reliably on
1344               ;; both my x86 and x86-64 systems.  -- CSR, 2006-09-27.
1345               (sb-ext:with-timeout 5
1346                 (wait-for-threads (list test)))
1347               (error "~@<test thread got condition:~2I~_~A~@:>" condition))
1348           (sb-ext:timeout ()
1349             (terminate-thread changer)
1350             (terminate-thread test)
1351             (wait-for-threads (list changer test))))))))
1352
1353 (format t "~&funcallable-instance test done~%")
1354
1355 (defun random-type (n)
1356   `(integer ,(random n) ,(+ n (random n))))
1357
1358 (defun subtypep-hash-cache-test ()
1359   (dotimes (i 10000)
1360     (let ((type1 (random-type 500))
1361           (type2 (random-type 500)))
1362       (let ((a (subtypep type1 type2)))
1363         (dotimes (i 100)
1364           (assert (eq (subtypep type1 type2) a))))))
1365   (format t "ok~%")
1366   (force-output))
1367
1368 (with-test (:name (:hash-cache :subtypep))
1369   (mapc #'join-thread
1370         (loop repeat 10
1371               collect (sb-thread:make-thread #'subtypep-hash-cache-test))))
1372 (format t "hash-cache tests done~%")
1373
1374 ;;;; BLACK BOX TESTS
1375
1376 (in-package :cl-user)
1377 (use-package :test-util)
1378 (use-package "ASSERTOID")
1379
1380 (format t "parallel defclass test -- WARNING, WILL HANG ON FAILURE!~%")
1381 (with-test (:name :parallel-defclass)
1382   (defclass test-1 () ((a :initform :orig-a)))
1383   (defclass test-2 () ((b :initform :orig-b)))
1384   (defclass test-3 (test-1 test-2) ((c :initform :orig-c)))
1385   ;; This test is more likely to pass on Windows with the FORCE-OUTPUT
1386   ;; calls disabled in the folloving code.  (As seen on a Server 2012
1387   ;; installation.)  Clearly, this sort of workaround in a test is
1388   ;; cheating, and might be hiding the underlying bug that the test is
1389   ;; exposing.  Let's review this later.
1390   (let* ((run t)
1391          (d1 (sb-thread:make-thread (lambda ()
1392                                       (loop while run
1393                                             do (defclass test-1 () ((a :initform :new-a)))
1394                                             (write-char #\1)
1395                                             #-win32 (force-output)))
1396                                     :name "d1"))
1397          (d2 (sb-thread:make-thread (lambda ()
1398                                       (loop while run
1399                                             do (defclass test-2 () ((b :initform :new-b)))
1400                                                (write-char #\2)
1401                                                #-win32 (force-output)))
1402                                     :name "d2"))
1403          (d3 (sb-thread:make-thread (lambda ()
1404                                       (loop while run
1405                                             do (defclass test-3 (test-1 test-2) ((c :initform :new-c)))
1406                                                (write-char #\3)
1407                                                #-win32 (force-output)))
1408                                     :name "d3"))
1409          (i (sb-thread:make-thread (lambda ()
1410                                      (loop while run
1411                                            do (let ((i (make-instance 'test-3)))
1412                                                 (assert (member (slot-value i 'a) '(:orig-a :new-a)))
1413                                                 (assert (member (slot-value i 'b) '(:orig-b :new-b)))
1414                                                 (assert (member (slot-value i 'c) '(:orig-c :new-c))))
1415                                               (write-char #\i)
1416                                               #-win32 (force-output)))
1417                                    :name "i")))
1418     (format t "~%sleeping!~%")
1419     (sleep 2.0)
1420     (format t "~%stopping!~%")
1421     (setf run nil)
1422     (mapc (lambda (th)
1423             (sb-thread:join-thread th)
1424             (format t "~%joined ~S~%" (sb-thread:thread-name th)))
1425           (list d1 d2 d3 i))
1426     (force-output)))
1427 (format t "parallel defclass test done~%")
1428
1429 (with-test (:name (:deadlock-detection :interrupts) :fails-on :win32)
1430   #+win32                               ;be more explicit than just :skipped-on
1431   (error "not attempting, because of deadlock error in background thread")
1432   (let* ((m1 (sb-thread:make-mutex :name "M1"))
1433          (m2 (sb-thread:make-mutex :name "M2"))
1434          (t1-can-go (sb-thread:make-semaphore :name "T1 can go"))
1435          (t2-can-go (sb-thread:make-semaphore :name "T2 can go"))
1436          (t1 (sb-thread:make-thread
1437               (lambda ()
1438                 (sb-thread:with-mutex (m1)
1439                   (sb-thread:wait-on-semaphore t1-can-go)
1440                   :ok1))
1441               :name "T1"))
1442          (t2 (sb-thread:make-thread
1443               (lambda ()
1444                 (sb-ext:wait-for (eq t1 (sb-thread:mutex-owner m1)))
1445                 (sb-thread:with-mutex (m1 :wait-p t)
1446                   (sb-thread:wait-on-semaphore t2-can-go)
1447                   :ok2))
1448               :name "T2")))
1449     (sb-ext:wait-for (eq m1 (sb-thread::thread-waiting-for t2)))
1450     (sb-thread:interrupt-thread t2 (lambda ()
1451                                      (sb-thread:with-mutex (m2 :wait-p t)
1452                                        (sb-ext:wait-for
1453                                         (eq m2 (sb-thread::thread-waiting-for t1)))
1454                                        (sb-thread:signal-semaphore t2-can-go))))
1455     (sb-ext:wait-for (eq t2 (sb-thread:mutex-owner m2)))
1456     (sb-thread:interrupt-thread t1 (lambda ()
1457                                      (sb-thread:with-mutex (m2 :wait-p t)
1458                                        (sb-thread:signal-semaphore t1-can-go))))
1459     ;; both threads should finish without a deadlock or deadlock
1460     ;; detection error
1461     (let ((res (list (sb-thread:join-thread t1)
1462                      (sb-thread:join-thread t2))))
1463       (assert (equal '(:ok1 :ok2) res)))))
1464
1465 (with-test (:name (:deadlock-detection :gc))
1466   ;; To semi-reliably trigger the error (in SBCL's where)
1467   ;; it was present you had to run this for > 30 seconds,
1468   ;; but that's a bit long for a single test.
1469   (let* ((stop (+ 5 (get-universal-time)))
1470          (m1 (sb-thread:make-mutex :name "m1"))
1471          (t1 (sb-thread:make-thread
1472               (lambda ()
1473                 (loop until (> (get-universal-time) stop)
1474                       do (sb-thread:with-mutex (m1)
1475                            (eval `(make-array 24))))
1476                 :ok)))
1477          (t2 (sb-thread:make-thread
1478               (lambda ()
1479                 (loop until (> (get-universal-time) stop)
1480                       do (sb-thread:with-mutex (m1)
1481                            (eval `(make-array 24))))
1482                 :ok))))
1483     (let ((res (list (sb-thread:join-thread t1)
1484                      (sb-thread:join-thread t2))))
1485       (assert (equal '(:ok :ok) res)))))
1486
1487 (with-test (:name :spinlock-api)
1488   (let* ((warned 0)
1489          (funs
1490            (handler-bind ((sb-int:early-deprecation-warning (lambda (_)
1491                                                               (declare (ignore _))
1492                                                               (incf warned))))
1493              (list (compile nil `(lambda (lock)
1494                                    (sb-thread::with-spinlock (lock)
1495                                      t)))
1496                    (compile nil `(lambda ()
1497                                    (sb-thread::make-spinlock :name "foo")))
1498                    (compile nil `(lambda (lock)
1499                                    (sb-thread::get-spinlock lock)))
1500                    (compile nil `(lambda (lock)
1501                                    (sb-thread::release-spinlock lock)))))))
1502     (assert (eql 4 warned))
1503     (handler-bind ((warning #'error))
1504       (destructuring-bind (with make get release) funs
1505         (let ((lock (funcall make)))
1506           (funcall get lock)
1507           (funcall release lock)
1508           (assert (eq t (funcall with lock))))))))
1509
1510 (with-test (:name :interrupt-io-unnamed-pipe)
1511   (let (result)
1512     (labels
1513         ((reader (fd)
1514            (let ((stream (sb-sys:make-fd-stream fd
1515                                                 :element-type :default
1516                                                 :serve-events nil)))
1517              (time
1518               (let ((ok (handler-case
1519                             (catch 'stop
1520                               (progn
1521                                 (read-char stream)
1522                                 (sleep 0.1)
1523                                 (sleep 0.1)
1524                                 (sleep 0.1)))
1525                           (error (c)
1526                             c))))
1527                 (setf result ok)
1528                 (progn
1529                   (format *trace-output* "~&=> ~A~%" ok)
1530                   (force-output *trace-output*))))
1531              (sleep 2)
1532              (ignore-errors (close stream))))
1533
1534          (writer ()
1535            (multiple-value-bind (read write)
1536                (sb-unix:unix-pipe)
1537              (let* ((reader (sb-thread:make-thread (lambda () (reader read))))
1538                     (stream (sb-sys:make-fd-stream write
1539                                                    :output t
1540                                                    :element-type :default
1541                                                    :serve-events nil))
1542                     (ok :ok))
1543                (sleep 1)
1544                (sb-thread:interrupt-thread reader (lambda ()
1545                                                     (print :throwing)
1546                                                     (force-output)
1547                                                     (throw 'stop ok)))
1548                (sleep 1)
1549                (setf ok :not-ok)
1550                (write-char #\x stream)
1551                (close stream)
1552                (sb-thread:join-thread reader)))))
1553       (writer))
1554     (assert (eq result :ok))))
1555
1556 (with-test (:name :thread-alloca)
1557   (sb-ext:run-program "sh"
1558                       '("run-compiler.sh" "-sbcl-pic" "-sbcl-shared"
1559                         "alloca.c" "-o" "alloca.so")
1560                       :search t)
1561   (load-shared-object (truename "alloca.so"))
1562
1563   (alien-funcall (extern-alien "alloca_test" (function void)))
1564   (sb-thread:join-thread
1565    (sb-thread:make-thread
1566     (lambda ()
1567       (alien-funcall (extern-alien "alloca_test" (function void)))))))
1568
1569 (with-test (:name :fp-mode-inheritance-threads)
1570   (flet ((test ()
1571            (let ((thread-fp-mode)
1572                  (fp-mode (dpb 0 sb-vm::float-sticky-bits (sb-vm:floating-point-modes))))
1573              (sb-thread:join-thread
1574               (sb-thread:make-thread
1575                (lambda ()
1576                  (setf thread-fp-mode
1577                        (dpb 0 sb-vm::float-sticky-bits (sb-vm:floating-point-modes))))))
1578              (assert (= fp-mode thread-fp-mode)))))
1579     (test)
1580     (sb-int:with-float-traps-masked (:divide-by-zero)
1581       (test))
1582     (setf (sb-vm:floating-point-modes)
1583           (dpb sb-vm:float-divide-by-zero-trap-bit
1584                sb-vm::float-traps-byte
1585                (sb-vm:floating-point-modes)))
1586     (test)))