GCC Code Coverage Report


Directory: ./
File: fppd.cpp
Date: 2026-12-01 12:27:28
Exec Total Coverage
Lines: 1112 1293 86.0%
Functions: 54 61 88.5%
Branches: 1188 2197 54.1%

Line Branch Exec Source
1 /*
2 * This file is part of the Falcon Player (FPP) and is Copyright (C)
3 * 2013-2022 by the Falcon Player Developers.
4 *
5 * The Falcon Player (FPP) is free software, and is covered under
6 * multiple Open Source licenses. Please see the included 'LICENSES'
7 * file for descriptions of what files are covered by each license.
8 *
9 * This source file is covered under the GPL v2 as described in the
10 * included LICENSE.GPL file.
11 */
12
13 #include "fpp-pch.h"
14
15 #include "fpp-json.h"
16
17 #ifdef PLATFORM_OSX
18 #include <sys/event.h>
19 #define USE_KQUEUE
20 #include "MacOSApp.h"
21 #else
22 #include <sys/epoll.h>
23 #include <sys/prctl.h>
24 #include <sys/sysinfo.h>
25 #include <sys/uio.h>
26 #include <syscall.h>
27 #endif
28
29 #include <Magick++/Image.h>
30 #include <curl/curl.h>
31 #include <magick/magick.h>
32 #include <sys/resource.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <atomic>
36 #include <chrono>
37 #include <cstdlib>
38 #include <ctime>
39 #include <errno.h>
40 #include <execinfo.h>
41 #include <fcntl.h>
42 #include <algorithm>
43 #include <filesystem>
44 #include <vector>
45 #include <fstream>
46 #include <functional>
47 #include <getopt.h>
48 #include <iostream>
49 #include <map>
50 #include <set>
51 #include <sstream>
52 #include <signal.h>
53 #include <stdio.h>
54 #include <string.h>
55 #include <string>
56 #include <thread>
57 #include <unistd.h>
58 #include <utility>
59
60 #include "common.h"
61 #include "log.h"
62 #include "mqtt.h"
63 #include "settings.h"
64
65 #include "CapeLicenseNotify.h"
66 #include "CurlManager.h"
67 #include "EPollManager.h"
68 #include "Events.h"
69 #include "FileMonitor.h"
70 #include "FPPLocale.h"
71 #include "MultiSync.h"
72 #include "NetworkMonitor.h"
73 #include "OutputMonitor.h"
74 #include "RecurringTasks.h"
75 #include "Player.h"
76 #include "Plugins.h"
77 #include "Scheduler.h"
78 #include "Sequence.h"
79 #include "Timers.h"
80 #include "Variables.h"
81 #include "Warnings.h"
82 #include "command.h"
83 #include "e131bridge.h"
84 #include "effects.h"
85 #include "fppversion.h"
86 #include "gpio.h"
87 #include "httpAPI.h"
88 #include "ping.h"
89 #include "channeloutput/ChannelOutputSetup.h"
90 #include "channeloutput/channeloutputthread.h"
91 #include "channeltester/ChannelTester.h"
92 #include "commands/Commands.h"
93 #include "mediaoutput/AES67Manager.h"
94 #include "mediaoutput/AudioLevelMonitor.h"
95 #include "mediaoutput/GStreamerOut.h"
96 #include "mediaoutput/OpusRTPManager.h"
97 #include "mediaoutput/RTSPOutputManager.h"
98 #include "mediaoutput/MediaOutputBase.h"
99 #include "mediaoutput/MediaOutputStatus.h"
100 #include "mediaoutput/VideoInputManager.h"
101 #include "mediaoutput/VideoOutputManager.h"
102 #include "mediaoutput/mediaoutput.h"
103 #include "overlays/PixelOverlay.h"
104 #include "playlist/Playlist.h"
105 #include "sensors/Sensors.h"
106 #include "util/GPIOUtils.h"
107 #include "util/TmpFileGPIO.h"
108
109 #include "MDNSManager.h"
110 #include "WLEDAPIResponder.h"
111 #include "WLEDAudioSync.h"
112
113 #include "fppd.h"
114
115 #if defined(PLATFORM_BBB) || defined(PLATFORM_BB64)
116 #include "util/BBBUtils.h"
117 #define PLAT_GPIO_CLASS BBBPinProvider
118 #elif defined(PLATFORM_PI)
119 #include "util/PiGPIOUtils.h"
120 #define PLAT_GPIO_CLASS PiGPIOPinProvider
121 #elif defined(GPIOD_CHIPS) && GPIOD_CHIPS > 0
122 #define PLAT_GPIO_CLASS NoPinCapabilitiesProvider
123 #else
124 #include "util/TmpFileGPIO.h"
125 #define PLAT_GPIO_CLASS TmpFilePinProvider
126 #endif
127
128 pid_t pid, sid;
129 // Cleared by the SIGINT/SIGTERM handler (httpAPI.cpp), which may only touch a
130 // lock-free atomic, and read by the main loop and its watchdog thread.
131 std::atomic_int runMainFPPDLoop{ 1 };
132 static_assert(std::atomic_int::is_always_lock_free, "the signal handler stores to runMainFPPDLoop");
133 // Set by the same handler. A stop that arrives while a restart tears down
134 // finds runMainFPPDLoop already 0; this is what keeps the restart from
135 // re-exec'ing a process that was asked to stop.
136 std::atomic_int fppdStopSignalled{ 0 };
137 volatile bool restartFPPD = 0;
138
139 /* Prototypes for functions below */
140 void MainLoop(void);
141 void PublishStatsBackground(std::string reason);
142 void PublishStatsForce(std::string reason);
143
144 34 static int IsDebuggerPresent() {
145 char buf[1024];
146 34 int debugger_present = 0;
147
148
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 int status_fd = open("/proc/self/status", O_RDONLY);
149
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 34 times.
34 if (status_fd == -1) {
150 ✗ return 0;
151 }
152
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 ssize_t num_read = read(status_fd, buf, sizeof(buf) - 1);
153
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 if (num_read > 0) {
154 static const char TracerPid[] = "TracerPid:";
155 char* tracer_pid;
156
157 34 buf[num_read] = 0;
158 34 tracer_pid = strstr(buf, TracerPid);
159
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 if (tracer_pid) {
160 34 debugger_present = !!atoi(tracer_pid + sizeof(TracerPid) - 1);
161 }
162 }
163 34 return debugger_present;
164 }
165
166 // Try to attach gdb to print stack trace (Linux only).
167 // The sole purpose is to improve the very poor stack traces generated by backtrace() on ARM platforms
168 // Sets *reason to a short constant describing why no gdb stack was produced.
169 // Recorded in the crash report because "symbol-only stack, no line numbers" is
170 // otherwise indistinguishable between causes -- gdb missing, gdb timing out,
171 // ptrace refused, or fork() failing under memory pressure all look identical
172 // downstream, and they call for completely different remedies.
173 34 static bool dumpstack_gdb(const char** reason = nullptr) {
174 // The watchdog callers only want the side effect of dumping a stack; only
175 // the crash handler records why it failed.
176 34 const char* ignored = nullptr;
177
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 32 times.
34 if (!reason) {
178 2 reason = &ignored;
179 }
180 34 *reason = "unknown";
181 #ifndef PLATFORM_OSX
182 char pid_buf[30];
183 34 snprintf(pid_buf, sizeof(pid_buf), "%d", getpid());
184 char thread_buf[30];
185 34 snprintf(thread_buf, sizeof(thread_buf), "(LWP %ld)", syscall(__NR_gettid));
186 char name_buf[512];
187 34 ssize_t nLink = readlink("/proc/self/exe", name_buf, sizeof(name_buf) - 1);
188
3/4
✓ Branch 0 taken 33 times.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 33 times.
✗ Branch 3 not taken.
34 if (nLink > 0 && nLink < (ssize_t)sizeof(name_buf)) {
189 33 name_buf[nLink] = '\0';
190 } else {
191 1 name_buf[0] = '\0';
192 }
193
194 constexpr static int kTimeoutSec = 30;
195
196
2/4
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 34 times.
34 if (IsDebuggerPresent()) {
197 ✗ *reason = "a debugger is already attached";
198 ✗ return false;
199 }
200 34 (void)remove("/tmp/fppd_crash.log");
201
202 // Allow us to be traced
203 // Note: Does not currently work in WSL: https://github.com/Microsoft/WSL/issues/3053
204 34 int retval = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
205 34 const bool ptraceSetFailed = (retval != 0);
206
207 // Spawn helper process which will keep running when gdb is attached to main domoticz process
208 34 pid_t intermediate_pid = fork();
209
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 70 times.
70 if (intermediate_pid == -1) {
210 // Overwhelmingly ENOMEM on a 480MB BeagleBone, or a crash that left the
211 // process unable to fork.
212 ✗ *reason = "fork() for the gdb helper failed";
213 ✗ return false;
214 }
215
2/2
✓ Branch 0 taken 36 times.
✓ Branch 1 taken 34 times.
70 if (!intermediate_pid) {
216 // Wathchdog 1: Used to kill sub processes to gdb which may hang
217 36 pid_t timeout_pid1 = fork();
218
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (timeout_pid1 == -1) {
219 ✗ _Exit(1);
220 }
221
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (timeout_pid1 == 0) {
222 ✗ sleep(kTimeoutSec);
223 ✗ _Exit(1);
224 }
225
226 // Wathchdog 2: Give up on gdb, if it still does not finish even after killing its sub processes
227 36 pid_t timeout_pid2 = fork();
228
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (timeout_pid2 == -1) {
229 ✗ kill(timeout_pid1, SIGKILL);
230 ✗ _Exit(1);
231 }
232
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (timeout_pid2 == 0) {
233 ✗ sleep(kTimeoutSec + 10);
234 ✗ _Exit(1);
235 }
236
237 // Worker: Spawns gdb
238 36 pid_t worker_pid = fork();
239
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 72 times.
72 if (worker_pid == -1) {
240 ✗ kill(timeout_pid1, SIGKILL);
241 ✗ kill(timeout_pid2, SIGKILL);
242 ✗ _Exit(1);
243 }
244
2/2
✓ Branch 0 taken 36 times.
✓ Branch 1 taken 36 times.
72 if (worker_pid == 0) {
245 36 (void)remove("/tmp/fppd_crash.log");
246
1/2
✓ Branch 0 taken 36 times.
✗ Branch 1 not taken.
36 int fd = open("/tmp/fppd_crash.log", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
247
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (fd == -1)
248 ✗ _Exit(1);
249
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (dup2(fd, STDOUT_FILENO) == -1)
250 ✗ _Exit(1);
251
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (dup2(fd, STDERR_FILENO) == -1)
252 ✗ _Exit(1);
253 36 execlp("gdb", "gdb", "--batch", "-n", "-ex", "thread apply all bt", "-ex", "info threads", "-ex", "bt", "-ex", "detach", name_buf, pid_buf, NULL);
254
255 // If gdb failed to start, signal back
256
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
36 close(fd);
257 ✗ _Exit(1);
258 }
259
260 36 int result = 1;
261
262 // Wait for all children to die
263
6/6
✓ Branch 0 taken 728 times.
✓ Branch 1 taken 108 times.
✓ Branch 2 taken 36 times.
✓ Branch 3 taken 72 times.
✓ Branch 4 taken 36 times.
✓ Branch 5 taken 36 times.
836 while (worker_pid || timeout_pid1 || timeout_pid2) {
264 800 int status = 0;
265 // pid_t exited_pid = wait(&status);
266
1/2
✓ Branch 0 taken 800 times.
✗ Branch 1 not taken.
800 usleep(100000);
267 // printf("pid worker_pid: %d, timeout_pid1: %d, timeout_pid2: %d\n", worker_pid, timeout_pid1, timeout_pid2);
268
7/8
✓ Branch 0 taken 728 times.
✓ Branch 1 taken 72 times.
✓ Branch 2 taken 728 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 36 times.
✓ Branch 5 taken 692 times.
✓ Branch 6 taken 36 times.
✓ Branch 7 taken 764 times.
800 if (worker_pid && waitpid(worker_pid, &status, WNOHANG)) {
269 36 worker_pid = 0;
270 // printf("Status: %x, wifexited: %u, wexitstatus: %u\n", status, WIFEXITED(status), WEXITSTATUS(status));
271 // printf("Sending SIGKILL to timeout_pid1\n");
272
1/2
✓ Branch 0 taken 36 times.
✗ Branch 1 not taken.
36 if (timeout_pid1)
273 36 kill(timeout_pid1, SIGKILL);
274
1/2
✓ Branch 0 taken 36 times.
✗ Branch 1 not taken.
36 if (timeout_pid2)
275 36 kill(timeout_pid2, SIGKILL);
276
7/8
✓ Branch 0 taken 728 times.
✓ Branch 1 taken 36 times.
✓ Branch 2 taken 728 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 36 times.
✓ Branch 5 taken 692 times.
✓ Branch 6 taken 36 times.
✓ Branch 7 taken 728 times.
764 } else if (timeout_pid1 && waitpid(timeout_pid1, &status, WNOHANG)) {
277 // Watchdog 1 timed out, attempt to recover by killing all gdb's child processes
278 char tmp[128];
279 36 timeout_pid1 = 0;
280 // printf("Sending SIGKILL to worker_pid's children\n");
281
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (worker_pid) {
282 ✗ snprintf(tmp, sizeof(tmp), "pkill -KILL -P %d", worker_pid);
283 ✗ int ret = system(tmp);
284 }
285
6/8
✓ Branch 0 taken 728 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 728 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 36 times.
✓ Branch 5 taken 692 times.
✓ Branch 6 taken 36 times.
✓ Branch 7 taken 692 times.
728 } else if (timeout_pid2 && waitpid(timeout_pid2, &status, WNOHANG)) {
286 // Watchdog 2 timed out, give up
287 36 timeout_pid2 = 0;
288 // printf("Sending SIGKILL to worker_pid\n");
289
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (worker_pid)
290 ✗ kill(worker_pid, SIGKILL);
291
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 36 times.
36 if (timeout_pid1)
292 ✗ kill(timeout_pid1, SIGKILL);
293 }
294 }
295 36 _Exit(result); // Or some more informative status
296 } else {
297 34 int status = 0;
298
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 pid_t res = waitpid(intermediate_pid, &status, 0);
299
2/4
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 34 times.
✗ Branch 3 not taken.
34 if (FileExists("/tmp/fppd_crash.log")) {
300
2/4
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 34 times.
✗ Branch 3 not taken.
34 std::string s = GetFileContents("/tmp/fppd_crash.log");
301
3/4
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 33 times.
✓ Branch 3 taken 1 times.
34 if (s != "") {
302
1/2
✓ Branch 0 taken 33 times.
✗ Branch 1 not taken.
33 LogErr(VB_ALL, "Stack: \n%s\n", s.c_str());
303 // printf("%s\n", s.c_str());
304 33 return true;
305 }
306 1 *reason = ptraceSetFailed
307
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 ? "gdb produced no output and PR_SET_PTRACER was refused"
308 : "gdb produced no output (not installed, exec failed, or watchdog timeout)";
309
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 33 times.
34 } else {
310 ✗ *reason = ptraceSetFailed
311 ✗ ? "gdb wrote no stack file and PR_SET_PTRACER was refused"
312 : "gdb wrote no stack file (not installed, exec failed, or watchdog timeout)";
313 }
314 }
315 #endif
316 1 return false;
317 }
318
319 64 static const char* safe(const char* in) {
320
1/2
✓ Branch 0 taken 64 times.
✗ Branch 1 not taken.
64 return in ? in : "<NULL>";
321 }
322
323 // ──────────────────────────────────────────────────────────────────────────
324 // Async-signal-safe crash-report primitives.
325 //
326 // Only write() and pure arithmetic -- no allocation, no locks, no stdio. A
327 // fatal signal that fires while this thread holds the malloc arena lock (a
328 // heap-corruption SIGABRT raised from inside free() always does) turns any
329 // allocating call into a self-deadlock, and that is the same condition most
330 // likely to have made gdb's fork() fail and dropped us onto the fallback path
331 // in the first place. So the machine-readable record is emitted with these
332 // first, and anything that can allocate is attempted only afterwards.
333 // ──────────────────────────────────────────────────────────────────────────
334 2381 static void safeWrite(int fd, const char* str) {
335
2/4
✓ Branch 0 taken 2381 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 2381 times.
2381 if (fd < 0 || !str) {
336 ✗ return;
337 }
338 2381 (void)!write(fd, str, strlen(str));
339 }
340
341 236 static void safeWriteHex(int fd, uintptr_t val) {
342 char buf[2 + sizeof(uintptr_t) * 2 + 1];
343 236 char* p = buf + sizeof(buf) - 1;
344 236 *p = '\0';
345
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 234 times.
236 if (val == 0) {
346 2 *--p = '0';
347 }
348
2/2
✓ Branch 0 taken 2150 times.
✓ Branch 1 taken 236 times.
2386 while (val) {
349 2150 *--p = "0123456789abcdef"[val & 0xF];
350 2150 val >>= 4;
351 }
352 236 *--p = 'x';
353 236 *--p = '0';
354
1/2
✓ Branch 0 taken 236 times.
✗ Branch 1 not taken.
236 safeWrite(fd, p);
355 236 }
356
357 160 static void safeWriteReg(int fd, const char* name, uintptr_t val) {
358 160 safeWrite(fd, name);
359 160 safeWrite(fd, "=");
360 160 safeWriteHex(fd, val);
361 160 safeWrite(fd, " ");
362 160 }
363
364 // Registers at the fault, taken from the signal's ucontext.
365 //
366 // This is the one piece of evidence that survives when the unwinder cannot
367 // walk the stack at all. Crashes inside a hand-written-assembly libc routine
368 // (Raspberry Pi preloads libarmmem's memcpy over glibc's) report a single
369 // frame and nothing else, because that code carries no unwind tables -- so the
370 // caller is unrecoverable by backtrace() no matter how fppd itself is
371 // compiled. The link register still holds the return address into the caller,
372 // and the argument registers still hold what was passed, which for a faulting
373 // memcpy is the destination, source and length that caused it.
374 32 static void safeWriteFaultRegisters(int fd, void* ctx) {
375
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 32 times.
32 if (!ctx) {
376 ✗ return;
377 }
378 32 safeWrite(fd, "\n=== registers at fault ===\n");
379 // Keyed on __linux__ rather than the FPP platform defines: these are glibc's
380 // ucontext layouts, and every other libc spells them differently.
381 #if defined(__linux__) && defined(__aarch64__)
382 ✗ const ucontext_t* uc = (const ucontext_t*)ctx;
383 ✗ safeWriteReg(fd, "pc", (uintptr_t)uc->uc_mcontext.pc);
384 ✗ safeWriteReg(fd, "sp", (uintptr_t)uc->uc_mcontext.sp);
385 ✗ safeWriteReg(fd, "lr", (uintptr_t)uc->uc_mcontext.regs[30]);
386 ✗ safeWrite(fd, "\n");
387 ✗ for (int i = 0; i < 8; i++) {
388 ✗ char nm[4] = { 'x', (char)('0' + i), '\0', '\0' };
389 ✗ safeWriteReg(fd, nm, (uintptr_t)uc->uc_mcontext.regs[i]);
390 }
391 ✗ safeWrite(fd, "\n");
392 #elif defined(__linux__) && defined(__arm__)
393 ✗ const ucontext_t* uc = (const ucontext_t*)ctx;
394 ✗ safeWriteReg(fd, "pc", (uintptr_t)uc->uc_mcontext.arm_pc);
395 ✗ safeWriteReg(fd, "sp", (uintptr_t)uc->uc_mcontext.arm_sp);
396 ✗ safeWriteReg(fd, "lr", (uintptr_t)uc->uc_mcontext.arm_lr);
397 // Bit 5 (T) says whether pc was running Thumb or ARM code, which is what
398 // decides how the bytes under "code at pc" disassemble: Debian's armhf is
399 // Thumb-2, Raspbian's is ARM.
400 ✗ safeWriteReg(fd, "cpsr", (uintptr_t)uc->uc_mcontext.arm_cpsr);
401 ✗ safeWrite(fd, "\n");
402 ✗ safeWriteReg(fd, "r0", (uintptr_t)uc->uc_mcontext.arm_r0);
403 ✗ safeWriteReg(fd, "r1", (uintptr_t)uc->uc_mcontext.arm_r1);
404 ✗ safeWriteReg(fd, "r2", (uintptr_t)uc->uc_mcontext.arm_r2);
405 ✗ safeWriteReg(fd, "r3", (uintptr_t)uc->uc_mcontext.arm_r3);
406 ✗ safeWrite(fd, "\n");
407 #elif defined(__linux__) && defined(__x86_64__)
408 32 const ucontext_t* uc = (const ucontext_t*)ctx;
409 32 safeWriteReg(fd, "rip", (uintptr_t)uc->uc_mcontext.gregs[REG_RIP]);
410 32 safeWriteReg(fd, "rsp", (uintptr_t)uc->uc_mcontext.gregs[REG_RSP]);
411 32 safeWrite(fd, "\n");
412 32 safeWriteReg(fd, "rdi", (uintptr_t)uc->uc_mcontext.gregs[REG_RDI]);
413 32 safeWriteReg(fd, "rsi", (uintptr_t)uc->uc_mcontext.gregs[REG_RSI]);
414 32 safeWriteReg(fd, "rdx", (uintptr_t)uc->uc_mcontext.gregs[REG_RDX]);
415 32 safeWrite(fd, "\n");
416 #else
417 (void)ctx;
418 safeWrite(fd, "(register dump not implemented for this architecture)\n");
419 #endif
420 }
421
422 // The instruction bytes around the faulting pc, as they were in memory.
423 //
424 // A SIGILL at an instruction that disassembles as perfectly valid in the
425 // packaged library can only mean the bytes the CPU ran were not the packaged
426 // ones -- a library damaged on disk, or overwritten under the running process.
427 // Without the bytes that can only be argued from the stack; with them it is
428 // a comparison. generate_crash_report compares them against the file on disk.
429 //
430 // Read with process_vm_readv rather than by dereferencing pc: a jump to an
431 // unmapped address is itself a common crash, and a fault in here would
432 // re-enter the handler. The syscall returns EFAULT instead, and reading our
433 // own process needs no ptrace permission. The two halves are read separately
434 // so a pc at the start of a mapping still gets the bytes from pc onwards.
435 32 static void safeWriteCodeAtFault(int fd, void* ctx) {
436 #if defined(__linux__) && (defined(__aarch64__) || defined(__arm__) || defined(__x86_64__))
437
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 32 times.
32 if (!ctx) {
438 ✗ return;
439 }
440 32 const ucontext_t* uc = (const ucontext_t*)ctx;
441 #if defined(__aarch64__)
442 ✗ uintptr_t pc = (uintptr_t)uc->uc_mcontext.pc;
443 #elif defined(__arm__)
444 ✗ uintptr_t pc = (uintptr_t)uc->uc_mcontext.arm_pc;
445 #else
446 32 uintptr_t pc = (uintptr_t)uc->uc_mcontext.gregs[REG_RIP];
447 #endif
448 32 constexpr size_t kHalf = 16;
449 32 safeWrite(fd, "\n=== code at pc (memory order, pc-16 to pc+16) ===\n");
450
2/2
✓ Branch 0 taken 64 times.
✓ Branch 1 taken 32 times.
96 for (int half = 0; half < 2; half++) {
451
2/2
✓ Branch 0 taken 32 times.
✓ Branch 1 taken 32 times.
64 uintptr_t addr = half == 0 ? pc - kHalf : pc;
452 unsigned char buf[kHalf];
453 64 struct iovec local = { buf, kHalf };
454 64 struct iovec remote = { (void*)addr, kHalf };
455 64 ssize_t n = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
456
1/2
✓ Branch 0 taken 64 times.
✗ Branch 1 not taken.
64 safeWriteHex(fd, addr);
457
1/2
✓ Branch 0 taken 64 times.
✗ Branch 1 not taken.
64 safeWrite(fd, ":");
458
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 64 times.
64 if (n != (ssize_t)kHalf) {
459 ✗ safeWrite(fd, " unreadable\n");
460 ✗ continue;
461 }
462
2/2
✓ Branch 0 taken 1024 times.
✓ Branch 1 taken 64 times.
1088 for (size_t i = 0; i < kHalf; i++) {
463 1024 char hex[4] = { ' ', "0123456789abcdef"[buf[i] >> 4], "0123456789abcdef"[buf[i] & 0xF], '\0' };
464
1/2
✓ Branch 0 taken 1024 times.
✗ Branch 1 not taken.
1024 safeWrite(fd, hex);
465 }
466
1/2
✓ Branch 0 taken 64 times.
✗ Branch 1 not taken.
64 safeWrite(fd, "\n");
467 }
468 #else
469 (void)fd;
470 (void)ctx;
471 #endif
472 }
473
474 #ifndef PLATFORM_OSX
475 // Appends s at p and returns the new end. No terminator.
476 4128 static char* safeAppend(char* p, const char* s) {
477
2/2
✓ Branch 0 taken 93728 times.
✓ Branch 1 taken 4128 times.
97856 while (*s) {
478 93728 *p++ = *s++;
479 }
480 4128 return p;
481 }
482
483 // Appends the decimal digits of v at p and returns the new end. No terminator.
484 2064 static char* safeAppendDec(char* p, unsigned long v) {
485 char tmp[24];
486 2064 int n = 0;
487 do {
488 3472 tmp[n++] = (char)('0' + v % 10);
489 3472 v /= 10;
490
2/2
✓ Branch 0 taken 1408 times.
✓ Branch 1 taken 2064 times.
3472 } while (v);
491
2/2
✓ Branch 0 taken 3472 times.
✓ Branch 1 taken 2064 times.
5536 while (n) {
492 3472 *p++ = tmp[--n];
493 }
494 2064 return p;
495 }
496
497 // A sysfs attribute into buf, trailing whitespace dropped. Only open, read
498 // and close, so the crash handler can call it.
499 2080 static bool safeReadAttr(const char* path, char* buf, size_t len) {
500 2080 int f = open(path, O_RDONLY | O_CLOEXEC);
501
2/2
✓ Branch 0 taken 2032 times.
✓ Branch 1 taken 48 times.
2080 if (f < 0) {
502 2032 return false;
503 }
504 48 ssize_t n = read(f, buf, len - 1);
505 48 close(f);
506
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 48 times.
48 if (n < 0) {
507 ✗ n = 0;
508 }
509
4/6
✓ Branch 0 taken 96 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 48 times.
✓ Branch 3 taken 48 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 48 times.
96 while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == ' ')) {
510 48 n--;
511 }
512 48 buf[n] = '\0';
513 48 return n > 0;
514 }
515
516 // Every thermal zone's temperature and every cpufreq policy's clock, read at
517 // the fault.
518 //
519 // A SIGILL at a valid instruction, or a pointer with one stray bit set, can be
520 // a part running too hot or clocked too fast for its supply rather than a bug.
521 // The statistics snapshot that rides along in some reports was taken minutes
522 // after fppd started, and the CPU cools within seconds of the load stopping,
523 // so only a reading taken here says how hot the part was when it failed.
524 //
525 // Thermal zones are on-chip sensors on every platform FPP runs on. Values are
526 // written in decimal with no "=0x", because the report side reads every
527 // name=0x... pair after the registers header as a register.
528 32 static void safeWriteThermal(int fd) {
529
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 safeWrite(fd, "\n=== thermal at fault ===\n");
530 char path[96];
531 char val[64];
532 32 bool any = false;
533
2/2
✓ Branch 0 taken 1024 times.
✓ Branch 1 taken 32 times.
1056 for (unsigned i = 0; i < 32; i++) {
534 1024 char* base = safeAppendDec(safeAppend(path, "/sys/class/thermal/thermal_zone"), i);
535 1024 *safeAppend(base, "/temp") = '\0';
536 char temp[24];
537
2/4
✓ Branch 0 taken 1024 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1024 times.
✗ Branch 3 not taken.
1024 if (!safeReadAttr(path, temp, sizeof(temp))) {
538 1024 continue;
539 }
540 ✗ any = true;
541 ✗ *safeAppend(base, "/type") = '\0';
542 ✗ safeWrite(fd, "thermal_zone");
543 char num[24];
544 ✗ *safeAppendDec(num, i) = '\0';
545 ✗ safeWrite(fd, num);
546 ✗ safeWrite(fd, " ");
547 ✗ safeWrite(fd, safeReadAttr(path, val, sizeof(val)) ? val : "?");
548 ✗ safeWrite(fd, ": ");
549 // Millidegrees C, possibly negative, written as degrees.
550 ✗ const char* t = temp;
551 ✗ bool neg = *t == '-';
552 ✗ if (neg) {
553 ✗ t++;
554 }
555 ✗ unsigned long mc = 0;
556 ✗ bool digits = *t != '\0';
557 ✗ for (; *t; t++) {
558 ✗ if (*t < '0' || *t > '9') {
559 ✗ digits = false;
560 ✗ break;
561 }
562 ✗ mc = mc * 10 + (unsigned long)(*t - '0');
563 }
564 ✗ if (!digits) {
565 ✗ safeWrite(fd, temp);
566 ✗ safeWrite(fd, " (unparsed)\n");
567 ✗ continue;
568 }
569 ✗ char* p = val;
570 ✗ if (neg) {
571 ✗ *p++ = '-';
572 }
573 ✗ p = safeAppendDec(p, mc / 1000);
574 ✗ *p++ = '.';
575 ✗ unsigned long frac = mc % 1000;
576 ✗ *p++ = (char)('0' + frac / 100);
577 ✗ *p++ = (char)('0' + frac / 10 % 10);
578 ✗ *p++ = (char)('0' + frac % 10);
579 ✗ *safeAppend(p, " C\n") = '\0';
580 ✗ safeWrite(fd, val);
581 }
582
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 if (!any) {
583
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 safeWrite(fd, "(no thermal zones)\n");
584 }
585
2/2
✓ Branch 0 taken 1024 times.
✓ Branch 1 taken 32 times.
1056 for (unsigned i = 0; i < 32; i++) {
586 1024 char* base = safeAppendDec(safeAppend(path, "/sys/devices/system/cpu/cpufreq/policy"), i);
587 1024 *safeAppend(base, "/scaling_cur_freq") = '\0';
588 char freq[24];
589
3/4
✓ Branch 0 taken 1024 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1008 times.
✓ Branch 3 taken 16 times.
1024 if (!safeReadAttr(path, freq, sizeof(freq))) {
590 1008 continue;
591 }
592
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, "cpufreq policy");
593 char num[24];
594 16 *safeAppendDec(num, i) = '\0';
595
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, num);
596
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, ": ");
597
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, freq);
598
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, " kHz");
599 16 *safeAppend(base, "/scaling_max_freq") = '\0';
600
2/4
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 16 times.
✗ Branch 3 not taken.
16 if (safeReadAttr(path, val, sizeof(val))) {
601
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, " (max ");
602
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, val);
603
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, ")");
604 }
605 16 *safeAppend(base, "/scaling_governor") = '\0';
606
2/4
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 16 times.
✗ Branch 3 not taken.
16 if (safeReadAttr(path, val, sizeof(val))) {
607
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, " ");
608
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, val);
609 }
610
1/2
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
16 safeWrite(fd, "\n");
611 }
612 32 }
613 #else
614 static void safeWriteThermal(int) {}
615 #endif
616
617 // Copy /proc/self/maps verbatim. Without the load address of each module, the
618 // raw frame addresses below are meaningless off-box: the report side needs
619 // (address - module base) to run addr2line against a stashed build.
620 33 static void safeWriteModuleMap(int fd) {
621 #ifndef PLATFORM_OSX
622
1/2
✓ Branch 0 taken 33 times.
✗ Branch 1 not taken.
33 safeWrite(fd, "\n=== module map (/proc/self/maps) ===\n");
623
1/2
✓ Branch 0 taken 33 times.
✗ Branch 1 not taken.
33 int mfd = open("/proc/self/maps", O_RDONLY);
624
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 33 times.
33 if (mfd < 0) {
625 ✗ safeWrite(fd, "(unavailable)\n");
626 ✗ return;
627 }
628 char buf[4096];
629 ssize_t n;
630
3/4
✓ Branch 0 taken 660 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 627 times.
✓ Branch 3 taken 33 times.
660 while ((n = read(mfd, buf, sizeof(buf))) > 0) {
631
1/2
✓ Branch 0 taken 627 times.
✗ Branch 1 not taken.
627 (void)!write(fd, buf, (size_t)n);
632 }
633
1/2
✓ Branch 0 taken 33 times.
✗ Branch 1 not taken.
33 close(mfd);
634 #else
635 safeWrite(fd, "\n=== module map unavailable on this platform ===\n");
636 #endif
637 }
638
639 // No allocation: the crash handler calls this
640 22 static bool IsManualCrashReport(const char* path) {
641 22 size_t len = strlen(path);
642
3/4
✓ Branch 0 taken 22 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 8 times.
✓ Branch 3 taken 14 times.
22 return len >= 11 && strcmp(path + len - 11, "-manual.zip") == 0;
643 }
644
645 // crashes/fpp-<type>-<version>-<uuid>-<time><suffix>.zip, relative to the media directory
646 29 static void CrashReportName(char* zfName, size_t zfLen, const char* suffix) {
647 char tbuffer[32];
648 time_t rawtime;
649 29 time(&rawtime);
650 struct tm timeinfo;
651 29 localtime_r(&rawtime, &timeinfo);
652 29 strftime(tbuffer, sizeof(tbuffer), "%Y-%m-%d_%H-%M-%S", &timeinfo);
653 #ifdef PLATFORM_ARMBIAN
654 char sysType[] = "Armbian";
655 #elif defined(PLATFORM_BBB)
656 ✗ char sysType[] = "BBB";
657 #elif defined(PLATFORM_BB64)
658 ✗ char sysType[] = "BB64";
659 #elif defined(PLATFORM_PI)
660 ✗ char sysType[] = "Pi";
661 #elif defined(PLATFORM_OSX)
662 char sysType[] = "MacOS";
663 #elif defined(PLATFORM_DOCKER)
664 29 char sysType[] = "Docker";
665 #elif defined(PLATFORM_DEBIAN)
666 char sysType[] = "Debian";
667 #else
668 char sysType[] = "Unknown";
669 #endif
670
1/2
✓ Branch 0 taken 29 times.
✗ Branch 1 not taken.
29 std::string SystemUUID = getSetting("SystemUUID", "unknown");
671 char safeUUID[64];
672 29 unsigned int uuidLen = 0;
673
3/4
✓ Branch 0 taken 215 times.
✓ Branch 1 taken 29 times.
✓ Branch 2 taken 215 times.
✗ Branch 3 not taken.
244 for (const char* p = SystemUUID.c_str(); *p != '\0' && uuidLen < sizeof(safeUUID) - 1; ++p) {
674 215 unsigned char c = *p;
675
12/18
✓ Branch 0 taken 214 times.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 209 times.
✓ Branch 3 taken 5 times.
✓ Branch 4 taken 209 times.
✓ Branch 5 taken 1 times.
✓ Branch 6 taken 180 times.
✓ Branch 7 taken 29 times.
✓ Branch 8 taken 180 times.
✓ Branch 9 taken 1 times.
✗ Branch 10 not taken.
✓ Branch 11 taken 180 times.
✗ Branch 12 not taken.
✓ Branch 13 taken 1 times.
✗ Branch 14 not taken.
✗ Branch 15 not taken.
✗ Branch 16 not taken.
✗ Branch 17 not taken.
215 bool safe = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '_' || c == '.';
676
1/2
✓ Branch 0 taken 215 times.
✗ Branch 1 not taken.
215 if (safe) {
677 215 safeUUID[uuidLen++] = c;
678 }
679 }
680 29 safeUUID[uuidLen] = '\0';
681
1/2
✓ Branch 0 taken 29 times.
✗ Branch 1 not taken.
29 snprintf(zfName, zfLen, "crashes/fpp-%s-%s-%s-%s%s.zip", sysType, getFPPVersion(), safeUUID, tbuffer, suffix);
682 29 }
683
684 32 static void handleCrash(int s, siginfo_t* si, void* ctx) {
685 static volatile bool inCrashHandler = false;
686
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 32 times.
32 if (inCrashHandler) {
687 // need to ignore any crashes in the crash handler
688 ✗ return;
689 }
690 32 inCrashHandler = true;
691 // SIGQUIT/SIGUSR1 (kill -3) ask for a stack dump of a running fppd, not a
692 // crash: fppd carries on afterwards, so they get the gdb stack and the
693 // context files but no ring freeze, crash report or upload.
694
3/4
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 31 times.
32 const bool requestedDump = (s == SIGQUIT || s == SIGUSR1);
695 // Everything this handler records goes through a new file: the /tmp stack,
696 // context and ring files, gdb's own output, the report script. An fppd
697 // that has leaked descriptors up to its soft limit -- itself a common way
698 // to crash, as a library asserting on EMFILE -- would fail every one of
699 // those open()s silently and send a report with no stack in it. Lift the
700 // soft limit to the hard one (a plain syscall, so signal-safe, and it
701 // can't race the other threads for a freed slot the way a reserved
702 // descriptor would); the children it starts inherit the room. A dump
703 // that carries on puts the limit back when it returns.
704 struct rlimit prevNoFile;
705 32 bool noFileRaised = false;
706
5/6
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 31 times.
✓ Branch 4 taken 1 times.
✓ Branch 5 taken 31 times.
32 if (getrlimit(RLIMIT_NOFILE, &prevNoFile) == 0 && prevNoFile.rlim_cur < prevNoFile.rlim_max) {
707 1 struct rlimit raised = prevNoFile;
708 1 raised.rlim_cur = raised.rlim_max;
709 1 noFileRaised = setrlimit(RLIMIT_NOFILE, &raised) == 0;
710 }
711
2/2
✓ Branch 0 taken 31 times.
✓ Branch 1 taken 1 times.
32 if (!requestedDump) {
712 // Everything this handler logs from here on -- the signal line, the gdb
713 // stack -- would otherwise push the pre-crash history out of the ring.
714 // Nothing unfreezes it, so a dump that carries on must not do this.
715
1/2
✓ Branch 0 taken 31 times.
✗ Branch 1 not taken.
31 CrashLogRingFreeze();
716 }
717 // Wedge-proofing: nearly everything below is async-signal-UNSAFE —
718 // fork()/gdb, LogErr (malloc), system()/curl. When the fatal signal
719 // fired while this thread held a libc lock (a heap-corruption SIGABRT
720 // inside free() always does), any of it can self-deadlock; the process
721 // then hangs forever, systemd keeps seeing it as running, and
722 // Restart=always never fires. Arm a watchdog with SIGALRM restored to
723 // its default (terminate) disposition — both calls are
724 // async-signal-safe — so a wedged handler still dies and gets
725 // restarted. Normal paths finish in _exit(-1) long before it fires;
726 // the timeout is generous because the crash-report zip + curl upload
727 // legitimately take time. A requested dump interrupts whatever the
728 // target thread was doing just the same, so it is armed for those too,
729 // and disarmed again when the dump returns.
730 32 constexpr unsigned int kCrashHandlerWatchdogSec = 120;
731 struct sigaction almAct;
732 struct sigaction prevAlmAct;
733 32 memset(&almAct, 0, sizeof(almAct));
734 32 memset(&prevAlmAct, 0, sizeof(prevAlmAct));
735 32 almAct.sa_handler = SIG_DFL;
736 32 sigemptyset(&almAct.sa_mask);
737 32 sigaction(SIGALRM, &almAct, &prevAlmAct);
738 32 unsigned int prevAlarm = alarm(kCrashHandlerWatchdogSec);
739 // The value used only until the user has answered, which is now a short and
740 // bounded window: the setup wizard writes ShareCrashData on Finish whether
741 // it was touched or not, and menuHead.inc will not let a box reach the rest
742 // of the UI until the wizard has been through. After that this fallback is
743 // unreachable and the user's own choice applies.
744 //
745 // For that window, 1 -- stack traces only. It is the level that rests on
746 // legitimate interests rather than consent (GDPR Art 6(1)(f)): a crash
747 // stack, the build, the plugin list and the playlist state identify nobody,
748 // and items 4 and 6 made level 1 mean exactly that. 3 was indefensible as an
749 // unanswered default because it ships settings, configuration and logs, all
750 // of which carry personal data and therefore rest on consent. 0 would be
751 // wrong in the other direction: it forfeits data the project has a lawful
752 // basis to collect, and a crash on first boot is exactly the one nobody can
753 // reproduce later.
754
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 int crashLog = getSettingInt("ShareCrashData", 1);
755 #ifndef PLATFORM_OSX
756
3/6
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 32 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 32 times.
✗ Branch 5 not taken.
32 LogErr(VB_ALL, "Crash handler called in thread %u: signal=%d (SIG%s: %s) addr=%p si_code=%d\n",
757 gettid(), s, safe(sigabbrev_np(s)), safe(sigdescr_np(s)),
758 si ? si->si_addr : nullptr, si ? si->si_code : -1);
759 #else
760 uint64_t tid;
761 pthread_threadid_np(NULL, &tid);
762 LogErr(VB_ALL, "Crash handler called in thread %u: signal=%d addr=%p\n", tid, s, si ? si->si_addr : nullptr);
763 #endif
764
765 // Deliberately the raw member, not GetSeqFilenameCopy(): this is a signal
766 // handler, so it can interrupt a thread that already holds m_seqFilenameLock
767 // and taking it here would self-deadlock the crash report. A torn read is
768 // the acceptable trade for a log line that is already best-effort.
769 // sequence is null before main() creates it and after shutdown deletes it,
770 // and a crash in either window still needs its report.
771 32 Sequence* seq = sequence;
772
5/6
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✓ Branch 3 taken 30 times.
✓ Branch 4 taken 2 times.
✓ Branch 5 taken 30 times.
32 if (seq && !seq->m_seqFilename.empty()) {
773
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
4 LogErr(VB_ALL, " while playing %s at %d ms\n", seq->m_seqFilename.c_str(), seq->m_seqMSElapsed.load());
774 }
775 32 const char* gdbFailReason = nullptr;
776
3/4
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 31 times.
32 if (!dumpstack_gdb(&gdbFailReason)) {
777 void* callstack[128];
778
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 int i, frames = backtrace(callstack, 128);
779
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 int fd = open("/tmp/fppd_crash.log", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
780
781 // Safe half first (see the safeWrite* helpers): the reason, the raw
782 // return addresses and the module map are enough to reconstruct the
783 // stack off-box with addr2line, and they are written with nothing that
784 // can block or allocate. Everything below this point may not run.
785
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 safeWrite(fd, "=== gdb stack unavailable: ");
786
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 safeWrite(fd, gdbFailReason ? gdbFailReason : "unknown");
787
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 safeWrite(fd, " ===\n=== raw frames (subtract the module base from the map below) ===\n");
788
2/2
✓ Branch 0 taken 12 times.
✓ Branch 1 taken 1 times.
13 for (i = 0; i < frames; i++) {
789
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 safeWriteHex(fd, (uintptr_t)callstack[i]);
790
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 safeWrite(fd, "\n");
791 }
792
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 safeWriteModuleMap(fd);
793
794 // Unsafe half: backtrace_symbols() allocates. Attempted last, and only
795 // for readability -- the record above already stands on its own.
796
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 safeWrite(fd, "\n=== symbolized frames (best effort) ===\n");
797 1 char** strs = backtrace_symbols(callstack, frames);
798
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 if (strs) {
799
2/2
✓ Branch 0 taken 12 times.
✓ Branch 1 taken 1 times.
13 for (i = 0; i < frames; i++) {
800
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 LogErr(VB_ALL, " %s\n", strs[i]);
801 }
802
2/2
✓ Branch 0 taken 12 times.
✓ Branch 1 taken 1 times.
13 for (i = 0; i < frames; i++) {
803
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 printf(" %s\n", strs[i]);
804
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 write(fd, strs[i], strlen(strs[i]));
805
1/2
✓ Branch 0 taken 12 times.
✗ Branch 1 not taken.
12 write(fd, "\n", 1);
806 }
807 1 free(strs);
808 } else {
809 ✗ safeWrite(fd, "(backtrace_symbols failed)\n");
810 }
811
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 write(fd, "\n", 1);
812
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 close(fd);
813 }
814
815 // Context files, written unconditionally (the gdb path above produces only
816 // a stack). Separate files so the stack parser is unaffected.
817 //
818 // Split into two on PRIVACY grounds, and the split must be kept: the
819 // playlist state and the fault registers are bare scalars that identify
820 // nothing, whereas the log ring is log content and FPP's logs are full of
821 // host names, LAN addresses and discovered-device identifiers. The
822 // bundler therefore ships the first at every share level and the second
823 // only where logs/fppd.log already goes. Putting them in one file sends a
824 // user's network topology to anyone who selected "stack traces only".
825 {
826
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 int cfd = open("/tmp/fppd_crash_context.log", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
827
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 if (cfd >= 0) {
828
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 PlaylistDumpCrashState(cfd);
829 // The last call the main loop entered. A pointer to a string
830 // literal (see SetMainLoopPhase), so reading it here is
831 // signal-safe, and it is the only record of what the main thread
832 // was doing that survives a stack gdb cannot fully unwind.
833
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 safeWrite(cfd, "Main loop phase: ");
834
2/4
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 32 times.
✗ Branch 3 not taken.
32 safeWrite(cfd, GetMainLoopPhase());
835
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 safeWrite(cfd, "\n");
836 // Written even when gdb succeeded: gdb reports the registers of
837 // the thread it happens to unwind, not necessarily the faulting
838 // one, and this costs nothing.
839
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 safeWriteFaultRegisters(cfd, ctx);
840 // Before the module map, which parsers read to the end of file.
841
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 safeWriteCodeAtFault(cfd, ctx);
842
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 safeWriteThermal(cfd);
843 // Also written even when gdb succeeded, and this is the half that
844 // was missing: gdb resolves what it can and leaves everything else
845 // as a bare address, and a frame it fails to unwind past is simply
846 // lost. Without the load addresses none of those can be recovered
847 // afterwards -- with them, any address in the dump maps back to a
848 // function with addr2line against the matching build. Addresses
849 // and library paths only, so it belongs with the registers rather
850 // than with the log ring.
851
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 safeWriteModuleMap(cfd);
852
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 close(cfd);
853 }
854
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 int rfd = open("/tmp/fppd_crash_log_ring.log", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
855
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 if (rfd >= 0) {
856
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 CrashLogRingDump(rfd);
857
1/2
✓ Branch 0 taken 32 times.
✗ Branch 1 not taken.
32 close(rfd);
858 }
859 }
860
4/4
✓ Branch 0 taken 27 times.
✓ Branch 1 taken 5 times.
✓ Branch 2 taken 26 times.
✓ Branch 3 taken 1 times.
32 if (crashLog >= 0 && !requestedDump) {
861 // (modification time, path) of every report in crashes/
862 26 std::vector<std::pair<std::filesystem::file_time_type, std::string>> reports;
863
2/4
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 26 times.
✗ Branch 3 not taken.
26 std::string mediaDir = getFPPMediaDir();
864
1/2
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
26 std::string cdir = mediaDir + "/crashes";
865
866 26 chdir(mediaDir.c_str());
867 26 mkdir(cdir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
868
1/2
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
26 SetFilePerms(cdir, true);
869
870 26 bool hasRecent = false;
871 // The error_code overloads throughout: a report removed while this
872 // runs (the UI deleting one, a manual report being pruned) made the
873 // throwing ones throw, and an exception here aborts the crash handler.
874 26 std::error_code ec;
875
8/12
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 26 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 15 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 41 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 15 times.
✓ Branch 9 taken 26 times.
✓ Branch 10 taken 15 times.
✓ Branch 11 taken 26 times.
41 for (std::filesystem::directory_iterator it(cdir, ec), end; !ec && it != end; it.increment(ec)) {
876 15 std::error_code fec;
877 15 auto ftime = it->last_write_time(fec);
878
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 15 times.
15 if (fec) {
879 1 continue; // gone since it was listed
880 }
881
2/4
✓ Branch 0 taken 15 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 15 times.
✗ Branch 3 not taken.
15 reports.emplace_back(ftime, it->path().string());
882 // Reports the user asked for are not crashes (see ManualCrashReportCallback)
883
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 14 times.
15 if (IsManualCrashReport(it->path().c_str())) {
884 1 continue;
885 }
886 14 std::chrono::system_clock::time_point stm;
887 #if defined(PLATFORM_OSX)
888 #if (__apple_build_version__ >= 14030022)
889 stm = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
890 std::chrono::file_clock::to_sys(ftime));
891 #else
892 std::time_t tt = decltype(ftime)::clock::to_time_t(ftime);
893 stm = std::chrono::system_clock::from_time_t(tt);
894 #endif
895 #else
896 14 stm = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
897 14 std::chrono::file_clock::to_sys(ftime));
898 #endif
899
2/4
✓ Branch 0 taken 14 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 14 times.
✗ Branch 3 not taken.
14 auto tdiff = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - stm);
900
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 13 times.
14 if (tdiff.count() < 60) {
901 1 hasRecent = true;
902 }
903 26 }
904 // Keep the ten newest. By time, not name: names start with the FPP
905 // version, so after an upgrade the oldest by name could be the newest.
906
1/2
✓ Branch 0 taken 26 times.
✗ Branch 1 not taken.
26 std::sort(reports.begin(), reports.end());
907
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 26 times.
28 for (size_t i = 0; i + 10 < reports.size(); i++) {
908 2 unlink(reports[i].second.c_str());
909 }
910
911
2/2
✓ Branch 0 taken 25 times.
✓ Branch 1 taken 1 times.
26 if (!hasRecent) {
912 char zfName[256];
913
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 CrashReportName(zfName, sizeof(zfName), "");
914
915 // Use script to generate crash report with passwords redacted.
916 // A full report (gdb on every thread, the logs, the config) takes
917 // well over two minutes on a slow player with a slow card, and the
918 // watchdog armed above cut it off there. This far the handler has
919 // not wedged, so give the script and the upload their own budget,
920 // and bound the script with timeout(1) so it still can't hang
921 // the restart.
922 25 constexpr unsigned int kReportScriptSec = 300;
923 25 constexpr unsigned int kUploadSec = 90;
924
2/2
✓ Branch 0 taken 9 times.
✓ Branch 1 taken 16 times.
25 alarm(kReportScriptSec + 15 + (crashLog >= 1 ? kUploadSec : 0));
925
3/6
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 25 times.
✗ Branch 5 not taken.
50 std::string scriptCmd = getFPPDDir("/scripts/generate_crash_report") + " " +
926
5/8
✓ Branch 0 taken 9 times.
✓ Branch 1 taken 16 times.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 25 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 25 times.
✗ Branch 7 not taken.
75 std::to_string(crashLog == 0 ? 3 : crashLog) + " " + zfName;
927
2/4
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
25 if (FileExists("/usr/bin/timeout")) {
928
3/6
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 25 times.
✗ Branch 5 not taken.
25 scriptCmd = "/usr/bin/timeout -k 10 " + std::to_string(kReportScriptSec) + " " + scriptCmd;
929 }
930 // The script lists this process's open descriptors by kind.
931
3/6
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 25 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 25 times.
✗ Branch 5 not taken.
25 scriptCmd = "FPPD_PID=" + std::to_string(getpid()) + " " + scriptCmd;
932
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 system(scriptCmd.c_str());
933
1/2
✓ Branch 0 taken 25 times.
✗ Branch 1 not taken.
25 SetFilePerms(zfName);
934
935
2/2
✓ Branch 0 taken 9 times.
✓ Branch 1 taken 16 times.
25 if (crashLog >= 1) {
936 // Upload crash report
937 char uploadCmd[512];
938 9 snprintf(uploadCmd, sizeof(uploadCmd), "curl --connect-timeout 15 --max-time %u https://crashes.falconplayer.com/crashUpload/index.php -F userfile=@%s",
939 kUploadSec - 5, zfName);
940
1/2
✓ Branch 0 taken 9 times.
✗ Branch 1 not taken.
9 system(uploadCmd);
941 }
942 25 } else {
943
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogErr(VB_ALL, "Very recent crash report found, not uploading\n");
944 }
945 26 }
946
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 31 times.
32 if (requestedDump) {
947 // fppd carries on: put SIGALRM and any alarm already pending (the
948 // loop watchdog's own exit timer) back as they were.
949 1 sigaction(SIGALRM, &prevAlmAct, nullptr);
950 1 alarm(prevAlarm);
951
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if (noFileRaised) {
952 ✗ setrlimit(RLIMIT_NOFILE, &prevNoFile);
953 }
954 1 inCrashHandler = false;
955 } else {
956 // For SIGBUS in non-main threads, terminate only the faulting thread
957 // instead of the entire process. This allows fppd to survive
958 // DRM/KMS buffer crashes in video consumer threads while keeping
959 // audio and other functionality running.
960 #ifndef PLATFORM_OSX
961
5/6
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 28 times.
✓ Branch 2 taken 3 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 3 times.
✓ Branch 5 taken 28 times.
31 if (s == SIGBUS && gettid() != getpid()) {
962
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 LogErr(VB_ALL, "SIGBUS in non-main thread %u — terminating thread only\n", gettid());
963 #else
964 if (s == SIGBUS && !pthread_main_np()) {
965 uint64_t tid = 0;
966 pthread_threadid_np(NULL, &tid);
967 LogErr(VB_ALL, "SIGBUS in non-main thread %llu — terminating thread only\n", tid);
968 #endif
969
2/4
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 3 times.
✗ Branch 3 not taken.
9 WarningHolder::AddWarning(1, "Video thread crashed (SIGBUS). Video output may be unavailable.");
970
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 WarningHolder::WriteWarningsFile();
971 // The handler stays installed: sigaction() is process-wide, so
972 // putting back SIG_DFL here would make the next SIGBUS on any
973 // thread fatal. SIGBUS stays blocked on this thread until it
974 // exits (no SA_NODEFER), so a fault in its exit cleanup takes the
975 // default action without coming back here.
976 // The process survives this path — disarm the crash watchdog.
977 3 alarm(0);
978 3 inCrashHandler = false;
979 3 pthread_exit(NULL);
980 return; // unreachable, but satisfies compiler
981 }
982 28 runMainFPPDLoop = 0;
983
1/2
✓ Branch 0 taken 28 times.
✗ Branch 1 not taken.
28 WarningHolder::StopNotifyThread();
984 // Written without warningsLock: the crashed thread may hold it, and
985 // waiting on it here left fppd dark until the watchdog fired.
986 // inCrashHandler stays set until _exit, so a fault from here on
987 // doesn't re-run the whole handler.
988
2/4
✓ Branch 0 taken 28 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 28 times.
✗ Branch 3 not taken.
28 WarningHolder::WriteCrashedWarningsFile(1, "FPPD has crashed. Check crash reports.");
989 // _exit(), not exit(): exit() runs the global/static destructors, and
990 // those take locks the crashed thread may still hold -- a crash inside
991 // RTSPOutputManager::ApplyConfig() left ~RTSPOutputManager waiting on
992 // its apply lock until the watchdog above killed fppd two minutes
993 // later, leaving the show dark all that time. main() skips them for
994 // the same reason on a normal exit (see its end), so nothing depends
995 // on them running.
996
1/2
✓ Branch 0 taken 28 times.
✗ Branch 1 not taken.
28 fflush(nullptr);
997 28 _exit(-1);
998 }
999 }
1000
1001 // A report the user asked for (POST /api/crashes/report), not a crash: level 3,
1002 // named -manual. Built in media/tmp/manual-crash, as zip's temp file in
1003 // crashes/ would look like a recent crash to handleCrash. No gdb stack:
1004 // attaching pauses fppd. One build at a time, then a 10s cooldown so a caller
1005 // in a loop cannot keep the player building back to back.
1006 206 static std::string ManualCrashReportCallback(std::string& error) {
1007 static std::mutex lock;
1008 static std::chrono::steady_clock::time_point last;
1009 static bool built = false;
1010 206 std::unique_lock<std::mutex> l(lock, std::try_to_lock);
1011
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 205 times.
206 if (!l.owns_lock()) {
1012
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 error = "busy";
1013
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
2 return "";
1014 }
1015
7/10
✓ Branch 0 taken 201 times.
✓ Branch 1 taken 4 times.
✓ Branch 2 taken 201 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 201 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 201 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 201 times.
✓ Branch 9 taken 4 times.
205 if (built && std::chrono::steady_clock::now() - last < std::chrono::seconds(10)) {
1016
1/2
✓ Branch 0 taken 201 times.
✗ Branch 1 not taken.
201 error = "rate-limited";
1017
1/2
✓ Branch 0 taken 201 times.
✗ Branch 1 not taken.
402 return "";
1018 }
1019 // Counted from the end of every build, failed or timed out ones included
1020 struct BuildDone {
1021 3 ~BuildDone() {
1022 3 last = std::chrono::steady_clock::now();
1023 3 built = true;
1024 3 }
1025 } buildDone;
1026
1027
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
4 std::string mediaDir = getFPPMediaDir();
1028 char name[256];
1029
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 CrashReportName(name, sizeof(name), "-manual");
1030 // A truncated name would not end -manual.zip; a quote would break the command
1031
3/6
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 4 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 4 times.
4 if (!IsManualCrashReport(name) || mediaDir.find('\'') != std::string::npos) {
1032 ✗ error = "build-failed";
1033 ✗ return "";
1034 }
1035
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 std::string base = name + strlen("crashes/");
1036
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 std::string tmpDir = mediaDir + "/tmp/manual-crash";
1037
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
4 std::string tmpPath = tmpDir + "/" + base;
1038
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 std::string cdir = mediaDir + "/crashes";
1039
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
4 std::string path = cdir + "/" + base;
1040
1041 // Only this builds in tmpDir, so anything there was left by a build that
1042 // fppd restarting or crashing cut short (the zip, zip's temp file and the
1043 // script's working directory)
1044 4 std::error_code ec;
1045
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
4 std::filesystem::remove_all(tmpDir, ec);
1046 4 mkdir(tmpDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
1047
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 SetFilePerms(tmpDir, true);
1048
1049 // "manual" leaves out the last crash's /tmp files. A hung script would hold
1050 // the lock until fppd restarts. Four minutes lets a Pi Zero on a slow SD card
1051 // finish; the timeout also answers inside PHP's 270s.
1052
5/10
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 4 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 4 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 4 times.
✗ Branch 9 not taken.
4 std::string cmd = getFPPDDir("/scripts/generate_crash_report") + " 3 '" + tmpPath + "' manual";
1053
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
4 if (FileExists("/usr/bin/timeout")) {
1054
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 cmd = "/usr/bin/timeout -k 10 240 " + cmd;
1055 }
1056 // The script lists this process's open descriptors by kind.
1057
3/6
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 4 times.
✗ Branch 5 not taken.
4 cmd = "FPPD_PID=" + std::to_string(getpid()) + " " + cmd;
1058
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
4 system(cmd.c_str());
1059
1060 struct stat st;
1061
3/6
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 3 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 3 times.
3 if (stat(tmpPath.c_str(), &st) != 0 || st.st_size == 0) {
1062 ✗ unlink(tmpPath.c_str());
1063 ✗ error = "build-failed";
1064 ✗ return "";
1065 }
1066
1067 3 mkdir(cdir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
1068
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 SetFilePerms(cdir, true);
1069 // media/tmp may be on another filesystem, so fall back to copy and delete
1070 3 ec.clear();
1071
2/4
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 3 times.
✗ Branch 3 not taken.
3 std::filesystem::rename(tmpPath, path, ec);
1072
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3 times.
3 if (ec) {
1073 ✗ ec.clear();
1074 ✗ std::filesystem::copy_file(tmpPath, path, ec);
1075 ✗ unlink(tmpPath.c_str());
1076 ✗ if (ec) {
1077 ✗ unlink(path.c_str());
1078 ✗ error = "build-failed";
1079 ✗ return "";
1080 }
1081 }
1082 // Keep at most two manual reports, counting the new one. Pruned after the
1083 // move so a failed move does not also lose the previous report. Oldest
1084 // first by time: the names start with the FPP version, so after an
1085 // upgrade sorting by name kept the wrong one.
1086 3 std::vector<std::pair<std::filesystem::file_time_type, std::string>> manual;
1087 3 ec.clear();
1088
8/12
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 3 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 3 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 6 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 3 times.
✓ Branch 9 taken 3 times.
✓ Branch 10 taken 3 times.
✓ Branch 11 taken 3 times.
6 for (std::filesystem::directory_iterator it(cdir, ec), end; !ec && it != end; it.increment(ec)) {
1089 3 std::error_code fec;
1090 3 auto t = it->last_write_time(fec);
1091
6/14
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 3 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 3 times.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✓ Branch 7 taken 3 times.
✓ Branch 8 taken 3 times.
✗ Branch 9 not taken.
✗ Branch 10 not taken.
✓ Branch 11 taken 3 times.
✗ Branch 12 not taken.
✗ Branch 13 not taken.
3 if (!fec && IsManualCrashReport(it->path().c_str()) && it->path() != path) {
1092 ✗ manual.emplace_back(t, it->path().string());
1093 }
1094 3 }
1095
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 std::sort(manual.begin(), manual.end());
1096
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 3 times.
3 for (size_t i = 0; i + 1 < manual.size(); i++) {
1097 ✗ unlink(manual[i].second.c_str());
1098 }
1099
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 SetFilePerms(path);
1100 3 return base;
1101 205 }
1102
1103 2652 bool setupExceptionHandlers() {
1104 // old sig handlers
1105 static bool s_savedHandlers = false;
1106 static struct sigaction s_handlerFPE,
1107 s_handlerILL,
1108 s_handlerBUS,
1109 s_handlerSEGV,
1110 s_handlerABRT;
1111
1112 2652 bool ok = true;
1113
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 if (!s_savedHandlers) {
1114 // install the signal handler
1115 struct sigaction act;
1116
1117 // some systems extend it with non std fields, so zero everything
1118 2652 memset(&act, 0, sizeof(act));
1119
1120 2652 act.sa_sigaction = handleCrash;
1121 2652 sigemptyset(&act.sa_mask);
1122 2652 act.sa_flags = SA_SIGINFO;
1123
1124 2652 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1125 2652 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1126 2652 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1127 2652 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1128 2652 ok &= sigaction(SIGABRT, &act, &s_handlerABRT) == 0;
1129 2652 ok &= sigaction(SIGQUIT, &act, nullptr) == 0;
1130 2652 ok &= sigaction(SIGUSR1, &act, nullptr) == 0;
1131
1132 struct sigaction sigchld_action;
1133 2652 sigchld_action.sa_handler = SIG_DFL;
1134 2652 sigchld_action.sa_flags = SA_NOCLDWAIT;
1135 2652 sigemptyset(&sigchld_action.sa_mask);
1136 2652 ok &= sigaction(SIGCHLD, &sigchld_action, NULL) == 0;
1137
1138
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2652 times.
2652 if (!ok) {
1139 ✗ LogWarn(VB_ALL, "Failed to install our signal handler.\n");
1140 }
1141 2652 s_savedHandlers = true;
1142 ✗ } else if (s_savedHandlers) {
1143 // uninstall the signal handler
1144 ✗ ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1145 ✗ ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1146 ✗ ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1147 ✗ ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1148 ✗ ok &= sigaction(SIGABRT, &s_handlerABRT, NULL) == 0;
1149 ✗ if (!ok) {
1150 ✗ LogWarn(VB_ALL, "Failed to install default signal handlers.\n");
1151 }
1152 ✗ s_savedHandlers = false;
1153 }
1154 2652 return ok;
1155 }
1156
1157 2651 static void initCapeFromFile(const std::string& f) {
1158
2/2
✓ Branch 0 taken 21 times.
✓ Branch 1 taken 2630 times.
2651 if (FileExists(f)) {
1159
1/2
✓ Branch 0 taken 21 times.
✗ Branch 1 not taken.
21 Json::Value root;
1160
2/4
✓ Branch 0 taken 21 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 21 times.
✗ Branch 3 not taken.
21 if (LoadJsonFromFile(f, root, JsonRoot::Object)) {
1161 // if there are sources of sensor data, get them loaded first
1162
2/4
✓ Branch 0 taken 21 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 21 times.
✗ Branch 3 not taken.
21 if (root.isMember("sensorSources")) {
1163
2/4
✓ Branch 0 taken 21 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 21 times.
✗ Branch 3 not taken.
21 Sensors::INSTANCE.addSensorSources(root["sensorSources"]);
1164 }
1165
2/4
✓ Branch 0 taken 21 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 21 times.
✗ Branch 3 not taken.
21 Sensors::INSTANCE.addSensors(root["sensors"]);
1166 }
1167 21 }
1168 2651 }
1169 2651 static void initCape() {
1170
3/6
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2651 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2651 times.
✗ Branch 5 not taken.
2651 initCapeFromFile(FPP_DIR_MEDIA("/tmp/cape-sensors.json"));
1171 2651 }
1172
1173 constexpr int WARNING_ID_PLUGIN_EDITED_FPP = 75;
1174
1175 // Raise the "a plugin edited FPP itself" banner while
1176 // logs/fpp_tree_modified.txt ("<plugin>\t<file>" lines) exists.
1177 2827 static void CheckPluginTreeEdits() {
1178
2/4
✓ Branch 0 taken 2827 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2827 times.
✗ Branch 3 not taken.
2827 const std::string path = getFPPMediaDir("/logs/fpp_tree_modified.txt");
1179
3/4
✓ Branch 0 taken 2827 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2825 times.
✓ Branch 3 taken 2 times.
2827 if (!FileExists(path)) {
1180 2825 return;
1181 }
1182 2 std::set<std::string> plugins;
1183 2 int files = 0;
1184
2/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
2 std::istringstream in(GetFileContents(path));
1185 2 std::string line;
1186
4/6
✓ Branch 0 taken 10 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 10 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 8 times.
✓ Branch 5 taken 2 times.
10 while (std::getline(in, line)) {
1187 8 auto tab = line.find('\t');
1188
4/4
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 3 times.
✓ Branch 2 taken 2 times.
✓ Branch 3 taken 3 times.
8 if (tab == std::string::npos || tab == 0) {
1189 5 continue;
1190 }
1191
2/4
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 3 times.
✗ Branch 3 not taken.
3 plugins.insert(line.substr(0, tab));
1192 3 ++files;
1193 }
1194
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 1 times.
2 if (files == 0) {
1195 1 return;
1196 }
1197 1 std::string names;
1198
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 1 times.
3 for (const auto& p : plugins) {
1199
4/6
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2 times.
✗ Branch 5 not taken.
2 names += (names.empty() ? "" : ", ") + p;
1200 }
1201
5/10
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2 times.
✓ Branch 7 taken 1 times.
✗ Branch 8 not taken.
✗ Branch 9 not taken.
6 WarningHolder::AddWarningTimeout(120, WARNING_ID_PLUGIN_EDITED_FPP,
1202
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
2 "Plugin " + names + " modified " + std::to_string(files) +
1203
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 " of FPP's own files. This blocks FPP updates and makes crash reports unreliable. Run an FPP update to set the changes aside, and report this to the plugin's author.",
1204 { { "fixUrl", "about.php" }, { "fixText", "Update FPP" } });
1205
10/16
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✓ Branch 5 taken 1 times.
✓ Branch 6 taken 1 times.
✓ Branch 7 taken 1 times.
✓ Branch 8 taken 1 times.
✓ Branch 9 taken 1 times.
✓ Branch 10 taken 1 times.
✓ Branch 11 taken 2826 times.
✗ Branch 12 not taken.
✗ Branch 13 not taken.
✗ Branch 14 not taken.
✗ Branch 15 not taken.
2831 }
1206
1207 // Leave without running the global/static destructors, as main()'s normal
1208 // exit and the crash handler already do (see the end of main()). An early
1209 // failure that called exit() ran them with fppd half started: the warnings
1210 // notify thread read WarningHolder's map while __cxa_finalize freed it, and
1211 // ~PluginManager's cleanup read settings that were already destroyed.
1212 1 [[noreturn]] static void ExitWithoutTeardown(int code) {
1213 1 fflush(nullptr);
1214 1 _exit(code);
1215 }
1216
1217 ✗ void usage(char* appname) {
1218 ✗ printf("Usage: %s [OPTION...]\n"
1219 "\n"
1220 "fppd is the Falcon Player daemon.\n"
1221 "\n"
1222 "Options:\n"
1223 " -f, --foreground - Don't daemonize the application. When run\n"
1224 " from a terminal, log lines are echoed to the\n"
1225 " console in addition to the log file. (Under\n"
1226 " systemd, where stdout is not a terminal, the\n"
1227 " console echo is suppressed to avoid doubling\n"
1228 " every line into the journal.)\n"
1229 " -d, --daemonize - Daemonize even if the config file says not to.\n"
1230 " -v, --volume VOLUME - Set a volume (over-written by config file)\n"
1231 " -m, --mode MODE - Set the mode: \"player\", \"bridge\",\n"
1232 " \"master\", or \"remote\"\n"
1233 " -l, --log-file FILENAME - Set the log file. Use \"stdout\" or \"stderr\"\n"
1234 " to log to the console instead of a file.\n"
1235 " -H --detect-hardware - Detect Falcon hardware on SPI port\n"
1236 " -C --configure-hardware - Configure detected Falcon hardware on SPI\n"
1237 " -h, --help - This menu.\n"
1238 " --log-level LEVEL - Set the global log output level (all loggers):\n"
1239 " \"info\", \"warn\", \"debug\", \"excess\")\n"
1240 " --log-level LEVEL:logger - Set the log level for one or more loggers.\n"
1241 " each level should be separated by semicolons\n"
1242 " with one or more loggers separated by commas.\n"
1243 " example: debug:schedule,player;excess:mqtt \n"
1244 " valid loggers are: \n"
1245 " ChannelData - channel data itself\n"
1246 " ChannelOut - channel output code\n"
1247 " Command - command processing\n"
1248 " Control - Control socket debugging\n"
1249 " E131Bridge - E1.31 bridge\n"
1250 " Effect - Effects sequences\n"
1251 " General - general messages\n"
1252 " GPIO - GPIO Input handling\n"
1253 " HTTP - HTTP API requests\n"
1254 " MediaOut - Media file handling\n"
1255 " Playlist - Playlist handling\n"
1256 " Plugin - Plugin handling\n"
1257 " Schedule - Playlist scheduling\n"
1258 " Sequence - Sequence parsing\n"
1259 " Setting - Settings parsing\n"
1260 " Sync - Player/Remote Synchronization\n"
1261 " The default logging is read from settings\n",
1262 appname);
1263 ✗ }
1264
1265 // The "-v" volume, applied once fppd has daemonized. Setting it while
1266 // parsing the arguments started the volume worker, which runs amixer and
1267 // pactl holding locks of its own, in the process that then forks into the
1268 // background: the daemon could inherit one of those locks held by a thread it
1269 // doesn't have, and never apply another volume change.
1270 static int s_argVolume = -1;
1271
1272 2652 int parseArguments(int argc, char** argv) {
1273 2652 char* s = NULL;
1274 int c;
1275
1276
4/8
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2652 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2652 times.
✗ Branch 7 not taken.
10608 SetSetting("logFile", FPP_FILE_LOG);
1277
1278 while (1) {
1279
1/2
✓ Branch 0 taken 25357 times.
✗ Branch 1 not taken.
25357 int this_option_optind = optind ? optind : 1;
1280 25357 int option_index = 0;
1281 static struct option long_options[] = {
1282 { "displayvers", no_argument, 0, 'V' },
1283 { "foreground", no_argument, 0, 'f' },
1284 { "daemonize", no_argument, 0, 'd' },
1285 { "restarted", no_argument, 0, 'r' },
1286 { "volume", required_argument, 0, 'v' },
1287 { "mode", required_argument, 0, 'm' },
1288 { "log-file", required_argument, 0, 'l' },
1289 { "playlist", required_argument, 0, 'p' },
1290 { "position", required_argument, 0, 'P' },
1291 { "detect-piface", no_argument, 0, 4 },
1292 { "resume-unscheduled", required_argument, 0, 5 },
1293 { "help", no_argument, 0, 'h' },
1294 { "log-level", required_argument, 0, 2 },
1295 { 0, 0, 0, 0 }
1296 };
1297
1298 25357 c = getopt_long(argc, argv, "Vfdrv:m:l:p:P:h",
1299 long_options, &option_index);
1300
2/2
✓ Branch 0 taken 2652 times.
✓ Branch 1 taken 22705 times.
25357 if (c == -1)
1301 2652 break;
1302
1303
10/13
✗ Branch 0 not taken.
✓ Branch 1 taken 17 times.
✓ Branch 2 taken 2647 times.
✓ Branch 3 taken 5 times.
✓ Branch 4 taken 15 times.
✓ Branch 5 taken 7 times.
✓ Branch 6 taken 8 times.
✓ Branch 7 taken 1 times.
✓ Branch 8 taken 4 times.
✓ Branch 9 taken 20000 times.
✓ Branch 10 taken 1 times.
✗ Branch 11 not taken.
✗ Branch 12 not taken.
22705 switch (c) {
1304 ✗ case 'V':
1305 ✗ printVersionInfo();
1306 ✗ ExitWithoutTeardown(0);
1307 17 case 2: // log-level
1308
2/4
✓ Branch 0 taken 17 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 17 times.
✗ Branch 3 not taken.
17 if (SetLogLevelComplex(optarg)) {
1309
3/6
✓ Branch 0 taken 17 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 17 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 17 times.
✗ Branch 5 not taken.
17 std::cout << FPPLogger::INSTANCE.GetLogLevelString() << std::endl;
1310
2/4
✓ Branch 0 taken 17 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 17 times.
✗ Branch 3 not taken.
17 LogInfo(VB_SETTING, "Log Level set to %d (%s)\n", FPPLogger::INSTANCE.MinimumLogLevel(), optarg);
1311 }
1312 17 break;
1313 2647 case 'f': // foreground
1314
2/4
✓ Branch 0 taken 2647 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2647 times.
✗ Branch 3 not taken.
2647 SetSetting("daemonize", 0);
1315 2647 break;
1316 5 case 'd': // daemonize
1317
2/4
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
✗ Branch 3 not taken.
5 SetSetting("daemonize", 1);
1318 5 break;
1319 15 case 'r': // restarted
1320
2/4
✓ Branch 0 taken 15 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 15 times.
✗ Branch 3 not taken.
15 SetSetting("restarted", 1);
1321 15 break;
1322 7 case 'p': // playlist
1323
3/6
✓ Branch 0 taken 7 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 7 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 7 times.
✗ Branch 5 not taken.
21 SetSetting("resumePlaylist", optarg);
1324 7 break;
1325 8 case 'P': // position
1326
2/4
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 8 times.
✗ Branch 3 not taken.
16 SetSetting("resumePosition", atoi(optarg));
1327 8 break;
1328 1 case 5: // resume-unscheduled <repeat>
1329 // -p/-P alone only restore the POSITION of a playlist the scheduler
1330 // is about to start anyway (Scheduler::PlayScheduledItem). This
1331 // says "start it yourself if the scheduler doesn't", which is what
1332 // a self-initiated recovery restart of a manually-started show
1333 // needs (issue #2727). The argument carries the repeat mode.
1334
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 SetSetting("resumeUnscheduled", 1);
1335
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
2 SetSetting("resumeRepeat", atoi(optarg));
1336 1 break;
1337 4 case 'v': // volume
1338 // Applied after daemonizing (see s_argVolume), not here.
1339 4 s_argVolume = atoi(optarg);
1340 4 break;
1341 20000 case 'm': // mode
1342
3/6
✓ Branch 0 taken 20000 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 20000 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 20000 times.
✗ Branch 5 not taken.
60000 SetSetting("fppMode", optarg);
1343 20000 break;
1344 1 case 'l': // log-file
1345
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
3 SetSetting("logFile", optarg);
1346 1 break;
1347 ✗ case 'h': // help
1348 ✗ usage(argv[0]);
1349 ✗ ExitWithoutTeardown(EXIT_SUCCESS);
1350 break;
1351 ✗ default:
1352 ✗ usage(argv[0]);
1353 ✗ ExitWithoutTeardown(EXIT_FAILURE);
1354 }
1355 22705 }
1356
1357 // fppd is the one binary that asks for the stdout copy to be dropped once a
1358 // line is in the log file: "-f" is how systemd runs it, so !daemonize is true
1359 // in normal operation and every line would otherwise be duplicated into
1360 // journald. (An interactive `fppd -f` still echoes -- log.cpp checks isatty.)
1361 // The suppression is opt-in precisely so fppoled and the other small services
1362 // that link this logger keep showing up in `journalctl -u <service>`.
1363 2652 SetSuppressDuplicateStdOut(true);
1364
3/6
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 295 times.
✗ Branch 5 not taken.
2652 SetLogFile(getSetting("logFile").c_str(), !getSettingInt("daemonize"));
1365
1366 2652 return 0;
1367 }
1368
1369 // Workaround ASan bug 27790 (https://bugs.llvm.org//show_bug.cgi?id=27790)
1370 // by logging if LD_LIBRARY_PATH doesn't include the path to argv[0] (our binary).
1371 // This is because ASan (and TSan, which shares the interceptor) intercepts dlopen
1372 // and causes calls to dlopen to use the sanitizer's rpath instead of the rpath of
1373 // the calling DSO, so the libfpp-co-*.so output plugins are not found. We cannot
1374 // change the LD_LIBRARY_PATH env var because the loader has already processed it
1375 // by the time that main() is called. We could fork()/execvpe(), but this has
1376 // implications for things like debugging that may be monitoring our pid.
1377 2652 bool checkASan(int argc, char** argv) {
1378 #if __SANITIZE_ADDRESS__ || __SANITIZE_THREAD__
1379 {
1380 struct FreeString {
1381 void operator()(char* p) {
1382 free(p);
1383 }
1384 };
1385 if (argc < 1 || !argv[0])
1386 abort(); // shouldn't happen
1387 std::unique_ptr<char[], FreeString> self(realpath(argv[0], NULL));
1388 if (!self)
1389 abort(); // shouldn't happen
1390 size_t sep = std::string_view(self.get()).rfind('/');
1391 if (sep == std::string_view::npos)
1392 abort(); // shouldn't happen
1393 self[sep] = '\0';
1394
1395 auto libraryPath = getenv("LD_LIBRARY_PATH");
1396 std::string_view libraryPathSv(libraryPath ? libraryPath : "");
1397 bool found = false;
1398 for (size_t start = 0, index = libraryPathSv.find(':');; start = index + 1, index = libraryPathSv.find(':', index + 1)) {
1399 if (auto pathSV = libraryPathSv.substr(start, index - start); !pathSV.empty()) {
1400 std::unique_ptr<char[], FreeString> resolved(realpath(std::string(pathSV).c_str(), NULL));
1401 if (resolved && strcmp(self.get(), resolved.get()) == 0) {
1402 found = true;
1403 break;
1404 }
1405 }
1406 if (index == libraryPathSv.npos)
1407 break;
1408 }
1409
1410 if (!found) {
1411 constexpr static char str[] = "When built with ASan or TSan, LD_LIBRARY_PATH must be set to include the path to fppd. Exiting.\n";
1412 LogErr(VB_GENERAL, str);
1413 fprintf(stderr, str);
1414 return false;
1415 }
1416 }
1417 #endif
1418
1419 2652 return true;
1420 }
1421
1422 2652 int main(int argc, char* argv[]) {
1423 5304 auto ensureEnvDefault = [](const char* key, const char* value) {
1424
2/2
✓ Branch 0 taken 5274 times.
✓ Branch 1 taken 30 times.
5304 if (!getenv(key)) {
1425 5274 setenv(key, value, 0);
1426 }
1427 5304 };
1428
1429 // Force line-buffered stdout so logs via systemd/journald appear promptly
1430 2652 setvbuf(stdout, NULL, _IOLBF, 0);
1431
1432
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 setupExceptionHandlers();
1433
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 FPPLogger::INSTANCE.Init();
1434
1435
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 2652 times.
2652 if (!checkASan(argc, argv))
1436 ✗ ExitWithoutTeardown(1);
1437
1438
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 LoadSettings(argv[0]);
1439
1440 // Align runtime audio library backend defaults with configured FPP backend.
1441 // This is a safety net in case the service env file is stale/missing.
1442
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
2652 std::string mediaBackend = toLowerCopy(getSetting("MediaBackend"));
1443
8/10
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2561 times.
✓ Branch 3 taken 91 times.
✓ Branch 4 taken 2561 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2554 times.
✓ Branch 7 taken 7 times.
✓ Branch 8 taken 2645 times.
✓ Branch 9 taken 7 times.
2652 if (mediaBackend == "pipewire" || mediaBackend == "pipewire-simple") {
1444 2645 ensureEnvDefault("SDL_AUDIODRIVER", "pulse");
1445 2645 ensureEnvDefault("ALSOFT_DRIVERS", "pulse");
1446 } else {
1447 7 ensureEnvDefault("SDL_AUDIODRIVER", "alsa");
1448 7 ensureEnvDefault("ALSOFT_DRIVERS", "alsa");
1449 }
1450
3/6
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2652 times.
✗ Branch 5 not taken.
2652 LogInfo(VB_MEDIAOUT, "Audio env: SDL_AUDIODRIVER=%s ALSOFT_DRIVERS=%s\n",
1451 getenv("SDL_AUDIODRIVER") ? getenv("SDL_AUDIODRIVER") : "(unset)",
1452 getenv("ALSOFT_DRIVERS") ? getenv("ALSOFT_DRIVERS") : "(unset)");
1453
1454
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 curl_global_init(CURL_GLOBAL_ALL);
1455
1456 // Initialize Magick, but we don't want the Magick signal handlers as they interfere with our own
1457
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 MagickLib::InitializeMagickEx(nullptr, MAGICK_OPT_NO_SIGNAL_HANDER, nullptr);
1458
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 Magick::InitializeMagick(NULL);
1459 // Cap the size of any image decoded in fppd (overlay image uploads over
1460 // HTTP, Image effects, playlist images, virtual display backgrounds).
1461 // GraphicsMagick allocates whatever the image header asks for: a 1 MB PNG
1462 // claiming 30000x30000 took 4+ GB and fppd was OOM-killed. A header past
1463 // this limit now fails to read. Only the pixel count is capped, not the
1464 // width or height: the limits apply to every image fppd makes, and the
1465 // Text effect draws a long message as one strip tens of thousands of
1466 // pixels wide (it bounds its own size). The cap is a quarter of RAM in
1467 // pixel cache (8 bytes a pixel at QuantumDepth 16), up to 128M pixels (a
1468 // 61 MP camera photo fits on a 4 GB Pi). There is no floor above that
1469 // rule: on a 512 MB BeagleBone a quarter is 16M pixels, which still fits
1470 // a 12 MP photo, and the 32M floor this once had let a 4 KB PNG take
1471 // over 300 MB there, an OOM kill. 32M only when RAM can't be read.
1472 {
1473 2652 long long ram = (long long)sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE);
1474
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 long long pixels = ram > 0 ? ram / 4 / 8 : 32LL * 1024 * 1024;
1475 2652 pixels = std::min(pixels, 128LL * 1024 * 1024);
1476
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 MagickLib::SetMagickResourceLimit(MagickLib::PixelsResource, (MagickLib::magick_int64_t)pixels);
1477 }
1478
1479 // Parse our arguments first, override any defaults
1480
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 parseArguments(argc, argv);
1481
1482 // Check to see if we were restarted and should skip sending blanking data at startup
1483
4/8
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2652 times.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✓ Branch 7 taken 2652 times.
5304 if (FileExists(FPP_DIR_MEDIA("/tmp/fppd_restarted"))) {
1484 ✗ unlink(FPP_DIR_MEDIA("/tmp/fppd_restarted").c_str());
1485 ✗ setSetting("restarted", 1);
1486 }
1487
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 std::string restartFlag = getSetting("restartFlag", "0");
1488
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 2652 times.
2652 if (restartFlag == "2") {
1489 // if this was a restart and a "quick" was requested, then mark as restarted
1490 ✗ setSetting("restartFlag", "0", true);
1491 }
1492
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
2652 if (loggingToFile()) {
1493
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 logVersionInfo();
1494 }
1495
1496 // Not modificationsOnly: the media directory is watched too, so a
1497 // settings file replaced by a rename (sed -i, an editor's save, a
1498 // restore) re-arms the watch. On the file alone, the rename dropped the
1499 // kernel's watch and no later change reached fppd until a restart.
1500
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
2947 FileMonitor::INSTANCE.AddFile(
1501
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
10313 "FPPD:Settings", FPP_DIR_MEDIA("/settings"), [argv]() {
1502 279 LogDebug(VB_SETTING, "Settings file changed, reloading settings\n");
1503 279 LoadSettings(argv[0], true);
1504 // A reload can change LogLevel_* (a hand edit, a restore, the PHP side).
1505 279 WarningHolder::UpdateLogLevelWarnings(); });
1506
1507 // Start functioning
1508
3/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
✓ Branch 3 taken 2647 times.
2652 if (getSettingInt("daemonize")) {
1509
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 CreateDaemon();
1510 }
1511
2/2
✓ Branch 0 taken 4 times.
✓ Branch 1 taken 2648 times.
2652 if (s_argVolume >= 0) {
1512
1/2
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
4 setVolume(s_argVolume);
1513 }
1514
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 2652 times.
2652 PLAT_GPIO_CLASS* gpioUtil = new PLAT_GPIO_CLASS();
1515
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
2652 PinCapabilities::InitGPIO("FPPD", gpioUtil);
1516
1517 // No srand() needed: FPPrand() seeds a per-thread PRNG on first use.
1518
1519
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 CommandManager::INSTANCE.Init();
1520
4/6
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 62 times.
✓ Branch 5 taken 2590 times.
2652 if (getSetting("MQTTHost") != "") {
1521
1/2
✓ Branch 0 taken 62 times.
✗ Branch 1 not taken.
62 LogInfo(VB_GENERAL, "Creating MQTT\n");
1522
8/18
✓ Branch 0 taken 62 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 62 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 62 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 62 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 62 times.
✗ Branch 9 not taken.
✓ Branch 10 taken 62 times.
✗ Branch 11 not taken.
✓ Branch 12 taken 62 times.
✗ Branch 13 not taken.
✗ Branch 14 not taken.
✓ Branch 15 taken 62 times.
✗ Branch 16 not taken.
✗ Branch 17 not taken.
188 mqtt = new MosquittoClient(getSetting("MQTTHost").c_str(), getSettingInt("MQTTPort"), getSetting("MQTTPrefix").c_str());
1523
1524
21/56
✓ Branch 0 taken 62 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 62 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 62 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 62 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 62 times.
✗ Branch 9 not taken.
✓ Branch 10 taken 62 times.
✗ Branch 11 not taken.
✓ Branch 12 taken 62 times.
✗ Branch 13 not taken.
✓ Branch 14 taken 62 times.
✗ Branch 15 not taken.
✓ Branch 16 taken 1 times.
✓ Branch 17 taken 61 times.
✓ Branch 18 taken 62 times.
✗ Branch 19 not taken.
✓ Branch 20 taken 62 times.
✗ Branch 21 not taken.
✓ Branch 22 taken 62 times.
✗ Branch 23 not taken.
✓ Branch 24 taken 62 times.
✗ Branch 25 not taken.
✓ Branch 26 taken 62 times.
✗ Branch 27 not taken.
✓ Branch 28 taken 62 times.
✗ Branch 29 not taken.
✓ Branch 30 taken 62 times.
✗ Branch 31 not taken.
✓ Branch 32 taken 62 times.
✗ Branch 33 not taken.
✓ Branch 34 taken 62 times.
✗ Branch 35 not taken.
✓ Branch 36 taken 1 times.
✓ Branch 37 taken 61 times.
✗ Branch 38 not taken.
✗ Branch 39 not taken.
✗ Branch 40 not taken.
✗ Branch 41 not taken.
✗ Branch 42 not taken.
✗ Branch 43 not taken.
✗ Branch 44 not taken.
✗ Branch 45 not taken.
✗ Branch 46 not taken.
✗ Branch 47 not taken.
✗ Branch 48 not taken.
✗ Branch 49 not taken.
✗ Branch 50 not taken.
✗ Branch 51 not taken.
✗ Branch 52 not taken.
✗ Branch 53 not taken.
✗ Branch 54 not taken.
✗ Branch 55 not taken.
434 if (!mqtt || !mqtt->Init(getSetting("MQTTUsername").c_str(), getSetting("MQTTPassword").c_str(), getSetting("MQTTCaFile").c_str())) {
1525
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogWarn(VB_CONTROL, "MQTT Init failed. Starting without MQTT. -- Maybe MQTT host doesn't resolve\n");
1526
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
3 WarningHolder::AddWarning(4, "MQTT init failed at startup - check the MQTT host/port settings");
1527 } else {
1528
1/2
✓ Branch 0 taken 61 times.
✗ Branch 1 not taken.
61 Events::AddEventHandler(mqtt);
1529 }
1530 }
1531
1532 std::function<void(const std::string&, const std::string&)>
1533 2654 fppd_callback = [](const std::string& topic_in,
1534 const std::string& payload) {
1535 2 LogDebug(VB_CONTROL, "System Callback for %s\n", topic_in.c_str());
1536
1537
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 1 times.
2 if (0 == topic_in.compare(topic_in.length() - 5, 5, "/stop")) {
1538 1 LogInfo(VB_CONTROL, "Stopping FPP for request: %s\n", topic_in.c_str());
1539 1 ShutdownFPPD(false);
1540
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 } else if (0 == topic_in.compare(topic_in.length() - 8, 8, "/restart")) {
1541 ✗ LogInfo(VB_CONTROL, "Restarting FPP for request: %s\n", topic_in.c_str());
1542 ✗ ShutdownFPPD(true);
1543 } else {
1544 1 LogWarn(VB_CONTROL, "Invalid request in fppd_callback %s\n", topic_in.c_str());
1545 }
1546 2652 };
1547 std::function<void(const std::string&, const std::string&)>
1548 2652 system_callback = [](const std::string& topic_in,
1549 const std::string& payload) {
1550
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 LogDebug(VB_CONTROL, "System Callback for %s\n", topic_in.c_str());
1551
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 std::string rc = "";
1552
1553
3/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 1 times.
2 if (0 == topic_in.compare(topic_in.length() - 9, 9, "/shutdown")) {
1554
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogInfo(VB_CONTROL, "Shutting down OS for request: %s\n", topic_in.c_str());
1555
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
4 urlPost("http://localhost/api/system/shutdown", "", rc);
1556
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 } else if (0 == topic_in.compare(topic_in.length() - 8, 8, "/restart")) {
1557
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogInfo(VB_CONTROL, "Restarting FPP for request: %s\n", topic_in.c_str());
1558
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
4 urlPost("http://localhost/api/system/reboot", "", rc);
1559 } else {
1560 ✗ LogWarn(VB_CONTROL, "Invalid request in mqtt_system_callback %s\n", topic_in.c_str());
1561 }
1562 2654 };
1563
1564
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
5304 Events::AddCallback("/system/fppd/#", fppd_callback);
1565
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
5304 Events::AddCallback("/system/shutdown", system_callback);
1566
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
2652 Events::AddCallback("/system/restart", system_callback);
1567
1568
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 WarningHolder::StartNotifyThread();
1569
1570 // Plugin edits to FPP's own files. scripts/fpp_tree_guard writes
1571 // logs/fpp_tree_modified.txt while such edits sit in the tree and removes it
1572 // when the next FPP update sets them aside. The warning is deliberately
1573 // timeout-based: re-added every poll while the file exists, so it ages out
1574 // ~2 minutes after the file goes away and there is no removal text to keep
1575 // in step with the message.
1576
2/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
7366 Timers::INSTANCE.addPeriodicTimer("PluginTreeEditsWarning", 30000, []() {
1577 175 CheckPluginTreeEdits();
1578 175 });
1579
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 CheckPluginTreeEdits();
1580
1581 // Check if boot delay is in progress and add warning
1582
5/8
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2652 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 3 times.
✓ Branch 7 taken 2649 times.
5304 if (FileExists(getFPPMediaDir("/tmp/boot_delay"))) {
1583
3/6
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 3 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 3 times.
✗ Branch 5 not taken.
3 std::string delayInfo = GetFileContents(getFPPMediaDir("/tmp/boot_delay"));
1584
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 TrimWhiteSpace(delayInfo);
1585 3 std::string msg;
1586
1587 // Parse the delay info - format is "startTime,duration" or "startTime,auto"
1588 3 size_t commaPos = delayInfo.find(',');
1589
5/6
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2 times.
✓ Branch 5 taken 1 times.
3 if (commaPos != std::string::npos && commaPos + 1 < delayInfo.length()) {
1590
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 std::string delayValue = delayInfo.substr(commaPos + 1);
1591
3/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 1 times.
2 if (delayValue == "auto") {
1592
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 msg = "Boot delay in progress: Waiting for valid system time (NTP/RTC) - up to 5 minutes";
1593 } else {
1594
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 msg = "Boot delay in progress: Waiting " + delayValue + " seconds before starting FPPD";
1595 }
1596 2 } else {
1597 // Fallback for old format or malformed data
1598
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 times.
1 if (delayInfo == "auto") {
1599 ✗ msg = "Boot delay in progress: Waiting for valid system time (NTP/RTC) - up to 5 minutes";
1600 } else {
1601
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 msg = "Boot delay in progress: Waiting " + delayInfo + " seconds before starting FPPD";
1602 }
1603 }
1604
1/2
✓ Branch 0 taken 3 times.
✗ Branch 1 not taken.
3 WarningHolder::AddWarning(12, msg);
1605 3 }
1606
1607
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 LogInfo(VB_GENERAL, "Creating Scheduler, Playlist, and Sequence\n");
1608
3/8
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 2652 times.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
2652 scheduler = new Scheduler();
1609
3/8
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2652 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 2652 times.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
2652 sequence = new Sequence();
1610
1/2
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
2652 LogInfo(VB_GENERAL, "Creation of Scheduler, Playlist, and Sequence Complete\n");
1611
1612
3/4
✓ Branch 0 taken 2652 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 2651 times.
2652 if (!MultiSync::INSTANCE.Init()) {
1613 1 ExitWithoutTeardown(EXIT_FAILURE);
1614 }
1615
1616
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 Sensors::INSTANCE.DetectHWSensors();
1617
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 initCape();
1618
1619
6/10
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2651 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2651 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2651 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 5 times.
✓ Branch 9 taken 2646 times.
5302 if (FileExists(FPP_DIR_CONFIG("/sensors.json"))) {
1620
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 Json::Value root;
1621
6/10
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 5 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 5 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 5 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 4 times.
✓ Branch 9 taken 1 times.
10 if (LoadJsonFromFile(FPP_DIR_CONFIG("/sensors.json"), root, JsonRoot::Object)) {
1622
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
4 Sensors::INSTANCE.addSensors(root["sensors"]);
1623 }
1624 5 }
1625
1626
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 Player::INSTANCE.Init();
1627
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 PluginManager::INSTANCE.init();
1628
1629
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 InitMediaOutput();
1630 #ifdef HAS_AES67_GSTREAMER
1631
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 AES67Manager::INSTANCE.Init();
1632
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 AES67Manager::INSTANCE.ApplyConfig();
1633 #endif
1634 #ifdef HAS_OPUS_RTP_GSTREAMER
1635
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 OpusRTPManager::INSTANCE.Init();
1636
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 OpusRTPManager::INSTANCE.ApplyConfig();
1637 #endif
1638
2/4
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2651 times.
✗ Branch 3 not taken.
2651 VideoInputManager::Instance().Init();
1639
2/4
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2651 times.
✗ Branch 3 not taken.
2651 VideoOutputManager::Instance().Init();
1640 #ifdef HAS_RTSP_OUTPUT_GSTREAMER
1641 // After the video managers: the RTSP mounts read the intervideo channels
1642 // those publish on, and its audio bridges want the PipeWire graph up.
1643
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 RTSPOutputManager::INSTANCE.Init();
1644
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 RTSPOutputManager::INSTANCE.ApplyConfig();
1645 #endif
1646
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 PixelOverlayManager::INSTANCE.Initialize();
1647
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 PingManager::INSTANCE.Initialize();
1648
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 WLEDAPIResponder::INSTANCE.Initialize();
1649
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 WLEDAudioSync::INSTANCE.Initialize();
1650
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 InitializeChannelOutputs();
1651
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 PluginManager::INSTANCE.loadUserPlugins();
1652
1653
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 InitEffects();
1654
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 ChannelTester::INSTANCE.RegisterCommands();
1655
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 LocaleHolder::RegisterCommands();
1656
1657
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 multiSync->WriteRuntimeInfoFile();
1658
1659
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2651 MainLoop();
1660 // DISABLED: Stats collected while fppd is shutting down
1661 // incomplete and cause problems with summary
1662 // PublishStatsForce("Shutdown"); // not background
1663
1664 // Sequence presets (SEQUENCE_STOPPED and the FSEQ frame-triggered commands)
1665 // are queued for the main loop rather than run at their call site, which
1666 // holds the sequence locks. A preset queued during the final loop
1667 // iteration -- a sequence that ended, or a stop command, landing just as
1668 // runMainFPPDLoop goes to 0 -- has no later tick to fire on. Drain it here
1669 // instead: still before FPPD_STOPPED, so the ordering a user would expect
1670 // between the two is preserved, and well before CommandManager::Cleanup().
1671
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 if (sequence) {
1672
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 sequence->drainPendingPresets();
1673 }
1674
1675
3/6
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2620 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 2620 times.
5240 if (CommandManager::INSTANCE.HasPreset("FPPD_STOPPED")) {
1676 ✗ CommandManager::INSTANCE.TriggerPreset("FPPD_STOPPED");
1677 }
1678
1679 // turn off processing of events so we don't get
1680 // events while we are shutting down
1681
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 Events::PrepareForShutdown();
1682
1683 // Scheduled commands run on detached threads; give any still running a
1684 // moment to finish before the media, outputs and command registry below go
1685 // away under them. Bounded so a stuck command can't hold up shutdown.
1686
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 Scheduler::WaitForCommandThreads(2000);
1687
1688 // Tear down mDNS *first* so the goodbye packets for our advertised
1689 // services go out on the wire before anything slower (media output
1690 // shutdown, channel-output close, or the WS responder draining its
1691 // client list) has a chance to hang. If shutdown is force-killed
1692 // partway through (e.g. fppd_stop's 1s timeout), at least other
1693 // discovery clients won't keep our entries cached for the TTL.
1694
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 MDNSManager::INSTANCE.Cleanup();
1695
1696 #ifdef HAS_AUDIO_LEVEL_MONITOR
1697 // Its poll thread reads the level elements of the pipelines torn down
1698 // below; stop it, and drop the meters, first. Nothing else ever joined
1699 // that thread, so it outlived the pipelines and was never reaped.
1700
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 AudioLevelMonitor::INSTANCE.Shutdown();
1701 #endif
1702 #ifdef HAS_RTSP_OUTPUT_GSTREAMER
1703 // Before the video managers it reads from, so no client is still being
1704 // served off an intervideo channel that is about to go away.
1705
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 RTSPOutputManager::INSTANCE.Shutdown();
1706 #endif
1707
2/4
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2620 times.
✗ Branch 3 not taken.
2620 VideoInputManager::Instance().Shutdown();
1708
2/4
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2620 times.
✗ Branch 3 not taken.
2620 VideoOutputManager::Instance().Shutdown();
1709 #ifdef HAS_AES67_GSTREAMER
1710
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 AES67Manager::INSTANCE.Shutdown();
1711 #endif
1712 #ifdef HAS_OPUS_RTP_GSTREAMER
1713
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 OpusRTPManager::INSTANCE.Shutdown();
1714 #endif
1715
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 CleanupMediaOutput();
1716
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 CloseEffects();
1717
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 CloseChannelOutputs();
1718
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 WLEDAPIResponder::INSTANCE.Cleanup();
1719
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 WLEDAudioSync::INSTANCE.Cleanup();
1720
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 PingManager::INSTANCE.Cleanup();
1721
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 OutputMonitor::INSTANCE.Cleanup();
1722 // Plugins must clean up before CommandManager: their unregister hooks
1723 // pull the commands they own out of the registry so CommandManager's
1724 // bulk delete below doesn't free objects a plugin still references.
1725
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 PluginManager::INSTANCE.Cleanup();
1726
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 CommandManager::INSTANCE.Cleanup();
1727
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 MultiSync::INSTANCE.ShutdownSync();
1728 // After everything that adds a request: what is still in flight (a probe
1729 // of an output's host, say) holds a resolver thread nobody would join.
1730
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 CurlManager::INSTANCE.cancelAll();
1731
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 GPIOManager::INSTANCE.Cleanup();
1732
1733 // Stop the notify thread before the deletes below, not after: its listeners
1734 // run arbitrary code on a warning change or notify timeout, and the status
1735 // listeners among them build a full status payload from scheduler and
1736 // sequence. Leaving it running across the deletes gives every shutdown a
1737 // window where a warning change reads freed objects.
1738
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 WarningHolder::StopNotifyThread();
1739
1740 // Cleared before the delete, not left dangling: the crash handler and any
1741 // straggler that checks these for null must not reach a freed object.
1742 2620 Scheduler* deadScheduler = scheduler;
1743 2620 scheduler = nullptr;
1744
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 delete deadScheduler;
1745 2620 Sequence* deadSequence = sequence;
1746 2620 sequence = nullptr;
1747
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 delete deadSequence;
1748 2620 runMainFPPDLoop = -1;
1749
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 Sensors::INSTANCE.Close();
1750
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 RecurringTasks::INSTANCE.Close();
1751
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 Variables::INSTANCE.Close();
1752
1753
2/2
✓ Branch 0 taken 62 times.
✓ Branch 1 taken 2558 times.
2620 if (mqtt) {
1754
1/2
✓ Branch 0 taken 62 times.
✗ Branch 1 not taken.
62 Events::RemoveEventHandler(mqtt);
1755
1/2
✓ Branch 0 taken 62 times.
✗ Branch 1 not taken.
62 delete mqtt;
1756 }
1757
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 delete gpioUtil;
1758
1759 // No DestroyMagick()/curl_global_cleanup(): every path from here ends in
1760 // execlp() or _exit(), which drop both libraries with the address space,
1761 // and tearing them down first pulled their state out from under any
1762 // detached thread (a scheduled command, an HTTP fetch) still inside them.
1763
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 std::string logLevelString = FPPLogger::INSTANCE.GetLogLevelString();
1764
1765 // Decide the restart resume HERE, while the log file is still open:
1766 // everything logged after CloseOpenFiles() below is silently discarded
1767 // (which is why "Performing Restart." has never appeared in a support log),
1768 // and "my show never came back after a restart" is otherwise
1769 // indistinguishable from "no playlist was running" (issue #2727).
1770 //
1771 // A manually-started playlist is normally NOT resumed across a restart -- a
1772 // user-requested restart shouldn't silently re-start a show they stopped by
1773 // restarting. A recovery restart we initiated ourselves is the opposite
1774 // case: the playlist was running, nobody asked for it to stop, and coming
1775 // back idle strands every synced remote mid-clip on a frozen frame.
1776 2620 std::string resumePlaylist;
1777 2620 std::string resumePosition;
1778 2620 std::string resumeRepeat;
1779 2620 bool resumeUnscheduled = false;
1780
2/2
✓ Branch 0 taken 17 times.
✓ Branch 1 taken 2603 times.
2620 if (restartFPPD) {
1781
5/6
✓ Branch 0 taken 17 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 8 times.
✓ Branch 3 taken 9 times.
✓ Branch 4 taken 8 times.
✓ Branch 5 taken 9 times.
25 if ((Player::INSTANCE.GetStatus() == FPP_STATUS_PLAYLIST_PLAYING) &&
1782
5/8
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✓ Branch 3 taken 6 times.
✓ Branch 4 taken 2 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2 times.
✗ Branch 7 not taken.
8 (Player::INSTANCE.WasScheduled() || RestartShouldResumePlaylist())) {
1783
1/2
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
8 resumePlaylist = Player::INSTANCE.GetPlaylistName();
1784
1/2
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
8 resumePosition = std::to_string(Player::INSTANCE.GetResumePosition());
1785
1/2
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
8 resumeRepeat = std::to_string(Player::INSTANCE.GetRepeat());
1786 // Force-start only what the scheduler won't restore itself. A
1787 // scheduled playlist is left to CheckIfShouldBePlayingNow(), which
1788 // is schedule-window aware -- forcing that one would restart a show
1789 // whose window closed while we were restarting.
1790
5/8
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✓ Branch 3 taken 6 times.
✓ Branch 4 taken 2 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2 times.
✗ Branch 7 not taken.
8 resumeUnscheduled = RestartShouldResumePlaylist() && !Player::INSTANCE.WasScheduled();
1791
3/4
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 6 times.
✓ Branch 2 taken 8 times.
✗ Branch 3 not taken.
8 LogInfo(VB_GENERAL, "Restart: resuming playlist '%s' at position %s (repeat %s, unscheduled resume %d)\n",
1792 resumePlaylist.c_str(), resumePosition.c_str(), resumeRepeat.c_str(),
1793 resumeUnscheduled ? 1 : 0);
1794 } else {
1795
6/10
✓ Branch 0 taken 9 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✓ Branch 3 taken 7 times.
✓ Branch 4 taken 9 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 9 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 9 times.
✗ Branch 9 not taken.
9 LogInfo(VB_GENERAL, "Restart: not resuming a playlist (status %d, scheduled %d, resume requested %d)\n",
1796 (int)Player::INSTANCE.GetStatus(), Player::INSTANCE.WasScheduled(),
1797 RestartShouldResumePlaylist() ? 1 : 0);
1798 }
1799 }
1800
1801
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 CloseCommand();
1802 // Not closed here: threads still running (a media teardown, GStreamer's
1803 // and PipeWire's) use them until the exec or _exit() below, which close
1804 // them; the restarted fppd must just not inherit them.
1805
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 MarkOpenFilesCloseOnExec();
1806
1807
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 WarningHolder::ClearWarningsFile();
1808
1809
2/2
✓ Branch 0 taken 17 times.
✓ Branch 1 taken 2603 times.
2620 if (restartFPPD) {
1810 // SIGINT/SIGTERM during the teardown above (systemd stopping fppd,
1811 // say) means stop, not restart. Block them before the check so one
1812 // arriving after it is not lost either: the mask and the pending
1813 // signal survive execlp(), and the new image unblocks them once its
1814 // handler is installed (APIServer::Init).
1815 sigset_t stopSigs;
1816 17 sigemptyset(&stopSigs);
1817 17 sigaddset(&stopSigs, SIGINT);
1818 17 sigaddset(&stopSigs, SIGTERM);
1819 17 pthread_sigmask(SIG_BLOCK, &stopSigs, nullptr);
1820
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 16 times.
17 if (fppdStopSignalled) {
1821 1 restartFPPD = false;
1822 }
1823 }
1824
2/2
✓ Branch 0 taken 16 times.
✓ Branch 1 taken 2604 times.
2620 if (restartFPPD) {
1825
2/4
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 16 times.
✗ Branch 3 not taken.
32 remove(FPP_DIR_MEDIA("/fpp-info.json").c_str());
1826
1827
2/4
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 16 times.
✗ Branch 3 not taken.
16 std::string fppdDir = getFPPDDir("/src/fppd");
1828
3/4
✓ Branch 0 taken 16 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 15 times.
16 const char* dmode = getSettingInt("daemonize") ? "-d" : "-f";
1829
2/2
✓ Branch 0 taken 8 times.
✓ Branch 1 taken 8 times.
16 if (!resumePlaylist.empty()) {
1830
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 6 times.
8 if (resumeUnscheduled) {
1831 // We asked for this restart, so the show must come back even
1832 // when no schedule would start it (issue #2727). -p/-P alone
1833 // only restore the position of a playlist the scheduler is
1834 // already starting.
1835 2 execlp(fppdDir.c_str(), fppdDir.c_str(), dmode, "--log-level", logLevelString.c_str(), "-r", "-p", resumePlaylist.c_str(), "-P", resumePosition.c_str(), "--resume-unscheduled", resumeRepeat.c_str(), NULL);
1836 }
1837 6 execlp(fppdDir.c_str(), fppdDir.c_str(), dmode, "--log-level", logLevelString.c_str(), "-r", "-p", resumePlaylist.c_str(), "-P", resumePosition.c_str(), NULL);
1838 } else {
1839 8 execlp(fppdDir.c_str(), fppdDir.c_str(), dmode, "--log-level", logLevelString.c_str(), "-r", NULL);
1840 }
1841 ✗ }
1842
1843 // Every subsystem was torn down explicitly above, so the C++ global/static
1844 // singleton destructors that would run on a normal return are redundant --
1845 // and crash-prone. Two distinct failure modes show up in the crash reports:
1846 // * macOS: a noexcept destructor locks a mutex belonging to an
1847 // already-destroyed singleton (or one a still-draining drogon thread is
1848 // touching); libc++ throws EINVAL ("mutex lock failed: Invalid
1849 // argument") from that lock, which escapes the noexcept dtor and calls
1850 // std::terminate.
1851 // * Linux: a file-static std::thread (the Events publish thread, the
1852 // WarningHolder notify thread, ...) that is still joinable when
1853 // __cxa_finalize destroys it -> std::thread::~thread calls
1854 // std::terminate. The orderly shutdown above joins these, but a late
1855 // restart (e.g. an event reconfigure during the drawn-out shutdown) can
1856 // leave one joinable again. This is the single most common fppd crash
1857 // on the dashboard, so the same _exit() shortcut macOS uses is applied
1858 // on Linux too.
1859 // Flush and exit now, skipping the redundant (and crash-prone) teardown.
1860
1/2
✓ Branch 0 taken 2604 times.
✗ Branch 1 not taken.
2604 fflush(nullptr);
1861 2604 _exit(0);
1862 return 0;
1863 ✗ }
1864
1865 21 void ShutdownFPPDCallback(bool restart) {
1866 21 LogInfo(VB_GENERAL, "Shutting down main loop.\n");
1867
1868 21 restartFPPD = restart;
1869 21 runMainFPPDLoop = 0;
1870 21 }
1871
1872 // ──────────────────────────────────────────────────────────────────────────────
1873 // Main-loop stall watchdog (issue #2727).
1874 //
1875 // The main loop services the MultiSync control socket, the `fpp` command socket
1876 // and (in remote mode) media processing. The HTTP API answers on its own
1877 // threads, so when something blocks the main loop the box looks alive from the
1878 // outside while doing nothing: the UI keeps reporting the last status it saw
1879 // ("playing" forever), the received-sync-packet counters stop moving because
1880 // ProcessControlPacket() never runs again, and "Restart FPPD" is a no-op
1881 // because that command is delivered through the same unserviced command
1882 // socket. That combination is exactly what a wedged remote looks like, and
1883 // nothing short of a power cycle recovers it.
1884 //
1885 // So heartbeat the loop and supervise it from a thread it cannot block: once
1886 // the loop goes quiet, dump a backtrace of every thread (the diagnostic that
1887 // has been missing from every report of this), tell the UI that the status it
1888 // is showing is stale, and if the loop never comes back, exit so systemd
1889 // (Restart=always) starts a clean process. Exiting rather than re-exec'ing is
1890 // deliberate: a stalled loop normally means a wedged decoder/DRM fd, and open
1891 // fds without CLOEXEC survive exec — only a fresh process gets them back from
1892 // the kernel.
1893 //
1894 // The show is restarted through the same resume path a wedge restart uses.
1895 // The snapshot lives in tmpfs so it can never resurrect a playlist after a
1896 // reboot, and it is taken by the main loop (never read out of Player from the
1897 // watchdog thread, which would race with whatever the stalled thread is doing).
1898 // ──────────────────────────────────────────────────────────────────────────────
1899 static constexpr const char* STALL_RESUME_STATE_FILE = "/run/fppd/stall_resume";
1900 static std::atomic<long long> s_mainLoopHeartbeat{ 0 };
1901 static std::atomic<bool> s_mainLoopWatchdogRunning{ false };
1902
1903 // Which call the main loop last entered (SetMainLoopPhase, in common.cpp, so
1904 // code inside libfpp can narrow it further). Only ever set to string literals,
1905 // so the watchdog can read the pointer from another thread and print it even
1906 // while the loop is wedged inside that call. A stalled loop that gdb cannot
1907 // unwind (the 2026-07-27 FPPv4-4 capture: the main thread's backtrace stopped
1908 // at a single bare libc frame) still tells us which call it is in.
1909 #define MAIN_LOOP_PHASE(p) SetMainLoopPhase(p)
1910
1911 static std::mutex s_mainLoopShowLock;
1912 static std::string s_mainLoopShowPlaylist;
1913 static int s_mainLoopShowPosition = 0;
1914 static int s_mainLoopShowRepeat = 0;
1915 static bool s_mainLoopShowScheduled = false;
1916
1917 606198 static long long MonotonicMS() {
1918 // Deliberately not GetTimeMS(): that is wall clock, and an NTP step would
1919 // read as a multi-second "stall".
1920
1/2
✓ Branch 0 taken 606198 times.
✗ Branch 1 not taken.
606198 return std::chrono::duration_cast<std::chrono::milliseconds>(
1921 1212396 std::chrono::steady_clock::now().time_since_epoch())
1922 1212396 .count();
1923 }
1924
1925 // Called from the main loop only.
1926 571726 static void RecordMainLoopShowSnapshot() {
1927 571726 std::unique_lock<std::mutex> lock(s_mainLoopShowLock, std::try_to_lock);
1928
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 571726 times.
571726 if (!lock.owns_lock()) {
1929 ✗ return;
1930 }
1931
3/4
✓ Branch 0 taken 571726 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 382654 times.
✓ Branch 3 taken 189072 times.
571726 if (Player::INSTANCE.GetStatus() == FPP_STATUS_PLAYLIST_PLAYING) {
1932
1/2
✓ Branch 0 taken 382654 times.
✗ Branch 1 not taken.
382654 s_mainLoopShowPlaylist = Player::INSTANCE.GetPlaylistName();
1933
1/2
✓ Branch 0 taken 382654 times.
✗ Branch 1 not taken.
382654 s_mainLoopShowPosition = Player::INSTANCE.GetPosition() - 1;
1934
1/2
✓ Branch 0 taken 382654 times.
✗ Branch 1 not taken.
382654 s_mainLoopShowRepeat = Player::INSTANCE.GetRepeat();
1935
1/2
✓ Branch 0 taken 382654 times.
✗ Branch 1 not taken.
382654 s_mainLoopShowScheduled = Player::INSTANCE.WasScheduled();
1936
2/2
✓ Branch 0 taken 1321 times.
✓ Branch 1 taken 187751 times.
189072 } else if (!s_mainLoopShowPlaylist.empty()) {
1937 1321 s_mainLoopShowPlaylist.clear();
1938 }
1939
1/2
✓ Branch 0 taken 571726 times.
✗ Branch 1 not taken.
571726 }
1940
1941 // Last act before the watchdog exits the process: leave behind whatever the
1942 // show was doing so the fresh process picks it back up.
1943 1 static void WriteStallResumeState() {
1944 1 std::unique_lock<std::mutex> lock(s_mainLoopShowLock, std::try_to_lock);
1945
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 1 times.
1 if (!lock.owns_lock() || s_mainLoopShowPlaylist.empty()) {
1946 ✗ return;
1947 }
1948
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 std::ofstream out(STALL_RESUME_STATE_FILE, std::ios::trunc);
1949
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 times.
1 if (!out) {
1950 ✗ return; // no /run/fppd (macOS, docker) -- nothing to resume from
1951 }
1952
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 out << s_mainLoopShowPlaylist << "\n"
1953
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 << s_mainLoopShowPosition << "\n"
1954
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 << s_mainLoopShowRepeat << "\n"
1955
3/6
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
1 << (s_mainLoopShowScheduled ? 1 : 0) << "\n";
1956
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 }
1957
1958 // Startup counterpart: turn a stall-restart snapshot into the same settings a
1959 // self-restart would have passed on the command line, then consume the file.
1960 2649 static void ApplyStallResumeState() {
1961
3/4
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2648 times.
✓ Branch 3 taken 1 times.
2649 if (!FileExists(STALL_RESUME_STATE_FILE)) {
1962 2648 return;
1963 }
1964 1 std::string playlist;
1965 1 int position = 0, repeat = 0, scheduled = 0;
1966 {
1967
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 std::ifstream in(STALL_RESUME_STATE_FILE);
1968 1 std::string line;
1969
7/14
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 1 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 1 times.
✗ Branch 9 not taken.
✓ Branch 10 taken 1 times.
✗ Branch 11 not taken.
✓ Branch 12 taken 1 times.
✗ Branch 13 not taken.
1 if (std::getline(in, playlist) && std::getline(in, line)) {
1970 1 position = atoi(line.c_str());
1971
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
1 if (std::getline(in, line)) {
1972 1 repeat = atoi(line.c_str());
1973 }
1974
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
1 if (std::getline(in, line)) {
1975 1 scheduled = atoi(line.c_str());
1976 }
1977 }
1978 1 }
1979 1 (void)remove(STALL_RESUME_STATE_FILE);
1980
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1 times.
1 if (playlist.empty()) {
1981 ✗ return;
1982 }
1983
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogWarn(VB_GENERAL, "Previous fppd was killed by the main-loop watchdog while playing '%s' — resuming at position %d\n",
1984 playlist.c_str(), position);
1985
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
2 SetSetting("resumePlaylist", playlist);
1986
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 SetSetting("resumePosition", position);
1987
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 if (!scheduled) {
1988 // Same rule as a wedge restart: the scheduler restores a scheduled
1989 // playlist itself (and is window-aware about it); an unscheduled show
1990 // has to be force-started or every synced remote is stranded.
1991
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
2 SetSetting("resumeUnscheduled", 1);
1992
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
2 SetSetting("resumeRepeat", repeat);
1993 }
1994
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 }
1995
1996 #ifndef PLATFORM_OSX
1997 // Read a small /proc file into a stack buffer. Everything in this dump is
1998 // deliberately heap-free: the whole point of running it is that some thread is
1999 // stuck, and if what it is stuck on is the malloc arena lock then anything that
2000 // allocates would wedge the watchdog too.
2001 136 static ssize_t ReadProcFile(const char* path, char* buf, size_t bufLen) {
2002 136 int fd = open(path, O_RDONLY | O_CLOEXEC);
2003
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 136 times.
136 if (fd < 0) {
2004 ✗ return -1;
2005 }
2006 136 ssize_t len = read(fd, buf, bufLen - 1);
2007 136 close(fd);
2008
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 136 times.
136 if (len < 0) {
2009 ✗ len = 0;
2010 }
2011 136 buf[len] = 0;
2012
4/6
✓ Branch 0 taken 238 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 102 times.
✓ Branch 3 taken 136 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 136 times.
238 while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == ' ')) {
2013 102 buf[--len] = 0;
2014 }
2015 136 return len;
2016 }
2017
2018 // Turn a runtime address into "libfoo.so+0x1234" so a PC captured on someone
2019 // else's Pi can be resolved offline against the matching binary. gdb prints
2020 // the raw address only, which is useless once the process is gone.
2021 34 static void ResolveAddr(unsigned long addr, char* out, size_t outLen) {
2022 34 snprintf(out, outLen, "0x%lx", addr);
2023
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 int fd = open("/proc/self/maps", O_RDONLY | O_CLOEXEC);
2024
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 34 times.
34 if (fd < 0) {
2025 34 return;
2026 }
2027 char buf[4096];
2028 char line[512];
2029 34 size_t lineLen = 0;
2030 ssize_t got;
2031
2/4
✓ Branch 0 taken 544 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 544 times.
✗ Branch 3 not taken.
544 while ((got = read(fd, buf, sizeof(buf))) > 0) {
2032
2/2
✓ Branch 0 taken 2149412 times.
✓ Branch 1 taken 510 times.
2149922 for (ssize_t i = 0; i < got; i++) {
2033
2/2
✓ Branch 0 taken 2129199 times.
✓ Branch 1 taken 20213 times.
2149412 if (buf[i] != '\n') {
2034
1/2
✓ Branch 0 taken 2129199 times.
✗ Branch 1 not taken.
2129199 if (lineLen < sizeof(line) - 1) {
2035 2129199 line[lineLen++] = buf[i];
2036 }
2037 2129199 continue;
2038 }
2039 20213 line[lineLen] = 0;
2040 20213 lineLen = 0;
2041
2042 20213 unsigned long start = 0, end = 0, fileOff = 0;
2043 char perms[8], path[256];
2044 20213 path[0] = 0;
2045 40426 if (sscanf(line, "%lx-%lx %7s %lx %*s %*u %255s",
2046 20213 &start, &end, perms, &fileOff, path) >= 4 &&
2047
7/10
✓ Branch 0 taken 20213 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 20213 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 34 times.
✓ Branch 5 taken 20179 times.
✓ Branch 6 taken 34 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 34 times.
✓ Branch 9 taken 20179 times.
20213 addr >= start && addr < end && path[0] == '/') {
2048 34 const char* base = strrchr(path, '/');
2049
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
34 snprintf(out, outLen, "%s+0x%lx", base ? base + 1 : path,
2050
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 addr - start + fileOff);
2051
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 close(fd);
2052 34 return;
2053 }
2054 }
2055 }
2056 ✗ close(fd);
2057 }
2058
2059 // One line per thread naming the syscall it is parked in, the kernel wait
2060 // channel, and the resolved user-space PC. This is the diagnostic gdb could
2061 // not give us: on 32-bit ARM the unwinder gives up inside libc's lock/futex
2062 // stubs, so the one thread that matters -- the stalled one -- comes back as a
2063 // single unnamed frame. /proc always answers.
2064 2 static void DumpThreadStates(void) {
2065 struct LinuxDirent64 {
2066 uint64_t d_ino;
2067 int64_t d_off;
2068 unsigned short d_reclen;
2069 unsigned char d_type;
2070 char d_name[];
2071 };
2072
2073
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 int fd = open("/proc/self/task", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
2074
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2 times.
2 if (fd < 0) {
2075 ✗ return;
2076 }
2077 // glibc futexes on the mutex word itself, which for a std::mutex is offset
2078 // 0 -- so a "syscall=98(<addr>,...)" line below whose first argument is one
2079 // of these is naming the exact lock the thread is stuck on. Anything else
2080 // means the contended lock is internal to GStreamer/PipeWire/libc.
2081
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 LogErr(VB_GENERAL, "Main loop watchdog: known locks: mediaOutputLock=%p\n",
2082 (void*)&mediaOutputLock);
2083
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 LogErr(VB_GENERAL, "Main loop watchdog: thread states (tid name state wchan syscall pc):\n");
2084
2085 char dirBuf[8192];
2086 long n;
2087
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 2 times.
4 while ((n = syscall(SYS_getdents64, fd, dirBuf, sizeof(dirBuf))) > 0) {
2088
2/2
✓ Branch 0 taken 38 times.
✓ Branch 1 taken 2 times.
40 for (long off = 0; off < n;) {
2089 38 LinuxDirent64* d = (LinuxDirent64*)(dirBuf + off);
2090 38 off += d->d_reclen;
2091
3/4
✓ Branch 0 taken 34 times.
✓ Branch 1 taken 4 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 34 times.
38 if (d->d_name[0] < '0' || d->d_name[0] > '9') {
2092 4 continue;
2093 }
2094
2095 34 char path[128], comm[64] = "?", wchan[64] = "?", sc[256] = "?", stat[512];
2096 34 snprintf(path, sizeof(path), "/proc/self/task/%s/comm", d->d_name);
2097
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 ReadProcFile(path, comm, sizeof(comm));
2098 34 snprintf(path, sizeof(path), "/proc/self/task/%s/wchan", d->d_name);
2099
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 ReadProcFile(path, wchan, sizeof(wchan));
2100 34 snprintf(path, sizeof(path), "/proc/self/task/%s/syscall", d->d_name);
2101
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 ReadProcFile(path, sc, sizeof(sc));
2102
2103 // /proc/<tid>/stat: the state letter is the field after the
2104 // parenthesised comm, which can itself contain spaces/parens.
2105 34 char state = '?';
2106 34 snprintf(path, sizeof(path), "/proc/self/task/%s/stat", d->d_name);
2107
2/4
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 34 times.
✗ Branch 3 not taken.
34 if (ReadProcFile(path, stat, sizeof(stat)) > 0) {
2108 34 const char* p = strrchr(stat, ')');
2109
3/6
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 34 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 34 times.
✗ Branch 5 not taken.
34 if (p && p[1] && p[2]) {
2110 34 state = p[2];
2111 }
2112 }
2113
2114 // "<nr> <arg0..arg5> <sp> <pc>", or "running", or "-1 <sp> <pc>".
2115 34 long nr = -1;
2116 34 unsigned long args[6] = { 0 }, sp = 0, pc = 0;
2117 34 int fields = sscanf(sc, "%ld 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx 0x%lx",
2118 &nr, &args[0], &args[1], &args[2], &args[3], &args[4],
2119 &args[5], &sp, &pc);
2120 34 char pcStr[128] = "-";
2121
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 if (fields == 9) {
2122
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 ResolveAddr(pc, pcStr, sizeof(pcStr));
2123 // arg0 of a futex wait is the lock address -- the only way to
2124 // tell "two threads fighting over one mutex" from "two threads
2125 // idle on their own condvars".
2126
1/2
✓ Branch 0 taken 34 times.
✗ Branch 1 not taken.
34 LogErr(VB_GENERAL, " tid %-6s %-16s %c %-24s syscall=%ld(0x%lx,0x%lx,0x%lx) pc=%s\n",
2127 d->d_name, comm, state, wchan, nr, args[0], args[1], args[2], pcStr);
2128 } else {
2129 ✗ LogErr(VB_GENERAL, " tid %-6s %-16s %c %-24s syscall=%s\n",
2130 d->d_name, comm, state, wchan, sc);
2131 }
2132 }
2133 }
2134
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 close(fd);
2135 }
2136 #else
2137 static void DumpThreadStates(void) {}
2138 #endif
2139
2140 // Kill the process now, leaving the show behind for the next one. Used for
2141 // both a stalled loop and a stalled shutdown.
2142 1 static void WatchdogExit(const char* why, long long stalledMS) {
2143 // Everything below can block if the stalled thread happens to hold a
2144 // libc/log lock, so make sure the process dies either way first (both
2145 // calls are async-signal-safe; the crash handler uses the same trick).
2146 struct sigaction almAct;
2147 1 memset(&almAct, 0, sizeof(almAct));
2148 1 almAct.sa_handler = SIG_DFL;
2149 1 sigemptyset(&almAct.sa_mask);
2150 1 sigaction(SIGALRM, &almAct, nullptr);
2151 1 alarm(20);
2152
2153
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
1 LogErr(VB_GENERAL, "Main loop watchdog: %s for %lld seconds in '%s' — exiting so a clean fppd is started\n",
2154 why, stalledMS / 1000, GetMainLoopPhase());
2155
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 WriteStallResumeState();
2156
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 WarningHolder::WriteWarningsFile();
2157
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 fflush(nullptr);
2158 1 _Exit(1);
2159 }
2160
2161 // The three timeouts, re-read on every pass. Reading them once at startup
2162 // meant a change made while fppd was running was silently ignored -- which is
2163 // exactly how these get set, since they are hand-edited hidden settings with no
2164 // UI (2026-07-27: MainLoopStallRestartTimeout="0" was set to keep a stalled
2165 // remote alive for inspection, and the box restarted itself anyway). Note a
2166 // hand edit of /home/fpp/media/settings still needs something to reload the
2167 // file into fppd; setting it through the UI/API applies immediately.
2168 8438 static void ReadWatchdogTimeouts(int& warnSec, int& restartSec, int& shutdownSec) {
2169 8438 warnSec = getSettingInt("MainLoopStallTimeout", 30);
2170 8438 restartSec = getSettingInt("MainLoopStallRestartTimeout", 180);
2171 8438 shutdownSec = getSettingInt("ShutdownStallTimeout", 120);
2172
2/4
✓ Branch 0 taken 8438 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 8438 times.
8438 if (restartSec > 0 && restartSec < warnSec) {
2173 ✗ restartSec = warnSec;
2174 }
2175 8438 }
2176
2177 2649 static void MainLoopWatchdog(int warnSec, int restartSec, int shutdownSec) {
2178
2/4
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2649 times.
✗ Branch 3 not taken.
2649 SetThreadName("FPP-LoopWatchdog");
2179 2649 bool warned = false;
2180 2649 long long shutdownStarted = 0;
2181
1/2
✓ Branch 0 taken 8437 times.
✗ Branch 1 not taken.
8437 while (s_mainLoopWatchdogRunning) {
2182
1/2
✓ Branch 0 taken 5789 times.
✗ Branch 1 not taken.
8437 std::this_thread::sleep_for(std::chrono::seconds(2));
2183
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5789 times.
5789 if (!s_mainLoopWatchdogRunning) {
2184 ✗ break;
2185 }
2186 5789 int prevRestartSec = restartSec;
2187 5789 ReadWatchdogTimeouts(warnSec, restartSec, shutdownSec);
2188
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5789 times.
5789 if (restartSec != prevRestartSec) {
2189 ✗ LogInfo(VB_GENERAL, "Main loop watchdog: restart timeout changed to %d seconds%s\n",
2190 restartSec, restartSec > 0 ? "" : " (restart disabled)");
2191 }
2192
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5789 times.
5789 if (warnSec <= 0) {
2193 ✗ continue; // disabled at runtime
2194 }
2195 // <= 0, not !: main() sets it to -1 partway through teardown, and a
2196 // shutdown that wedged after that point was reported as a loop stall.
2197
2/2
✓ Branch 0 taken 237 times.
✓ Branch 1 taken 5552 times.
5789 if (runMainFPPDLoop <= 0) {
2198 // Teardown is underway. It ends in _exit()/execlp(), so this
2199 // thread simply stops existing on a healthy shutdown; if it is
2200 // still here much later, the shutdown itself wedged and systemd
2201 // will never see the process go away.
2202
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 237 times.
237 if (shutdownSec <= 0) {
2203 ✗ break;
2204 }
2205 237 long long nowMS = MonotonicMS();
2206
2/2
✓ Branch 0 taken 210 times.
✓ Branch 1 taken 27 times.
237 if (!shutdownStarted) {
2207 210 shutdownStarted = nowMS;
2208
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 27 times.
27 } else if ((nowMS - shutdownStarted) >= (long long)shutdownSec * 1000) {
2209 ✗ dumpstack_gdb();
2210 ✗ WatchdogExit("shutdown did not complete", nowMS - shutdownStarted);
2211 }
2212 237 continue;
2213 237 }
2214 5552 long long hb = s_mainLoopHeartbeat.load();
2215
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5552 times.
5552 if (hb == 0) {
2216 ✗ continue;
2217 }
2218 5552 long long stalledMS = MonotonicMS() - hb;
2219
2/2
✓ Branch 0 taken 5548 times.
✓ Branch 1 taken 4 times.
5552 if (stalledMS < (long long)warnSec * 1000) {
2220
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 5547 times.
5548 if (warned) {
2221 1 LogWarn(VB_GENERAL, "Main loop watchdog: loop resumed (was in '%s')\n",
2222 GetMainLoopPhase());
2223
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
3 WarningHolder::RemoveWarning(59, "fppd main loop is stalled - the status shown may be stale and sync packets are not being processed");
2224 1 warned = false;
2225 }
2226 5548 continue;
2227 }
2228
2229
2/2
✓ Branch 0 taken 2 times.
✓ Branch 1 taken 2 times.
4 if (!warned) {
2230 2 warned = true;
2231 2 LogErr(VB_GENERAL, "Main loop watchdog: no main loop iteration for %lld seconds, stalled in '%s' — dumping thread state\n",
2232 stalledMS / 1000, GetMainLoopPhase());
2233
2/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
6 WarningHolder::AddWarning(59, "fppd main loop is stalled - the status shown may be stale and sync packets are not being processed");
2234 2 WarningHolder::WriteWarningsFile();
2235 // Cheap and always available, so take it first: it names the
2236 // syscall and lock address of every thread even when the unwinder
2237 // cannot walk the stalled stack.
2238 2 DumpThreadStates();
2239 // The one diagnostic that says *where* it is stuck. gdb stops the
2240 // process briefly; it is already doing nothing.
2241 2 dumpstack_gdb();
2242 }
2243
2244
3/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✓ Branch 3 taken 3 times.
4 if (restartSec > 0 && stalledMS >= (long long)restartSec * 1000) {
2245 1 WatchdogExit("main loop stalled", stalledMS);
2246 }
2247 }
2248 ✗ }
2249
2250 2649 static void StartMainLoopWatchdog() {
2251 // 0 disables the watchdog entirely; a stall shorter than the warn time is
2252 // normal (a large sequence load, a slow media start).
2253 2649 int warnSec = 0, restartSec = 0, shutdownSec = 0;
2254
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 ReadWatchdogTimeouts(warnSec, restartSec, shutdownSec);
2255
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 2649 times.
2649 if (warnSec <= 0) {
2256 ✗ LogInfo(VB_GENERAL, "Main loop watchdog disabled (MainLoopStallTimeout=%d)\n", warnSec);
2257 ✗ return;
2258 }
2259 // Logged so a soak log answers "which timeouts was it actually using?"
2260 // without having to guess at what the settings file said at the time.
2261
2/4
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2649 times.
✗ Branch 3 not taken.
2649 LogInfo(VB_GENERAL, "Main loop watchdog: warn after %ds, restart after %ds%s, shutdown limit %ds\n",
2262 warnSec, restartSec, restartSec > 0 ? "" : " (restart disabled)", shutdownSec);
2263
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 s_mainLoopHeartbeat.store(MonotonicMS());
2264 2649 s_mainLoopWatchdogRunning = true;
2265 // Detached on purpose: it outlives the main loop to supervise the shutdown
2266 // that follows it, and every exit path from there is _exit()/execlp(),
2267 // which takes the thread with it. (A joinable file-static std::thread
2268 // reaching static destruction is its own crash -- see ShutdownFPPD.)
2269
2/4
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2649 times.
✗ Branch 3 not taken.
2649 std::thread(MainLoopWatchdog, warnSec, restartSec, shutdownSec).detach();
2270 }
2271
2272 // How long to wait after statistics are switched on before the first upload.
2273 // Long enough that somebody who ticked the wrong box, or was looking around the
2274 // setup wizard, can put it back before anything is sent.
2275 #define STATS_OPT_IN_GRACE_SECONDS 120
2276
2277 // Publish when the user turns statistics ON, rather than leaving them waiting
2278 // for the next scheduled ask.
2279 //
2280 // The main loop's ask is rate limited to once a day, and a box that booted with
2281 // statistics off has usually already spent that ask -- so somebody who enabled
2282 // them during setup could see nothing published for up to 24 hours, with no way
2283 // to tell whether it had worked. This makes the act of enabling the trigger.
2284 //
2285 // The grace period is the point of the delay: the setting is read AGAIN when the
2286 // timer fires, so switching it back off within the window cancels the upload
2287 // rather than merely delaying it. A generation counter means repeated toggling
2288 // leaves exactly one pending timer that acts, no matter how many were started.
2289 static std::atomic<uint64_t> statsOptInGeneration{ 0 };
2290
2291 2651 static void RegisterStatsOptInListener() {
2292
3/6
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2651 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2651 times.
✗ Branch 5 not taken.
12665 registerSettingsListener("fppd-stats-optin", "statsPublish", [](const std::string& value) {
2293
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 2 times.
3 if (value != "Enabled") {
2294 // Bumping the generation is what cancels a pending timer.
2295 1 statsOptInGeneration++;
2296 1 return;
2297 }
2298 2 uint64_t gen = ++statsOptInGeneration;
2299 2 std::thread([gen]() {
2300
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 std::this_thread::sleep_for(std::chrono::seconds(STATS_OPT_IN_GRACE_SECONDS));
2301
2/2
✓ Branch 0 taken 1 times.
✓ Branch 1 taken 1 times.
2 if (statsOptInGeneration != gen) {
2302 // LogInfo, not LogDebug: this and the check below are the two
2303 // ways an opt-in ends in nothing being sent, and "nothing was
2304 // sent and nothing was said" is indistinguishable from the timer
2305 // never having been scheduled -- for someone reading the log to
2306 // work out why, and for a test trying to prove the cancel path
2307 // actually ran.
2308 1 LogInfo(VB_GENERAL, "Statistics opt-in superseded by a later change, not publishing\n");
2309 1 return;
2310 }
2311
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 1 times.
1 if (getSetting("statsPublish") != "Enabled") {
2312 ✗ LogInfo(VB_GENERAL, "Statistics were turned back off within %d seconds, not publishing\n",
2313 STATS_OPT_IN_GRACE_SECONDS);
2314 ✗ return;
2315 }
2316
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
2 PublishStatsForce("Statistics enabled");
2317
2/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
2 }).detach();
2318 });
2319 2651 }
2320
2321 2651 void MainLoop(void) {
2322
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 RegisterShutdownHandler(ShutdownFPPDCallback);
2323
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 RegisterManualCrashReportHandler(ManualCrashReportCallback);
2324
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 RegisterStatsOptInListener();
2325
2326 2651 PlaylistStatus prevFPPstatus = FPP_STATUS_IDLE;
2327 2651 int sleepms = 50;
2328 2651 int publishCounter = 200; // about 40 seconds after boot
2329
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 std::string publishReason("Startup");
2330 2651 std::map<int, std::function<bool(int)>> callbacks;
2331
2332
1/2
✓ Branch 0 taken 2651 times.
✗ Branch 1 not taken.
2651 LogDebug(VB_GENERAL, "MainLoop()\n");
2333
2334 #ifdef PLATFORM_OSX
2335 // Lets media show a video window: this main thread pumps Cocoa from its
2336 // wait in EPollManager::waitForEvents(). Only in a GUI login session.
2337 if (MacOSAppInit()) {
2338 LogInfo(VB_GENERAL, "macOS: GUI session found, video output windows enabled\n");
2339 } else {
2340 LogInfo(VB_GENERAL, "macOS: no GUI session, video output windows disabled\n");
2341 }
2342 #endif
2343
2344
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
2651 int sock = Command_Initialize();
2345
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
2650 LogDebug(VB_GENERAL, "Command socket: %d\n", sock);
2346
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
2650 if (sock >= 0) {
2347
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
5300 callbacks[sock] = [](int i) {
2348 663 MAIN_LOOP_PHASE("fpp command socket");
2349 663 CommandProc();
2350 663 return false;
2351 2650 };
2352 }
2353
2354 2650 sock = multiSync->GetControlSocket();
2355
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
2650 LogDebug(VB_GENERAL, "Multisync socket: %d\n", sock);
2356
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
2650 if (sock >= 0) {
2357
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
5300 callbacks[sock] = [](int i) {
2358 6728 MAIN_LOOP_PHASE("multisync ProcessControlPacket");
2359 6728 multiSync->ProcessControlPacket();
2360 6728 return false;
2361 2650 };
2362 }
2363
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
2650 Bridge_Initialize(callbacks);
2364
2365
1/2
✓ Branch 0 taken 2650 times.
✗ Branch 1 not taken.
2650 APIServer apiServer;
2366
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2650 apiServer.Init();
2367
2368
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 OutputMonitor::INSTANCE.Initialize(callbacks);
2369
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 GPIOManager::INSTANCE.Initialize(callbacks);
2370
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 PluginManager::INSTANCE.addControlCallbacks(callbacks);
2371
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 NetworkMonitor::INSTANCE.Init(callbacks);
2372
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 Sensors::INSTANCE.Init(callbacks);
2373
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 Variables::INSTANCE.Init();
2374
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 RecurringTasks::INSTANCE.Init();
2375
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 FileMonitor::INSTANCE.Initialize(callbacks);
2376
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 MDNSManager::INSTANCE.Initialize(callbacks);
2377
2378 // Get the last release date from rpi-imager file to use as minimum valid date
2379 // Systems without RTC boot with filesystem timestamps, which will be older than the release
2380 // If clock shows a date before the last OS release, it's definitely wrong
2381 2649 std::tm minValidDate = {};
2382 2649 minValidDate.tm_year = 125; // 2025 fallback
2383 2649 minValidDate.tm_mon = 0;
2384 2649 minValidDate.tm_mday = 1;
2385
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 Json::Value imagerRoot;
2386
4/8
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2649 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2649 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2649 times.
✗ Branch 7 not taken.
5298 if (LoadJsonFromFile(getFPPDDir("/rpi-imager/rpi-imager_falcon_player.json"), imagerRoot, JsonRoot::Object)) {
2387
6/12
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2649 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2649 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2649 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 2649 times.
✗ Branch 9 not taken.
✓ Branch 10 taken 2649 times.
✗ Branch 11 not taken.
2649 if (imagerRoot.isMember("os_list") && imagerRoot["os_list"].isArray()) {
2388 2649 std::time_t latestRelease = 0;
2389 // Find the latest release date across all OS images
2390
8/14
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2649 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2649 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 10596 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 10596 times.
✗ Branch 9 not taken.
✓ Branch 10 taken 13245 times.
✗ Branch 11 not taken.
✓ Branch 12 taken 10596 times.
✓ Branch 13 taken 2649 times.
13245 for (const auto& osEntry : imagerRoot["os_list"]) {
2391 // Parsed without throwing: std::stoi on a malformed date (and
2392 // isMember/asString on an entry of the wrong JSON type) threw
2393 // out of MainLoop and took fppd down at startup. An entry
2394 // that doesn't parse is skipped.
2395
6/12
✓ Branch 0 taken 10596 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 10596 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 10596 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 10596 times.
✗ Branch 7 not taken.
✗ Branch 8 not taken.
✓ Branch 9 taken 10596 times.
✗ Branch 10 not taken.
✓ Branch 11 taken 10596 times.
10596 if (!osEntry.isObject() || !osEntry["release_date"].isString()) {
2396 ✗ continue;
2397 }
2398 // Parse "YYYY-MM-DD" format
2399 10596 int year = 0, month = 0, day = 0;
2400
2/4
✓ Branch 0 taken 10596 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 10596 times.
✗ Branch 3 not taken.
10596 if (sscanf(osEntry["release_date"].asCString(), "%4d-%2d-%2d", &year, &month, &day) != 3 ||
2401
7/14
✓ Branch 0 taken 10596 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 10596 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 10596 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 10596 times.
✗ Branch 7 not taken.
✓ Branch 8 taken 10596 times.
✗ Branch 9 not taken.
✗ Branch 10 not taken.
✓ Branch 11 taken 10596 times.
✗ Branch 12 not taken.
✓ Branch 13 taken 10596 times.
10596 year < 1970 || month < 1 || month > 12 || day < 1 || day > 31) {
2402 ✗ continue;
2403 }
2404 10596 std::tm releaseTime = {};
2405 10596 releaseTime.tm_year = year - 1900;
2406 10596 releaseTime.tm_mon = month - 1;
2407 10596 releaseTime.tm_mday = day;
2408 10596 std::time_t releaseTimestamp = std::mktime(&releaseTime);
2409
2/2
✓ Branch 0 taken 2649 times.
✓ Branch 1 taken 7947 times.
10596 if (releaseTimestamp > latestRelease) {
2410 2649 latestRelease = releaseTimestamp;
2411 2649 minValidDate = releaseTime;
2412 }
2413 }
2414 }
2415 }
2416 2649 std::time_t minValidTime = std::mktime(&minValidDate);
2417 2649 bool clockWarningAdded = false;
2418
2419
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 StartChannelOutputThread();
2420
3/4
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2634 times.
✓ Branch 3 taken 15 times.
2649 if (!getSettingInt("restarted")) {
2421
1/2
✓ Branch 0 taken 2634 times.
✗ Branch 1 not taken.
2634 sequence->SendBlankingData();
2422 }
2423
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 bool alwaysTransmit = (bool)getSettingInt("alwaysTransmit");
2424
2425 // A process killed by the main-loop watchdog leaves its show behind in
2426 // tmpfs instead of on the command line (there is no orderly re-exec to put
2427 // it there) -- fold it into the same resume settings a restart would have
2428 // set, before either resume path below reads them (issue #2727).
2429
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 ApplyStallResumeState();
2430
2431
3/4
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2588 times.
✓ Branch 3 taken 61 times.
2649 if (getFPPmode() & PLAYER_MODE) {
2432 // Don't start scheduler if clock is obviously wrong (date before last release)
2433 // This prevents scheduling issues on systems without RTC that boot with incorrect time
2434 // The scheduler will start when time is corrected via time jump detection
2435 2588 std::time_t now = time(nullptr);
2436
2437
2/2
✓ Branch 0 taken 2579 times.
✓ Branch 1 taken 9 times.
2588 if (now >= minValidTime) {
2438
1/2
✓ Branch 0 taken 2579 times.
✗ Branch 1 not taken.
2579 scheduler->CheckIfShouldBePlayingNow();
2439 } else {
2440 struct tm timeinfo;
2441 9 localtime_r(&now, &timeinfo);
2442
1/2
✓ Branch 0 taken 9 times.
✗ Branch 1 not taken.
9 LogWarn(VB_SCHEDULE, "Clock appears incorrect (date %04d-%02d-%02d before release), delaying scheduler start until time sync\n",
2443 timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday);
2444
2/4
✓ Branch 0 taken 9 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 9 times.
✗ Branch 3 not taken.
27 WarningHolder::AddWarning(55, "System clock not set - scheduler start delayed until time sync");
2445 9 clockWarningAdded = true;
2446 }
2447
2448 // If a scheduled item covered the resume, CheckIfShouldBePlayingNow()
2449 // above already started it and cleared resumePlaylist. Anything left
2450 // here is a show that was running with no schedule behind it when we
2451 // restarted ourselves to recover the video decoder -- start it, or the
2452 // player comes back idle and every synced remote sits on its last frame
2453 // waiting for sync packets that never arrive (issue #2727).
2454
1/2
✓ Branch 0 taken 2588 times.
✗ Branch 1 not taken.
2588 std::string resumePlaylist = getSetting("resumePlaylist");
2455
6/8
✓ Branch 0 taken 2588 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✓ Branch 3 taken 2586 times.
✓ Branch 4 taken 2 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 2 times.
✓ Branch 7 taken 2586 times.
2590 if (getSettingInt("resumeUnscheduled") && !resumePlaylist.empty() &&
2456
2/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
2 Player::INSTANCE.GetStatus() == FPP_STATUS_IDLE) {
2457
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 int resumePosition = getSettingInt("resumePosition");
2458
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 int resumeRepeat = getSettingInt("resumeRepeat");
2459
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 LogInfo(VB_PLAYLIST, "Resuming unscheduled playlist '%s' at position %d (repeat %d) after restart\n",
2460 resumePlaylist.c_str(), resumePosition, resumeRepeat);
2461
3/6
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 2 times.
✗ Branch 5 not taken.
8 SetSetting("resumePlaylist", "");
2462
2/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
4 SetSetting("resumePosition", 0);
2463
2/4
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2 times.
✗ Branch 3 not taken.
2 SetSetting("resumeUnscheduled", 0);
2464
1/2
✓ Branch 0 taken 2 times.
✗ Branch 1 not taken.
2 Player::INSTANCE.StartPlaylist(resumePlaylist, resumeRepeat, resumePosition);
2465 }
2466 2588 }
2467
4/6
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 2649 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✓ Branch 5 taken 2648 times.
5298 if (CommandManager::INSTANCE.HasPreset("FPPD_STARTED")) {
2468
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
2 CommandManager::INSTANCE.TriggerPreset("FPPD_STARTED");
2469 }
2470
2471
2/2
✓ Branch 0 taken 10608 times.
✓ Branch 1 taken 2649 times.
13257 for (auto& a : callbacks) {
2472
1/2
✓ Branch 0 taken 10608 times.
✗ Branch 1 not taken.
10608 EPollManager::INSTANCE.addFileDescriptor(a.first, a.second);
2473 }
2474
2475
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 multiSync->Discover();
2476
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 Events::Ready();
2477
2478 // Wire up EPollManager timer to fire Timers, so epoll_wait/kevent
2479 // wakes precisely when the next timer is due
2480
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 EPollManager::INSTANCE.setTimerCallback([]() {
2481 21001 Timers::INSTANCE.fireTimers();
2482 21001 });
2483
2484
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 LogInfo(VB_GENERAL, "Starting main processing loop\n");
2485
2486
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 WarningHolder::UpdateLogLevelWarnings();
2487
2488 2649 int idleCount = 0;
2489
2490
1/2
✓ Branch 0 taken 2649 times.
✗ Branch 1 not taken.
2649 StartMainLoopWatchdog();
2491
2492 // Relaxed: a stop flag and a timestamp for the watchdog, read or written
2493 // on every pass, with nothing published through either.
2494
2/2
✓ Branch 0 taken 597760 times.
✓ Branch 1 taken 2620 times.
603029 while (runMainFPPDLoop.load(std::memory_order_relaxed)) {
2495
1/2
✓ Branch 0 taken 597760 times.
✗ Branch 1 not taken.
597760 s_mainLoopHeartbeat.store(MonotonicMS(), std::memory_order_relaxed);
2496
1/2
✓ Branch 0 taken 597760 times.
✗ Branch 1 not taken.
597760 MAIN_LOOP_PHASE("epoll/callbacks");
2497
1/2
✓ Branch 0 taken 597731 times.
✗ Branch 1 not taken.
597760 EPollManager::WaitResult epollresult = EPollManager::INSTANCE.waitForEvents(sleepms);
2498 597731 bool pushBridgeData = epollresult == EPollManager::WaitResult::SOME_TRUE;
2499
2/2
✓ Branch 0 taken 2665 times.
✓ Branch 1 taken 595066 times.
597731 if (epollresult == EPollManager::WaitResult::INTERRUPTED) {
2500 // We get interrupted when media players finish
2501 2665 continue;
2502 }
2503
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 595066 times.
595066 if (epollresult == EPollManager::WaitResult::FAILED) {
2504 ✗ LogErr(VB_GENERAL, "Main epoll() failed: %s\n", FPPstrerror(errno));
2505 ✗ runMainFPPDLoop = 0;
2506 ✗ continue;
2507 }
2508 // Check to see if we need to start up the output thread.
2509
1/2
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
595066 MAIN_LOOP_PHASE("channel output thread check");
2510 // A video playing onto an overlay model counts too: its frames only
2511 // reach the model through this thread, and the model does not show as
2512 // active until one has, so after an output reload stopped the thread
2513 // nothing else would start it again.
2514
5/6
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 116264 times.
✓ Branch 3 taken 478802 times.
✓ Branch 4 taken 33 times.
✓ Branch 5 taken 595033 times.
711330 if ((!ChannelOutputThreadIsRunning()) &&
2515
2/4
✓ Branch 0 taken 116264 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 116264 times.
✗ Branch 3 not taken.
116264 ((PixelOverlayManager::INSTANCE.hasActiveOverlays()) ||
2516
3/6
✓ Branch 0 taken 116264 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 116264 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 116264 times.
✗ Branch 5 not taken.
116264 (ChannelTester::INSTANCE.Testing()) ||
2517
3/4
✓ Branch 0 taken 116264 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 116232 times.
✓ Branch 3 taken 32 times.
116264 (alwaysTransmit) || sequence->hasBridgeData() ||
2518 #ifdef HAS_GSTREAMER
2519
4/6
✓ Branch 0 taken 116232 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 116231 times.
✓ Branch 3 taken 1 times.
✗ Branch 4 not taken.
✓ Branch 5 taken 116231 times.
116232 GStreamerOutput::IsOverlayingVideo() ||
2520 #endif
2521 pushBridgeData)) {
2522
1/2
✓ Branch 0 taken 33 times.
✗ Branch 1 not taken.
33 StartChannelOutputThread();
2523 }
2524
2525
3/4
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 571726 times.
✓ Branch 3 taken 23340 times.
595066 if (getFPPmode() & PLAYER_MODE) {
2526 // Keep the watchdog's idea of what is playing current -- it cannot
2527 // read this out of Player itself once the loop is stalled.
2528
1/2
✓ Branch 0 taken 571726 times.
✗ Branch 1 not taken.
571726 RecordMainLoopShowSnapshot();
2529
2530
3/4
✓ Branch 0 taken 571726 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 391469 times.
✓ Branch 3 taken 180257 times.
571726 if (Player::INSTANCE.IsPlaying()) {
2531
2/2
✓ Branch 0 taken 1186 times.
✓ Branch 1 taken 390283 times.
391469 if (prevFPPstatus == FPP_STATUS_IDLE) {
2532 1186 sleepms = 10;
2533 }
2534
2535 // Check again here in case PlayListPlayingInit
2536 // didn't find anything and put us back to IDLE
2537
2/4
✓ Branch 0 taken 391469 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 391469 times.
✗ Branch 3 not taken.
391469 if (Player::INSTANCE.IsPlaying()) {
2538
1/2
✓ Branch 0 taken 391469 times.
✗ Branch 1 not taken.
391469 MAIN_LOOP_PHASE("Player::Process");
2539
1/2
✓ Branch 0 taken 391469 times.
✗ Branch 1 not taken.
391469 Player::INSTANCE.Process();
2540 }
2541 }
2542
2543 // Read once: a stop from another thread (the API, MQTT) can land
2544 // between two reads, and then the second recorded "idle" as the
2545 // previous status and the playing-to-idle change was never seen,
2546 // so the stopped playlist was never cleaned up and the scheduler
2547 // never asked whether something should be playing. For the same
2548 // reason "stopping now" counts below: a stop holds it while the
2549 // entry stops, and a pass that read it then never saw the change.
2550
1/2
✓ Branch 0 taken 571726 times.
✗ Branch 1 not taken.
571726 PlaylistStatus curStatus = Player::INSTANCE.GetStatus();
2551 571726 int reactivated = 0;
2552 // Set when the change to idle is left for a later pass to see.
2553 571726 bool unrecorded = false;
2554
2/2
✓ Branch 0 taken 180497 times.
✓ Branch 1 taken 391229 times.
571726 if (curStatus == FPP_STATUS_IDLE) {
2555
4/4
✓ Branch 0 taken 177631 times.
✓ Branch 1 taken 2866 times.
✓ Branch 2 taken 177628 times.
✓ Branch 3 taken 3 times.
180497 if ((prevFPPstatus == FPP_STATUS_PLAYLIST_PLAYING) ||
2556
2/2
✓ Branch 0 taken 177381 times.
✓ Branch 1 taken 247 times.
177628 (prevFPPstatus == FPP_STATUS_PLAYLIST_PAUSED) ||
2557
2/2
✓ Branch 0 taken 177371 times.
✓ Branch 1 taken 10 times.
177381 (prevFPPstatus == FPP_STATUS_STOPPING_NOW) ||
2558
2/2
✓ Branch 0 taken 3 times.
✓ Branch 1 taken 177368 times.
177371 (prevFPPstatus == FPP_STATUS_STOPPING_GRACEFULLY) ||
2559 (prevFPPstatus == FPP_STATUS_STOPPING_GRACEFULLY_AFTER_LOOP)) {
2560
1/2
✓ Branch 0 taken 3129 times.
✗ Branch 1 not taken.
3129 MAIN_LOOP_PHASE("Player::Cleanup");
2561 // Read after the status: a switch holds its scope from
2562 // before its stop, so idle in one is seen with it held.
2563 // Cleanup() returns 0 if a start landed since the read.
2564 // Either way nothing stopped, and asking the scheduler
2565 // would pre-empt the new playlist (issue #3140). If the
2566 // start fails, a later pass sees the idle and acts.
2567
8/10
✓ Branch 0 taken 3129 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 906 times.
✓ Branch 3 taken 2223 times.
✓ Branch 4 taken 906 times.
✗ Branch 5 not taken.
✓ Branch 6 taken 1 times.
✓ Branch 7 taken 905 times.
✓ Branch 8 taken 2224 times.
✓ Branch 9 taken 905 times.
3129 if (Player::Switching() || !Player::INSTANCE.Cleanup()) {
2568 2224 unrecorded = true;
2569 } else {
2570
3/4
✓ Branch 0 taken 905 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 536 times.
✓ Branch 3 taken 369 times.
905 if (Player::INSTANCE.GetForceStopped())
2571
2/4
✓ Branch 0 taken 536 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 536 times.
✗ Branch 3 not taken.
536 scheduler->CheckIfShouldBePlayingNow(0, Player::INSTANCE.GetScheduleEntry());
2572 else
2573
1/2
✓ Branch 0 taken 369 times.
✗ Branch 1 not taken.
369 scheduler->CheckIfShouldBePlayingNow();
2574
2575
3/4
✓ Branch 0 taken 905 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 40 times.
✓ Branch 3 taken 865 times.
905 if (Player::INSTANCE.GetStatus() != FPP_STATUS_IDLE)
2576 40 reactivated = 1;
2577 else
2578 865 sleepms = 50;
2579 }
2580 }
2581 }
2582
2583
2/2
✓ Branch 0 taken 40 times.
✓ Branch 1 taken 571686 times.
571726 if (reactivated)
2584 40 prevFPPstatus = FPP_STATUS_IDLE;
2585
2/2
✓ Branch 0 taken 569462 times.
✓ Branch 1 taken 2224 times.
571686 else if (!unrecorded)
2586 569462 prevFPPstatus = curStatus;
2587
2588 // Process() frees retired playlists and entries, but only runs
2589 // while something plays; free them while idle too.
2590
3/4
✓ Branch 0 taken 571726 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 180632 times.
✓ Branch 3 taken 391094 times.
571726 if (!Player::INSTANCE.IsPlaying()) {
2591
1/2
✓ Branch 0 taken 180632 times.
✗ Branch 1 not taken.
180632 Playlist::ReleaseRetired();
2592 }
2593
2594
2/4
✓ Branch 0 taken 23340 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 23340 times.
✗ Branch 3 not taken.
23340 } else if (getFPPmode() == REMOTE_MODE) {
2595
2/2
✓ Branch 0 taken 14085 times.
✓ Branch 1 taken 9255 times.
23340 if (mediaOutputStatus.status == MEDIAOUTPUTSTATUS_PLAYING) {
2596
1/2
✓ Branch 0 taken 14085 times.
✗ Branch 1 not taken.
14085 MAIN_LOOP_PHASE("Player::ProcessMedia");
2597
1/2
✓ Branch 0 taken 14085 times.
✗ Branch 1 not taken.
14085 Player::INSTANCE.ProcessMedia();
2598 } else {
2599
1/2
✓ Branch 0 taken 9255 times.
✗ Branch 1 not taken.
9255 MAIN_LOOP_PHASE("CheckSyncedMediaIdleTimeout");
2600 // Media that ran to its end and was never stopped by the
2601 // player (issue #2727) -- only checked when not playing, so
2602 // free-running through a sync gap is untouched.
2603
1/2
✓ Branch 0 taken 9255 times.
✗ Branch 1 not taken.
9255 multiSync->CheckSyncedMediaIdleTimeout();
2604 }
2605 }
2606
2607 // Only run scheduler if clock appears valid (same check as initial scheduler start)
2608 595066 std::time_t now = time(nullptr);
2609
2/2
✓ Branch 0 taken 592789 times.
✓ Branch 1 taken 2277 times.
595066 if (now >= minValidTime) {
2610
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 592789 times.
592789 if (clockWarningAdded) {
2611 // clock was corrected (time sync) since startup — clear the warning
2612 ✗ WarningHolder::RemoveWarning(55, "System clock not set - scheduler start delayed until time sync");
2613 ✗ clockWarningAdded = false;
2614 }
2615
1/2
✓ Branch 0 taken 592789 times.
✗ Branch 1 not taken.
592789 MAIN_LOOP_PHASE("scheduler");
2616
1/2
✓ Branch 0 taken 592789 times.
✗ Branch 1 not taken.
592789 scheduler->ScheduleProc();
2617 }
2618
2619
2/2
✓ Branch 0 taken 19551 times.
✓ Branch 1 taken 575515 times.
595066 if (pushBridgeData) {
2620
1/2
✓ Branch 0 taken 19551 times.
✗ Branch 1 not taken.
19551 MAIN_LOOP_PHASE("ForceChannelOutputNow");
2621
1/2
✓ Branch 0 taken 19551 times.
✗ Branch 1 not taken.
19551 ForceChannelOutputNow();
2622 }
2623 595066 bool doPing = false;
2624
2/2
✓ Branch 0 taken 513711 times.
✓ Branch 1 taken 81355 times.
595066 if (epollresult == EPollManager::WaitResult::TIMEOUT) {
2625 513711 idleCount++;
2626
2/2
✓ Branch 0 taken 21437 times.
✓ Branch 1 taken 492274 times.
513711 if (idleCount >= 20) {
2627 21437 doPing = true;
2628 }
2629
2/2
✓ Branch 0 taken 7884 times.
✓ Branch 1 taken 73471 times.
81355 } else if (idleCount > 0) {
2630 7884 doPing = true;
2631 } else {
2632 73471 idleCount--;
2633
2/2
✓ Branch 0 taken 3121 times.
✓ Branch 1 taken 70350 times.
73471 if (idleCount < -20) {
2634 3121 doPing = true;
2635 }
2636 }
2637
2/2
✓ Branch 0 taken 32442 times.
✓ Branch 1 taken 562624 times.
595066 if (doPing) {
2638 32442 idleCount = 0;
2639
1/2
✓ Branch 0 taken 32442 times.
✗ Branch 1 not taken.
32442 MAIN_LOOP_PHASE("multisync PeriodicPing");
2640
1/2
✓ Branch 0 taken 32442 times.
✗ Branch 1 not taken.
32442 multiSync->PeriodicPing();
2641
2/2
✓ Branch 0 taken 20 times.
✓ Branch 1 taken 32422 times.
32442 if (--publishCounter < 0) {
2642
2/4
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 20 times.
✗ Branch 3 not taken.
20 PublishStatsBackground(publishReason);
2643 // This counter only decides how often the (very cheap) time
2644 // check inside PublishStatsBackground runs; that check enforces
2645 // the real cadence. It has to be comfortably finer than the
2646 // cadence or it becomes the limiting factor: doPing runs about
2647 // once a second when idle, so the previous 60480 was roughly 17
2648 // hours and a 24-hour guard would have landed near 34.
2649 20 publishCounter = 3600;
2650
1/2
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
20 publishReason = "normal";
2651 }
2652 // A cape whose signature is not bound to this hardware is detected
2653 // at boot, before there is a network to report it over. This is the
2654 // point where there is one.
2655
1/2
✓ Branch 0 taken 32442 times.
✗ Branch 1 not taken.
32442 MAIN_LOOP_PHASE("cape license notify");
2656
1/2
✓ Branch 0 taken 32442 times.
✗ Branch 1 not taken.
32442 CapeLicenseNotifyBackground();
2657 // also do the periodic work in the api server while idle
2658
1/2
✓ Branch 0 taken 32442 times.
✗ Branch 1 not taken.
32442 MAIN_LOOP_PHASE("apiServer periodicWork");
2659
1/2
✓ Branch 0 taken 32442 times.
✗ Branch 1 not taken.
32442 apiServer.periodicWork();
2660 }
2661
1/2
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
595066 MAIN_LOOP_PHASE("timers");
2662
1/2
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
595066 Timers::INSTANCE.fireTimers();
2663
1/2
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
595066 MAIN_LOOP_PHASE("curls");
2664
1/2
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
595066 CurlManager::INSTANCE.processCurls();
2665
1/2
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
595066 MAIN_LOOP_PHASE("GPIO inputs");
2666
1/2
✓ Branch 0 taken 595066 times.
✗ Branch 1 not taken.
595066 GPIOManager::INSTANCE.CheckGPIOInputs();
2667 }
2668
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 MAIN_LOOP_PHASE("loop exited");
2669
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 FileMonitor::INSTANCE.Cleanup();
2670
2671
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 LogInfo(VB_GENERAL, "Stopping channel output thread.\n");
2672
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 StopChannelOutputThread();
2673
2674
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 Bridge_Shutdown();
2675
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 EPollManager::INSTANCE.shutdown();
2676
1/2
✓ Branch 0 taken 2620 times.
✗ Branch 1 not taken.
2620 LogInfo(VB_GENERAL, "Main Loop complete, shutting down.\n");
2677 2620 }
2678
2679 // Each process CreateDaemon() leaves behind exits without running static
2680 // destructors: they belong to the daemon. A destructor can block on a thread
2681 // started before the fork: glibc's pthread_cond_destroy() waits for its
2682 // waiters, and when "-v" started the volume worker that early, exit() never
2683 // returned and whatever ran "fppd -d" never saw its process end.
2684 10 static void LeaveForkedProcess(int code) {
2685 10 fflush(nullptr);
2686 10 _exit(code);
2687 }
2688
2689 5 void CreateDaemon(void) {
2690 /* Fork and terminate parent so we can run in the background */
2691 /* Fork off the parent process */
2692 5 pid = fork();
2693
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (pid < 0) {
2694 ✗ LeaveForkedProcess(EXIT_FAILURE);
2695 }
2696 /* If we got a good PID, then
2697 we can exit the parent process. */
2698
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 5 times.
10 if (pid > 0) {
2699 5 LeaveForkedProcess(EXIT_SUCCESS);
2700 }
2701
2702 /* Change the file mode mask */
2703 5 umask(0);
2704
2705 /* Create a new SID for the child process */
2706 5 sid = setsid();
2707
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 5 times.
5 if (sid < 0) {
2708 /* Log any failures here */
2709 ✗ LeaveForkedProcess(EXIT_FAILURE);
2710 }
2711
2712 /* Fork a second time to get rid of session leader */
2713 /* Fork off the parent process */
2714 5 pid = fork();
2715
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 10 times.
10 if (pid < 0) {
2716 ✗ LeaveForkedProcess(EXIT_FAILURE);
2717 }
2718 /* If we got a good PID, then
2719 we can exit the parent process. */
2720
2/2
✓ Branch 0 taken 5 times.
✓ Branch 1 taken 5 times.
10 if (pid > 0) {
2721 5 LeaveForkedProcess(EXIT_SUCCESS);
2722 }
2723
2724 /* Point the standard file descriptors at /dev/null. Closed, they were
2725 taken by whatever fppd opened next (see OpenStandardDescriptors() in
2726 common_mini.cpp) */
2727 5 int devNull = open("/dev/null", O_RDWR);
2728
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 if (devNull >= 0) {
2729 5 dup2(devNull, STDIN_FILENO);
2730 5 dup2(devNull, STDOUT_FILENO);
2731 5 dup2(devNull, STDERR_FILENO);
2732
1/2
✓ Branch 0 taken 5 times.
✗ Branch 1 not taken.
5 if (devNull > STDERR_FILENO) {
2733 5 close(devNull);
2734 }
2735 }
2736 5 }
2737
2738 1 void PublishStatsForce(std::string reason) {
2739
2/4
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
2 SetThreadName("FPP-PubStats");
2740
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
2 std::string result("");
2741
3/6
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 1 times.
✗ Branch 5 not taken.
1 urlPost("http://localhost/api/statistics/usage?reason=" + reason, "", result);
2742
1/2
✓ Branch 0 taken 1 times.
✗ Branch 1 not taken.
1 LogInfo(VB_GENERAL, "Publishing statistics because of \"%s\" = %s\n", reason.c_str(), result.c_str());
2743 1 }
2744
2745 // How often this daemon ASKS the statistics route whether to publish. It is
2746 // deliberately much shorter than the publish interval itself, which lives in the
2747 // route (STATS_PUBLISH_INTERVAL_DAYS) because that is the side that can see the
2748 // payload and hold a timestamp across restarts.
2749 //
2750 // The two must not be equal. This counter resets on every restart, so if it
2751 // matched the publish interval a box that rebooted just before the interval
2752 // elapsed would be told "not yet", spend its guard, and not ask again for a full
2753 // interval -- pushing the periodic publish out to nearly double, and with it the
2754 // only signal that says the device is still alive. Asking daily bounds that
2755 // error at one day.
2756 #define STATS_PUBLISH_ASK_HOURS 24
2757
2758 20 void PublishStatsBackground(std::string reason) {
2759 // Rate limit on ASKING, not on sending. Whether anything is actually
2760 // uploaded is the route's decision: a restart publishes when the device's
2761 // configuration signature has moved and stays quiet when it has not, and a
2762 // device that never changes still checks in on the publish interval so the
2763 // project can see it is alive.
2764 // steady_clock: a wall-clock step back held the ask off for the size of the step
2765
3/8
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 20 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 20 times.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
20 static auto lastAsk = std::chrono::steady_clock::now() - std::chrono::hours(STATS_PUBLISH_ASK_HOURS);
2766 20 auto now_ts = std::chrono::steady_clock::now();
2767
2/4
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 20 times.
✗ Branch 3 not taken.
20 auto hours = std::chrono::duration_cast<std::chrono::hours>(now_ts - lastAsk);
2768
2769
1/2
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
20 if (hours.count() >= STATS_PUBLISH_ASK_HOURS) {
2770
1/2
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
20 std::string mode = getSetting("statsPublish");
2771
2/4
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 20 times.
20 if (mode == "Enabled") {
2772 // Spend the budget only on a call that can actually do something.
2773 // It used to be spent here unconditionally, which meant a box that
2774 // booted with statistics off burned its one ask of the day on a
2775 // branch that contacts nobody -- so a user who then turned them on
2776 // during setup published nothing for up to 24 hours, unless a reboot
2777 // happened to reset this static. Now the first tick after they opt
2778 // in is the one that publishes.
2779 ✗ lastAsk = now_ts;
2780 ✗ std::thread t(PublishStatsForce, reason);
2781 ✗ t.detach();
2782 ✗ } else {
2783 // Not spending lastAsk means this branch is reached on every idle
2784 // tick rather than daily, so the message needs its own limiter or it
2785 // becomes a per-second log. The setting lookup itself is a cheap map
2786 // read and is fine to repeat.
2787
3/8
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 20 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 20 times.
✗ Branch 5 not taken.
✗ Branch 6 not taken.
✗ Branch 7 not taken.
20 static auto lastLog = std::chrono::steady_clock::now() - std::chrono::hours(STATS_PUBLISH_ASK_HOURS);
2788
3/6
✓ Branch 0 taken 20 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 20 times.
✗ Branch 3 not taken.
✗ Branch 4 not taken.
✓ Branch 5 taken 20 times.
20 if (std::chrono::duration_cast<std::chrono::hours>(now_ts - lastLog).count() >= STATS_PUBLISH_ASK_HOURS) {
2789 ✗ lastLog = now_ts;
2790 ✗ LogInfo(VB_GENERAL, "Not Publishing statistics as mode is '%s'\n", mode.c_str());
2791 }
2792 }
2793 20 } else {
2794 ✗ LogDebug(VB_GENERAL, "PublishStats called, but not time to ask yet.\n");
2795 }
2796 20 }
2797