Bug Summary

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