beecrypt-3.0.0 merge: doxygen pass.
[platform/upstream/rpm.git] / rpmio / rpmsq.c
1 /** \ingroup rpmio
2  * \file rpmio/rpmsq.c
3  */
4
5 #include "system.h"
6
7 #if defined(__LCLINT__)
8 #define _BITS_SIGTHREAD_H       /* XXX avoid __sigset_t heartburn. */
9
10 /*@-exportheader@*/
11 /*@constant int SA_SIGINFO@*/
12 extern int sighold(int sig)
13         /*@globals errno, systemState @*/;
14 extern int sigignore(int sig)
15         /*@globals errno, systemState @*/;
16 extern int sigpause(int sig)
17         /*@globals errno, systemState @*/;
18 extern int sigrelse(int sig)
19         /*@globals errno, systemState @*/;
20 extern void (*sigset(int sig, void (*disp)(int)))(int)
21         /*@globals errno, systemState @*/;
22
23 struct qelem;
24 extern  void insque(struct qelem * __elem, struct qelem * __prev)
25         /*@modifies  __elem, __prev @*/;
26 extern  void remque(struct qelem * __elem)
27         /*@modifies  __elem @*/;
28
29 extern pthread_t pthread_self(void)
30         /*@*/;
31 extern int pthread_equal(pthread_t t1, pthread_t t2)
32         /*@*/;
33
34 extern int pthread_create(/*@out@*/ pthread_t *restrict thread,
35                 const pthread_attr_t *restrict attr,
36                 void *(*start_routine)(void*), void *restrict arg)
37         /*@modifies *thread @*/;
38 extern int pthread_join(pthread_t thread, /*@out@*/ void **value_ptr)
39         /*@modifies *value_ptr @*/;
40
41 extern int pthread_setcancelstate(int state, /*@out@*/ int *oldstate)
42         /*@globals internalState @*/
43         /*@modifies *oldstate, internalState @*/;
44 extern int pthread_setcanceltype(int type, /*@out@*/ int *oldtype)
45         /*@globals internalState @*/
46         /*@modifies *oldtype, internalState @*/;
47 extern void pthread_testcancel(void)
48         /*@globals internalState @*/
49         /*@modifies internalState @*/;
50 extern void pthread_cleanup_pop(int execute)
51         /*@globals internalState @*/
52         /*@modifies internalState @*/;
53 extern void pthread_cleanup_push(void (*routine)(void*), void *arg)
54         /*@globals internalState @*/
55         /*@modifies internalState @*/;
56 extern void _pthread_cleanup_pop(/*@out@*/ struct _pthread_cleanup_buffer *__buffer, int execute)
57         /*@globals internalState @*/
58         /*@modifies internalState @*/;
59 extern void _pthread_cleanup_push(/*@out@*/ struct _pthread_cleanup_buffer *__buffer, void (*routine)(void*), /*@out@*/ void *arg)
60         /*@globals internalState @*/
61         /*@modifies internalState @*/;
62
63 extern int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
64         /*@modifies *attr @*/;
65 extern int pthread_mutexattr_init(/*@out@*/ pthread_mutexattr_t *attr)
66         /*@modifies *attr @*/;
67
68 int pthread_mutexattr_gettype(const pthread_mutexattr_t *restrict attr,
69                 /*@out@*/ int *restrict type)
70         /*@modifies *type @*/;
71 int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
72         /*@modifies *attr @*/;
73
74 extern int pthread_mutex_destroy(pthread_mutex_t *mutex)
75         /*@modifies *mutex @*/;
76 extern int pthread_mutex_init(/*@out@*/ pthread_mutex_t *restrict mutex,
77                 /*@null@*/ const pthread_mutexattr_t *restrict attr)
78         /*@modifies *mutex @*/;
79
80 extern int pthread_mutex_lock(pthread_mutex_t *mutex)
81         /*@modifies *mutex @*/;
82 extern int pthread_mutex_trylock(pthread_mutex_t *mutex)
83         /*@modifies *mutex @*/;
84 extern int pthread_mutex_unlock(pthread_mutex_t *mutex)
85         /*@modifies *mutex @*/;
86
87 extern int pthread_cond_destroy(pthread_cond_t *cond)
88         /*@modifies *cond @*/;
89 extern int pthread_cond_init(/*@out@*/ pthread_cond_t *restrict cond,
90                 const pthread_condattr_t *restrict attr)
91         /*@modifies *cond @*/;
92
93 extern int pthread_cond_timedwait(pthread_cond_t *restrict cond,
94                 pthread_mutex_t *restrict mutex,
95                 const struct timespec *restrict abstime)
96         /*@modifies *cond, *mutex @*/;
97 extern int pthread_cond_wait(pthread_cond_t *restrict cond,
98                 pthread_mutex_t *restrict mutex)
99         /*@modifies *cond, *mutex @*/;
100 extern int pthread_cond_broadcast(pthread_cond_t *cond)
101         /*@modifies *cond @*/;
102 extern int pthread_cond_signal(pthread_cond_t *cond)
103         /*@modifies *cond @*/;
104
105 /*@=exportheader@*/
106 #endif
107
108 #include <signal.h>
109 #include <sys/signal.h>
110 #include <sys/wait.h>
111 #include <search.h>
112
113 #if defined(HAVE_PTHREAD_H)
114
115 #include <pthread.h>
116
117 /*@unchecked@*/
118 /*@-type@*/
119 static pthread_mutex_t rpmsigTbl_lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
120 /*@=type@*/
121
122 #define DO_LOCK()       pthread_mutex_lock(&rpmsigTbl_lock);
123 #define DO_UNLOCK()     pthread_mutex_unlock(&rpmsigTbl_lock);
124 #define INIT_LOCK()     \
125     {   pthread_mutexattr_t attr; \
126         (void) pthread_mutexattr_init(&attr); \
127         (void) pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); \
128         (void) pthread_mutex_init (&rpmsigTbl_lock, &attr); \
129         (void) pthread_mutexattr_destroy(&attr); \
130         rpmsigTbl_sigchld->active = 0; \
131     }
132 #define ADD_REF(__tbl)  (__tbl)->active++
133 #define SUB_REF(__tbl)  --(__tbl)->active
134 #define CLEANUP_HANDLER(__handler, __arg, __oldtypeptr) \
135     (void) pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, (__oldtypeptr));\
136         pthread_cleanup_push((__handler), (__arg));
137 #define CLEANUP_RESET(__execute, __oldtype) \
138     (void) pthread_cleanup_pop(__execute); \
139     (void) pthread_setcanceltype ((__oldtype), &(__oldtype));
140
141 #define SAME_THREAD(_a, _b)     pthread_equal(((pthread_t)_a), ((pthread_t)_b))
142
143 #define ME()    ((void *)pthread_self())
144
145 #else
146
147 #define DO_LOCK()
148 #define DO_UNLOCK()
149 #define INIT_LOCK()
150 #define ADD_REF(__tbl)  /*@-noeffect@*/ (0) /*@=noeffect@*/
151 #define SUB_REF(__tbl)  /*@-noeffect@*/ (0) /*@=noeffect@*/
152 #define CLEANUP_HANDLER(__handler, __arg, __oldtypeptr)
153 #define CLEANUP_RESET(__execute, __oldtype)
154
155 #define SAME_THREAD(_a, _b)     (42)
156
157 #define ME()    (((void *)getpid()))
158
159 #endif  /* HAVE_PTHREAD_H */
160
161 #include <rpmsq.h>
162
163 #include "debug.h"
164
165 #define _RPMSQ_DEBUG    0
166 /*@unchecked@*/
167 int _rpmsq_debug = _RPMSQ_DEBUG;
168
169 /*@unchecked@*/
170 static struct rpmsqElem rpmsqRock;
171
172 /*@-compmempass@*/
173 /*@unchecked@*/
174 rpmsq rpmsqQueue = &rpmsqRock;
175 /*@=compmempass@*/
176
177 int rpmsqInsert(void * elem, void * prev)
178 {
179     rpmsq sq = (rpmsq) elem;
180     int ret = -1;
181
182     if (sq != NULL) {
183 #ifdef _RPMSQ_DEBUG
184 if (_rpmsq_debug)
185 fprintf(stderr, "    Insert(%p): %p\n", ME(), sq);
186 #endif
187         ret = sighold(SIGCHLD);
188         if (ret == 0) {
189             sq->child = 0;
190             sq->reaped = 0;
191             sq->status = 0;
192             sq->reaper = 1;
193 /*@-bounds@*/
194             sq->pipes[0] = sq->pipes[1] = -1;
195 /*@=bounds@*/
196
197             sq->id = ME();
198             ret = pthread_mutex_init(&sq->mutex, NULL);
199             ret = pthread_cond_init(&sq->cond, NULL);
200             insque(elem, (prev != NULL ? prev : rpmsqQueue));
201             ret = sigrelse(SIGCHLD);
202         }
203     }
204     return ret;
205 }
206
207 int rpmsqRemove(void * elem)
208 {
209     rpmsq sq = (rpmsq) elem;
210     int ret = -1;
211
212     if (elem != NULL) {
213
214 #ifdef _RPMSQ_DEBUG
215 if (_rpmsq_debug)
216 fprintf(stderr, "    Remove(%p): %p\n", ME(), sq);
217 #endif
218         ret = sighold (SIGCHLD);
219         if (ret == 0) {
220             remque(elem);
221             ret = pthread_cond_destroy(&sq->cond);
222             ret = pthread_mutex_destroy(&sq->mutex);
223             sq->id = NULL;
224 /*@-bounds@*/
225             if (sq->pipes[1])   ret = close(sq->pipes[1]);
226             if (sq->pipes[0])   ret = close(sq->pipes[0]);
227             sq->pipes[0] = sq->pipes[1] = -1;
228 /*@=bounds@*/
229 #ifdef  NOTYET  /* rpmpsmWait debugging message needs */
230             sq->reaper = 1;
231             sq->status = 0;
232             sq->reaped = 0;
233             sq->child = 0;
234 #endif
235             ret = sigrelse(SIGCHLD);
236         }
237     }
238     return ret;
239 }
240
241 /*@unchecked@*/
242 sigset_t rpmsqCaught;
243
244 /*@unchecked@*/
245 /*@-fullinitblock@*/
246 static struct rpmsig_s {
247     int signum;
248     void (*handler) (int signum, void * info, void * context);
249     int active;
250     struct sigaction oact;
251 } rpmsigTbl[] = {
252     { SIGINT,   rpmsqAction },
253 #define rpmsigTbl_sigint        (&rpmsigTbl[0])
254     { SIGQUIT,  rpmsqAction },
255 #define rpmsigTbl_sigquit       (&rpmsigTbl[1])
256     { SIGCHLD,  rpmsqAction },
257 #define rpmsigTbl_sigchld       (&rpmsigTbl[2])
258     { SIGHUP,   rpmsqAction },
259 #define rpmsigTbl_sighup        (&rpmsigTbl[3])
260     { SIGTERM,  rpmsqAction },
261 #define rpmsigTbl_sigterm       (&rpmsigTbl[4])
262     { SIGPIPE,  rpmsqAction },
263 #define rpmsigTbl_sigpipe       (&rpmsigTbl[5])
264     { -1,       NULL },
265 };
266 /*@=fullinitblock@*/
267
268 void rpmsqAction(int signum,
269                 /*@unused@*/ void * info, /*@unused@*/ void * context)
270 {
271     int save = errno;
272     rpmsig tbl;
273
274     for (tbl = rpmsigTbl; tbl->signum >= 0; tbl++) {
275         if (tbl->signum != signum)
276             continue;
277
278         (void) sigaddset(&rpmsqCaught, signum);
279
280         switch (signum) {
281         case SIGCHLD:
282             while (1) {
283                 rpmsq sq;
284                 int status = 0;
285                 pid_t reaped = waitpid(0, &status, WNOHANG);
286
287                 /* XXX errno set to ECHILD/EINVAL/EINTR. */
288                 if (reaped <= 0)
289                     /*@innerbreak@*/ break;
290
291                 /* XXX insque(3)/remque(3) are dequeue, not ring. */
292                 for (sq = rpmsqQueue->q_forw;
293                      sq != NULL && sq != rpmsqQueue;
294                      sq = sq->q_forw)
295                 {
296                     if (sq->child != reaped)
297                         /*@innercontinue@*/ continue;
298                     sq->reaped = reaped;
299                     sq->status = status;
300                     (void) pthread_cond_signal(&sq->cond);
301                     /*@innerbreak@*/ break;
302                 }
303             }
304             /*@switchbreak@*/ break;
305         default:
306             /*@switchbreak@*/ break;
307         }
308         break;
309     }
310     errno = save;
311 }
312
313 int rpmsqEnable(int signum, /*@null@*/ rpmsqAction_t handler)
314         /*@globals rpmsigTbl @*/
315         /*@modifies rpmsigTbl @*/
316 {
317     int tblsignum = (signum >= 0 ? signum : -signum);
318     struct sigaction sa;
319     rpmsig tbl;
320     int ret = -1;
321
322     (void) DO_LOCK ();
323     if (rpmsqQueue->id == NULL)
324         rpmsqQueue->id = ME();
325     for (tbl = rpmsigTbl; tbl->signum >= 0; tbl++) {
326         if (tblsignum != tbl->signum)
327             continue;
328
329         if (signum >= 0) {                      /* Enable. */
330             if (ADD_REF(tbl) <= 0) {
331                 (void) sigdelset(&rpmsqCaught, tbl->signum);
332                 (void) sigemptyset (&sa.sa_mask);
333 /*@-compdef -type @*/
334                 sa.sa_flags = SA_SIGINFO;
335                 sa.sa_sigaction = (handler != NULL ? handler : tbl->handler);
336                 if (sigaction(tbl->signum, &sa, &tbl->oact) < 0) {
337                     SUB_REF(tbl);
338                     break;
339                 }
340 /*@=compdef =type @*/
341                 tbl->active = 1;                /* XXX just in case */
342                 if (handler != NULL)
343                     tbl->handler = handler;
344             }
345         } else {                                /* Disable. */
346             if (SUB_REF(tbl) <= 0) {
347                 if (sigaction(tbl->signum, &tbl->oact, NULL) < 0)
348                     break;
349                 tbl->active = 0;                /* XXX just in case */
350                 tbl->handler = (handler != NULL ? handler : rpmsqAction);
351             }
352         }
353         ret = tbl->active;
354         break;
355     }
356     (void) DO_UNLOCK ();
357     return ret;
358 }
359
360 pid_t rpmsqFork(rpmsq sq)
361 {
362     pid_t pid;
363     int xx;
364
365     if (sq->reaper) {
366         xx = rpmsqInsert(sq, NULL);
367 #ifdef _RPMSQ_DEBUG
368 if (_rpmsq_debug)
369 fprintf(stderr, "    Enable(%p): %p\n", ME(), sq);
370 #endif
371         xx = rpmsqEnable(SIGCHLD, NULL);
372     }
373
374     xx = pipe(sq->pipes);
375
376     xx = sighold(SIGCHLD);
377
378     pid = fork();
379     if (pid < (pid_t) 0) {              /* fork failed.  */
380 /*@-bounds@*/
381         xx = close(sq->pipes[0]);
382         xx = close(sq->pipes[1]);
383         sq->pipes[0] = sq->pipes[1] = -1;
384 /*@=bounds@*/
385         goto out;
386     } else if (pid == (pid_t) 0) {      /* Child. */
387         int yy;
388
389         /* Block to permit parent to wait. */
390 /*@-bounds@*/
391         xx = close(sq->pipes[1]);
392         xx = read(sq->pipes[0], &yy, sizeof(yy));
393         xx = close(sq->pipes[0]);
394         sq->pipes[0] = sq->pipes[1] = -1;
395 /*@=bounds@*/
396
397 #ifdef _RPMSQ_DEBUG
398 if (_rpmsq_debug)
399 fprintf(stderr, "     Child(%p): %p child %d\n", ME(), sq, getpid());
400 #endif
401
402     } else {                            /* Parent. */
403
404         sq->child = pid;
405
406 #ifdef _RPMSQ_DEBUG
407 if (_rpmsq_debug)
408 fprintf(stderr, "    Parent(%p): %p child %d\n", ME(), sq, sq->child);
409 #endif
410
411     }
412
413 out:
414     xx = sigrelse(SIGCHLD);
415     return sq->child;
416 }
417
418 /**
419  * Wait for child process to be reaped, and unregister SIGCHLD handler.
420  * @param sq            scriptlet queue element
421  * @return              0 on success
422  */
423 static int rpmsqWaitUnregister(rpmsq sq)
424         /*@globals fileSystem, internalState @*/
425         /*@modifies sq, fileSystem, internalState @*/
426 {
427     int same_thread = 0;
428     int ret = 0;
429     int xx;
430
431     if (same_thread)
432         ret = sighold(SIGCHLD);
433     else
434         ret = pthread_mutex_lock(&sq->mutex);
435
436     /* Start the child. */
437 /*@-bounds@*/
438     if (sq->pipes[0] >= 0)
439         xx = close(sq->pipes[0]);
440     if (sq->pipes[1] >= 0)
441         xx = close(sq->pipes[1]);
442     sq->pipes[0] = sq->pipes[1] = -1;
443 /*@=bounds@*/
444
445     (void) rpmswEnter(&sq->op, -1);
446
447     /*@-infloops@*/
448     while (ret == 0 && sq->reaped != sq->child) {
449         if (same_thread)
450             ret = sigpause(SIGCHLD);
451         else
452             ret = pthread_cond_wait(&sq->cond, &sq->mutex);
453     }
454     /*@=infloops@*/
455
456     sq->ms_scriptlets += rpmswExit(&sq->op, -1)/1000;
457
458     if (same_thread)
459         xx = sigrelse(SIGCHLD);
460     else
461         xx = pthread_mutex_unlock(&sq->mutex);
462
463 #ifdef _RPMSQ_DEBUG
464 if (_rpmsq_debug)
465 fprintf(stderr, "      Wake(%p): %p child %d reaper %d ret %d\n", ME(), sq, sq->child, sq->reaper, ret);
466 #endif
467
468     xx = rpmsqRemove(sq);
469     xx = rpmsqEnable(-SIGCHLD, NULL);
470 #ifdef _RPMSQ_DEBUG
471 if (_rpmsq_debug)
472 fprintf(stderr, "   Disable(%p): %p\n", ME(), sq);
473 #endif
474
475     return ret;
476 }
477
478 pid_t rpmsqWait(rpmsq sq)
479 {
480
481 #ifdef _RPMSQ_DEBUG
482 if (_rpmsq_debug)
483 fprintf(stderr, "      Wait(%p): %p child %d reaper %d\n", ME(), sq, sq->child, sq->reaper);
484 #endif
485
486     if (sq->reaper) {
487         (void) rpmsqWaitUnregister(sq);
488     } else {
489         pid_t reaped;
490         int status;
491         do {
492             reaped = waitpid(sq->child, &status, 0);
493         } while (reaped >= 0 && reaped != sq->child);
494         sq->reaped = reaped;
495         sq->status = status;
496 #ifdef _RPMSQ_DEBUG
497 if (_rpmsq_debug)
498 fprintf(stderr, "   Waitpid(%p): %p child %d reaped %d\n", ME(), sq, sq->child, sq->reaped);
499 #endif
500     }
501
502 #ifdef _RPMSQ_DEBUG
503 if (_rpmsq_debug)
504 fprintf(stderr, "      Fini(%p): %p child %d status 0x%x\n", ME(), sq, sq->child, sq->status);
505 #endif
506
507     return sq->reaped;
508 }
509
510 void * rpmsqThread(void * (*start) (void * arg), void * arg)
511 {
512     pthread_t pth;
513     int ret;
514
515     ret = pthread_create(&pth, NULL, start, arg);
516     return (ret == 0 ? (void *)pth : NULL);
517 }
518
519 int rpmsqJoin(void * thread)
520 {
521     pthread_t pth = (pthread_t) thread;
522     if (thread == NULL)
523         return EINVAL;
524     return pthread_join(pth, NULL);
525 }
526
527 int rpmsqThreadEqual(void * thread)
528 {
529     pthread_t t1 = (pthread_t) thread;
530     pthread_t t2 = pthread_self();
531     return pthread_equal(t1, t2);
532 }
533
534 /**
535  * SIGCHLD cancellation handler.
536  */
537 static void
538 sigchld_cancel (void *arg)
539         /*@globals rpmsigTbl, fileSystem, internalState @*/
540         /*@modifies rpmsigTbl, fileSystem, internalState @*/
541 {
542     pid_t child = *(pid_t *) arg;
543     pid_t result;
544
545     (void) kill(child, SIGKILL);
546
547     do {
548         result = waitpid(child, NULL, 0);
549     } while (result == (pid_t)-1 && errno == EINTR);
550
551     (void) DO_LOCK ();
552     if (SUB_REF (rpmsigTbl_sigchld) == 0) {
553         (void) rpmsqEnable(-SIGQUIT, NULL);
554         (void) rpmsqEnable(-SIGINT, NULL);
555     }
556     (void) DO_UNLOCK ();
557 }
558
559 /**
560  * Execute a command, returning its status.
561  */
562 int
563 rpmsqExecve (const char ** argv)
564         /*@globals rpmsigTbl @*/
565         /*@modifies rpmsigTbl @*/
566 {
567     int oldtype;
568     int status = -1;
569     pid_t pid = 0;
570     pid_t result;
571     sigset_t newMask, oldMask;
572     rpmsq sq = memset(alloca(sizeof(*sq)), 0, sizeof(*sq));
573
574     (void) DO_LOCK ();
575     if (ADD_REF (rpmsigTbl_sigchld) == 0) {
576         if (rpmsqEnable(SIGINT, NULL) < 0) {
577             SUB_REF (rpmsigTbl_sigchld);
578             goto out;
579         }
580         if (rpmsqEnable(SIGQUIT, NULL) < 0) {
581             SUB_REF (rpmsigTbl_sigchld);
582             goto out_restore_sigint;
583         }
584     }
585     (void) DO_UNLOCK ();
586
587     (void) sigemptyset (&newMask);
588     (void) sigaddset (&newMask, SIGCHLD);
589     if (sigprocmask (SIG_BLOCK, &newMask, &oldMask) < 0) {
590         (void) DO_LOCK ();
591         if (SUB_REF (rpmsigTbl_sigchld) == 0)
592             goto out_restore_sigquit_and_sigint;
593         goto out;
594     }
595
596     CLEANUP_HANDLER(sigchld_cancel, &pid, &oldtype);
597
598     pid = fork ();
599     if (pid < (pid_t) 0) {              /* fork failed.  */
600         goto out;
601     } else if (pid == (pid_t) 0) {      /* Child. */
602
603         /* Restore the signals.  */
604         (void) sigaction (SIGINT, &rpmsigTbl_sigint->oact, NULL);
605         (void) sigaction (SIGQUIT, &rpmsigTbl_sigquit->oact, NULL);
606         (void) sigprocmask (SIG_SETMASK, &oldMask, NULL);
607
608         /* Reset rpmsigTbl lock and refcnt. */
609         INIT_LOCK ();
610
611         (void) execve (argv[0], (char *const *) argv, environ);
612         _exit (127);
613     } else {                            /* Parent. */
614         do {
615             result = waitpid(pid, &status, 0);
616         } while (result == (pid_t)-1 && errno == EINTR);
617         if (result != pid)
618             status = -1;
619     }
620
621     CLEANUP_RESET(0, oldtype);
622
623     (void) DO_LOCK ();
624     if ((SUB_REF (rpmsigTbl_sigchld) == 0 &&
625         (rpmsqEnable(-SIGINT, NULL) < 0 || rpmsqEnable (-SIGQUIT, NULL) < 0))
626       || sigprocmask (SIG_SETMASK, &oldMask, NULL) != 0)
627     {
628         status = -1;
629     }
630     goto out;
631
632 out_restore_sigquit_and_sigint:
633     (void) rpmsqEnable(-SIGQUIT, NULL);
634 out_restore_sigint:
635     (void) rpmsqEnable(-SIGINT, NULL);
636 out:
637     (void) DO_UNLOCK ();
638     return status;
639 }