Bug Summary

File:lib/lwan-thread.c
Warning:line 895, column 31
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-09-01-160346-3158436-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 struct lwan_connection *conns = t->lwan->conns;
520
521 while (true1) {
522 int fd =
523 accept4(t->listen_fd, NULL((void*)0), NULL((void*)0), SOCK_NONBLOCKSOCK_NONBLOCK | SOCK_CLOEXECSOCK_CLOEXEC);
524
525 if (LIKELY(fd >= 0)__builtin_expect((!!(fd >= 0)), (1))) {
526 const struct lwan_connection *conn = &conns[fd];
527 struct epoll_event ev = {
528 .data.ptr = (void *)conn,
529 .events = conn_flags_to_epoll_events(CONN_EVENTS_READ),
530 };
531 int r = epoll_ctl(conn->thread->epoll_fd, EPOLL_CTL_ADD1, fd, &ev);
532
533 if (UNLIKELY(r < 0)__builtin_expect(((r < 0)), (0))) {
534 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"
, 536, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
535 "set %d. Dropping connection",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 536, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
536 fd, conn->thread->epoll_fd)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 536, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
;
537
538 send_response_without_coro(t->lwan, fd, HTTP_UNAVAILABLE);
539 shutdown(fd, SHUT_RDWRSHUT_RDWR);
540 close(fd);
541 }
542
543 continue;
544 }
545
546 switch (errno(*__errno_location ())) {
547 default:
548 lwan_status_perror("Unexpected error while accepting connections")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 548, __FUNCTION__, "Unexpected error while accepting connections"
)
;
549 /* fallthrough */
550
551 case EAGAIN11:
552 return true1;
553
554 case EBADF9:
555 case ECONNABORTED103:
556 case EINVAL22:
557 lwan_status_info("Listening socket closed")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 557, __FUNCTION__, "Listening socket closed")
;
558 return false0;
559 }
560 }
561
562 __builtin_unreachable();
563}
564
565static int create_listen_socket(struct lwan_thread *t,
566 unsigned int num)
567{
568 int listen_fd;
569
570 listen_fd = lwan_create_listen_socket(t->lwan, num == 0);
571 if (listen_fd < 0)
572 lwan_status_critical("Could not create listen_fd")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 572, __FUNCTION__, "Could not create listen_fd")
;
573
574 /* Ignore errors here, as this is just a hint */
575#if defined(HAVE_SO_ATTACH_REUSEPORT_CBPF)
576 /* From socket(7): "These options may be set repeatedly at any time on
577 * any socket in the group to replace the current BPF program used by
578 * all sockets in the group." */
579 if (num == 0) {
580 /* From socket(7): "The BPF program must return an index between 0 and
581 * N-1 representing the socket which should receive the packet (where N
582 * is the number of sockets in the group)." */
583 const uint32_t cpu_ad_off = (uint32_t)SKF_AD_OFF(-0x1000) + SKF_AD_CPU36;
584 struct sock_filter filter[] = {
585 {BPF_LD0x00 | BPF_W0x00 | BPF_ABS0x20, 0, 0, cpu_ad_off}, /* A = curr_cpu_index */
586 {BPF_RET0x06 | BPF_A0x10, 0, 0, 0}, /* return A */
587 };
588 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]))
};
589
590 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_ATTACH_REUSEPORT_CBPF51,
591 &fprog, sizeof(fprog));
592 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_LOCK_FILTER44,
593 (int[]){1}, sizeof(int));
594 }
595#elif defined(HAVE_SO_INCOMING_CPU) && defined(__x86_64__1)
596 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_INCOMING_CPU49, &t->cpu,
597 sizeof(t->cpu));
598#endif
599
600 struct epoll_event event = {
601 .events = EPOLLINEPOLLIN | EPOLLETEPOLLET | EPOLLERREPOLLERR,
602 .data.ptr = NULL((void*)0),
603 };
604 if (epoll_ctl(t->epoll_fd, EPOLL_CTL_ADD1, listen_fd, &event) < 0)
605 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"
, 605, __FUNCTION__, "Could not add socket to epoll")
;
606
607 return listen_fd;
608}
609
610static void *thread_io_loop(void *data)
611{
612 struct lwan_thread *t = data;
613 int epoll_fd = t->epoll_fd;
614 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; })
;
615 struct lwan *lwan = t->lwan;
616 struct epoll_event *events;
617 struct coro_switcher switcher;
618 struct timeout_queue tq;
619
620 lwan_status_debug("Worker thread #%zd starting",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 621, __FUNCTION__, "Worker thread #%zd starting", t - t->
lwan->thread.threads + 1)
621 t - t->lwan->thread.threads + 1)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 621, __FUNCTION__, "Worker thread #%zd starting", t - t->
lwan->thread.threads + 1)
;
622 lwan_set_thread_name("worker");
623
624 events = calloc((size_t)max_events, sizeof(*events));
625 if (UNLIKELY(!events)__builtin_expect(((!events)), (0)))
626 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"
, 626, __FUNCTION__, "Could not allocate memory for events")
;
627
628 update_date_cache(t);
629
630 timeout_queue_init(&tq, lwan);
631
632 lwan_random_seed_prng_for_thread(t);
633
634 pthread_barrier_wait(&lwan->thread.barrier);
635
636 for (;;) {
637 int timeout = turn_timer_wheel(&tq, t, epoll_fd);
638 int n_fds = epoll_wait(epoll_fd, events, max_events, timeout);
639 bool_Bool accepted_connections = false0;
640
641 if (UNLIKELY(n_fds < 0)__builtin_expect(((n_fds < 0)), (0))) {
642 if (errno(*__errno_location ()) == EBADF9 || errno(*__errno_location ()) == EINVAL22)
643 break;
644 continue;
645 }
646
647 for (struct epoll_event *event = events; n_fds--; event++) {
648 struct lwan_connection *conn;
649
650 if (!event->data.ptr) {
651 if (LIKELY(accept_waiting_clients(t))__builtin_expect((!!(accept_waiting_clients(t))), (1))) {
652 accepted_connections = true1;
653 continue;
654 }
655 close(epoll_fd);
656 epoll_fd = -1;
657 break;
658 }
659
660 conn = event->data.ptr;
661
662 if (UNLIKELY(event->events & (EPOLLRDHUP | EPOLLHUP))__builtin_expect(((event->events & (EPOLLRDHUP | EPOLLHUP
))), (0))
) {
663 timeout_queue_expire(&tq, conn);
664 continue;
665 }
666
667 if (!conn->coro) {
668 if (UNLIKELY(!spawn_coro(conn, &switcher, &tq))__builtin_expect(((!spawn_coro(conn, &switcher, &tq))
), (0))
)
669 continue;
670 }
671
672 resume_coro(&tq, conn, epoll_fd);
673 timeout_queue_move_to_last(&tq, conn);
674 }
675
676 if (accepted_connections)
677 timeouts_add(t->wheel, &tq.timeout, 1000);
678 }
679
680 pthread_barrier_wait(&lwan->thread.barrier);
681
682 timeout_queue_expire_all(&tq);
683 free(events);
684
685 return NULL((void*)0);
686}
687
688static void create_thread(struct lwan *l, struct lwan_thread *thread)
689{
690 int ignore;
691 pthread_attr_t attr;
692
693 thread->lwan = l;
694
695 thread->wheel = timeouts_open(&ignore);
696 if (!thread->wheel)
697 lwan_status_critical("Could not create timer wheel")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 697, __FUNCTION__, "Could not create timer wheel")
;
698
699 if ((thread->epoll_fd = epoll_create1(EPOLL_CLOEXECEPOLL_CLOEXEC)) < 0)
700 lwan_status_critical_perror("epoll_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 700, __FUNCTION__, "epoll_create")
;
701
702 if (pthread_attr_init(&attr))
703 lwan_status_critical_perror("pthread_attr_init")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 703, __FUNCTION__, "pthread_attr_init")
;
704
705 if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEMPTHREAD_SCOPE_SYSTEM))
706 lwan_status_critical_perror("pthread_attr_setscope")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 706, __FUNCTION__, "pthread_attr_setscope")
;
707
708 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLEPTHREAD_CREATE_JOINABLE))
709 lwan_status_critical_perror("pthread_attr_setdetachstate")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 709, __FUNCTION__, "pthread_attr_setdetachstate")
;
710
711 if (pthread_create(&thread->self, &attr, thread_io_loop, thread))
712 lwan_status_critical_perror("pthread_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 712, __FUNCTION__, "pthread_create")
;
713
714 if (pthread_attr_destroy(&attr))
715 lwan_status_critical_perror("pthread_attr_destroy")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 715, __FUNCTION__, "pthread_attr_destroy")
;
716}
717
718#if defined(__linux__1) && defined(__x86_64__1)
719static bool_Bool read_cpu_topology(struct lwan *l, uint32_t siblings[])
720{
721 char path[PATH_MAX4096];
722
723 for (uint32_t i = 0; i < l->available_cpus; i++)
724 siblings[i] = 0xbebacafe;
725
726 for (unsigned int i = 0; i < l->available_cpus; i++) {
727 FILE *sib;
728 uint32_t id, sibling;
729 char separator;
730
731 snprintf(path, sizeof(path),
732 "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list",
733 i);
734
735 sib = fopen(path, "re");
736 if (!sib) {
737 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"
, 738, __FUNCTION__, "Could not open `%s` to determine CPU topology"
, path)
738 path)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 738, __FUNCTION__, "Could not open `%s` to determine CPU topology"
, path)
;
739 return false0;
740 }
741
742 switch (fscanf(sib, "%u%c%u", &id, &separator, &sibling)) {
743 case 2: /* No SMT */
744 siblings[i] = id;
745 break;
746 case 3: /* SMT */
747 if (!(separator == ',' || separator == '-')) {
748 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"
, 748, __FUNCTION__, "Expecting either ',' or '-' for sibling separator"
)
;
749 __builtin_unreachable();
750 }
751
752 siblings[i] = sibling;
753 break;
754 default:
755 lwan_status_critical("%s has invalid format", path)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 755, __FUNCTION__, "%s has invalid format", path)
;
756 __builtin_unreachable();
757 }
758
759 fclose(sib);
760 }
761
762 /* Perform a sanity check here, as some systems seem to filter out the
763 * result of sysconf() to obtain the number of configured and online
764 * CPUs but don't bother changing what's available through sysfs as far
765 * as the CPU topology information goes. It's better to fall back to a
766 * possibly non-optimal setup than just crash during startup while
767 * trying to perform an out-of-bounds array access. */
768 for (unsigned int i = 0; i < l->available_cpus; i++) {
769 if (siblings[i] == 0xbebacafe) {
770 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"
, 770, __FUNCTION__, "Could not determine sibling for CPU %d"
, i)
;
771 return false0;
772 }
773
774 if (siblings[i] >= l->available_cpus) {
775 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"
, 778, __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 "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"
, 778, __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 "Is Lwan running in a (broken) container?",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 778, __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)
778 siblings[i], l->available_cpus, l->online_cpus)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 778, __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)
;
779 return false0;
780 }
781 }
782
783 return true1;
784}
785
786static void
787siblings_to_schedtbl(struct lwan *l, uint32_t siblings[], uint32_t schedtbl[])
788{
789 int *seen = alloca(l->available_cpus * sizeof(int))__builtin_alloca (l->available_cpus * sizeof(int));
790 unsigned int n_schedtbl = 0;
791
792 for (uint32_t i = 0; i < l->available_cpus; i++)
793 seen[i] = -1;
794
795 for (uint32_t i = 0; i < l->available_cpus; i++) {
796 if (seen[siblings[i]] < 0) {
797 seen[siblings[i]] = (int)i;
798 } else {
799 schedtbl[n_schedtbl++] = (uint32_t)seen[siblings[i]];
800 schedtbl[n_schedtbl++] = i;
801 }
802 }
803
804 if (n_schedtbl != l->available_cpus)
805 memcpy(schedtbl, seen, l->available_cpus * sizeof(int));
806}
807
808static bool_Bool
809topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads)
810{
811 uint32_t *siblings = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t));
812
813 if (read_cpu_topology(l, siblings)) {
6
Assuming the condition is false
7
Taking false branch
814 uint32_t *affinity = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t));
815
816 siblings_to_schedtbl(l, siblings, affinity);
817
818 for (uint32_t i = 0; i < n_threads; i++)
819 schedtbl[i] = affinity[i % l->available_cpus];
820 return true1;
821 }
822
823 for (uint32_t i = 0; i < n_threads; i++)
8
Assuming 'i' is >= 'n_threads'
9
Loop condition is false. Execution continues on line 825
824 schedtbl[i] = (i / 2) % l->thread.count;
825 return false0;
10
Returning without writing to '*schedtbl'
826}
827
828static void
829adjust_thread_affinity(const struct lwan_thread *thread)
830{
831 cpu_set_t set;
832
833 CPU_ZERO(&set)do __builtin_memset (&set, '\0', sizeof (cpu_set_t)); while
(0)
;
834 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; }))
;
835
836 if (pthread_setaffinity_np(thread->self, sizeof(set), &set))
837 lwan_status_warning("Could not set thread affinity")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 837, __FUNCTION__, "Could not set thread affinity")
;
838}
839#elif defined(__x86_64__1)
840static bool_Bool
841topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads)
842{
843 for (uint32_t i = 0; i < n_threads; i++)
844 schedtbl[i] = (i / 2) % l->thread.count;
845 return false0;
846}
847
848static void
849adjust_thread_affinity(const struct lwan_thread *thread)
850{
851 (void)thread;
852}
853#endif
854
855void lwan_thread_init(struct lwan *l)
856{
857 const unsigned int total_conns = l->thread.max_fd * l->thread.count;
858
859 lwan_status_debug("Initializing threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 859, __FUNCTION__, "Initializing threads")
;
860
861 l->thread.threads =
862 calloc((size_t)l->thread.count, sizeof(struct lwan_thread));
863 if (!l->thread.threads)
1
Assuming field 'threads' is non-null
2
Taking false branch
864 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"
, 864, __FUNCTION__, "Could not allocate memory for threads")
;
865
866#ifdef __x86_64__1
867 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; })]
868 "Two connections per cache line")extern int (*__Static_assert_function (void)) [!!sizeof (struct
{ int __error_if_negative: (sizeof(struct lwan_connection) ==
32) ? 2 : -1; })]
;
869#ifdef _SC_LEVEL1_DCACHE_LINESIZE_SC_LEVEL1_DCACHE_LINESIZE
870 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"
, 870, __extension__ __PRETTY_FUNCTION__); }))
;
3
Assuming the condition is true
4
Taking true branch
871#endif
872
873 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"
, 875, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
874 "Reading topology to pre-schedule clients",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 875, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
875 l->online_cpus, l->available_cpus)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 875, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
;
876
877 /*
878 * Pre-schedule each file descriptor, to reduce some operations in the
879 * fast path.
880 *
881 * Since struct lwan_connection is guaranteed to be 32-byte long, two of
882 * them can fill up a cache line. Assume siblings share cache lines and
883 * use the CPU topology to group two connections per cache line in such
884 * a way that false sharing is avoided.
885 */
886 uint32_t n_threads =
887 (uint32_t)lwan_nextpow2((size_t)((l->thread.count - 1) * 2));
888 uint32_t *schedtbl = alloca(n_threads * sizeof(uint32_t))__builtin_alloca (n_threads * sizeof(uint32_t));
889
890 bool_Bool adj_affinity = topology_to_schedtbl(l, schedtbl, n_threads);
5
Calling 'topology_to_schedtbl'
11
Returning from 'topology_to_schedtbl'
891
892 n_threads--; /* Transform count into mask for AND below */
893
894 for (unsigned int i = 0; i < total_conns; i++)
12
Assuming 'i' is < 'total_conns'
13
Loop condition is true. Entering loop body
895 l->conns[i].thread = &l->thread.threads[schedtbl[i & n_threads]];
14
Array subscript is undefined
896#else
897 for (unsigned int i = 0; i < l->thread.count; i++)
898 l->thread.threads[i].cpu = i % l->online_cpus;
899 for (unsigned int i = 0; i < total_conns; i++)
900 l->conns[i].thread = &l->thread.threads[i % l->thread.count];
901
902 uint32_t *schedtbl = NULL((void*)0);
903 const bool_Bool adj_affinity = false0;
904#endif
905
906 for (unsigned int i = 0; i < l->thread.count; i++) {
907 struct lwan_thread *thread = NULL((void*)0);
908
909 if (schedtbl) {
910 /* This is not the most elegant thing, but this assures that the
911 * listening sockets are added to the SO_REUSEPORT group in a
912 * specific order, because that's what the CBPF program to direct
913 * the incoming connection to the right CPU will use. */
914 for (uint32_t thread_id = 0; thread_id < l->thread.count;
915 thread_id++) {
916 if (schedtbl[thread_id & n_threads] == i) {
917 thread = &l->thread.threads[thread_id];
918 break;
919 }
920 }
921 if (!thread) {
922 /* FIXME: can this happen when we have a offline CPU? */
923 lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 924, __FUNCTION__, "Could not figure out which CPU thread %d should go to"
, i)
924 "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"
, 924, __FUNCTION__, "Could not figure out which CPU thread %d should go to"
, i)
;
925 }
926 } else {
927 thread = &l->thread.threads[i % l->thread.count];
928 }
929
930 if (pthread_barrier_init(&l->thread.barrier, NULL((void*)0), 2))
931 lwan_status_critical("Could not create barrier")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 931, __FUNCTION__, "Could not create barrier")
;
932
933 create_thread(l, thread);
934
935 if ((thread->listen_fd = create_listen_socket(thread, i)) < 0)
936 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"
, 936, __FUNCTION__, "Could not create listening socket")
;
937
938 if (adj_affinity) {
939 l->thread.threads[i].cpu = schedtbl[i & n_threads];
940 adjust_thread_affinity(thread);
941 }
942
943 pthread_barrier_wait(&l->thread.barrier);
944 }
945
946 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"
, 946, __FUNCTION__, "Worker threads created and ready to serve"
)
;
947}
948
949void lwan_thread_shutdown(struct lwan *l)
950{
951 lwan_status_debug("Shutting down threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 951, __FUNCTION__, "Shutting down threads")
;
952
953 for (unsigned int i = 0; i < l->thread.count; i++) {
954 struct lwan_thread *t = &l->thread.threads[i];
955 int epoll_fd = t->epoll_fd;
956 int listen_fd = t->listen_fd;
957
958 t->listen_fd = -1;
959 t->epoll_fd = -1;
960 close(epoll_fd);
961 close(listen_fd);
962 }
963
964 pthread_barrier_wait(&l->thread.barrier);
965 pthread_barrier_destroy(&l->thread.barrier);
966
967 for (unsigned int i = 0; i < l->thread.count; i++) {
968 struct lwan_thread *t = &l->thread.threads[i];
969
970 pthread_join(l->thread.threads[i].self, NULL((void*)0));
971 timeouts_close(t->wheel);
972 }
973
974 free(l->thread.threads);
975}