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-config.h>
32 #include <lttng/ust-utils.h>
33 #include <lttng/ust-events.h>
34 #include <lttng/ust-abi.h>
35 #include <lttng/ust-fork.h>
36 #include <lttng/ust-error.h>
37 #include <lttng/ust-ctl.h>
38 #include <lttng/ust-libc-wrapper.h>
39 #include <lttng/ust-thread.h>
40 #include <lttng/ust-tracer.h>
41 #include <lttng/ust-common.h>
42 #include <lttng/ust-cancelstate.h>
43 #include <urcu/tls-compat.h>
44 #include "lib/lttng-ust/futex.h"
45 #include "common/ustcomm.h"
46 #include "common/ust-fd.h"
47 #include "common/logging.h"
48 #include "common/macros.h"
49 #include "common/tracepoint.h"
50 #include "lttng-tracer-core.h"
51 #include "common/compat/pthread.h"
52 #include "common/procname.h"
53 #include "common/ringbuffer/rb-init.h"
54 #include "lttng-ust-statedump.h"
55 #include "common/clock.h"
56 #include "common/getenv.h"
57 #include "lib/lttng-ust/events.h"
58 #include "context-internal.h"
59 #include "common/align.h"
60 #include "common/counter-clients/clients.h"
61 #include "common/ringbuffer-clients/clients.h"
64 * Has lttng ust comm constructor been called ?
66 static int initialized
;
69 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
70 * Held when handling a command, also held by fork() to deal with
71 * removal of threads, and by exit path.
73 * The UST lock is the centralized mutex across UST tracing control and
76 * ust_exit_mutex must never nest in ust_mutex.
78 * ust_fork_mutex must never nest in ust_mutex.
80 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
81 * counter lazy initialization called by events within the statedump,
82 * which traces while the ust_mutex is held.
84 * ust_lock nests within the dynamic loader lock (within glibc) because
85 * it is taken within the library constructor.
87 * The ust fd tracker lock nests within the ust_mutex.
89 static pthread_mutex_t ust_mutex
= PTHREAD_MUTEX_INITIALIZER
;
91 /* Allow nesting the ust_mutex within the same thread. */
92 static DEFINE_URCU_TLS(int, ust_mutex_nest
);
95 * ust_exit_mutex protects thread_active variable wrt thread exit. It
96 * cannot be done by ust_mutex because pthread_cancel(), which takes an
97 * internal libc lock, cannot nest within ust_mutex.
99 * It never nests within a ust_mutex.
101 static pthread_mutex_t ust_exit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
104 * ust_fork_mutex protects base address statedump tracing against forks. It
105 * prevents the dynamic loader lock to be taken (by base address statedump
106 * tracing) while a fork is happening, thus preventing deadlock issues with
107 * the dynamic loader lock.
109 static pthread_mutex_t ust_fork_mutex
= PTHREAD_MUTEX_INITIALIZER
;
111 /* Should the ust comm thread quit ? */
112 static int lttng_ust_comm_should_quit
;
115 * This variable can be tested by applications to check whether
116 * lttng-ust is loaded. They simply have to define their own
117 * "lttng_ust_loaded1" weak symbol, and test it. It is set to 1 by the
118 * library constructor.
120 static int lttng_ust_loaded_orig
;
123 * Notes on async-signal-safety of ust lock: a few libc functions are used
124 * which are not strictly async-signal-safe:
126 * - pthread_setcancelstate
127 * - pthread_mutex_lock
128 * - pthread_mutex_unlock
130 * As of glibc 2.35, the implementation of pthread_setcancelstate only
131 * touches TLS data, and it appears to be safe to use from signal
132 * handlers. If the libc implementation changes, this will need to be
133 * revisited, and we may ask glibc to provide an async-signal-safe
134 * pthread_setcancelstate.
136 * As of glibc 2.35, the implementation of pthread_mutex_lock/unlock
137 * for fast mutexes only relies on the pthread_mutex_t structure.
138 * Disabling signals around all uses of this mutex ensures
139 * signal-safety. If the libc implementation changes and eventually uses
140 * other global resources, this will need to be revisited and we may
141 * need to implement our own mutex.
145 * Return 0 on success, -1 if should quit.
146 * The lock is taken in both cases.
151 sigset_t sig_all_blocked
, orig_mask
;
154 if (lttng_ust_cancelstate_disable_push()) {
155 ERR("lttng_ust_cancelstate_disable_push");
157 sigfillset(&sig_all_blocked
);
158 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
160 ERR("pthread_sigmask: ret=%d", ret
);
162 if (!URCU_TLS(ust_mutex_nest
)++)
163 pthread_mutex_lock(&ust_mutex
);
164 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
166 ERR("pthread_sigmask: ret=%d", ret
);
168 if (lttng_ust_comm_should_quit
) {
176 * ust_lock_nocheck() can be used in constructors/destructors, because
177 * they are already nested within the dynamic loader lock, and therefore
178 * have exclusive access against execution of liblttng-ust destructor.
181 void ust_lock_nocheck(void)
183 sigset_t sig_all_blocked
, orig_mask
;
186 if (lttng_ust_cancelstate_disable_push()) {
187 ERR("lttng_ust_cancelstate_disable_push");
189 sigfillset(&sig_all_blocked
);
190 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
192 ERR("pthread_sigmask: ret=%d", ret
);
194 if (!URCU_TLS(ust_mutex_nest
)++)
195 pthread_mutex_lock(&ust_mutex
);
196 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
198 ERR("pthread_sigmask: ret=%d", ret
);
205 void ust_unlock(void)
207 sigset_t sig_all_blocked
, orig_mask
;
210 sigfillset(&sig_all_blocked
);
211 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
213 ERR("pthread_sigmask: ret=%d", ret
);
215 if (!--URCU_TLS(ust_mutex_nest
))
216 pthread_mutex_unlock(&ust_mutex
);
217 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
219 ERR("pthread_sigmask: ret=%d", ret
);
221 if (lttng_ust_cancelstate_disable_pop()) {
222 ERR("lttng_ust_cancelstate_disable_pop");
227 * Wait for either of these before continuing to the main
229 * - the register_done message from sessiond daemon
230 * (will let the sessiond daemon enable sessions before main
232 * - sessiond daemon is not reachable.
233 * - timeout (ensuring applications are resilient to session
236 static sem_t constructor_wait
;
238 * Doing this for both the global and local sessiond.
241 sem_count_initial_value
= 4,
244 static int sem_count
= sem_count_initial_value
;
247 * Counting nesting within lttng-ust. Used to ensure that calling fork()
248 * from liblttng-ust does not execute the pre/post fork handlers.
250 static DEFINE_URCU_TLS(int, lttng_ust_nest_count
);
253 * Info about socket and associated listener thread.
257 pthread_t ust_listener
; /* listener thread */
259 int registration_done
;
264 char sock_path
[PATH_MAX
];
268 char wait_shm_path
[PATH_MAX
];
270 /* Keep track of lazy state dump not performed yet. */
271 int statedump_pending
;
272 int initial_statedump_done
;
273 /* Keep procname for statedump */
274 char procname
[LTTNG_UST_CONTEXT_PROCNAME_LEN
];
277 /* Socket from app (connect) to session daemon (listen) for communication */
278 static struct sock_info global_apps
= {
283 .registration_done
= 0,
287 .sock_path
= LTTNG_DEFAULT_RUNDIR
"/" LTTNG_UST_SOCK_FILENAME
,
291 .wait_shm_path
= "/" LTTNG_UST_WAIT_FILENAME
,
293 .statedump_pending
= 0,
294 .initial_statedump_done
= 0,
298 /* TODO: allow global_apps_sock_path override */
300 static struct sock_info local_apps
= {
304 .registration_done
= 0,
305 .allowed
= 0, /* Check setuid bit first */
311 .statedump_pending
= 0,
312 .initial_statedump_done
= 0,
316 static int wait_poll_fallback
;
318 static const char *cmd_name_mapping
[] = {
319 [ LTTNG_UST_ABI_RELEASE
] = "Release",
320 [ LTTNG_UST_ABI_SESSION
] = "Create Session",
321 [ LTTNG_UST_ABI_TRACER_VERSION
] = "Get Tracer Version",
323 [ LTTNG_UST_ABI_TRACEPOINT_LIST
] = "Create Tracepoint List",
324 [ LTTNG_UST_ABI_WAIT_QUIESCENT
] = "Wait for Quiescent State",
325 [ LTTNG_UST_ABI_REGISTER_DONE
] = "Registration Done",
326 [ LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST
] = "Create Tracepoint Field List",
328 [ LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
] = "Create event notifier group",
330 /* Session FD commands */
331 [ LTTNG_UST_ABI_CHANNEL
] = "Create Channel",
332 [ LTTNG_UST_ABI_SESSION_START
] = "Start Session",
333 [ LTTNG_UST_ABI_SESSION_STOP
] = "Stop Session",
335 /* Channel FD commands */
336 [ LTTNG_UST_ABI_STREAM
] = "Create Stream",
337 [ LTTNG_UST_ABI_EVENT
] = "Create Event",
339 /* Event and Channel FD commands */
340 [ LTTNG_UST_ABI_CONTEXT
] = "Create Context",
341 [ LTTNG_UST_ABI_FLUSH_BUFFER
] = "Flush Buffer",
343 /* Event, Channel and Session commands */
344 [ LTTNG_UST_ABI_ENABLE
] = "Enable",
345 [ LTTNG_UST_ABI_DISABLE
] = "Disable",
347 /* Tracepoint list commands */
348 [ LTTNG_UST_ABI_TRACEPOINT_LIST_GET
] = "List Next Tracepoint",
349 [ LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET
] = "List Next Tracepoint Field",
351 /* Event FD commands */
352 [ LTTNG_UST_ABI_FILTER
] = "Create Filter",
353 [ LTTNG_UST_ABI_EXCLUSION
] = "Add exclusions to event",
355 /* Event notifier group commands */
356 [ LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
] = "Create event notifier",
358 /* Session and event notifier group commands */
359 [ LTTNG_UST_ABI_COUNTER
] = "Create Counter",
361 /* Counter commands */
362 [ LTTNG_UST_ABI_COUNTER_GLOBAL
] = "Create Counter Global",
363 [ LTTNG_UST_ABI_COUNTER_CPU
] = "Create Counter CPU",
366 static const char *str_timeout
;
367 static int got_timeout_env
;
369 static char *get_map_shm(struct sock_info
*sock_info
);
372 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
376 const char *get_lttng_home_dir(void)
380 val
= (const char *) lttng_ust_getenv("LTTNG_HOME");
384 return (const char *) lttng_ust_getenv("HOME");
388 * Force a read (imply TLS allocation for dlopen) of TLS variables.
391 void lttng_nest_count_alloc_tls(void)
393 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count
)));
397 void lttng_ust_mutex_nest_alloc_tls(void)
399 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest
)));
403 * Allocate lttng-ust urcu TLS.
406 void lttng_lttng_ust_urcu_alloc_tls(void)
408 (void) lttng_ust_urcu_read_ongoing();
411 void lttng_ust_alloc_tls(void)
413 lttng_lttng_ust_urcu_alloc_tls();
414 lttng_ringbuffer_alloc_tls();
415 lttng_vtid_alloc_tls();
416 lttng_nest_count_alloc_tls();
417 lttng_procname_alloc_tls();
418 lttng_ust_mutex_nest_alloc_tls();
419 lttng_ust_perf_counter_alloc_tls();
420 lttng_ust_common_alloc_tls();
421 lttng_cgroup_ns_alloc_tls();
422 lttng_ipc_ns_alloc_tls();
423 lttng_net_ns_alloc_tls();
424 lttng_time_ns_alloc_tls();
425 lttng_uts_ns_alloc_tls();
426 lttng_ust_ring_buffer_client_discard_alloc_tls();
427 lttng_ust_ring_buffer_client_discard_rt_alloc_tls();
428 lttng_ust_ring_buffer_client_overwrite_alloc_tls();
429 lttng_ust_ring_buffer_client_overwrite_rt_alloc_tls();
433 * LTTng-UST uses Global Dynamic model TLS variables rather than IE
434 * model because many versions of glibc don't preallocate a pool large
435 * enough for TLS variables IE model defined in other shared libraries,
436 * and causes issues when using LTTng-UST for Java tracing.
438 * Because of this use of Global Dynamic TLS variables, users wishing to
439 * trace from signal handlers need to explicitly trigger the lazy
440 * allocation of those variables for each thread before using them.
441 * This can be triggered by calling lttng_ust_init_thread().
443 void lttng_ust_init_thread(void)
446 * Because those TLS variables are global dynamic, we need to
447 * ensure those are initialized before a signal handler nesting over
448 * this thread attempts to use them.
450 lttng_ust_alloc_tls();
453 int lttng_get_notify_socket(void *owner
)
455 struct sock_info
*info
= owner
;
457 return info
->notify_socket
;
461 char* lttng_ust_sockinfo_get_procname(void *owner
)
463 struct sock_info
*info
= owner
;
465 return info
->procname
;
469 void print_cmd(int cmd
, int handle
)
471 const char *cmd_name
= "Unknown";
473 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
474 && cmd_name_mapping
[cmd
]) {
475 cmd_name
= cmd_name_mapping
[cmd
];
477 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
479 lttng_ust_obj_get_name(handle
), handle
);
483 int setup_global_apps(void)
486 assert(!global_apps
.wait_shm_mmap
);
488 global_apps
.wait_shm_mmap
= get_map_shm(&global_apps
);
489 if (!global_apps
.wait_shm_mmap
) {
490 WARN("Unable to get map shm for global apps. Disabling LTTng-UST global tracing.");
491 global_apps
.allowed
= 0;
496 global_apps
.allowed
= 1;
497 lttng_pthread_getname_np(global_apps
.procname
, LTTNG_UST_CONTEXT_PROCNAME_LEN
);
502 int setup_local_apps(void)
505 const char *home_dir
;
508 assert(!local_apps
.wait_shm_mmap
);
512 * Disallow per-user tracing for setuid binaries.
514 if (uid
!= geteuid()) {
515 assert(local_apps
.allowed
== 0);
519 home_dir
= get_lttng_home_dir();
521 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
522 assert(local_apps
.allowed
== 0);
526 local_apps
.allowed
= 1;
527 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
529 LTTNG_DEFAULT_HOME_RUNDIR
,
530 LTTNG_UST_SOCK_FILENAME
);
531 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
532 LTTNG_UST_WAIT_FILENAME
,
535 local_apps
.wait_shm_mmap
= get_map_shm(&local_apps
);
536 if (!local_apps
.wait_shm_mmap
) {
537 WARN("Unable to get map shm for local apps. Disabling LTTng-UST per-user tracing.");
538 local_apps
.allowed
= 0;
543 lttng_pthread_getname_np(local_apps
.procname
, LTTNG_UST_CONTEXT_PROCNAME_LEN
);
549 * Get socket timeout, in ms.
550 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
553 long get_timeout(void)
555 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
557 if (!got_timeout_env
) {
558 str_timeout
= lttng_ust_getenv("LTTNG_UST_REGISTER_TIMEOUT");
562 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
563 /* All negative values are considered as "-1". */
564 if (constructor_delay_ms
< -1)
565 constructor_delay_ms
= -1;
566 return constructor_delay_ms
;
569 /* Timeout for notify socket send and recv. */
571 long get_notify_sock_timeout(void)
573 return get_timeout();
576 /* Timeout for connecting to cmd and notify sockets. */
578 long get_connect_sock_timeout(void)
580 return get_timeout();
584 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
587 int get_constructor_timeout(struct timespec
*constructor_timeout
)
589 long constructor_delay_ms
;
592 constructor_delay_ms
= get_timeout();
594 switch (constructor_delay_ms
) {
595 case -1:/* fall-through */
597 return constructor_delay_ms
;
603 * If we are unable to find the current time, don't wait.
605 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
610 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
611 constructor_timeout
->tv_nsec
+=
612 (constructor_delay_ms
% 1000UL) * 1000000UL;
613 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
614 constructor_timeout
->tv_sec
++;
615 constructor_timeout
->tv_nsec
-= 1000000000UL;
617 /* Timeout wait (constructor_delay_ms). */
622 void get_allow_blocking(void)
624 const char *str_allow_blocking
=
625 lttng_ust_getenv("LTTNG_UST_ALLOW_BLOCKING");
627 if (str_allow_blocking
) {
628 DBG("%s environment variable is set",
629 "LTTNG_UST_ALLOW_BLOCKING");
630 lttng_ust_ringbuffer_set_allow_blocking();
635 int register_to_sessiond(int socket
, enum lttng_ust_ctl_socket_type type
,
636 const char *procname
)
638 return ustcomm_send_reg_msg(socket
,
641 lttng_ust_rb_alignof(uint8_t) * CHAR_BIT
,
642 lttng_ust_rb_alignof(uint16_t) * CHAR_BIT
,
643 lttng_ust_rb_alignof(uint32_t) * CHAR_BIT
,
644 lttng_ust_rb_alignof(uint64_t) * CHAR_BIT
,
645 lttng_ust_rb_alignof(unsigned long) * CHAR_BIT
,
650 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
654 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
657 DBG("message successfully sent");
660 if (len
== -ECONNRESET
) {
661 DBG("remote end closed connection");
666 DBG("incorrect message size: %zd", len
);
672 void decrement_sem_count(unsigned int count
)
676 assert(uatomic_read(&sem_count
) >= count
);
678 if (uatomic_read(&sem_count
) <= 0) {
682 ret
= uatomic_add_return(&sem_count
, -count
);
684 ret
= sem_post(&constructor_wait
);
690 int handle_register_done(struct sock_info
*sock_info
)
692 if (sock_info
->registration_done
)
694 sock_info
->registration_done
= 1;
696 decrement_sem_count(1);
697 if (!sock_info
->statedump_pending
) {
698 sock_info
->initial_statedump_done
= 1;
699 decrement_sem_count(1);
706 int handle_register_failed(struct sock_info
*sock_info
)
708 if (sock_info
->registration_done
)
710 sock_info
->registration_done
= 1;
711 sock_info
->initial_statedump_done
= 1;
713 decrement_sem_count(2);
719 * Only execute pending statedump after the constructor semaphore has
720 * been posted by the current listener thread. This means statedump will
721 * only be performed after the "registration done" command is received
722 * from this thread's session daemon.
724 * This ensures we don't run into deadlock issues with the dynamic
725 * loader mutex, which is held while the constructor is called and
726 * waiting on the constructor semaphore. All operations requiring this
727 * dynamic loader lock need to be postponed using this mechanism.
729 * In a scenario with two session daemons connected to the application,
730 * it is possible that the first listener thread which receives the
731 * registration done command issues its statedump while the dynamic
732 * loader lock is still held by the application constructor waiting on
733 * the semaphore. It will however be allowed to proceed when the
734 * second session daemon sends the registration done command to the
735 * second listener thread. This situation therefore does not produce
739 void handle_pending_statedump(struct sock_info
*sock_info
)
741 if (sock_info
->registration_done
&& sock_info
->statedump_pending
) {
742 sock_info
->statedump_pending
= 0;
743 pthread_mutex_lock(&ust_fork_mutex
);
744 lttng_handle_pending_statedump(sock_info
);
745 pthread_mutex_unlock(&ust_fork_mutex
);
747 if (!sock_info
->initial_statedump_done
) {
748 sock_info
->initial_statedump_done
= 1;
749 decrement_sem_count(1);
755 const char *bytecode_type_str(uint32_t cmd
)
758 case LTTNG_UST_ABI_CAPTURE
:
760 case LTTNG_UST_ABI_FILTER
:
768 int handle_bytecode_recv(struct sock_info
*sock_info
,
769 int sock
, struct ustcomm_ust_msg
*lum
)
771 struct lttng_ust_bytecode_node
*bytecode
= NULL
;
772 enum lttng_ust_bytecode_type type
;
773 const struct lttng_ust_abi_objd_ops
*ops
;
774 uint32_t data_size
, data_size_max
, reloc_offset
;
780 case LTTNG_UST_ABI_FILTER
:
781 type
= LTTNG_UST_BYTECODE_TYPE_FILTER
;
782 data_size
= lum
->u
.filter
.data_size
;
783 data_size_max
= LTTNG_UST_ABI_FILTER_BYTECODE_MAX_LEN
;
784 reloc_offset
= lum
->u
.filter
.reloc_offset
;
785 seqnum
= lum
->u
.filter
.seqnum
;
787 case LTTNG_UST_ABI_CAPTURE
:
788 type
= LTTNG_UST_BYTECODE_TYPE_CAPTURE
;
789 data_size
= lum
->u
.capture
.data_size
;
790 data_size_max
= LTTNG_UST_ABI_CAPTURE_BYTECODE_MAX_LEN
;
791 reloc_offset
= lum
->u
.capture
.reloc_offset
;
792 seqnum
= lum
->u
.capture
.seqnum
;
798 if (data_size
> data_size_max
) {
799 ERR("Bytecode %s data size is too large: %u bytes",
800 bytecode_type_str(lum
->cmd
), data_size
);
805 if (reloc_offset
> data_size
) {
806 ERR("Bytecode %s reloc offset %u is not within data",
807 bytecode_type_str(lum
->cmd
), reloc_offset
);
812 /* Allocate the structure AND the `data[]` field. */
813 bytecode
= zmalloc(sizeof(*bytecode
) + data_size
);
819 bytecode
->bc
.len
= data_size
;
820 bytecode
->bc
.reloc_offset
= reloc_offset
;
821 bytecode
->bc
.seqnum
= seqnum
;
822 bytecode
->type
= type
;
824 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
, bytecode
->bc
.len
);
826 case 0: /* orderly shutdown */
830 if (len
== bytecode
->bc
.len
) {
831 DBG("Bytecode %s data received",
832 bytecode_type_str(lum
->cmd
));
834 } else if (len
< 0) {
835 DBG("Receive failed from lttng-sessiond with errno %d",
837 if (len
== -ECONNRESET
) {
838 ERR("%s remote end closed connection",
846 DBG("Incorrect %s bytecode data message size: %zd",
847 bytecode_type_str(lum
->cmd
), len
);
853 ops
= lttng_ust_abi_objd_ops(lum
->handle
);
860 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
861 (unsigned long) &bytecode
,
872 void prepare_cmd_reply(struct ustcomm_ust_reply
*lur
, uint32_t handle
, uint32_t cmd
, int ret
)
874 lur
->handle
= handle
;
878 lur
->ret_code
= LTTNG_UST_OK
;
881 * Use -LTTNG_UST_ERR as wildcard for UST internal
882 * error that are not caused by the transport, except if
883 * we already have a more precise error message to
886 if (ret
> -LTTNG_UST_ERR
) {
887 /* Translate code to UST error. */
890 lur
->ret_code
= -LTTNG_UST_ERR_EXIST
;
893 lur
->ret_code
= -LTTNG_UST_ERR_INVAL
;
896 lur
->ret_code
= -LTTNG_UST_ERR_NOENT
;
899 lur
->ret_code
= -LTTNG_UST_ERR_PERM
;
902 lur
->ret_code
= -LTTNG_UST_ERR_NOSYS
;
905 lur
->ret_code
= -LTTNG_UST_ERR
;
915 int handle_message(struct sock_info
*sock_info
,
916 int sock
, struct ustcomm_ust_msg
*lum
)
919 const struct lttng_ust_abi_objd_ops
*ops
;
920 struct ustcomm_ust_reply lur
;
921 union lttng_ust_abi_args args
;
922 char ctxstr
[LTTNG_UST_ABI_SYM_NAME_LEN
]; /* App context string. */
925 memset(&lur
, 0, sizeof(lur
));
928 ret
= -LTTNG_UST_ERR_EXITING
;
932 ops
= lttng_ust_abi_objd_ops(lum
->handle
);
939 case LTTNG_UST_ABI_FILTER
:
940 case LTTNG_UST_ABI_EXCLUSION
:
941 case LTTNG_UST_ABI_CHANNEL
:
942 case LTTNG_UST_ABI_STREAM
:
943 case LTTNG_UST_ABI_CONTEXT
:
945 * Those commands send additional payload after struct
946 * ustcomm_ust_msg, which makes it pretty much impossible to
947 * deal with "unknown command" errors without leaving the
948 * communication pipe in a out-of-sync state. This is part of
949 * the ABI between liblttng-ust-ctl and liblttng-ust, and
950 * should be fixed on the next breaking
951 * LTTNG_UST_ABI_MAJOR_VERSION protocol bump by indicating the
952 * total command message length as part of a message header so
953 * that the protocol can recover from invalid command errors.
957 case LTTNG_UST_ABI_CAPTURE
:
958 case LTTNG_UST_ABI_COUNTER
:
959 case LTTNG_UST_ABI_COUNTER_GLOBAL
:
960 case LTTNG_UST_ABI_COUNTER_CPU
:
961 case LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
:
962 case LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
:
964 * Those commands expect a reply to the struct ustcomm_ust_msg
965 * before sending additional payload.
967 prepare_cmd_reply(&lur
, lum
->handle
, lum
->cmd
, 0);
969 ret
= send_reply(sock
, &lur
);
971 DBG("error sending reply");
978 * Other commands either don't send additional payload, or are
985 case LTTNG_UST_ABI_REGISTER_DONE
:
986 if (lum
->handle
== LTTNG_UST_ABI_ROOT_HANDLE
)
987 ret
= handle_register_done(sock_info
);
991 case LTTNG_UST_ABI_RELEASE
:
992 if (lum
->handle
== LTTNG_UST_ABI_ROOT_HANDLE
)
995 ret
= lttng_ust_abi_objd_unref(lum
->handle
, 1);
997 case LTTNG_UST_ABI_CAPTURE
:
998 case LTTNG_UST_ABI_FILTER
:
999 ret
= handle_bytecode_recv(sock_info
, sock
, lum
);
1003 case LTTNG_UST_ABI_EXCLUSION
:
1005 /* Receive exclusion names */
1006 struct lttng_ust_excluder_node
*node
;
1009 count
= lum
->u
.exclusion
.count
;
1011 /* There are no names to read */
1015 node
= zmalloc(sizeof(*node
) +
1016 count
* LTTNG_UST_ABI_SYM_NAME_LEN
);
1021 node
->excluder
.count
= count
;
1022 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
1023 count
* LTTNG_UST_ABI_SYM_NAME_LEN
);
1025 case 0: /* orderly shutdown */
1030 if (len
== count
* LTTNG_UST_ABI_SYM_NAME_LEN
) {
1031 DBG("Exclusion data received");
1033 } else if (len
< 0) {
1034 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1035 if (len
== -ECONNRESET
) {
1036 ERR("%s remote end closed connection", sock_info
->name
);
1045 DBG("Incorrect exclusion data message size: %zd", len
);
1052 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1053 (unsigned long) &node
,
1060 case LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
:
1062 int event_notifier_notif_fd
, close_ret
;
1064 len
= ustcomm_recv_event_notifier_notif_fd_from_sessiond(sock
,
1065 &event_notifier_notif_fd
);
1067 case 0: /* orderly shutdown */
1074 DBG("Receive failed from lttng-sessiond with errno %d",
1076 if (len
== -ECONNRESET
) {
1077 ERR("%s remote end closed connection",
1085 DBG("Incorrect event notifier fd message size: %zd",
1091 args
.event_notifier_handle
.event_notifier_notif_fd
=
1092 event_notifier_notif_fd
;
1094 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1095 (unsigned long) &lum
->u
,
1099 if (args
.event_notifier_handle
.event_notifier_notif_fd
>= 0) {
1100 lttng_ust_lock_fd_tracker();
1101 close_ret
= close(args
.event_notifier_handle
.event_notifier_notif_fd
);
1102 lttng_ust_unlock_fd_tracker();
1108 case LTTNG_UST_ABI_CHANNEL
:
1113 len
= ustcomm_recv_channel_from_sessiond(sock
,
1114 &chan_data
, lum
->u
.channel
.len
,
1117 case 0: /* orderly shutdown */
1121 if (len
== lum
->u
.channel
.len
) {
1122 DBG("channel data received");
1124 } else if (len
< 0) {
1125 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1126 if (len
== -ECONNRESET
) {
1127 ERR("%s remote end closed connection", sock_info
->name
);
1134 DBG("incorrect channel data message size: %zd", len
);
1139 args
.channel
.chan_data
= chan_data
;
1140 args
.channel
.wakeup_fd
= wakeup_fd
;
1142 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1143 (unsigned long) &lum
->u
,
1147 if (args
.channel
.wakeup_fd
>= 0) {
1150 lttng_ust_lock_fd_tracker();
1151 close_ret
= close(args
.channel
.wakeup_fd
);
1152 lttng_ust_unlock_fd_tracker();
1153 args
.channel
.wakeup_fd
= -1;
1157 free(args
.channel
.chan_data
);
1160 case LTTNG_UST_ABI_STREAM
:
1164 /* Receive shm_fd, wakeup_fd */
1165 ret
= ustcomm_recv_stream_from_sessiond(sock
,
1167 &args
.stream
.shm_fd
,
1168 &args
.stream
.wakeup_fd
);
1174 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1175 (unsigned long) &lum
->u
,
1179 if (args
.stream
.shm_fd
>= 0) {
1180 lttng_ust_lock_fd_tracker();
1181 close_ret
= close(args
.stream
.shm_fd
);
1182 lttng_ust_unlock_fd_tracker();
1183 args
.stream
.shm_fd
= -1;
1187 if (args
.stream
.wakeup_fd
>= 0) {
1188 lttng_ust_lock_fd_tracker();
1189 close_ret
= close(args
.stream
.wakeup_fd
);
1190 lttng_ust_unlock_fd_tracker();
1191 args
.stream
.wakeup_fd
= -1;
1197 case LTTNG_UST_ABI_CONTEXT
:
1198 switch (lum
->u
.context
.ctx
) {
1199 case LTTNG_UST_ABI_CONTEXT_APP_CONTEXT
:
1202 size_t ctxlen
, recvlen
;
1204 ctxlen
= strlen("$app.") + lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1
1205 + strlen(":") + lum
->u
.context
.u
.app_ctx
.ctx_name_len
;
1206 if (ctxlen
>= LTTNG_UST_ABI_SYM_NAME_LEN
) {
1207 ERR("Application context string length size is too large: %zu bytes",
1212 strcpy(ctxstr
, "$app.");
1213 p
= &ctxstr
[strlen("$app.")];
1214 recvlen
= ctxlen
- strlen("$app.");
1215 len
= ustcomm_recv_unix_sock(sock
, p
, recvlen
);
1217 case 0: /* orderly shutdown */
1221 if (len
== recvlen
) {
1222 DBG("app context data received");
1224 } else if (len
< 0) {
1225 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1226 if (len
== -ECONNRESET
) {
1227 ERR("%s remote end closed connection", sock_info
->name
);
1234 DBG("incorrect app context data message size: %zd", len
);
1239 /* Put : between provider and ctxname. */
1240 p
[lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1] = ':';
1241 args
.app_context
.ctxname
= ctxstr
;
1248 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1249 (unsigned long) &lum
->u
,
1255 case LTTNG_UST_ABI_COUNTER
:
1259 len
= ustcomm_recv_counter_from_sessiond(sock
,
1260 &counter_data
, lum
->u
.counter
.len
);
1262 case 0: /* orderly shutdown */
1266 if (len
== lum
->u
.counter
.len
) {
1267 DBG("counter data received");
1269 } else if (len
< 0) {
1270 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1271 if (len
== -ECONNRESET
) {
1272 ERR("%s remote end closed connection", sock_info
->name
);
1279 DBG("incorrect counter data message size: %zd", len
);
1284 args
.counter
.counter_data
= counter_data
;
1286 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1287 (unsigned long) &lum
->u
,
1291 free(args
.counter
.counter_data
);
1294 case LTTNG_UST_ABI_COUNTER_GLOBAL
:
1296 /* Receive shm_fd */
1297 ret
= ustcomm_recv_counter_shm_from_sessiond(sock
,
1298 &args
.counter_shm
.shm_fd
);
1304 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1305 (unsigned long) &lum
->u
,
1309 if (args
.counter_shm
.shm_fd
>= 0) {
1312 lttng_ust_lock_fd_tracker();
1313 close_ret
= close(args
.counter_shm
.shm_fd
);
1314 lttng_ust_unlock_fd_tracker();
1315 args
.counter_shm
.shm_fd
= -1;
1321 case LTTNG_UST_ABI_COUNTER_CPU
:
1323 /* Receive shm_fd */
1324 ret
= ustcomm_recv_counter_shm_from_sessiond(sock
,
1325 &args
.counter_shm
.shm_fd
);
1331 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1332 (unsigned long) &lum
->u
,
1336 if (args
.counter_shm
.shm_fd
>= 0) {
1339 lttng_ust_lock_fd_tracker();
1340 close_ret
= close(args
.counter_shm
.shm_fd
);
1341 lttng_ust_unlock_fd_tracker();
1342 args
.counter_shm
.shm_fd
= -1;
1348 case LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
:
1350 /* Receive struct lttng_ust_event_notifier */
1351 struct lttng_ust_abi_event_notifier event_notifier
;
1353 if (sizeof(event_notifier
) != lum
->u
.event_notifier
.len
) {
1354 DBG("incorrect event notifier data message size: %u", lum
->u
.event_notifier
.len
);
1358 len
= ustcomm_recv_unix_sock(sock
, &event_notifier
, sizeof(event_notifier
));
1360 case 0: /* orderly shutdown */
1364 if (len
== sizeof(event_notifier
)) {
1365 DBG("event notifier data received");
1367 } else if (len
< 0) {
1368 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1369 if (len
== -ECONNRESET
) {
1370 ERR("%s remote end closed connection", sock_info
->name
);
1377 DBG("incorrect event notifier data message size: %zd", len
);
1383 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1384 (unsigned long) &event_notifier
,
1393 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1394 (unsigned long) &lum
->u
,
1401 prepare_cmd_reply(&lur
, lum
->handle
, lum
->cmd
, ret
);
1405 case LTTNG_UST_ABI_TRACER_VERSION
:
1406 lur
.u
.version
= lum
->u
.version
;
1408 case LTTNG_UST_ABI_TRACEPOINT_LIST_GET
:
1409 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
1413 DBG("Return value: %d", lur
.ret_val
);
1418 * Performed delayed statedump operations outside of the UST
1419 * lock. We need to take the dynamic loader lock before we take
1420 * the UST lock internally within handle_pending_statedump().
1422 handle_pending_statedump(sock_info
);
1425 ret
= -LTTNG_UST_ERR_EXITING
;
1429 ret
= send_reply(sock
, &lur
);
1431 DBG("error sending reply");
1436 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1439 if (lur
.ret_code
== LTTNG_UST_OK
) {
1441 case LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET
:
1442 len
= ustcomm_send_unix_sock(sock
,
1443 &args
.field_list
.entry
,
1444 sizeof(args
.field_list
.entry
));
1449 if (len
!= sizeof(args
.field_list
.entry
)) {
1463 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
1467 if (sock_info
->root_handle
!= -1) {
1468 ret
= lttng_ust_abi_objd_unref(sock_info
->root_handle
, 1);
1470 ERR("Error unref root handle");
1472 sock_info
->root_handle
= -1;
1477 * wait_shm_mmap, socket and notify socket are used by listener
1478 * threads outside of the ust lock, so we cannot tear them down
1479 * ourselves, because we cannot join on these threads. Leave
1480 * responsibility of cleaning up these resources to the OS
1486 sock_info
->registration_done
= 0;
1487 sock_info
->initial_statedump_done
= 0;
1489 if (sock_info
->socket
!= -1) {
1490 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1492 ERR("Error closing ust cmd socket");
1494 sock_info
->socket
= -1;
1496 if (sock_info
->notify_socket
!= -1) {
1497 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1499 ERR("Error closing ust notify socket");
1501 sock_info
->notify_socket
= -1;
1503 if (sock_info
->wait_shm_mmap
) {
1506 page_size
= LTTNG_UST_PAGE_SIZE
;
1507 if (page_size
<= 0) {
1511 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1513 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
1515 ERR("Error unmapping wait shm");
1518 sock_info
->wait_shm_mmap
= NULL
;
1523 * Using fork to set umask in the child process (not multi-thread safe).
1524 * We deal with the shm_open vs ftruncate race (happening when the
1525 * sessiond owns the shm and does not let everybody modify it, to ensure
1526 * safety against shm_unlink) by simply letting the mmap fail and
1527 * retrying after a few seconds.
1528 * For global shm, everybody has rw access to it until the sessiond
1532 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
1534 int wait_shm_fd
, ret
;
1538 * Try to open read-only.
1540 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1541 if (wait_shm_fd
>= 0) {
1544 size_t bytes_read
= 0;
1547 * Try to read the fd. If unable to do so, try opening
1551 len
= read(wait_shm_fd
,
1552 &((char *) &tmp_read
)[bytes_read
],
1553 sizeof(tmp_read
) - bytes_read
);
1557 } while ((len
< 0 && errno
== EINTR
)
1558 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
1559 if (bytes_read
!= sizeof(tmp_read
)) {
1560 ret
= close(wait_shm_fd
);
1562 ERR("close wait_shm_fd");
1567 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
1569 * Real-only open did not work, and it's not because the
1570 * entry was not present. It's a failure that prohibits
1573 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1579 * If the open failed because the file did not exist, or because
1580 * the file was not truncated yet, try creating it ourself.
1582 URCU_TLS(lttng_ust_nest_count
)++;
1584 URCU_TLS(lttng_ust_nest_count
)--;
1586 int status
, wait_ret
;
1589 * Parent: wait for child to return, in which case the
1590 * shared memory map will have been created.
1592 wait_ret
= waitpid(pid
, &status
, 0);
1593 if (wait_ret
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
1598 * Try to open read-only again after creation.
1600 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1601 if (wait_shm_fd
< 0) {
1603 * Real-only open did not work. It's a failure
1604 * that prohibits using shm.
1606 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1610 } else if (pid
== 0) {
1614 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
1615 if (sock_info
->global
)
1616 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
1618 * We're alone in a child process, so we can modify the
1619 * process-wide umask.
1621 umask(~create_mode
);
1623 * Try creating shm (or get rw access).
1624 * We don't do an exclusive open, because we allow other
1625 * processes to create+ftruncate it concurrently.
1627 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
1628 O_RDWR
| O_CREAT
, create_mode
);
1629 if (wait_shm_fd
>= 0) {
1630 ret
= ftruncate(wait_shm_fd
, mmap_size
);
1632 PERROR("ftruncate");
1633 _exit(EXIT_FAILURE
);
1635 _exit(EXIT_SUCCESS
);
1638 * For local shm, we need to have rw access to accept
1639 * opening it: this means the local sessiond will be
1640 * able to wake us up. For global shm, we open it even
1641 * if rw access is not granted, because the root.root
1642 * sessiond will be able to override all rights and wake
1645 if (!sock_info
->global
&& errno
!= EACCES
) {
1646 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1647 _exit(EXIT_FAILURE
);
1650 * The shm exists, but we cannot open it RW. Report
1653 _exit(EXIT_SUCCESS
);
1658 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
1659 struct stat statbuf
;
1662 * Ensure that our user is the owner of the shm file for
1663 * local shm. If we do not own the file, it means our
1664 * sessiond will not have access to wake us up (there is
1665 * probably a rogue process trying to fake our
1666 * sessiond). Fallback to polling method in this case.
1668 ret
= fstat(wait_shm_fd
, &statbuf
);
1673 if (statbuf
.st_uid
!= getuid())
1679 ret
= close(wait_shm_fd
);
1681 PERROR("Error closing fd");
1687 char *get_map_shm(struct sock_info
*sock_info
)
1690 int wait_shm_fd
, ret
;
1691 char *wait_shm_mmap
;
1693 page_size
= sysconf(_SC_PAGE_SIZE
);
1694 if (page_size
<= 0) {
1698 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1702 lttng_ust_lock_fd_tracker();
1703 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1704 if (wait_shm_fd
< 0) {
1705 lttng_ust_unlock_fd_tracker();
1709 ret
= lttng_ust_add_fd_to_tracker(wait_shm_fd
);
1711 ret
= close(wait_shm_fd
);
1713 PERROR("Error closing fd");
1715 lttng_ust_unlock_fd_tracker();
1720 lttng_ust_unlock_fd_tracker();
1722 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1723 MAP_SHARED
, wait_shm_fd
, 0);
1725 /* close shm fd immediately after taking the mmap reference */
1726 lttng_ust_lock_fd_tracker();
1727 ret
= close(wait_shm_fd
);
1729 lttng_ust_delete_fd_from_tracker(wait_shm_fd
);
1731 PERROR("Error closing fd");
1733 lttng_ust_unlock_fd_tracker();
1735 if (wait_shm_mmap
== MAP_FAILED
) {
1736 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1739 return wait_shm_mmap
;
1746 void wait_for_sessiond(struct sock_info
*sock_info
)
1748 /* Use ust_lock to check if we should quit. */
1752 if (wait_poll_fallback
) {
1757 assert(sock_info
->wait_shm_mmap
);
1759 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1760 /* Wait for futex wakeup */
1761 while (!uatomic_read((int32_t *) sock_info
->wait_shm_mmap
)) {
1762 if (!lttng_ust_futex_async((int32_t *) sock_info
->wait_shm_mmap
, FUTEX_WAIT
, 0, NULL
, NULL
, 0)) {
1764 * Prior queued wakeups queued by unrelated code
1765 * using the same address can cause futex wait to
1766 * return 0 even through the futex value is still
1767 * 0 (spurious wakeups). Check the value again
1768 * in user-space to validate whether it really
1775 /* Value already changed. */
1778 /* Retry if interrupted by signal. */
1779 break; /* Get out of switch. Check again. */
1781 wait_poll_fallback
= 1;
1783 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1784 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1785 "Please upgrade your kernel "
1786 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1787 "mainline). LTTng-UST will use polling mode fallback.");
1788 if (lttng_ust_logging_debug_enabled())
1806 * This thread does not allocate any resource, except within
1807 * handle_message, within mutex protection. This mutex protects against
1809 * The other moment it allocates resources is at socket connection, which
1810 * is also protected by the mutex.
1813 void *ust_listener_thread(void *arg
)
1815 struct sock_info
*sock_info
= arg
;
1816 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0, fd
;
1819 lttng_ust_alloc_tls();
1821 * If available, add '-ust' to the end of this thread's
1824 ret
= lttng_ust_setustprocname();
1826 ERR("Unable to set UST process name");
1829 /* Restart trying to connect to the session daemon */
1831 if (prev_connect_failed
) {
1832 /* Wait for sessiond availability with pipe */
1833 wait_for_sessiond(sock_info
);
1837 * Sleep for 5 seconds before retrying after a
1838 * sequence of failure / wait / failure. This
1839 * deals with a killed or broken session daemon.
1845 prev_connect_failed
= 0;
1852 if (sock_info
->socket
!= -1) {
1853 /* FD tracker is updated by ustcomm_close_unix_sock() */
1854 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1856 ERR("Error closing %s ust cmd socket",
1859 sock_info
->socket
= -1;
1861 if (sock_info
->notify_socket
!= -1) {
1862 /* FD tracker is updated by ustcomm_close_unix_sock() */
1863 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1865 ERR("Error closing %s ust notify socket",
1868 sock_info
->notify_socket
= -1;
1873 * Register. We need to perform both connect and sending
1874 * registration message before doing the next connect otherwise
1875 * we may reach unix socket connect queue max limits and block
1876 * on the 2nd connect while the session daemon is awaiting the
1877 * first connect registration message.
1879 /* Connect cmd socket */
1880 lttng_ust_lock_fd_tracker();
1881 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
,
1882 get_connect_sock_timeout());
1884 lttng_ust_unlock_fd_tracker();
1885 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1886 prev_connect_failed
= 1;
1889 * If we cannot find the sessiond daemon, don't delay
1890 * constructor execution.
1892 ret
= handle_register_failed(sock_info
);
1898 ret
= lttng_ust_add_fd_to_tracker(fd
);
1902 PERROR("close on sock_info->socket");
1905 lttng_ust_unlock_fd_tracker();
1910 sock_info
->socket
= ret
;
1911 lttng_ust_unlock_fd_tracker();
1915 * Unlock/relock ust lock because connect is blocking (with
1916 * timeout). Don't delay constructors on the ust lock for too
1924 * Create only one root handle per listener thread for the whole
1925 * process lifetime, so we ensure we get ID which is statically
1926 * assigned to the root handle.
1928 if (sock_info
->root_handle
== -1) {
1929 ret
= lttng_abi_create_root_handle();
1931 ERR("Error creating root handle");
1934 sock_info
->root_handle
= ret
;
1937 ret
= register_to_sessiond(sock_info
->socket
, LTTNG_UST_CTL_SOCKET_CMD
,
1938 sock_info
->procname
);
1940 ERR("Error registering to %s ust cmd socket",
1942 prev_connect_failed
= 1;
1944 * If we cannot register to the sessiond daemon, don't
1945 * delay constructor execution.
1947 ret
= handle_register_failed(sock_info
);
1955 * Unlock/relock ust lock because connect is blocking (with
1956 * timeout). Don't delay constructors on the ust lock for too
1963 /* Connect notify socket */
1964 lttng_ust_lock_fd_tracker();
1965 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
,
1966 get_connect_sock_timeout());
1968 lttng_ust_unlock_fd_tracker();
1969 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1970 prev_connect_failed
= 1;
1973 * If we cannot find the sessiond daemon, don't delay
1974 * constructor execution.
1976 ret
= handle_register_failed(sock_info
);
1983 ret
= lttng_ust_add_fd_to_tracker(fd
);
1987 PERROR("close on sock_info->notify_socket");
1990 lttng_ust_unlock_fd_tracker();
1995 sock_info
->notify_socket
= ret
;
1996 lttng_ust_unlock_fd_tracker();
2000 * Unlock/relock ust lock because connect is blocking (with
2001 * timeout). Don't delay constructors on the ust lock for too
2008 timeout
= get_notify_sock_timeout();
2011 * Give at least 10ms to sessiond to reply to
2016 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
2019 WARN("Error setting socket receive timeout");
2021 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
2024 WARN("Error setting socket send timeout");
2026 } else if (timeout
< -1) {
2027 WARN("Unsupported timeout value %ld", timeout
);
2030 ret
= register_to_sessiond(sock_info
->notify_socket
,
2031 LTTNG_UST_CTL_SOCKET_NOTIFY
, sock_info
->procname
);
2033 ERR("Error registering to %s ust notify socket",
2035 prev_connect_failed
= 1;
2037 * If we cannot register to the sessiond daemon, don't
2038 * delay constructor execution.
2040 ret
= handle_register_failed(sock_info
);
2045 sock
= sock_info
->socket
;
2051 struct ustcomm_ust_msg lum
;
2053 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
2055 case 0: /* orderly shutdown */
2056 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
2061 * Either sessiond has shutdown or refused us by closing the socket.
2062 * In either case, we don't want to delay construction execution,
2063 * and we need to wait before retry.
2065 prev_connect_failed
= 1;
2067 * If we cannot register to the sessiond daemon, don't
2068 * delay constructor execution.
2070 ret
= handle_register_failed(sock_info
);
2075 print_cmd(lum
.cmd
, lum
.handle
);
2076 ret
= handle_message(sock_info
, sock
, &lum
);
2078 ERR("Error handling message for %s socket",
2081 * Close socket if protocol error is
2089 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
2091 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
2093 if (len
== -ECONNRESET
) {
2094 DBG("%s remote end closed connection", sock_info
->name
);
2105 /* Cleanup socket handles before trying to reconnect */
2106 lttng_ust_abi_objd_table_owner_cleanup(sock_info
);
2108 goto restart
; /* try to reconnect */
2113 pthread_mutex_lock(&ust_exit_mutex
);
2114 sock_info
->thread_active
= 0;
2115 pthread_mutex_unlock(&ust_exit_mutex
);
2120 * Weak symbol to call when the ust malloc wrapper is not loaded.
2122 __attribute__((weak
))
2123 void lttng_ust_libc_wrapper_malloc_ctor(void)
2128 * Use a symbol of the previous ABI to detect if liblttng-ust.so.0 is loaded in
2129 * the current process.
2131 #define LTTNG_UST_SONAME_0_SYM "ltt_probe_register"
2134 void lttng_ust_check_soname_0(void)
2136 if (!dlsym(RTLD_DEFAULT
, LTTNG_UST_SONAME_0_SYM
))
2139 CRIT("Incompatible library ABIs detected within the same process. "
2140 "The process is likely linked against different major soname of LTTng-UST which is unsupported. "
2141 "The detection was triggered by lookup of ABI 0 symbol \"%s\" in the Global Symbol Table\n",
2142 LTTNG_UST_SONAME_0_SYM
);
2146 * Expose a canary symbol of the previous ABI to ensure we catch uses of a
2147 * liblttng-ust.so.0 dlopen'd after .so.1 has been loaded. Use a different
2148 * symbol than the detection code to ensure we don't detect ourself.
2150 * This scheme will only work on systems where the global symbol table has
2151 * priority when resolving the symbols of a dlopened shared object, which is
2152 * the case on Linux but not on FreeBSD.
2154 void init_usterr(void);
2155 void init_usterr(void)
2157 CRIT("Incompatible library ABIs detected within the same process. "
2158 "The process is likely linked against different major soname of LTTng-UST which is unsupported. "
2159 "The detection was triggered by canary symbol \"%s\"\n", __func__
);
2163 * sessiond monitoring thread: monitor presence of global and per-user
2164 * sessiond by polling the application common named pipe.
2167 void lttng_ust_ctor(void)
2168 __attribute__((constructor
));
2170 void lttng_ust_ctor(void)
2172 struct timespec constructor_timeout
;
2173 sigset_t sig_all_blocked
, orig_parent_mask
;
2174 pthread_attr_t thread_attr
;
2179 if (uatomic_xchg(&initialized
, 1) == 1)
2183 * Fixup interdependency between TLS allocation mutex (which happens
2184 * to be the dynamic linker mutex) and ust_lock, taken within
2187 lttng_ust_alloc_tls();
2189 lttng_ust_loaded_orig
= 1;
2192 * Check if we find a symbol of the previous ABI in the current process
2193 * as different ABIs of liblttng-ust can't co-exist in a process. If we
2194 * do so, emit a critical log message which will also abort if the
2195 * LTTNG_UST_ABORT_ON_CRITICAL environment variable is set.
2197 lttng_ust_check_soname_0();
2200 * We need to ensure that the liblttng-ust library is not unloaded to avoid
2201 * the unloading of code used by the ust_listener_threads as we can not
2202 * reliably know when they exited. To do that, manually load
2203 * liblttng-ust.so to increment the dynamic loader's internal refcount for
2204 * this library so it never becomes zero, thus never gets unloaded from the
2205 * address space of the process. Since we are already running in the
2206 * constructor of the LTTNG_UST_LIB_SONAME library, calling dlopen will
2207 * simply increment the refcount and no additionnal work is needed by the
2208 * dynamic loader as the shared library is already loaded in the address
2209 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
2210 * unloading of the UST library if its refcount becomes zero (which should
2211 * never happen). Do the return value check but discard the handle at the
2212 * end of the function as it's not needed.
2214 handle
= dlopen(LTTNG_UST_LIB_SONAME
, RTLD_LAZY
| RTLD_NODELETE
);
2216 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME
);
2218 DBG("dlopened liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME
);
2222 * We want precise control over the order in which we construct
2223 * our sub-libraries vs starting to receive commands from
2224 * sessiond (otherwise leading to errors when trying to create
2225 * sessiond before the init functions are completed).
2229 * Both the logging and getenv lazy-initialization uses getenv()
2230 * internally and thus needs to be explicitly initialized in
2231 * liblttng-ust before we start any threads as an unsuspecting normally
2232 * single threaded application using liblttng-ust could be using
2233 * setenv() which is not thread-safe.
2235 lttng_ust_logging_init();
2236 lttng_ust_getenv_init();
2238 /* Call the liblttng-ust-common constructor. */
2239 lttng_ust_common_ctor();
2241 lttng_ust_tp_init();
2242 lttng_ust_statedump_init();
2243 lttng_ust_ring_buffer_clients_init();
2244 lttng_ust_counter_clients_init();
2245 lttng_perf_counter_init();
2247 * Invoke ust malloc wrapper init before starting other threads.
2249 lttng_ust_libc_wrapper_malloc_ctor();
2251 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
2253 get_allow_blocking();
2255 ret
= sem_init(&constructor_wait
, 0, 0);
2260 ret
= setup_global_apps();
2262 assert(global_apps
.allowed
== 0);
2263 DBG("global apps setup returned %d", ret
);
2266 ret
= setup_local_apps();
2268 assert(local_apps
.allowed
== 0);
2269 DBG("local apps setup returned %d", ret
);
2272 /* A new thread created by pthread_create inherits the signal mask
2273 * from the parent. To avoid any signal being received by the
2274 * listener thread, we block all signals temporarily in the parent,
2275 * while we create the listener thread.
2277 sigfillset(&sig_all_blocked
);
2278 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
2280 ERR("pthread_sigmask: %s", strerror(ret
));
2283 ret
= pthread_attr_init(&thread_attr
);
2285 ERR("pthread_attr_init: %s", strerror(ret
));
2287 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
2289 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
2292 if (global_apps
.allowed
) {
2293 pthread_mutex_lock(&ust_exit_mutex
);
2294 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
2295 ust_listener_thread
, &global_apps
);
2297 ERR("pthread_create global: %s", strerror(ret
));
2299 global_apps
.thread_active
= 1;
2300 pthread_mutex_unlock(&ust_exit_mutex
);
2302 handle_register_done(&global_apps
);
2305 if (local_apps
.allowed
) {
2306 pthread_mutex_lock(&ust_exit_mutex
);
2307 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
2308 ust_listener_thread
, &local_apps
);
2310 ERR("pthread_create local: %s", strerror(ret
));
2312 local_apps
.thread_active
= 1;
2313 pthread_mutex_unlock(&ust_exit_mutex
);
2315 handle_register_done(&local_apps
);
2317 ret
= pthread_attr_destroy(&thread_attr
);
2319 ERR("pthread_attr_destroy: %s", strerror(ret
));
2322 /* Restore original signal mask in parent */
2323 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
2325 ERR("pthread_sigmask: %s", strerror(ret
));
2328 switch (timeout_mode
) {
2329 case 1: /* timeout wait */
2331 ret
= sem_timedwait(&constructor_wait
,
2332 &constructor_timeout
);
2333 } while (ret
< 0 && errno
== EINTR
);
2337 ERR("Timed out waiting for lttng-sessiond");
2340 PERROR("sem_timedwait");
2343 ERR("Unexpected error \"%s\" returned by sem_timedwait",
2348 case -1:/* wait forever */
2350 ret
= sem_wait(&constructor_wait
);
2351 } while (ret
< 0 && errno
== EINTR
);
2358 ERR("Unexpected error \"%s\" returned by sem_wait",
2363 case 0: /* no timeout */
2369 void lttng_ust_cleanup(int exiting
)
2371 cleanup_sock_info(&global_apps
, exiting
);
2372 cleanup_sock_info(&local_apps
, exiting
);
2373 local_apps
.allowed
= 0;
2374 global_apps
.allowed
= 0;
2376 * The teardown in this function all affect data structures
2377 * accessed under the UST lock by the listener thread. This
2378 * lock, along with the lttng_ust_comm_should_quit flag, ensure
2379 * that none of these threads are accessing this data at this
2382 lttng_ust_abi_exit();
2383 lttng_ust_abi_events_exit();
2384 lttng_perf_counter_exit();
2385 lttng_ust_ring_buffer_clients_exit();
2386 lttng_ust_counter_clients_exit();
2387 lttng_ust_statedump_destroy();
2388 lttng_ust_tp_exit();
2390 /* Reinitialize values for fork */
2391 sem_count
= sem_count_initial_value
;
2392 lttng_ust_comm_should_quit
= 0;
2398 void lttng_ust_exit(void)
2399 __attribute__((destructor
));
2401 void lttng_ust_exit(void)
2406 * Using pthread_cancel here because:
2407 * A) we don't want to hang application teardown.
2408 * B) the thread is not allocating any resource.
2412 * Require the communication thread to quit. Synchronize with
2413 * mutexes to ensure it is not in a mutex critical section when
2414 * pthread_cancel is later called.
2417 lttng_ust_comm_should_quit
= 1;
2420 pthread_mutex_lock(&ust_exit_mutex
);
2421 /* cancel threads */
2422 if (global_apps
.thread_active
) {
2423 ret
= pthread_cancel(global_apps
.ust_listener
);
2425 ERR("Error cancelling global ust listener thread: %s",
2428 global_apps
.thread_active
= 0;
2431 if (local_apps
.thread_active
) {
2432 ret
= pthread_cancel(local_apps
.ust_listener
);
2434 ERR("Error cancelling local ust listener thread: %s",
2437 local_apps
.thread_active
= 0;
2440 pthread_mutex_unlock(&ust_exit_mutex
);
2443 * Do NOT join threads: use of sys_futex makes it impossible to
2444 * join the threads without using async-cancel, but async-cancel
2445 * is delivered by a signal, which could hit the target thread
2446 * anywhere in its code path, including while the ust_lock() is
2447 * held, causing a deadlock for the other thread. Let the OS
2448 * cleanup the threads if there are stalled in a syscall.
2450 lttng_ust_cleanup(1);
2454 void ust_context_ns_reset(void)
2456 lttng_context_pid_ns_reset();
2457 lttng_context_cgroup_ns_reset();
2458 lttng_context_ipc_ns_reset();
2459 lttng_context_mnt_ns_reset();
2460 lttng_context_net_ns_reset();
2461 lttng_context_user_ns_reset();
2462 lttng_context_time_ns_reset();
2463 lttng_context_uts_ns_reset();
2467 void ust_context_vuids_reset(void)
2469 lttng_context_vuid_reset();
2470 lttng_context_veuid_reset();
2471 lttng_context_vsuid_reset();
2475 void ust_context_vgids_reset(void)
2477 lttng_context_vgid_reset();
2478 lttng_context_vegid_reset();
2479 lttng_context_vsgid_reset();
2483 * We exclude the worker threads across fork and clone (except
2484 * CLONE_VM), because these system calls only keep the forking thread
2485 * running in the child. Therefore, we don't want to call fork or clone
2486 * in the middle of an tracepoint or ust tracing state modification.
2487 * Holding this mutex protects these structures across fork and clone.
2489 void lttng_ust_before_fork(sigset_t
*save_sigset
)
2492 * Disable signals. This is to avoid that the child intervenes
2493 * before it is properly setup for tracing. It is safer to
2494 * disable all signals, because then we know we are not breaking
2495 * anything by restoring the original mask.
2500 /* Allocate lttng-ust TLS. */
2501 lttng_ust_alloc_tls();
2503 if (URCU_TLS(lttng_ust_nest_count
))
2505 /* Disable signals */
2506 sigfillset(&all_sigs
);
2507 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
2509 PERROR("sigprocmask");
2512 pthread_mutex_lock(&ust_fork_mutex
);
2515 lttng_ust_urcu_before_fork();
2516 lttng_ust_lock_fd_tracker();
2520 static void ust_after_fork_common(sigset_t
*restore_sigset
)
2524 DBG("process %d", getpid());
2525 lttng_perf_unlock();
2526 lttng_ust_unlock_fd_tracker();
2529 pthread_mutex_unlock(&ust_fork_mutex
);
2531 /* Restore signals */
2532 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
2534 PERROR("sigprocmask");
2538 void lttng_ust_after_fork_parent(sigset_t
*restore_sigset
)
2540 if (URCU_TLS(lttng_ust_nest_count
))
2542 DBG("process %d", getpid());
2543 lttng_ust_urcu_after_fork_parent();
2544 /* Release mutexes and reenable signals */
2545 ust_after_fork_common(restore_sigset
);
2549 * After fork, in the child, we need to cleanup all the leftover state,
2550 * except the worker thread which already magically disappeared thanks
2551 * to the weird Linux fork semantics. After tyding up, we call
2552 * lttng_ust_ctor() again to start over as a new PID.
2554 * This is meant for forks() that have tracing in the child between the
2555 * fork and following exec call (if there is any).
2557 void lttng_ust_after_fork_child(sigset_t
*restore_sigset
)
2559 if (URCU_TLS(lttng_ust_nest_count
))
2561 lttng_context_vpid_reset();
2562 lttng_context_vtid_reset();
2563 lttng_ust_context_procname_reset();
2564 ust_context_ns_reset();
2565 ust_context_vuids_reset();
2566 ust_context_vgids_reset();
2567 DBG("process %d", getpid());
2568 /* Release urcu mutexes */
2569 lttng_ust_urcu_after_fork_child();
2570 lttng_ust_cleanup(0);
2571 /* Release mutexes and reenable signals */
2572 ust_after_fork_common(restore_sigset
);
2576 void lttng_ust_after_setns(void)
2578 ust_context_ns_reset();
2579 ust_context_vuids_reset();
2580 ust_context_vgids_reset();
2583 void lttng_ust_after_unshare(void)
2585 ust_context_ns_reset();
2586 ust_context_vuids_reset();
2587 ust_context_vgids_reset();
2590 void lttng_ust_after_setuid(void)
2592 ust_context_vuids_reset();
2595 void lttng_ust_after_seteuid(void)
2597 ust_context_vuids_reset();
2600 void lttng_ust_after_setreuid(void)
2602 ust_context_vuids_reset();
2605 void lttng_ust_after_setresuid(void)
2607 ust_context_vuids_reset();
2610 void lttng_ust_after_setgid(void)
2612 ust_context_vgids_reset();
2615 void lttng_ust_after_setegid(void)
2617 ust_context_vgids_reset();
2620 void lttng_ust_after_setregid(void)
2622 ust_context_vgids_reset();
2625 void lttng_ust_after_setresgid(void)
2627 ust_context_vgids_reset();
2630 void lttng_ust_sockinfo_session_enabled(void *owner
)
2632 struct sock_info
*sock_info
= owner
;
2633 sock_info
->statedump_pending
= 1;
2636 /* Custom upgrade 2.12 to 2.13 */
2637 extern int lttng_ust_loaded1
__attribute__((weak
, alias("lttng_ust_loaded_orig")));
2639 #ifdef LTTNG_UST_CUSTOM_UPGRADE_CONFLICTING_SYMBOLS
2640 extern int lttng_ust_loaded
__attribute__((weak
, alias("lttng_ust_loaded_orig")));