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