2 * SPDX-License-Identifier: LGPL-2.1-only
4 * Copyright (C) 2011 EfficiOS Inc.
5 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
11 #include <sys/types.h>
12 #include <sys/socket.h>
15 #include <sys/types.h>
22 #include <semaphore.h>
27 #include <urcu/uatomic.h>
28 #include <urcu/compiler.h>
29 #include <lttng/urcu/urcu-ust.h>
31 #include <lttng/ust-utils.h>
32 #include <lttng/ust-events.h>
33 #include <lttng/ust-abi.h>
34 #include <lttng/ust-fork.h>
35 #include <lttng/ust-error.h>
36 #include <lttng/ust-ctl.h>
37 #include <lttng/ust-libc-wrapper.h>
38 #include <lttng/ust-thread.h>
39 #include <lttng/ust-tracer.h>
40 #include <lttng/ust-common.h>
41 #include <lttng/ust-cancelstate.h>
42 #include <urcu/tls-compat.h>
43 #include "lib/lttng-ust/futex.h"
44 #include "common/ustcomm.h"
45 #include "common/ust-fd.h"
46 #include "common/logging.h"
47 #include "common/macros.h"
48 #include "common/tracepoint.h"
49 #include "lttng-tracer-core.h"
50 #include "common/compat/pthread.h"
51 #include "common/procname.h"
52 #include "common/ringbuffer/rb-init.h"
53 #include "lttng-ust-statedump.h"
54 #include "common/clock.h"
55 #include "common/getenv.h"
56 #include "lib/lttng-ust/events.h"
57 #include "context-internal.h"
58 #include "common/align.h"
59 #include "common/counter-clients/clients.h"
60 #include "common/ringbuffer-clients/clients.h"
63 * Has lttng ust comm constructor been called ?
65 static int initialized
;
68 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
69 * Held when handling a command, also held by fork() to deal with
70 * removal of threads, and by exit path.
72 * The UST lock is the centralized mutex across UST tracing control and
75 * ust_exit_mutex must never nest in ust_mutex.
77 * ust_fork_mutex must never nest in ust_mutex.
79 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
80 * counter lazy initialization called by events within the statedump,
81 * which traces while the ust_mutex is held.
83 * ust_lock nests within the dynamic loader lock (within glibc) because
84 * it is taken within the library constructor.
86 * The ust fd tracker lock nests within the ust_mutex.
88 static pthread_mutex_t ust_mutex
= PTHREAD_MUTEX_INITIALIZER
;
90 /* Allow nesting the ust_mutex within the same thread. */
91 static DEFINE_URCU_TLS(int, ust_mutex_nest
);
94 * ust_exit_mutex protects thread_active variable wrt thread exit. It
95 * cannot be done by ust_mutex because pthread_cancel(), which takes an
96 * internal libc lock, cannot nest within ust_mutex.
98 * It never nests within a ust_mutex.
100 static pthread_mutex_t ust_exit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
103 * ust_fork_mutex protects base address statedump tracing against forks. It
104 * prevents the dynamic loader lock to be taken (by base address statedump
105 * tracing) while a fork is happening, thus preventing deadlock issues with
106 * the dynamic loader lock.
108 static pthread_mutex_t ust_fork_mutex
= PTHREAD_MUTEX_INITIALIZER
;
110 /* Should the ust comm thread quit ? */
111 static int lttng_ust_comm_should_quit
;
114 * This variable can be tested by applications to check whether
115 * lttng-ust is loaded. They simply have to define their own
116 * "lttng_ust_loaded" weak symbol, and test it. It is set to 1 by the
117 * library constructor.
119 int lttng_ust_loaded
__attribute__((weak
));
122 * Notes on async-signal-safety of ust lock: a few libc functions are used
123 * which are not strictly async-signal-safe:
125 * - pthread_setcancelstate
126 * - pthread_mutex_lock
127 * - pthread_mutex_unlock
129 * As of glibc 2.35, the implementation of pthread_setcancelstate only
130 * touches TLS data, and it appears to be safe to use from signal
131 * handlers. If the libc implementation changes, this will need to be
132 * revisited, and we may ask glibc to provide an async-signal-safe
133 * pthread_setcancelstate.
135 * As of glibc 2.35, the implementation of pthread_mutex_lock/unlock
136 * for fast mutexes only relies on the pthread_mutex_t structure.
137 * Disabling signals around all uses of this mutex ensures
138 * signal-safety. If the libc implementation changes and eventually uses
139 * other global resources, this will need to be revisited and we may
140 * need to implement our own mutex.
144 * Return 0 on success, -1 if should quit.
145 * The lock is taken in both cases.
150 sigset_t sig_all_blocked
, orig_mask
;
153 if (lttng_ust_cancelstate_disable_push()) {
154 ERR("lttng_ust_cancelstate_disable_push");
156 sigfillset(&sig_all_blocked
);
157 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
159 ERR("pthread_sigmask: ret=%d", ret
);
161 if (!URCU_TLS(ust_mutex_nest
)++)
162 pthread_mutex_lock(&ust_mutex
);
163 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
165 ERR("pthread_sigmask: ret=%d", ret
);
167 if (lttng_ust_comm_should_quit
) {
175 * ust_lock_nocheck() can be used in constructors/destructors, because
176 * they are already nested within the dynamic loader lock, and therefore
177 * have exclusive access against execution of liblttng-ust destructor.
180 void ust_lock_nocheck(void)
182 sigset_t sig_all_blocked
, orig_mask
;
185 if (lttng_ust_cancelstate_disable_push()) {
186 ERR("lttng_ust_cancelstate_disable_push");
188 sigfillset(&sig_all_blocked
);
189 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
191 ERR("pthread_sigmask: ret=%d", ret
);
193 if (!URCU_TLS(ust_mutex_nest
)++)
194 pthread_mutex_lock(&ust_mutex
);
195 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
197 ERR("pthread_sigmask: ret=%d", ret
);
204 void ust_unlock(void)
206 sigset_t sig_all_blocked
, orig_mask
;
209 sigfillset(&sig_all_blocked
);
210 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
212 ERR("pthread_sigmask: ret=%d", ret
);
214 if (!--URCU_TLS(ust_mutex_nest
))
215 pthread_mutex_unlock(&ust_mutex
);
216 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
218 ERR("pthread_sigmask: ret=%d", ret
);
220 if (lttng_ust_cancelstate_disable_pop()) {
221 ERR("lttng_ust_cancelstate_disable_pop");
226 * Wait for either of these before continuing to the main
228 * - the register_done message from sessiond daemon
229 * (will let the sessiond daemon enable sessions before main
231 * - sessiond daemon is not reachable.
232 * - timeout (ensuring applications are resilient to session
235 static sem_t constructor_wait
;
237 * Doing this for both the global and local sessiond.
240 sem_count_initial_value
= 4,
243 static int sem_count
= sem_count_initial_value
;
246 * Counting nesting within lttng-ust. Used to ensure that calling fork()
247 * from liblttng-ust does not execute the pre/post fork handlers.
249 static DEFINE_URCU_TLS(int, lttng_ust_nest_count
);
252 * Info about socket and associated listener thread.
256 pthread_t ust_listener
; /* listener thread */
258 int registration_done
;
263 char sock_path
[PATH_MAX
];
267 char wait_shm_path
[PATH_MAX
];
269 /* Keep track of lazy state dump not performed yet. */
270 int statedump_pending
;
271 int initial_statedump_done
;
272 /* Keep procname for statedump */
273 char procname
[LTTNG_UST_CONTEXT_PROCNAME_LEN
];
276 /* Socket from app (connect) to session daemon (listen) for communication */
277 static struct sock_info global_apps
= {
282 .registration_done
= 0,
286 .sock_path
= LTTNG_DEFAULT_RUNDIR
"/" LTTNG_UST_SOCK_FILENAME
,
290 .wait_shm_path
= "/" LTTNG_UST_WAIT_FILENAME
,
292 .statedump_pending
= 0,
293 .initial_statedump_done
= 0,
297 /* TODO: allow global_apps_sock_path override */
299 static struct sock_info local_apps
= {
303 .registration_done
= 0,
304 .allowed
= 0, /* Check setuid bit first */
310 .statedump_pending
= 0,
311 .initial_statedump_done
= 0,
315 static int wait_poll_fallback
;
317 static const char *cmd_name_mapping
[] = {
318 [ LTTNG_UST_ABI_RELEASE
] = "Release",
319 [ LTTNG_UST_ABI_SESSION
] = "Create Session",
320 [ LTTNG_UST_ABI_TRACER_VERSION
] = "Get Tracer Version",
322 [ LTTNG_UST_ABI_TRACEPOINT_LIST
] = "Create Tracepoint List",
323 [ LTTNG_UST_ABI_WAIT_QUIESCENT
] = "Wait for Quiescent State",
324 [ LTTNG_UST_ABI_REGISTER_DONE
] = "Registration Done",
325 [ LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST
] = "Create Tracepoint Field List",
327 [ LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
] = "Create event notifier group",
329 /* Session FD commands */
330 [ LTTNG_UST_ABI_CHANNEL
] = "Create Channel",
331 [ LTTNG_UST_ABI_SESSION_START
] = "Start Session",
332 [ LTTNG_UST_ABI_SESSION_STOP
] = "Stop Session",
334 /* Channel FD commands */
335 [ LTTNG_UST_ABI_STREAM
] = "Create Stream",
336 [ LTTNG_UST_ABI_EVENT
] = "Create Event",
338 /* Event and Channel FD commands */
339 [ LTTNG_UST_ABI_CONTEXT
] = "Create Context",
340 [ LTTNG_UST_ABI_FLUSH_BUFFER
] = "Flush Buffer",
342 /* Event, Channel and Session commands */
343 [ LTTNG_UST_ABI_ENABLE
] = "Enable",
344 [ LTTNG_UST_ABI_DISABLE
] = "Disable",
346 /* Tracepoint list commands */
347 [ LTTNG_UST_ABI_TRACEPOINT_LIST_GET
] = "List Next Tracepoint",
348 [ LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET
] = "List Next Tracepoint Field",
350 /* Event FD commands */
351 [ LTTNG_UST_ABI_FILTER
] = "Create Filter",
352 [ LTTNG_UST_ABI_EXCLUSION
] = "Add exclusions to event",
354 /* Event notifier group commands */
355 [ LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
] = "Create event notifier",
357 /* Session and event notifier group commands */
358 [ LTTNG_UST_ABI_COUNTER
] = "Create Counter",
360 /* Counter commands */
361 [ LTTNG_UST_ABI_COUNTER_GLOBAL
] = "Create Counter Global",
362 [ LTTNG_UST_ABI_COUNTER_CPU
] = "Create Counter CPU",
365 static const char *str_timeout
;
366 static int got_timeout_env
;
368 static char *get_map_shm(struct sock_info
*sock_info
);
371 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
373 * The following env are checked in order of priority:
379 const char *get_lttng_home_dir(void)
383 val
= (const char *) lttng_ust_getenv("LTTNG_UST_HOME");
388 val
= (const char *) lttng_ust_getenv("LTTNG_HOME");
393 return (const char *) lttng_ust_getenv("HOME");
397 * Force a read (imply TLS allocation for dlopen) of TLS variables.
400 void lttng_ust_nest_count_alloc_tls(void)
402 __asm__
__volatile__ ("" : : "m" (URCU_TLS(lttng_ust_nest_count
)));
406 void lttng_ust_mutex_nest_alloc_tls(void)
408 __asm__
__volatile__ ("" : : "m" (URCU_TLS(ust_mutex_nest
)));
412 * Allocate lttng-ust urcu TLS.
415 void lttng_ust_urcu_alloc_tls(void)
417 (void) lttng_ust_urcu_read_ongoing();
420 void lttng_ust_common_init_thread(int flags
)
422 lttng_ust_urcu_alloc_tls();
423 lttng_ringbuffer_alloc_tls();
424 lttng_ust_vtid_init_thread(flags
);
425 lttng_ust_nest_count_alloc_tls();
426 lttng_ust_procname_init_thread(flags
);
427 lttng_ust_mutex_nest_alloc_tls();
428 lttng_ust_perf_counter_init_thread(flags
);
429 lttng_ust_common_alloc_tls();
430 lttng_ust_cgroup_ns_init_thread(flags
);
431 lttng_ust_ipc_ns_init_thread(flags
);
432 lttng_ust_net_ns_init_thread(flags
);
433 lttng_ust_time_ns_init_thread(flags
);
434 lttng_ust_uts_ns_init_thread(flags
);
435 lttng_ust_ring_buffer_client_discard_alloc_tls();
436 lttng_ust_ring_buffer_client_discard_rt_alloc_tls();
437 lttng_ust_ring_buffer_client_overwrite_alloc_tls();
438 lttng_ust_ring_buffer_client_overwrite_rt_alloc_tls();
442 * LTTng-UST uses Global Dynamic model TLS variables rather than IE
443 * model because many versions of glibc don't preallocate a pool large
444 * enough for TLS variables IE model defined in other shared libraries,
445 * and causes issues when using LTTng-UST for Java tracing.
447 * Because of this use of Global Dynamic TLS variables, users wishing to
448 * trace from signal handlers need to explicitly trigger the lazy
449 * allocation of those variables for each thread before using them.
450 * This can be triggered by calling lttng_ust_init_thread().
452 void lttng_ust_init_thread(void)
455 * Because those TLS variables are global dynamic, we need to
456 * ensure those are initialized before a signal handler nesting over
457 * this thread attempts to use them.
459 lttng_ust_common_init_thread(LTTNG_UST_INIT_THREAD_MASK
);
461 lttng_ust_urcu_register_thread();
464 int lttng_get_notify_socket(void *owner
)
466 struct sock_info
*info
= owner
;
468 return info
->notify_socket
;
472 char* lttng_ust_sockinfo_get_procname(void *owner
)
474 struct sock_info
*info
= owner
;
476 return info
->procname
;
480 void print_cmd(int cmd
, int handle
)
482 const char *cmd_name
= "Unknown";
484 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
485 && cmd_name_mapping
[cmd
]) {
486 cmd_name
= cmd_name_mapping
[cmd
];
488 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
490 lttng_ust_obj_get_name(handle
), handle
);
494 int setup_global_apps(void)
497 assert(!global_apps
.wait_shm_mmap
);
499 global_apps
.wait_shm_mmap
= get_map_shm(&global_apps
);
500 if (!global_apps
.wait_shm_mmap
) {
501 WARN("Unable to get map shm for global apps. Disabling LTTng-UST global tracing.");
502 global_apps
.allowed
= 0;
507 global_apps
.allowed
= 1;
508 lttng_pthread_getname_np(global_apps
.procname
, LTTNG_UST_CONTEXT_PROCNAME_LEN
);
513 int setup_local_apps(void)
516 const char *home_dir
;
519 assert(!local_apps
.wait_shm_mmap
);
523 * Disallow per-user tracing for setuid binaries.
525 if (uid
!= geteuid()) {
526 assert(local_apps
.allowed
== 0);
530 home_dir
= get_lttng_home_dir();
532 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
533 assert(local_apps
.allowed
== 0);
537 local_apps
.allowed
= 1;
538 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
540 LTTNG_DEFAULT_HOME_RUNDIR
,
541 LTTNG_UST_SOCK_FILENAME
);
542 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
543 LTTNG_UST_WAIT_FILENAME
,
546 local_apps
.wait_shm_mmap
= get_map_shm(&local_apps
);
547 if (!local_apps
.wait_shm_mmap
) {
548 WARN("Unable to get map shm for local apps. Disabling LTTng-UST per-user tracing.");
549 local_apps
.allowed
= 0;
554 lttng_pthread_getname_np(local_apps
.procname
, LTTNG_UST_CONTEXT_PROCNAME_LEN
);
560 * Get socket timeout, in ms.
561 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
564 long get_timeout(void)
566 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
568 if (!got_timeout_env
) {
569 str_timeout
= lttng_ust_getenv("LTTNG_UST_REGISTER_TIMEOUT");
573 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
574 /* All negative values are considered as "-1". */
575 if (constructor_delay_ms
< -1)
576 constructor_delay_ms
= -1;
577 return constructor_delay_ms
;
580 /* Timeout for notify socket send and recv. */
582 long get_notify_sock_timeout(void)
584 return get_timeout();
587 /* Timeout for connecting to cmd and notify sockets. */
589 long get_connect_sock_timeout(void)
591 return get_timeout();
595 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
598 int get_constructor_timeout(struct timespec
*constructor_timeout
)
600 long constructor_delay_ms
;
603 constructor_delay_ms
= get_timeout();
605 switch (constructor_delay_ms
) {
606 case -1:/* fall-through */
608 return constructor_delay_ms
;
614 * If we are unable to find the current time, don't wait.
616 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
621 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
622 constructor_timeout
->tv_nsec
+=
623 (constructor_delay_ms
% 1000UL) * 1000000UL;
624 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
625 constructor_timeout
->tv_sec
++;
626 constructor_timeout
->tv_nsec
-= 1000000000UL;
628 /* Timeout wait (constructor_delay_ms). */
633 void get_allow_blocking(void)
635 const char *str_allow_blocking
=
636 lttng_ust_getenv("LTTNG_UST_ALLOW_BLOCKING");
638 if (str_allow_blocking
) {
639 DBG("%s environment variable is set",
640 "LTTNG_UST_ALLOW_BLOCKING");
641 lttng_ust_ringbuffer_set_allow_blocking();
646 int register_to_sessiond(int socket
, enum lttng_ust_ctl_socket_type type
,
647 const char *procname
)
649 return ustcomm_send_reg_msg(socket
,
652 lttng_ust_rb_alignof(uint8_t) * CHAR_BIT
,
653 lttng_ust_rb_alignof(uint16_t) * CHAR_BIT
,
654 lttng_ust_rb_alignof(uint32_t) * CHAR_BIT
,
655 lttng_ust_rb_alignof(uint64_t) * CHAR_BIT
,
656 lttng_ust_rb_alignof(unsigned long) * CHAR_BIT
,
661 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
665 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
668 DBG("message successfully sent");
671 if (len
== -ECONNRESET
) {
672 DBG("remote end closed connection");
677 DBG("incorrect message size: %zd", len
);
683 void decrement_sem_count(unsigned int count
)
687 assert(uatomic_read(&sem_count
) >= count
);
689 if (uatomic_read(&sem_count
) <= 0) {
693 ret
= uatomic_add_return(&sem_count
, -count
);
695 ret
= sem_post(&constructor_wait
);
701 int handle_register_done(struct sock_info
*sock_info
)
703 if (sock_info
->registration_done
)
705 sock_info
->registration_done
= 1;
707 decrement_sem_count(1);
708 if (!sock_info
->statedump_pending
) {
709 sock_info
->initial_statedump_done
= 1;
710 decrement_sem_count(1);
717 int handle_register_failed(struct sock_info
*sock_info
)
719 if (sock_info
->registration_done
)
721 sock_info
->registration_done
= 1;
722 sock_info
->initial_statedump_done
= 1;
724 decrement_sem_count(2);
730 * Only execute pending statedump after the constructor semaphore has
731 * been posted by the current listener thread. This means statedump will
732 * only be performed after the "registration done" command is received
733 * from this thread's session daemon.
735 * This ensures we don't run into deadlock issues with the dynamic
736 * loader mutex, which is held while the constructor is called and
737 * waiting on the constructor semaphore. All operations requiring this
738 * dynamic loader lock need to be postponed using this mechanism.
740 * In a scenario with two session daemons connected to the application,
741 * it is possible that the first listener thread which receives the
742 * registration done command issues its statedump while the dynamic
743 * loader lock is still held by the application constructor waiting on
744 * the semaphore. It will however be allowed to proceed when the
745 * second session daemon sends the registration done command to the
746 * second listener thread. This situation therefore does not produce
750 void handle_pending_statedump(struct sock_info
*sock_info
)
752 if (sock_info
->registration_done
&& sock_info
->statedump_pending
) {
753 sock_info
->statedump_pending
= 0;
754 pthread_mutex_lock(&ust_fork_mutex
);
755 lttng_handle_pending_statedump(sock_info
);
756 pthread_mutex_unlock(&ust_fork_mutex
);
758 if (!sock_info
->initial_statedump_done
) {
759 sock_info
->initial_statedump_done
= 1;
760 decrement_sem_count(1);
766 const char *bytecode_type_str(uint32_t cmd
)
769 case LTTNG_UST_ABI_CAPTURE
:
771 case LTTNG_UST_ABI_FILTER
:
779 int handle_bytecode_recv(struct sock_info
*sock_info
,
780 int sock
, struct ustcomm_ust_msg
*lum
)
782 struct lttng_ust_bytecode_node
*bytecode
= NULL
;
783 enum lttng_ust_bytecode_type type
;
784 const struct lttng_ust_abi_objd_ops
*ops
;
785 uint32_t data_size
, data_size_max
, reloc_offset
;
791 case LTTNG_UST_ABI_FILTER
:
792 type
= LTTNG_UST_BYTECODE_TYPE_FILTER
;
793 data_size
= lum
->u
.filter
.data_size
;
794 data_size_max
= LTTNG_UST_ABI_FILTER_BYTECODE_MAX_LEN
;
795 reloc_offset
= lum
->u
.filter
.reloc_offset
;
796 seqnum
= lum
->u
.filter
.seqnum
;
798 case LTTNG_UST_ABI_CAPTURE
:
799 type
= LTTNG_UST_BYTECODE_TYPE_CAPTURE
;
800 data_size
= lum
->u
.capture
.data_size
;
801 data_size_max
= LTTNG_UST_ABI_CAPTURE_BYTECODE_MAX_LEN
;
802 reloc_offset
= lum
->u
.capture
.reloc_offset
;
803 seqnum
= lum
->u
.capture
.seqnum
;
809 if (data_size
> data_size_max
) {
810 ERR("Bytecode %s data size is too large: %u bytes",
811 bytecode_type_str(lum
->cmd
), data_size
);
816 if (reloc_offset
> data_size
) {
817 ERR("Bytecode %s reloc offset %u is not within data",
818 bytecode_type_str(lum
->cmd
), reloc_offset
);
823 /* Allocate the structure AND the `data[]` field. */
824 bytecode
= zmalloc(sizeof(*bytecode
) + data_size
);
830 bytecode
->bc
.len
= data_size
;
831 bytecode
->bc
.reloc_offset
= reloc_offset
;
832 bytecode
->bc
.seqnum
= seqnum
;
833 bytecode
->type
= type
;
835 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
, bytecode
->bc
.len
);
837 case 0: /* orderly shutdown */
841 if (len
== bytecode
->bc
.len
) {
842 DBG("Bytecode %s data received",
843 bytecode_type_str(lum
->cmd
));
845 } else if (len
< 0) {
846 DBG("Receive failed from lttng-sessiond with errno %d",
848 if (len
== -ECONNRESET
) {
849 ERR("%s remote end closed connection",
857 DBG("Incorrect %s bytecode data message size: %zd",
858 bytecode_type_str(lum
->cmd
), len
);
864 ops
= lttng_ust_abi_objd_ops(lum
->handle
);
871 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
872 (unsigned long) &bytecode
,
883 void prepare_cmd_reply(struct ustcomm_ust_reply
*lur
, uint32_t handle
, uint32_t cmd
, int ret
)
885 lur
->handle
= handle
;
889 lur
->ret_code
= LTTNG_UST_OK
;
892 * Use -LTTNG_UST_ERR as wildcard for UST internal
893 * error that are not caused by the transport, except if
894 * we already have a more precise error message to
897 if (ret
> -LTTNG_UST_ERR
) {
898 /* Translate code to UST error. */
901 lur
->ret_code
= -LTTNG_UST_ERR_EXIST
;
904 lur
->ret_code
= -LTTNG_UST_ERR_INVAL
;
907 lur
->ret_code
= -LTTNG_UST_ERR_NOENT
;
910 lur
->ret_code
= -LTTNG_UST_ERR_PERM
;
913 lur
->ret_code
= -LTTNG_UST_ERR_NOSYS
;
916 lur
->ret_code
= -LTTNG_UST_ERR
;
926 int handle_message(struct sock_info
*sock_info
,
927 int sock
, struct ustcomm_ust_msg
*lum
)
930 const struct lttng_ust_abi_objd_ops
*ops
;
931 struct ustcomm_ust_reply lur
;
932 union lttng_ust_abi_args args
;
933 char ctxstr
[LTTNG_UST_ABI_SYM_NAME_LEN
]; /* App context string. */
936 memset(&lur
, 0, sizeof(lur
));
939 ret
= -LTTNG_UST_ERR_EXITING
;
943 ops
= lttng_ust_abi_objd_ops(lum
->handle
);
950 case LTTNG_UST_ABI_FILTER
:
951 case LTTNG_UST_ABI_EXCLUSION
:
952 case LTTNG_UST_ABI_CHANNEL
:
953 case LTTNG_UST_ABI_STREAM
:
954 case LTTNG_UST_ABI_CONTEXT
:
956 * Those commands send additional payload after struct
957 * ustcomm_ust_msg, which makes it pretty much impossible to
958 * deal with "unknown command" errors without leaving the
959 * communication pipe in a out-of-sync state. This is part of
960 * the ABI between liblttng-ust-ctl and liblttng-ust, and
961 * should be fixed on the next breaking
962 * LTTNG_UST_ABI_MAJOR_VERSION protocol bump by indicating the
963 * total command message length as part of a message header so
964 * that the protocol can recover from invalid command errors.
968 case LTTNG_UST_ABI_CAPTURE
:
969 case LTTNG_UST_ABI_COUNTER
:
970 case LTTNG_UST_ABI_COUNTER_GLOBAL
:
971 case LTTNG_UST_ABI_COUNTER_CPU
:
972 case LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
:
973 case LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
:
975 * Those commands expect a reply to the struct ustcomm_ust_msg
976 * before sending additional payload.
978 prepare_cmd_reply(&lur
, lum
->handle
, lum
->cmd
, 0);
980 ret
= send_reply(sock
, &lur
);
982 DBG("error sending reply");
989 * Other commands either don't send additional payload, or are
996 case LTTNG_UST_ABI_REGISTER_DONE
:
997 if (lum
->handle
== LTTNG_UST_ABI_ROOT_HANDLE
)
998 ret
= handle_register_done(sock_info
);
1002 case LTTNG_UST_ABI_RELEASE
:
1003 if (lum
->handle
== LTTNG_UST_ABI_ROOT_HANDLE
)
1006 ret
= lttng_ust_abi_objd_unref(lum
->handle
, 1);
1008 case LTTNG_UST_ABI_CAPTURE
:
1009 case LTTNG_UST_ABI_FILTER
:
1010 ret
= handle_bytecode_recv(sock_info
, sock
, lum
);
1014 case LTTNG_UST_ABI_EXCLUSION
:
1016 /* Receive exclusion names */
1017 struct lttng_ust_excluder_node
*node
;
1020 count
= lum
->u
.exclusion
.count
;
1022 /* There are no names to read */
1026 node
= zmalloc(sizeof(*node
) +
1027 count
* LTTNG_UST_ABI_SYM_NAME_LEN
);
1032 node
->excluder
.count
= count
;
1033 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
1034 count
* LTTNG_UST_ABI_SYM_NAME_LEN
);
1036 case 0: /* orderly shutdown */
1041 if (len
== count
* LTTNG_UST_ABI_SYM_NAME_LEN
) {
1042 DBG("Exclusion data received");
1044 } else if (len
< 0) {
1045 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1046 if (len
== -ECONNRESET
) {
1047 ERR("%s remote end closed connection", sock_info
->name
);
1056 DBG("Incorrect exclusion data message size: %zd", len
);
1063 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1064 (unsigned long) &node
,
1071 case LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
:
1073 int event_notifier_notif_fd
, close_ret
;
1075 len
= ustcomm_recv_event_notifier_notif_fd_from_sessiond(sock
,
1076 &event_notifier_notif_fd
);
1078 case 0: /* orderly shutdown */
1085 DBG("Receive failed from lttng-sessiond with errno %d",
1087 if (len
== -ECONNRESET
) {
1088 ERR("%s remote end closed connection",
1096 DBG("Incorrect event notifier fd message size: %zd",
1102 args
.event_notifier_handle
.event_notifier_notif_fd
=
1103 event_notifier_notif_fd
;
1105 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1106 (unsigned long) &lum
->u
,
1110 if (args
.event_notifier_handle
.event_notifier_notif_fd
>= 0) {
1111 lttng_ust_lock_fd_tracker();
1112 close_ret
= close(args
.event_notifier_handle
.event_notifier_notif_fd
);
1113 lttng_ust_unlock_fd_tracker();
1119 case LTTNG_UST_ABI_CHANNEL
:
1124 len
= ustcomm_recv_channel_from_sessiond(sock
,
1125 &chan_data
, lum
->u
.channel
.len
,
1128 case 0: /* orderly shutdown */
1132 if (len
== lum
->u
.channel
.len
) {
1133 DBG("channel data received");
1135 } else if (len
< 0) {
1136 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1137 if (len
== -ECONNRESET
) {
1138 ERR("%s remote end closed connection", sock_info
->name
);
1145 DBG("incorrect channel data message size: %zd", len
);
1150 args
.channel
.chan_data
= chan_data
;
1151 args
.channel
.wakeup_fd
= wakeup_fd
;
1153 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1154 (unsigned long) &lum
->u
,
1158 if (args
.channel
.wakeup_fd
>= 0) {
1161 lttng_ust_lock_fd_tracker();
1162 close_ret
= close(args
.channel
.wakeup_fd
);
1163 lttng_ust_unlock_fd_tracker();
1164 args
.channel
.wakeup_fd
= -1;
1168 free(args
.channel
.chan_data
);
1171 case LTTNG_UST_ABI_STREAM
:
1175 /* Receive shm_fd, wakeup_fd */
1176 ret
= ustcomm_recv_stream_from_sessiond(sock
,
1178 &args
.stream
.shm_fd
,
1179 &args
.stream
.wakeup_fd
);
1185 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1186 (unsigned long) &lum
->u
,
1190 if (args
.stream
.shm_fd
>= 0) {
1191 lttng_ust_lock_fd_tracker();
1192 close_ret
= close(args
.stream
.shm_fd
);
1193 lttng_ust_unlock_fd_tracker();
1194 args
.stream
.shm_fd
= -1;
1198 if (args
.stream
.wakeup_fd
>= 0) {
1199 lttng_ust_lock_fd_tracker();
1200 close_ret
= close(args
.stream
.wakeup_fd
);
1201 lttng_ust_unlock_fd_tracker();
1202 args
.stream
.wakeup_fd
= -1;
1208 case LTTNG_UST_ABI_CONTEXT
:
1209 switch (lum
->u
.context
.ctx
) {
1210 case LTTNG_UST_ABI_CONTEXT_APP_CONTEXT
:
1213 size_t ctxlen
, recvlen
;
1215 ctxlen
= strlen("$app.") + lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1
1216 + strlen(":") + lum
->u
.context
.u
.app_ctx
.ctx_name_len
;
1217 if (ctxlen
>= LTTNG_UST_ABI_SYM_NAME_LEN
) {
1218 ERR("Application context string length size is too large: %zu bytes",
1223 strcpy(ctxstr
, "$app.");
1224 p
= &ctxstr
[strlen("$app.")];
1225 recvlen
= ctxlen
- strlen("$app.");
1226 len
= ustcomm_recv_unix_sock(sock
, p
, recvlen
);
1228 case 0: /* orderly shutdown */
1232 if (len
== recvlen
) {
1233 DBG("app context data received");
1235 } else if (len
< 0) {
1236 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1237 if (len
== -ECONNRESET
) {
1238 ERR("%s remote end closed connection", sock_info
->name
);
1245 DBG("incorrect app context data message size: %zd", len
);
1250 /* Put : between provider and ctxname. */
1251 p
[lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1] = ':';
1252 args
.app_context
.ctxname
= ctxstr
;
1259 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1260 (unsigned long) &lum
->u
,
1266 case LTTNG_UST_ABI_COUNTER
:
1270 len
= ustcomm_recv_counter_from_sessiond(sock
,
1271 &counter_data
, lum
->u
.counter
.len
);
1273 case 0: /* orderly shutdown */
1277 if (len
== lum
->u
.counter
.len
) {
1278 DBG("counter data received");
1280 } else if (len
< 0) {
1281 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1282 if (len
== -ECONNRESET
) {
1283 ERR("%s remote end closed connection", sock_info
->name
);
1290 DBG("incorrect counter data message size: %zd", len
);
1295 args
.counter
.counter_data
= counter_data
;
1297 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1298 (unsigned long) &lum
->u
,
1302 free(args
.counter
.counter_data
);
1305 case LTTNG_UST_ABI_COUNTER_GLOBAL
:
1307 /* Receive shm_fd */
1308 ret
= ustcomm_recv_counter_shm_from_sessiond(sock
,
1309 &args
.counter_shm
.shm_fd
);
1315 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1316 (unsigned long) &lum
->u
,
1320 if (args
.counter_shm
.shm_fd
>= 0) {
1323 lttng_ust_lock_fd_tracker();
1324 close_ret
= close(args
.counter_shm
.shm_fd
);
1325 lttng_ust_unlock_fd_tracker();
1326 args
.counter_shm
.shm_fd
= -1;
1332 case LTTNG_UST_ABI_COUNTER_CPU
:
1334 /* Receive shm_fd */
1335 ret
= ustcomm_recv_counter_shm_from_sessiond(sock
,
1336 &args
.counter_shm
.shm_fd
);
1342 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1343 (unsigned long) &lum
->u
,
1347 if (args
.counter_shm
.shm_fd
>= 0) {
1350 lttng_ust_lock_fd_tracker();
1351 close_ret
= close(args
.counter_shm
.shm_fd
);
1352 lttng_ust_unlock_fd_tracker();
1353 args
.counter_shm
.shm_fd
= -1;
1359 case LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
:
1361 /* Receive struct lttng_ust_event_notifier */
1362 struct lttng_ust_abi_event_notifier event_notifier
;
1364 if (sizeof(event_notifier
) != lum
->u
.event_notifier
.len
) {
1365 DBG("incorrect event notifier data message size: %u", lum
->u
.event_notifier
.len
);
1369 len
= ustcomm_recv_unix_sock(sock
, &event_notifier
, sizeof(event_notifier
));
1371 case 0: /* orderly shutdown */
1375 if (len
== sizeof(event_notifier
)) {
1376 DBG("event notifier data received");
1378 } else if (len
< 0) {
1379 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1380 if (len
== -ECONNRESET
) {
1381 ERR("%s remote end closed connection", sock_info
->name
);
1388 DBG("incorrect event notifier data message size: %zd", len
);
1394 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1395 (unsigned long) &event_notifier
,
1404 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1405 (unsigned long) &lum
->u
,
1412 prepare_cmd_reply(&lur
, lum
->handle
, lum
->cmd
, ret
);
1416 case LTTNG_UST_ABI_TRACER_VERSION
:
1417 lur
.u
.version
= lum
->u
.version
;
1419 case LTTNG_UST_ABI_TRACEPOINT_LIST_GET
:
1420 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
1424 DBG("Return value: %d", lur
.ret_val
);
1429 * Performed delayed statedump operations outside of the UST
1430 * lock. We need to take the dynamic loader lock before we take
1431 * the UST lock internally within handle_pending_statedump().
1433 handle_pending_statedump(sock_info
);
1436 ret
= -LTTNG_UST_ERR_EXITING
;
1440 ret
= send_reply(sock
, &lur
);
1442 DBG("error sending reply");
1447 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1450 if (lur
.ret_code
== LTTNG_UST_OK
) {
1452 case LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET
:
1453 len
= ustcomm_send_unix_sock(sock
,
1454 &args
.field_list
.entry
,
1455 sizeof(args
.field_list
.entry
));
1460 if (len
!= sizeof(args
.field_list
.entry
)) {
1474 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
1478 if (sock_info
->root_handle
!= -1) {
1479 ret
= lttng_ust_abi_objd_unref(sock_info
->root_handle
, 1);
1481 ERR("Error unref root handle");
1483 sock_info
->root_handle
= -1;
1488 * wait_shm_mmap, socket and notify socket are used by listener
1489 * threads outside of the ust lock, so we cannot tear them down
1490 * ourselves, because we cannot join on these threads. Leave
1491 * responsibility of cleaning up these resources to the OS
1497 sock_info
->registration_done
= 0;
1498 sock_info
->initial_statedump_done
= 0;
1500 if (sock_info
->socket
!= -1) {
1501 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1503 ERR("Error closing ust cmd socket");
1505 sock_info
->socket
= -1;
1507 if (sock_info
->notify_socket
!= -1) {
1508 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1510 ERR("Error closing ust notify socket");
1512 sock_info
->notify_socket
= -1;
1514 if (sock_info
->wait_shm_mmap
) {
1517 page_size
= LTTNG_UST_PAGE_SIZE
;
1518 if (page_size
<= 0) {
1522 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1524 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
1526 ERR("Error unmapping wait shm");
1529 sock_info
->wait_shm_mmap
= NULL
;
1534 * Using fork to set umask in the child process (not multi-thread safe).
1535 * We deal with the shm_open vs ftruncate race (happening when the
1536 * sessiond owns the shm and does not let everybody modify it, to ensure
1537 * safety against shm_unlink) by simply letting the mmap fail and
1538 * retrying after a few seconds.
1539 * For global shm, everybody has rw access to it until the sessiond
1543 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
1545 int wait_shm_fd
, ret
;
1549 * Try to open read-only.
1551 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1552 if (wait_shm_fd
>= 0) {
1555 size_t bytes_read
= 0;
1558 * Try to read the fd. If unable to do so, try opening
1562 len
= read(wait_shm_fd
,
1563 &((char *) &tmp_read
)[bytes_read
],
1564 sizeof(tmp_read
) - bytes_read
);
1568 } while ((len
< 0 && errno
== EINTR
)
1569 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
1570 if (bytes_read
!= sizeof(tmp_read
)) {
1571 ret
= close(wait_shm_fd
);
1573 ERR("close wait_shm_fd");
1578 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
1580 * Real-only open did not work, and it's not because the
1581 * entry was not present. It's a failure that prohibits
1584 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1590 * If the open failed because the file did not exist, or because
1591 * the file was not truncated yet, try creating it ourself.
1593 URCU_TLS(lttng_ust_nest_count
)++;
1595 URCU_TLS(lttng_ust_nest_count
)--;
1597 int status
, wait_ret
;
1600 * Parent: wait for child to return, in which case the
1601 * shared memory map will have been created.
1603 wait_ret
= waitpid(pid
, &status
, 0);
1604 if (wait_ret
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
1609 * Try to open read-only again after creation.
1611 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1612 if (wait_shm_fd
< 0) {
1614 * Real-only open did not work. It's a failure
1615 * that prohibits using shm.
1617 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1621 } else if (pid
== 0) {
1625 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
1626 if (sock_info
->global
)
1627 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
1629 * We're alone in a child process, so we can modify the
1630 * process-wide umask.
1632 umask(~create_mode
);
1634 * Try creating shm (or get rw access).
1635 * We don't do an exclusive open, because we allow other
1636 * processes to create+ftruncate it concurrently.
1638 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
1639 O_RDWR
| O_CREAT
, create_mode
);
1640 if (wait_shm_fd
>= 0) {
1641 ret
= ftruncate(wait_shm_fd
, mmap_size
);
1643 PERROR("ftruncate");
1644 _exit(EXIT_FAILURE
);
1646 _exit(EXIT_SUCCESS
);
1649 * For local shm, we need to have rw access to accept
1650 * opening it: this means the local sessiond will be
1651 * able to wake us up. For global shm, we open it even
1652 * if rw access is not granted, because the root.root
1653 * sessiond will be able to override all rights and wake
1656 if (!sock_info
->global
&& errno
!= EACCES
) {
1657 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1658 _exit(EXIT_FAILURE
);
1661 * The shm exists, but we cannot open it RW. Report
1664 _exit(EXIT_SUCCESS
);
1669 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
1670 struct stat statbuf
;
1673 * Ensure that our user is the owner of the shm file for
1674 * local shm. If we do not own the file, it means our
1675 * sessiond will not have access to wake us up (there is
1676 * probably a rogue process trying to fake our
1677 * sessiond). Fallback to polling method in this case.
1679 ret
= fstat(wait_shm_fd
, &statbuf
);
1684 if (statbuf
.st_uid
!= getuid())
1690 ret
= close(wait_shm_fd
);
1692 PERROR("Error closing fd");
1698 char *get_map_shm(struct sock_info
*sock_info
)
1701 int wait_shm_fd
, ret
;
1702 char *wait_shm_mmap
;
1704 page_size
= sysconf(_SC_PAGE_SIZE
);
1705 if (page_size
<= 0) {
1709 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1713 lttng_ust_lock_fd_tracker();
1714 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1715 if (wait_shm_fd
< 0) {
1716 lttng_ust_unlock_fd_tracker();
1720 ret
= lttng_ust_add_fd_to_tracker(wait_shm_fd
);
1722 ret
= close(wait_shm_fd
);
1724 PERROR("Error closing fd");
1726 lttng_ust_unlock_fd_tracker();
1731 lttng_ust_unlock_fd_tracker();
1733 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1734 MAP_SHARED
, wait_shm_fd
, 0);
1736 /* close shm fd immediately after taking the mmap reference */
1737 lttng_ust_lock_fd_tracker();
1738 ret
= close(wait_shm_fd
);
1740 lttng_ust_delete_fd_from_tracker(wait_shm_fd
);
1742 PERROR("Error closing fd");
1744 lttng_ust_unlock_fd_tracker();
1746 if (wait_shm_mmap
== MAP_FAILED
) {
1747 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1750 return wait_shm_mmap
;
1757 void wait_for_sessiond(struct sock_info
*sock_info
)
1759 /* Use ust_lock to check if we should quit. */
1763 if (wait_poll_fallback
) {
1768 assert(sock_info
->wait_shm_mmap
);
1770 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1771 /* Wait for futex wakeup */
1772 while (!uatomic_read((int32_t *) sock_info
->wait_shm_mmap
)) {
1773 if (!lttng_ust_futex_async((int32_t *) sock_info
->wait_shm_mmap
, FUTEX_WAIT
, 0, NULL
, NULL
, 0)) {
1775 * Prior queued wakeups queued by unrelated code
1776 * using the same address can cause futex wait to
1777 * return 0 even through the futex value is still
1778 * 0 (spurious wakeups). Check the value again
1779 * in user-space to validate whether it really
1786 /* Value already changed. */
1789 /* Retry if interrupted by signal. */
1790 break; /* Get out of switch. Check again. */
1792 wait_poll_fallback
= 1;
1794 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1795 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1796 "Please upgrade your kernel "
1797 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1798 "mainline). LTTng-UST will use polling mode fallback.");
1799 if (lttng_ust_logging_debug_enabled())
1817 * This thread does not allocate any resource, except within
1818 * handle_message, within mutex protection. This mutex protects against
1820 * The other moment it allocates resources is at socket connection, which
1821 * is also protected by the mutex.
1824 void *ust_listener_thread(void *arg
)
1826 struct sock_info
*sock_info
= arg
;
1827 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0, fd
;
1830 lttng_ust_common_init_thread(0);
1832 * If available, add '-ust' to the end of this thread's
1835 ret
= lttng_ust_setustprocname();
1837 ERR("Unable to set UST process name");
1840 /* Restart trying to connect to the session daemon */
1842 if (prev_connect_failed
) {
1843 /* Wait for sessiond availability with pipe */
1844 wait_for_sessiond(sock_info
);
1848 * Sleep for 5 seconds before retrying after a
1849 * sequence of failure / wait / failure. This
1850 * deals with a killed or broken session daemon.
1856 prev_connect_failed
= 0;
1863 if (sock_info
->socket
!= -1) {
1864 /* FD tracker is updated by ustcomm_close_unix_sock() */
1865 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1867 ERR("Error closing %s ust cmd socket",
1870 sock_info
->socket
= -1;
1872 if (sock_info
->notify_socket
!= -1) {
1873 /* FD tracker is updated by ustcomm_close_unix_sock() */
1874 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1876 ERR("Error closing %s ust notify socket",
1879 sock_info
->notify_socket
= -1;
1884 * Register. We need to perform both connect and sending
1885 * registration message before doing the next connect otherwise
1886 * we may reach unix socket connect queue max limits and block
1887 * on the 2nd connect while the session daemon is awaiting the
1888 * first connect registration message.
1890 /* Connect cmd socket */
1891 lttng_ust_lock_fd_tracker();
1892 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
,
1893 get_connect_sock_timeout());
1895 lttng_ust_unlock_fd_tracker();
1896 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1897 prev_connect_failed
= 1;
1900 * If we cannot find the sessiond daemon, don't delay
1901 * constructor execution.
1903 ret
= handle_register_failed(sock_info
);
1909 ret
= lttng_ust_add_fd_to_tracker(fd
);
1913 PERROR("close on sock_info->socket");
1916 lttng_ust_unlock_fd_tracker();
1921 sock_info
->socket
= ret
;
1922 lttng_ust_unlock_fd_tracker();
1926 * Unlock/relock ust lock because connect is blocking (with
1927 * timeout). Don't delay constructors on the ust lock for too
1935 * Create only one root handle per listener thread for the whole
1936 * process lifetime, so we ensure we get ID which is statically
1937 * assigned to the root handle.
1939 if (sock_info
->root_handle
== -1) {
1940 ret
= lttng_abi_create_root_handle();
1942 ERR("Error creating root handle");
1945 sock_info
->root_handle
= ret
;
1948 ret
= register_to_sessiond(sock_info
->socket
, LTTNG_UST_CTL_SOCKET_CMD
,
1949 sock_info
->procname
);
1951 ERR("Error registering to %s ust cmd socket",
1953 prev_connect_failed
= 1;
1955 * If we cannot register to the sessiond daemon, don't
1956 * delay constructor execution.
1958 ret
= handle_register_failed(sock_info
);
1966 * Unlock/relock ust lock because connect is blocking (with
1967 * timeout). Don't delay constructors on the ust lock for too
1974 /* Connect notify socket */
1975 lttng_ust_lock_fd_tracker();
1976 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
,
1977 get_connect_sock_timeout());
1979 lttng_ust_unlock_fd_tracker();
1980 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1981 prev_connect_failed
= 1;
1984 * If we cannot find the sessiond daemon, don't delay
1985 * constructor execution.
1987 ret
= handle_register_failed(sock_info
);
1994 ret
= lttng_ust_add_fd_to_tracker(fd
);
1998 PERROR("close on sock_info->notify_socket");
2001 lttng_ust_unlock_fd_tracker();
2006 sock_info
->notify_socket
= ret
;
2007 lttng_ust_unlock_fd_tracker();
2011 * Unlock/relock ust lock because connect is blocking (with
2012 * timeout). Don't delay constructors on the ust lock for too
2019 timeout
= get_notify_sock_timeout();
2022 * Give at least 10ms to sessiond to reply to
2027 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
2030 WARN("Error setting socket receive timeout");
2032 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
2035 WARN("Error setting socket send timeout");
2037 } else if (timeout
< -1) {
2038 WARN("Unsupported timeout value %ld", timeout
);
2041 ret
= register_to_sessiond(sock_info
->notify_socket
,
2042 LTTNG_UST_CTL_SOCKET_NOTIFY
, sock_info
->procname
);
2044 ERR("Error registering to %s ust notify socket",
2046 prev_connect_failed
= 1;
2048 * If we cannot register to the sessiond daemon, don't
2049 * delay constructor execution.
2051 ret
= handle_register_failed(sock_info
);
2056 sock
= sock_info
->socket
;
2062 struct ustcomm_ust_msg lum
;
2064 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
2066 case 0: /* orderly shutdown */
2067 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
2072 * Either sessiond has shutdown or refused us by closing the socket.
2073 * In either case, we don't want to delay construction execution,
2074 * and we need to wait before retry.
2076 prev_connect_failed
= 1;
2078 * If we cannot register to the sessiond daemon, don't
2079 * delay constructor execution.
2081 ret
= handle_register_failed(sock_info
);
2086 print_cmd(lum
.cmd
, lum
.handle
);
2087 ret
= handle_message(sock_info
, sock
, &lum
);
2089 ERR("Error handling message for %s socket",
2092 * Close socket if protocol error is
2100 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
2102 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
2104 if (len
== -ECONNRESET
) {
2105 DBG("%s remote end closed connection", sock_info
->name
);
2116 /* Cleanup socket handles before trying to reconnect */
2117 lttng_ust_abi_objd_table_owner_cleanup(sock_info
);
2119 goto restart
; /* try to reconnect */
2124 pthread_mutex_lock(&ust_exit_mutex
);
2125 sock_info
->thread_active
= 0;
2126 pthread_mutex_unlock(&ust_exit_mutex
);
2131 * Weak symbol to call when the ust malloc wrapper is not loaded.
2133 __attribute__((weak
))
2134 void lttng_ust_libc_wrapper_malloc_ctor(void)
2139 * Use a symbol of the previous ABI to detect if liblttng-ust.so.0 is loaded in
2140 * the current process.
2142 #define LTTNG_UST_SONAME_0_SYM "ltt_probe_register"
2145 void lttng_ust_check_soname_0(void)
2147 if (!dlsym(RTLD_DEFAULT
, LTTNG_UST_SONAME_0_SYM
))
2150 CRIT("Incompatible library ABIs detected within the same process. "
2151 "The process is likely linked against different major soname of LTTng-UST which is unsupported. "
2152 "The detection was triggered by lookup of ABI 0 symbol \"%s\" in the Global Symbol Table\n",
2153 LTTNG_UST_SONAME_0_SYM
);
2157 * Expose a canary symbol of the previous ABI to ensure we catch uses of a
2158 * liblttng-ust.so.0 dlopen'd after .so.1 has been loaded. Use a different
2159 * symbol than the detection code to ensure we don't detect ourself.
2161 * This scheme will only work on systems where the global symbol table has
2162 * priority when resolving the symbols of a dlopened shared object, which is
2163 * the case on Linux but not on FreeBSD.
2165 void init_usterr(void);
2166 void init_usterr(void)
2168 CRIT("Incompatible library ABIs detected within the same process. "
2169 "The process is likely linked against different major soname of LTTng-UST which is unsupported. "
2170 "The detection was triggered by canary symbol \"%s\"\n", __func__
);
2174 * sessiond monitoring thread: monitor presence of global and per-user
2175 * sessiond by polling the application common named pipe.
2178 void lttng_ust_ctor(void)
2179 __attribute__((constructor
));
2181 void lttng_ust_ctor(void)
2183 struct timespec constructor_timeout
;
2184 sigset_t sig_all_blocked
, orig_parent_mask
;
2185 pthread_attr_t thread_attr
;
2190 if (uatomic_xchg(&initialized
, 1) == 1)
2194 * Fixup interdependency between TLS allocation mutex (which happens
2195 * to be the dynamic linker mutex) and ust_lock, taken within
2198 lttng_ust_common_init_thread(0);
2200 lttng_ust_loaded
= 1;
2203 * Check if we find a symbol of the previous ABI in the current process
2204 * as different ABIs of liblttng-ust can't co-exist in a process. If we
2205 * do so, emit a critical log message which will also abort if the
2206 * LTTNG_UST_ABORT_ON_CRITICAL environment variable is set.
2208 lttng_ust_check_soname_0();
2211 * We need to ensure that the liblttng-ust library is not unloaded to avoid
2212 * the unloading of code used by the ust_listener_threads as we can not
2213 * reliably know when they exited. To do that, manually load
2214 * liblttng-ust.so to increment the dynamic loader's internal refcount for
2215 * this library so it never becomes zero, thus never gets unloaded from the
2216 * address space of the process. Since we are already running in the
2217 * constructor of the LTTNG_UST_LIB_SONAME library, calling dlopen will
2218 * simply increment the refcount and no additional work is needed by the
2219 * dynamic loader as the shared library is already loaded in the address
2220 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
2221 * unloading of the UST library if its refcount becomes zero (which should
2222 * never happen). Do the return value check but discard the handle at the
2223 * end of the function as it's not needed.
2225 handle
= dlopen(LTTNG_UST_LIB_SONAME
, RTLD_LAZY
| RTLD_NODELETE
);
2227 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME
);
2229 DBG("dlopened liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME
);
2233 * We want precise control over the order in which we construct
2234 * our sub-libraries vs starting to receive commands from
2235 * sessiond (otherwise leading to errors when trying to create
2236 * sessiond before the init functions are completed).
2240 * Both the logging and getenv lazy-initialization uses getenv()
2241 * internally and thus needs to be explicitly initialized in
2242 * liblttng-ust before we start any threads as an unsuspecting normally
2243 * single threaded application using liblttng-ust could be using
2244 * setenv() which is not thread-safe.
2246 lttng_ust_logging_init();
2247 lttng_ust_getenv_init();
2249 /* Call the liblttng-ust-common constructor. */
2250 lttng_ust_common_ctor();
2252 lttng_ust_tp_init();
2253 lttng_ust_statedump_init();
2254 lttng_ust_ring_buffer_clients_init();
2255 lttng_ust_counter_clients_init();
2256 lttng_perf_counter_init();
2258 * Invoke ust malloc wrapper init before starting other threads.
2260 lttng_ust_libc_wrapper_malloc_ctor();
2262 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
2264 get_allow_blocking();
2266 ret
= sem_init(&constructor_wait
, 0, 0);
2271 ret
= setup_global_apps();
2273 assert(global_apps
.allowed
== 0);
2274 DBG("global apps setup returned %d", ret
);
2277 ret
= setup_local_apps();
2279 assert(local_apps
.allowed
== 0);
2280 DBG("local apps setup returned %d", ret
);
2283 /* A new thread created by pthread_create inherits the signal mask
2284 * from the parent. To avoid any signal being received by the
2285 * listener thread, we block all signals temporarily in the parent,
2286 * while we create the listener thread.
2288 sigfillset(&sig_all_blocked
);
2289 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
2291 ERR("pthread_sigmask: %s", strerror(ret
));
2294 ret
= pthread_attr_init(&thread_attr
);
2296 ERR("pthread_attr_init: %s", strerror(ret
));
2298 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
2300 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
2303 if (global_apps
.allowed
) {
2304 pthread_mutex_lock(&ust_exit_mutex
);
2305 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
2306 ust_listener_thread
, &global_apps
);
2308 ERR("pthread_create global: %s", strerror(ret
));
2310 global_apps
.thread_active
= 1;
2311 pthread_mutex_unlock(&ust_exit_mutex
);
2313 handle_register_done(&global_apps
);
2316 if (local_apps
.allowed
) {
2317 pthread_mutex_lock(&ust_exit_mutex
);
2318 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
2319 ust_listener_thread
, &local_apps
);
2321 ERR("pthread_create local: %s", strerror(ret
));
2323 local_apps
.thread_active
= 1;
2324 pthread_mutex_unlock(&ust_exit_mutex
);
2326 handle_register_done(&local_apps
);
2328 ret
= pthread_attr_destroy(&thread_attr
);
2330 ERR("pthread_attr_destroy: %s", strerror(ret
));
2333 /* Restore original signal mask in parent */
2334 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
2336 ERR("pthread_sigmask: %s", strerror(ret
));
2339 switch (timeout_mode
) {
2340 case 1: /* timeout wait */
2342 ret
= sem_timedwait(&constructor_wait
,
2343 &constructor_timeout
);
2344 } while (ret
< 0 && errno
== EINTR
);
2348 ERR("Timed out waiting for lttng-sessiond");
2351 PERROR("sem_timedwait");
2354 ERR("Unexpected error \"%s\" returned by sem_timedwait",
2359 case -1:/* wait forever */
2361 ret
= sem_wait(&constructor_wait
);
2362 } while (ret
< 0 && errno
== EINTR
);
2369 ERR("Unexpected error \"%s\" returned by sem_wait",
2374 case 0: /* no timeout */
2380 void lttng_ust_cleanup(int exiting
)
2382 cleanup_sock_info(&global_apps
, exiting
);
2383 cleanup_sock_info(&local_apps
, exiting
);
2384 local_apps
.allowed
= 0;
2385 global_apps
.allowed
= 0;
2387 * The teardown in this function all affect data structures
2388 * accessed under the UST lock by the listener thread. This
2389 * lock, along with the lttng_ust_comm_should_quit flag, ensure
2390 * that none of these threads are accessing this data at this
2393 lttng_ust_abi_exit();
2394 lttng_ust_abi_events_exit();
2395 lttng_perf_counter_exit();
2396 lttng_ust_ring_buffer_clients_exit();
2397 lttng_ust_counter_clients_exit();
2398 lttng_ust_statedump_destroy();
2399 lttng_ust_tp_exit();
2401 /* Reinitialize values for fork */
2402 sem_count
= sem_count_initial_value
;
2403 lttng_ust_comm_should_quit
= 0;
2409 void lttng_ust_exit(void)
2410 __attribute__((destructor
));
2412 void lttng_ust_exit(void)
2417 * Using pthread_cancel here because:
2418 * A) we don't want to hang application teardown.
2419 * B) the thread is not allocating any resource.
2423 * Require the communication thread to quit. Synchronize with
2424 * mutexes to ensure it is not in a mutex critical section when
2425 * pthread_cancel is later called.
2428 lttng_ust_comm_should_quit
= 1;
2431 pthread_mutex_lock(&ust_exit_mutex
);
2432 /* cancel threads */
2433 if (global_apps
.thread_active
) {
2434 ret
= pthread_cancel(global_apps
.ust_listener
);
2436 ERR("Error cancelling global ust listener thread: %s",
2439 global_apps
.thread_active
= 0;
2442 if (local_apps
.thread_active
) {
2443 ret
= pthread_cancel(local_apps
.ust_listener
);
2445 ERR("Error cancelling local ust listener thread: %s",
2448 local_apps
.thread_active
= 0;
2451 pthread_mutex_unlock(&ust_exit_mutex
);
2454 * Do NOT join threads: use of sys_futex makes it impossible to
2455 * join the threads without using async-cancel, but async-cancel
2456 * is delivered by a signal, which could hit the target thread
2457 * anywhere in its code path, including while the ust_lock() is
2458 * held, causing a deadlock for the other thread. Let the OS
2459 * cleanup the threads if there are stalled in a syscall.
2461 lttng_ust_cleanup(1);
2465 void ust_context_ns_reset(void)
2467 lttng_context_pid_ns_reset();
2468 lttng_context_cgroup_ns_reset();
2469 lttng_context_ipc_ns_reset();
2470 lttng_context_mnt_ns_reset();
2471 lttng_context_net_ns_reset();
2472 lttng_context_user_ns_reset();
2473 lttng_context_time_ns_reset();
2474 lttng_context_uts_ns_reset();
2478 void ust_context_vuids_reset(void)
2480 lttng_context_vuid_reset();
2481 lttng_context_veuid_reset();
2482 lttng_context_vsuid_reset();
2486 void ust_context_vgids_reset(void)
2488 lttng_context_vgid_reset();
2489 lttng_context_vegid_reset();
2490 lttng_context_vsgid_reset();
2494 * We exclude the worker threads across fork and clone (except
2495 * CLONE_VM), because these system calls only keep the forking thread
2496 * running in the child. Therefore, we don't want to call fork or clone
2497 * in the middle of an tracepoint or ust tracing state modification.
2498 * Holding this mutex protects these structures across fork and clone.
2500 void lttng_ust_before_fork(sigset_t
*save_sigset
)
2503 * Disable signals. This is to avoid that the child intervenes
2504 * before it is properly setup for tracing. It is safer to
2505 * disable all signals, because then we know we are not breaking
2506 * anything by restoring the original mask.
2511 /* Allocate lttng-ust TLS. */
2512 lttng_ust_common_init_thread(0);
2514 if (URCU_TLS(lttng_ust_nest_count
))
2516 /* Disable signals */
2517 sigfillset(&all_sigs
);
2518 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
2520 PERROR("sigprocmask");
2523 pthread_mutex_lock(&ust_fork_mutex
);
2526 lttng_ust_urcu_before_fork();
2527 lttng_ust_lock_fd_tracker();
2531 static void ust_after_fork_common(sigset_t
*restore_sigset
)
2535 DBG("process %d", getpid());
2536 lttng_perf_unlock();
2537 lttng_ust_unlock_fd_tracker();
2540 pthread_mutex_unlock(&ust_fork_mutex
);
2542 /* Restore signals */
2543 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
2545 PERROR("sigprocmask");
2549 void lttng_ust_after_fork_parent(sigset_t
*restore_sigset
)
2551 if (URCU_TLS(lttng_ust_nest_count
))
2553 DBG("process %d", getpid());
2554 lttng_ust_urcu_after_fork_parent();
2555 /* Release mutexes and re-enable signals */
2556 ust_after_fork_common(restore_sigset
);
2560 * After fork, in the child, we need to cleanup all the leftover state,
2561 * except the worker thread which already magically disappeared thanks
2562 * to the weird Linux fork semantics. After tyding up, we call
2563 * lttng_ust_ctor() again to start over as a new PID.
2565 * This is meant for forks() that have tracing in the child between the
2566 * fork and following exec call (if there is any).
2568 void lttng_ust_after_fork_child(sigset_t
*restore_sigset
)
2570 if (URCU_TLS(lttng_ust_nest_count
))
2572 lttng_context_vpid_reset();
2573 lttng_context_vtid_reset();
2574 lttng_ust_context_procname_reset();
2575 ust_context_ns_reset();
2576 ust_context_vuids_reset();
2577 ust_context_vgids_reset();
2578 DBG("process %d", getpid());
2579 /* Release urcu mutexes */
2580 lttng_ust_urcu_after_fork_child();
2581 lttng_ust_cleanup(0);
2582 /* Release mutexes and re-enable signals */
2583 ust_after_fork_common(restore_sigset
);
2587 void lttng_ust_after_setns(void)
2589 ust_context_ns_reset();
2590 ust_context_vuids_reset();
2591 ust_context_vgids_reset();
2594 void lttng_ust_after_unshare(void)
2596 ust_context_ns_reset();
2597 ust_context_vuids_reset();
2598 ust_context_vgids_reset();
2601 void lttng_ust_after_setuid(void)
2603 ust_context_vuids_reset();
2606 void lttng_ust_after_seteuid(void)
2608 ust_context_vuids_reset();
2611 void lttng_ust_after_setreuid(void)
2613 ust_context_vuids_reset();
2616 void lttng_ust_after_setresuid(void)
2618 ust_context_vuids_reset();
2621 void lttng_ust_after_setgid(void)
2623 ust_context_vgids_reset();
2626 void lttng_ust_after_setegid(void)
2628 ust_context_vgids_reset();
2631 void lttng_ust_after_setregid(void)
2633 ust_context_vgids_reset();
2636 void lttng_ust_after_setresgid(void)
2638 ust_context_vgids_reset();
2641 void lttng_ust_sockinfo_session_enabled(void *owner
)
2643 struct sock_info
*sock_info
= owner
;
2644 sock_info
->statedump_pending
= 1;