Fix: memory leak on connection reset
[lttng-ust.git] / liblttng-ust / lttng-ust-comm.c
1 /*
2 * lttng-ust-comm.c
3 *
4 * Copyright (C) 2011 David Goulet <david.goulet@polymtl.ca>
5 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; only
10 * version 2.1 of the License.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #define _LGPL_SOURCE
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <sys/mman.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <fcntl.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <pthread.h>
33 #include <semaphore.h>
34 #include <time.h>
35 #include <assert.h>
36 #include <signal.h>
37 #include <urcu/uatomic.h>
38 #include <urcu/futex.h>
39 #include <urcu/compiler.h>
40
41 #include <lttng/ust-events.h>
42 #include <lttng/ust-abi.h>
43 #include <lttng/ust.h>
44 #include <lttng/ust-error.h>
45 #include <lttng/ust-ctl.h>
46 #include <urcu/tls-compat.h>
47 #include <ust-comm.h>
48 #include <usterr-signal-safe.h>
49 #include <helper.h>
50 #include "tracepoint-internal.h"
51 #include "lttng-tracer-core.h"
52 #include "compat.h"
53 #include "../libringbuffer/tlsfixup.h"
54
55 /*
56 * Has lttng ust comm constructor been called ?
57 */
58 static int initialized;
59
60 /*
61 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
62 * Held when handling a command, also held by fork() to deal with
63 * removal of threads, and by exit path.
64 */
65
66 /* Should the ust comm thread quit ? */
67 static int lttng_ust_comm_should_quit;
68
69 /*
70 * Wait for either of these before continuing to the main
71 * program:
72 * - the register_done message from sessiond daemon
73 * (will let the sessiond daemon enable sessions before main
74 * starts.)
75 * - sessiond daemon is not reachable.
76 * - timeout (ensuring applications are resilient to session
77 * daemon problems).
78 */
79 static sem_t constructor_wait;
80 /*
81 * Doing this for both the global and local sessiond.
82 */
83 static int sem_count = { 2 };
84
85 /*
86 * Counting nesting within lttng-ust. Used to ensure that calling fork()
87 * from liblttng-ust does not execute the pre/post fork handlers.
88 */
89 static DEFINE_URCU_TLS(int, lttng_ust_nest_count);
90
91 /*
92 * Info about socket and associated listener thread.
93 */
94 struct sock_info {
95 const char *name;
96 pthread_t ust_listener; /* listener thread */
97 int root_handle;
98 int constructor_sem_posted;
99 int allowed;
100 int global;
101 int thread_active;
102
103 char sock_path[PATH_MAX];
104 int socket;
105 int notify_socket;
106
107 char wait_shm_path[PATH_MAX];
108 char *wait_shm_mmap;
109 };
110
111 /* Socket from app (connect) to session daemon (listen) for communication */
112 struct sock_info global_apps = {
113 .name = "global",
114 .global = 1,
115
116 .root_handle = -1,
117 .allowed = 1,
118 .thread_active = 0,
119
120 .sock_path = LTTNG_DEFAULT_RUNDIR "/" LTTNG_UST_SOCK_FILENAME,
121 .socket = -1,
122 .notify_socket = -1,
123
124 .wait_shm_path = "/" LTTNG_UST_WAIT_FILENAME,
125 };
126
127 /* TODO: allow global_apps_sock_path override */
128
129 struct sock_info local_apps = {
130 .name = "local",
131 .global = 0,
132 .root_handle = -1,
133 .allowed = 0, /* Check setuid bit first */
134 .thread_active = 0,
135
136 .socket = -1,
137 .notify_socket = -1,
138 };
139
140 static int wait_poll_fallback;
141
142 static const char *cmd_name_mapping[] = {
143 [ LTTNG_UST_RELEASE ] = "Release",
144 [ LTTNG_UST_SESSION ] = "Create Session",
145 [ LTTNG_UST_TRACER_VERSION ] = "Get Tracer Version",
146
147 [ LTTNG_UST_TRACEPOINT_LIST ] = "Create Tracepoint List",
148 [ LTTNG_UST_WAIT_QUIESCENT ] = "Wait for Quiescent State",
149 [ LTTNG_UST_REGISTER_DONE ] = "Registration Done",
150 [ LTTNG_UST_TRACEPOINT_FIELD_LIST ] = "Create Tracepoint Field List",
151
152 /* Session FD commands */
153 [ LTTNG_UST_CHANNEL ] = "Create Channel",
154 [ LTTNG_UST_SESSION_START ] = "Start Session",
155 [ LTTNG_UST_SESSION_STOP ] = "Stop Session",
156
157 /* Channel FD commands */
158 [ LTTNG_UST_STREAM ] = "Create Stream",
159 [ LTTNG_UST_EVENT ] = "Create Event",
160
161 /* Event and Channel FD commands */
162 [ LTTNG_UST_CONTEXT ] = "Create Context",
163 [ LTTNG_UST_FLUSH_BUFFER ] = "Flush Buffer",
164
165 /* Event, Channel and Session commands */
166 [ LTTNG_UST_ENABLE ] = "Enable",
167 [ LTTNG_UST_DISABLE ] = "Disable",
168
169 /* Tracepoint list commands */
170 [ LTTNG_UST_TRACEPOINT_LIST_GET ] = "List Next Tracepoint",
171 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET ] = "List Next Tracepoint Field",
172
173 /* Event FD commands */
174 [ LTTNG_UST_FILTER ] = "Create Filter",
175 };
176
177 static const char *str_timeout;
178 static int got_timeout_env;
179
180 extern void lttng_ring_buffer_client_overwrite_init(void);
181 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
182 extern void lttng_ring_buffer_client_discard_init(void);
183 extern void lttng_ring_buffer_client_discard_rt_init(void);
184 extern void lttng_ring_buffer_metadata_client_init(void);
185 extern void lttng_ring_buffer_client_overwrite_exit(void);
186 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
187 extern void lttng_ring_buffer_client_discard_exit(void);
188 extern void lttng_ring_buffer_client_discard_rt_exit(void);
189 extern void lttng_ring_buffer_metadata_client_exit(void);
190
191 /*
192 * Force a read (imply TLS fixup for dlopen) of TLS variables.
193 */
194 static
195 void lttng_fixup_nest_count_tls(void)
196 {
197 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count)));
198 }
199
200 int lttng_get_notify_socket(void *owner)
201 {
202 struct sock_info *info = owner;
203
204 return info->notify_socket;
205 }
206
207 static
208 void print_cmd(int cmd, int handle)
209 {
210 const char *cmd_name = "Unknown";
211
212 if (cmd_name_mapping[cmd]) {
213 cmd_name = cmd_name_mapping[cmd];
214 }
215 DBG("Message Received \"%s\", Handle \"%s\" (%d)", cmd_name,
216 lttng_ust_obj_get_name(handle), handle);
217 }
218
219 static
220 int setup_local_apps(void)
221 {
222 const char *home_dir;
223 uid_t uid;
224
225 uid = getuid();
226 /*
227 * Disallow per-user tracing for setuid binaries.
228 */
229 if (uid != geteuid()) {
230 assert(local_apps.allowed == 0);
231 return 0;
232 }
233 home_dir = (const char *) getenv("HOME");
234 if (!home_dir) {
235 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
236 assert(local_apps.allowed == 0);
237 return -ENOENT;
238 }
239 local_apps.allowed = 1;
240 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
241 home_dir,
242 LTTNG_DEFAULT_HOME_RUNDIR,
243 LTTNG_UST_SOCK_FILENAME);
244 snprintf(local_apps.wait_shm_path, PATH_MAX, "/%s-%u",
245 LTTNG_UST_WAIT_FILENAME,
246 uid);
247 return 0;
248 }
249
250 /*
251 * Get notify_sock timeout, in ms.
252 * -1: don't wait. 0: wait forever. >0: timeout, in ms.
253 */
254 static
255 long get_timeout(void)
256 {
257 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
258
259 if (!got_timeout_env) {
260 str_timeout = getenv("LTTNG_UST_REGISTER_TIMEOUT");
261 got_timeout_env = 1;
262 }
263 if (str_timeout)
264 constructor_delay_ms = strtol(str_timeout, NULL, 10);
265 return constructor_delay_ms;
266 }
267
268 static
269 long get_notify_sock_timeout(void)
270 {
271 return get_timeout();
272 }
273
274 /*
275 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
276 */
277 static
278 int get_constructor_timeout(struct timespec *constructor_timeout)
279 {
280 long constructor_delay_ms;
281 int ret;
282
283 constructor_delay_ms = get_timeout();
284
285 switch (constructor_delay_ms) {
286 case -1:/* fall-through */
287 case 0:
288 return constructor_delay_ms;
289 default:
290 break;
291 }
292
293 /*
294 * If we are unable to find the current time, don't wait.
295 */
296 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
297 if (ret) {
298 return -1;
299 }
300 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
301 constructor_timeout->tv_nsec +=
302 (constructor_delay_ms % 1000UL) * 1000000UL;
303 if (constructor_timeout->tv_nsec >= 1000000000UL) {
304 constructor_timeout->tv_sec++;
305 constructor_timeout->tv_nsec -= 1000000000UL;
306 }
307 return 1;
308 }
309
310 static
311 int register_to_sessiond(int socket, enum ustctl_socket_type type)
312 {
313 return ustcomm_send_reg_msg(socket,
314 type,
315 CAA_BITS_PER_LONG,
316 lttng_alignof(uint8_t) * CHAR_BIT,
317 lttng_alignof(uint16_t) * CHAR_BIT,
318 lttng_alignof(uint32_t) * CHAR_BIT,
319 lttng_alignof(uint64_t) * CHAR_BIT,
320 lttng_alignof(unsigned long) * CHAR_BIT);
321 }
322
323 static
324 int send_reply(int sock, struct ustcomm_ust_reply *lur)
325 {
326 ssize_t len;
327
328 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
329 switch (len) {
330 case sizeof(*lur):
331 DBG("message successfully sent");
332 return 0;
333 default:
334 if (len == -ECONNRESET) {
335 DBG("remote end closed connection");
336 return 0;
337 }
338 if (len < 0)
339 return len;
340 DBG("incorrect message size: %zd", len);
341 return -EINVAL;
342 }
343 }
344
345 static
346 int handle_register_done(struct sock_info *sock_info)
347 {
348 int ret;
349
350 if (sock_info->constructor_sem_posted)
351 return 0;
352 sock_info->constructor_sem_posted = 1;
353 if (uatomic_read(&sem_count) <= 0) {
354 return 0;
355 }
356 ret = uatomic_add_return(&sem_count, -1);
357 if (ret == 0) {
358 ret = sem_post(&constructor_wait);
359 assert(!ret);
360 }
361 return 0;
362 }
363
364 static
365 int handle_message(struct sock_info *sock_info,
366 int sock, struct ustcomm_ust_msg *lum)
367 {
368 int ret = 0;
369 const struct lttng_ust_objd_ops *ops;
370 struct ustcomm_ust_reply lur;
371 union ust_args args;
372 ssize_t len;
373
374 ust_lock();
375
376 memset(&lur, 0, sizeof(lur));
377
378 if (lttng_ust_comm_should_quit) {
379 ret = -LTTNG_UST_ERR_EXITING;
380 goto end;
381 }
382
383 ops = objd_ops(lum->handle);
384 if (!ops) {
385 ret = -ENOENT;
386 goto end;
387 }
388
389 switch (lum->cmd) {
390 case LTTNG_UST_REGISTER_DONE:
391 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
392 ret = handle_register_done(sock_info);
393 else
394 ret = -EINVAL;
395 break;
396 case LTTNG_UST_RELEASE:
397 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
398 ret = -EPERM;
399 else
400 ret = lttng_ust_objd_unref(lum->handle, 1);
401 break;
402 case LTTNG_UST_FILTER:
403 {
404 /* Receive filter data */
405 struct lttng_ust_filter_bytecode_node *bytecode;
406
407 if (lum->u.filter.data_size > FILTER_BYTECODE_MAX_LEN) {
408 ERR("Filter data size is too large: %u bytes",
409 lum->u.filter.data_size);
410 ret = -EINVAL;
411 goto error;
412 }
413
414 if (lum->u.filter.reloc_offset > lum->u.filter.data_size) {
415 ERR("Filter reloc offset %u is not within data",
416 lum->u.filter.reloc_offset);
417 ret = -EINVAL;
418 goto error;
419 }
420
421 bytecode = zmalloc(sizeof(*bytecode) + lum->u.filter.data_size);
422 if (!bytecode) {
423 ret = -ENOMEM;
424 goto error;
425 }
426 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data,
427 lum->u.filter.data_size);
428 switch (len) {
429 case 0: /* orderly shutdown */
430 ret = 0;
431 free(bytecode);
432 goto error;
433 default:
434 if (len == lum->u.filter.data_size) {
435 DBG("filter data received");
436 break;
437 } else if (len < 0) {
438 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
439 if (len == -ECONNRESET) {
440 ERR("%s remote end closed connection", sock_info->name);
441 ret = len;
442 free(bytecode);
443 goto error;
444 }
445 ret = len;
446 free(bytecode);
447 goto end;
448 } else {
449 DBG("incorrect filter data message size: %zd", len);
450 ret = -EINVAL;
451 free(bytecode);
452 goto end;
453 }
454 }
455 bytecode->bc.len = lum->u.filter.data_size;
456 bytecode->bc.reloc_offset = lum->u.filter.reloc_offset;
457 bytecode->bc.seqnum = lum->u.filter.seqnum;
458 if (ops->cmd) {
459 ret = ops->cmd(lum->handle, lum->cmd,
460 (unsigned long) bytecode,
461 &args, sock_info);
462 if (ret) {
463 free(bytecode);
464 }
465 /* don't free bytecode if everything went fine. */
466 } else {
467 ret = -ENOSYS;
468 free(bytecode);
469 }
470 break;
471 }
472 case LTTNG_UST_CHANNEL:
473 {
474 void *chan_data;
475 int wakeup_fd;
476
477 len = ustcomm_recv_channel_from_sessiond(sock,
478 &chan_data, lum->u.channel.len,
479 &wakeup_fd);
480 switch (len) {
481 case 0: /* orderly shutdown */
482 ret = 0;
483 goto error;
484 default:
485 if (len == lum->u.channel.len) {
486 DBG("channel data received");
487 break;
488 } else if (len < 0) {
489 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
490 if (len == -ECONNRESET) {
491 ERR("%s remote end closed connection", sock_info->name);
492 ret = len;
493 goto error;
494 }
495 ret = len;
496 goto end;
497 } else {
498 DBG("incorrect channel data message size: %zd", len);
499 ret = -EINVAL;
500 goto end;
501 }
502 }
503 args.channel.chan_data = chan_data;
504 args.channel.wakeup_fd = wakeup_fd;
505 if (ops->cmd)
506 ret = ops->cmd(lum->handle, lum->cmd,
507 (unsigned long) &lum->u,
508 &args, sock_info);
509 else
510 ret = -ENOSYS;
511 break;
512 }
513 case LTTNG_UST_STREAM:
514 {
515 /* Receive shm_fd, wakeup_fd */
516 ret = ustcomm_recv_stream_from_sessiond(sock,
517 &lum->u.stream.len,
518 &args.stream.shm_fd,
519 &args.stream.wakeup_fd);
520 if (ret) {
521 goto end;
522 }
523 if (ops->cmd)
524 ret = ops->cmd(lum->handle, lum->cmd,
525 (unsigned long) &lum->u,
526 &args, sock_info);
527 else
528 ret = -ENOSYS;
529 break;
530 }
531 default:
532 if (ops->cmd)
533 ret = ops->cmd(lum->handle, lum->cmd,
534 (unsigned long) &lum->u,
535 &args, sock_info);
536 else
537 ret = -ENOSYS;
538 break;
539 }
540
541 end:
542 lur.handle = lum->handle;
543 lur.cmd = lum->cmd;
544 lur.ret_val = ret;
545 if (ret >= 0) {
546 lur.ret_code = LTTNG_UST_OK;
547 } else {
548 /*
549 * Use -LTTNG_UST_ERR as wildcard for UST internal
550 * error that are not caused by the transport, except if
551 * we already have a more precise error message to
552 * report.
553 */
554 if (ret > -LTTNG_UST_ERR) {
555 /* Translate code to UST error. */
556 switch (ret) {
557 case -EEXIST:
558 lur.ret_code = -LTTNG_UST_ERR_EXIST;
559 break;
560 case -EINVAL:
561 lur.ret_code = -LTTNG_UST_ERR_INVAL;
562 break;
563 case -ENOENT:
564 lur.ret_code = -LTTNG_UST_ERR_NOENT;
565 break;
566 case -EPERM:
567 lur.ret_code = -LTTNG_UST_ERR_PERM;
568 break;
569 case -ENOSYS:
570 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
571 break;
572 default:
573 lur.ret_code = -LTTNG_UST_ERR;
574 break;
575 }
576 } else {
577 lur.ret_code = ret;
578 }
579 }
580 if (ret >= 0) {
581 switch (lum->cmd) {
582 case LTTNG_UST_TRACER_VERSION:
583 lur.u.version = lum->u.version;
584 break;
585 case LTTNG_UST_TRACEPOINT_LIST_GET:
586 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
587 break;
588 }
589 }
590 DBG("Return value: %d", lur.ret_val);
591 ret = send_reply(sock, &lur);
592 if (ret < 0) {
593 DBG("error sending reply");
594 goto error;
595 }
596
597 /*
598 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
599 * after the reply.
600 */
601 if (lur.ret_code == LTTNG_UST_OK) {
602 switch (lum->cmd) {
603 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
604 len = ustcomm_send_unix_sock(sock,
605 &args.field_list.entry,
606 sizeof(args.field_list.entry));
607 if (len < 0) {
608 ret = len;
609 goto error;
610 }
611 if (len != sizeof(args.field_list.entry)) {
612 ret = -EINVAL;
613 goto error;
614 }
615 }
616 }
617
618 error:
619 ust_unlock();
620 return ret;
621 }
622
623 static
624 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
625 {
626 int ret;
627
628 if (sock_info->socket != -1) {
629 ret = ustcomm_close_unix_sock(sock_info->socket);
630 if (ret) {
631 ERR("Error closing ust cmd socket");
632 }
633 sock_info->socket = -1;
634 }
635 if (sock_info->notify_socket != -1) {
636 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
637 if (ret) {
638 ERR("Error closing ust notify socket");
639 }
640 sock_info->notify_socket = -1;
641 }
642 if (sock_info->root_handle != -1) {
643 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
644 if (ret) {
645 ERR("Error unref root handle");
646 }
647 sock_info->root_handle = -1;
648 }
649 sock_info->constructor_sem_posted = 0;
650 /*
651 * wait_shm_mmap is used by listener threads outside of the
652 * ust lock, so we cannot tear it down ourselves, because we
653 * cannot join on these threads. Leave this task to the OS
654 * process exit.
655 */
656 if (!exiting && sock_info->wait_shm_mmap) {
657 ret = munmap(sock_info->wait_shm_mmap, sysconf(_SC_PAGE_SIZE));
658 if (ret) {
659 ERR("Error unmapping wait shm");
660 }
661 sock_info->wait_shm_mmap = NULL;
662 }
663 }
664
665 /*
666 * Using fork to set umask in the child process (not multi-thread safe).
667 * We deal with the shm_open vs ftruncate race (happening when the
668 * sessiond owns the shm and does not let everybody modify it, to ensure
669 * safety against shm_unlink) by simply letting the mmap fail and
670 * retrying after a few seconds.
671 * For global shm, everybody has rw access to it until the sessiond
672 * starts.
673 */
674 static
675 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
676 {
677 int wait_shm_fd, ret;
678 pid_t pid;
679
680 /*
681 * Try to open read-only.
682 */
683 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
684 if (wait_shm_fd >= 0) {
685 goto end;
686 } else if (wait_shm_fd < 0 && errno != ENOENT) {
687 /*
688 * Real-only open did not work, and it's not because the
689 * entry was not present. It's a failure that prohibits
690 * using shm.
691 */
692 ERR("Error opening shm %s", sock_info->wait_shm_path);
693 goto end;
694 }
695 /*
696 * If the open failed because the file did not exist, try
697 * creating it ourself.
698 */
699 URCU_TLS(lttng_ust_nest_count)++;
700 pid = fork();
701 URCU_TLS(lttng_ust_nest_count)--;
702 if (pid > 0) {
703 int status;
704
705 /*
706 * Parent: wait for child to return, in which case the
707 * shared memory map will have been created.
708 */
709 pid = wait(&status);
710 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
711 wait_shm_fd = -1;
712 goto end;
713 }
714 /*
715 * Try to open read-only again after creation.
716 */
717 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
718 if (wait_shm_fd < 0) {
719 /*
720 * Real-only open did not work. It's a failure
721 * that prohibits using shm.
722 */
723 ERR("Error opening shm %s", sock_info->wait_shm_path);
724 goto end;
725 }
726 goto end;
727 } else if (pid == 0) {
728 int create_mode;
729
730 /* Child */
731 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
732 if (sock_info->global)
733 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
734 /*
735 * We're alone in a child process, so we can modify the
736 * process-wide umask.
737 */
738 umask(~create_mode);
739 /*
740 * Try creating shm (or get rw access).
741 * We don't do an exclusive open, because we allow other
742 * processes to create+ftruncate it concurrently.
743 */
744 wait_shm_fd = shm_open(sock_info->wait_shm_path,
745 O_RDWR | O_CREAT, create_mode);
746 if (wait_shm_fd >= 0) {
747 ret = ftruncate(wait_shm_fd, mmap_size);
748 if (ret) {
749 PERROR("ftruncate");
750 _exit(EXIT_FAILURE);
751 }
752 _exit(EXIT_SUCCESS);
753 }
754 /*
755 * For local shm, we need to have rw access to accept
756 * opening it: this means the local sessiond will be
757 * able to wake us up. For global shm, we open it even
758 * if rw access is not granted, because the root.root
759 * sessiond will be able to override all rights and wake
760 * us up.
761 */
762 if (!sock_info->global && errno != EACCES) {
763 ERR("Error opening shm %s", sock_info->wait_shm_path);
764 _exit(EXIT_FAILURE);
765 }
766 /*
767 * The shm exists, but we cannot open it RW. Report
768 * success.
769 */
770 _exit(EXIT_SUCCESS);
771 } else {
772 return -1;
773 }
774 end:
775 if (wait_shm_fd >= 0 && !sock_info->global) {
776 struct stat statbuf;
777
778 /*
779 * Ensure that our user is the owner of the shm file for
780 * local shm. If we do not own the file, it means our
781 * sessiond will not have access to wake us up (there is
782 * probably a rogue process trying to fake our
783 * sessiond). Fallback to polling method in this case.
784 */
785 ret = fstat(wait_shm_fd, &statbuf);
786 if (ret) {
787 PERROR("fstat");
788 goto error_close;
789 }
790 if (statbuf.st_uid != getuid())
791 goto error_close;
792 }
793 return wait_shm_fd;
794
795 error_close:
796 ret = close(wait_shm_fd);
797 if (ret) {
798 PERROR("Error closing fd");
799 }
800 return -1;
801 }
802
803 static
804 char *get_map_shm(struct sock_info *sock_info)
805 {
806 size_t mmap_size = sysconf(_SC_PAGE_SIZE);
807 int wait_shm_fd, ret;
808 char *wait_shm_mmap;
809
810 wait_shm_fd = get_wait_shm(sock_info, mmap_size);
811 if (wait_shm_fd < 0) {
812 goto error;
813 }
814 wait_shm_mmap = mmap(NULL, mmap_size, PROT_READ,
815 MAP_SHARED, wait_shm_fd, 0);
816 /* close shm fd immediately after taking the mmap reference */
817 ret = close(wait_shm_fd);
818 if (ret) {
819 PERROR("Error closing fd");
820 }
821 if (wait_shm_mmap == MAP_FAILED) {
822 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
823 goto error;
824 }
825 return wait_shm_mmap;
826
827 error:
828 return NULL;
829 }
830
831 static
832 void wait_for_sessiond(struct sock_info *sock_info)
833 {
834 int ret;
835
836 ust_lock();
837 if (lttng_ust_comm_should_quit) {
838 goto quit;
839 }
840 if (wait_poll_fallback) {
841 goto error;
842 }
843 if (!sock_info->wait_shm_mmap) {
844 sock_info->wait_shm_mmap = get_map_shm(sock_info);
845 if (!sock_info->wait_shm_mmap)
846 goto error;
847 }
848 ust_unlock();
849
850 DBG("Waiting for %s apps sessiond", sock_info->name);
851 /* Wait for futex wakeup */
852 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap) == 0) {
853 ret = futex_async((int32_t *) sock_info->wait_shm_mmap,
854 FUTEX_WAIT, 0, NULL, NULL, 0);
855 if (ret < 0) {
856 if (errno == EFAULT) {
857 wait_poll_fallback = 1;
858 DBG(
859 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
860 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
861 "Please upgrade your kernel "
862 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
863 "mainline). LTTng-UST will use polling mode fallback.");
864 if (ust_debug())
865 PERROR("futex");
866 }
867 }
868 }
869 return;
870
871 quit:
872 ust_unlock();
873 return;
874
875 error:
876 ust_unlock();
877 return;
878 }
879
880 /*
881 * This thread does not allocate any resource, except within
882 * handle_message, within mutex protection. This mutex protects against
883 * fork and exit.
884 * The other moment it allocates resources is at socket connection, which
885 * is also protected by the mutex.
886 */
887 static
888 void *ust_listener_thread(void *arg)
889 {
890 struct sock_info *sock_info = arg;
891 int sock, ret, prev_connect_failed = 0, has_waited = 0;
892 int open_sock[2];
893 int i;
894 long timeout;
895
896 /* Restart trying to connect to the session daemon */
897 restart:
898 if (prev_connect_failed) {
899 /* Wait for sessiond availability with pipe */
900 wait_for_sessiond(sock_info);
901 if (has_waited) {
902 has_waited = 0;
903 /*
904 * Sleep for 5 seconds before retrying after a
905 * sequence of failure / wait / failure. This
906 * deals with a killed or broken session daemon.
907 */
908 sleep(5);
909 }
910 has_waited = 1;
911 prev_connect_failed = 0;
912 }
913 ust_lock();
914
915 if (lttng_ust_comm_should_quit) {
916 goto quit;
917 }
918
919 if (sock_info->socket != -1) {
920 ret = ustcomm_close_unix_sock(sock_info->socket);
921 if (ret) {
922 ERR("Error closing %s ust cmd socket",
923 sock_info->name);
924 }
925 sock_info->socket = -1;
926 }
927 if (sock_info->notify_socket != -1) {
928 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
929 if (ret) {
930 ERR("Error closing %s ust notify socket",
931 sock_info->name);
932 }
933 sock_info->notify_socket = -1;
934 }
935
936 /* Register */
937 for (i = 0; i < 2; i++) {
938 ret = ustcomm_connect_unix_sock(sock_info->sock_path);
939 if (ret < 0) {
940 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
941 prev_connect_failed = 1;
942 /*
943 * If we cannot find the sessiond daemon, don't delay
944 * constructor execution.
945 */
946 ret = handle_register_done(sock_info);
947 assert(!ret);
948 ust_unlock();
949 goto restart;
950 }
951 open_sock[i] = ret;
952 }
953
954 sock_info->socket = open_sock[0];
955 sock_info->notify_socket = open_sock[1];
956
957 timeout = get_notify_sock_timeout();
958 if (timeout >= 0) {
959 /*
960 * Give at least 10ms to sessiond to reply to
961 * notifications.
962 */
963 if (timeout < 10)
964 timeout = 10;
965 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
966 timeout);
967 if (ret < 0) {
968 WARN("Error setting socket receive timeout");
969 }
970 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
971 timeout);
972 if (ret < 0) {
973 WARN("Error setting socket send timeout");
974 }
975 } else if (timeout < -1) {
976 WARN("Unsuppoorted timeout value %ld", timeout);
977 }
978
979 /*
980 * Create only one root handle per listener thread for the whole
981 * process lifetime, so we ensure we get ID which is statically
982 * assigned to the root handle.
983 */
984 if (sock_info->root_handle == -1) {
985 ret = lttng_abi_create_root_handle();
986 if (ret < 0) {
987 ERR("Error creating root handle");
988 goto quit;
989 }
990 sock_info->root_handle = ret;
991 }
992
993 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
994 if (ret < 0) {
995 ERR("Error registering to %s ust cmd socket",
996 sock_info->name);
997 prev_connect_failed = 1;
998 /*
999 * If we cannot register to the sessiond daemon, don't
1000 * delay constructor execution.
1001 */
1002 ret = handle_register_done(sock_info);
1003 assert(!ret);
1004 ust_unlock();
1005 goto restart;
1006 }
1007 ret = register_to_sessiond(sock_info->notify_socket,
1008 USTCTL_SOCKET_NOTIFY);
1009 if (ret < 0) {
1010 ERR("Error registering to %s ust notify socket",
1011 sock_info->name);
1012 prev_connect_failed = 1;
1013 /*
1014 * If we cannot register to the sessiond daemon, don't
1015 * delay constructor execution.
1016 */
1017 ret = handle_register_done(sock_info);
1018 assert(!ret);
1019 ust_unlock();
1020 goto restart;
1021 }
1022 sock = sock_info->socket;
1023
1024 ust_unlock();
1025
1026 for (;;) {
1027 ssize_t len;
1028 struct ustcomm_ust_msg lum;
1029
1030 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1031 switch (len) {
1032 case 0: /* orderly shutdown */
1033 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
1034 ust_lock();
1035 if (lttng_ust_comm_should_quit) {
1036 goto quit;
1037 }
1038 /*
1039 * Either sessiond has shutdown or refused us by closing the socket.
1040 * In either case, we don't want to delay construction execution,
1041 * and we need to wait before retry.
1042 */
1043 prev_connect_failed = 1;
1044 /*
1045 * If we cannot register to the sessiond daemon, don't
1046 * delay constructor execution.
1047 */
1048 ret = handle_register_done(sock_info);
1049 assert(!ret);
1050 ust_unlock();
1051 goto end;
1052 case sizeof(lum):
1053 print_cmd(lum.cmd, lum.handle);
1054 ret = handle_message(sock_info, sock, &lum);
1055 if (ret) {
1056 ERR("Error handling message for %s socket", sock_info->name);
1057 }
1058 continue;
1059 default:
1060 if (len < 0) {
1061 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1062 } else {
1063 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1064 }
1065 if (len == -ECONNRESET) {
1066 DBG("%s remote end closed connection", sock_info->name);
1067 goto end;
1068 }
1069 goto end;
1070 }
1071
1072 }
1073 end:
1074 ust_lock();
1075 if (lttng_ust_comm_should_quit) {
1076 goto quit;
1077 }
1078 /* Cleanup socket handles before trying to reconnect */
1079 lttng_ust_objd_table_owner_cleanup(sock_info);
1080 ust_unlock();
1081 goto restart; /* try to reconnect */
1082
1083 quit:
1084 sock_info->thread_active = 0;
1085 ust_unlock();
1086 return NULL;
1087 }
1088
1089 /*
1090 * sessiond monitoring thread: monitor presence of global and per-user
1091 * sessiond by polling the application common named pipe.
1092 */
1093 void __attribute__((constructor)) lttng_ust_init(void)
1094 {
1095 struct timespec constructor_timeout;
1096 sigset_t sig_all_blocked, orig_parent_mask;
1097 pthread_attr_t thread_attr;
1098 int timeout_mode;
1099 int ret;
1100
1101 if (uatomic_xchg(&initialized, 1) == 1)
1102 return;
1103
1104 /*
1105 * Fixup interdependency between TLS fixup mutex (which happens
1106 * to be the dynamic linker mutex) and ust_lock, taken within
1107 * the ust lock.
1108 */
1109 lttng_fixup_ringbuffer_tls();
1110 lttng_fixup_vtid_tls();
1111 lttng_fixup_nest_count_tls();
1112 lttng_fixup_procname_tls();
1113
1114 /*
1115 * We want precise control over the order in which we construct
1116 * our sub-libraries vs starting to receive commands from
1117 * sessiond (otherwise leading to errors when trying to create
1118 * sessiond before the init functions are completed).
1119 */
1120 init_usterr();
1121 init_tracepoint();
1122 lttng_ring_buffer_metadata_client_init();
1123 lttng_ring_buffer_client_overwrite_init();
1124 lttng_ring_buffer_client_overwrite_rt_init();
1125 lttng_ring_buffer_client_discard_init();
1126 lttng_ring_buffer_client_discard_rt_init();
1127 lttng_context_init();
1128
1129 timeout_mode = get_constructor_timeout(&constructor_timeout);
1130
1131 ret = sem_init(&constructor_wait, 0, 0);
1132 assert(!ret);
1133
1134 ret = setup_local_apps();
1135 if (ret) {
1136 DBG("local apps setup returned %d", ret);
1137 }
1138
1139 /* A new thread created by pthread_create inherits the signal mask
1140 * from the parent. To avoid any signal being received by the
1141 * listener thread, we block all signals temporarily in the parent,
1142 * while we create the listener thread.
1143 */
1144 sigfillset(&sig_all_blocked);
1145 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1146 if (ret) {
1147 ERR("pthread_sigmask: %s", strerror(ret));
1148 }
1149
1150 ret = pthread_attr_init(&thread_attr);
1151 if (ret) {
1152 ERR("pthread_attr_init: %s", strerror(ret));
1153 }
1154 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1155 if (ret) {
1156 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1157 }
1158
1159 ust_lock();
1160 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1161 ust_listener_thread, &global_apps);
1162 if (ret) {
1163 ERR("pthread_create global: %s", strerror(ret));
1164 }
1165 global_apps.thread_active = 1;
1166 ust_unlock();
1167
1168 if (local_apps.allowed) {
1169 ust_lock();
1170 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
1171 ust_listener_thread, &local_apps);
1172 if (ret) {
1173 ERR("pthread_create local: %s", strerror(ret));
1174 }
1175 local_apps.thread_active = 1;
1176 ust_unlock();
1177 } else {
1178 handle_register_done(&local_apps);
1179 }
1180 ret = pthread_attr_destroy(&thread_attr);
1181 if (ret) {
1182 ERR("pthread_attr_destroy: %s", strerror(ret));
1183 }
1184
1185 /* Restore original signal mask in parent */
1186 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1187 if (ret) {
1188 ERR("pthread_sigmask: %s", strerror(ret));
1189 }
1190
1191 switch (timeout_mode) {
1192 case 1: /* timeout wait */
1193 do {
1194 ret = sem_timedwait(&constructor_wait,
1195 &constructor_timeout);
1196 } while (ret < 0 && errno == EINTR);
1197 if (ret < 0 && errno == ETIMEDOUT) {
1198 ERR("Timed out waiting for lttng-sessiond");
1199 } else {
1200 assert(!ret);
1201 }
1202 break;
1203 case -1:/* wait forever */
1204 do {
1205 ret = sem_wait(&constructor_wait);
1206 } while (ret < 0 && errno == EINTR);
1207 assert(!ret);
1208 break;
1209 case 0: /* no timeout */
1210 break;
1211 }
1212 }
1213
1214 static
1215 void lttng_ust_cleanup(int exiting)
1216 {
1217 cleanup_sock_info(&global_apps, exiting);
1218 if (local_apps.allowed) {
1219 cleanup_sock_info(&local_apps, exiting);
1220 }
1221 /*
1222 * The teardown in this function all affect data structures
1223 * accessed under the UST lock by the listener thread. This
1224 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1225 * that none of these threads are accessing this data at this
1226 * point.
1227 */
1228 lttng_ust_abi_exit();
1229 lttng_ust_events_exit();
1230 lttng_context_exit();
1231 lttng_ring_buffer_client_discard_rt_exit();
1232 lttng_ring_buffer_client_discard_exit();
1233 lttng_ring_buffer_client_overwrite_rt_exit();
1234 lttng_ring_buffer_client_overwrite_exit();
1235 lttng_ring_buffer_metadata_client_exit();
1236 exit_tracepoint();
1237 if (!exiting) {
1238 /* Reinitialize values for fork */
1239 sem_count = 2;
1240 lttng_ust_comm_should_quit = 0;
1241 initialized = 0;
1242 }
1243 }
1244
1245 void __attribute__((destructor)) lttng_ust_exit(void)
1246 {
1247 int ret;
1248
1249 /*
1250 * Using pthread_cancel here because:
1251 * A) we don't want to hang application teardown.
1252 * B) the thread is not allocating any resource.
1253 */
1254
1255 /*
1256 * Require the communication thread to quit. Synchronize with
1257 * mutexes to ensure it is not in a mutex critical section when
1258 * pthread_cancel is later called.
1259 */
1260 ust_lock();
1261 lttng_ust_comm_should_quit = 1;
1262
1263 /* cancel threads */
1264 if (global_apps.thread_active) {
1265 ret = pthread_cancel(global_apps.ust_listener);
1266 if (ret) {
1267 ERR("Error cancelling global ust listener thread: %s",
1268 strerror(ret));
1269 } else {
1270 global_apps.thread_active = 0;
1271 }
1272 }
1273 if (local_apps.thread_active) {
1274 ret = pthread_cancel(local_apps.ust_listener);
1275 if (ret) {
1276 ERR("Error cancelling local ust listener thread: %s",
1277 strerror(ret));
1278 } else {
1279 local_apps.thread_active = 0;
1280 }
1281 }
1282 ust_unlock();
1283
1284 /*
1285 * Do NOT join threads: use of sys_futex makes it impossible to
1286 * join the threads without using async-cancel, but async-cancel
1287 * is delivered by a signal, which could hit the target thread
1288 * anywhere in its code path, including while the ust_lock() is
1289 * held, causing a deadlock for the other thread. Let the OS
1290 * cleanup the threads if there are stalled in a syscall.
1291 */
1292 lttng_ust_cleanup(1);
1293 }
1294
1295 /*
1296 * We exclude the worker threads across fork and clone (except
1297 * CLONE_VM), because these system calls only keep the forking thread
1298 * running in the child. Therefore, we don't want to call fork or clone
1299 * in the middle of an tracepoint or ust tracing state modification.
1300 * Holding this mutex protects these structures across fork and clone.
1301 */
1302 void ust_before_fork(sigset_t *save_sigset)
1303 {
1304 /*
1305 * Disable signals. This is to avoid that the child intervenes
1306 * before it is properly setup for tracing. It is safer to
1307 * disable all signals, because then we know we are not breaking
1308 * anything by restoring the original mask.
1309 */
1310 sigset_t all_sigs;
1311 int ret;
1312
1313 if (URCU_TLS(lttng_ust_nest_count))
1314 return;
1315 /* Disable signals */
1316 sigfillset(&all_sigs);
1317 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
1318 if (ret == -1) {
1319 PERROR("sigprocmask");
1320 }
1321 ust_lock();
1322 rcu_bp_before_fork();
1323 }
1324
1325 static void ust_after_fork_common(sigset_t *restore_sigset)
1326 {
1327 int ret;
1328
1329 DBG("process %d", getpid());
1330 ust_unlock();
1331 /* Restore signals */
1332 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
1333 if (ret == -1) {
1334 PERROR("sigprocmask");
1335 }
1336 }
1337
1338 void ust_after_fork_parent(sigset_t *restore_sigset)
1339 {
1340 if (URCU_TLS(lttng_ust_nest_count))
1341 return;
1342 DBG("process %d", getpid());
1343 rcu_bp_after_fork_parent();
1344 /* Release mutexes and reenable signals */
1345 ust_after_fork_common(restore_sigset);
1346 }
1347
1348 /*
1349 * After fork, in the child, we need to cleanup all the leftover state,
1350 * except the worker thread which already magically disappeared thanks
1351 * to the weird Linux fork semantics. After tyding up, we call
1352 * lttng_ust_init() again to start over as a new PID.
1353 *
1354 * This is meant for forks() that have tracing in the child between the
1355 * fork and following exec call (if there is any).
1356 */
1357 void ust_after_fork_child(sigset_t *restore_sigset)
1358 {
1359 if (URCU_TLS(lttng_ust_nest_count))
1360 return;
1361 DBG("process %d", getpid());
1362 /* Release urcu mutexes */
1363 rcu_bp_after_fork_child();
1364 lttng_ust_cleanup(0);
1365 lttng_context_vtid_reset();
1366 /* Release mutexes and reenable signals */
1367 ust_after_fork_common(restore_sigset);
1368 lttng_ust_init();
1369 }
This page took 0.089365 seconds and 4 git commands to generate.