SoW-2020-0002: Trace Hit Counters
[deliverable/lttng-ust.git] / liblttng-ust / lttng-ust-comm.c
1 /*
2 * SPDX-License-Identifier: LGPL-2.1-only
3 *
4 * Copyright (C) 2011 David Goulet <david.goulet@polymtl.ca>
5 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
6 */
7
8 #define _LGPL_SOURCE
9 #include <stddef.h>
10 #include <stdint.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <sys/mman.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <sys/wait.h>
17 #include <dlfcn.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20 #include <errno.h>
21 #include <pthread.h>
22 #include <semaphore.h>
23 #include <time.h>
24 #include <assert.h>
25 #include <signal.h>
26 #include <limits.h>
27 #include <urcu/uatomic.h>
28 #include "futex.h"
29 #include <urcu/compiler.h>
30 #include <lttng/urcu/urcu-ust.h>
31
32 #include <lttng/align.h>
33 #include <lttng/ust-events.h>
34 #include <lttng/ust-abi.h>
35 #include <lttng/ust.h>
36 #include <lttng/ust-error.h>
37 #include <lttng/ust-ctl.h>
38 #include <urcu/tls-compat.h>
39 #include <ust-comm.h>
40 #include <ust-fd.h>
41 #include <usterr-signal-safe.h>
42 #include <helper.h>
43 #include "tracepoint-internal.h"
44 #include "lttng-tracer-core.h"
45 #include "compat.h"
46 #include "../libringbuffer/rb-init.h"
47 #include "lttng-ust-statedump.h"
48 #include "clock.h"
49 #include "../libringbuffer/getcpu.h"
50 #include "getenv.h"
51 #include "ust-events-internal.h"
52 #include "context-internal.h"
53
54 /* Concatenate lttng ust shared library name with its major version number. */
55 #define LTTNG_UST_LIB_SO_NAME "liblttng-ust.so." __ust_stringify(CONFIG_LTTNG_UST_LIBRARY_VERSION_MAJOR)
56
57 /*
58 * Has lttng ust comm constructor been called ?
59 */
60 static int initialized;
61
62 /*
63 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
64 * Held when handling a command, also held by fork() to deal with
65 * removal of threads, and by exit path.
66 *
67 * The UST lock is the centralized mutex across UST tracing control and
68 * probe registration.
69 *
70 * ust_exit_mutex must never nest in ust_mutex.
71 *
72 * ust_fork_mutex must never nest in ust_mutex.
73 *
74 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
75 * counter lazy initialization called by events within the statedump,
76 * which traces while the ust_mutex is held.
77 *
78 * ust_lock nests within the dynamic loader lock (within glibc) because
79 * it is taken within the library constructor.
80 *
81 * The ust fd tracker lock nests within the ust_mutex.
82 */
83 static pthread_mutex_t ust_mutex = PTHREAD_MUTEX_INITIALIZER;
84
85 /* Allow nesting the ust_mutex within the same thread. */
86 static DEFINE_URCU_TLS(int, ust_mutex_nest);
87
88 /*
89 * ust_exit_mutex protects thread_active variable wrt thread exit. It
90 * cannot be done by ust_mutex because pthread_cancel(), which takes an
91 * internal libc lock, cannot nest within ust_mutex.
92 *
93 * It never nests within a ust_mutex.
94 */
95 static pthread_mutex_t ust_exit_mutex = PTHREAD_MUTEX_INITIALIZER;
96
97 /*
98 * ust_fork_mutex protects base address statedump tracing against forks. It
99 * prevents the dynamic loader lock to be taken (by base address statedump
100 * tracing) while a fork is happening, thus preventing deadlock issues with
101 * the dynamic loader lock.
102 */
103 static pthread_mutex_t ust_fork_mutex = PTHREAD_MUTEX_INITIALIZER;
104
105 /* Should the ust comm thread quit ? */
106 static int lttng_ust_comm_should_quit;
107
108 /*
109 * This variable can be tested by applications to check whether
110 * lttng-ust is loaded. They simply have to define their own
111 * "lttng_ust_loaded" weak symbol, and test it. It is set to 1 by the
112 * library constructor.
113 */
114 int lttng_ust_loaded __attribute__((weak));
115
116 /*
117 * Return 0 on success, -1 if should quit.
118 * The lock is taken in both cases.
119 * Signal-safe.
120 */
121 int ust_lock(void)
122 {
123 sigset_t sig_all_blocked, orig_mask;
124 int ret, oldstate;
125
126 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
127 if (ret) {
128 ERR("pthread_setcancelstate: %s", strerror(ret));
129 }
130 if (oldstate != PTHREAD_CANCEL_ENABLE) {
131 ERR("pthread_setcancelstate: unexpected oldstate");
132 }
133 sigfillset(&sig_all_blocked);
134 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
135 if (ret) {
136 ERR("pthread_sigmask: %s", strerror(ret));
137 }
138 if (!URCU_TLS(ust_mutex_nest)++)
139 pthread_mutex_lock(&ust_mutex);
140 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
141 if (ret) {
142 ERR("pthread_sigmask: %s", strerror(ret));
143 }
144 if (lttng_ust_comm_should_quit) {
145 return -1;
146 } else {
147 return 0;
148 }
149 }
150
151 /*
152 * ust_lock_nocheck() can be used in constructors/destructors, because
153 * they are already nested within the dynamic loader lock, and therefore
154 * have exclusive access against execution of liblttng-ust destructor.
155 * Signal-safe.
156 */
157 void ust_lock_nocheck(void)
158 {
159 sigset_t sig_all_blocked, orig_mask;
160 int ret, oldstate;
161
162 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
163 if (ret) {
164 ERR("pthread_setcancelstate: %s", strerror(ret));
165 }
166 if (oldstate != PTHREAD_CANCEL_ENABLE) {
167 ERR("pthread_setcancelstate: unexpected oldstate");
168 }
169 sigfillset(&sig_all_blocked);
170 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
171 if (ret) {
172 ERR("pthread_sigmask: %s", strerror(ret));
173 }
174 if (!URCU_TLS(ust_mutex_nest)++)
175 pthread_mutex_lock(&ust_mutex);
176 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
177 if (ret) {
178 ERR("pthread_sigmask: %s", strerror(ret));
179 }
180 }
181
182 /*
183 * Signal-safe.
184 */
185 void ust_unlock(void)
186 {
187 sigset_t sig_all_blocked, orig_mask;
188 int ret, oldstate;
189
190 sigfillset(&sig_all_blocked);
191 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
192 if (ret) {
193 ERR("pthread_sigmask: %s", strerror(ret));
194 }
195 if (!--URCU_TLS(ust_mutex_nest))
196 pthread_mutex_unlock(&ust_mutex);
197 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
198 if (ret) {
199 ERR("pthread_sigmask: %s", strerror(ret));
200 }
201 ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
202 if (ret) {
203 ERR("pthread_setcancelstate: %s", strerror(ret));
204 }
205 if (oldstate != PTHREAD_CANCEL_DISABLE) {
206 ERR("pthread_setcancelstate: unexpected oldstate");
207 }
208 }
209
210 /*
211 * Wait for either of these before continuing to the main
212 * program:
213 * - the register_done message from sessiond daemon
214 * (will let the sessiond daemon enable sessions before main
215 * starts.)
216 * - sessiond daemon is not reachable.
217 * - timeout (ensuring applications are resilient to session
218 * daemon problems).
219 */
220 static sem_t constructor_wait;
221 /*
222 * Doing this for both the global and local sessiond.
223 */
224 enum {
225 sem_count_initial_value = 4,
226 };
227
228 static int sem_count = sem_count_initial_value;
229
230 /*
231 * Counting nesting within lttng-ust. Used to ensure that calling fork()
232 * from liblttng-ust does not execute the pre/post fork handlers.
233 */
234 static DEFINE_URCU_TLS(int, lttng_ust_nest_count);
235
236 /*
237 * Info about socket and associated listener thread.
238 */
239 struct sock_info {
240 const char *name;
241 pthread_t ust_listener; /* listener thread */
242 int root_handle;
243 int registration_done;
244 int allowed;
245 int global;
246 int thread_active;
247
248 char sock_path[PATH_MAX];
249 int socket;
250 int notify_socket;
251
252 char wait_shm_path[PATH_MAX];
253 char *wait_shm_mmap;
254 /* Keep track of lazy state dump not performed yet. */
255 int statedump_pending;
256 int initial_statedump_done;
257 /* Keep procname for statedump */
258 char procname[LTTNG_UST_ABI_PROCNAME_LEN];
259 };
260
261 /* Socket from app (connect) to session daemon (listen) for communication */
262 struct sock_info global_apps = {
263 .name = "global",
264 .global = 1,
265
266 .root_handle = -1,
267 .registration_done = 0,
268 .allowed = 0,
269 .thread_active = 0,
270
271 .sock_path = LTTNG_DEFAULT_RUNDIR "/" LTTNG_UST_SOCK_FILENAME,
272 .socket = -1,
273 .notify_socket = -1,
274
275 .wait_shm_path = "/" LTTNG_UST_WAIT_FILENAME,
276
277 .statedump_pending = 0,
278 .initial_statedump_done = 0,
279 .procname[0] = '\0'
280 };
281
282 /* TODO: allow global_apps_sock_path override */
283
284 struct sock_info local_apps = {
285 .name = "local",
286 .global = 0,
287 .root_handle = -1,
288 .registration_done = 0,
289 .allowed = 0, /* Check setuid bit first */
290 .thread_active = 0,
291
292 .socket = -1,
293 .notify_socket = -1,
294
295 .statedump_pending = 0,
296 .initial_statedump_done = 0,
297 .procname[0] = '\0'
298 };
299
300 static int wait_poll_fallback;
301
302 static const char *cmd_name_mapping[] = {
303 [ LTTNG_UST_RELEASE ] = "Release",
304 [ LTTNG_UST_SESSION ] = "Create Session",
305 [ LTTNG_UST_TRACER_VERSION ] = "Get Tracer Version",
306
307 [ LTTNG_UST_TRACEPOINT_LIST ] = "Create Tracepoint List",
308 [ LTTNG_UST_WAIT_QUIESCENT ] = "Wait for Quiescent State",
309 [ LTTNG_UST_REGISTER_DONE ] = "Registration Done",
310 [ LTTNG_UST_TRACEPOINT_FIELD_LIST ] = "Create Tracepoint Field List",
311
312 [ LTTNG_UST_EVENT_NOTIFIER_GROUP_CREATE ] = "Create event notifier group",
313
314 /* Session FD commands */
315 [ LTTNG_UST_CHANNEL ] = "Create Channel",
316 [ LTTNG_UST_SESSION_START ] = "Start Session",
317 [ LTTNG_UST_SESSION_STOP ] = "Stop Session",
318
319 /* Channel FD commands */
320 [ LTTNG_UST_STREAM ] = "Create Stream",
321 [ LTTNG_UST_EVENT ] = "Create Event",
322
323 /* Event and Channel FD commands */
324 [ LTTNG_UST_CONTEXT ] = "Create Context",
325 [ LTTNG_UST_FLUSH_BUFFER ] = "Flush Buffer",
326
327 /* Event, Channel and Session commands */
328 [ LTTNG_UST_ENABLE ] = "Enable",
329 [ LTTNG_UST_DISABLE ] = "Disable",
330
331 /* Tracepoint list commands */
332 [ LTTNG_UST_TRACEPOINT_LIST_GET ] = "List Next Tracepoint",
333 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET ] = "List Next Tracepoint Field",
334
335 /* Event FD commands */
336 [ LTTNG_UST_FILTER ] = "Create Filter",
337 [ LTTNG_UST_EXCLUSION ] = "Add exclusions to event",
338
339 /* Event notifier group commands */
340 [ LTTNG_UST_EVENT_NOTIFIER_CREATE ] = "Create event notifier",
341
342 /* Session and event notifier group commands */
343 [ LTTNG_UST_COUNTER ] = "Create Counter",
344
345 /* Counter commands */
346 [ LTTNG_UST_COUNTER_GLOBAL ] = "Create Counter Global",
347 [ LTTNG_UST_COUNTER_CPU ] = "Create Counter CPU",
348 [ LTTNG_UST_COUNTER_EVENT ] = "Create Counter Event",
349 };
350
351 static const char *str_timeout;
352 static int got_timeout_env;
353
354 extern void lttng_ring_buffer_client_overwrite_init(void);
355 extern void lttng_ring_buffer_client_overwrite_rt_init(void);
356 extern void lttng_ring_buffer_client_discard_init(void);
357 extern void lttng_ring_buffer_client_discard_rt_init(void);
358 extern void lttng_ring_buffer_metadata_client_init(void);
359 extern void lttng_ring_buffer_client_overwrite_exit(void);
360 extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
361 extern void lttng_ring_buffer_client_discard_exit(void);
362 extern void lttng_ring_buffer_client_discard_rt_exit(void);
363 extern void lttng_ring_buffer_metadata_client_exit(void);
364 LTTNG_HIDDEN
365 extern void lttng_counter_client_percpu_32_modular_init(void);
366 LTTNG_HIDDEN
367 extern void lttng_counter_client_percpu_32_modular_exit(void);
368 LTTNG_HIDDEN
369 extern void lttng_counter_client_percpu_64_modular_init(void);
370 LTTNG_HIDDEN
371 extern void lttng_counter_client_percpu_64_modular_exit(void);
372
373 static char *get_map_shm(struct sock_info *sock_info);
374
375 ssize_t lttng_ust_read(int fd, void *buf, size_t len)
376 {
377 ssize_t ret;
378 size_t copied = 0, to_copy = len;
379
380 do {
381 ret = read(fd, buf + copied, to_copy);
382 if (ret > 0) {
383 copied += ret;
384 to_copy -= ret;
385 }
386 } while ((ret > 0 && to_copy > 0)
387 || (ret < 0 && errno == EINTR));
388 if (ret > 0) {
389 ret = copied;
390 }
391 return ret;
392 }
393 /*
394 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
395 * pointer.
396 */
397 static
398 const char *get_lttng_home_dir(void)
399 {
400 const char *val;
401
402 val = (const char *) lttng_getenv("LTTNG_HOME");
403 if (val != NULL) {
404 return val;
405 }
406 return (const char *) lttng_getenv("HOME");
407 }
408
409 /*
410 * Force a read (imply TLS fixup for dlopen) of TLS variables.
411 */
412 static
413 void lttng_fixup_nest_count_tls(void)
414 {
415 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count)));
416 }
417
418 static
419 void lttng_fixup_ust_mutex_nest_tls(void)
420 {
421 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest)));
422 }
423
424 /*
425 * Fixup lttng-ust urcu TLS.
426 */
427 static
428 void lttng_fixup_lttng_ust_urcu_tls(void)
429 {
430 (void) lttng_ust_urcu_read_ongoing();
431 }
432
433 void lttng_ust_fixup_tls(void)
434 {
435 lttng_fixup_lttng_ust_urcu_tls();
436 lttng_fixup_ringbuffer_tls();
437 lttng_fixup_vtid_tls();
438 lttng_fixup_nest_count_tls();
439 lttng_fixup_procname_tls();
440 lttng_fixup_ust_mutex_nest_tls();
441 lttng_ust_fixup_perf_counter_tls();
442 lttng_ust_fixup_fd_tracker_tls();
443 lttng_fixup_cgroup_ns_tls();
444 lttng_fixup_ipc_ns_tls();
445 lttng_fixup_net_ns_tls();
446 lttng_fixup_time_ns_tls();
447 lttng_fixup_uts_ns_tls();
448 }
449
450 int lttng_get_notify_socket(void *owner)
451 {
452 struct sock_info *info = owner;
453
454 return info->notify_socket;
455 }
456
457
458 LTTNG_HIDDEN
459 char* lttng_ust_sockinfo_get_procname(void *owner)
460 {
461 struct sock_info *info = owner;
462
463 return info->procname;
464 }
465
466 static
467 void print_cmd(int cmd, int handle)
468 {
469 const char *cmd_name = "Unknown";
470
471 if (cmd >= 0 && cmd < LTTNG_ARRAY_SIZE(cmd_name_mapping)
472 && cmd_name_mapping[cmd]) {
473 cmd_name = cmd_name_mapping[cmd];
474 }
475 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
476 cmd_name, cmd,
477 lttng_ust_obj_get_name(handle), handle);
478 }
479
480 static
481 int setup_global_apps(void)
482 {
483 int ret = 0;
484 assert(!global_apps.wait_shm_mmap);
485
486 global_apps.wait_shm_mmap = get_map_shm(&global_apps);
487 if (!global_apps.wait_shm_mmap) {
488 WARN("Unable to get map shm for global apps. Disabling LTTng-UST global tracing.");
489 global_apps.allowed = 0;
490 ret = -EIO;
491 goto error;
492 }
493
494 global_apps.allowed = 1;
495 lttng_pthread_getname_np(global_apps.procname, LTTNG_UST_ABI_PROCNAME_LEN);
496 error:
497 return ret;
498 }
499 static
500 int setup_local_apps(void)
501 {
502 int ret = 0;
503 const char *home_dir;
504 uid_t uid;
505
506 assert(!local_apps.wait_shm_mmap);
507
508 uid = getuid();
509 /*
510 * Disallow per-user tracing for setuid binaries.
511 */
512 if (uid != geteuid()) {
513 assert(local_apps.allowed == 0);
514 ret = 0;
515 goto end;
516 }
517 home_dir = get_lttng_home_dir();
518 if (!home_dir) {
519 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
520 assert(local_apps.allowed == 0);
521 ret = -ENOENT;
522 goto end;
523 }
524 local_apps.allowed = 1;
525 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
526 home_dir,
527 LTTNG_DEFAULT_HOME_RUNDIR,
528 LTTNG_UST_SOCK_FILENAME);
529 snprintf(local_apps.wait_shm_path, PATH_MAX, "/%s-%u",
530 LTTNG_UST_WAIT_FILENAME,
531 uid);
532
533 local_apps.wait_shm_mmap = get_map_shm(&local_apps);
534 if (!local_apps.wait_shm_mmap) {
535 WARN("Unable to get map shm for local apps. Disabling LTTng-UST per-user tracing.");
536 local_apps.allowed = 0;
537 ret = -EIO;
538 goto end;
539 }
540
541 lttng_pthread_getname_np(local_apps.procname, LTTNG_UST_ABI_PROCNAME_LEN);
542 end:
543 return ret;
544 }
545
546 /*
547 * Get socket timeout, in ms.
548 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
549 */
550 static
551 long get_timeout(void)
552 {
553 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
554
555 if (!got_timeout_env) {
556 str_timeout = lttng_getenv("LTTNG_UST_REGISTER_TIMEOUT");
557 got_timeout_env = 1;
558 }
559 if (str_timeout)
560 constructor_delay_ms = strtol(str_timeout, NULL, 10);
561 /* All negative values are considered as "-1". */
562 if (constructor_delay_ms < -1)
563 constructor_delay_ms = -1;
564 return constructor_delay_ms;
565 }
566
567 /* Timeout for notify socket send and recv. */
568 static
569 long get_notify_sock_timeout(void)
570 {
571 return get_timeout();
572 }
573
574 /* Timeout for connecting to cmd and notify sockets. */
575 static
576 long get_connect_sock_timeout(void)
577 {
578 return get_timeout();
579 }
580
581 /*
582 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
583 */
584 static
585 int get_constructor_timeout(struct timespec *constructor_timeout)
586 {
587 long constructor_delay_ms;
588 int ret;
589
590 constructor_delay_ms = get_timeout();
591
592 switch (constructor_delay_ms) {
593 case -1:/* fall-through */
594 case 0:
595 return constructor_delay_ms;
596 default:
597 break;
598 }
599
600 /*
601 * If we are unable to find the current time, don't wait.
602 */
603 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
604 if (ret) {
605 /* Don't wait. */
606 return 0;
607 }
608 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
609 constructor_timeout->tv_nsec +=
610 (constructor_delay_ms % 1000UL) * 1000000UL;
611 if (constructor_timeout->tv_nsec >= 1000000000UL) {
612 constructor_timeout->tv_sec++;
613 constructor_timeout->tv_nsec -= 1000000000UL;
614 }
615 /* Timeout wait (constructor_delay_ms). */
616 return 1;
617 }
618
619 static
620 void get_allow_blocking(void)
621 {
622 const char *str_allow_blocking =
623 lttng_getenv("LTTNG_UST_ALLOW_BLOCKING");
624
625 if (str_allow_blocking) {
626 DBG("%s environment variable is set",
627 "LTTNG_UST_ALLOW_BLOCKING");
628 lttng_ust_ringbuffer_set_allow_blocking();
629 }
630 }
631
632 static
633 int register_to_sessiond(int socket, enum ustctl_socket_type type)
634 {
635 return ustcomm_send_reg_msg(socket,
636 type,
637 CAA_BITS_PER_LONG,
638 lttng_alignof(uint8_t) * CHAR_BIT,
639 lttng_alignof(uint16_t) * CHAR_BIT,
640 lttng_alignof(uint32_t) * CHAR_BIT,
641 lttng_alignof(uint64_t) * CHAR_BIT,
642 lttng_alignof(unsigned long) * CHAR_BIT);
643 }
644
645 static
646 int send_reply(int sock, struct ustcomm_ust_reply *lur)
647 {
648 ssize_t len;
649
650 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
651 switch (len) {
652 case sizeof(*lur):
653 DBG("message successfully sent");
654 return 0;
655 default:
656 if (len == -ECONNRESET) {
657 DBG("remote end closed connection");
658 return 0;
659 }
660 if (len < 0)
661 return len;
662 DBG("incorrect message size: %zd", len);
663 return -EINVAL;
664 }
665 }
666
667 static
668 void decrement_sem_count(unsigned int count)
669 {
670 int ret;
671
672 assert(uatomic_read(&sem_count) >= count);
673
674 if (uatomic_read(&sem_count) <= 0) {
675 return;
676 }
677
678 ret = uatomic_add_return(&sem_count, -count);
679 if (ret == 0) {
680 ret = sem_post(&constructor_wait);
681 assert(!ret);
682 }
683 }
684
685 static
686 int handle_register_done(struct sock_info *sock_info)
687 {
688 if (sock_info->registration_done)
689 return 0;
690 sock_info->registration_done = 1;
691
692 decrement_sem_count(1);
693 if (!sock_info->statedump_pending) {
694 sock_info->initial_statedump_done = 1;
695 decrement_sem_count(1);
696 }
697
698 return 0;
699 }
700
701 static
702 int handle_register_failed(struct sock_info *sock_info)
703 {
704 if (sock_info->registration_done)
705 return 0;
706 sock_info->registration_done = 1;
707 sock_info->initial_statedump_done = 1;
708
709 decrement_sem_count(2);
710
711 return 0;
712 }
713
714 /*
715 * Only execute pending statedump after the constructor semaphore has
716 * been posted by the current listener thread. This means statedump will
717 * only be performed after the "registration done" command is received
718 * from this thread's session daemon.
719 *
720 * This ensures we don't run into deadlock issues with the dynamic
721 * loader mutex, which is held while the constructor is called and
722 * waiting on the constructor semaphore. All operations requiring this
723 * dynamic loader lock need to be postponed using this mechanism.
724 *
725 * In a scenario with two session daemons connected to the application,
726 * it is possible that the first listener thread which receives the
727 * registration done command issues its statedump while the dynamic
728 * loader lock is still held by the application constructor waiting on
729 * the semaphore. It will however be allowed to proceed when the
730 * second session daemon sends the registration done command to the
731 * second listener thread. This situation therefore does not produce
732 * a deadlock.
733 */
734 static
735 void handle_pending_statedump(struct sock_info *sock_info)
736 {
737 if (sock_info->registration_done && sock_info->statedump_pending) {
738 sock_info->statedump_pending = 0;
739 pthread_mutex_lock(&ust_fork_mutex);
740 lttng_handle_pending_statedump(sock_info);
741 pthread_mutex_unlock(&ust_fork_mutex);
742
743 if (!sock_info->initial_statedump_done) {
744 sock_info->initial_statedump_done = 1;
745 decrement_sem_count(1);
746 }
747 }
748 }
749
750 static inline
751 const char *bytecode_type_str(uint32_t cmd)
752 {
753 switch (cmd) {
754 case LTTNG_UST_CAPTURE:
755 return "capture";
756 case LTTNG_UST_FILTER:
757 return "filter";
758 default:
759 abort();
760 }
761 }
762
763 static
764 int handle_bytecode_recv(struct sock_info *sock_info,
765 int sock, struct ustcomm_ust_msg *lum)
766 {
767 struct lttng_ust_bytecode_node *bytecode = NULL;
768 enum lttng_ust_bytecode_node_type type;
769 const struct lttng_ust_objd_ops *ops;
770 uint32_t data_size, data_size_max, reloc_offset;
771 uint64_t seqnum;
772 ssize_t len;
773 int ret = 0;
774
775 switch (lum->cmd) {
776 case LTTNG_UST_FILTER:
777 type = LTTNG_UST_BYTECODE_NODE_TYPE_FILTER;
778 data_size = lum->u.filter.data_size;
779 data_size_max = FILTER_BYTECODE_MAX_LEN;
780 reloc_offset = lum->u.filter.reloc_offset;
781 seqnum = lum->u.filter.seqnum;
782 break;
783 case LTTNG_UST_CAPTURE:
784 type = LTTNG_UST_BYTECODE_NODE_TYPE_CAPTURE;
785 data_size = lum->u.capture.data_size;
786 data_size_max = CAPTURE_BYTECODE_MAX_LEN;
787 reloc_offset = lum->u.capture.reloc_offset;
788 seqnum = lum->u.capture.seqnum;
789 break;
790 default:
791 abort();
792 }
793
794 if (data_size > data_size_max) {
795 ERR("Bytecode %s data size is too large: %u bytes",
796 bytecode_type_str(lum->cmd), data_size);
797 ret = -EINVAL;
798 goto end;
799 }
800
801 if (reloc_offset > data_size) {
802 ERR("Bytecode %s reloc offset %u is not within data",
803 bytecode_type_str(lum->cmd), reloc_offset);
804 ret = -EINVAL;
805 goto end;
806 }
807
808 /* Allocate the structure AND the `data[]` field. */
809 bytecode = zmalloc(sizeof(*bytecode) + data_size);
810 if (!bytecode) {
811 ret = -ENOMEM;
812 goto end;
813 }
814
815 bytecode->bc.len = data_size;
816 bytecode->bc.reloc_offset = reloc_offset;
817 bytecode->bc.seqnum = seqnum;
818 bytecode->type = type;
819
820 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data, bytecode->bc.len);
821 switch (len) {
822 case 0: /* orderly shutdown */
823 ret = 0;
824 goto end;
825 default:
826 if (len == bytecode->bc.len) {
827 DBG("Bytecode %s data received",
828 bytecode_type_str(lum->cmd));
829 break;
830 } else if (len < 0) {
831 DBG("Receive failed from lttng-sessiond with errno %d",
832 (int) -len);
833 if (len == -ECONNRESET) {
834 ERR("%s remote end closed connection",
835 sock_info->name);
836 ret = len;
837 goto end;
838 }
839 ret = len;
840 goto end;
841 } else {
842 DBG("Incorrect %s bytecode data message size: %zd",
843 bytecode_type_str(lum->cmd), len);
844 ret = -EINVAL;
845 goto end;
846 }
847 }
848
849 ops = objd_ops(lum->handle);
850 if (!ops) {
851 ret = -ENOENT;
852 goto end;
853 }
854
855 if (ops->cmd)
856 ret = ops->cmd(lum->handle, lum->cmd,
857 (unsigned long) &bytecode,
858 NULL, sock_info);
859 else
860 ret = -ENOSYS;
861
862 end:
863 free(bytecode);
864 return ret;
865 }
866
867 static
868 int handle_message(struct sock_info *sock_info,
869 int sock, struct ustcomm_ust_msg *lum)
870 {
871 int ret = 0;
872 const struct lttng_ust_objd_ops *ops;
873 struct ustcomm_ust_reply lur;
874 union ust_args args;
875 char ctxstr[LTTNG_UST_SYM_NAME_LEN]; /* App context string. */
876 ssize_t len;
877
878 memset(&lur, 0, sizeof(lur));
879
880 if (ust_lock()) {
881 ret = -LTTNG_UST_ERR_EXITING;
882 goto error;
883 }
884
885 ops = objd_ops(lum->handle);
886 if (!ops) {
887 ret = -ENOENT;
888 goto error;
889 }
890
891 switch (lum->cmd) {
892 case LTTNG_UST_REGISTER_DONE:
893 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
894 ret = handle_register_done(sock_info);
895 else
896 ret = -EINVAL;
897 break;
898 case LTTNG_UST_RELEASE:
899 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
900 ret = -EPERM;
901 else
902 ret = lttng_ust_objd_unref(lum->handle, 1);
903 break;
904 case LTTNG_UST_CAPTURE:
905 case LTTNG_UST_FILTER:
906 ret = handle_bytecode_recv(sock_info, sock, lum);
907 if (ret)
908 goto error;
909 break;
910 case LTTNG_UST_EXCLUSION:
911 {
912 /* Receive exclusion names */
913 struct lttng_ust_excluder_node *node;
914 unsigned int count;
915
916 count = lum->u.exclusion.count;
917 if (count == 0) {
918 /* There are no names to read */
919 ret = 0;
920 goto error;
921 }
922 node = zmalloc(sizeof(*node) +
923 count * LTTNG_UST_SYM_NAME_LEN);
924 if (!node) {
925 ret = -ENOMEM;
926 goto error;
927 }
928 node->excluder.count = count;
929 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
930 count * LTTNG_UST_SYM_NAME_LEN);
931 switch (len) {
932 case 0: /* orderly shutdown */
933 ret = 0;
934 free(node);
935 goto error;
936 default:
937 if (len == count * LTTNG_UST_SYM_NAME_LEN) {
938 DBG("Exclusion data received");
939 break;
940 } else if (len < 0) {
941 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
942 if (len == -ECONNRESET) {
943 ERR("%s remote end closed connection", sock_info->name);
944 ret = len;
945 free(node);
946 goto error;
947 }
948 ret = len;
949 free(node);
950 goto error;
951 } else {
952 DBG("Incorrect exclusion data message size: %zd", len);
953 ret = -EINVAL;
954 free(node);
955 goto error;
956 }
957 }
958 if (ops->cmd)
959 ret = ops->cmd(lum->handle, lum->cmd,
960 (unsigned long) &node,
961 &args, sock_info);
962 else
963 ret = -ENOSYS;
964 free(node);
965 break;
966 }
967 case LTTNG_UST_EVENT_NOTIFIER_GROUP_CREATE:
968 {
969 int event_notifier_notif_fd, close_ret;
970
971 len = ustcomm_recv_event_notifier_notif_fd_from_sessiond(sock,
972 &event_notifier_notif_fd);
973 switch (len) {
974 case 0: /* orderly shutdown */
975 ret = 0;
976 goto error;
977 case 1:
978 break;
979 default:
980 if (len < 0) {
981 DBG("Receive failed from lttng-sessiond with errno %d",
982 (int) -len);
983 if (len == -ECONNRESET) {
984 ERR("%s remote end closed connection",
985 sock_info->name);
986 ret = len;
987 goto error;
988 }
989 ret = len;
990 goto error;
991 } else {
992 DBG("Incorrect event notifier fd message size: %zd",
993 len);
994 ret = -EINVAL;
995 goto error;
996 }
997 }
998 args.event_notifier_handle.event_notifier_notif_fd =
999 event_notifier_notif_fd;
1000 if (ops->cmd)
1001 ret = ops->cmd(lum->handle, lum->cmd,
1002 (unsigned long) &lum->u,
1003 &args, sock_info);
1004 else
1005 ret = -ENOSYS;
1006 if (args.event_notifier_handle.event_notifier_notif_fd >= 0) {
1007 lttng_ust_lock_fd_tracker();
1008 close_ret = close(args.event_notifier_handle.event_notifier_notif_fd);
1009 lttng_ust_unlock_fd_tracker();
1010 if (close_ret)
1011 PERROR("close");
1012 }
1013 break;
1014 }
1015 case LTTNG_UST_CHANNEL:
1016 {
1017 void *chan_data;
1018 int wakeup_fd;
1019
1020 len = ustcomm_recv_channel_from_sessiond(sock,
1021 &chan_data, lum->u.channel.len,
1022 &wakeup_fd);
1023 switch (len) {
1024 case 0: /* orderly shutdown */
1025 ret = 0;
1026 goto error;
1027 default:
1028 if (len == lum->u.channel.len) {
1029 DBG("channel data received");
1030 break;
1031 } else if (len < 0) {
1032 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1033 if (len == -ECONNRESET) {
1034 ERR("%s remote end closed connection", sock_info->name);
1035 ret = len;
1036 goto error;
1037 }
1038 ret = len;
1039 goto error;
1040 } else {
1041 DBG("incorrect channel data message size: %zd", len);
1042 ret = -EINVAL;
1043 goto error;
1044 }
1045 }
1046 args.channel.chan_data = chan_data;
1047 args.channel.wakeup_fd = wakeup_fd;
1048 if (ops->cmd)
1049 ret = ops->cmd(lum->handle, lum->cmd,
1050 (unsigned long) &lum->u,
1051 &args, sock_info);
1052 else
1053 ret = -ENOSYS;
1054 if (args.channel.wakeup_fd >= 0) {
1055 int close_ret;
1056
1057 lttng_ust_lock_fd_tracker();
1058 close_ret = close(args.channel.wakeup_fd);
1059 lttng_ust_unlock_fd_tracker();
1060 args.channel.wakeup_fd = -1;
1061 if (close_ret)
1062 PERROR("close");
1063 }
1064 free(args.channel.chan_data);
1065 break;
1066 }
1067 case LTTNG_UST_STREAM:
1068 {
1069 int close_ret;
1070
1071 /* Receive shm_fd, wakeup_fd */
1072 ret = ustcomm_recv_stream_from_sessiond(sock,
1073 NULL,
1074 &args.stream.shm_fd,
1075 &args.stream.wakeup_fd);
1076 if (ret) {
1077 goto error;
1078 }
1079
1080 if (ops->cmd)
1081 ret = ops->cmd(lum->handle, lum->cmd,
1082 (unsigned long) &lum->u,
1083 &args, sock_info);
1084 else
1085 ret = -ENOSYS;
1086 if (args.stream.shm_fd >= 0) {
1087 lttng_ust_lock_fd_tracker();
1088 close_ret = close(args.stream.shm_fd);
1089 lttng_ust_unlock_fd_tracker();
1090 args.stream.shm_fd = -1;
1091 if (close_ret)
1092 PERROR("close");
1093 }
1094 if (args.stream.wakeup_fd >= 0) {
1095 lttng_ust_lock_fd_tracker();
1096 close_ret = close(args.stream.wakeup_fd);
1097 lttng_ust_unlock_fd_tracker();
1098 args.stream.wakeup_fd = -1;
1099 if (close_ret)
1100 PERROR("close");
1101 }
1102 break;
1103 }
1104 case LTTNG_UST_CONTEXT:
1105 switch (lum->u.context.ctx) {
1106 case LTTNG_UST_CONTEXT_APP_CONTEXT:
1107 {
1108 char *p;
1109 size_t ctxlen, recvlen;
1110
1111 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
1112 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
1113 if (ctxlen >= LTTNG_UST_SYM_NAME_LEN) {
1114 ERR("Application context string length size is too large: %zu bytes",
1115 ctxlen);
1116 ret = -EINVAL;
1117 goto error;
1118 }
1119 strcpy(ctxstr, "$app.");
1120 p = &ctxstr[strlen("$app.")];
1121 recvlen = ctxlen - strlen("$app.");
1122 len = ustcomm_recv_unix_sock(sock, p, recvlen);
1123 switch (len) {
1124 case 0: /* orderly shutdown */
1125 ret = 0;
1126 goto error;
1127 default:
1128 if (len == recvlen) {
1129 DBG("app context data received");
1130 break;
1131 } else if (len < 0) {
1132 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1133 if (len == -ECONNRESET) {
1134 ERR("%s remote end closed connection", sock_info->name);
1135 ret = len;
1136 goto error;
1137 }
1138 ret = len;
1139 goto error;
1140 } else {
1141 DBG("incorrect app context data message size: %zd", len);
1142 ret = -EINVAL;
1143 goto error;
1144 }
1145 }
1146 /* Put : between provider and ctxname. */
1147 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
1148 args.app_context.ctxname = ctxstr;
1149 break;
1150 }
1151 default:
1152 break;
1153 }
1154 if (ops->cmd) {
1155 ret = ops->cmd(lum->handle, lum->cmd,
1156 (unsigned long) &lum->u,
1157 &args, sock_info);
1158 } else {
1159 ret = -ENOSYS;
1160 }
1161 break;
1162 case LTTNG_UST_COUNTER:
1163 {
1164 void *counter_data;
1165
1166 len = ustcomm_recv_counter_from_sessiond(sock,
1167 &counter_data, lum->u.counter.len);
1168 switch (len) {
1169 case 0: /* orderly shutdown */
1170 ret = 0;
1171 goto error;
1172 default:
1173 if (len == lum->u.counter.len) {
1174 DBG("counter data received");
1175 break;
1176 } else if (len < 0) {
1177 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1178 if (len == -ECONNRESET) {
1179 ERR("%s remote end closed connection", sock_info->name);
1180 ret = len;
1181 goto error;
1182 }
1183 ret = len;
1184 goto error;
1185 } else {
1186 DBG("incorrect counter data message size: %zd", len);
1187 ret = -EINVAL;
1188 goto error;
1189 }
1190 }
1191 args.counter.counter_data = counter_data;
1192 if (ops->cmd)
1193 ret = ops->cmd(lum->handle, lum->cmd,
1194 (unsigned long) &lum->u,
1195 &args, sock_info);
1196 else
1197 ret = -ENOSYS;
1198 free(args.counter.counter_data);
1199 break;
1200 }
1201 case LTTNG_UST_COUNTER_GLOBAL:
1202 {
1203 /* Receive shm_fd */
1204 ret = ustcomm_recv_counter_shm_from_sessiond(sock,
1205 &args.counter_shm.shm_fd);
1206 if (ret) {
1207 goto error;
1208 }
1209
1210 if (ops->cmd)
1211 ret = ops->cmd(lum->handle, lum->cmd,
1212 (unsigned long) &lum->u,
1213 &args, sock_info);
1214 else
1215 ret = -ENOSYS;
1216 if (args.counter_shm.shm_fd >= 0) {
1217 int close_ret;
1218
1219 lttng_ust_lock_fd_tracker();
1220 close_ret = close(args.counter_shm.shm_fd);
1221 lttng_ust_unlock_fd_tracker();
1222 args.counter_shm.shm_fd = -1;
1223 if (close_ret)
1224 PERROR("close");
1225 }
1226 break;
1227 }
1228 case LTTNG_UST_COUNTER_CPU:
1229 {
1230 /* Receive shm_fd */
1231 ret = ustcomm_recv_counter_shm_from_sessiond(sock,
1232 &args.counter_shm.shm_fd);
1233 if (ret) {
1234 goto error;
1235 }
1236
1237 if (ops->cmd)
1238 ret = ops->cmd(lum->handle, lum->cmd,
1239 (unsigned long) &lum->u,
1240 &args, sock_info);
1241 else
1242 ret = -ENOSYS;
1243 if (args.counter_shm.shm_fd >= 0) {
1244 int close_ret;
1245
1246 lttng_ust_lock_fd_tracker();
1247 close_ret = close(args.counter_shm.shm_fd);
1248 lttng_ust_unlock_fd_tracker();
1249 args.counter_shm.shm_fd = -1;
1250 if (close_ret)
1251 PERROR("close");
1252 }
1253 break;
1254 }
1255 case LTTNG_UST_EVENT_NOTIFIER_CREATE:
1256 {
1257 /* Receive struct lttng_ust_event_notifier */
1258 struct lttng_ust_event_notifier event_notifier;
1259
1260 if (sizeof(event_notifier) != lum->u.event_notifier.len) {
1261 DBG("incorrect event notifier data message size: %u", lum->u.event_notifier.len);
1262 ret = -EINVAL;
1263 goto error;
1264 }
1265 len = ustcomm_recv_unix_sock(sock, &event_notifier, sizeof(event_notifier));
1266 switch (len) {
1267 case 0: /* orderly shutdown */
1268 ret = 0;
1269 goto error;
1270 default:
1271 if (len == sizeof(event_notifier)) {
1272 DBG("event notifier data received");
1273 break;
1274 } else if (len < 0) {
1275 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1276 if (len == -ECONNRESET) {
1277 ERR("%s remote end closed connection", sock_info->name);
1278 ret = len;
1279 goto error;
1280 }
1281 ret = len;
1282 goto error;
1283 } else {
1284 DBG("incorrect event notifier data message size: %zd", len);
1285 ret = -EINVAL;
1286 goto error;
1287 }
1288 }
1289 if (ops->cmd)
1290 ret = ops->cmd(lum->handle, lum->cmd,
1291 (unsigned long) &event_notifier,
1292 &args, sock_info);
1293 else
1294 ret = -ENOSYS;
1295 break;
1296 }
1297 case LTTNG_UST_COUNTER_EVENT:
1298 {
1299 /* Receive struct lttng_ust_counter_event */
1300 struct lttng_ust_counter_event counter_event;
1301
1302 if (sizeof(counter_event) != lum->u.counter_event.len) {
1303 DBG("incorrect counter event data message size: %u", lum->u.counter_event.len);
1304 ret = -EINVAL;
1305 goto error;
1306 }
1307 len = ustcomm_recv_unix_sock(sock, &counter_event, sizeof(counter_event));
1308 switch (len) {
1309 case 0: /* orderly shutdown */
1310 ret = 0;
1311 goto error;
1312 default:
1313 if (len == sizeof(counter_event)) {
1314 DBG("counter event data received");
1315 break;
1316 } else if (len < 0) {
1317 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1318 if (len == -ECONNRESET) {
1319 ERR("%s remote end closed connection", sock_info->name);
1320 ret = len;
1321 goto error;
1322 }
1323 ret = len;
1324 goto error;
1325 } else {
1326 DBG("incorrect event notifier data message size: %zd", len);
1327 ret = -EINVAL;
1328 goto error;
1329 }
1330 }
1331 if (ops->cmd)
1332 ret = ops->cmd(lum->handle, lum->cmd,
1333 (unsigned long) &counter_event,
1334 &args, sock_info);
1335 else
1336 ret = -ENOSYS;
1337 break;
1338 }
1339 default:
1340 if (ops->cmd)
1341 ret = ops->cmd(lum->handle, lum->cmd,
1342 (unsigned long) &lum->u,
1343 &args, sock_info);
1344 else
1345 ret = -ENOSYS;
1346 break;
1347 }
1348
1349 lur.handle = lum->handle;
1350 lur.cmd = lum->cmd;
1351 lur.ret_val = ret;
1352 if (ret >= 0) {
1353 lur.ret_code = LTTNG_UST_OK;
1354 } else {
1355 /*
1356 * Use -LTTNG_UST_ERR as wildcard for UST internal
1357 * error that are not caused by the transport, except if
1358 * we already have a more precise error message to
1359 * report.
1360 */
1361 if (ret > -LTTNG_UST_ERR) {
1362 /* Translate code to UST error. */
1363 switch (ret) {
1364 case -EEXIST:
1365 lur.ret_code = -LTTNG_UST_ERR_EXIST;
1366 break;
1367 case -EINVAL:
1368 lur.ret_code = -LTTNG_UST_ERR_INVAL;
1369 break;
1370 case -ENOENT:
1371 lur.ret_code = -LTTNG_UST_ERR_NOENT;
1372 break;
1373 case -EPERM:
1374 lur.ret_code = -LTTNG_UST_ERR_PERM;
1375 break;
1376 case -ENOSYS:
1377 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
1378 break;
1379 default:
1380 lur.ret_code = -LTTNG_UST_ERR;
1381 break;
1382 }
1383 } else {
1384 lur.ret_code = ret;
1385 }
1386 }
1387 if (ret >= 0) {
1388 switch (lum->cmd) {
1389 case LTTNG_UST_TRACER_VERSION:
1390 lur.u.version = lum->u.version;
1391 break;
1392 case LTTNG_UST_TRACEPOINT_LIST_GET:
1393 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1394 break;
1395 }
1396 }
1397 DBG("Return value: %d", lur.ret_val);
1398
1399 ust_unlock();
1400
1401 /*
1402 * Performed delayed statedump operations outside of the UST
1403 * lock. We need to take the dynamic loader lock before we take
1404 * the UST lock internally within handle_pending_statedump().
1405 */
1406 handle_pending_statedump(sock_info);
1407
1408 if (ust_lock()) {
1409 ret = -LTTNG_UST_ERR_EXITING;
1410 goto error;
1411 }
1412
1413 ret = send_reply(sock, &lur);
1414 if (ret < 0) {
1415 DBG("error sending reply");
1416 goto error;
1417 }
1418
1419 /*
1420 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1421 * after the reply.
1422 */
1423 if (lur.ret_code == LTTNG_UST_OK) {
1424 switch (lum->cmd) {
1425 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
1426 len = ustcomm_send_unix_sock(sock,
1427 &args.field_list.entry,
1428 sizeof(args.field_list.entry));
1429 if (len < 0) {
1430 ret = len;
1431 goto error;
1432 }
1433 if (len != sizeof(args.field_list.entry)) {
1434 ret = -EINVAL;
1435 goto error;
1436 }
1437 }
1438 }
1439
1440 error:
1441 ust_unlock();
1442
1443 return ret;
1444 }
1445
1446 static
1447 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
1448 {
1449 int ret;
1450
1451 if (sock_info->root_handle != -1) {
1452 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1453 if (ret) {
1454 ERR("Error unref root handle");
1455 }
1456 sock_info->root_handle = -1;
1457 }
1458 sock_info->registration_done = 0;
1459 sock_info->initial_statedump_done = 0;
1460
1461 /*
1462 * wait_shm_mmap, socket and notify socket are used by listener
1463 * threads outside of the ust lock, so we cannot tear them down
1464 * ourselves, because we cannot join on these threads. Leave
1465 * responsibility of cleaning up these resources to the OS
1466 * process exit.
1467 */
1468 if (exiting)
1469 return;
1470
1471 if (sock_info->socket != -1) {
1472 ret = ustcomm_close_unix_sock(sock_info->socket);
1473 if (ret) {
1474 ERR("Error closing ust cmd socket");
1475 }
1476 sock_info->socket = -1;
1477 }
1478 if (sock_info->notify_socket != -1) {
1479 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1480 if (ret) {
1481 ERR("Error closing ust notify socket");
1482 }
1483 sock_info->notify_socket = -1;
1484 }
1485 if (sock_info->wait_shm_mmap) {
1486 long page_size;
1487
1488 page_size = LTTNG_UST_PAGE_SIZE;
1489 if (page_size <= 0) {
1490 if (!page_size) {
1491 errno = EINVAL;
1492 }
1493 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1494 } else {
1495 ret = munmap(sock_info->wait_shm_mmap, page_size);
1496 if (ret) {
1497 ERR("Error unmapping wait shm");
1498 }
1499 }
1500 sock_info->wait_shm_mmap = NULL;
1501 }
1502 }
1503
1504 /*
1505 * Using fork to set umask in the child process (not multi-thread safe).
1506 * We deal with the shm_open vs ftruncate race (happening when the
1507 * sessiond owns the shm and does not let everybody modify it, to ensure
1508 * safety against shm_unlink) by simply letting the mmap fail and
1509 * retrying after a few seconds.
1510 * For global shm, everybody has rw access to it until the sessiond
1511 * starts.
1512 */
1513 static
1514 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
1515 {
1516 int wait_shm_fd, ret;
1517 pid_t pid;
1518
1519 /*
1520 * Try to open read-only.
1521 */
1522 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1523 if (wait_shm_fd >= 0) {
1524 int32_t tmp_read;
1525 ssize_t len;
1526 size_t bytes_read = 0;
1527
1528 /*
1529 * Try to read the fd. If unable to do so, try opening
1530 * it in write mode.
1531 */
1532 do {
1533 len = read(wait_shm_fd,
1534 &((char *) &tmp_read)[bytes_read],
1535 sizeof(tmp_read) - bytes_read);
1536 if (len > 0) {
1537 bytes_read += len;
1538 }
1539 } while ((len < 0 && errno == EINTR)
1540 || (len > 0 && bytes_read < sizeof(tmp_read)));
1541 if (bytes_read != sizeof(tmp_read)) {
1542 ret = close(wait_shm_fd);
1543 if (ret) {
1544 ERR("close wait_shm_fd");
1545 }
1546 goto open_write;
1547 }
1548 goto end;
1549 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1550 /*
1551 * Real-only open did not work, and it's not because the
1552 * entry was not present. It's a failure that prohibits
1553 * using shm.
1554 */
1555 ERR("Error opening shm %s", sock_info->wait_shm_path);
1556 goto end;
1557 }
1558
1559 open_write:
1560 /*
1561 * If the open failed because the file did not exist, or because
1562 * the file was not truncated yet, try creating it ourself.
1563 */
1564 URCU_TLS(lttng_ust_nest_count)++;
1565 pid = fork();
1566 URCU_TLS(lttng_ust_nest_count)--;
1567 if (pid > 0) {
1568 int status;
1569
1570 /*
1571 * Parent: wait for child to return, in which case the
1572 * shared memory map will have been created.
1573 */
1574 pid = wait(&status);
1575 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1576 wait_shm_fd = -1;
1577 goto end;
1578 }
1579 /*
1580 * Try to open read-only again after creation.
1581 */
1582 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1583 if (wait_shm_fd < 0) {
1584 /*
1585 * Real-only open did not work. It's a failure
1586 * that prohibits using shm.
1587 */
1588 ERR("Error opening shm %s", sock_info->wait_shm_path);
1589 goto end;
1590 }
1591 goto end;
1592 } else if (pid == 0) {
1593 int create_mode;
1594
1595 /* Child */
1596 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
1597 if (sock_info->global)
1598 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
1599 /*
1600 * We're alone in a child process, so we can modify the
1601 * process-wide umask.
1602 */
1603 umask(~create_mode);
1604 /*
1605 * Try creating shm (or get rw access).
1606 * We don't do an exclusive open, because we allow other
1607 * processes to create+ftruncate it concurrently.
1608 */
1609 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1610 O_RDWR | O_CREAT, create_mode);
1611 if (wait_shm_fd >= 0) {
1612 ret = ftruncate(wait_shm_fd, mmap_size);
1613 if (ret) {
1614 PERROR("ftruncate");
1615 _exit(EXIT_FAILURE);
1616 }
1617 _exit(EXIT_SUCCESS);
1618 }
1619 /*
1620 * For local shm, we need to have rw access to accept
1621 * opening it: this means the local sessiond will be
1622 * able to wake us up. For global shm, we open it even
1623 * if rw access is not granted, because the root.root
1624 * sessiond will be able to override all rights and wake
1625 * us up.
1626 */
1627 if (!sock_info->global && errno != EACCES) {
1628 ERR("Error opening shm %s", sock_info->wait_shm_path);
1629 _exit(EXIT_FAILURE);
1630 }
1631 /*
1632 * The shm exists, but we cannot open it RW. Report
1633 * success.
1634 */
1635 _exit(EXIT_SUCCESS);
1636 } else {
1637 return -1;
1638 }
1639 end:
1640 if (wait_shm_fd >= 0 && !sock_info->global) {
1641 struct stat statbuf;
1642
1643 /*
1644 * Ensure that our user is the owner of the shm file for
1645 * local shm. If we do not own the file, it means our
1646 * sessiond will not have access to wake us up (there is
1647 * probably a rogue process trying to fake our
1648 * sessiond). Fallback to polling method in this case.
1649 */
1650 ret = fstat(wait_shm_fd, &statbuf);
1651 if (ret) {
1652 PERROR("fstat");
1653 goto error_close;
1654 }
1655 if (statbuf.st_uid != getuid())
1656 goto error_close;
1657 }
1658 return wait_shm_fd;
1659
1660 error_close:
1661 ret = close(wait_shm_fd);
1662 if (ret) {
1663 PERROR("Error closing fd");
1664 }
1665 return -1;
1666 }
1667
1668 static
1669 char *get_map_shm(struct sock_info *sock_info)
1670 {
1671 long page_size;
1672 int wait_shm_fd, ret;
1673 char *wait_shm_mmap;
1674
1675 page_size = sysconf(_SC_PAGE_SIZE);
1676 if (page_size <= 0) {
1677 if (!page_size) {
1678 errno = EINVAL;
1679 }
1680 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1681 goto error;
1682 }
1683
1684 lttng_ust_lock_fd_tracker();
1685 wait_shm_fd = get_wait_shm(sock_info, page_size);
1686 if (wait_shm_fd < 0) {
1687 lttng_ust_unlock_fd_tracker();
1688 goto error;
1689 }
1690
1691 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1692 if (ret < 0) {
1693 ret = close(wait_shm_fd);
1694 if (!ret) {
1695 PERROR("Error closing fd");
1696 }
1697 lttng_ust_unlock_fd_tracker();
1698 goto error;
1699 }
1700
1701 wait_shm_fd = ret;
1702 lttng_ust_unlock_fd_tracker();
1703
1704 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
1705 MAP_SHARED, wait_shm_fd, 0);
1706
1707 /* close shm fd immediately after taking the mmap reference */
1708 lttng_ust_lock_fd_tracker();
1709 ret = close(wait_shm_fd);
1710 if (!ret) {
1711 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1712 } else {
1713 PERROR("Error closing fd");
1714 }
1715 lttng_ust_unlock_fd_tracker();
1716
1717 if (wait_shm_mmap == MAP_FAILED) {
1718 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1719 goto error;
1720 }
1721 return wait_shm_mmap;
1722
1723 error:
1724 return NULL;
1725 }
1726
1727 static
1728 void wait_for_sessiond(struct sock_info *sock_info)
1729 {
1730 /* Use ust_lock to check if we should quit. */
1731 if (ust_lock()) {
1732 goto quit;
1733 }
1734 if (wait_poll_fallback) {
1735 goto error;
1736 }
1737 ust_unlock();
1738
1739 assert(sock_info->wait_shm_mmap);
1740
1741 DBG("Waiting for %s apps sessiond", sock_info->name);
1742 /* Wait for futex wakeup */
1743 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1744 goto end_wait;
1745
1746 while (lttng_ust_futex_async((int32_t *) sock_info->wait_shm_mmap,
1747 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1748 switch (errno) {
1749 case EWOULDBLOCK:
1750 /* Value already changed. */
1751 goto end_wait;
1752 case EINTR:
1753 /* Retry if interrupted by signal. */
1754 break; /* Get out of switch. */
1755 case EFAULT:
1756 wait_poll_fallback = 1;
1757 DBG(
1758 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1759 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1760 "Please upgrade your kernel "
1761 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1762 "mainline). LTTng-UST will use polling mode fallback.");
1763 if (ust_debug())
1764 PERROR("futex");
1765 goto end_wait;
1766 }
1767 }
1768 end_wait:
1769 return;
1770
1771 quit:
1772 ust_unlock();
1773 return;
1774
1775 error:
1776 ust_unlock();
1777 return;
1778 }
1779
1780 /*
1781 * This thread does not allocate any resource, except within
1782 * handle_message, within mutex protection. This mutex protects against
1783 * fork and exit.
1784 * The other moment it allocates resources is at socket connection, which
1785 * is also protected by the mutex.
1786 */
1787 static
1788 void *ust_listener_thread(void *arg)
1789 {
1790 struct sock_info *sock_info = arg;
1791 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
1792 long timeout;
1793
1794 lttng_ust_fixup_tls();
1795 /*
1796 * If available, add '-ust' to the end of this thread's
1797 * process name
1798 */
1799 ret = lttng_ust_setustprocname();
1800 if (ret) {
1801 ERR("Unable to set UST process name");
1802 }
1803
1804 /* Restart trying to connect to the session daemon */
1805 restart:
1806 if (prev_connect_failed) {
1807 /* Wait for sessiond availability with pipe */
1808 wait_for_sessiond(sock_info);
1809 if (has_waited) {
1810 has_waited = 0;
1811 /*
1812 * Sleep for 5 seconds before retrying after a
1813 * sequence of failure / wait / failure. This
1814 * deals with a killed or broken session daemon.
1815 */
1816 sleep(5);
1817 } else {
1818 has_waited = 1;
1819 }
1820 prev_connect_failed = 0;
1821 }
1822
1823 if (ust_lock()) {
1824 goto quit;
1825 }
1826
1827 if (sock_info->socket != -1) {
1828 /* FD tracker is updated by ustcomm_close_unix_sock() */
1829 ret = ustcomm_close_unix_sock(sock_info->socket);
1830 if (ret) {
1831 ERR("Error closing %s ust cmd socket",
1832 sock_info->name);
1833 }
1834 sock_info->socket = -1;
1835 }
1836 if (sock_info->notify_socket != -1) {
1837 /* FD tracker is updated by ustcomm_close_unix_sock() */
1838 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1839 if (ret) {
1840 ERR("Error closing %s ust notify socket",
1841 sock_info->name);
1842 }
1843 sock_info->notify_socket = -1;
1844 }
1845
1846
1847 /*
1848 * Register. We need to perform both connect and sending
1849 * registration message before doing the next connect otherwise
1850 * we may reach unix socket connect queue max limits and block
1851 * on the 2nd connect while the session daemon is awaiting the
1852 * first connect registration message.
1853 */
1854 /* Connect cmd socket */
1855 lttng_ust_lock_fd_tracker();
1856 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1857 get_connect_sock_timeout());
1858 if (ret < 0) {
1859 lttng_ust_unlock_fd_tracker();
1860 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1861 prev_connect_failed = 1;
1862
1863 /*
1864 * If we cannot find the sessiond daemon, don't delay
1865 * constructor execution.
1866 */
1867 ret = handle_register_failed(sock_info);
1868 assert(!ret);
1869 ust_unlock();
1870 goto restart;
1871 }
1872 fd = ret;
1873 ret = lttng_ust_add_fd_to_tracker(fd);
1874 if (ret < 0) {
1875 ret = close(fd);
1876 if (ret) {
1877 PERROR("close on sock_info->socket");
1878 }
1879 ret = -1;
1880 lttng_ust_unlock_fd_tracker();
1881 ust_unlock();
1882 goto quit;
1883 }
1884
1885 sock_info->socket = ret;
1886 lttng_ust_unlock_fd_tracker();
1887
1888 ust_unlock();
1889 /*
1890 * Unlock/relock ust lock because connect is blocking (with
1891 * timeout). Don't delay constructors on the ust lock for too
1892 * long.
1893 */
1894 if (ust_lock()) {
1895 goto quit;
1896 }
1897
1898 /*
1899 * Create only one root handle per listener thread for the whole
1900 * process lifetime, so we ensure we get ID which is statically
1901 * assigned to the root handle.
1902 */
1903 if (sock_info->root_handle == -1) {
1904 ret = lttng_abi_create_root_handle();
1905 if (ret < 0) {
1906 ERR("Error creating root handle");
1907 goto quit;
1908 }
1909 sock_info->root_handle = ret;
1910 }
1911
1912 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
1913 if (ret < 0) {
1914 ERR("Error registering to %s ust cmd socket",
1915 sock_info->name);
1916 prev_connect_failed = 1;
1917 /*
1918 * If we cannot register to the sessiond daemon, don't
1919 * delay constructor execution.
1920 */
1921 ret = handle_register_failed(sock_info);
1922 assert(!ret);
1923 ust_unlock();
1924 goto restart;
1925 }
1926
1927 ust_unlock();
1928 /*
1929 * Unlock/relock ust lock because connect is blocking (with
1930 * timeout). Don't delay constructors on the ust lock for too
1931 * long.
1932 */
1933 if (ust_lock()) {
1934 goto quit;
1935 }
1936
1937 /* Connect notify socket */
1938 lttng_ust_lock_fd_tracker();
1939 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1940 get_connect_sock_timeout());
1941 if (ret < 0) {
1942 lttng_ust_unlock_fd_tracker();
1943 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1944 prev_connect_failed = 1;
1945
1946 /*
1947 * If we cannot find the sessiond daemon, don't delay
1948 * constructor execution.
1949 */
1950 ret = handle_register_failed(sock_info);
1951 assert(!ret);
1952 ust_unlock();
1953 goto restart;
1954 }
1955
1956 fd = ret;
1957 ret = lttng_ust_add_fd_to_tracker(fd);
1958 if (ret < 0) {
1959 ret = close(fd);
1960 if (ret) {
1961 PERROR("close on sock_info->notify_socket");
1962 }
1963 ret = -1;
1964 lttng_ust_unlock_fd_tracker();
1965 ust_unlock();
1966 goto quit;
1967 }
1968
1969 sock_info->notify_socket = ret;
1970 lttng_ust_unlock_fd_tracker();
1971
1972 ust_unlock();
1973 /*
1974 * Unlock/relock ust lock because connect is blocking (with
1975 * timeout). Don't delay constructors on the ust lock for too
1976 * long.
1977 */
1978 if (ust_lock()) {
1979 goto quit;
1980 }
1981
1982 timeout = get_notify_sock_timeout();
1983 if (timeout >= 0) {
1984 /*
1985 * Give at least 10ms to sessiond to reply to
1986 * notifications.
1987 */
1988 if (timeout < 10)
1989 timeout = 10;
1990 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1991 timeout);
1992 if (ret < 0) {
1993 WARN("Error setting socket receive timeout");
1994 }
1995 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1996 timeout);
1997 if (ret < 0) {
1998 WARN("Error setting socket send timeout");
1999 }
2000 } else if (timeout < -1) {
2001 WARN("Unsupported timeout value %ld", timeout);
2002 }
2003
2004 ret = register_to_sessiond(sock_info->notify_socket,
2005 USTCTL_SOCKET_NOTIFY);
2006 if (ret < 0) {
2007 ERR("Error registering to %s ust notify socket",
2008 sock_info->name);
2009 prev_connect_failed = 1;
2010 /*
2011 * If we cannot register to the sessiond daemon, don't
2012 * delay constructor execution.
2013 */
2014 ret = handle_register_failed(sock_info);
2015 assert(!ret);
2016 ust_unlock();
2017 goto restart;
2018 }
2019 sock = sock_info->socket;
2020
2021 ust_unlock();
2022
2023 for (;;) {
2024 ssize_t len;
2025 struct ustcomm_ust_msg lum;
2026
2027 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
2028 switch (len) {
2029 case 0: /* orderly shutdown */
2030 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
2031 if (ust_lock()) {
2032 goto quit;
2033 }
2034 /*
2035 * Either sessiond has shutdown or refused us by closing the socket.
2036 * In either case, we don't want to delay construction execution,
2037 * and we need to wait before retry.
2038 */
2039 prev_connect_failed = 1;
2040 /*
2041 * If we cannot register to the sessiond daemon, don't
2042 * delay constructor execution.
2043 */
2044 ret = handle_register_failed(sock_info);
2045 assert(!ret);
2046 ust_unlock();
2047 goto end;
2048 case sizeof(lum):
2049 print_cmd(lum.cmd, lum.handle);
2050 ret = handle_message(sock_info, sock, &lum);
2051 if (ret) {
2052 ERR("Error handling message for %s socket",
2053 sock_info->name);
2054 /*
2055 * Close socket if protocol error is
2056 * detected.
2057 */
2058 goto end;
2059 }
2060 continue;
2061 default:
2062 if (len < 0) {
2063 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
2064 } else {
2065 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
2066 }
2067 if (len == -ECONNRESET) {
2068 DBG("%s remote end closed connection", sock_info->name);
2069 goto end;
2070 }
2071 goto end;
2072 }
2073
2074 }
2075 end:
2076 if (ust_lock()) {
2077 goto quit;
2078 }
2079 /* Cleanup socket handles before trying to reconnect */
2080 lttng_ust_objd_table_owner_cleanup(sock_info);
2081 ust_unlock();
2082 goto restart; /* try to reconnect */
2083
2084 quit:
2085 ust_unlock();
2086
2087 pthread_mutex_lock(&ust_exit_mutex);
2088 sock_info->thread_active = 0;
2089 pthread_mutex_unlock(&ust_exit_mutex);
2090 return NULL;
2091 }
2092
2093 /*
2094 * Weak symbol to call when the ust malloc wrapper is not loaded.
2095 */
2096 __attribute__((weak))
2097 void lttng_ust_malloc_wrapper_init(void)
2098 {
2099 }
2100
2101 /*
2102 * sessiond monitoring thread: monitor presence of global and per-user
2103 * sessiond by polling the application common named pipe.
2104 */
2105 void __attribute__((constructor)) lttng_ust_init(void)
2106 {
2107 struct timespec constructor_timeout;
2108 sigset_t sig_all_blocked, orig_parent_mask;
2109 pthread_attr_t thread_attr;
2110 int timeout_mode;
2111 int ret;
2112 void *handle;
2113
2114 if (uatomic_xchg(&initialized, 1) == 1)
2115 return;
2116
2117 /*
2118 * Fixup interdependency between TLS fixup mutex (which happens
2119 * to be the dynamic linker mutex) and ust_lock, taken within
2120 * the ust lock.
2121 */
2122 lttng_ust_fixup_tls();
2123
2124 lttng_ust_loaded = 1;
2125
2126 /*
2127 * We need to ensure that the liblttng-ust library is not unloaded to avoid
2128 * the unloading of code used by the ust_listener_threads as we can not
2129 * reliably know when they exited. To do that, manually load
2130 * liblttng-ust.so to increment the dynamic loader's internal refcount for
2131 * this library so it never becomes zero, thus never gets unloaded from the
2132 * address space of the process. Since we are already running in the
2133 * constructor of the LTTNG_UST_LIB_SO_NAME library, calling dlopen will
2134 * simply increment the refcount and no additionnal work is needed by the
2135 * dynamic loader as the shared library is already loaded in the address
2136 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
2137 * unloading of the UST library if its refcount becomes zero (which should
2138 * never happen). Do the return value check but discard the handle at the
2139 * end of the function as it's not needed.
2140 */
2141 handle = dlopen(LTTNG_UST_LIB_SO_NAME, RTLD_LAZY | RTLD_NODELETE);
2142 if (!handle) {
2143 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SO_NAME);
2144 }
2145
2146 /*
2147 * We want precise control over the order in which we construct
2148 * our sub-libraries vs starting to receive commands from
2149 * sessiond (otherwise leading to errors when trying to create
2150 * sessiond before the init functions are completed).
2151 */
2152 init_usterr();
2153 lttng_ust_getenv_init(); /* Needs init_usterr() to be completed. */
2154 init_tracepoint();
2155 lttng_ust_init_fd_tracker();
2156 lttng_ust_clock_init();
2157 lttng_ust_getcpu_init();
2158 lttng_ust_statedump_init();
2159 lttng_ring_buffer_metadata_client_init();
2160 lttng_ring_buffer_client_overwrite_init();
2161 lttng_ring_buffer_client_overwrite_rt_init();
2162 lttng_ring_buffer_client_discard_init();
2163 lttng_ring_buffer_client_discard_rt_init();
2164 lttng_counter_client_percpu_32_modular_init();
2165 lttng_counter_client_percpu_64_modular_init();
2166 lttng_perf_counter_init();
2167 /*
2168 * Invoke ust malloc wrapper init before starting other threads.
2169 */
2170 lttng_ust_malloc_wrapper_init();
2171
2172 timeout_mode = get_constructor_timeout(&constructor_timeout);
2173
2174 get_allow_blocking();
2175
2176 ret = sem_init(&constructor_wait, 0, 0);
2177 if (ret) {
2178 PERROR("sem_init");
2179 }
2180
2181 ret = setup_global_apps();
2182 if (ret) {
2183 assert(global_apps.allowed == 0);
2184 DBG("global apps setup returned %d", ret);
2185 }
2186
2187 ret = setup_local_apps();
2188 if (ret) {
2189 assert(local_apps.allowed == 0);
2190 DBG("local apps setup returned %d", ret);
2191 }
2192
2193 /* A new thread created by pthread_create inherits the signal mask
2194 * from the parent. To avoid any signal being received by the
2195 * listener thread, we block all signals temporarily in the parent,
2196 * while we create the listener thread.
2197 */
2198 sigfillset(&sig_all_blocked);
2199 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
2200 if (ret) {
2201 ERR("pthread_sigmask: %s", strerror(ret));
2202 }
2203
2204 ret = pthread_attr_init(&thread_attr);
2205 if (ret) {
2206 ERR("pthread_attr_init: %s", strerror(ret));
2207 }
2208 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
2209 if (ret) {
2210 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
2211 }
2212
2213 if (global_apps.allowed) {
2214 pthread_mutex_lock(&ust_exit_mutex);
2215 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
2216 ust_listener_thread, &global_apps);
2217 if (ret) {
2218 ERR("pthread_create global: %s", strerror(ret));
2219 }
2220 global_apps.thread_active = 1;
2221 pthread_mutex_unlock(&ust_exit_mutex);
2222 } else {
2223 handle_register_done(&global_apps);
2224 }
2225
2226 if (local_apps.allowed) {
2227 pthread_mutex_lock(&ust_exit_mutex);
2228 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
2229 ust_listener_thread, &local_apps);
2230 if (ret) {
2231 ERR("pthread_create local: %s", strerror(ret));
2232 }
2233 local_apps.thread_active = 1;
2234 pthread_mutex_unlock(&ust_exit_mutex);
2235 } else {
2236 handle_register_done(&local_apps);
2237 }
2238 ret = pthread_attr_destroy(&thread_attr);
2239 if (ret) {
2240 ERR("pthread_attr_destroy: %s", strerror(ret));
2241 }
2242
2243 /* Restore original signal mask in parent */
2244 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
2245 if (ret) {
2246 ERR("pthread_sigmask: %s", strerror(ret));
2247 }
2248
2249 switch (timeout_mode) {
2250 case 1: /* timeout wait */
2251 do {
2252 ret = sem_timedwait(&constructor_wait,
2253 &constructor_timeout);
2254 } while (ret < 0 && errno == EINTR);
2255 if (ret < 0) {
2256 switch (errno) {
2257 case ETIMEDOUT:
2258 ERR("Timed out waiting for lttng-sessiond");
2259 break;
2260 case EINVAL:
2261 PERROR("sem_timedwait");
2262 break;
2263 default:
2264 ERR("Unexpected error \"%s\" returned by sem_timedwait",
2265 strerror(errno));
2266 }
2267 }
2268 break;
2269 case -1:/* wait forever */
2270 do {
2271 ret = sem_wait(&constructor_wait);
2272 } while (ret < 0 && errno == EINTR);
2273 if (ret < 0) {
2274 switch (errno) {
2275 case EINVAL:
2276 PERROR("sem_wait");
2277 break;
2278 default:
2279 ERR("Unexpected error \"%s\" returned by sem_wait",
2280 strerror(errno));
2281 }
2282 }
2283 break;
2284 case 0: /* no timeout */
2285 break;
2286 }
2287 }
2288
2289 static
2290 void lttng_ust_cleanup(int exiting)
2291 {
2292 cleanup_sock_info(&global_apps, exiting);
2293 cleanup_sock_info(&local_apps, exiting);
2294 local_apps.allowed = 0;
2295 global_apps.allowed = 0;
2296 /*
2297 * The teardown in this function all affect data structures
2298 * accessed under the UST lock by the listener thread. This
2299 * lock, along with the lttng_ust_comm_should_quit flag, ensure
2300 * that none of these threads are accessing this data at this
2301 * point.
2302 */
2303 lttng_ust_abi_exit();
2304 lttng_ust_events_exit();
2305 lttng_perf_counter_exit();
2306 lttng_ring_buffer_client_discard_rt_exit();
2307 lttng_ring_buffer_client_discard_exit();
2308 lttng_ring_buffer_client_overwrite_rt_exit();
2309 lttng_ring_buffer_client_overwrite_exit();
2310 lttng_ring_buffer_metadata_client_exit();
2311 lttng_counter_client_percpu_32_modular_exit();
2312 lttng_counter_client_percpu_64_modular_exit();
2313 lttng_ust_statedump_destroy();
2314 exit_tracepoint();
2315 if (!exiting) {
2316 /* Reinitialize values for fork */
2317 sem_count = sem_count_initial_value;
2318 lttng_ust_comm_should_quit = 0;
2319 initialized = 0;
2320 }
2321 }
2322
2323 void __attribute__((destructor)) lttng_ust_exit(void)
2324 {
2325 int ret;
2326
2327 /*
2328 * Using pthread_cancel here because:
2329 * A) we don't want to hang application teardown.
2330 * B) the thread is not allocating any resource.
2331 */
2332
2333 /*
2334 * Require the communication thread to quit. Synchronize with
2335 * mutexes to ensure it is not in a mutex critical section when
2336 * pthread_cancel is later called.
2337 */
2338 ust_lock_nocheck();
2339 lttng_ust_comm_should_quit = 1;
2340 ust_unlock();
2341
2342 pthread_mutex_lock(&ust_exit_mutex);
2343 /* cancel threads */
2344 if (global_apps.thread_active) {
2345 ret = pthread_cancel(global_apps.ust_listener);
2346 if (ret) {
2347 ERR("Error cancelling global ust listener thread: %s",
2348 strerror(ret));
2349 } else {
2350 global_apps.thread_active = 0;
2351 }
2352 }
2353 if (local_apps.thread_active) {
2354 ret = pthread_cancel(local_apps.ust_listener);
2355 if (ret) {
2356 ERR("Error cancelling local ust listener thread: %s",
2357 strerror(ret));
2358 } else {
2359 local_apps.thread_active = 0;
2360 }
2361 }
2362 pthread_mutex_unlock(&ust_exit_mutex);
2363
2364 /*
2365 * Do NOT join threads: use of sys_futex makes it impossible to
2366 * join the threads without using async-cancel, but async-cancel
2367 * is delivered by a signal, which could hit the target thread
2368 * anywhere in its code path, including while the ust_lock() is
2369 * held, causing a deadlock for the other thread. Let the OS
2370 * cleanup the threads if there are stalled in a syscall.
2371 */
2372 lttng_ust_cleanup(1);
2373 }
2374
2375 static
2376 void ust_context_ns_reset(void)
2377 {
2378 lttng_context_pid_ns_reset();
2379 lttng_context_cgroup_ns_reset();
2380 lttng_context_ipc_ns_reset();
2381 lttng_context_mnt_ns_reset();
2382 lttng_context_net_ns_reset();
2383 lttng_context_user_ns_reset();
2384 lttng_context_time_ns_reset();
2385 lttng_context_uts_ns_reset();
2386 }
2387
2388 static
2389 void ust_context_vuids_reset(void)
2390 {
2391 lttng_context_vuid_reset();
2392 lttng_context_veuid_reset();
2393 lttng_context_vsuid_reset();
2394 }
2395
2396 static
2397 void ust_context_vgids_reset(void)
2398 {
2399 lttng_context_vgid_reset();
2400 lttng_context_vegid_reset();
2401 lttng_context_vsgid_reset();
2402 }
2403
2404 /*
2405 * We exclude the worker threads across fork and clone (except
2406 * CLONE_VM), because these system calls only keep the forking thread
2407 * running in the child. Therefore, we don't want to call fork or clone
2408 * in the middle of an tracepoint or ust tracing state modification.
2409 * Holding this mutex protects these structures across fork and clone.
2410 */
2411 void ust_before_fork(sigset_t *save_sigset)
2412 {
2413 /*
2414 * Disable signals. This is to avoid that the child intervenes
2415 * before it is properly setup for tracing. It is safer to
2416 * disable all signals, because then we know we are not breaking
2417 * anything by restoring the original mask.
2418 */
2419 sigset_t all_sigs;
2420 int ret;
2421
2422 /* Fixup lttng-ust TLS. */
2423 lttng_ust_fixup_tls();
2424
2425 if (URCU_TLS(lttng_ust_nest_count))
2426 return;
2427 /* Disable signals */
2428 sigfillset(&all_sigs);
2429 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
2430 if (ret == -1) {
2431 PERROR("sigprocmask");
2432 }
2433
2434 pthread_mutex_lock(&ust_fork_mutex);
2435
2436 ust_lock_nocheck();
2437 lttng_ust_urcu_before_fork();
2438 lttng_ust_lock_fd_tracker();
2439 lttng_perf_lock();
2440 }
2441
2442 static void ust_after_fork_common(sigset_t *restore_sigset)
2443 {
2444 int ret;
2445
2446 DBG("process %d", getpid());
2447 lttng_perf_unlock();
2448 lttng_ust_unlock_fd_tracker();
2449 ust_unlock();
2450
2451 pthread_mutex_unlock(&ust_fork_mutex);
2452
2453 /* Restore signals */
2454 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
2455 if (ret == -1) {
2456 PERROR("sigprocmask");
2457 }
2458 }
2459
2460 void ust_after_fork_parent(sigset_t *restore_sigset)
2461 {
2462 if (URCU_TLS(lttng_ust_nest_count))
2463 return;
2464 DBG("process %d", getpid());
2465 lttng_ust_urcu_after_fork_parent();
2466 /* Release mutexes and reenable signals */
2467 ust_after_fork_common(restore_sigset);
2468 }
2469
2470 /*
2471 * After fork, in the child, we need to cleanup all the leftover state,
2472 * except the worker thread which already magically disappeared thanks
2473 * to the weird Linux fork semantics. After tyding up, we call
2474 * lttng_ust_init() again to start over as a new PID.
2475 *
2476 * This is meant for forks() that have tracing in the child between the
2477 * fork and following exec call (if there is any).
2478 */
2479 void ust_after_fork_child(sigset_t *restore_sigset)
2480 {
2481 if (URCU_TLS(lttng_ust_nest_count))
2482 return;
2483 lttng_context_vpid_reset();
2484 lttng_context_vtid_reset();
2485 lttng_context_procname_reset();
2486 ust_context_ns_reset();
2487 ust_context_vuids_reset();
2488 ust_context_vgids_reset();
2489 DBG("process %d", getpid());
2490 /* Release urcu mutexes */
2491 lttng_ust_urcu_after_fork_child();
2492 lttng_ust_cleanup(0);
2493 /* Release mutexes and reenable signals */
2494 ust_after_fork_common(restore_sigset);
2495 lttng_ust_init();
2496 }
2497
2498 void ust_after_setns(void)
2499 {
2500 ust_context_ns_reset();
2501 ust_context_vuids_reset();
2502 ust_context_vgids_reset();
2503 }
2504
2505 void ust_after_unshare(void)
2506 {
2507 ust_context_ns_reset();
2508 ust_context_vuids_reset();
2509 ust_context_vgids_reset();
2510 }
2511
2512 void ust_after_setuid(void)
2513 {
2514 ust_context_vuids_reset();
2515 }
2516
2517 void ust_after_seteuid(void)
2518 {
2519 ust_context_vuids_reset();
2520 }
2521
2522 void ust_after_setreuid(void)
2523 {
2524 ust_context_vuids_reset();
2525 }
2526
2527 void ust_after_setresuid(void)
2528 {
2529 ust_context_vuids_reset();
2530 }
2531
2532 void ust_after_setgid(void)
2533 {
2534 ust_context_vgids_reset();
2535 }
2536
2537 void ust_after_setegid(void)
2538 {
2539 ust_context_vgids_reset();
2540 }
2541
2542 void ust_after_setregid(void)
2543 {
2544 ust_context_vgids_reset();
2545 }
2546
2547 void ust_after_setresgid(void)
2548 {
2549 ust_context_vgids_reset();
2550 }
2551
2552 void lttng_ust_sockinfo_session_enabled(void *owner)
2553 {
2554 struct sock_info *sock_info = owner;
2555 sock_info->statedump_pending = 1;
2556 }
This page took 0.131373 seconds and 5 git commands to generate.