Bug Summary

File:lwan-thread.c
Warning:line 881, column 35
Array subscript is undefined

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