vdr 2.8.3
thread.c
Go to the documentation of this file.
1/*
2 * thread.c: A simple thread base class
3 *
4 * See the main source file 'vdr.c' for copyright information and
5 * how to reach the author.
6 *
7 * $Id: thread.c 5.10 2026/08/31 10:48:15 kls Exp $
8 */
9
10#include "thread.h"
11#include <cxxabi.h>
12#include <dlfcn.h>
13#include <errno.h>
14#include <execinfo.h>
15#include <linux/unistd.h>
16#include <malloc.h>
17#include <stdarg.h>
18#include <stdlib.h>
19#include <sys/prctl.h>
20#include <sys/resource.h>
21#include <sys/syscall.h>
22#include <sys/time.h>
23#include <sys/wait.h>
24#include <unistd.h>
25#include "tools.h"
26
27#define ABORT { dsyslog("ABORT!"); cBackTrace::BackTrace(); abort(); }
28
29//#define DEBUG_LOCKING // uncomment this line to activate debug output for locking
30#define DEBUG_LOCKSEQ // uncomment this line to activate debug output for invalid locking sequence
31//#define DEBUG_LOCKCALL // uncomment this line to activate caller information with DEBUG_LOCKSEQ (WARNING: expensive operation, use only when actually debugging the locking sequence!)
32
33#ifdef DEBUG_LOCKING
34#define dbglocking(a...) fprintf(stderr, a)
35#else
36#define dbglocking(a...)
37#endif
38
39static bool GetAbsTime(struct timespec *Abstime, int MillisecondsFromNow)
40{
41 struct timeval now;
42 if (gettimeofday(&now, NULL) == 0) { // get current time
43 MillisecondsFromNow = max(MillisecondsFromNow, 3); // // making sure the time is >2ms to avoid possible busy waits
44 now.tv_sec += MillisecondsFromNow / 1000; // add full seconds
45 now.tv_usec += (MillisecondsFromNow % 1000) * 1000; // add microseconds
46 if (now.tv_usec >= 1000000) { // take care of an overflow
47 now.tv_sec++;
48 now.tv_usec -= 1000000;
49 }
50 Abstime->tv_sec = now.tv_sec; // seconds
51 Abstime->tv_nsec = now.tv_usec * 1000; // nano seconds
52 return true;
53 }
54 return false;
55}
56
57// --- cCondWait -------------------------------------------------------------
58
60{
61 signaled = false;
62 pthread_mutex_init(&mutex, NULL);
63 pthread_cond_init(&cond, NULL);
64}
65
67{
68 pthread_cond_broadcast(&cond); // wake up any sleepers
69 pthread_cond_destroy(&cond);
70 pthread_mutex_destroy(&mutex);
71}
72
73void cCondWait::SleepMs(int TimeoutMs)
74{
75 cCondWait w;
76 w.Wait(max(TimeoutMs, 3)); // making sure the time is >2ms to avoid a possible busy wait
77}
78
79bool cCondWait::Wait(int TimeoutMs)
80{
81 pthread_mutex_lock(&mutex);
82 if (!signaled) {
83 if (TimeoutMs) {
84 struct timespec abstime;
85 if (GetAbsTime(&abstime, TimeoutMs)) {
86 while (!signaled) {
87 if (pthread_cond_timedwait(&cond, &mutex, &abstime) == ETIMEDOUT)
88 break;
89 }
90 }
91 }
92 else
93 pthread_cond_wait(&cond, &mutex);
94 }
95 bool r = signaled;
96 signaled = false;
97 pthread_mutex_unlock(&mutex);
98 return r;
99}
100
102{
103 pthread_mutex_lock(&mutex);
104 signaled = true;
105 pthread_cond_broadcast(&cond);
106 pthread_mutex_unlock(&mutex);
107}
108
109// --- cCondVar --------------------------------------------------------------
110
112{
113 pthread_cond_init(&cond, 0);
114}
115
117{
118 pthread_cond_broadcast(&cond); // wake up any sleepers
119 pthread_cond_destroy(&cond);
120}
121
123{
124 if (Mutex.locked) {
125 int locked = Mutex.locked;
126 Mutex.locked = 0; // have to clear the locked count here, as pthread_cond_wait
127 // does an implicit unlock of the mutex
128 Mutex.lockThreadId = 0;
129 pthread_cond_wait(&cond, &Mutex.mutex);
130 Mutex.lockThreadId = cThread::ThreadId(); // pthread_cond_wait re-locked the mutex without going through cMutex::Lock()
131 Mutex.locked = locked;
132 }
133}
134
135bool cCondVar::TimedWait(cMutex &Mutex, int TimeoutMs)
136{
137 bool r = true; // true = condition signaled, false = timeout
138
139 if (Mutex.locked) {
140 struct timespec abstime;
141 if (GetAbsTime(&abstime, TimeoutMs)) {
142 int locked = Mutex.locked;
143 Mutex.locked = 0; // have to clear the locked count here, as pthread_cond_timedwait
144 // does an implicit unlock of the mutex.
145 Mutex.lockThreadId = 0;
146 if (pthread_cond_timedwait(&cond, &Mutex.mutex, &abstime) == ETIMEDOUT)
147 r = false;
148 Mutex.lockThreadId = cThread::ThreadId(); // pthread_cond_timedwait re-locked the mutex without going through cMutex::Lock()
149 Mutex.locked = locked;
150 }
151 }
152 return r;
153}
154
156{
157 pthread_cond_broadcast(&cond);
158}
159
160// --- cRwLock ---------------------------------------------------------------
161
162cRwLock::cRwLock(bool PreferWriter)
163{
164 locked = 0;
166 pthread_rwlockattr_t attr;
167 pthread_rwlockattr_init(&attr);
168 pthread_rwlockattr_setkind_np(&attr, PreferWriter ? PTHREAD_RWLOCK_PREFER_WRITER_NP : PTHREAD_RWLOCK_PREFER_READER_NP);
169 pthread_rwlock_init(&rwlock, &attr);
170}
171
173{
174 pthread_rwlock_destroy(&rwlock);
175}
176
177bool cRwLock::Lock(bool Write, int TimeoutMs)
178{
179 int Result = 0;
180 struct timespec abstime;
181 if (TimeoutMs) {
182 if (!GetAbsTime(&abstime, TimeoutMs))
183 TimeoutMs = 0;
184 }
185 if (Write) {
186 Result = TimeoutMs ? pthread_rwlock_timedwrlock(&rwlock, &abstime) : pthread_rwlock_wrlock(&rwlock);
187 if (Result == 0)
189 }
190 else if (writeLockThreadId == cThread::ThreadId()) {
191 locked++; // there can be any number of stacked read locks, so we keep track here
192 Result = 0; // acquiring a read lock while holding a write lock within the same thread is OK
193 }
194 else
195 Result = TimeoutMs ? pthread_rwlock_timedrdlock(&rwlock, &abstime) : pthread_rwlock_rdlock(&rwlock);
196 return Result == 0;
197}
198
200{
201 if (writeLockThreadId == cThread::ThreadId()) { // this is the thread that obtained the initial write lock
202 if (locked) { // this is the unlock of a read lock within the write lock
203 locked--;
204 return;
205 }
206 }
208 pthread_rwlock_unlock(&rwlock);
209}
210
211// --- cMutex ----------------------------------------------------------------
212
214{
215 lockThreadId = 0;
216 locked = 0;
217 pthread_mutexattr_t attr;
218 pthread_mutexattr_init(&attr);
219 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
220 pthread_mutex_init(&mutex, &attr);
221}
222
224{
225 pthread_mutex_destroy(&mutex);
226}
227
228bool cMutex::Lock(int TimeoutMs, bool *TimedOut)
229{
230 // PTHREAD_MUTEX_ERRORCHECK_NP rejects recursive entry from the same thread; handle the
231 // nested cMutexLock case (documented in thread.h) here, like cRwLock does below:
232 tThreadId ThisThreadId = cThread::ThreadId();
233 if (lockThreadId == ThisThreadId && locked) {
234 locked++;
235 return true;
236 }
237 if (TimeoutMs > 0) {
238 struct timespec abstime;
239 if (!GetAbsTime(&abstime, TimeoutMs) || pthread_mutex_timedlock(&mutex, &abstime) != 0) {
240 if (TimedOut)
241 *TimedOut = true;
242 return false;
243 }
244 }
245 else
246 pthread_mutex_lock(&mutex);
247 lockThreadId = ThisThreadId;
248 locked++;
249 return true;
250}
251
253{
254 if (!--locked) {
255 lockThreadId = 0;
256 pthread_mutex_unlock(&mutex);
257 }
258}
259
260// --- cThread ---------------------------------------------------------------
261
263
264cThread::cThread(const char *Description, bool LowPriority)
265{
266 active = running = false;
267 childTid = 0;
268 childThreadId = 0;
269 description = NULL;
270 if (Description)
271 SetDescription("%s", Description);
272 lowPriority = LowPriority;
273}
274
276{
277 Cancel(); // just in case the derived class didn't call it
278 free(description);
279}
280
281void cThread::SetPriority(int Priority)
282{
283 if (setpriority(PRIO_PROCESS, 0, Priority) < 0)
284 LOG_ERROR;
285}
286
287void cThread::SetIOPriority(int Priority)
288{
289 if (syscall(SYS_ioprio_set, 1, 0, (Priority & 0xff) | (3 << 13)) < 0) // idle class
290 LOG_ERROR;
291}
292
293void cThread::SetDescription(const char *Description, ...)
294{
295 free(description);
296 description = NULL;
297 if (Description) {
298 va_list ap;
299 va_start(ap, Description);
300 description = strdup(cString::vsprintf(Description, ap));
301 va_end(ap);
302 }
303}
304
306{
307 Thread->childThreadId = ThreadId();
308 if (Thread->description) {
309 dsyslog("%s thread started (pid=%d, tid=%d, prio=%s)", Thread->description, getpid(), Thread->childThreadId.load(), Thread->lowPriority ? "low" : "high");
310#ifdef PR_SET_NAME
311 if (prctl(PR_SET_NAME, Thread->description, 0, 0, 0) < 0)
312 esyslog("%s thread naming failed (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId.load());
313#endif
314 }
315 if (Thread->lowPriority) {
316 Thread->SetPriority(19);
317 Thread->SetIOPriority(7);
318 }
319 Thread->Action();
320 if (Thread->description)
321 dsyslog("%s thread ended (pid=%d, tid=%d)", Thread->description, getpid(), Thread->childThreadId.load());
322 Thread->running = false;
323 Thread->active = false;
324 return NULL;
325}
326
327#define THREAD_STOP_TIMEOUT 3000 // ms to wait for a thread to stop before newly starting it
328#define THREAD_STOP_SLEEP 30 // ms to sleep while waiting for a thread to stop
329
331{
332 if (!running) {
333 if (active) {
334 // Wait until the previous incarnation of this thread has completely ended
335 // before starting it newly:
336 cTimeMs RestartTimeout;
337 while (!running && active && RestartTimeout.Elapsed() < THREAD_STOP_TIMEOUT)
339 }
340 if (!active) {
341 active = running = true;
342 if (pthread_create(&childTid, NULL, (void *(*) (void *))&StartThread, (void *)this) == 0) {
343 pthread_detach(childTid); // auto-reap
344 }
345 else {
346 LOG_ERROR;
347 active = running = false;
348 return false;
349 }
350 }
351 }
352 return true;
353}
354
356{
357 if (active) {
358 //
359 // Single UNIX Spec v2 says:
360 //
361 // The pthread_kill() function is used to request
362 // that a signal be delivered to the specified thread.
363 //
364 // As in kill(), if sig is zero, error checking is
365 // performed but no signal is actually sent.
366 //
367 int err;
368 if ((err = pthread_kill(childTid, 0)) != 0) {
369 if (err != ESRCH)
370 LOG_ERROR;
371 childTid = 0;
372 active = running = false;
373 }
374 else
375 return true;
376 }
377 return false;
378}
379
380void cThread::Cancel(int WaitSeconds)
381{
382 running = false;
383 if (active && WaitSeconds > -1) {
384 if (WaitSeconds > 0) {
385 cTimeMs t(WaitSeconds * 1000);
386 while (!t.TimedOut()) {
387 if (!Active())
388 return;
390 }
391 esyslog("ERROR: %s thread %d won't end (waited %d seconds) - canceling it...", description ? description : "", childThreadId.load(), WaitSeconds);
392 }
393 pthread_cancel(childTid);
394 childTid = 0;
395 active = false;
396 }
397}
398
400{
401 // Cache the result in thread-local storage. This is called on every
402 // cMutex::Lock() and every cRwLock operation; the bare syscall costs
403 // ~70ns whereas a TLS read costs ~1.5ns. A thread's id is fixed for its
404 // lifetime, so caching is always safe. Each thread starts with 0 and
405 // fetches its own id on first use.
406 static thread_local tThreadId threadId = 0;
407 if (threadId == 0)
408 threadId = syscall(__NR_gettid);
409 return threadId;
410}
411
413{
414 if (mainThreadId == 0)
416 else
417 esyslog("ERROR: attempt to set main thread id to %d while it already is %d", ThreadId(), mainThreadId);
418}
419
420// --- cMutexLock ------------------------------------------------------------
421
423{
424 mutex = NULL;
425 locked = false;
426 Lock(Mutex);
427}
428
430{
431 if (mutex && locked)
432 mutex->Unlock();
433}
434
435bool cMutexLock::Lock(cMutex *Mutex, int TimeoutMs, bool *TimedOut)
436{
437 if (Mutex && !mutex) {
438 if (!Mutex->Lock(TimeoutMs, TimedOut))
439 return false;
440 mutex = Mutex;
441 locked = true;
442 return true;
443 }
444 return false;
445}
446
447// --- cThreadLock -----------------------------------------------------------
448
450{
451 thread = NULL;
452 locked = false;
453 Lock(Thread);
454}
455
457{
458 if (thread && locked)
459 thread->Unlock();
460}
461
463{
464 if (Thread && !thread) {
465 thread = Thread;
466 Thread->Lock();
467 locked = true;
468 return true;
469 }
470 return false;
471}
472
473// --- cBackTrace ------------------------------------------------------------
474
475#define BT_BUF_SIZE 100
476
478{
479 char *Module = s;
480 char *Function = NULL;
481 char *Offset = NULL;
482 char *Address = NULL;
483 // separate the string:
484 for (char *q = Module; *q; q++) {
485 if (*q == '(') {
486 *q = 0;
487 Function = q + 1;
488 }
489 else if (*q == '+') {
490 *q = 0;
491 Offset = q + 1;
492 }
493 else if (*q == ')')
494 *q = 0;
495 else if (*q == '[')
496 Address = q + 1;
497 else if (*q == ']') {
498 *q = 0;
499 break;
500 }
501 }
502 // demangle the function name:
503 char *DemangledFunction = NULL;
504 if (Function) {
505 int status;
506 DemangledFunction = abi::__cxa_demangle(Function, NULL, 0, &status);
507 if (DemangledFunction)
508 Function = DemangledFunction;
509 if (!*Function)
510 Function = NULL;
511 }
512 cString d = cString::sprintf("%s%s%s", Module, Function ? " " : "", Function ? Function : "");
513 // convert string address to numbers:
514 unsigned long long addr = Address ? strtoull(Address, NULL, 0) : 0;
515 unsigned long long offs = Offset ? strtoull(Offset, NULL, 0) : 0;
516 // for shared libraries we need get the offset inside the library:
517 if (Function) {
518 // check whether the module name ends with ".so*":
519 char *e = Module;
520 char *p = NULL;
521 while (e = strstr(e, ".so"))
522 p = e++;
523 if (p && !strchr(p, '/')) {
524 Dl_info dlinfo;
525 if (dladdr(reinterpret_cast<void*>(addr), &dlinfo)) {
526 if ((strcmp(Module, dlinfo.dli_fname) == 0) && dlinfo.dli_fbase) {
527 unsigned long long base = reinterpret_cast<unsigned long long>(dlinfo.dli_fbase);
528 addr -= base;
529 addr &= 0x0FFFFFFFF; // to make it work on both 32 and 64 bit systems
530 }
531 }
532 }
533 }
534 // determine the file name and line number:
535 cString cmd = cString::sprintf("addr2line --functions --demangle --inlines --basename --exe=%s 0x%llx", Module, Function ? addr : offs);
536 cPipe p;
537 if (p.Open(cmd, "r")) {
538 int n = 0;
539 cReadLine rl;
540 while (char *l = rl.Read(p)) {
541 if (n == 0) {
542 if (Function && strcmp(l, Function))
543 d = cString::sprintf("%s calling %s", *d, l);
544 }
545 else
546 d = cString::sprintf("%s at %s", *d, l);
547 n++;
548 }
549 p.Close();
550 }
551 free(DemangledFunction);
552 return d;
553}
554
555void cBackTrace::BackTrace(cStringList &StringList, int Level, bool Mangled)
556{
557 void *b[BT_BUF_SIZE];
558 int n = backtrace(b, BT_BUF_SIZE);
559 if (char **s = backtrace_symbols(b, n)) {
560 for (int i = max(Level, 0) + 1; i < n; i++) // 1 is the call to this function itself
561 StringList.Append(strdup(Mangled ? s[i] : *Demangle(s[i])));
562 free(s);
563 }
564}
565
566void cBackTrace::BackTrace(FILE *f, int Level, bool Mangled)
567{
568 cStringList sl;
569 BackTrace(sl, Level + 1, Mangled); // 1 is the call to this function itself
570 for (int i = 0; i < sl.Size(); i++) {
571 if (f)
572 fprintf(f, "%s\n", sl[i]);
573 else
574 dsyslog("%s", sl[i]);
575 }
576}
577
578cString cBackTrace::GetCaller(int Level, bool Mangled)
579{
580 cString Caller;
581 Level = max(Level, 0) + 1; // 1 is the call to this function itself
582 void *b[BT_BUF_SIZE];
583 int n = backtrace(b, BT_BUF_SIZE);
584 if (char **s = backtrace_symbols(b, n)) {
585 if (Level < n)
586 Caller = Mangled ? s[Level] : *Demangle(s[Level]);
587 free(s);
588 }
589 return Caller;
590}
591
592// --- cStateLockLog ---------------------------------------------------------
593
594#ifdef DEBUG_LOCKSEQ
595#define SLL_SIZE 20 // the number of log entries
596#define SLL_LENGTH 512 // the maximum length of log entries
597#define SLL_THREADS 20 // the maximum number of threads holding locks at the same time (typically well below 10)
598#define SLL_MAX_LIST 9 // max. number of lists to log
599#define SLL_WRITE_FLAG 0x80000000
600#define SLL_LOCK_FLAG 0x40000000
601
603private:
610#ifdef DEBUG_LOCKCALL
611 char logCaller[SLL_SIZE][SLL_LENGTH];
612#endif
614 bool dumped;
615 void Dump(const char *Name, tThreadId ThreadId);
616public:
617 cStateLockLog(void);
618 void Check(const char *Name, bool Lock, bool Write = false);
619 };
620
622{
623 memset(logThreadIds, 0, sizeof(logThreadIds));
624 memset(logFlags, 0, sizeof(logFlags));
625 memset(logCounter, 0, sizeof(logCounter));
626#ifdef DEBUG_LOCKCALL
627 memset(logCaller, 0, sizeof(logCaller));
628#endif
629 logIndex = 0;
630 dumped = false;
631}
632
633void cStateLockLog::Dump(const char *Name, tThreadId ThreadId)
634{
635 dsyslog("--- begin invalid lock sequence report");
636 dsyslog("TID T C R DR S ST");
637 int LastFlags = 0;
638 for (int i = 0; i < SLL_SIZE; i++) {
639 if (tThreadId tid = logThreadIds[logIndex]) {
640 char msg[SLL_LENGTH];
641 char *q = msg;
642 q += sprintf(q, "%5d", tid);
643 int Flags = logFlags[logIndex];
644 bool Write = Flags & SLL_WRITE_FLAG;
645 bool Lock = Flags & SLL_LOCK_FLAG;
646 Flags &= ~(SLL_WRITE_FLAG | SLL_LOCK_FLAG);
647 int Changed = LastFlags ^ Flags;
648 LastFlags = Flags;
649 for (int i = 0; i <= SLL_MAX_LIST; i++) {
650 char c = '-';
651 int b = 1 << i;
652 if ((Flags & b) != 0)
653 c = '*';
654 if ((Changed & b) != 0)
655 c = Lock ? Write ? 'W' : 'R' : 'U';
656 q += sprintf(q, " %c", c);
657 }
658 q += sprintf(q, " %c", Lock ? 'L' : 'U');
659#ifdef DEBUG_LOCKCALL
660 if (*logCaller[logIndex]) {
661 *q++ = ' ';
662 strn0cpy(q, *cBackTrace::Demangle(logCaller[logIndex]), sizeof(msg) - (q - msg));
663 }
664#endif
665 dsyslog("%s", msg);
666 }
667 if (++logIndex >= SLL_SIZE)
668 logIndex = 0;
669 }
670 dsyslog("%5d invalid lock sequence: %s", ThreadId, Name);
671 dsyslog("full backtrace:");
672 cBackTrace::BackTrace(NULL, 2);
673 dsyslog("--- end invalid lock sequence report");
674 dsyslog("--- THERE WILL BE NO FURTHER REPORTS UNTIL VDR IS RESTARTED!");
675 fprintf(stderr, "invalid lock sequence at %s\n", *DayDateTime(time(NULL)));
676}
677
678void cStateLockLog::Check(const char *Name, bool Lock, bool Write)
679{
680 if (!dumped && Name) {
681 int n = *Name - '0' - 1;
682 if (0 <= n && n < SLL_MAX_LIST) {
683 int b = 1 << n;
684 cMutexLock MutexLock(&mutex);
685 tThreadId ThreadId = cThread::ThreadId();
686 int Index = -1;
687 int AvailableIndex = -1;
688 for (int i = 0; i < threadIds.Size(); i++) {
689 if (ThreadId == threadIds[i]) {
690 Index = i;
691 break;
692 }
693 if (threadIds[i] == 0)
694 AvailableIndex = i;
695 }
696 if (Index < 0) {
697 if (AvailableIndex < 0) {
698 Index = threadIds.Size();
699 threadIds.Append(ThreadId);
700 flags.Append(0);
701 }
702 else {
703 Index = AvailableIndex;
704 threadIds[Index] = ThreadId;
705 }
706 }
707 if (Index >= SLL_THREADS) {
708 // should never happen!
709 esyslog("ERROR: too many threads holding list locks at the same time - stopped logging locks!");
710 dumped = true;
711 return;
712 }
713 bool DoDump = false;
714 if (Lock) {
715 if ((flags[Index] & ~b) < b) // thread holds only "smaller" locks -> OK
716 ;
717 else if ((flags[Index] & b) == 0) // thread already holds "bigger" locks, so it may only re-lock one that it already has!
718 DoDump = true;
719 logCounter[Index][n]++;
720 flags[Index] |= b;
721 }
722 else if (--logCounter[Index][n] == 0)
723 flags[Index] &= ~b;
724 logThreadIds[logIndex] = ThreadId;
725 logFlags[logIndex] = flags[Index] | (Write ? SLL_WRITE_FLAG : 0) | (Lock ? SLL_LOCK_FLAG : 0);
726 if (flags[Index] == 0)
727 threadIds[Index] = 0;
728#ifdef DEBUG_LOCKCALL
729 strn0cpy(logCaller[logIndex], cBackTrace::GetCaller(Lock ? 3 : 5, true), SLL_LENGTH);
730#endif
731 if (++logIndex >= SLL_SIZE)
732 logIndex = 0;
733 if (DoDump) {
734 Dump(Name, ThreadId);
735 dumped = true;
736 }
737 }
738 }
739}
740
742
743#define dbglockseq(n, l, w) StateLockLog.Check(n, l, w)
744#else
745#define dbglockseq(n, l, w)
746#endif // DEBUG_LOCKSEQ
747
748// --- cStateLock ------------------------------------------------------------
749
750cStateLock::cStateLock(const char *Name)
751:rwLock(true)
752{
753 name = Name;
754 threadId = 0;
755 state = 0;
757 syncStateKey = NULL;
758}
759
760bool cStateLock::Lock(cStateKey &StateKey, bool Write, int TimeoutMs)
761{
762 dbglocking("%5d %-12s %10p lock state = %d/%d write = %d timeout = %d\n", cThread::ThreadId(), name, &StateKey, state, StateKey.state, Write, TimeoutMs);
763 StateKey.timedOut = false;
764 if (StateKey.stateLock) {
765 esyslog("ERROR: StateKey already in use in call to cStateLock::Lock() (tid=%d, lock=%s)", StateKey.stateLock->threadId, name);
766 ABORT;
767 return false;
768 }
769 if (rwLock.Lock(Write, TimeoutMs)) {
770 dbglockseq(name, true, Write);
771 StateKey.stateLock = this;
772 if (Write) {
773 dbglocking("%5d %-12s %10p locked write\n", cThread::ThreadId(), name, &StateKey);
775 StateKey.write = true;
776 return true;
777 }
778 else if (state != StateKey.state) {
779 dbglocking("%5d %-12s %10p locked read\n", cThread::ThreadId(), name, &StateKey);
780 return true;
781 }
782 else {
783 dbglocking("%5d %-12s %10p state unchanged\n", cThread::ThreadId(), name, &StateKey);
784 StateKey.stateLock = NULL;
785 dbglockseq(name, false, false);
786 rwLock.Unlock();
787 }
788 }
789 else if (TimeoutMs) {
790 dbglocking("%5d %-12s %10p timeout\n", cThread::ThreadId(), name, &StateKey);
791 StateKey.timedOut = true;
792 }
793 else if (threadId == cThread::ThreadId()) {
794 static bool DoubleWriteLockReported = false;
795 if (!DoubleWriteLockReported) {
796 dsyslog("WARNING: attempt to acquire write lock while already holding a write lock in the same thread - this may crash! (backtrace follows)");
798 DoubleWriteLockReported = true;
799 }
800 }
801 return false;
802}
803
804void cStateLock::Unlock(cStateKey &StateKey, bool IncState)
805{
806 dbglocking("%5d %-12s %10p unlock state = %d/%d inc = %d\n", cThread::ThreadId(), name, &StateKey, state, StateKey.state, IncState);
807 if (StateKey.stateLock != this) {
808 esyslog("ERROR: cStateLock::Unlock() called with an unused key (tid=%d, lock=%s)", threadId, name);
809 ABORT;
810 return;
811 }
812 if (StateKey.write && threadId != cThread::ThreadId()) {
813 esyslog("ERROR: cStateLock::Unlock() called without holding a write lock (tid=%d, lock=%s)", threadId, name);
814 ABORT;
815 return;
816 }
817 if (StateKey.write && (IncState && explicitModify != emArmed || explicitModify == emEnabled)) {
820 state++;
821 }
822 StateKey.state = state;
823 StateKey.stateLock = NULL;
824 if (StateKey.write) {
825 StateKey.write = false;
826 threadId = 0;
828 syncStateKey = NULL;
829 }
830 dbglockseq(name, false, false);
831 rwLock.Unlock();
832}
833
835{
836 dbglocking("%5d %-12s %10p SetSyncStateKey\n", cThread::ThreadId(), name, &StateKey);
837 if (threadId != cThread::ThreadId()) {
838 esyslog("ERROR: cStateLock::SetSyncStateKey() called without holding a write lock (tid=%d, lock=%s)", threadId, name);
839 ABORT;
840 return;
841 }
842 if (StateKey.stateLock == this) {
843 esyslog("ERROR: cStateLock::SetSyncStateKey() called with locked key (tid=%d, lock=%s)", threadId, name);
844 ABORT;
845 return;
846 }
847 if (syncStateKey) {
848 esyslog("ERROR: cStateLock::SetSyncStateKey() called twice (tid=%d, lock=%s)", threadId, name);
849 ABORT;
850 return;
851 }
852 syncStateKey = &StateKey;
853}
854
856{
857 if (threadId != cThread::ThreadId()) {
858 esyslog("ERROR: cStateLock::SetExplicitModify() called without holding a write lock (tid=%d, lock=%s)", threadId, name);
859 ABORT;
860 return;
861 }
862 if (explicitModify != emDisabled) {
863 esyslog("ERROR: cStateLock::SetExplicitModify() called twice (tid=%d, lock=%s)", threadId, name);
864 ABORT;
865 return;
866 }
868}
869
871{
872 if (threadId != cThread::ThreadId()) {
873 esyslog("ERROR: cStateLock::SetModified() called without holding a write lock (tid=%d, lock=%s)", threadId, name);
874 ABORT;
875 return;
876 }
878}
879
880// --- cStateKey -------------------------------------------------------------
881
882cStateKey::cStateKey(bool IgnoreFirst)
883{
884 stateLock = NULL;
885 write = false;
886 state = 0;
887 if (!IgnoreFirst)
888 Reset();
889}
890
892{
893 if (stateLock) {
894 esyslog("ERROR: cStateKey::~cStateKey() called without releasing the lock first (tid=%d, lock=%s, key=%p)", stateLock->threadId, stateLock->name, this);
895 ABORT;
896 }
897}
898
900{
901 state = -1; // lock and key are initialized differently, to make the first check return true
902}
903
904void cStateKey::Remove(bool IncState)
905{
906 if (stateLock)
907 stateLock->Unlock(*this, IncState);
908 else {
909 esyslog("ERROR: cStateKey::Remove() called without holding a lock (key=%p)", this);
910 ABORT;
911 }
912}
913
915{
916 if (!stateLock) {
917 esyslog("ERROR: cStateKey::StateChanged() called without holding a lock (tid=%d, key=%p)", cThread::ThreadId(), this);
918 ABORT;
919 }
920 else if (write)
921 return state != stateLock->state;
922 else
923 return true;
924}
925
926// --- cIoThrottle -----------------------------------------------------------
927
929std::atomic<int> cIoThrottle::count(0);
930
932{
933 active = false;
934}
935
940
942{
943 mutex.Lock();
944 if (!active) {
945 count++;
946 active = true;
947 dsyslog("i/o throttle activated, count = %d (tid=%d)", count.load(), cThread::ThreadId());
948 }
949 mutex.Unlock();
950}
951
953{
954 mutex.Lock();
955 if (active) {
956 count--;
957 active = false;
958 dsyslog("i/o throttle released, count = %d (tid=%d)", count.load(), cThread::ThreadId());
959 }
960 mutex.Unlock();
961}
962
964{
965 return count > 0;
966}
967
968// --- cPipe -----------------------------------------------------------------
969
970// cPipe::Open() and cPipe::Close() are based on code originally received from
971// Andreas Vitting <Andreas@huji.de>
972
974{
975 pid = -1;
976 f = NULL;
977}
978
980{
981 Close();
982}
983
984bool cPipe::Open(const char *Command, const char *Mode)
985{
986 int fd[2];
987
988 if (pipe(fd) < 0) {
989 LOG_ERROR_STR(Command);
990 return false;
991 }
992 if ((pid = fork()) < 0) { // fork failed
993 LOG_ERROR_STR(Command);
994 close(fd[0]);
995 close(fd[1]);
996 return false;
997 }
998
999 const char *mode = "w";
1000 int iopipe = 0;
1001
1002 if (pid > 0) { // parent process
1003 if (strcmp(Mode, "r") == 0) {
1004 mode = "r";
1005 iopipe = 1;
1006 }
1007 close(fd[iopipe]);
1008 if ((f = fdopen(fd[1 - iopipe], mode)) == NULL) {
1009 LOG_ERROR_STR(Command);
1010 close(fd[1 - iopipe]);
1011 }
1012 return f != NULL;
1013 }
1014 else { // child process
1015 int iofd = STDOUT_FILENO;
1016 if (strcmp(Mode, "w") == 0) {
1017 iopipe = 1;
1018 iofd = STDIN_FILENO;
1019 }
1020 close(fd[iopipe]);
1021 if (dup2(fd[1 - iopipe], iofd) == -1) { // now redirect
1022 close(fd[1 - iopipe]);
1023 _exit(-1);
1024 }
1025 else {
1026 int MaxPossibleFileDescriptors = getdtablesize();
1027 for (int i = STDERR_FILENO + 1; i < MaxPossibleFileDescriptors; i++)
1028 close(i); //close all dup'ed filedescriptors
1029 if (execl("/bin/sh", "sh", "-c", Command, NULL) == -1) {
1030 close(fd[1 - iopipe]);
1031 _exit(-1);
1032 }
1033 }
1034 _exit(0);
1035 }
1036}
1037
1039{
1040 int ret = -1;
1041
1042 if (f) {
1043 fclose(f);
1044 f = NULL;
1045 }
1046
1047 if (pid > 0) {
1048 int status = 0;
1049 int i = 5;
1050 while (i > 0) {
1051 ret = waitpid(pid, &status, WNOHANG);
1052 if (ret < 0) {
1053 if (errno != EINTR && errno != ECHILD) {
1054 LOG_ERROR;
1055 break;
1056 }
1057 }
1058 else if (ret == pid)
1059 break;
1060 i--;
1061 cCondWait::SleepMs(100);
1062 }
1063 if (!i) {
1064 kill(pid, SIGKILL);
1065 ret = -1;
1066 }
1067 else if (ret == -1 || !WIFEXITED(status))
1068 ret = -1;
1069 pid = -1;
1070 }
1071
1072 return ret;
1073}
1074
1075// --- SystemExec ------------------------------------------------------------
1076
1077int SystemExec(const char *Command, bool Detached)
1078{
1079 pid_t pid;
1080
1081 if ((pid = fork()) < 0) { // fork failed
1082 LOG_ERROR_STR(Command);
1083 return -1;
1084 }
1085
1086 if (pid > 0) { // parent process
1087 int status = 0;
1088 if (waitpid(pid, &status, 0) < 0) {
1089 LOG_ERROR_STR(Command);
1090 return -1;
1091 }
1092 return status;
1093 }
1094 else { // child process
1095 if (Detached) {
1096 // Fork again and let first child die - grandchild stays alive without parent
1097 if (fork() > 0)
1098 _exit(0);
1099 // Start a new session
1100 pid_t sid = setsid();
1101 if (sid < 0)
1102 _exit(-1);
1103 // close STDIN and re-open as /dev/null
1104 int devnull = open("/dev/null", O_RDONLY);
1105 if (devnull < 0 || dup2(devnull, 0) < 0)
1106 _exit(-1);
1107 }
1108 int MaxPossibleFileDescriptors = getdtablesize();
1109 for (int i = STDERR_FILENO + 1; i < MaxPossibleFileDescriptors; i++)
1110 close(i); //close all dup'ed filedescriptors
1111 if (execl("/bin/sh", "sh", "-c", Command, NULL) == -1)
1112 _exit(-1);
1113 _exit(0);
1114 }
1115}
static void BackTrace(cStringList &StringList, int Level=0, bool Mangled=false)
Produces a backtrace and stores it in the given StringList.
Definition thread.c:555
static cString GetCaller(int Level=0, bool Mangled=false)
Returns the caller at the given Level (or the immediate caller, if Level is 0).
Definition thread.c:578
static cString Demangle(char *s)
Demangles the function name in the given string and returns the converted version of s.
Definition thread.c:477
void Wait(cMutex &Mutex)
Definition thread.c:122
cCondVar(void)
Definition thread.c:111
bool TimedWait(cMutex &Mutex, int TimeoutMs)
Definition thread.c:135
void Broadcast(void)
Definition thread.c:155
pthread_cond_t cond
Definition thread.h:47
~cCondVar()
Definition thread.c:116
pthread_cond_t cond
Definition thread.h:23
bool signaled
Definition thread.h:24
cCondWait(void)
Definition thread.c:59
~cCondWait()
Definition thread.c:66
bool Wait(int TimeoutMs=0)
Waits at most TimeoutMs milliseconds for a call to Signal(), or forever if TimeoutMs is 0.
Definition thread.c:79
void Signal(void)
Signals a caller of Wait() that the condition it is waiting for is met.
Definition thread.c:101
static void SleepMs(int TimeoutMs)
Creates a cCondWait object and uses it to sleep for TimeoutMs milliseconds, immediately giving up the...
Definition thread.c:73
pthread_mutex_t mutex
Definition thread.h:22
cIoThrottle(void)
Definition thread.c:931
static std::atomic< int > count
Definition thread.h:284
void Activate(void)
Activates the global I/O throttling mechanism.
Definition thread.c:941
~cIoThrottle()
Definition thread.c:936
void Release(void)
Releases the global I/O throttling mechanism.
Definition thread.c:952
bool active
Definition thread.h:285
static bool Engaged(void)
Returns true if any I/O throttling object is currently active.
Definition thread.c:963
static cMutex mutex
Definition thread.h:283
cMutexLock(cMutex *Mutex=NULL)
Definition thread.c:422
~cMutexLock()
Definition thread.c:429
cMutex * mutex
Definition thread.h:152
bool Lock(cMutex *Mutex, int TimeoutMs=0, bool *TimedOut=NULL)
Returns true if the mutex was successfully locked.
Definition thread.c:435
bool locked
Definition thread.h:153
bool Lock(int TimeoutMs=0, bool *TimedOut=NULL)
Returns true if the mutex was successfully locked.
Definition thread.c:228
std::atomic< tThreadId > lockThreadId
Definition thread.h:72
pthread_mutex_t mutex
Definition thread.h:71
cMutex(void)
Definition thread.c:213
~cMutex()
Definition thread.c:223
int locked
Definition thread.h:73
void Unlock(void)
Definition thread.c:252
pid_t pid
Definition thread.h:308
int Close(void)
Definition thread.c:1038
FILE * f
Definition thread.h:309
bool Open(const char *Command, const char *Mode)
Definition thread.c:984
cPipe(void)
Definition thread.c:973
~cPipe()
Definition thread.c:979
char * Read(FILE *f)
Definition tools.c:1574
int locked
Definition thread.h:59
pthread_rwlock_t rwlock
Definition thread.h:58
cRwLock(bool PreferWriter=false)
Definition thread.c:162
std::atomic< tThreadId > writeLockThreadId
Definition thread.h:60
bool Lock(bool Write, int TimeoutMs=0)
Definition thread.c:177
void Unlock(void)
Definition thread.c:199
~cRwLock()
Definition thread.c:172
cStateLock * stateLock
Definition thread.h:250
cStateKey(bool IgnoreFirst=false)
Sets up a new state key.
Definition thread.c:882
int state
Definition thread.h:252
void Remove(bool IncState=true)
Removes this key from the lock it was previously used with.
Definition thread.c:904
~cStateKey()
Definition thread.c:891
void Reset(void)
Resets the state of this key, so that the next call to a lock's Lock() function with this key will re...
Definition thread.c:899
bool timedOut
Definition thread.h:253
bool write
Definition thread.h:251
bool StateChanged(void)
Returns true if this key is used for obtaining a write lock, and the lock's state differs from that o...
Definition thread.c:914
cVector< int > flags
Definition thread.c:606
cVector< tThreadId > threadIds
Definition thread.c:605
cStateLockLog(void)
Definition thread.c:621
uint8_t logCounter[SLL_THREADS][SLL_MAX_LIST]
Definition thread.c:609
int logFlags[SLL_SIZE]
Definition thread.c:608
void Check(const char *Name, bool Lock, bool Write=false)
Definition thread.c:678
tThreadId logThreadIds[SLL_SIZE]
Definition thread.c:607
bool dumped
Definition thread.c:614
void Dump(const char *Name, tThreadId ThreadId)
Definition thread.c:633
cMutex mutex
Definition thread.c:604
tThreadId threadId
Definition thread.h:190
const char * name
Definition thread.h:189
cRwLock rwLock
Definition thread.h:191
int state
Definition thread.h:192
void SetExplicitModify(void)
If you have obtained a write lock on this lock, and you don't want its state to be automatically incr...
Definition thread.c:855
cStateLock(const char *Name=NULL)
Definition thread.c:750
friend class cStateKey
Definition thread.h:186
cStateKey * syncStateKey
Definition thread.h:194
int explicitModify
Definition thread.h:193
void Unlock(cStateKey &StateKey, bool IncState=true)
Releases a lock that has been obtained by a previous call to Lock() with the given StateKey.
Definition thread.c:804
void SetSyncStateKey(cStateKey &StateKey)
Sets the given StateKey to be synchronized to the state of this lock.
Definition thread.c:834
void SetModified(void)
Sets this lock to have its state incremented when the current write lock state key is removed.
Definition thread.c:870
bool Lock(cStateKey &StateKey, bool Write=false, int TimeoutMs=0)
Tries to get a lock and returns true if successful.
Definition thread.c:760
@ emDisabled
Definition thread.h:188
@ emEnabled
Definition thread.h:188
static cString static cString vsprintf(const char *fmt, va_list &ap)
Definition tools.c:1255
static cString sprintf(const char *fmt,...) __attribute__((format(printf
Definition tools.c:1242
cThreadLock(cThread *Thread=NULL)
Definition thread.c:449
bool Lock(cThread *Thread)
Definition thread.c:462
bool locked
Definition thread.h:174
~cThreadLock()
Definition thread.c:456
cThread * thread
Definition thread.h:173
virtual ~cThread()
Definition thread.c:275
void SetIOPriority(int Priority)
Definition thread.c:287
void Unlock(void)
Definition thread.h:104
std::atomic< tThreadId > childThreadId
Definition thread.h:94
static void SetMainThreadId(void)
Definition thread.c:412
virtual void Action(void)=0
A derived cThread class must implement the code it wants to execute as a separate thread in this func...
void bool Start(void)
Sets the description of this thread, which will be used when logging starting or stopping of the thre...
Definition thread.c:330
void SetDescription(const char *Description,...) __attribute__((format(printf
Definition thread.c:293
std::atomic< bool > active
Definition thread.h:91
void SetPriority(int Priority)
Definition thread.c:281
void Lock(void)
Definition thread.h:103
cThread(const char *Description=NULL, bool LowPriority=false)
Creates a new thread.
Definition thread.c:264
bool lowPriority
Definition thread.h:97
static void * StartThread(cThread *Thread)
Definition thread.c:305
void Cancel(int WaitSeconds=0)
Cancels the thread by first setting 'running' to false, so that the Action() loop can finish in an or...
Definition thread.c:380
std::atomic< bool > running
Definition thread.h:92
static tThreadId mainThreadId
Definition thread.h:98
pthread_t childTid
Definition thread.h:93
bool Active(void)
Checks whether the thread is still alive.
Definition thread.c:355
static tThreadId ThreadId(void)
Definition thread.c:399
char * description
Definition thread.h:96
uint64_t Elapsed(void) const
Returns the number of milliseconds that have elapsed since the last call to Set().
Definition tools.c:855
bool TimedOut(void) const
Returns true if the number of milliseconds given in the last call to Set() have passed.
Definition tools.c:850
int Size(void) const
Definition tools.h:773
virtual void Append(T Data)
Definition tools.h:794
#define BT_BUF_SIZE
Definition thread.c:475
static bool GetAbsTime(struct timespec *Abstime, int MillisecondsFromNow)
Definition thread.c:39
#define SLL_LENGTH
Definition thread.c:596
#define dbglockseq(n, l, w)
Definition thread.c:743
#define ABORT
Definition thread.c:27
#define SLL_MAX_LIST
Definition thread.c:598
#define THREAD_STOP_SLEEP
Definition thread.c:328
#define SLL_SIZE
Definition thread.c:595
int SystemExec(const char *Command, bool Detached)
Definition thread.c:1077
#define SLL_THREADS
Definition thread.c:597
#define SLL_LOCK_FLAG
Definition thread.c:600
#define SLL_WRITE_FLAG
Definition thread.c:599
#define THREAD_STOP_TIMEOUT
Definition thread.c:327
static cStateLockLog StateLockLog
Definition thread.c:741
#define dbglocking(a...)
Definition thread.c:36
pid_t tThreadId
Definition thread.h:18
cString DayDateTime(time_t t)
Converts the given time to a string of the form "www dd.mm. hh:mm".
Definition tools.c:1307
char * strn0cpy(char *dest, const char *src, size_t n)
Definition tools.c:128
#define LOG_ERROR_STR(s)
Definition tools.h:40
#define dsyslog(a...)
Definition tools.h:37
T max(T a, T b)
Definition tools.h:64
#define esyslog(a...)
Definition tools.h:35
#define LOG_ERROR
Definition tools.h:39