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