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