Bug Summary

File:lwan-thread.c
Warning:line 885, column 53
The left operand of '==' is a garbage value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name lwan-thread.c -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -mframe-pointer=all -fmath-errno -fno-rounding-math -mconstructor-aliases -fno-plt -munwind-tables -target-cpu x86-64 -fno-split-dwarf-inlining -debugger-tuning=gdb -resource-dir /usr/lib/clang/11.1.0 -include /home/buildbot/lwan-worker/clang-analyze/build/lwan-build-config.h -D _FILE_OFFSET_BITS=64 -D _TIME_BITS=64 -I /home/buildbot/lwan-worker/clang-analyze/build/src/lib/missing -I /usr/include/luajit-2.0 -I /usr/include/valgrind -I /home/buildbot/lwan-worker/clang-analyze/build/src/lib -I /home/buildbot/lwan-worker/clang-analyze/build -internal-isystem /usr/local/include -internal-isystem /usr/lib/clang/11.1.0/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-unused-parameter -Wno-free-nonheap-object -std=gnu99 -fdebug-compilation-dir /home/buildbot/lwan-worker/clang-analyze/build/src/lib -ferror-limit 19 -stack-protector 2 -fgnuc-version=4.2.1 -analyzer-output=html -faddrsig -o /home/buildbot/lwan-worker/clang-analyze/CLANG/2021-05-28-160918-1241651-1 -x c /home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c
1/*
2 * lwan - simple web server
3 * Copyright (c) 2012, 2013 Leandro A. F. Pereira <leandro@hardinfo.org>
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
18 * USA.
19 */
20
21#define _GNU_SOURCE
22#include <assert.h>
23#include <errno(*__errno_location ()).h>
24#include <fcntl.h>
25#include <pthread.h>
26#include <sched.h>
27#include <stdlib.h>
28#include <string.h>
29#include <sys/epoll.h>
30#include <sys/ioctl.h>
31#include <sys/socket.h>
32#include <unistd.h>
33
34#if defined(HAVE_SO_ATTACH_REUSEPORT_CBPF)
35#include <linux1/filter.h>
36#endif
37
38#include "lwan-private.h"
39#include "lwan-tq.h"
40#include "list.h"
41
42static void lwan_strbuf_free_defer(void *data)
43{
44 lwan_strbuf_free((struct lwan_strbuf *)data);
45}
46
47static void graceful_close(struct lwan *l,
48 struct lwan_connection *conn,
49 char buffer[static DEFAULT_BUFFER_SIZE4096])
50{
51 int fd = lwan_connection_get_fd(l, conn);
52
53 while (TIOCOUTQ0x5411) {
54 /* This ioctl isn't probably doing what it says on the tin; the details
55 * are subtle, but it seems to do the trick to allow gracefully closing
56 * the connection in some cases with minimal system calls. */
57 int bytes_waiting;
58 int r = ioctl(fd, TIOCOUTQ0x5411, &bytes_waiting);
59
60 if (!r && !bytes_waiting) /* See note about close(2) below. */
61 return;
62 if (r < 0 && errno(*__errno_location ()) == EINTR4)
63 continue;
64
65 break;
66 }
67
68 if (UNLIKELY(shutdown(fd, SHUT_WR) < 0)__builtin_expect(((shutdown(fd, SHUT_WR) < 0)), (0))) {
69 if (UNLIKELY(errno == ENOTCONN)__builtin_expect((((*__errno_location ()) == 107)), (0)))
70 return;
71 }
72
73 for (int tries = 0; tries < 20; tries++) {
74 ssize_t r = recv(fd, buffer, DEFAULT_BUFFER_SIZE4096, 0);
75
76 if (!r)
77 break;
78
79 if (r < 0) {
80 switch (errno(*__errno_location ())) {
81 case EAGAIN11:
82 break;
83 case EINTR4:
84 continue;
85 default:
86 return;
87 }
88 }
89
90 coro_yield(conn->coro, CONN_CORO_WANT_READ);
91 }
92
93 /* close(2) will be called when the coroutine yields with CONN_CORO_ABORT */
94}
95
96static __thread __uint128_t lehmer64_state;
97
98static void lwan_random_seed_prng_for_thread(uint64_t fallback_seed)
99{
100 if (lwan_getentropy(&lehmer64_state, sizeof(lehmer64_state), 0) < 0) {
101 lwan_status_warning("Couldn't get proper entropy for PRNG, using fallback seed")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 101, __FUNCTION__, "Couldn't get proper entropy for PRNG, using fallback seed"
)
;
102 lehmer64_state |= fallback_seed;
103 lehmer64_state <<= 32;
104 lehmer64_state |= fallback_seed;
105 }
106}
107
108uint64_t lwan_random_uint64()
109{
110 /* https://lemire.me/blog/2019/03/19/the-fastest-conventional-random-number-generator-that-can-pass-big-crush/ */
111 lehmer64_state *= 0xda942042e4dd58b5ull;
112 return (uint64_t)(lehmer64_state >> 64);
113}
114
115__attribute__((noreturn)) static int process_request_coro(struct coro *coro,
116 void *data)
117{
118 /* NOTE: This function should not return; coro_yield should be used
119 * instead. This ensures the storage for `strbuf` is alive when the
120 * coroutine ends and lwan_strbuf_free() is called. */
121 struct lwan_connection *conn = data;
122 struct lwan *lwan = conn->thread->lwan;
123 int fd = lwan_connection_get_fd(lwan, conn);
124 enum lwan_request_flags flags = lwan->config.request_flags;
125 struct lwan_strbuf strbuf = LWAN_STRBUF_STATIC_INIT(struct lwan_strbuf) { .buffer = "" };
126 char request_buffer[DEFAULT_BUFFER_SIZE4096];
127 struct lwan_value buffer = {.value = request_buffer, .len = 0};
128 char *next_request = NULL((void*)0);
129 char *header_start[N_HEADER_START64];
130 struct lwan_proxy proxy;
131 const int error_when_n_packets = lwan_calculate_n_packets(DEFAULT_BUFFER_SIZE4096);
132
133 coro_defer(coro, lwan_strbuf_free_defer, &strbuf);
134
135 const size_t init_gen = 1; /* 1 call to coro_defer() */
136 assert(init_gen == coro_deferred_get_generation(coro))((void) sizeof ((init_gen == coro_deferred_get_generation(coro
)) ? 1 : 0), __extension__ ({ if (init_gen == coro_deferred_get_generation
(coro)) ; else __assert_fail ("init_gen == coro_deferred_get_generation(coro)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 136, __extension__ __PRETTY_FUNCTION__); }))
;
137
138 while (true1) {
139 struct lwan_request_parser_helper helper = {
140 .buffer = &buffer,
141 .next_request = next_request,
142 .error_when_n_packets = error_when_n_packets,
143 .header_start = header_start,
144 };
145 struct lwan_request request = {.conn = conn,
146 .global_response_headers = &lwan->headers,
147 .fd = fd,
148 .response = {.buffer = &strbuf},
149 .flags = flags,
150 .proxy = &proxy,
151 .helper = &helper};
152
153 lwan_process_request(lwan, &request);
154
155 /* Run the deferred instructions now (except those used to initialize
156 * the coroutine), so that if the connection is gracefully closed,
157 * the storage for ``helper'' is still there. */
158 coro_deferred_run(coro, init_gen);
159
160 if (UNLIKELY(!(conn->flags & CONN_IS_KEEP_ALIVE))__builtin_expect(((!(conn->flags & CONN_IS_KEEP_ALIVE)
)), (0))
) {
161 graceful_close(lwan, conn, request_buffer);
162 break;
163 }
164
165 if (next_request && *next_request) {
166 conn->flags |= CONN_CORK;
167
168 if (!(conn->flags & CONN_EVENTS_WRITE))
169 coro_yield(coro, CONN_CORO_WANT_WRITE);
170 } else {
171 conn->flags &= ~CONN_CORK;
172 coro_yield(coro, CONN_CORO_WANT_READ);
173 }
174
175 /* Ensure string buffer is reset between requests, and that the backing
176 * store isn't over 2KB. */
177 lwan_strbuf_reset_trim(&strbuf, 2048);
178
179 /* Only allow flags from config. */
180 flags = request.flags & (REQUEST_PROXIED | REQUEST_ALLOW_CORS);
181 next_request = helper.next_request;
182 }
183
184 coro_yield(coro, CONN_CORO_ABORT);
185 __builtin_unreachable();
186}
187
188static ALWAYS_INLINEinline __attribute__((always_inline)) uint32_t
189conn_flags_to_epoll_events(enum lwan_connection_flags flags)
190{
191 static const uint32_t map[CONN_EVENTS_MASK + 1] = {
192 [0 /* Suspended (timer or await) */] = EPOLLRDHUPEPOLLRDHUP,
193 [CONN_EVENTS_WRITE] = EPOLLOUTEPOLLOUT | EPOLLRDHUPEPOLLRDHUP,
194 [CONN_EVENTS_READ] = EPOLLINEPOLLIN | EPOLLRDHUPEPOLLRDHUP,
195 [CONN_EVENTS_READ_WRITE] = EPOLLINEPOLLIN | EPOLLOUTEPOLLOUT | EPOLLRDHUPEPOLLRDHUP,
196 };
197
198 return map[flags & CONN_EVENTS_MASK];
199}
200
201static void update_epoll_flags(int fd,
202 struct lwan_connection *conn,
203 int epoll_fd,
204 enum lwan_connection_coro_yield yield_result)
205{
206 static const enum lwan_connection_flags or_mask[CONN_CORO_MAX] = {
207 [CONN_CORO_YIELD] = 0,
208
209 [CONN_CORO_WANT_READ_WRITE] = CONN_EVENTS_READ_WRITE,
210 [CONN_CORO_WANT_READ] = CONN_EVENTS_READ,
211 [CONN_CORO_WANT_WRITE] = CONN_EVENTS_WRITE,
212
213 /* While the coro is suspended, we're not interested in either EPOLLIN
214 * or EPOLLOUT events. We still want to track this fd in epoll, though,
215 * so unset both so that only EPOLLRDHUP (plus the implicitly-set ones)
216 * are set. */
217 [CONN_CORO_SUSPEND] = CONN_SUSPENDED,
218
219 /* Ideally, when suspending a coroutine, the current flags&CONN_EVENTS_MASK
220 * would have to be stored and restored -- however, resuming as if the
221 * client coroutine is interested in a write event always guarantees that
222 * they'll be resumed as they're TCP sockets. There's a good chance that
223 * trying to read from a socket after resuming a coroutine will succeed,
224 * but if it doesn't because read() returns -EAGAIN, the I/O wrappers will
225 * yield with CONN_CORO_WANT_READ anyway. */
226 [CONN_CORO_RESUME] = CONN_EVENTS_WRITE,
227 };
228 static const enum lwan_connection_flags and_mask[CONN_CORO_MAX] = {
229 [CONN_CORO_YIELD] = ~0,
230
231 [CONN_CORO_WANT_READ_WRITE] = ~0,
232 [CONN_CORO_WANT_READ] = ~CONN_EVENTS_WRITE,
233 [CONN_CORO_WANT_WRITE] = ~CONN_EVENTS_READ,
234
235 [CONN_CORO_SUSPEND] = ~CONN_EVENTS_READ_WRITE,
236 [CONN_CORO_RESUME] = ~CONN_SUSPENDED,
237 };
238 enum lwan_connection_flags prev_flags = conn->flags;
239
240 conn->flags |= or_mask[yield_result];
241 conn->flags &= and_mask[yield_result];
242
243 if (conn->flags == prev_flags)
244 return;
245
246 struct epoll_event event = {
247 .events = conn_flags_to_epoll_events(conn->flags),
248 .data.ptr = conn,
249 };
250
251 if (UNLIKELY(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &event) < 0)__builtin_expect(((epoll_ctl(epoll_fd, 3, fd, &event) <
0)), (0))
)
252 lwan_status_perror("epoll_ctl")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 252, __FUNCTION__, "epoll_ctl")
;
253}
254
255static void clear_async_await_flag(void *data)
256{
257 struct lwan_connection *async_fd_conn = data;
258
259 async_fd_conn->flags &= ~CONN_ASYNC_AWAIT;
260}
261
262static enum lwan_connection_coro_yield
263resume_async(struct timeout_queue *tq,
264 enum lwan_connection_coro_yield yield_result,
265 int64_t from_coro,
266 struct lwan_connection *conn,
267 int epoll_fd)
268{
269 static const enum lwan_connection_flags to_connection_flags[] = {
270 [CONN_CORO_ASYNC_AWAIT_READ] = CONN_EVENTS_READ,
271 [CONN_CORO_ASYNC_AWAIT_WRITE] = CONN_EVENTS_WRITE,
272 [CONN_CORO_ASYNC_AWAIT_READ_WRITE] = CONN_EVENTS_READ_WRITE,
273 };
274 int await_fd = (int)((uint64_t)from_coro >> 32);
275 enum lwan_connection_flags flags;
276 int op;
277
278 assert(await_fd >= 0)((void) sizeof ((await_fd >= 0) ? 1 : 0), __extension__ ({
if (await_fd >= 0) ; else __assert_fail ("await_fd >= 0"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 278, __extension__ __PRETTY_FUNCTION__); }))
;
279 assert(yield_result >= CONN_CORO_ASYNC_AWAIT_READ &&((void) sizeof ((yield_result >= CONN_CORO_ASYNC_AWAIT_READ
&& yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE
) ? 1 : 0), __extension__ ({ if (yield_result >= CONN_CORO_ASYNC_AWAIT_READ
&& yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE
) ; else __assert_fail ("yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 280, __extension__ __PRETTY_FUNCTION__); }))
280 yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE)((void) sizeof ((yield_result >= CONN_CORO_ASYNC_AWAIT_READ
&& yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE
) ? 1 : 0), __extension__ ({ if (yield_result >= CONN_CORO_ASYNC_AWAIT_READ
&& yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE
) ; else __assert_fail ("yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 280, __extension__ __PRETTY_FUNCTION__); }))
;
281
282 flags = to_connection_flags[yield_result];
283
284 struct lwan_connection *await_fd_conn = &tq->lwan->conns[await_fd];
285 if (LIKELY(await_fd_conn->flags & CONN_ASYNC_AWAIT)__builtin_expect((!!(await_fd_conn->flags & CONN_ASYNC_AWAIT
)), (1))
) {
286 if (LIKELY((await_fd_conn->flags & CONN_EVENTS_MASK) == flags)__builtin_expect((!!((await_fd_conn->flags & CONN_EVENTS_MASK
) == flags)), (1))
)
287 return CONN_CORO_SUSPEND;
288
289 op = EPOLL_CTL_MOD3;
290 } else {
291 op = EPOLL_CTL_ADD1;
292 flags |= CONN_ASYNC_AWAIT;
293 coro_defer(conn->coro, clear_async_await_flag, await_fd_conn);
294 }
295
296 struct epoll_event event = {.events = conn_flags_to_epoll_events(flags),
297 .data.ptr = conn};
298 if (LIKELY(!epoll_ctl(epoll_fd, op, await_fd, &event))__builtin_expect((!!(!epoll_ctl(epoll_fd, op, await_fd, &
event))), (1))
) {
299 await_fd_conn->flags &= ~CONN_EVENTS_MASK;
300 await_fd_conn->flags |= flags;
301 return CONN_CORO_SUSPEND;
302 }
303
304 return CONN_CORO_ABORT;
305}
306
307static ALWAYS_INLINEinline __attribute__((always_inline)) void resume_coro(struct timeout_queue *tq,
308 struct lwan_connection *conn,
309 int epoll_fd)
310{
311 assert(conn->coro)((void) sizeof ((conn->coro) ? 1 : 0), __extension__ ({ if
(conn->coro) ; else __assert_fail ("conn->coro", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 311, __extension__ __PRETTY_FUNCTION__); }))
;
312
313 int64_t from_coro = coro_resume(conn->coro);
314 enum lwan_connection_coro_yield yield_result = from_coro & 0xffffffff;
315
316 if (UNLIKELY(yield_result >= CONN_CORO_ASYNC)__builtin_expect(((yield_result >= CONN_CORO_ASYNC)), (0)))
317 yield_result = resume_async(tq, yield_result, from_coro, conn, epoll_fd);
318
319 if (UNLIKELY(yield_result == CONN_CORO_ABORT)__builtin_expect(((yield_result == CONN_CORO_ABORT)), (0)))
320 return timeout_queue_expire(tq, conn);
321
322 return update_epoll_flags(lwan_connection_get_fd(tq->lwan, conn), conn,
323 epoll_fd, yield_result);
324}
325
326static void update_date_cache(struct lwan_thread *thread)
327{
328 time_t now = time(NULL((void*)0));
329
330 lwan_format_rfc_time(now, thread->date.date);
331 lwan_format_rfc_time(now + (time_t)thread->lwan->config.expires,
332 thread->date.expires);
333}
334
335static bool_Bool send_buffer_without_coro(int fd, const char *buf, size_t buf_len)
336{
337 size_t total_sent = 0;
338
339 for (int try = 0; try < 10; try++) {
340 size_t to_send = buf_len - total_sent;
341 if (!to_send)
342 return true1;
343
344 ssize_t sent = write(fd, buf + total_sent, to_send);
345 if (sent <= 0) {
346 if (errno(*__errno_location ()) == EINTR4)
347 continue;
348 break;
349 }
350
351 total_sent += (size_t)sent;
352 }
353
354 return false0;
355}
356
357static bool_Bool send_string_without_coro(int fd, const char *str)
358{
359 return send_buffer_without_coro(fd, str, strlen(str));
360}
361
362static ALWAYS_INLINEinline __attribute__((always_inline)) bool_Bool spawn_coro(struct lwan_connection *conn,
363 struct coro_switcher *switcher,
364 struct timeout_queue *tq)
365{
366 struct lwan_thread *t = conn->thread;
367
368 assert(!conn->coro)((void) sizeof ((!conn->coro) ? 1 : 0), __extension__ ({ if
(!conn->coro) ; else __assert_fail ("!conn->coro", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 368, __extension__ __PRETTY_FUNCTION__); }))
;
369 assert(!(conn->flags & CONN_ASYNC_AWAIT))((void) sizeof ((!(conn->flags & CONN_ASYNC_AWAIT)) ? 1
: 0), __extension__ ({ if (!(conn->flags & CONN_ASYNC_AWAIT
)) ; else __assert_fail ("!(conn->flags & CONN_ASYNC_AWAIT)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 369, __extension__ __PRETTY_FUNCTION__); }))
;
370 assert(t)((void) sizeof ((t) ? 1 : 0), __extension__ ({ if (t) ; else __assert_fail
("t", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 370, __extension__ __PRETTY_FUNCTION__); }))
;
371 assert((uintptr_t)t >= (uintptr_t)tq->lwan->thread.threads)((void) sizeof (((uintptr_t)t >= (uintptr_t)tq->lwan->
thread.threads) ? 1 : 0), __extension__ ({ if ((uintptr_t)t >=
(uintptr_t)tq->lwan->thread.threads) ; else __assert_fail
("(uintptr_t)t >= (uintptr_t)tq->lwan->thread.threads"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 371, __extension__ __PRETTY_FUNCTION__); }))
;
372 assert((uintptr_t)t <((void) sizeof (((uintptr_t)t < (uintptr_t)(tq->lwan->
thread.threads + tq->lwan->thread.count)) ? 1 : 0), __extension__
({ if ((uintptr_t)t < (uintptr_t)(tq->lwan->thread.
threads + tq->lwan->thread.count)) ; else __assert_fail
("(uintptr_t)t < (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 373, __extension__ __PRETTY_FUNCTION__); }))
373 (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count))((void) sizeof (((uintptr_t)t < (uintptr_t)(tq->lwan->
thread.threads + tq->lwan->thread.count)) ? 1 : 0), __extension__
({ if ((uintptr_t)t < (uintptr_t)(tq->lwan->thread.
threads + tq->lwan->thread.count)) ; else __assert_fail
("(uintptr_t)t < (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 373, __extension__ __PRETTY_FUNCTION__); }))
;
374
375 *conn = (struct lwan_connection){
376 .coro = coro_new(switcher, process_request_coro, conn),
377 .flags = CONN_EVENTS_READ,
378 .time_to_expire = tq->current_time + tq->move_to_last_bump,
379 .thread = t,
380 };
381 if (LIKELY(conn->coro)__builtin_expect((!!(conn->coro)), (1))) {
382 timeout_queue_insert(tq, conn);
383 return true1;
384 }
385
386 conn->flags = 0;
387
388 int fd = lwan_connection_get_fd(tq->lwan, conn);
389
390 lwan_status_error("Couldn't spawn coroutine for file descriptor %d", fd)lwan_status_error_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 390, __FUNCTION__, "Couldn't spawn coroutine for file descriptor %d"
, fd)
;
391
392 if (!send_string_without_coro(fd, "HTTP/1.0 503 Unavailable"))
393 goto out;
394 if (!send_string_without_coro(fd, "\r\nConnection: close"))
395 goto out;
396 if (!send_string_without_coro(fd, "\r\nContent-Type: text/html"))
397 goto out;
398 if (send_buffer_without_coro(fd, lwan_strbuf_get_buffer(&tq->lwan->headers),
399 lwan_strbuf_get_length(&tq->lwan->headers))) {
400 struct lwan_strbuf buffer;
401
402 lwan_strbuf_init(&buffer);
403 lwan_fill_default_response(&buffer, HTTP_UNAVAILABLE);
404
405 send_buffer_without_coro(fd, lwan_strbuf_get_buffer(&buffer),
406 lwan_strbuf_get_length(&buffer));
407
408 lwan_strbuf_free(&buffer);
409 }
410
411out:
412 shutdown(fd, SHUT_RDWRSHUT_RDWR);
413 close(fd);
414 return false0;
415}
416
417static bool_Bool process_pending_timers(struct timeout_queue *tq,
418 struct lwan_thread *t,
419 int epoll_fd)
420{
421 struct timeout *timeout;
422 bool_Bool should_expire_timers = false0;
423
424 while ((timeout = timeouts_get(t->wheel))) {
425 struct lwan_request *request;
426
427 if (timeout == &tq->timeout) {
428 should_expire_timers = true1;
429 continue;
430 }
431
432 request = container_of(timeout, struct lwan_request, timeout)((struct lwan_request *) ((char *)(timeout) - __builtin_offsetof
(struct lwan_request, timeout)) + ((typeof(*(timeout)) *)0 !=
(typeof(((struct lwan_request *)0)->timeout) *)0))
;
433
434 update_epoll_flags(request->fd, request->conn, epoll_fd,
435 CONN_CORO_RESUME);
436 }
437
438 if (should_expire_timers) {
439 timeout_queue_expire_waiting(tq);
440
441 /* tq timeout expires every 1000ms if there are connections, so
442 * update the date cache at this point as well. */
443 update_date_cache(t);
444
445 if (!timeout_queue_empty(tq)) {
446 timeouts_add(t->wheel, &tq->timeout, 1000);
447 return true1;
448 }
449
450 timeouts_del(t->wheel, &tq->timeout);
451 }
452
453 return false0;
454}
455
456static int
457turn_timer_wheel(struct timeout_queue *tq, struct lwan_thread *t, int epoll_fd)
458{
459 const int infinite_timeout = -1;
460 timeout_t wheel_timeout;
461 struct timespec now;
462
463 if (UNLIKELY(clock_gettime(monotonic_clock_id, &now) < 0)__builtin_expect(((clock_gettime(monotonic_clock_id, &now
) < 0)), (0))
)
464 lwan_status_critical("Could not get monotonic time")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 464, __FUNCTION__, "Could not get monotonic time")
;
465
466 timeouts_update(t->wheel,
467 (timeout_t)(now.tv_sec * 1000 + now.tv_nsec / 1000000));
468
469 /* Check if there's an expired timer. */
470 wheel_timeout = timeouts_timeout(t->wheel);
471 if (wheel_timeout > 0) {
472 return (int)wheel_timeout; /* No, but will soon. Wake us up in
473 wheel_timeout ms. */
474 }
475
476 if (UNLIKELY((int64_t)wheel_timeout < 0)__builtin_expect((((int64_t)wheel_timeout < 0)), (0)))
477 return infinite_timeout; /* None found. */
478
479 if (!process_pending_timers(tq, t, epoll_fd))
480 return infinite_timeout; /* No more timers to process. */
481
482 /* After processing pending timers, determine when to wake up. */
483 return (int)timeouts_timeout(t->wheel);
484}
485
486static bool_Bool accept_waiting_clients(const struct lwan_thread *t)
487{
488 const struct lwan_connection *conns = t->lwan->conns;
489
490 while (true1) {
491 int fd =
492 accept4(t->listen_fd, NULL((void*)0), NULL((void*)0), SOCK_NONBLOCKSOCK_NONBLOCK | SOCK_CLOEXECSOCK_CLOEXEC);
493
494 if (LIKELY(fd >= 0)__builtin_expect((!!(fd >= 0)), (1))) {
495 const struct lwan_connection *conn = &conns[fd];
496 struct epoll_event ev = {
497 .data.ptr = (void *)conn,
498 .events = conn_flags_to_epoll_events(CONN_EVENTS_READ),
499 };
500 int r = epoll_ctl(conn->thread->epoll_fd, EPOLL_CTL_ADD1, fd, &ev);
501
502 if (UNLIKELY(r < 0)__builtin_expect(((r < 0)), (0))) {
503 /* FIXME: send a "busy" response here? No coroutine has been
504 * created at this point to use the usual stuff, though. */
505 lwan_status_perror("Could not add file descriptor %d to epoll "lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 507, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
506 "set %d. Dropping connection",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 507, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
507 fd, conn->thread->epoll_fd)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 507, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
;
508 shutdown(fd, SHUT_RDWRSHUT_RDWR);
509 close(fd);
510 }
511
512 continue;
513 }
514
515 switch (errno(*__errno_location ())) {
516 default:
517 lwan_status_perror("Unexpected error while accepting connections")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 517, __FUNCTION__, "Unexpected error while accepting connections"
)
;
518 /* fallthrough */
519
520 case EAGAIN11:
521 return true1;
522
523 case EBADF9:
524 case ECONNABORTED103:
525 case EINVAL22:
526 lwan_status_info("Listening socket closed")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 526, __FUNCTION__, "Listening socket closed")
;
527 return false0;
528 }
529 }
530
531 __builtin_unreachable();
532}
533
534static int create_listen_socket(struct lwan_thread *t,
535 unsigned int num)
536{
537 int listen_fd;
538
539 listen_fd = lwan_create_listen_socket(t->lwan, num == 0);
540 if (listen_fd < 0)
541 lwan_status_critical("Could not create listen_fd")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 541, __FUNCTION__, "Could not create listen_fd")
;
542
543 /* Ignore errors here, as this is just a hint */
544#if defined(HAVE_SO_ATTACH_REUSEPORT_CBPF)
545 /* From socket(7): "These options may be set repeatedly at any time on
546 * any socket in the group to replace the current BPF program used by
547 * all sockets in the group." */
548 if (num == 0) {
549 /* From socket(7): "The BPF program must return an index between 0 and
550 * N-1 representing the socket which should receive the packet (where N
551 * is the number of sockets in the group)." */
552 const uint32_t cpu_ad_off = (uint32_t)SKF_AD_OFF(-0x1000) + SKF_AD_CPU36;
553 struct sock_filter filter[] = {
554 {BPF_LD0x00 | BPF_W0x00 | BPF_ABS0x20, 0, 0, cpu_ad_off}, /* A = curr_cpu_index */
555 {BPF_RET0x06 | BPF_A0x10, 0, 0, 0}, /* return A */
556 };
557 struct sock_fprog fprog = {.filter = filter, .len = N_ELEMENTS(filter)((!sizeof(char[1 - 2 * __builtin_types_compatible_p( __typeof__
(filter), __typeof__(&(filter)[0]))])) | sizeof(filter) /
sizeof(filter[0]))
};
558
559 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_ATTACH_REUSEPORT_CBPF51,
560 &fprog, sizeof(fprog));
561 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_LOCK_FILTER44,
562 (int[]){1}, sizeof(int));
563 }
564#elif defined(HAVE_SO_INCOMING_CPU) && defined(__x86_64__1)
565 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_INCOMING_CPU49, &t->cpu,
566 sizeof(t->cpu));
567#endif
568
569 struct epoll_event event = {
570 .events = EPOLLINEPOLLIN | EPOLLETEPOLLET | EPOLLERREPOLLERR,
571 .data.ptr = NULL((void*)0),
572 };
573 if (epoll_ctl(t->epoll_fd, EPOLL_CTL_ADD1, listen_fd, &event) < 0)
574 lwan_status_critical_perror("Could not add socket to epoll")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 574, __FUNCTION__, "Could not add socket to epoll")
;
575
576 return listen_fd;
577}
578
579static void *thread_io_loop(void *data)
580{
581 struct lwan_thread *t = data;
582 int epoll_fd = t->epoll_fd;
583 const int max_events = LWAN_MIN((int)t->lwan->thread.max_fd, 1024)({ const __typeof__(((int)t->lwan->thread.max_fd) + 0) lwan_tmp_id6
= ((int)t->lwan->thread.max_fd); const __typeof__((1024
) + 0) lwan_tmp_id7 = (1024); lwan_tmp_id6 > lwan_tmp_id7 ?
lwan_tmp_id7 : lwan_tmp_id6; })
;
584 struct lwan *lwan = t->lwan;
585 struct epoll_event *events;
586 struct coro_switcher switcher;
587 struct timeout_queue tq;
588
589 lwan_status_debug("Worker thread #%zd starting",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 590, __FUNCTION__, "Worker thread #%zd starting", t - t->
lwan->thread.threads + 1)
590 t - t->lwan->thread.threads + 1)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 590, __FUNCTION__, "Worker thread #%zd starting", t - t->
lwan->thread.threads + 1)
;
591 lwan_set_thread_name("worker");
592
593 events = calloc((size_t)max_events, sizeof(*events));
594 if (UNLIKELY(!events)__builtin_expect(((!events)), (0)))
595 lwan_status_critical("Could not allocate memory for events")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 595, __FUNCTION__, "Could not allocate memory for events")
;
596
597 update_date_cache(t);
598
599 timeout_queue_init(&tq, lwan);
600
601 lwan_random_seed_prng_for_thread((uint64_t)(epoll_fd | time(NULL((void*)0))));
602
603 pthread_barrier_wait(&lwan->thread.barrier);
604
605 for (;;) {
606 int timeout = turn_timer_wheel(&tq, t, epoll_fd);
607 int n_fds = epoll_wait(epoll_fd, events, max_events, timeout);
608 bool_Bool accepted_connections = false0;
609
610 if (UNLIKELY(n_fds < 0)__builtin_expect(((n_fds < 0)), (0))) {
611 if (errno(*__errno_location ()) == EBADF9 || errno(*__errno_location ()) == EINVAL22)
612 break;
613 continue;
614 }
615
616 for (struct epoll_event *event = events; n_fds--; event++) {
617 struct lwan_connection *conn;
618
619 if (!event->data.ptr) {
620 if (LIKELY(accept_waiting_clients(t))__builtin_expect((!!(accept_waiting_clients(t))), (1))) {
621 accepted_connections = true1;
622 continue;
623 }
624 close(epoll_fd);
625 epoll_fd = -1;
626 break;
627 }
628
629 conn = event->data.ptr;
630
631 if (UNLIKELY(event->events & (EPOLLRDHUP | EPOLLHUP))__builtin_expect(((event->events & (EPOLLRDHUP | EPOLLHUP
))), (0))
) {
632 timeout_queue_expire(&tq, conn);
633 continue;
634 }
635
636 if (!conn->coro) {
637 if (UNLIKELY(!spawn_coro(conn, &switcher, &tq))__builtin_expect(((!spawn_coro(conn, &switcher, &tq))
), (0))
)
638 continue;
639 }
640
641 resume_coro(&tq, conn, epoll_fd);
642 timeout_queue_move_to_last(&tq, conn);
643 }
644
645 if (accepted_connections)
646 timeouts_add(t->wheel, &tq.timeout, 1000);
647 }
648
649 pthread_barrier_wait(&lwan->thread.barrier);
650
651 timeout_queue_expire_all(&tq);
652 free(events);
653
654 return NULL((void*)0);
655}
656
657static void create_thread(struct lwan *l, struct lwan_thread *thread)
658{
659 int ignore;
660 pthread_attr_t attr;
661
662 thread->lwan = l;
663
664 thread->wheel = timeouts_open(&ignore);
665 if (!thread->wheel)
666 lwan_status_critical("Could not create timer wheel")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 666, __FUNCTION__, "Could not create timer wheel")
;
667
668 if ((thread->epoll_fd = epoll_create1(EPOLL_CLOEXECEPOLL_CLOEXEC)) < 0)
669 lwan_status_critical_perror("epoll_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 669, __FUNCTION__, "epoll_create")
;
670
671 if (pthread_attr_init(&attr))
672 lwan_status_critical_perror("pthread_attr_init")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 672, __FUNCTION__, "pthread_attr_init")
;
673
674 if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEMPTHREAD_SCOPE_SYSTEM))
675 lwan_status_critical_perror("pthread_attr_setscope")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 675, __FUNCTION__, "pthread_attr_setscope")
;
676
677 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLEPTHREAD_CREATE_JOINABLE))
678 lwan_status_critical_perror("pthread_attr_setdetachstate")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 678, __FUNCTION__, "pthread_attr_setdetachstate")
;
679
680 if (pthread_create(&thread->self, &attr, thread_io_loop, thread))
681 lwan_status_critical_perror("pthread_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 681, __FUNCTION__, "pthread_create")
;
682
683 if (pthread_attr_destroy(&attr))
684 lwan_status_critical_perror("pthread_attr_destroy")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 684, __FUNCTION__, "pthread_attr_destroy")
;
685}
686
687#if defined(__linux__1) && defined(__x86_64__1)
688static bool_Bool read_cpu_topology(struct lwan *l, uint32_t siblings[])
689{
690 char path[PATH_MAX4096];
691
692 for (uint32_t i = 0; i < l->available_cpus; i++)
693 siblings[i] = 0xbebacafe;
694
695 for (unsigned int i = 0; i < l->available_cpus; i++) {
696 FILE *sib;
697 uint32_t id, sibling;
698 char separator;
699
700 snprintf(path, sizeof(path),
701 "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list",
702 i);
703
704 sib = fopen(path, "re");
705 if (!sib) {
706 lwan_status_warning("Could not open `%s` to determine CPU topology",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 707, __FUNCTION__, "Could not open `%s` to determine CPU topology"
, path)
707 path)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 707, __FUNCTION__, "Could not open `%s` to determine CPU topology"
, path)
;
708 return false0;
709 }
710
711 switch (fscanf(sib, "%u%c%u", &id, &separator, &sibling)) {
712 case 2: /* No SMT */
713 siblings[i] = id;
714 break;
715 case 3: /* SMT */
716 if (!(separator == ',' || separator == '-')) {
717 lwan_status_critical("Expecting either ',' or '-' for sibling separator")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 717, __FUNCTION__, "Expecting either ',' or '-' for sibling separator"
)
;
718 __builtin_unreachable();
719 }
720
721 siblings[i] = sibling;
722 break;
723 default:
724 lwan_status_critical("%s has invalid format", path)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 724, __FUNCTION__, "%s has invalid format", path)
;
725 __builtin_unreachable();
726 }
727
728 fclose(sib);
729 }
730
731 /* Perform a sanity check here, as some systems seem to filter out the
732 * result of sysconf() to obtain the number of configured and online
733 * CPUs but don't bother changing what's available through sysfs as far
734 * as the CPU topology information goes. It's better to fall back to a
735 * possibly non-optimal setup than just crash during startup while
736 * trying to perform an out-of-bounds array access. */
737 for (unsigned int i = 0; i < l->available_cpus; i++) {
738 if (siblings[i] == 0xbebacafe) {
739 lwan_status_warning("Could not determine sibling for CPU %d", i)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 739, __FUNCTION__, "Could not determine sibling for CPU %d"
, i)
;
740 return false0;
741 }
742
743 if (siblings[i] >= l->available_cpus) {
744 lwan_status_warning("CPU information topology says CPU %d exists, "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 747, __FUNCTION__, "CPU information topology says CPU %d exists, "
"but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?"
, siblings[i], l->available_cpus, l->online_cpus)
745 "but max available CPUs is %d (online CPUs: %d). "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 747, __FUNCTION__, "CPU information topology says CPU %d exists, "
"but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?"
, siblings[i], l->available_cpus, l->online_cpus)
746 "Is Lwan running in a (broken) container?",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 747, __FUNCTION__, "CPU information topology says CPU %d exists, "
"but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?"
, siblings[i], l->available_cpus, l->online_cpus)
747 siblings[i], l->available_cpus, l->online_cpus)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 747, __FUNCTION__, "CPU information topology says CPU %d exists, "
"but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?"
, siblings[i], l->available_cpus, l->online_cpus)
;
748 return false0;
749 }
750 }
751
752 return true1;
753}
754
755static void
756siblings_to_schedtbl(struct lwan *l, uint32_t siblings[], uint32_t schedtbl[])
757{
758 int *seen = alloca(l->available_cpus * sizeof(int))__builtin_alloca (l->available_cpus * sizeof(int));
759 unsigned int n_schedtbl = 0;
760
761 for (uint32_t i = 0; i < l->available_cpus; i++)
762 seen[i] = -1;
763
764 for (uint32_t i = 0; i < l->available_cpus; i++) {
765 if (seen[siblings[i]] < 0) {
766 seen[siblings[i]] = (int)i;
767 } else {
768 schedtbl[n_schedtbl++] = (uint32_t)seen[siblings[i]];
769 schedtbl[n_schedtbl++] = i;
770 }
771 }
772
773 if (n_schedtbl != l->available_cpus)
774 memcpy(schedtbl, seen, l->available_cpus * sizeof(int));
775}
776
777static bool_Bool
778topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads)
779{
780 uint32_t *siblings = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t));
781
782 if (read_cpu_topology(l, siblings)) {
6
Assuming the condition is false
7
Taking false branch
783 uint32_t *affinity = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t));
784
785 siblings_to_schedtbl(l, siblings, affinity);
786
787 for (uint32_t i = 0; i < n_threads; i++)
788 schedtbl[i] = affinity[i % l->available_cpus];
789 return true1;
790 }
791
792 for (uint32_t i = 0; i < n_threads; i++)
8
Assuming 'i' is >= 'n_threads'
9
Loop condition is false. Execution continues on line 794
793 schedtbl[i] = (i / 2) % l->thread.count;
794 return false0;
10
Returning without writing to '*schedtbl'
795}
796
797static void
798adjust_thread_affinity(const struct lwan_thread *thread)
799{
800 cpu_set_t set;
801
802 CPU_ZERO(&set)do __builtin_memset (&set, '\0', sizeof (cpu_set_t)); while
(0)
;
803 CPU_SET(thread->cpu, &set)(__extension__ ({ size_t __cpu = (thread->cpu); __cpu / 8 <
(sizeof (cpu_set_t)) ? (((__cpu_mask *) ((&set)->__bits
))[((__cpu) / (8 * sizeof (__cpu_mask)))] |= ((__cpu_mask) 1 <<
((__cpu) % (8 * sizeof (__cpu_mask))))) : 0; }))
;
804
805 if (pthread_setaffinity_np(thread->self, sizeof(set), &set))
806 lwan_status_warning("Could not set thread affinity")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 806, __FUNCTION__, "Could not set thread affinity")
;
807}
808#elif defined(__x86_64__1)
809static bool_Bool
810topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads)
811{
812 for (uint32_t i = 0; i < n_threads; i++)
813 schedtbl[i] = (i / 2) % l->thread.count;
814 return false0;
815}
816
817static void
818adjust_thread_affinity(const struct lwan_thread *thread)
819{
820 (void)thread;
821}
822#endif
823
824void lwan_thread_init(struct lwan *l)
825{
826 const unsigned int total_conns = l->thread.max_fd * l->thread.count;
827
828 lwan_status_debug("Initializing threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 828, __FUNCTION__, "Initializing threads")
;
829
830 l->thread.threads =
831 calloc((size_t)l->thread.count, sizeof(struct lwan_thread));
832 if (!l->thread.threads)
1
Assuming field 'threads' is non-null
2
Taking false branch
833 lwan_status_critical("Could not allocate memory for threads")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 833, __FUNCTION__, "Could not allocate memory for threads")
;
834
835#ifdef __x86_64__1
836 static_assert(sizeof(struct lwan_connection) == 32,extern int (*__Static_assert_function (void)) [!!sizeof (struct
{ int __error_if_negative: (sizeof(struct lwan_connection) ==
32) ? 2 : -1; })]
837 "Two connections per cache line")extern int (*__Static_assert_function (void)) [!!sizeof (struct
{ int __error_if_negative: (sizeof(struct lwan_connection) ==
32) ? 2 : -1; })]
;
838#ifdef _SC_LEVEL1_DCACHE_LINESIZE_SC_LEVEL1_DCACHE_LINESIZE
839 assert(sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64)((void) sizeof ((sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64) ?
1 : 0), __extension__ ({ if (sysconf(_SC_LEVEL1_DCACHE_LINESIZE
) == 64) ; else __assert_fail ("sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 839, __extension__ __PRETTY_FUNCTION__); }))
;
3
Assuming the condition is true
4
Taking true branch
840#endif
841
842 lwan_status_debug("%d CPUs of %d are online. "lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 844, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
843 "Reading topology to pre-schedule clients",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 844, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
844 l->online_cpus, l->available_cpus)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 844, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
;
845
846 /*
847 * Pre-schedule each file descriptor, to reduce some operations in the
848 * fast path.
849 *
850 * Since struct lwan_connection is guaranteed to be 32-byte long, two of
851 * them can fill up a cache line. Assume siblings share cache lines and
852 * use the CPU topology to group two connections per cache line in such
853 * a way that false sharing is avoided.
854 */
855 uint32_t n_threads =
856 (uint32_t)lwan_nextpow2((size_t)((l->thread.count - 1) * 2));
857 uint32_t *schedtbl = alloca(n_threads * sizeof(uint32_t))__builtin_alloca (n_threads * sizeof(uint32_t));
858
859 bool_Bool adj_affinity = topology_to_schedtbl(l, schedtbl, n_threads);
5
Calling 'topology_to_schedtbl'
11
Returning from 'topology_to_schedtbl'
860
861 n_threads--; /* Transform count into mask for AND below */
862
863 for (unsigned int i = 0; i < total_conns; i++)
12
Assuming 'i' is >= 'total_conns'
13
Loop condition is false. Execution continues on line 875
864 l->conns[i].thread = &l->thread.threads[schedtbl[i & n_threads]];
865#else
866 for (unsigned int i = 0; i < l->thread.count; i++)
867 l->thread.threads[i].cpu = i % l->online_cpus;
868 for (unsigned int i = 0; i < total_conns; i++)
869 l->conns[i].thread = &l->thread.threads[i % l->thread.count];
870
871 uint32_t *schedtbl = NULL((void*)0);
872 const bool_Bool adj_affinity = false0;
873#endif
874
875 for (unsigned int i = 0; i < l->thread.count; i++) {
14
Assuming 'i' is < field 'count'
15
Loop condition is true. Entering loop body
876 struct lwan_thread *thread = NULL((void*)0);
877
878 if (schedtbl
15.1
'schedtbl' is non-null
) {
16
Taking true branch
879 /* This is not the most elegant thing, but this assures that the
880 * listening sockets are added to the SO_REUSEPORT group in a
881 * specific order, because that's what the CBPF program to direct
882 * the incoming connection to the right CPU will use. */
883 for (uint32_t thread_id = 0; thread_id
16.1
'thread_id' is < field 'count'
< l->thread.count;
17
Loop condition is true. Entering loop body
884 thread_id++) {
885 if (schedtbl[thread_id & n_threads] == i) {
18
The left operand of '==' is a garbage value
886 thread = &l->thread.threads[thread_id];
887 break;
888 }
889 }
890 if (!thread) {
891 /* FIXME: can this happen when we have a offline CPU? */
892 lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 893, __FUNCTION__, "Could not figure out which CPU thread %d should go to"
, i)
893 "Could not figure out which CPU thread %d should go to", i)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 893, __FUNCTION__, "Could not figure out which CPU thread %d should go to"
, i)
;
894 }
895 } else {
896 thread = &l->thread.threads[i % l->thread.count];
897 }
898
899 if (pthread_barrier_init(&l->thread.barrier, NULL((void*)0), 2))
900 lwan_status_critical("Could not create barrier")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 900, __FUNCTION__, "Could not create barrier")
;
901
902 create_thread(l, thread);
903
904 if ((thread->listen_fd = create_listen_socket(thread, i)) < 0)
905 lwan_status_critical_perror("Could not create listening socket")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 905, __FUNCTION__, "Could not create listening socket")
;
906
907 if (adj_affinity) {
908 l->thread.threads[i].cpu = schedtbl[i & n_threads];
909 adjust_thread_affinity(thread);
910 }
911
912 pthread_barrier_wait(&l->thread.barrier);
913 }
914
915 lwan_status_debug("Worker threads created and ready to serve")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 915, __FUNCTION__, "Worker threads created and ready to serve"
)
;
916}
917
918void lwan_thread_shutdown(struct lwan *l)
919{
920 lwan_status_debug("Shutting down threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 920, __FUNCTION__, "Shutting down threads")
;
921
922 for (unsigned int i = 0; i < l->thread.count; i++) {
923 struct lwan_thread *t = &l->thread.threads[i];
924 int epoll_fd = t->epoll_fd;
925 int listen_fd = t->listen_fd;
926
927 t->listen_fd = -1;
928 t->epoll_fd = -1;
929 close(epoll_fd);
930 close(listen_fd);
931 }
932
933 pthread_barrier_wait(&l->thread.barrier);
934 pthread_barrier_destroy(&l->thread.barrier);
935
936 for (unsigned int i = 0; i < l->thread.count; i++) {
937 struct lwan_thread *t = &l->thread.threads[i];
938
939 pthread_join(l->thread.threads[i].self, NULL((void*)0));
940 timeouts_close(t->wheel);
941 }
942
943 free(l->thread.threads);
944}