Bug Summary

File:lib/lwan-thread.c
Warning:line 1247, 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 -debugger-tuning=gdb -fcoverage-compilation-dir=/home/buildbot/lwan-worker/clang-analyze/build/src/lib -resource-dir /usr/lib/clang/13.0.1 -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.1 -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/lib/clang/13.0.1/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../x86_64-pc-linux-gnu/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 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/buildbot/lwan-worker/clang-analyze/CLANG/2022-02-19-073348-1490237-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 L. A. F. Pereira <l@tia.mat.br>
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#if defined(HAVE_MBEDTLS)
39#include <mbedtls/entropy.h>
40#include <mbedtls/error.h>
41#include <mbedtls/gcm.h>
42#include <mbedtls/net_sockets.h>
43#include <mbedtls/ssl_internal.h>
44
45#include <linux1/tls.h>
46#include <netinet/tcp.h>
47#endif
48
49#include "list.h"
50#include "murmur3.h"
51#include "lwan-private.h"
52#include "lwan-tq.h"
53
54static void lwan_strbuf_free_defer(void *data)
55{
56 return lwan_strbuf_free((struct lwan_strbuf *)data);
57}
58
59static void graceful_close(struct lwan *l,
60 struct lwan_connection *conn,
61 char buffer[static DEFAULT_BUFFER_SIZE4096])
62{
63 int fd = lwan_connection_get_fd(l, conn);
64
65 while (TIOCOUTQ0x5411) {
66 /* This ioctl isn't probably doing what it says on the tin; the details
67 * are subtle, but it seems to do the trick to allow gracefully closing
68 * the connection in some cases with minimal system calls. */
69 int bytes_waiting;
70 int r = ioctl(fd, TIOCOUTQ0x5411, &bytes_waiting);
71
72 if (!r && !bytes_waiting) /* See note about close(2) below. */
73 return;
74 if (r < 0 && errno(*__errno_location ()) == EINTR4)
75 continue;
76
77 break;
78 }
79
80 if (UNLIKELY(shutdown(fd, SHUT_WR) < 0)__builtin_expect(((shutdown(fd, SHUT_WR) < 0)), (0))) {
81 if (UNLIKELY(errno == ENOTCONN)__builtin_expect((((*__errno_location ()) == 107)), (0)))
82 return;
83 }
84
85 for (int tries = 0; tries < 20; tries++) {
86 ssize_t r = recv(fd, buffer, DEFAULT_BUFFER_SIZE4096, 0);
87
88 if (!r)
89 break;
90
91 if (r < 0) {
92 switch (errno(*__errno_location ())) {
93 case EAGAIN11:
94 break;
95 case EINTR4:
96 continue;
97 default:
98 return;
99 }
100 }
101
102 coro_yield(conn->coro, CONN_CORO_WANT_READ);
103 }
104
105 /* close(2) will be called when the coroutine yields with CONN_CORO_ABORT */
106}
107
108#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
109static void lwan_random_seed_prng_for_thread(const struct lwan_thread *t)
110{
111 (void)t;
112}
113
114uint64_t lwan_random_uint64()
115{
116 static uint64_t value;
117
118 return ATOMIC_INC(value)(__sync_add_and_fetch(((&(value))), ((1))));
119}
120#else
121static __thread __uint128_t lehmer64_state;
122
123static void lwan_random_seed_prng_for_thread(const struct lwan_thread *t)
124{
125 if (lwan_getentropy(&lehmer64_state, sizeof(lehmer64_state), 0) < 0) {
126 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"
, 126, __FUNCTION__, "Couldn't get proper entropy for PRNG, using fallback seed"
)
;
127 lehmer64_state |= murmur3_fmix64((uint64_t)(uintptr_t)t);
128 lehmer64_state <<= 64;
129 lehmer64_state |= murmur3_fmix64((uint64_t)t->epoll_fd);
130 }
131}
132
133uint64_t lwan_random_uint64()
134{
135 /* https://lemire.me/blog/2019/03/19/the-fastest-conventional-random-number-generator-that-can-pass-big-crush/ */
136 lehmer64_state *= 0xda942042e4dd58b5ull;
137 return (uint64_t)(lehmer64_state >> 64);
138}
139#endif
140
141uint64_t lwan_request_get_id(struct lwan_request *request)
142{
143 struct lwan_request_parser_helper *helper = request->helper;
144
145 if (helper->request_id == 0)
146 helper->request_id = lwan_random_uint64();
147
148 return helper->request_id;
149}
150
151#if defined(HAVE_MBEDTLS)
152static bool_Bool
153lwan_setup_tls_keys(int fd, const mbedtls_ssl_context *ssl, int rx_or_tx)
154{
155 struct tls12_crypto_info_aes_gcm_128 info = {
156 .info = {.version = TLS_1_2_VERSION((((0x3) & 0xFF) << 8) | ((0x3) & 0xFF)),
157 .cipher_type = TLS_CIPHER_AES_GCM_12851},
158 };
159 const unsigned char *salt, *iv, *rec_seq;
160 const mbedtls_gcm_context *gcm_ctx;
161 const mbedtls_aes_context *aes_ctx;
162
163 switch (rx_or_tx) {
164 case TLS_RX2:
165 salt = ssl->transform->iv_dec;
166 rec_seq = ssl->in_ctr;
167 gcm_ctx = ssl->transform->cipher_ctx_dec.cipher_ctx;
168 break;
169 case TLS_TX1:
170 salt = ssl->transform->iv_enc;
171 rec_seq = ssl->cur_out_ctr;
172 gcm_ctx = ssl->transform->cipher_ctx_enc.cipher_ctx;
173 break;
174 default:
175 __builtin_unreachable();
176 }
177
178 iv = salt + 4;
179 aes_ctx = gcm_ctx->cipher_ctx.cipher_ctx;
180
181 memcpy(info.iv, iv, TLS_CIPHER_AES_GCM_128_IV_SIZE8);
182 memcpy(info.rec_seq, rec_seq, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE8);
183 memcpy(info.key, aes_ctx->rk, TLS_CIPHER_AES_GCM_128_KEY_SIZE16);
184 memcpy(info.salt, salt, TLS_CIPHER_AES_GCM_128_SALT_SIZE4);
185
186 if (UNLIKELY(setsockopt(fd, SOL_TLS, rx_or_tx, &info, sizeof(info)) < 0)__builtin_expect(((setsockopt(fd, 282, rx_or_tx, &info, sizeof
(info)) < 0)), (0))
) {
187 lwan_status_perror("Could not set %s kTLS keys for fd %d",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 189, __FUNCTION__, "Could not set %s kTLS keys for fd %d", rx_or_tx
== 1 ? "transmission" : "reception", fd)
188 rx_or_tx == TLS_TX ? "transmission" : "reception",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 189, __FUNCTION__, "Could not set %s kTLS keys for fd %d", rx_or_tx
== 1 ? "transmission" : "reception", fd)
189 fd)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 189, __FUNCTION__, "Could not set %s kTLS keys for fd %d", rx_or_tx
== 1 ? "transmission" : "reception", fd)
;
190 lwan_always_bzero(&info, sizeof(info));
191 return false0;
192 }
193
194 lwan_always_bzero(&info, sizeof(info));
195 return true1;
196}
197
198__attribute__((format(printf, 2, 3)))
199__attribute__((noinline, cold))
200static void lwan_status_mbedtls_error(int error_code, const char *fmt, ...)
201{
202 char *formatted;
203 va_list ap;
204 int r;
205
206 va_start(ap, fmt)__builtin_va_start(ap, fmt);
207 r = vasprintf(&formatted, fmt, ap);
208 if (r >= 0) {
209 char mbedtls_errbuf[128];
210
211 mbedtls_strerror(error_code, mbedtls_errbuf, sizeof(mbedtls_errbuf));
212 lwan_status_error("%s: %s", formatted, mbedtls_errbuf)lwan_status_error_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 212, __FUNCTION__, "%s: %s", formatted, mbedtls_errbuf)
;
213 free(formatted);
214 }
215 va_end(ap)__builtin_va_end(ap);
216}
217
218static void lwan_setup_tls_free_ssl_context(void *data)
219{
220 mbedtls_ssl_context *ssl = data;
221
222 mbedtls_ssl_free(ssl);
223}
224
225static bool_Bool lwan_setup_tls(const struct lwan *l, struct lwan_connection *conn)
226{
227 mbedtls_ssl_context ssl;
228 bool_Bool retval = false0;
229 int r;
230
231 mbedtls_ssl_init(&ssl);
232
233 r = mbedtls_ssl_setup(&ssl, &l->tls->config);
234 if (UNLIKELY(r != 0)__builtin_expect(((r != 0)), (0))) {
235 lwan_status_mbedtls_error(r, "Could not setup TLS context");
236 return false0;
237 }
238
239 /* Yielding the coroutine during the handshake enables the I/O loop to
240 * destroy this coro (e.g. on connection hangup) before we have the
241 * opportunity to free the SSL context. Defer this call for these
242 * cases. */
243 struct coro_defer *defer =
244 coro_defer(conn->coro, lwan_setup_tls_free_ssl_context, &ssl);
245
246 if (UNLIKELY(!defer)__builtin_expect(((!defer)), (0))) {
247 lwan_status_error("Could not defer cleanup of the TLS context")lwan_status_error_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 247, __FUNCTION__, "Could not defer cleanup of the TLS context"
)
;
248 return false0;
249 }
250
251 int fd = lwan_connection_get_fd(l, conn);
252 /* FIXME: This is only required for the handshake; this uses read() and
253 * write() under the hood but maybe we can use something like recv() and
254 * send() instead to force MSG_MORE et al? (strace shows a few
255 * consecutive calls to write(); this might be sent in separate TCP
256 * fragments.) */
257 mbedtls_ssl_set_bio(&ssl, &fd, mbedtls_net_send, mbedtls_net_recv, NULL((void*)0));
258
259 while (true1) {
260 switch (mbedtls_ssl_handshake(&ssl)) {
261 case 0:
262 goto enable_tls_ulp;
263 case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS-0x6500:
264 case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS-0x7000:
265 case MBEDTLS_ERR_SSL_WANT_READ-0x6900:
266 coro_yield(conn->coro, CONN_CORO_WANT_READ);
267 break;
268 case MBEDTLS_ERR_SSL_WANT_WRITE-0x6880:
269 coro_yield(conn->coro, CONN_CORO_WANT_WRITE);
270 break;
271 default:
272 goto fail;
273 }
274 }
275
276enable_tls_ulp:
277 if (UNLIKELY(setsockopt(fd, SOL_TCP, TCP_ULP, "tls", sizeof("tls")) < 0)__builtin_expect(((setsockopt(fd, 6, 31, "tls", sizeof("tls")
) < 0)), (0))
)
278 goto fail;
279 if (UNLIKELY(!lwan_setup_tls_keys(fd, &ssl, TLS_RX))__builtin_expect(((!lwan_setup_tls_keys(fd, &ssl, 2))), (
0))
)
280 goto fail;
281 if (UNLIKELY(!lwan_setup_tls_keys(fd, &ssl, TLS_TX))__builtin_expect(((!lwan_setup_tls_keys(fd, &ssl, 1))), (
0))
)
282 goto fail;
283
284 retval = true1;
285
286fail:
287 coro_defer_disarm(conn->coro, defer);
288 mbedtls_ssl_free(&ssl);
289 return retval;
290}
291#endif
292
293__attribute__((noreturn)) static int process_request_coro(struct coro *coro,
294 void *data)
295{
296 /* NOTE: This function should not return; coro_yield should be used
297 * instead. This ensures the storage for `strbuf` is alive when the
298 * coroutine ends and lwan_strbuf_free() is called. */
299 struct lwan_connection *conn = data;
300 struct lwan *lwan = conn->thread->lwan;
301 int fd = lwan_connection_get_fd(lwan, conn);
302 enum lwan_request_flags flags = lwan->config.request_flags;
303 struct lwan_strbuf strbuf = LWAN_STRBUF_STATIC_INIT(struct lwan_strbuf) { .buffer = "" };
304 char request_buffer[DEFAULT_BUFFER_SIZE4096];
305 struct lwan_value buffer = {.value = request_buffer, .len = 0};
306 char *next_request = NULL((void*)0);
307 char *header_start[N_HEADER_START64];
308 struct lwan_proxy proxy;
309 const int error_when_n_packets = lwan_calculate_n_packets(DEFAULT_BUFFER_SIZE4096);
310
311 coro_defer(coro, lwan_strbuf_free_defer, &strbuf);
312
313 const size_t init_gen = 1; /* 1 call to coro_defer() */
314 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"
, 314, __extension__ __PRETTY_FUNCTION__); }))
;
315
316#if defined(HAVE_MBEDTLS)
317 if (conn->flags & CONN_TLS) {
318 if (UNLIKELY(!lwan_setup_tls(lwan, conn))__builtin_expect(((!lwan_setup_tls(lwan, conn))), (0))) {
319 coro_yield(conn->coro, CONN_CORO_ABORT);
320 __builtin_unreachable();
321 }
322 }
323#else
324 assert(!(conn->flags & CONN_TLS))((void) sizeof ((!(conn->flags & CONN_TLS)) ? 1 : 0), __extension__
({ if (!(conn->flags & CONN_TLS)) ; else __assert_fail
("!(conn->flags & CONN_TLS)", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 324, __extension__ __PRETTY_FUNCTION__); }))
;
325#endif
326
327 while (true1) {
328 struct lwan_request_parser_helper helper = {
329 .buffer = &buffer,
330 .next_request = next_request,
331 .error_when_n_packets = error_when_n_packets,
332 .header_start = header_start,
333 };
334 struct lwan_request request = {.conn = conn,
335 .global_response_headers = &lwan->headers,
336 .fd = fd,
337 .response = {.buffer = &strbuf},
338 .flags = flags,
339 .proxy = &proxy,
340 .helper = &helper};
341
342 lwan_process_request(lwan, &request);
343
344 /* Run the deferred instructions now (except those used to initialize
345 * the coroutine), so that if the connection is gracefully closed,
346 * the storage for ``helper'' is still there. */
347 coro_deferred_run(coro, init_gen);
348
349 if (UNLIKELY(!(conn->flags & CONN_IS_KEEP_ALIVE))__builtin_expect(((!(conn->flags & CONN_IS_KEEP_ALIVE)
)), (0))
) {
350 graceful_close(lwan, conn, request_buffer);
351 break;
352 }
353
354 if (next_request && *next_request) {
355 conn->flags |= CONN_CORK;
356
357 if (!(conn->flags & CONN_EVENTS_WRITE))
358 coro_yield(coro, CONN_CORO_WANT_WRITE);
359 } else {
360 conn->flags &= ~CONN_CORK;
361 coro_yield(coro, CONN_CORO_WANT_READ);
362 }
363
364 /* Ensure string buffer is reset between requests, and that the backing
365 * store isn't over 2KB. */
366 lwan_strbuf_reset_trim(&strbuf, 2048);
367
368 /* Only allow flags from config. */
369 flags = request.flags & (REQUEST_PROXIED | REQUEST_ALLOW_CORS | REQUEST_WANTS_HSTS_HEADER);
370 next_request = helper.next_request;
371 }
372
373 coro_yield(coro, CONN_CORO_ABORT);
374 __builtin_unreachable();
375}
376
377static ALWAYS_INLINEinline __attribute__((always_inline)) uint32_t
378conn_flags_to_epoll_events(enum lwan_connection_flags flags)
379{
380 static const uint32_t map[CONN_EVENTS_MASK + 1] = {
381 [0 /* Suspended (timer or await) */] = EPOLLRDHUPEPOLLRDHUP,
382 [CONN_EVENTS_WRITE] = EPOLLOUTEPOLLOUT | EPOLLRDHUPEPOLLRDHUP,
383 [CONN_EVENTS_READ] = EPOLLINEPOLLIN | EPOLLRDHUPEPOLLRDHUP,
384 [CONN_EVENTS_READ_WRITE] = EPOLLINEPOLLIN | EPOLLOUTEPOLLOUT | EPOLLRDHUPEPOLLRDHUP,
385 };
386
387 return map[flags & CONN_EVENTS_MASK];
388}
389
390static void update_epoll_flags(int fd,
391 struct lwan_connection *conn,
392 int epoll_fd,
393 enum lwan_connection_coro_yield yield_result)
394{
395 static const enum lwan_connection_flags or_mask[CONN_CORO_MAX] = {
396 [CONN_CORO_YIELD] = 0,
397
398 [CONN_CORO_WANT_READ_WRITE] = CONN_EVENTS_READ_WRITE,
399 [CONN_CORO_WANT_READ] = CONN_EVENTS_READ,
400 [CONN_CORO_WANT_WRITE] = CONN_EVENTS_WRITE,
401
402 /* While the coro is suspended, we're not interested in either EPOLLIN
403 * or EPOLLOUT events. We still want to track this fd in epoll, though,
404 * so unset both so that only EPOLLRDHUP (plus the implicitly-set ones)
405 * are set. */
406 [CONN_CORO_SUSPEND] = CONN_SUSPENDED,
407
408 /* Ideally, when suspending a coroutine, the current flags&CONN_EVENTS_MASK
409 * would have to be stored and restored -- however, resuming as if the
410 * client coroutine is interested in a write event always guarantees that
411 * they'll be resumed as they're TCP sockets. There's a good chance that
412 * trying to read from a socket after resuming a coroutine will succeed,
413 * but if it doesn't because read() returns -EAGAIN, the I/O wrappers will
414 * yield with CONN_CORO_WANT_READ anyway. */
415 [CONN_CORO_RESUME] = CONN_EVENTS_WRITE,
416 };
417 static const enum lwan_connection_flags and_mask[CONN_CORO_MAX] = {
418 [CONN_CORO_YIELD] = ~0,
419
420 [CONN_CORO_WANT_READ_WRITE] = ~0,
421 [CONN_CORO_WANT_READ] = ~CONN_EVENTS_WRITE,
422 [CONN_CORO_WANT_WRITE] = ~CONN_EVENTS_READ,
423
424 [CONN_CORO_SUSPEND] = ~CONN_EVENTS_READ_WRITE,
425 [CONN_CORO_RESUME] = ~CONN_SUSPENDED,
426 };
427 enum lwan_connection_flags prev_flags = conn->flags;
428
429 conn->flags |= or_mask[yield_result];
430 conn->flags &= and_mask[yield_result];
431
432 assert(!(conn->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS)))((void) sizeof ((!(conn->flags & (CONN_LISTENER_HTTP |
CONN_LISTENER_HTTPS))) ? 1 : 0), __extension__ ({ if (!(conn
->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS)))
; else __assert_fail ("!(conn->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS))"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 432, __extension__ __PRETTY_FUNCTION__); }))
;
433 assert((conn->flags & CONN_TLS) == (prev_flags & CONN_TLS))((void) sizeof (((conn->flags & CONN_TLS) == (prev_flags
& CONN_TLS)) ? 1 : 0), __extension__ ({ if ((conn->flags
& CONN_TLS) == (prev_flags & CONN_TLS)) ; else __assert_fail
("(conn->flags & CONN_TLS) == (prev_flags & CONN_TLS)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 433, __extension__ __PRETTY_FUNCTION__); }))
;
434
435 if (conn->flags == prev_flags)
436 return;
437
438 struct epoll_event event = {
439 .events = conn_flags_to_epoll_events(conn->flags),
440 .data.ptr = conn,
441 };
442
443 if (UNLIKELY(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &event) < 0)__builtin_expect(((epoll_ctl(epoll_fd, 3, fd, &event) <
0)), (0))
)
444 lwan_status_perror("epoll_ctl")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 444, __FUNCTION__, "epoll_ctl")
;
445}
446
447static void clear_async_await_flag(void *data)
448{
449 struct lwan_connection *async_fd_conn = data;
450
451 async_fd_conn->flags &= ~CONN_ASYNC_AWAIT;
452}
453
454static enum lwan_connection_coro_yield
455resume_async(struct timeout_queue *tq,
456 enum lwan_connection_coro_yield yield_result,
457 int64_t from_coro,
458 struct lwan_connection *conn,
459 int epoll_fd)
460{
461 static const enum lwan_connection_flags to_connection_flags[] = {
462 [CONN_CORO_ASYNC_AWAIT_READ] = CONN_EVENTS_READ,
463 [CONN_CORO_ASYNC_AWAIT_WRITE] = CONN_EVENTS_WRITE,
464 [CONN_CORO_ASYNC_AWAIT_READ_WRITE] = CONN_EVENTS_READ_WRITE,
465 };
466 int await_fd = (int)((uint64_t)from_coro >> 32);
467 enum lwan_connection_flags flags;
468 int op;
469
470 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"
, 470, __extension__ __PRETTY_FUNCTION__); }))
;
471 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"
, 472, __extension__ __PRETTY_FUNCTION__); }))
472 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"
, 472, __extension__ __PRETTY_FUNCTION__); }))
;
473
474 flags = to_connection_flags[yield_result];
475
476 struct lwan_connection *await_fd_conn = &tq->lwan->conns[await_fd];
477 if (LIKELY(await_fd_conn->flags & CONN_ASYNC_AWAIT)__builtin_expect((!!(await_fd_conn->flags & CONN_ASYNC_AWAIT
)), (1))
) {
478 if (LIKELY((await_fd_conn->flags & CONN_EVENTS_MASK) == flags)__builtin_expect((!!((await_fd_conn->flags & CONN_EVENTS_MASK
) == flags)), (1))
)
479 return CONN_CORO_SUSPEND;
480
481 op = EPOLL_CTL_MOD3;
482 } else {
483 op = EPOLL_CTL_ADD1;
484 flags |= CONN_ASYNC_AWAIT;
485 coro_defer(conn->coro, clear_async_await_flag, await_fd_conn);
486 }
487
488 struct epoll_event event = {.events = conn_flags_to_epoll_events(flags),
489 .data.ptr = conn};
490 if (LIKELY(!epoll_ctl(epoll_fd, op, await_fd, &event))__builtin_expect((!!(!epoll_ctl(epoll_fd, op, await_fd, &
event))), (1))
) {
491 await_fd_conn->flags &= ~CONN_EVENTS_MASK;
492 await_fd_conn->flags |= flags;
493 return CONN_CORO_SUSPEND;
494 }
495
496 return CONN_CORO_ABORT;
497}
498
499static ALWAYS_INLINEinline __attribute__((always_inline)) void resume_coro(struct timeout_queue *tq,
500 struct lwan_connection *conn,
501 int epoll_fd)
502{
503 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"
, 503, __extension__ __PRETTY_FUNCTION__); }))
;
504
505 int64_t from_coro = coro_resume(conn->coro);
506 enum lwan_connection_coro_yield yield_result = from_coro & 0xffffffff;
507
508 if (UNLIKELY(yield_result >= CONN_CORO_ASYNC)__builtin_expect(((yield_result >= CONN_CORO_ASYNC)), (0)))
509 yield_result = resume_async(tq, yield_result, from_coro, conn, epoll_fd);
510
511 if (UNLIKELY(yield_result == CONN_CORO_ABORT)__builtin_expect(((yield_result == CONN_CORO_ABORT)), (0)))
512 return timeout_queue_expire(tq, conn);
513
514 return update_epoll_flags(lwan_connection_get_fd(tq->lwan, conn), conn,
515 epoll_fd, yield_result);
516}
517
518static void update_date_cache(struct lwan_thread *thread)
519{
520 time_t now = time(NULL((void*)0));
521
522 lwan_format_rfc_time(now, thread->date.date);
523 lwan_format_rfc_time(now + (time_t)thread->lwan->config.expires,
524 thread->date.expires);
525}
526
527__attribute__((cold))
528static bool_Bool send_buffer_without_coro(int fd, const char *buf, size_t buf_len, int flags)
529{
530 size_t total_sent = 0;
531
532 for (int try = 0; try < 10; try++) {
533 size_t to_send = buf_len - total_sent;
534 if (!to_send)
535 return true1;
536
537 ssize_t sent = send(fd, buf + total_sent, to_send, flags);
538 if (sent <= 0) {
539 if (errno(*__errno_location ()) == EINTR4)
540 continue;
541 if (errno(*__errno_location ()) == EAGAIN11)
542 continue;
543 break;
544 }
545
546 total_sent += (size_t)sent;
547 }
548
549 return false0;
550}
551
552__attribute__((cold))
553static bool_Bool send_string_without_coro(int fd, const char *str, int flags)
554{
555 return send_buffer_without_coro(fd, str, strlen(str), flags);
556}
557
558__attribute__((cold)) static void
559send_last_response_without_coro(const struct lwan *l,
560 const struct lwan_connection *conn,
561 enum lwan_http_status status)
562{
563 int fd = lwan_connection_get_fd(l, conn);
564
565 if (conn->flags & CONN_TLS) {
566 /* There's nothing that can be done here if a client is expecting a
567 * TLS connection: the TLS handshake requires a coroutine as it
568 * might yield. (In addition, the TLS handshake might allocate
569 * memory, and if you couldn't create a coroutine at this point,
570 * it's unlikely you'd be able to allocate memory for the TLS
571 * context anyway.) */
572 goto shutdown_and_close;
573 }
574
575 if (!send_string_without_coro(fd, "HTTP/1.0 ", MSG_MOREMSG_MORE))
576 goto shutdown_and_close;
577
578 if (!send_string_without_coro(
579 fd, lwan_http_status_as_string_with_code(status), MSG_MOREMSG_MORE))
580 goto shutdown_and_close;
581
582 if (!send_string_without_coro(fd, "\r\nConnection: close", MSG_MOREMSG_MORE))
583 goto shutdown_and_close;
584
585 if (!send_string_without_coro(fd, "\r\nContent-Type: text/html", MSG_MOREMSG_MORE))
586 goto shutdown_and_close;
587
588 if (send_buffer_without_coro(fd, l->headers.value, l->headers.len,
589 MSG_MOREMSG_MORE)) {
590 struct lwan_strbuf buffer;
591
592 lwan_strbuf_init(&buffer);
593 lwan_fill_default_response(&buffer, status);
594
595 send_buffer_without_coro(fd, lwan_strbuf_get_buffer(&buffer),
596 lwan_strbuf_get_length(&buffer), 0);
597
598 lwan_strbuf_free(&buffer);
599 }
600
601shutdown_and_close:
602 shutdown(fd, SHUT_RDWRSHUT_RDWR);
603 close(fd);
604}
605
606static ALWAYS_INLINEinline __attribute__((always_inline)) bool_Bool spawn_coro(struct lwan_connection *conn,
607 struct coro_switcher *switcher,
608 struct timeout_queue *tq)
609{
610 struct lwan_thread *t = conn->thread;
611#if defined(HAVE_MBEDTLS)
612 const enum lwan_connection_flags flags_to_keep = conn->flags & CONN_TLS;
613#else
614 const enum lwan_connection_flags flags_to_keep = 0;
615#endif
616
617 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"
, 617, __extension__ __PRETTY_FUNCTION__); }))
;
618 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"
, 618, __extension__ __PRETTY_FUNCTION__); }))
;
619 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"
, 619, __extension__ __PRETTY_FUNCTION__); }))
;
620 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"
, 620, __extension__ __PRETTY_FUNCTION__); }))
;
621 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"
, 622, __extension__ __PRETTY_FUNCTION__); }))
622 (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"
, 622, __extension__ __PRETTY_FUNCTION__); }))
;
623
624 *conn = (struct lwan_connection){
625 .coro = coro_new(switcher, process_request_coro, conn),
626 .flags = CONN_EVENTS_READ | flags_to_keep,
627 .time_to_expire = tq->current_time + tq->move_to_last_bump,
628 .thread = t,
629 };
630 if (LIKELY(conn->coro)__builtin_expect((!!(conn->coro)), (1))) {
631 timeout_queue_insert(tq, conn);
632 return true1;
633 }
634
635 conn->flags = 0;
636
637 int fd = lwan_connection_get_fd(tq->lwan, conn);
638
639 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"
, 639, __FUNCTION__, "Couldn't spawn coroutine for file descriptor %d"
, fd)
;
640
641 send_last_response_without_coro(tq->lwan, conn, HTTP_UNAVAILABLE);
642 return false0;
643}
644
645static bool_Bool process_pending_timers(struct timeout_queue *tq,
646 struct lwan_thread *t,
647 int epoll_fd)
648{
649 struct timeout *timeout;
650 bool_Bool should_expire_timers = false0;
651
652 while ((timeout = timeouts_get(t->wheel))) {
653 struct lwan_request *request;
654
655 if (timeout == &tq->timeout) {
656 should_expire_timers = true1;
657 continue;
658 }
659
660 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))
;
661
662 update_epoll_flags(request->fd, request->conn, epoll_fd,
663 CONN_CORO_RESUME);
664 }
665
666 if (should_expire_timers) {
667 timeout_queue_expire_waiting(tq);
668
669 /* tq timeout expires every 1000ms if there are connections, so
670 * update the date cache at this point as well. */
671 update_date_cache(t);
672
673 if (!timeout_queue_empty(tq)) {
674 timeouts_add(t->wheel, &tq->timeout, 1000);
675 return true1;
676 }
677
678 timeouts_del(t->wheel, &tq->timeout);
679 }
680
681 return false0;
682}
683
684static int
685turn_timer_wheel(struct timeout_queue *tq, struct lwan_thread *t, int epoll_fd)
686{
687 const int infinite_timeout = -1;
688 timeout_t wheel_timeout;
689 struct timespec now;
690
691 if (UNLIKELY(clock_gettime(monotonic_clock_id, &now) < 0)__builtin_expect(((clock_gettime(monotonic_clock_id, &now
) < 0)), (0))
)
692 lwan_status_critical("Could not get monotonic time")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 692, __FUNCTION__, "Could not get monotonic time")
;
693
694 timeouts_update(t->wheel,
695 (timeout_t)(now.tv_sec * 1000 + now.tv_nsec / 1000000));
696
697 /* Check if there's an expired timer. */
698 wheel_timeout = timeouts_timeout(t->wheel);
699 if (wheel_timeout > 0) {
700 return (int)wheel_timeout; /* No, but will soon. Wake us up in
701 wheel_timeout ms. */
702 }
703
704 if (UNLIKELY((int64_t)wheel_timeout < 0)__builtin_expect((((int64_t)wheel_timeout < 0)), (0)))
705 return infinite_timeout; /* None found. */
706
707 if (!process_pending_timers(tq, t, epoll_fd))
708 return infinite_timeout; /* No more timers to process. */
709
710 /* After processing pending timers, determine when to wake up. */
711 return (int)timeouts_timeout(t->wheel);
712}
713
714static bool_Bool accept_waiting_clients(const struct lwan_thread *t,
715 const struct lwan_connection *listen_socket)
716{
717 const uint32_t read_events = conn_flags_to_epoll_events(CONN_EVENTS_READ);
718 struct lwan_connection *conns = t->lwan->conns;
719 int listen_fd = (int)(intptr_t)(listen_socket - conns);
720 enum lwan_connection_flags new_conn_flags = 0;
721
722#if defined(HAVE_MBEDTLS)
723 if (listen_socket->flags & CONN_LISTENER_HTTPS) {
724 assert(listen_fd == t->tls_listen_fd)((void) sizeof ((listen_fd == t->tls_listen_fd) ? 1 : 0), __extension__
({ if (listen_fd == t->tls_listen_fd) ; else __assert_fail
("listen_fd == t->tls_listen_fd", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 724, __extension__ __PRETTY_FUNCTION__); }))
;
725 assert(!(listen_socket->flags & CONN_LISTENER_HTTP))((void) sizeof ((!(listen_socket->flags & CONN_LISTENER_HTTP
)) ? 1 : 0), __extension__ ({ if (!(listen_socket->flags &
CONN_LISTENER_HTTP)) ; else __assert_fail ("!(listen_socket->flags & CONN_LISTENER_HTTP)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 725, __extension__ __PRETTY_FUNCTION__); }))
;
726 new_conn_flags = CONN_TLS;
727 } else {
728 assert(listen_fd == t->listen_fd)((void) sizeof ((listen_fd == t->listen_fd) ? 1 : 0), __extension__
({ if (listen_fd == t->listen_fd) ; else __assert_fail ("listen_fd == t->listen_fd"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 728, __extension__ __PRETTY_FUNCTION__); }))
;
729 assert(listen_socket->flags & CONN_LISTENER_HTTP)((void) sizeof ((listen_socket->flags & CONN_LISTENER_HTTP
) ? 1 : 0), __extension__ ({ if (listen_socket->flags &
CONN_LISTENER_HTTP) ; else __assert_fail ("listen_socket->flags & CONN_LISTENER_HTTP"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 729, __extension__ __PRETTY_FUNCTION__); }))
;
730 }
731#endif
732
733 while (true1) {
734 int fd = accept4(listen_fd, NULL((void*)0), NULL((void*)0), SOCK_NONBLOCKSOCK_NONBLOCK | SOCK_CLOEXECSOCK_CLOEXEC);
735
736 if (LIKELY(fd >= 0)__builtin_expect((!!(fd >= 0)), (1))) {
737 struct lwan_connection *conn = &conns[fd];
738 struct epoll_event ev = {.data.ptr = conn, .events = read_events};
739 int r;
740
741 conn->flags = new_conn_flags;
742
743 r = epoll_ctl(conn->thread->epoll_fd, EPOLL_CTL_ADD1, fd, &ev);
744 if (UNLIKELY(r < 0)__builtin_expect(((r < 0)), (0))) {
745 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"
, 747, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
746 "set %d. Dropping connection",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 747, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
747 fd, conn->thread->epoll_fd)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 747, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
;
748 send_last_response_without_coro(t->lwan, conn, HTTP_UNAVAILABLE);
749 conn->flags = 0;
750 }
751
752 continue;
753 }
754
755 switch (errno(*__errno_location ())) {
756 default:
757 lwan_status_perror("Unexpected error while accepting connections")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 757, __FUNCTION__, "Unexpected error while accepting connections"
)
;
758 /* fallthrough */
759
760 case EAGAIN11:
761 return true1;
762
763 case EBADF9:
764 case ECONNABORTED103:
765 case EINVAL22:
766 lwan_status_info("Listening socket closed")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 766, __FUNCTION__, "Listening socket closed")
;
767 return false0;
768 }
769 }
770
771 __builtin_unreachable();
772}
773
774static int create_listen_socket(struct lwan_thread *t,
775 unsigned int num,
776 bool_Bool tls)
777{
778 const struct lwan *lwan = t->lwan;
779 int listen_fd;
780
781 listen_fd = lwan_create_listen_socket(lwan, num == 0, tls);
782 if (listen_fd < 0)
783 lwan_status_critical("Could not create listen_fd")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 783, __FUNCTION__, "Could not create listen_fd")
;
784
785 /* Ignore errors here, as this is just a hint */
786#if defined(HAVE_SO_ATTACH_REUSEPORT_CBPF)
787 /* From socket(7): "These options may be set repeatedly at any time on
788 * any socket in the group to replace the current BPF program used by
789 * all sockets in the group." */
790 if (num == 0) {
791 /* From socket(7): "The BPF program must return an index between 0 and
792 * N-1 representing the socket which should receive the packet (where N
793 * is the number of sockets in the group)." */
794 const uint32_t cpu_ad_off = (uint32_t)SKF_AD_OFF(-0x1000) + SKF_AD_CPU36;
795 struct sock_filter filter[] = {
796 {BPF_LD0x00 | BPF_W0x00 | BPF_ABS0x20, 0, 0, cpu_ad_off}, /* A = curr_cpu_index */
797 {BPF_RET0x06 | BPF_A0x10, 0, 0, 0}, /* return A */
798 };
799 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]))
};
800
801 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_ATTACH_REUSEPORT_CBPF51,
802 &fprog, sizeof(fprog));
803 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_LOCK_FILTER44,
804 (int[]){1}, sizeof(int));
805 }
806#elif defined(HAVE_SO_INCOMING_CPU) && defined(__x86_64__1)
807 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_INCOMING_CPU49, &t->cpu,
808 sizeof(t->cpu));
809#endif
810
811 struct epoll_event event = {
812 .events = EPOLLINEPOLLIN | EPOLLETEPOLLET | EPOLLERREPOLLERR,
813 .data.ptr = &t->lwan->conns[listen_fd],
814 };
815 if (epoll_ctl(t->epoll_fd, EPOLL_CTL_ADD1, listen_fd, &event) < 0)
816 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"
, 816, __FUNCTION__, "Could not add socket to epoll")
;
817
818 return listen_fd;
819}
820
821static void *thread_io_loop(void *data)
822{
823 struct lwan_thread *t = data;
824 int epoll_fd = t->epoll_fd;
825 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; })
;
826 struct lwan *lwan = t->lwan;
827 struct epoll_event *events;
828 struct coro_switcher switcher;
829 struct timeout_queue tq;
830
831 lwan_status_debug("Worker thread #%zd starting",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 832, __FUNCTION__, "Worker thread #%zd starting", t - t->
lwan->thread.threads + 1)
832 t - t->lwan->thread.threads + 1)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 832, __FUNCTION__, "Worker thread #%zd starting", t - t->
lwan->thread.threads + 1)
;
833 lwan_set_thread_name("worker");
834
835 events = calloc((size_t)max_events, sizeof(*events));
836 if (UNLIKELY(!events)__builtin_expect(((!events)), (0)))
837 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"
, 837, __FUNCTION__, "Could not allocate memory for events")
;
838
839 update_date_cache(t);
840
841 timeout_queue_init(&tq, lwan);
842
843 lwan_random_seed_prng_for_thread(t);
844
845 pthread_barrier_wait(&lwan->thread.barrier);
846
847 for (;;) {
848 int timeout = turn_timer_wheel(&tq, t, epoll_fd);
849 int n_fds = epoll_wait(epoll_fd, events, max_events, timeout);
850 bool_Bool accepted_connections = false0;
851
852 if (UNLIKELY(n_fds < 0)__builtin_expect(((n_fds < 0)), (0))) {
853 if (errno(*__errno_location ()) == EBADF9 || errno(*__errno_location ()) == EINVAL22)
854 break;
855 continue;
856 }
857
858 for (struct epoll_event *event = events; n_fds--; event++) {
859 struct lwan_connection *conn = event->data.ptr;
860
861 if (UNLIKELY(event->events & (EPOLLRDHUP | EPOLLHUP))__builtin_expect(((event->events & (EPOLLRDHUP | EPOLLHUP
))), (0))
) {
862 timeout_queue_expire(&tq, conn);
863 continue;
864 }
865
866 if (conn->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS)) {
867 if (LIKELY(accept_waiting_clients(t, conn))__builtin_expect((!!(accept_waiting_clients(t, conn))), (1))) {
868 accepted_connections = true1;
869 continue;
870 }
871 close(epoll_fd);
872 epoll_fd = -1;
873 break;
874 }
875
876 if (!conn->coro) {
877 if (UNLIKELY(!spawn_coro(conn, &switcher, &tq))__builtin_expect(((!spawn_coro(conn, &switcher, &tq))
), (0))
) {
878 send_last_response_without_coro(t->lwan, conn, HTTP_INTERNAL_ERROR);
879 continue;
880 }
881 }
882
883 resume_coro(&tq, conn, epoll_fd);
884 timeout_queue_move_to_last(&tq, conn);
885 }
886
887 if (accepted_connections)
888 timeouts_add(t->wheel, &tq.timeout, 1000);
889 }
890
891 pthread_barrier_wait(&lwan->thread.barrier);
892
893 timeout_queue_expire_all(&tq);
894 free(events);
895
896 return NULL((void*)0);
897}
898
899static void create_thread(struct lwan *l, struct lwan_thread *thread)
900{
901 int ignore;
902 pthread_attr_t attr;
903
904 thread->lwan = l;
905
906 thread->wheel = timeouts_open(&ignore);
907 if (!thread->wheel)
908 lwan_status_critical("Could not create timer wheel")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 908, __FUNCTION__, "Could not create timer wheel")
;
909
910 if ((thread->epoll_fd = epoll_create1(EPOLL_CLOEXECEPOLL_CLOEXEC)) < 0)
911 lwan_status_critical_perror("epoll_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 911, __FUNCTION__, "epoll_create")
;
912
913 if (pthread_attr_init(&attr))
914 lwan_status_critical_perror("pthread_attr_init")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 914, __FUNCTION__, "pthread_attr_init")
;
915
916 if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEMPTHREAD_SCOPE_SYSTEM))
917 lwan_status_critical_perror("pthread_attr_setscope")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 917, __FUNCTION__, "pthread_attr_setscope")
;
918
919 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLEPTHREAD_CREATE_JOINABLE))
920 lwan_status_critical_perror("pthread_attr_setdetachstate")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 920, __FUNCTION__, "pthread_attr_setdetachstate")
;
921
922 if (pthread_create(&thread->self, &attr, thread_io_loop, thread))
923 lwan_status_critical_perror("pthread_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 923, __FUNCTION__, "pthread_create")
;
924
925 if (pthread_attr_destroy(&attr))
926 lwan_status_critical_perror("pthread_attr_destroy")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 926, __FUNCTION__, "pthread_attr_destroy")
;
927}
928
929#if defined(__linux__1) && defined(__x86_64__1)
930static bool_Bool read_cpu_topology(struct lwan *l, uint32_t siblings[])
931{
932 char path[PATH_MAX4096];
933
934 for (uint32_t i = 0; i < l->available_cpus; i++)
935 siblings[i] = 0xbebacafe;
936
937 for (unsigned int i = 0; i < l->available_cpus; i++) {
938 FILE *sib;
939 uint32_t id, sibling;
940 char separator;
941
942 snprintf(path, sizeof(path),
943 "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list",
944 i);
945
946 sib = fopen(path, "re");
947 if (!sib) {
948 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"
, 949, __FUNCTION__, "Could not open `%s` to determine CPU topology"
, path)
949 path)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 949, __FUNCTION__, "Could not open `%s` to determine CPU topology"
, path)
;
950 return false0;
951 }
952
953 switch (fscanf(sib, "%u%c%u", &id, &separator, &sibling)) {
954 case 2: /* No SMT */
955 siblings[i] = id;
956 break;
957 case 3: /* SMT */
958 if (!(separator == ',' || separator == '-')) {
959 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"
, 959, __FUNCTION__, "Expecting either ',' or '-' for sibling separator"
)
;
960 __builtin_unreachable();
961 }
962
963 siblings[i] = sibling;
964 break;
965 default:
966 lwan_status_critical("%s has invalid format", path)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 966, __FUNCTION__, "%s has invalid format", path)
;
967 __builtin_unreachable();
968 }
969
970 fclose(sib);
971 }
972
973 /* Perform a sanity check here, as some systems seem to filter out the
974 * result of sysconf() to obtain the number of configured and online
975 * CPUs but don't bother changing what's available through sysfs as far
976 * as the CPU topology information goes. It's better to fall back to a
977 * possibly non-optimal setup than just crash during startup while
978 * trying to perform an out-of-bounds array access. */
979 for (unsigned int i = 0; i < l->available_cpus; i++) {
980 if (siblings[i] == 0xbebacafe) {
981 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"
, 981, __FUNCTION__, "Could not determine sibling for CPU %d"
, i)
;
982 return false0;
983 }
984
985 if (siblings[i] >= l->available_cpus) {
986 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"
, 989, __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)
987 "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"
, 989, __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)
988 "Is Lwan running in a (broken) container?",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 989, __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)
989 siblings[i], l->available_cpus, l->online_cpus)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 989, __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)
;
990 return false0;
991 }
992 }
993
994 return true1;
995}
996
997static void
998siblings_to_schedtbl(struct lwan *l, uint32_t siblings[], uint32_t schedtbl[])
999{
1000 int *seen = alloca(l->available_cpus * sizeof(int))__builtin_alloca (l->available_cpus * sizeof(int));
1001 unsigned int n_schedtbl = 0;
1002
1003 for (uint32_t i = 0; i < l->available_cpus; i++)
1004 seen[i] = -1;
1005
1006 for (uint32_t i = 0; i < l->available_cpus; i++) {
1007 if (seen[siblings[i]] < 0) {
1008 seen[siblings[i]] = (int)i;
1009 } else {
1010 schedtbl[n_schedtbl++] = (uint32_t)seen[siblings[i]];
1011 schedtbl[n_schedtbl++] = i;
1012 }
1013 }
1014
1015 if (n_schedtbl != l->available_cpus)
1016 memcpy(schedtbl, seen, l->available_cpus * sizeof(int));
1017}
1018
1019static bool_Bool
1020topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads)
1021{
1022 uint32_t *siblings = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t));
1023
1024 if (read_cpu_topology(l, siblings)) {
8
Assuming the condition is false
9
Taking false branch
1025 uint32_t *affinity = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t));
1026
1027 siblings_to_schedtbl(l, siblings, affinity);
1028
1029 for (uint32_t i = 0; i < n_threads; i++)
1030 schedtbl[i] = affinity[i % l->available_cpus];
1031 return true1;
1032 }
1033
1034 for (uint32_t i = 0; i < n_threads; i++)
10
Assuming 'i' is >= 'n_threads'
11
Loop condition is false. Execution continues on line 1036
1035 schedtbl[i] = (i / 2) % l->thread.count;
1036 return false0;
12
Returning without writing to '*schedtbl'
1037}
1038
1039static void
1040adjust_thread_affinity(const struct lwan_thread *thread)
1041{
1042 cpu_set_t set;
1043
1044 CPU_ZERO(&set)do __builtin_memset (&set, '\0', sizeof (cpu_set_t)); while
(0)
;
1045 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; }))
;
1046
1047 if (pthread_setaffinity_np(thread->self, sizeof(set), &set))
1048 lwan_status_warning("Could not set thread affinity")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1048, __FUNCTION__, "Could not set thread affinity")
;
1049}
1050#endif
1051
1052#if defined(HAVE_MBEDTLS)
1053static bool_Bool is_tls_ulp_supported(void)
1054{
1055 FILE *available_ulp = fopen("/proc/sys/net/ipv4/tcp_available_ulp", "re");
1056 char buffer[512];
1057 bool_Bool available = false0;
1058
1059 if (!available_ulp)
1060 return false0;
1061
1062 if (fgets(buffer, 512, available_ulp)) {
1063 if (strstr(buffer, "tls"))
1064 available = true1;
1065 }
1066
1067 fclose(available_ulp);
1068 return available;
1069}
1070
1071static bool_Bool lwan_init_tls(struct lwan *l)
1072{
1073 static const int aes128_ciphers[] = {
1074 /* Only allow Ephemeral Diffie-Hellman key exchange, so Perfect
1075 * Forward Secrecy is possible. */
1076 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA2560xC02F,
1077 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA2560xC02B,
1078 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA2560x9E,
1079 MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA2560xAA,
1080
1081 /* FIXME: Other ciphers are supported by kTLS, notably AES256 and
1082 * ChaCha20-Poly1305. Add those here and patch
1083 * lwan_setup_tls_keys() to match. */
1084
1085 /* FIXME: Maybe allow this to be user-tunable like other servers do? */
1086 0,
1087 };
1088 int r;
1089
1090 if (!l->config.ssl.cert || !l->config.ssl.key)
1091 return false0;
1092
1093 if (!is_tls_ulp_supported()) {
1094 lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1095, __FUNCTION__, "TLS ULP not loaded. Try running `modprobe tls` as root."
)
1095 "TLS ULP not loaded. Try running `modprobe tls` as root.")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1095, __FUNCTION__, "TLS ULP not loaded. Try running `modprobe tls` as root."
)
;
1096 }
1097
1098 l->tls = calloc(1, sizeof(*l->tls));
1099 if (!l->tls)
1100 lwan_status_critical("Could not allocate memory for SSL context")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1100, __FUNCTION__, "Could not allocate memory for SSL context"
)
;
1101
1102 lwan_status_debug("Initializing mbedTLS")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1102, __FUNCTION__, "Initializing mbedTLS")
;
1103
1104 mbedtls_ssl_config_init(&l->tls->config);
1105 mbedtls_x509_crt_init(&l->tls->server_cert);
1106 mbedtls_pk_init(&l->tls->server_key);
1107 mbedtls_entropy_init(&l->tls->entropy);
1108 mbedtls_ctr_drbg_init(&l->tls->ctr_drbg);
1109
1110 r = mbedtls_x509_crt_parse_file(&l->tls->server_cert, l->config.ssl.cert);
1111 if (r) {
1112 lwan_status_mbedtls_error(r, "Could not parse certificate at %s",
1113 l->config.ssl.cert);
1114 abort();
1115 }
1116
1117 r = mbedtls_pk_parse_keyfile(&l->tls->server_key, l->config.ssl.key, NULL((void*)0));
1118 if (r) {
1119 lwan_status_mbedtls_error(r, "Could not parse key file at %s",
1120 l->config.ssl.key);
1121 abort();
1122 }
1123
1124 /* Even though this points to files that will probably be outside
1125 * the reach of the server (if straightjackets are used), wipe this
1126 * struct to get rid of the paths to these files. */
1127 lwan_always_bzero(l->config.ssl.cert, strlen(l->config.ssl.cert));
1128 free(l->config.ssl.cert);
1129 lwan_always_bzero(l->config.ssl.key, strlen(l->config.ssl.key));
1130 free(l->config.ssl.key);
1131 lwan_always_bzero(&l->config.ssl, sizeof(l->config.ssl));
1132
1133 mbedtls_ssl_conf_ca_chain(&l->tls->config, l->tls->server_cert.next, NULL((void*)0));
1134 r = mbedtls_ssl_conf_own_cert(&l->tls->config, &l->tls->server_cert,
1135 &l->tls->server_key);
1136 if (r) {
1137 lwan_status_mbedtls_error(r, "Could not set cert/key");
1138 abort();
1139 }
1140
1141 r = mbedtls_ctr_drbg_seed(&l->tls->ctr_drbg, mbedtls_entropy_func,
1142 &l->tls->entropy, NULL((void*)0), 0);
1143 if (r) {
1144 lwan_status_mbedtls_error(r, "Could not seed ctr_drbg");
1145 abort();
1146 }
1147
1148 r = mbedtls_ssl_config_defaults(&l->tls->config, MBEDTLS_SSL_IS_SERVER1,
1149 MBEDTLS_SSL_TRANSPORT_STREAM0,
1150 MBEDTLS_SSL_PRESET_DEFAULT0);
1151 if (r) {
1152 lwan_status_mbedtls_error(r, "Could not set mbedTLS default config");
1153 abort();
1154 }
1155
1156 mbedtls_ssl_conf_rng(&l->tls->config, mbedtls_ctr_drbg_random,
1157 &l->tls->ctr_drbg);
1158 mbedtls_ssl_conf_ciphersuites(&l->tls->config, aes128_ciphers);
1159
1160 mbedtls_ssl_conf_renegotiation(&l->tls->config,
1161 MBEDTLS_SSL_RENEGOTIATION_DISABLED0);
1162 mbedtls_ssl_conf_legacy_renegotiation(&l->tls->config,
1163 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION0);
1164
1165#if defined(MBEDTLS_SSL_ALPN)
1166 static const char *alpn_protos[] = {"http/1.1", NULL((void*)0)};
1167 mbedtls_ssl_conf_alpn_protocols(&l->tls->config, alpn_protos);
1168#endif
1169
1170 return true1;
1171}
1172#endif
1173
1174void lwan_thread_init(struct lwan *l)
1175{
1176 const unsigned int total_conns = l->thread.max_fd * l->thread.count;
1177#if defined(HAVE_MBEDTLS)
1178 const bool_Bool tls_initialized = lwan_init_tls(l);
1179#else
1180 const bool_Bool tls_initialized = false0;
1181#endif
1182
1183 lwan_status_debug("Initializing threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1183, __FUNCTION__, "Initializing threads")
;
1184
1185 l->thread.threads =
1186 calloc((size_t)l->thread.count, sizeof(struct lwan_thread));
1187 if (!l->thread.threads)
1
Assuming field 'threads' is non-null
2
Taking false branch
1188 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"
, 1188, __FUNCTION__, "Could not allocate memory for threads"
)
;
1189
1190 uint32_t *schedtbl;
1191 uint32_t n_threads;
1192 bool_Bool adj_affinity;
1193
1194#if defined(__x86_64__1) && defined(__linux__1)
1195 if (l->online_cpus > 1) {
3
Assuming field 'online_cpus' is > 1
4
Taking true branch
1196 static_assert_Static_assert(sizeof(struct lwan_connection) == 32,
1197 "Two connections per cache line");
1198#ifdef _SC_LEVEL1_DCACHE_LINESIZE_SC_LEVEL1_DCACHE_LINESIZE
1199 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"
, 1199, __extension__ __PRETTY_FUNCTION__); }))
;
5
Assuming the condition is true
6
Taking true branch
1200#endif
1201 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"
, 1203, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
1202 "Reading topology to pre-schedule clients",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1203, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
1203 l->online_cpus, l->available_cpus)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1203, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
;
1204 /*
1205 * Pre-schedule each file descriptor, to reduce some operations in the
1206 * fast path.
1207 *
1208 * Since struct lwan_connection is guaranteed to be 32-byte long, two of
1209 * them can fill up a cache line. Assume siblings share cache lines and
1210 * use the CPU topology to group two connections per cache line in such
1211 * a way that false sharing is avoided.
1212 */
1213 n_threads = (uint32_t)lwan_nextpow2((size_t)((l->thread.count - 1) * 2));
1214 schedtbl = alloca(n_threads * sizeof(uint32_t))__builtin_alloca (n_threads * sizeof(uint32_t));
1215
1216 adj_affinity = topology_to_schedtbl(l, schedtbl, n_threads);
7
Calling 'topology_to_schedtbl'
13
Returning from 'topology_to_schedtbl'
1217
1218 n_threads--; /* Transform count into mask for AND below */
1219
1220 for (unsigned int i = 0; i < total_conns; i++)
14
Assuming 'i' is >= 'total_conns'
15
Loop condition is false. Execution continues on line 1237
1221 l->conns[i].thread = &l->thread.threads[schedtbl[i & n_threads]];
1222 } else
1223#endif /* __x86_64__ && __linux__ */
1224 {
1225 lwan_status_debug("Using round-robin to preschedule clients")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1225, __FUNCTION__, "Using round-robin to preschedule clients"
)
;
1226
1227 for (unsigned int i = 0; i < l->thread.count; i++)
1228 l->thread.threads[i].cpu = i % l->online_cpus;
1229 for (unsigned int i = 0; i < total_conns; i++)
1230 l->conns[i].thread = &l->thread.threads[i % l->thread.count];
1231
1232 schedtbl = NULL((void*)0);
1233 adj_affinity = false0;
1234 n_threads = l->thread.count;
1235 }
1236
1237 for (unsigned int i = 0; i < l->thread.count; i++) {
16
Assuming 'i' is < field 'count'
17
Loop condition is true. Entering loop body
1238 struct lwan_thread *thread = NULL((void*)0);
1239
1240 if (schedtbl
17.1
'schedtbl' is non-null
) {
18
Taking true branch
1241 /* This is not the most elegant thing, but this assures that the
1242 * listening sockets are added to the SO_REUSEPORT group in a
1243 * specific order, because that's what the CBPF program to direct
1244 * the incoming connection to the right CPU will use. */
1245 for (uint32_t thread_id = 0; thread_id
18.1
'thread_id' is < field 'count'
< l->thread.count;
19
Loop condition is true. Entering loop body
1246 thread_id++) {
1247 if (schedtbl[thread_id & n_threads] == i) {
20
The left operand of '==' is a garbage value
1248 thread = &l->thread.threads[thread_id];
1249 break;
1250 }
1251 }
1252 if (!thread) {
1253 /* FIXME: can this happen when we have a offline CPU? */
1254 lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1255, __FUNCTION__, "Could not figure out which CPU thread %d should go to"
, i)
1255 "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"
, 1255, __FUNCTION__, "Could not figure out which CPU thread %d should go to"
, i)
;
1256 }
1257 } else {
1258 thread = &l->thread.threads[i % l->thread.count];
1259 }
1260
1261 if (pthread_barrier_init(&l->thread.barrier, NULL((void*)0), 2))
1262 lwan_status_critical("Could not create barrier")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1262, __FUNCTION__, "Could not create barrier")
;
1263
1264 create_thread(l, thread);
1265
1266 if ((thread->listen_fd = create_listen_socket(thread, i, false0)) < 0)
1267 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"
, 1267, __FUNCTION__, "Could not create listening socket")
;
1268 l->conns[thread->listen_fd].flags |= CONN_LISTENER_HTTP;
1269
1270 if (tls_initialized) {
1271 if ((thread->tls_listen_fd = create_listen_socket(thread, i, true1)) < 0)
1272 lwan_status_critical_perror("Could not create TLS listening socket")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1272, __FUNCTION__, "Could not create TLS listening socket"
)
;
1273 l->conns[thread->tls_listen_fd].flags |= CONN_LISTENER_HTTPS;
1274 } else {
1275 thread->tls_listen_fd = -1;
1276 }
1277
1278 if (adj_affinity) {
1279 l->thread.threads[i].cpu = schedtbl[i & n_threads];
1280 adjust_thread_affinity(thread);
1281 }
1282
1283 pthread_barrier_wait(&l->thread.barrier);
1284 }
1285
1286 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"
, 1286, __FUNCTION__, "Worker threads created and ready to serve"
)
;
1287}
1288
1289void lwan_thread_shutdown(struct lwan *l)
1290{
1291 lwan_status_debug("Shutting down threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1291, __FUNCTION__, "Shutting down threads")
;
1292
1293 for (unsigned int i = 0; i < l->thread.count; i++) {
1294 struct lwan_thread *t = &l->thread.threads[i];
1295 int epoll_fd = t->epoll_fd;
1296 int listen_fd = t->listen_fd;
1297
1298 t->listen_fd = -1;
1299 t->epoll_fd = -1;
1300 close(epoll_fd);
1301 close(listen_fd);
1302 }
1303
1304 pthread_barrier_wait(&l->thread.barrier);
1305 pthread_barrier_destroy(&l->thread.barrier);
1306
1307 for (unsigned int i = 0; i < l->thread.count; i++) {
1308 struct lwan_thread *t = &l->thread.threads[i];
1309
1310 pthread_join(l->thread.threads[i].self, NULL((void*)0));
1311 timeouts_close(t->wheel);
1312 }
1313
1314 free(l->thread.threads);
1315
1316#if defined(HAVE_MBEDTLS)
1317 if (l->tls) {
1318 mbedtls_ssl_config_free(&l->tls->config);
1319 mbedtls_x509_crt_free(&l->tls->server_cert);
1320 mbedtls_pk_free(&l->tls->server_key);
1321 mbedtls_entropy_free(&l->tls->entropy);
1322 mbedtls_ctr_drbg_free(&l->tls->ctr_drbg);
1323 free(l->tls);
1324 }
1325#endif
1326}