Fix: Block all signals in listener thread
[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 <ust-comm.h>
45 #include <usterr-signal-safe.h>
46 #include "tracepoint-internal.h"
47 #include "ltt-tracer-core.h"
48 #include "compat.h"
49 #include "../libringbuffer/tlsfixup.h"
50
51 /*
52 * Has lttng ust comm constructor been called ?
53 */
54 static int initialized;
55
56 /*
57 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
58 * Held when handling a command, also held by fork() to deal with
59 * removal of threads, and by exit path.
60 */
61
62 /* Should the ust comm thread quit ? */
63 static int lttng_ust_comm_should_quit;
64
65 /*
66 * Wait for either of these before continuing to the main
67 * program:
68 * - the register_done message from sessiond daemon
69 * (will let the sessiond daemon enable sessions before main
70 * starts.)
71 * - sessiond daemon is not reachable.
72 * - timeout (ensuring applications are resilient to session
73 * daemon problems).
74 */
75 static sem_t constructor_wait;
76 /*
77 * Doing this for both the global and local sessiond.
78 */
79 static int sem_count = { 2 };
80
81 /*
82 * Info about socket and associated listener thread.
83 */
84 struct sock_info {
85 const char *name;
86 pthread_t ust_listener; /* listener thread */
87 int root_handle;
88 int constructor_sem_posted;
89 int allowed;
90 int global;
91
92 char sock_path[PATH_MAX];
93 int socket;
94
95 char wait_shm_path[PATH_MAX];
96 char *wait_shm_mmap;
97 };
98
99 /* Socket from app (connect) to session daemon (listen) for communication */
100 struct sock_info global_apps = {
101 .name = "global",
102 .global = 1,
103
104 .root_handle = -1,
105 .allowed = 1,
106
107 .sock_path = DEFAULT_GLOBAL_APPS_UNIX_SOCK,
108 .socket = -1,
109
110 .wait_shm_path = DEFAULT_GLOBAL_APPS_WAIT_SHM_PATH,
111 };
112
113 /* TODO: allow global_apps_sock_path override */
114
115 struct sock_info local_apps = {
116 .name = "local",
117 .global = 0,
118 .root_handle = -1,
119 .allowed = 0, /* Check setuid bit first */
120
121 .socket = -1,
122 };
123
124 static int wait_poll_fallback;
125
126 extern void ltt_ring_buffer_client_overwrite_init(void);
127 extern void ltt_ring_buffer_client_discard_init(void);
128 extern void ltt_ring_buffer_metadata_client_init(void);
129 extern void ltt_ring_buffer_client_overwrite_exit(void);
130 extern void ltt_ring_buffer_client_discard_exit(void);
131 extern void ltt_ring_buffer_metadata_client_exit(void);
132
133 static
134 int setup_local_apps(void)
135 {
136 const char *home_dir;
137 uid_t uid;
138
139 uid = getuid();
140 /*
141 * Disallow per-user tracing for setuid binaries.
142 */
143 if (uid != geteuid()) {
144 local_apps.allowed = 0;
145 return 0;
146 } else {
147 local_apps.allowed = 1;
148 }
149 home_dir = (const char *) getenv("HOME");
150 if (!home_dir)
151 return -ENOENT;
152 snprintf(local_apps.sock_path, PATH_MAX,
153 DEFAULT_HOME_APPS_UNIX_SOCK, home_dir);
154 snprintf(local_apps.wait_shm_path, PATH_MAX,
155 DEFAULT_HOME_APPS_WAIT_SHM_PATH, uid);
156 return 0;
157 }
158
159 static
160 int register_app_to_sessiond(int socket)
161 {
162 ssize_t ret;
163 struct {
164 uint32_t major;
165 uint32_t minor;
166 pid_t pid;
167 pid_t ppid;
168 uid_t uid;
169 gid_t gid;
170 uint32_t bits_per_long;
171 char name[16]; /* process name */
172 } reg_msg;
173
174 reg_msg.major = LTTNG_UST_COMM_VERSION_MAJOR;
175 reg_msg.minor = LTTNG_UST_COMM_VERSION_MINOR;
176 reg_msg.pid = getpid();
177 reg_msg.ppid = getppid();
178 reg_msg.uid = getuid();
179 reg_msg.gid = getgid();
180 reg_msg.bits_per_long = CAA_BITS_PER_LONG;
181 lttng_ust_getprocname(reg_msg.name);
182
183 ret = ustcomm_send_unix_sock(socket, &reg_msg, sizeof(reg_msg));
184 if (ret >= 0 && ret != sizeof(reg_msg))
185 return -EIO;
186 return ret;
187 }
188
189 static
190 int send_reply(int sock, struct ustcomm_ust_reply *lur)
191 {
192 ssize_t len;
193
194 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
195 switch (len) {
196 case sizeof(*lur):
197 DBG("message successfully sent");
198 return 0;
199 case -1:
200 if (errno == ECONNRESET) {
201 printf("remote end closed connection\n");
202 return 0;
203 }
204 return -1;
205 default:
206 printf("incorrect message size: %zd\n", len);
207 return -1;
208 }
209 }
210
211 static
212 int handle_register_done(struct sock_info *sock_info)
213 {
214 int ret;
215
216 if (sock_info->constructor_sem_posted)
217 return 0;
218 sock_info->constructor_sem_posted = 1;
219 if (uatomic_read(&sem_count) <= 0) {
220 return 0;
221 }
222 ret = uatomic_add_return(&sem_count, -1);
223 if (ret == 0) {
224 ret = sem_post(&constructor_wait);
225 assert(!ret);
226 }
227 return 0;
228 }
229
230 static
231 int handle_message(struct sock_info *sock_info,
232 int sock, struct ustcomm_ust_msg *lum)
233 {
234 int ret = 0;
235 const struct lttng_ust_objd_ops *ops;
236 struct ustcomm_ust_reply lur;
237 int shm_fd, wait_fd;
238 union ust_args args;
239
240 ust_lock();
241
242 memset(&lur, 0, sizeof(lur));
243
244 if (lttng_ust_comm_should_quit) {
245 ret = -EPERM;
246 goto end;
247 }
248
249 ops = objd_ops(lum->handle);
250 if (!ops) {
251 ret = -ENOENT;
252 goto end;
253 }
254
255 switch (lum->cmd) {
256 case LTTNG_UST_REGISTER_DONE:
257 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
258 ret = handle_register_done(sock_info);
259 else
260 ret = -EINVAL;
261 break;
262 case LTTNG_UST_RELEASE:
263 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
264 ret = -EPERM;
265 else
266 ret = lttng_ust_objd_unref(lum->handle);
267 break;
268 default:
269 if (ops->cmd)
270 ret = ops->cmd(lum->handle, lum->cmd,
271 (unsigned long) &lum->u,
272 &args);
273 else
274 ret = -ENOSYS;
275 break;
276 }
277
278 end:
279 lur.handle = lum->handle;
280 lur.cmd = lum->cmd;
281 lur.ret_val = ret;
282 if (ret >= 0) {
283 lur.ret_code = USTCOMM_OK;
284 } else {
285 //lur.ret_code = USTCOMM_SESSION_FAIL;
286 lur.ret_code = ret;
287 }
288 if (ret >= 0) {
289 switch (lum->cmd) {
290 case LTTNG_UST_STREAM:
291 /*
292 * Special-case reply to send stream info.
293 * Use lum.u output.
294 */
295 lur.u.stream.memory_map_size = *args.stream.memory_map_size;
296 shm_fd = *args.stream.shm_fd;
297 wait_fd = *args.stream.wait_fd;
298 break;
299 case LTTNG_UST_METADATA:
300 case LTTNG_UST_CHANNEL:
301 lur.u.channel.memory_map_size = *args.channel.memory_map_size;
302 shm_fd = *args.channel.shm_fd;
303 wait_fd = *args.channel.wait_fd;
304 break;
305 case LTTNG_UST_TRACER_VERSION:
306 lur.u.version = lum->u.version;
307 break;
308 case LTTNG_UST_TRACEPOINT_LIST_GET:
309 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
310 break;
311 }
312 }
313 ret = send_reply(sock, &lur);
314 if (ret < 0) {
315 perror("error sending reply");
316 goto error;
317 }
318
319 if ((lum->cmd == LTTNG_UST_STREAM
320 || lum->cmd == LTTNG_UST_CHANNEL
321 || lum->cmd == LTTNG_UST_METADATA)
322 && lur.ret_code == USTCOMM_OK) {
323 int sendret = 0;
324
325 /* we also need to send the file descriptors. */
326 ret = ustcomm_send_fds_unix_sock(sock,
327 &shm_fd, &shm_fd,
328 1, sizeof(int));
329 if (ret < 0) {
330 perror("send shm_fd");
331 sendret = ret;
332 }
333 /*
334 * The sessiond expects 2 file descriptors, even upon
335 * error.
336 */
337 ret = ustcomm_send_fds_unix_sock(sock,
338 &wait_fd, &wait_fd,
339 1, sizeof(int));
340 if (ret < 0) {
341 perror("send wait_fd");
342 goto error;
343 }
344 if (sendret) {
345 ret = sendret;
346 goto error;
347 }
348 }
349 /*
350 * We still have the memory map reference, and the fds have been
351 * sent to the sessiond. We can therefore close those fds. Note
352 * that we keep the write side of the wait_fd open, but close
353 * the read side.
354 */
355 if (lur.ret_code == USTCOMM_OK) {
356 switch (lum->cmd) {
357 case LTTNG_UST_STREAM:
358 if (shm_fd >= 0) {
359 ret = close(shm_fd);
360 if (ret) {
361 PERROR("Error closing stream shm_fd");
362 }
363 *args.stream.shm_fd = -1;
364 }
365 if (wait_fd >= 0) {
366 ret = close(wait_fd);
367 if (ret) {
368 PERROR("Error closing stream wait_fd");
369 }
370 *args.stream.wait_fd = -1;
371 }
372 break;
373 case LTTNG_UST_METADATA:
374 case LTTNG_UST_CHANNEL:
375 if (shm_fd >= 0) {
376 ret = close(shm_fd);
377 if (ret) {
378 PERROR("Error closing channel shm_fd");
379 }
380 *args.channel.shm_fd = -1;
381 }
382 if (wait_fd >= 0) {
383 ret = close(wait_fd);
384 if (ret) {
385 PERROR("Error closing channel wait_fd");
386 }
387 *args.channel.wait_fd = -1;
388 }
389 break;
390 }
391 }
392
393 error:
394 ust_unlock();
395 return ret;
396 }
397
398 static
399 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
400 {
401 int ret;
402
403 if (sock_info->socket != -1) {
404 ret = ustcomm_close_unix_sock(sock_info->socket);
405 if (ret) {
406 ERR("Error closing apps socket");
407 }
408 sock_info->socket = -1;
409 }
410 if (sock_info->root_handle != -1) {
411 ret = lttng_ust_objd_unref(sock_info->root_handle);
412 if (ret) {
413 ERR("Error unref root handle");
414 }
415 sock_info->root_handle = -1;
416 }
417 sock_info->constructor_sem_posted = 0;
418 /*
419 * wait_shm_mmap is used by listener threads outside of the
420 * ust lock, so we cannot tear it down ourselves, because we
421 * cannot join on these threads. Leave this task to the OS
422 * process exit.
423 */
424 if (!exiting && sock_info->wait_shm_mmap) {
425 ret = munmap(sock_info->wait_shm_mmap, sysconf(_SC_PAGE_SIZE));
426 if (ret) {
427 ERR("Error unmapping wait shm");
428 }
429 sock_info->wait_shm_mmap = NULL;
430 }
431 }
432
433 /*
434 * Using fork to set umask in the child process (not multi-thread safe).
435 * We deal with the shm_open vs ftruncate race (happening when the
436 * sessiond owns the shm and does not let everybody modify it, to ensure
437 * safety against shm_unlink) by simply letting the mmap fail and
438 * retrying after a few seconds.
439 * For global shm, everybody has rw access to it until the sessiond
440 * starts.
441 */
442 static
443 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
444 {
445 int wait_shm_fd, ret;
446 pid_t pid;
447
448 /*
449 * Try to open read-only.
450 */
451 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
452 if (wait_shm_fd >= 0) {
453 goto end;
454 } else if (wait_shm_fd < 0 && errno != ENOENT) {
455 /*
456 * Real-only open did not work, and it's not because the
457 * entry was not present. It's a failure that prohibits
458 * using shm.
459 */
460 ERR("Error opening shm %s", sock_info->wait_shm_path);
461 goto end;
462 }
463 /*
464 * If the open failed because the file did not exist, try
465 * creating it ourself.
466 */
467 pid = fork();
468 if (pid > 0) {
469 int status;
470
471 /*
472 * Parent: wait for child to return, in which case the
473 * shared memory map will have been created.
474 */
475 pid = wait(&status);
476 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
477 wait_shm_fd = -1;
478 goto end;
479 }
480 /*
481 * Try to open read-only again after creation.
482 */
483 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
484 if (wait_shm_fd < 0) {
485 /*
486 * Real-only open did not work. It's a failure
487 * that prohibits using shm.
488 */
489 ERR("Error opening shm %s", sock_info->wait_shm_path);
490 goto end;
491 }
492 goto end;
493 } else if (pid == 0) {
494 int create_mode;
495
496 /* Child */
497 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
498 if (sock_info->global)
499 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
500 /*
501 * We're alone in a child process, so we can modify the
502 * process-wide umask.
503 */
504 umask(~create_mode);
505 /*
506 * Try creating shm (or get rw access).
507 * We don't do an exclusive open, because we allow other
508 * processes to create+ftruncate it concurrently.
509 */
510 wait_shm_fd = shm_open(sock_info->wait_shm_path,
511 O_RDWR | O_CREAT, create_mode);
512 if (wait_shm_fd >= 0) {
513 ret = ftruncate(wait_shm_fd, mmap_size);
514 if (ret) {
515 PERROR("ftruncate");
516 exit(EXIT_FAILURE);
517 }
518 exit(EXIT_SUCCESS);
519 }
520 /*
521 * For local shm, we need to have rw access to accept
522 * opening it: this means the local sessiond will be
523 * able to wake us up. For global shm, we open it even
524 * if rw access is not granted, because the root.root
525 * sessiond will be able to override all rights and wake
526 * us up.
527 */
528 if (!sock_info->global && errno != EACCES) {
529 ERR("Error opening shm %s", sock_info->wait_shm_path);
530 exit(EXIT_FAILURE);
531 }
532 /*
533 * The shm exists, but we cannot open it RW. Report
534 * success.
535 */
536 exit(EXIT_SUCCESS);
537 } else {
538 return -1;
539 }
540 end:
541 if (wait_shm_fd >= 0 && !sock_info->global) {
542 struct stat statbuf;
543
544 /*
545 * Ensure that our user is the owner of the shm file for
546 * local shm. If we do not own the file, it means our
547 * sessiond will not have access to wake us up (there is
548 * probably a rogue process trying to fake our
549 * sessiond). Fallback to polling method in this case.
550 */
551 ret = fstat(wait_shm_fd, &statbuf);
552 if (ret) {
553 PERROR("fstat");
554 goto error_close;
555 }
556 if (statbuf.st_uid != getuid())
557 goto error_close;
558 }
559 return wait_shm_fd;
560
561 error_close:
562 ret = close(wait_shm_fd);
563 if (ret) {
564 PERROR("Error closing fd");
565 }
566 return -1;
567 }
568
569 static
570 char *get_map_shm(struct sock_info *sock_info)
571 {
572 size_t mmap_size = sysconf(_SC_PAGE_SIZE);
573 int wait_shm_fd, ret;
574 char *wait_shm_mmap;
575
576 wait_shm_fd = get_wait_shm(sock_info, mmap_size);
577 if (wait_shm_fd < 0) {
578 goto error;
579 }
580 wait_shm_mmap = mmap(NULL, mmap_size, PROT_READ,
581 MAP_SHARED, wait_shm_fd, 0);
582 /* close shm fd immediately after taking the mmap reference */
583 ret = close(wait_shm_fd);
584 if (ret) {
585 PERROR("Error closing fd");
586 }
587 if (wait_shm_mmap == MAP_FAILED) {
588 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
589 goto error;
590 }
591 return wait_shm_mmap;
592
593 error:
594 return NULL;
595 }
596
597 static
598 void wait_for_sessiond(struct sock_info *sock_info)
599 {
600 int ret;
601
602 ust_lock();
603 if (lttng_ust_comm_should_quit) {
604 goto quit;
605 }
606 if (wait_poll_fallback) {
607 goto error;
608 }
609 if (!sock_info->wait_shm_mmap) {
610 sock_info->wait_shm_mmap = get_map_shm(sock_info);
611 if (!sock_info->wait_shm_mmap)
612 goto error;
613 }
614 ust_unlock();
615
616 DBG("Waiting for %s apps sessiond", sock_info->name);
617 /* Wait for futex wakeup */
618 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap) == 0) {
619 ret = futex_async((int32_t *) sock_info->wait_shm_mmap,
620 FUTEX_WAIT, 0, NULL, NULL, 0);
621 if (ret < 0) {
622 if (errno == EFAULT) {
623 wait_poll_fallback = 1;
624 DBG(
625 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
626 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
627 "Please upgrade your kernel "
628 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
629 "mainline). LTTng-UST will use polling mode fallback.");
630 if (ust_debug())
631 PERROR("futex");
632 }
633 }
634 }
635 return;
636
637 quit:
638 ust_unlock();
639 return;
640
641 error:
642 ust_unlock();
643 return;
644 }
645
646 /*
647 * This thread does not allocate any resource, except within
648 * handle_message, within mutex protection. This mutex protects against
649 * fork and exit.
650 * The other moment it allocates resources is at socket connexion, which
651 * is also protected by the mutex.
652 */
653 static
654 void *ust_listener_thread(void *arg)
655 {
656 struct sock_info *sock_info = arg;
657 int sock, ret, prev_connect_failed = 0, has_waited = 0;
658
659 /* Restart trying to connect to the session daemon */
660 restart:
661 if (prev_connect_failed) {
662 /* Wait for sessiond availability with pipe */
663 wait_for_sessiond(sock_info);
664 if (has_waited) {
665 has_waited = 0;
666 /*
667 * Sleep for 5 seconds before retrying after a
668 * sequence of failure / wait / failure. This
669 * deals with a killed or broken session daemon.
670 */
671 sleep(5);
672 }
673 has_waited = 1;
674 prev_connect_failed = 0;
675 }
676 ust_lock();
677
678 if (lttng_ust_comm_should_quit) {
679 ust_unlock();
680 goto quit;
681 }
682
683 if (sock_info->socket != -1) {
684 ret = ustcomm_close_unix_sock(sock_info->socket);
685 if (ret) {
686 ERR("Error closing %s apps socket", sock_info->name);
687 }
688 sock_info->socket = -1;
689 }
690
691 /* Register */
692 ret = ustcomm_connect_unix_sock(sock_info->sock_path);
693 if (ret < 0) {
694 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
695 prev_connect_failed = 1;
696 /*
697 * If we cannot find the sessiond daemon, don't delay
698 * constructor execution.
699 */
700 ret = handle_register_done(sock_info);
701 assert(!ret);
702 ust_unlock();
703 goto restart;
704 }
705
706 sock_info->socket = sock = ret;
707
708 /*
709 * Create only one root handle per listener thread for the whole
710 * process lifetime.
711 */
712 if (sock_info->root_handle == -1) {
713 ret = lttng_abi_create_root_handle();
714 if (ret < 0) {
715 ERR("Error creating root handle");
716 ust_unlock();
717 goto quit;
718 }
719 sock_info->root_handle = ret;
720 }
721
722 ret = register_app_to_sessiond(sock);
723 if (ret < 0) {
724 ERR("Error registering to %s apps socket", sock_info->name);
725 prev_connect_failed = 1;
726 /*
727 * If we cannot register to the sessiond daemon, don't
728 * delay constructor execution.
729 */
730 ret = handle_register_done(sock_info);
731 assert(!ret);
732 ust_unlock();
733 goto restart;
734 }
735 ust_unlock();
736
737 for (;;) {
738 ssize_t len;
739 struct ustcomm_ust_msg lum;
740
741 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
742 switch (len) {
743 case 0: /* orderly shutdown */
744 DBG("%s ltt-sessiond has performed an orderly shutdown\n", sock_info->name);
745 ust_lock();
746 /*
747 * Either sessiond has shutdown or refused us by closing the socket.
748 * In either case, we don't want to delay construction execution,
749 * and we need to wait before retry.
750 */
751 prev_connect_failed = 1;
752 /*
753 * If we cannot register to the sessiond daemon, don't
754 * delay constructor execution.
755 */
756 ret = handle_register_done(sock_info);
757 assert(!ret);
758 ust_unlock();
759 goto end;
760 case sizeof(lum):
761 DBG("message received\n");
762 ret = handle_message(sock_info, sock, &lum);
763 if (ret < 0) {
764 ERR("Error handling message for %s socket", sock_info->name);
765 }
766 continue;
767 case -1:
768 DBG("Receive failed from lttng-sessiond with errno %d", errno);
769 if (errno == ECONNRESET) {
770 ERR("%s remote end closed connection\n", sock_info->name);
771 goto end;
772 }
773 goto end;
774 default:
775 ERR("incorrect message size (%s socket): %zd\n", sock_info->name, len);
776 continue;
777 }
778
779 }
780 end:
781 goto restart; /* try to reconnect */
782 quit:
783 return NULL;
784 }
785
786 /*
787 * Return values: -1: don't wait. 0: wait forever. 1: timeout wait.
788 */
789 static
790 int get_timeout(struct timespec *constructor_timeout)
791 {
792 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
793 char *str_delay;
794 int ret;
795
796 str_delay = getenv("LTTNG_UST_REGISTER_TIMEOUT");
797 if (str_delay) {
798 constructor_delay_ms = strtol(str_delay, NULL, 10);
799 }
800
801 switch (constructor_delay_ms) {
802 case -1:/* fall-through */
803 case 0:
804 return constructor_delay_ms;
805 default:
806 break;
807 }
808
809 /*
810 * If we are unable to find the current time, don't wait.
811 */
812 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
813 if (ret) {
814 return -1;
815 }
816 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
817 constructor_timeout->tv_nsec +=
818 (constructor_delay_ms % 1000UL) * 1000000UL;
819 if (constructor_timeout->tv_nsec >= 1000000000UL) {
820 constructor_timeout->tv_sec++;
821 constructor_timeout->tv_nsec -= 1000000000UL;
822 }
823 return 1;
824 }
825
826 /*
827 * sessiond monitoring thread: monitor presence of global and per-user
828 * sessiond by polling the application common named pipe.
829 */
830 /* TODO */
831
832 void __attribute__((constructor)) lttng_ust_init(void)
833 {
834 struct timespec constructor_timeout;
835 sigset_t sig_all_blocked, orig_parent_mask;
836 int timeout_mode;
837 int ret;
838
839 if (uatomic_xchg(&initialized, 1) == 1)
840 return;
841
842 /*
843 * Fixup interdependency between TLS fixup mutex (which happens
844 * to be the dynamic linker mutex) and ust_lock, taken within
845 * the ust lock.
846 */
847 lttng_fixup_event_tls();
848 lttng_fixup_ringbuffer_tls();
849 lttng_fixup_vtid_tls();
850
851 /*
852 * We want precise control over the order in which we construct
853 * our sub-libraries vs starting to receive commands from
854 * sessiond (otherwise leading to errors when trying to create
855 * sessiond before the init functions are completed).
856 */
857 init_usterr();
858 init_tracepoint();
859 ltt_ring_buffer_metadata_client_init();
860 ltt_ring_buffer_client_overwrite_init();
861 ltt_ring_buffer_client_discard_init();
862
863 timeout_mode = get_timeout(&constructor_timeout);
864
865 ret = sem_init(&constructor_wait, 0, 0);
866 assert(!ret);
867
868 ret = setup_local_apps();
869 if (ret) {
870 ERR("Error setting up to local apps");
871 }
872
873 /* A new thread created by pthread_create inherits the signal mask
874 * from the parent. To avoid any signal being received by the
875 * listener thread, we block all signals temporarily in the parent,
876 * while we create the listener thread.
877 */
878 sigfillset(&sig_all_blocked);
879 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
880 if (ret) {
881 PERROR("pthread_sigmask: %s", strerror(ret));
882 }
883
884 ret = pthread_create(&local_apps.ust_listener, NULL,
885 ust_listener_thread, &local_apps);
886
887 if (local_apps.allowed) {
888 ret = pthread_create(&global_apps.ust_listener, NULL,
889 ust_listener_thread, &global_apps);
890 } else {
891 handle_register_done(&local_apps);
892 }
893
894 /* Restore original signal mask in parent */
895 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
896 if (ret) {
897 PERROR("pthread_sigmask: %s", strerror(ret));
898 }
899
900 switch (timeout_mode) {
901 case 1: /* timeout wait */
902 do {
903 ret = sem_timedwait(&constructor_wait,
904 &constructor_timeout);
905 } while (ret < 0 && errno == EINTR);
906 if (ret < 0 && errno == ETIMEDOUT) {
907 ERR("Timed out waiting for ltt-sessiond");
908 } else {
909 assert(!ret);
910 }
911 break;
912 case -1:/* wait forever */
913 do {
914 ret = sem_wait(&constructor_wait);
915 } while (ret < 0 && errno == EINTR);
916 assert(!ret);
917 break;
918 case 0: /* no timeout */
919 break;
920 }
921 }
922
923 static
924 void lttng_ust_cleanup(int exiting)
925 {
926 cleanup_sock_info(&global_apps, exiting);
927 if (local_apps.allowed) {
928 cleanup_sock_info(&local_apps, exiting);
929 }
930 /*
931 * The teardown in this function all affect data structures
932 * accessed under the UST lock by the listener thread. This
933 * lock, along with the lttng_ust_comm_should_quit flag, ensure
934 * that none of these threads are accessing this data at this
935 * point.
936 */
937 lttng_ust_abi_exit();
938 lttng_ust_events_exit();
939 ltt_ring_buffer_client_discard_exit();
940 ltt_ring_buffer_client_overwrite_exit();
941 ltt_ring_buffer_metadata_client_exit();
942 exit_tracepoint();
943 if (!exiting) {
944 /* Reinitialize values for fork */
945 sem_count = 2;
946 lttng_ust_comm_should_quit = 0;
947 initialized = 0;
948 }
949 }
950
951 void __attribute__((destructor)) lttng_ust_exit(void)
952 {
953 int ret;
954
955 /*
956 * Using pthread_cancel here because:
957 * A) we don't want to hang application teardown.
958 * B) the thread is not allocating any resource.
959 */
960
961 /*
962 * Require the communication thread to quit. Synchronize with
963 * mutexes to ensure it is not in a mutex critical section when
964 * pthread_cancel is later called.
965 */
966 ust_lock();
967 lttng_ust_comm_should_quit = 1;
968 ust_unlock();
969
970 /* cancel threads */
971 ret = pthread_cancel(global_apps.ust_listener);
972 if (ret) {
973 ERR("Error cancelling global ust listener thread");
974 }
975 if (local_apps.allowed) {
976 ret = pthread_cancel(local_apps.ust_listener);
977 if (ret) {
978 ERR("Error cancelling local ust listener thread");
979 }
980 }
981 /*
982 * Do NOT join threads: use of sys_futex makes it impossible to
983 * join the threads without using async-cancel, but async-cancel
984 * is delivered by a signal, which could hit the target thread
985 * anywhere in its code path, including while the ust_lock() is
986 * held, causing a deadlock for the other thread. Let the OS
987 * cleanup the threads if there are stalled in a syscall.
988 */
989 lttng_ust_cleanup(1);
990 }
991
992 /*
993 * We exclude the worker threads across fork and clone (except
994 * CLONE_VM), because these system calls only keep the forking thread
995 * running in the child. Therefore, we don't want to call fork or clone
996 * in the middle of an tracepoint or ust tracing state modification.
997 * Holding this mutex protects these structures across fork and clone.
998 */
999 void ust_before_fork(sigset_t *save_sigset)
1000 {
1001 /*
1002 * Disable signals. This is to avoid that the child intervenes
1003 * before it is properly setup for tracing. It is safer to
1004 * disable all signals, because then we know we are not breaking
1005 * anything by restoring the original mask.
1006 */
1007 sigset_t all_sigs;
1008 int ret;
1009
1010 /* Disable signals */
1011 sigfillset(&all_sigs);
1012 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
1013 if (ret == -1) {
1014 PERROR("sigprocmask");
1015 }
1016 ust_lock();
1017 rcu_bp_before_fork();
1018 }
1019
1020 static void ust_after_fork_common(sigset_t *restore_sigset)
1021 {
1022 int ret;
1023
1024 DBG("process %d", getpid());
1025 ust_unlock();
1026 /* Restore signals */
1027 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
1028 if (ret == -1) {
1029 PERROR("sigprocmask");
1030 }
1031 }
1032
1033 void ust_after_fork_parent(sigset_t *restore_sigset)
1034 {
1035 DBG("process %d", getpid());
1036 rcu_bp_after_fork_parent();
1037 /* Release mutexes and reenable signals */
1038 ust_after_fork_common(restore_sigset);
1039 }
1040
1041 /*
1042 * After fork, in the child, we need to cleanup all the leftover state,
1043 * except the worker thread which already magically disappeared thanks
1044 * to the weird Linux fork semantics. After tyding up, we call
1045 * lttng_ust_init() again to start over as a new PID.
1046 *
1047 * This is meant for forks() that have tracing in the child between the
1048 * fork and following exec call (if there is any).
1049 */
1050 void ust_after_fork_child(sigset_t *restore_sigset)
1051 {
1052 DBG("process %d", getpid());
1053 /* Release urcu mutexes */
1054 rcu_bp_after_fork_child();
1055 lttng_ust_cleanup(0);
1056 lttng_context_vtid_reset();
1057 /* Release mutexes and reenable signals */
1058 ust_after_fork_common(restore_sigset);
1059 lttng_ust_init();
1060 }
This page took 0.050569 seconds and 5 git commands to generate.