]> git.decadent.org.uk Git - ion3.git/blob - libmainloop/signal.c
fd37161b332689c7073b5065f930ab5e11549428
[ion3.git] / libmainloop / signal.c
1 /*
2  * ion/libmainloop/signal.c
3  *
4  * Copyright (c) Tuomo Valkonen 1999-2008. 
5  *
6  * See the included file LICENSE for details.
7  */
8
9 #include <unistd.h>
10 #include <sys/types.h>
11 #include <sys/wait.h>
12 #include <sys/time.h>
13 #include <time.h>
14 #include <signal.h>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <errno.h>
18
19 #include <libtu/objp.h>
20 #include <libtu/types.h>
21 #include <libtu/misc.h>
22 #include <libtu/locale.h>
23 #include <libtu/output.h>
24
25 #include "signal.h"
26 #include "hooks.h"
27
28 static int kill_sig=0;
29 #if 1
30 static int wait_sig=0;
31 #endif
32
33 static int usr2_sig=0;
34 static bool had_tmr=FALSE;
35
36 WHook *mainloop_sigchld_hook=NULL;
37 WHook *mainloop_sigusr2_hook=NULL;
38
39 static sigset_t special_sigs;
40
41
42 /*{{{ Timers */
43
44
45 static WTimer *queue=NULL;
46
47
48 int mainloop_gettime(struct timeval *val)
49 {
50 #if defined(_POSIX_MONOTONIC_CLOCK) && (_POSIX_MONOTONIC_CLOCK>=0)
51     struct timespec spec;
52     int ret;
53     static int checked=0;
54     
55     if(checked>=0){
56         ret=clock_gettime(CLOCK_MONOTONIC, &spec);
57     
58         if(ret==-1 && errno==EINVAL && checked==0){
59             checked=-1;
60         }else{
61             checked=1;
62             
63             val->tv_sec=spec.tv_sec;
64             val->tv_usec=spec.tv_nsec/1000;
65         
66             return ret;
67         }
68     }
69 #else
70     #warning "Monotonic clock unavailable; please fix your operating system."
71 #endif
72     return gettimeofday(val, NULL);
73 }
74
75
76 #define TIMEVAL_LATER(a, b) \
77     ((a.tv_sec > b.tv_sec) || \
78     ((a.tv_sec == b.tv_sec) && \
79      (a.tv_usec > b.tv_usec)))
80
81 #define USECS_IN_SEC 1000000
82
83
84 bool libmainloop_get_timeout(struct timeval *tv)
85 {
86     if(queue==NULL)
87         return FALSE;
88
89     /* Subtract queue time from current time, don't go below zero */
90     mainloop_gettime(tv);
91     if(TIMEVAL_LATER((queue)->when, (*tv))){
92         if(queue->when.tv_usec<tv->tv_usec){
93             queue->when.tv_usec+=USECS_IN_SEC;
94             queue->when.tv_sec--;
95         }
96         tv->tv_usec=queue->when.tv_usec-tv->tv_usec;
97         tv->tv_sec=queue->when.tv_sec-tv->tv_sec;
98         if(tv->tv_usec<0)
99             tv->tv_usec=0;
100         /* POSIX and some kernels have been designed by absolute morons and 
101          * contain idiotic artificial restrictions on the value of tv_usec, 
102          * that will only cause more code being run and clock cycles being 
103          * spent to do the same thing, as the kernel will in any case convert
104          * the seconds to some other units.
105          */
106          tv->tv_sec+=tv->tv_usec/USECS_IN_SEC;
107          tv->tv_usec%=USECS_IN_SEC;
108     }else{
109         had_tmr=TRUE;
110         return FALSE;
111     }
112     
113     return TRUE;
114 }
115
116
117 static void do_timer_set()
118 {
119     struct itimerval val={{0, 0}, {0, 0}};
120     
121     if(libmainloop_get_timeout(&val.it_value)){
122         val.it_interval.tv_usec=0;
123         val.it_interval.tv_sec=0;
124         
125         if((setitimer(ITIMER_REAL, &val, NULL)))
126             had_tmr=TRUE;
127     }else if(!had_tmr){
128         setitimer(ITIMER_REAL, &val, NULL);
129     }
130 }
131
132
133 typedef struct{
134     pid_t pid;
135     int code;
136 } ChldParams;
137
138
139 static bool mrsh_chld(void (*fn)(pid_t, int), ChldParams *p)
140 {
141     fn(p->pid, p->code);
142     return TRUE;
143 }
144
145
146 static bool mrsh_chld_extl(ExtlFn fn, ChldParams *p)
147 {
148     ExtlTab t=extl_create_table();
149     bool ret;
150
151     extl_table_sets_i(t, "pid", (int)p->pid);
152     
153     if(WIFEXITED(p->code)){
154         extl_table_sets_b(t, "exited", TRUE);
155         extl_table_sets_i(t, "exitstatus", WEXITSTATUS(p->code));
156     }
157     if(WIFSIGNALED(p->code)){
158         extl_table_sets_b(t, "signaled", TRUE);
159         extl_table_sets_i(t, "termsig", WTERMSIG(p->code));
160 #ifdef WCOREDUMP 
161         extl_table_sets_i(t, "coredump", WCOREDUMP(p->code));
162 #endif
163     }
164     if(WIFSTOPPED(p->code)){
165         extl_table_sets_b(t, "stopped", TRUE);
166         extl_table_sets_i(t, "stopsig", WSTOPSIG(p->code));
167     }
168     /*if(WIFCONTINUED(p->code)){
169         extl_table_sets_b(t, "continued", TRUE);
170     }*/
171     
172     ret=extl_call(fn, "t", NULL, t);
173     
174     extl_unref_table(t);
175     
176     return ret;
177 }
178
179 static bool mrsh_usr2(void (*fn)(void), void *p)
180 {
181     fn();
182     return TRUE;
183 }
184
185 static bool mrsh_usr2_extl(ExtlFn fn, void *p)
186 {
187     bool ret;
188     ExtlTab t=extl_create_table();
189     ret=extl_call(fn, "t", NULL, t);
190     extl_unref_table(t);
191     return ret;
192 }
193
194
195 bool mainloop_check_signals()
196 {
197     struct timeval current_time;
198     WTimer *q;
199     int ret=0;
200
201     if(usr2_sig!=0){
202         usr2_sig=0;
203         if(mainloop_sigusr2_hook!=NULL){
204             hook_call(mainloop_sigusr2_hook, NULL,
205                       (WHookMarshall*)mrsh_usr2,
206                       (WHookMarshallExtl*)mrsh_usr2_extl);
207         }
208     }
209
210 #if 1    
211     if(wait_sig!=0){
212         ChldParams p;
213         wait_sig=0;
214         while((p.pid=waitpid(-1, &p.code, WNOHANG|WUNTRACED))>0){
215             if(mainloop_sigchld_hook!=NULL &&
216                (WIFEXITED(p.code) || WIFSIGNALED(p.code))){
217                 hook_call(mainloop_sigchld_hook, &p, 
218                           (WHookMarshall*)mrsh_chld,
219                           (WHookMarshallExtl*)mrsh_chld_extl);
220             }
221         }
222     }
223 #endif
224     
225     if(kill_sig!=0)
226         return kill_sig;
227
228     /* Check for timer events in the queue */
229     while(had_tmr && queue!=NULL){
230         had_tmr=FALSE;
231         mainloop_gettime(&current_time);
232         while(queue!=NULL){
233             if(TIMEVAL_LATER(current_time, queue->when)){
234                 q=queue;
235                 queue=q->next;
236                 q->next=NULL;
237                 if(q->handler!=NULL){
238                     WTimerHandler *handler=q->handler;
239                     Obj *obj=q->objwatch.obj;
240                     q->handler=NULL;
241                     watch_reset(&(q->objwatch));
242                     handler(q, obj);
243                 }else if(q->extl_handler!=extl_fn_none()){
244                     ExtlFn fn=q->extl_handler;
245                     Obj *obj=q->objwatch.obj;
246                     watch_reset(&(q->objwatch));
247                     q->extl_handler=extl_fn_none();
248                     extl_call(fn, "o", NULL, obj);
249                     extl_unref_fn(fn);
250                 }
251             }else{
252                 break;
253             }
254         }
255         do_timer_set();
256     }
257     
258     return ret;
259 }
260
261
262 void mainloop_block_signals(sigset_t *oldmask)
263 {
264     sigprocmask(SIG_BLOCK, &special_sigs, oldmask);
265 }
266
267
268 bool mainloop_unhandled_signals()
269 {
270     return (usr2_sig || wait_sig || kill_sig || had_tmr);
271 }
272
273
274 static void add_to_current_time(struct timeval *when, uint msecs)
275 {
276     long tmp_usec;
277
278     mainloop_gettime(when);
279     tmp_usec=when->tv_usec + (msecs * 1000);
280     when->tv_usec=tmp_usec % 1000000;
281     when->tv_sec+=tmp_usec / 1000000;
282 }
283
284
285 /*EXTL_DOC
286  * Is timer set?
287  */
288 EXTL_EXPORT_MEMBER
289 bool timer_is_set(WTimer *timer)
290 {
291     WTimer *tmr;
292     for(tmr=queue; tmr!=NULL; tmr=tmr->next){
293         if(tmr==timer)
294             return TRUE;
295     }
296     return FALSE;
297 }
298
299
300 void timer_do_set(WTimer *timer, uint msecs, WTimerHandler *handler,
301                   Obj *obj, ExtlFn fn)
302 {
303     WTimer *q, **qptr;
304     bool set=FALSE;
305     
306     timer_reset(timer);
307
308     /* Initialize the new queue timer event */
309     add_to_current_time(&(timer->when), msecs);
310     timer->next=NULL;
311     timer->handler=handler;
312     timer->extl_handler=fn;
313     if(obj!=NULL)
314         watch_setup(&(timer->objwatch), obj, NULL);
315     else
316         watch_reset(&(timer->objwatch));
317
318     /* Add timerevent in place to queue */
319     q=queue;
320     qptr=&queue;
321     
322     while(q!=NULL){
323         if(TIMEVAL_LATER(q->when, timer->when))
324             break;
325         qptr=&(q->next);
326         q=q->next;
327     }
328     
329     timer->next=q;
330     *qptr=timer;
331
332     do_timer_set();
333 }
334
335
336 void timer_set(WTimer *timer, uint msecs, WTimerHandler *handler,
337                Obj *obj)
338 {
339     timer_do_set(timer, msecs, handler, obj, extl_fn_none());
340 }
341
342
343 /*EXTL_DOC
344  * Set \var{timer} to call \var{fn} in \var{msecs} milliseconds.
345  */
346 EXTL_EXPORT_AS(WTimer, set)
347 void timer_set_extl(WTimer *timer, uint msecs, ExtlFn fn)
348 {
349     timer_do_set(timer, msecs, NULL, NULL, extl_ref_fn(fn));
350 }
351
352     
353 /*EXTL_DOC
354  * Reset timer.
355  */
356 EXTL_EXPORT_MEMBER
357 void timer_reset(WTimer *timer)
358 {
359     WTimer *q=queue, **qptr=&queue;
360     
361     while(q!=NULL){
362         if(q==timer){
363             *qptr=timer->next;
364             do_timer_set();
365             break;
366         }
367         qptr=&(q->next);
368         q=q->next;
369         
370     }
371     
372     timer->handler=NULL;
373     extl_unref_fn(timer->extl_handler);
374     timer->extl_handler=extl_fn_none();
375     watch_reset(&(timer->objwatch));
376 }
377
378
379 bool timer_init(WTimer *timer)
380 {
381     timer->when.tv_sec=0;
382     timer->when.tv_usec=0;
383     timer->next=NULL;
384     timer->handler=NULL;
385     timer->extl_handler=extl_fn_none();
386     watch_init(&(timer->objwatch));
387     return TRUE;
388 }
389
390 void timer_deinit(WTimer *timer)
391 {
392     timer_reset(timer);
393 }
394
395
396 WTimer *create_timer()
397 {
398     CREATEOBJ_IMPL(WTimer, timer, (p));
399 }
400
401 /*EXTL_DOC
402  * Create a new timer.
403  */
404 EXTL_EXPORT_AS(mainloop, create_timer)
405 WTimer *create_timer_extl_owned()
406 {
407     WTimer *timer=create_timer();
408     if(timer!=NULL)
409         ((Obj*)timer)->flags|=OBJ_EXTL_OWNED;
410     return timer;
411 }
412
413
414 EXTL_EXPORT
415 IMPLCLASS(WTimer, Obj, timer_deinit, NULL);
416
417
418 /*}}}*/
419
420
421 /*{{{ Signal handling */
422
423
424 static void fatal_signal_handler(int signal_num)
425 {
426     set_warn_handler(NULL);
427     warn(TR("Caught fatal signal %d. Dying without deinit."), signal_num); 
428     signal(signal_num, SIG_DFL);
429     kill(getpid(), signal_num);
430 }
431
432            
433 static void deadly_signal_handler(int signal_num)
434 {
435     set_warn_handler(NULL);
436     warn(TR("Caught signal %d. Dying."), signal_num);
437     signal(signal_num, SIG_DFL);
438     /*if(ioncore_g.opmode==IONCORE_OPMODE_INIT)
439         kill(getpid(), signal_num);
440     else*/
441         kill_sig=signal_num;
442 }
443
444
445 static void chld_handler(int signal_num)
446 {
447 #if 0
448     pid_t pid;
449
450     while((pid=waitpid(-1, NULL, WNOHANG|WUNTRACED))>0){
451         /* nothing */
452     }
453 #else
454     wait_sig=1;
455 #endif
456 }
457
458 static void usr2_handler(int signal_num)
459 {
460     usr2_sig=1;
461 }
462
463
464 static void exit_handler(int signal_num)
465 {
466     if(kill_sig>0){
467         warn(TR("Got signal %d while %d is still to be handled."),
468              signal_num, kill_sig);
469     }
470     kill_sig=signal_num;
471 }
472
473
474 static void timer_handler(int signal_num)
475 {
476     had_tmr=TRUE;
477 }
478
479
480 static void ignore_handler(int signal_num)
481 {
482     
483 }
484
485
486 #ifndef SA_RESTART
487  /* glibc is broken (?) and does not define SA_RESTART with
488   * '-ansi -D_XOPEN_SOURCE -D_XOPEN_SOURCE_EXTENDED', so just try to live
489   * without it.
490   */
491 #define SA_RESTART 0
492 #endif
493
494 #define IFTRAP(X) if(sigismember(which, X))
495 #define DEADLY(X) IFTRAP(X) signal(X, deadly_signal_handler);
496 #define FATAL(X) IFTRAP(X) signal(X, fatal_signal_handler);
497 #define IGNORE(X) IFTRAP(X) signal(X, SIG_IGN)
498
499
500 void mainloop_trap_signals(const sigset_t *which)
501 {
502     struct sigaction sa;
503     sigset_t set, oldset;
504     sigset_t dummy;
505
506     if(which==NULL){
507         sigfillset(&dummy);
508         which=&dummy;
509     }
510     
511     sigemptyset(&special_sigs);
512     sigemptyset(&set);
513     sigemptyset(&oldset);
514     sigprocmask(SIG_SETMASK, &set, &oldset);
515     
516     DEADLY(SIGHUP);
517     DEADLY(SIGQUIT);
518     DEADLY(SIGINT);
519     DEADLY(SIGABRT);
520
521     FATAL(SIGILL);
522     FATAL(SIGSEGV);
523     FATAL(SIGFPE);
524     FATAL(SIGBUS);
525     
526     IGNORE(SIGTRAP);
527     /*IGNORE(SIGWINCH);*/
528
529     sigemptyset(&(sa.sa_mask));
530
531     IFTRAP(SIGALRM){
532         sa.sa_handler=timer_handler;
533         sa.sa_flags=SA_RESTART;
534         sigaction(SIGALRM, &sa, NULL);
535         sigaddset(&special_sigs, SIGALRM);
536     }
537
538     IFTRAP(SIGCHLD){
539         sa.sa_handler=chld_handler;
540         sa.sa_flags=SA_NOCLDSTOP|SA_RESTART;
541         sigaction(SIGCHLD, &sa, NULL);
542         sigaddset(&special_sigs, SIGCHLD);
543     }
544
545     IFTRAP(SIGUSR2){
546         sa.sa_handler=usr2_handler;
547         sa.sa_flags=SA_RESTART;
548         sigaction(SIGUSR2, &sa, NULL);
549         sigaddset(&special_sigs, SIGUSR2);
550     }
551
552     IFTRAP(SIGTERM){
553         sa.sa_handler=exit_handler;
554         sa.sa_flags=SA_RESTART;
555         sigaction(SIGTERM, &sa, NULL);
556         sigaddset(&special_sigs, SIGTERM);
557     }
558     
559     IFTRAP(SIGUSR1){
560         sa.sa_handler=exit_handler;
561         sa.sa_flags=SA_RESTART;
562         sigaction(SIGUSR1, &sa, NULL);
563     }
564     
565     /* SIG_IGN is preserved over execve and since the the default action
566      * for SIGPIPE is not to ignore it, some programs may get upset if
567      * the behaviour is not the default.
568      */
569     IFTRAP(SIGPIPE){
570         sa.sa_handler=ignore_handler;
571         sigaction(SIGPIPE, &sa, NULL);
572     }
573
574 }
575
576 #undef IGNORE
577 #undef FATAL
578 #undef DEADLY
579
580
581 /*}}}*/
582