Bug Summary

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