2 * SPDX-License-Identifier: LGPL-2.1-only
4 * Copyright (C) 2011 David Goulet <david.goulet@polymtl.ca>
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 <urcu/tls-compat.h>
42 #include "lib/lttng-ust/futex.h"
43 #include "common/ustcomm.h"
44 #include "common/ust-fd.h"
45 #include "common/logging.h"
46 #include "common/macros.h"
47 #include "common/tracepoint.h"
48 #include "lttng-tracer-core.h"
49 #include "common/compat/pthread.h"
50 #include "common/procname.h"
51 #include "common/ringbuffer/rb-init.h"
52 #include "lttng-ust-statedump.h"
53 #include "common/clock.h"
54 #include "common/getenv.h"
55 #include "lib/lttng-ust/events.h"
56 #include "context-internal.h"
57 #include "common/align.h"
58 #include "common/counter-clients/clients.h"
59 #include "common/ringbuffer-clients/clients.h"
62 * Has lttng ust comm constructor been called ?
64 static int initialized
;
67 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
68 * Held when handling a command, also held by fork() to deal with
69 * removal of threads, and by exit path.
71 * The UST lock is the centralized mutex across UST tracing control and
74 * ust_exit_mutex must never nest in ust_mutex.
76 * ust_fork_mutex must never nest in ust_mutex.
78 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
79 * counter lazy initialization called by events within the statedump,
80 * which traces while the ust_mutex is held.
82 * ust_lock nests within the dynamic loader lock (within glibc) because
83 * it is taken within the library constructor.
85 * The ust fd tracker lock nests within the ust_mutex.
87 static pthread_mutex_t ust_mutex
= PTHREAD_MUTEX_INITIALIZER
;
89 /* Allow nesting the ust_mutex within the same thread. */
90 static DEFINE_URCU_TLS(int, ust_mutex_nest
);
93 * ust_exit_mutex protects thread_active variable wrt thread exit. It
94 * cannot be done by ust_mutex because pthread_cancel(), which takes an
95 * internal libc lock, cannot nest within ust_mutex.
97 * It never nests within a ust_mutex.
99 static pthread_mutex_t ust_exit_mutex
= PTHREAD_MUTEX_INITIALIZER
;
102 * ust_fork_mutex protects base address statedump tracing against forks. It
103 * prevents the dynamic loader lock to be taken (by base address statedump
104 * tracing) while a fork is happening, thus preventing deadlock issues with
105 * the dynamic loader lock.
107 static pthread_mutex_t ust_fork_mutex
= PTHREAD_MUTEX_INITIALIZER
;
109 /* Should the ust comm thread quit ? */
110 static int lttng_ust_comm_should_quit
;
113 * This variable can be tested by applications to check whether
114 * lttng-ust is loaded. They simply have to define their own
115 * "lttng_ust_loaded" weak symbol, and test it. It is set to 1 by the
116 * library constructor.
118 int lttng_ust_loaded
__attribute__((weak
));
121 * Return 0 on success, -1 if should quit.
122 * The lock is taken in both cases.
127 sigset_t sig_all_blocked
, orig_mask
;
130 ret
= pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &oldstate
);
132 ERR("pthread_setcancelstate: %s", strerror(ret
));
134 if (oldstate
!= PTHREAD_CANCEL_ENABLE
) {
135 ERR("pthread_setcancelstate: unexpected oldstate");
137 sigfillset(&sig_all_blocked
);
138 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
140 ERR("pthread_sigmask: %s", strerror(ret
));
142 if (!URCU_TLS(ust_mutex_nest
)++)
143 pthread_mutex_lock(&ust_mutex
);
144 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
146 ERR("pthread_sigmask: %s", strerror(ret
));
148 if (lttng_ust_comm_should_quit
) {
156 * ust_lock_nocheck() can be used in constructors/destructors, because
157 * they are already nested within the dynamic loader lock, and therefore
158 * have exclusive access against execution of liblttng-ust destructor.
161 void ust_lock_nocheck(void)
163 sigset_t sig_all_blocked
, orig_mask
;
166 ret
= pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &oldstate
);
168 ERR("pthread_setcancelstate: %s", strerror(ret
));
170 if (oldstate
!= PTHREAD_CANCEL_ENABLE
) {
171 ERR("pthread_setcancelstate: unexpected oldstate");
173 sigfillset(&sig_all_blocked
);
174 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
176 ERR("pthread_sigmask: %s", strerror(ret
));
178 if (!URCU_TLS(ust_mutex_nest
)++)
179 pthread_mutex_lock(&ust_mutex
);
180 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
182 ERR("pthread_sigmask: %s", strerror(ret
));
189 void ust_unlock(void)
191 sigset_t sig_all_blocked
, orig_mask
;
194 sigfillset(&sig_all_blocked
);
195 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_mask
);
197 ERR("pthread_sigmask: %s", strerror(ret
));
199 if (!--URCU_TLS(ust_mutex_nest
))
200 pthread_mutex_unlock(&ust_mutex
);
201 ret
= pthread_sigmask(SIG_SETMASK
, &orig_mask
, NULL
);
203 ERR("pthread_sigmask: %s", strerror(ret
));
205 ret
= pthread_setcancelstate(PTHREAD_CANCEL_ENABLE
, &oldstate
);
207 ERR("pthread_setcancelstate: %s", strerror(ret
));
209 if (oldstate
!= PTHREAD_CANCEL_DISABLE
) {
210 ERR("pthread_setcancelstate: unexpected oldstate");
215 * Wait for either of these before continuing to the main
217 * - the register_done message from sessiond daemon
218 * (will let the sessiond daemon enable sessions before main
220 * - sessiond daemon is not reachable.
221 * - timeout (ensuring applications are resilient to session
224 static sem_t constructor_wait
;
226 * Doing this for both the global and local sessiond.
229 sem_count_initial_value
= 4,
232 static int sem_count
= sem_count_initial_value
;
235 * Counting nesting within lttng-ust. Used to ensure that calling fork()
236 * from liblttng-ust does not execute the pre/post fork handlers.
238 static DEFINE_URCU_TLS(int, lttng_ust_nest_count
);
241 * Info about socket and associated listener thread.
245 pthread_t ust_listener
; /* listener thread */
247 int registration_done
;
252 char sock_path
[PATH_MAX
];
256 char wait_shm_path
[PATH_MAX
];
258 /* Keep track of lazy state dump not performed yet. */
259 int statedump_pending
;
260 int initial_statedump_done
;
261 /* Keep procname for statedump */
262 char procname
[LTTNG_UST_ABI_PROCNAME_LEN
];
265 /* Socket from app (connect) to session daemon (listen) for communication */
266 static struct sock_info global_apps
= {
271 .registration_done
= 0,
275 .sock_path
= LTTNG_DEFAULT_RUNDIR
"/" LTTNG_UST_SOCK_FILENAME
,
279 .wait_shm_path
= "/" LTTNG_UST_WAIT_FILENAME
,
281 .statedump_pending
= 0,
282 .initial_statedump_done
= 0,
286 /* TODO: allow global_apps_sock_path override */
288 static struct sock_info local_apps
= {
292 .registration_done
= 0,
293 .allowed
= 0, /* Check setuid bit first */
299 .statedump_pending
= 0,
300 .initial_statedump_done
= 0,
304 static int wait_poll_fallback
;
306 static const char *cmd_name_mapping
[] = {
307 [ LTTNG_UST_ABI_RELEASE
] = "Release",
308 [ LTTNG_UST_ABI_SESSION
] = "Create Session",
309 [ LTTNG_UST_ABI_TRACER_VERSION
] = "Get Tracer Version",
311 [ LTTNG_UST_ABI_TRACEPOINT_LIST
] = "Create Tracepoint List",
312 [ LTTNG_UST_ABI_WAIT_QUIESCENT
] = "Wait for Quiescent State",
313 [ LTTNG_UST_ABI_REGISTER_DONE
] = "Registration Done",
314 [ LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST
] = "Create Tracepoint Field List",
316 [ LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
] = "Create event notifier group",
318 /* Session FD commands */
319 [ LTTNG_UST_ABI_CHANNEL
] = "Create Channel",
320 [ LTTNG_UST_ABI_SESSION_START
] = "Start Session",
321 [ LTTNG_UST_ABI_SESSION_STOP
] = "Stop Session",
323 /* Channel FD commands */
324 [ LTTNG_UST_ABI_STREAM
] = "Create Stream",
325 [ LTTNG_UST_ABI_EVENT
] = "Create Event",
327 /* Event and Channel FD commands */
328 [ LTTNG_UST_ABI_CONTEXT
] = "Create Context",
329 [ LTTNG_UST_ABI_FLUSH_BUFFER
] = "Flush Buffer",
331 /* Event, Channel and Session commands */
332 [ LTTNG_UST_ABI_ENABLE
] = "Enable",
333 [ LTTNG_UST_ABI_DISABLE
] = "Disable",
335 /* Tracepoint list commands */
336 [ LTTNG_UST_ABI_TRACEPOINT_LIST_GET
] = "List Next Tracepoint",
337 [ LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET
] = "List Next Tracepoint Field",
339 /* Event FD commands */
340 [ LTTNG_UST_ABI_FILTER
] = "Create Filter",
341 [ LTTNG_UST_ABI_EXCLUSION
] = "Add exclusions to event",
343 /* Event notifier group commands */
344 [ LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
] = "Create event notifier",
346 /* Session and event notifier group commands */
347 [ LTTNG_UST_ABI_COUNTER
] = "Create Counter",
349 /* Counter commands */
350 [ LTTNG_UST_ABI_COUNTER_GLOBAL
] = "Create Counter Global",
351 [ LTTNG_UST_ABI_COUNTER_CPU
] = "Create Counter CPU",
354 static const char *str_timeout
;
355 static int got_timeout_env
;
357 static char *get_map_shm(struct sock_info
*sock_info
);
360 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
364 const char *get_lttng_home_dir(void)
368 val
= (const char *) lttng_ust_getenv("LTTNG_HOME");
372 return (const char *) lttng_ust_getenv("HOME");
376 * Force a read (imply TLS allocation for dlopen) of TLS variables.
379 void lttng_nest_count_alloc_tls(void)
381 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count
)));
385 void lttng_ust_mutex_nest_alloc_tls(void)
387 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest
)));
391 * Allocate lttng-ust urcu TLS.
394 void lttng_lttng_ust_urcu_alloc_tls(void)
396 (void) lttng_ust_urcu_read_ongoing();
399 void lttng_ust_alloc_tls(void)
401 lttng_lttng_ust_urcu_alloc_tls();
402 lttng_ringbuffer_alloc_tls();
403 lttng_vtid_alloc_tls();
404 lttng_nest_count_alloc_tls();
405 lttng_procname_alloc_tls();
406 lttng_ust_mutex_nest_alloc_tls();
407 lttng_ust_perf_counter_alloc_tls();
408 lttng_ust_common_alloc_tls();
409 lttng_cgroup_ns_alloc_tls();
410 lttng_ipc_ns_alloc_tls();
411 lttng_net_ns_alloc_tls();
412 lttng_time_ns_alloc_tls();
413 lttng_uts_ns_alloc_tls();
414 lttng_ust_ring_buffer_client_discard_alloc_tls();
415 lttng_ust_ring_buffer_client_discard_rt_alloc_tls();
416 lttng_ust_ring_buffer_client_overwrite_alloc_tls();
417 lttng_ust_ring_buffer_client_overwrite_rt_alloc_tls();
421 * LTTng-UST uses Global Dynamic model TLS variables rather than IE
422 * model because many versions of glibc don't preallocate a pool large
423 * enough for TLS variables IE model defined in other shared libraries,
424 * and causes issues when using LTTng-UST for Java tracing.
426 * Because of this use of Global Dynamic TLS variables, users wishing to
427 * trace from signal handlers need to explicitly trigger the lazy
428 * allocation of those variables for each thread before using them.
429 * This can be triggered by calling lttng_ust_init_thread().
431 void lttng_ust_init_thread(void)
434 * Because those TLS variables are global dynamic, we need to
435 * ensure those are initialized before a signal handler nesting over
436 * this thread attempts to use them.
438 lttng_ust_alloc_tls();
441 int lttng_get_notify_socket(void *owner
)
443 struct sock_info
*info
= owner
;
445 return info
->notify_socket
;
449 char* lttng_ust_sockinfo_get_procname(void *owner
)
451 struct sock_info
*info
= owner
;
453 return info
->procname
;
457 void print_cmd(int cmd
, int handle
)
459 const char *cmd_name
= "Unknown";
461 if (cmd
>= 0 && cmd
< LTTNG_ARRAY_SIZE(cmd_name_mapping
)
462 && cmd_name_mapping
[cmd
]) {
463 cmd_name
= cmd_name_mapping
[cmd
];
465 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
467 lttng_ust_obj_get_name(handle
), handle
);
471 int setup_global_apps(void)
474 assert(!global_apps
.wait_shm_mmap
);
476 global_apps
.wait_shm_mmap
= get_map_shm(&global_apps
);
477 if (!global_apps
.wait_shm_mmap
) {
478 WARN("Unable to get map shm for global apps. Disabling LTTng-UST global tracing.");
479 global_apps
.allowed
= 0;
484 global_apps
.allowed
= 1;
485 lttng_pthread_getname_np(global_apps
.procname
, LTTNG_UST_ABI_PROCNAME_LEN
);
490 int setup_local_apps(void)
493 const char *home_dir
;
496 assert(!local_apps
.wait_shm_mmap
);
500 * Disallow per-user tracing for setuid binaries.
502 if (uid
!= geteuid()) {
503 assert(local_apps
.allowed
== 0);
507 home_dir
= get_lttng_home_dir();
509 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
510 assert(local_apps
.allowed
== 0);
514 local_apps
.allowed
= 1;
515 snprintf(local_apps
.sock_path
, PATH_MAX
, "%s/%s/%s",
517 LTTNG_DEFAULT_HOME_RUNDIR
,
518 LTTNG_UST_SOCK_FILENAME
);
519 snprintf(local_apps
.wait_shm_path
, PATH_MAX
, "/%s-%u",
520 LTTNG_UST_WAIT_FILENAME
,
523 local_apps
.wait_shm_mmap
= get_map_shm(&local_apps
);
524 if (!local_apps
.wait_shm_mmap
) {
525 WARN("Unable to get map shm for local apps. Disabling LTTng-UST per-user tracing.");
526 local_apps
.allowed
= 0;
531 lttng_pthread_getname_np(local_apps
.procname
, LTTNG_UST_ABI_PROCNAME_LEN
);
537 * Get socket timeout, in ms.
538 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
541 long get_timeout(void)
543 long constructor_delay_ms
= LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS
;
545 if (!got_timeout_env
) {
546 str_timeout
= lttng_ust_getenv("LTTNG_UST_REGISTER_TIMEOUT");
550 constructor_delay_ms
= strtol(str_timeout
, NULL
, 10);
551 /* All negative values are considered as "-1". */
552 if (constructor_delay_ms
< -1)
553 constructor_delay_ms
= -1;
554 return constructor_delay_ms
;
557 /* Timeout for notify socket send and recv. */
559 long get_notify_sock_timeout(void)
561 return get_timeout();
564 /* Timeout for connecting to cmd and notify sockets. */
566 long get_connect_sock_timeout(void)
568 return get_timeout();
572 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
575 int get_constructor_timeout(struct timespec
*constructor_timeout
)
577 long constructor_delay_ms
;
580 constructor_delay_ms
= get_timeout();
582 switch (constructor_delay_ms
) {
583 case -1:/* fall-through */
585 return constructor_delay_ms
;
591 * If we are unable to find the current time, don't wait.
593 ret
= clock_gettime(CLOCK_REALTIME
, constructor_timeout
);
598 constructor_timeout
->tv_sec
+= constructor_delay_ms
/ 1000UL;
599 constructor_timeout
->tv_nsec
+=
600 (constructor_delay_ms
% 1000UL) * 1000000UL;
601 if (constructor_timeout
->tv_nsec
>= 1000000000UL) {
602 constructor_timeout
->tv_sec
++;
603 constructor_timeout
->tv_nsec
-= 1000000000UL;
605 /* Timeout wait (constructor_delay_ms). */
610 void get_allow_blocking(void)
612 const char *str_allow_blocking
=
613 lttng_ust_getenv("LTTNG_UST_ALLOW_BLOCKING");
615 if (str_allow_blocking
) {
616 DBG("%s environment variable is set",
617 "LTTNG_UST_ALLOW_BLOCKING");
618 lttng_ust_ringbuffer_set_allow_blocking();
623 int register_to_sessiond(int socket
, enum lttng_ust_ctl_socket_type type
)
625 return ustcomm_send_reg_msg(socket
,
628 lttng_ust_rb_alignof(uint8_t) * CHAR_BIT
,
629 lttng_ust_rb_alignof(uint16_t) * CHAR_BIT
,
630 lttng_ust_rb_alignof(uint32_t) * CHAR_BIT
,
631 lttng_ust_rb_alignof(uint64_t) * CHAR_BIT
,
632 lttng_ust_rb_alignof(unsigned long) * CHAR_BIT
);
636 int send_reply(int sock
, struct ustcomm_ust_reply
*lur
)
640 len
= ustcomm_send_unix_sock(sock
, lur
, sizeof(*lur
));
643 DBG("message successfully sent");
646 if (len
== -ECONNRESET
) {
647 DBG("remote end closed connection");
652 DBG("incorrect message size: %zd", len
);
658 void decrement_sem_count(unsigned int count
)
662 assert(uatomic_read(&sem_count
) >= count
);
664 if (uatomic_read(&sem_count
) <= 0) {
668 ret
= uatomic_add_return(&sem_count
, -count
);
670 ret
= sem_post(&constructor_wait
);
676 int handle_register_done(struct sock_info
*sock_info
)
678 if (sock_info
->registration_done
)
680 sock_info
->registration_done
= 1;
682 decrement_sem_count(1);
683 if (!sock_info
->statedump_pending
) {
684 sock_info
->initial_statedump_done
= 1;
685 decrement_sem_count(1);
692 int handle_register_failed(struct sock_info
*sock_info
)
694 if (sock_info
->registration_done
)
696 sock_info
->registration_done
= 1;
697 sock_info
->initial_statedump_done
= 1;
699 decrement_sem_count(2);
705 * Only execute pending statedump after the constructor semaphore has
706 * been posted by the current listener thread. This means statedump will
707 * only be performed after the "registration done" command is received
708 * from this thread's session daemon.
710 * This ensures we don't run into deadlock issues with the dynamic
711 * loader mutex, which is held while the constructor is called and
712 * waiting on the constructor semaphore. All operations requiring this
713 * dynamic loader lock need to be postponed using this mechanism.
715 * In a scenario with two session daemons connected to the application,
716 * it is possible that the first listener thread which receives the
717 * registration done command issues its statedump while the dynamic
718 * loader lock is still held by the application constructor waiting on
719 * the semaphore. It will however be allowed to proceed when the
720 * second session daemon sends the registration done command to the
721 * second listener thread. This situation therefore does not produce
725 void handle_pending_statedump(struct sock_info
*sock_info
)
727 if (sock_info
->registration_done
&& sock_info
->statedump_pending
) {
728 sock_info
->statedump_pending
= 0;
729 pthread_mutex_lock(&ust_fork_mutex
);
730 lttng_handle_pending_statedump(sock_info
);
731 pthread_mutex_unlock(&ust_fork_mutex
);
733 if (!sock_info
->initial_statedump_done
) {
734 sock_info
->initial_statedump_done
= 1;
735 decrement_sem_count(1);
741 const char *bytecode_type_str(uint32_t cmd
)
744 case LTTNG_UST_ABI_CAPTURE
:
746 case LTTNG_UST_ABI_FILTER
:
754 int handle_bytecode_recv(struct sock_info
*sock_info
,
755 int sock
, struct ustcomm_ust_msg
*lum
)
757 struct lttng_ust_bytecode_node
*bytecode
= NULL
;
758 enum lttng_ust_bytecode_type type
;
759 const struct lttng_ust_abi_objd_ops
*ops
;
760 uint32_t data_size
, data_size_max
, reloc_offset
;
766 case LTTNG_UST_ABI_FILTER
:
767 type
= LTTNG_UST_BYTECODE_TYPE_FILTER
;
768 data_size
= lum
->u
.filter
.data_size
;
769 data_size_max
= LTTNG_UST_ABI_FILTER_BYTECODE_MAX_LEN
;
770 reloc_offset
= lum
->u
.filter
.reloc_offset
;
771 seqnum
= lum
->u
.filter
.seqnum
;
773 case LTTNG_UST_ABI_CAPTURE
:
774 type
= LTTNG_UST_BYTECODE_TYPE_CAPTURE
;
775 data_size
= lum
->u
.capture
.data_size
;
776 data_size_max
= LTTNG_UST_ABI_CAPTURE_BYTECODE_MAX_LEN
;
777 reloc_offset
= lum
->u
.capture
.reloc_offset
;
778 seqnum
= lum
->u
.capture
.seqnum
;
784 if (data_size
> data_size_max
) {
785 ERR("Bytecode %s data size is too large: %u bytes",
786 bytecode_type_str(lum
->cmd
), data_size
);
791 if (reloc_offset
> data_size
) {
792 ERR("Bytecode %s reloc offset %u is not within data",
793 bytecode_type_str(lum
->cmd
), reloc_offset
);
798 /* Allocate the structure AND the `data[]` field. */
799 bytecode
= zmalloc(sizeof(*bytecode
) + data_size
);
805 bytecode
->bc
.len
= data_size
;
806 bytecode
->bc
.reloc_offset
= reloc_offset
;
807 bytecode
->bc
.seqnum
= seqnum
;
808 bytecode
->type
= type
;
810 len
= ustcomm_recv_unix_sock(sock
, bytecode
->bc
.data
, bytecode
->bc
.len
);
812 case 0: /* orderly shutdown */
816 if (len
== bytecode
->bc
.len
) {
817 DBG("Bytecode %s data received",
818 bytecode_type_str(lum
->cmd
));
820 } else if (len
< 0) {
821 DBG("Receive failed from lttng-sessiond with errno %d",
823 if (len
== -ECONNRESET
) {
824 ERR("%s remote end closed connection",
832 DBG("Incorrect %s bytecode data message size: %zd",
833 bytecode_type_str(lum
->cmd
), len
);
839 ops
= lttng_ust_abi_objd_ops(lum
->handle
);
846 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
847 (unsigned long) &bytecode
,
858 void prepare_cmd_reply(struct ustcomm_ust_reply
*lur
, uint32_t handle
, uint32_t cmd
, int ret
)
860 lur
->handle
= handle
;
864 lur
->ret_code
= LTTNG_UST_OK
;
867 * Use -LTTNG_UST_ERR as wildcard for UST internal
868 * error that are not caused by the transport, except if
869 * we already have a more precise error message to
872 if (ret
> -LTTNG_UST_ERR
) {
873 /* Translate code to UST error. */
876 lur
->ret_code
= -LTTNG_UST_ERR_EXIST
;
879 lur
->ret_code
= -LTTNG_UST_ERR_INVAL
;
882 lur
->ret_code
= -LTTNG_UST_ERR_NOENT
;
885 lur
->ret_code
= -LTTNG_UST_ERR_PERM
;
888 lur
->ret_code
= -LTTNG_UST_ERR_NOSYS
;
891 lur
->ret_code
= -LTTNG_UST_ERR
;
901 int handle_message(struct sock_info
*sock_info
,
902 int sock
, struct ustcomm_ust_msg
*lum
)
905 const struct lttng_ust_abi_objd_ops
*ops
;
906 struct ustcomm_ust_reply lur
;
907 union lttng_ust_abi_args args
;
908 char ctxstr
[LTTNG_UST_ABI_SYM_NAME_LEN
]; /* App context string. */
911 memset(&lur
, 0, sizeof(lur
));
914 ret
= -LTTNG_UST_ERR_EXITING
;
918 ops
= lttng_ust_abi_objd_ops(lum
->handle
);
925 case LTTNG_UST_ABI_FILTER
:
926 case LTTNG_UST_ABI_EXCLUSION
:
927 case LTTNG_UST_ABI_CHANNEL
:
928 case LTTNG_UST_ABI_STREAM
:
929 case LTTNG_UST_ABI_CONTEXT
:
931 * Those commands send additional payload after struct
932 * ustcomm_ust_msg, which makes it pretty much impossible to
933 * deal with "unknown command" errors without leaving the
934 * communication pipe in a out-of-sync state. This is part of
935 * the ABI between liblttng-ust-ctl and liblttng-ust, and
936 * should be fixed on the next breaking
937 * LTTNG_UST_ABI_MAJOR_VERSION protocol bump by indicating the
938 * total command message length as part of a message header so
939 * that the protocol can recover from invalid command errors.
943 case LTTNG_UST_ABI_CAPTURE
:
944 case LTTNG_UST_ABI_COUNTER
:
945 case LTTNG_UST_ABI_COUNTER_GLOBAL
:
946 case LTTNG_UST_ABI_COUNTER_CPU
:
947 case LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
:
948 case LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
:
950 * Those commands expect a reply to the struct ustcomm_ust_msg
951 * before sending additional payload.
953 prepare_cmd_reply(&lur
, lum
->handle
, lum
->cmd
, 0);
955 ret
= send_reply(sock
, &lur
);
957 DBG("error sending reply");
964 * Other commands either don't send additional payload, or are
971 case LTTNG_UST_ABI_REGISTER_DONE
:
972 if (lum
->handle
== LTTNG_UST_ABI_ROOT_HANDLE
)
973 ret
= handle_register_done(sock_info
);
977 case LTTNG_UST_ABI_RELEASE
:
978 if (lum
->handle
== LTTNG_UST_ABI_ROOT_HANDLE
)
981 ret
= lttng_ust_abi_objd_unref(lum
->handle
, 1);
983 case LTTNG_UST_ABI_CAPTURE
:
984 case LTTNG_UST_ABI_FILTER
:
985 ret
= handle_bytecode_recv(sock_info
, sock
, lum
);
989 case LTTNG_UST_ABI_EXCLUSION
:
991 /* Receive exclusion names */
992 struct lttng_ust_excluder_node
*node
;
995 count
= lum
->u
.exclusion
.count
;
997 /* There are no names to read */
1001 node
= zmalloc(sizeof(*node
) +
1002 count
* LTTNG_UST_ABI_SYM_NAME_LEN
);
1007 node
->excluder
.count
= count
;
1008 len
= ustcomm_recv_unix_sock(sock
, node
->excluder
.names
,
1009 count
* LTTNG_UST_ABI_SYM_NAME_LEN
);
1011 case 0: /* orderly shutdown */
1016 if (len
== count
* LTTNG_UST_ABI_SYM_NAME_LEN
) {
1017 DBG("Exclusion data received");
1019 } else if (len
< 0) {
1020 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1021 if (len
== -ECONNRESET
) {
1022 ERR("%s remote end closed connection", sock_info
->name
);
1031 DBG("Incorrect exclusion data message size: %zd", len
);
1038 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1039 (unsigned long) &node
,
1046 case LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE
:
1048 int event_notifier_notif_fd
, close_ret
;
1050 len
= ustcomm_recv_event_notifier_notif_fd_from_sessiond(sock
,
1051 &event_notifier_notif_fd
);
1053 case 0: /* orderly shutdown */
1060 DBG("Receive failed from lttng-sessiond with errno %d",
1062 if (len
== -ECONNRESET
) {
1063 ERR("%s remote end closed connection",
1071 DBG("Incorrect event notifier fd message size: %zd",
1077 args
.event_notifier_handle
.event_notifier_notif_fd
=
1078 event_notifier_notif_fd
;
1080 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1081 (unsigned long) &lum
->u
,
1085 if (args
.event_notifier_handle
.event_notifier_notif_fd
>= 0) {
1086 lttng_ust_lock_fd_tracker();
1087 close_ret
= close(args
.event_notifier_handle
.event_notifier_notif_fd
);
1088 lttng_ust_unlock_fd_tracker();
1094 case LTTNG_UST_ABI_CHANNEL
:
1099 len
= ustcomm_recv_channel_from_sessiond(sock
,
1100 &chan_data
, lum
->u
.channel
.len
,
1103 case 0: /* orderly shutdown */
1107 if (len
== lum
->u
.channel
.len
) {
1108 DBG("channel data received");
1110 } else if (len
< 0) {
1111 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1112 if (len
== -ECONNRESET
) {
1113 ERR("%s remote end closed connection", sock_info
->name
);
1120 DBG("incorrect channel data message size: %zd", len
);
1125 args
.channel
.chan_data
= chan_data
;
1126 args
.channel
.wakeup_fd
= wakeup_fd
;
1128 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1129 (unsigned long) &lum
->u
,
1133 if (args
.channel
.wakeup_fd
>= 0) {
1136 lttng_ust_lock_fd_tracker();
1137 close_ret
= close(args
.channel
.wakeup_fd
);
1138 lttng_ust_unlock_fd_tracker();
1139 args
.channel
.wakeup_fd
= -1;
1143 free(args
.channel
.chan_data
);
1146 case LTTNG_UST_ABI_STREAM
:
1150 /* Receive shm_fd, wakeup_fd */
1151 ret
= ustcomm_recv_stream_from_sessiond(sock
,
1153 &args
.stream
.shm_fd
,
1154 &args
.stream
.wakeup_fd
);
1160 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1161 (unsigned long) &lum
->u
,
1165 if (args
.stream
.shm_fd
>= 0) {
1166 lttng_ust_lock_fd_tracker();
1167 close_ret
= close(args
.stream
.shm_fd
);
1168 lttng_ust_unlock_fd_tracker();
1169 args
.stream
.shm_fd
= -1;
1173 if (args
.stream
.wakeup_fd
>= 0) {
1174 lttng_ust_lock_fd_tracker();
1175 close_ret
= close(args
.stream
.wakeup_fd
);
1176 lttng_ust_unlock_fd_tracker();
1177 args
.stream
.wakeup_fd
= -1;
1183 case LTTNG_UST_ABI_CONTEXT
:
1184 switch (lum
->u
.context
.ctx
) {
1185 case LTTNG_UST_ABI_CONTEXT_APP_CONTEXT
:
1188 size_t ctxlen
, recvlen
;
1190 ctxlen
= strlen("$app.") + lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1
1191 + strlen(":") + lum
->u
.context
.u
.app_ctx
.ctx_name_len
;
1192 if (ctxlen
>= LTTNG_UST_ABI_SYM_NAME_LEN
) {
1193 ERR("Application context string length size is too large: %zu bytes",
1198 strcpy(ctxstr
, "$app.");
1199 p
= &ctxstr
[strlen("$app.")];
1200 recvlen
= ctxlen
- strlen("$app.");
1201 len
= ustcomm_recv_unix_sock(sock
, p
, recvlen
);
1203 case 0: /* orderly shutdown */
1207 if (len
== recvlen
) {
1208 DBG("app context data received");
1210 } else if (len
< 0) {
1211 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1212 if (len
== -ECONNRESET
) {
1213 ERR("%s remote end closed connection", sock_info
->name
);
1220 DBG("incorrect app context data message size: %zd", len
);
1225 /* Put : between provider and ctxname. */
1226 p
[lum
->u
.context
.u
.app_ctx
.provider_name_len
- 1] = ':';
1227 args
.app_context
.ctxname
= ctxstr
;
1234 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1235 (unsigned long) &lum
->u
,
1241 case LTTNG_UST_ABI_COUNTER
:
1245 len
= ustcomm_recv_counter_from_sessiond(sock
,
1246 &counter_data
, lum
->u
.counter
.len
);
1248 case 0: /* orderly shutdown */
1252 if (len
== lum
->u
.counter
.len
) {
1253 DBG("counter data received");
1255 } else if (len
< 0) {
1256 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1257 if (len
== -ECONNRESET
) {
1258 ERR("%s remote end closed connection", sock_info
->name
);
1265 DBG("incorrect counter data message size: %zd", len
);
1270 args
.counter
.counter_data
= counter_data
;
1272 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1273 (unsigned long) &lum
->u
,
1277 free(args
.counter
.counter_data
);
1280 case LTTNG_UST_ABI_COUNTER_GLOBAL
:
1282 /* Receive shm_fd */
1283 ret
= ustcomm_recv_counter_shm_from_sessiond(sock
,
1284 &args
.counter_shm
.shm_fd
);
1290 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1291 (unsigned long) &lum
->u
,
1295 if (args
.counter_shm
.shm_fd
>= 0) {
1298 lttng_ust_lock_fd_tracker();
1299 close_ret
= close(args
.counter_shm
.shm_fd
);
1300 lttng_ust_unlock_fd_tracker();
1301 args
.counter_shm
.shm_fd
= -1;
1307 case LTTNG_UST_ABI_COUNTER_CPU
:
1309 /* Receive shm_fd */
1310 ret
= ustcomm_recv_counter_shm_from_sessiond(sock
,
1311 &args
.counter_shm
.shm_fd
);
1317 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1318 (unsigned long) &lum
->u
,
1322 if (args
.counter_shm
.shm_fd
>= 0) {
1325 lttng_ust_lock_fd_tracker();
1326 close_ret
= close(args
.counter_shm
.shm_fd
);
1327 lttng_ust_unlock_fd_tracker();
1328 args
.counter_shm
.shm_fd
= -1;
1334 case LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE
:
1336 /* Receive struct lttng_ust_event_notifier */
1337 struct lttng_ust_abi_event_notifier event_notifier
;
1339 if (sizeof(event_notifier
) != lum
->u
.event_notifier
.len
) {
1340 DBG("incorrect event notifier data message size: %u", lum
->u
.event_notifier
.len
);
1344 len
= ustcomm_recv_unix_sock(sock
, &event_notifier
, sizeof(event_notifier
));
1346 case 0: /* orderly shutdown */
1350 if (len
== sizeof(event_notifier
)) {
1351 DBG("event notifier data received");
1353 } else if (len
< 0) {
1354 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
1355 if (len
== -ECONNRESET
) {
1356 ERR("%s remote end closed connection", sock_info
->name
);
1363 DBG("incorrect event notifier data message size: %zd", len
);
1369 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1370 (unsigned long) &event_notifier
,
1379 ret
= ops
->cmd(lum
->handle
, lum
->cmd
,
1380 (unsigned long) &lum
->u
,
1387 prepare_cmd_reply(&lur
, lum
->handle
, lum
->cmd
, ret
);
1391 case LTTNG_UST_ABI_TRACER_VERSION
:
1392 lur
.u
.version
= lum
->u
.version
;
1394 case LTTNG_UST_ABI_TRACEPOINT_LIST_GET
:
1395 memcpy(&lur
.u
.tracepoint
, &lum
->u
.tracepoint
, sizeof(lur
.u
.tracepoint
));
1399 DBG("Return value: %d", lur
.ret_val
);
1404 * Performed delayed statedump operations outside of the UST
1405 * lock. We need to take the dynamic loader lock before we take
1406 * the UST lock internally within handle_pending_statedump().
1408 handle_pending_statedump(sock_info
);
1411 ret
= -LTTNG_UST_ERR_EXITING
;
1415 ret
= send_reply(sock
, &lur
);
1417 DBG("error sending reply");
1422 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1425 if (lur
.ret_code
== LTTNG_UST_OK
) {
1427 case LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET
:
1428 len
= ustcomm_send_unix_sock(sock
,
1429 &args
.field_list
.entry
,
1430 sizeof(args
.field_list
.entry
));
1435 if (len
!= sizeof(args
.field_list
.entry
)) {
1449 void cleanup_sock_info(struct sock_info
*sock_info
, int exiting
)
1453 if (sock_info
->root_handle
!= -1) {
1454 ret
= lttng_ust_abi_objd_unref(sock_info
->root_handle
, 1);
1456 ERR("Error unref root handle");
1458 sock_info
->root_handle
= -1;
1460 sock_info
->registration_done
= 0;
1461 sock_info
->initial_statedump_done
= 0;
1464 * wait_shm_mmap, socket and notify socket are used by listener
1465 * threads outside of the ust lock, so we cannot tear them down
1466 * ourselves, because we cannot join on these threads. Leave
1467 * responsibility of cleaning up these resources to the OS
1473 if (sock_info
->socket
!= -1) {
1474 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1476 ERR("Error closing ust cmd socket");
1478 sock_info
->socket
= -1;
1480 if (sock_info
->notify_socket
!= -1) {
1481 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1483 ERR("Error closing ust notify socket");
1485 sock_info
->notify_socket
= -1;
1487 if (sock_info
->wait_shm_mmap
) {
1490 page_size
= LTTNG_UST_PAGE_SIZE
;
1491 if (page_size
<= 0) {
1495 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1497 ret
= munmap(sock_info
->wait_shm_mmap
, page_size
);
1499 ERR("Error unmapping wait shm");
1502 sock_info
->wait_shm_mmap
= NULL
;
1507 * Using fork to set umask in the child process (not multi-thread safe).
1508 * We deal with the shm_open vs ftruncate race (happening when the
1509 * sessiond owns the shm and does not let everybody modify it, to ensure
1510 * safety against shm_unlink) by simply letting the mmap fail and
1511 * retrying after a few seconds.
1512 * For global shm, everybody has rw access to it until the sessiond
1516 int get_wait_shm(struct sock_info
*sock_info
, size_t mmap_size
)
1518 int wait_shm_fd
, ret
;
1522 * Try to open read-only.
1524 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1525 if (wait_shm_fd
>= 0) {
1528 size_t bytes_read
= 0;
1531 * Try to read the fd. If unable to do so, try opening
1535 len
= read(wait_shm_fd
,
1536 &((char *) &tmp_read
)[bytes_read
],
1537 sizeof(tmp_read
) - bytes_read
);
1541 } while ((len
< 0 && errno
== EINTR
)
1542 || (len
> 0 && bytes_read
< sizeof(tmp_read
)));
1543 if (bytes_read
!= sizeof(tmp_read
)) {
1544 ret
= close(wait_shm_fd
);
1546 ERR("close wait_shm_fd");
1551 } else if (wait_shm_fd
< 0 && errno
!= ENOENT
) {
1553 * Real-only open did not work, and it's not because the
1554 * entry was not present. It's a failure that prohibits
1557 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1563 * If the open failed because the file did not exist, or because
1564 * the file was not truncated yet, try creating it ourself.
1566 URCU_TLS(lttng_ust_nest_count
)++;
1568 URCU_TLS(lttng_ust_nest_count
)--;
1573 * Parent: wait for child to return, in which case the
1574 * shared memory map will have been created.
1576 pid
= wait(&status
);
1577 if (pid
< 0 || !WIFEXITED(status
) || WEXITSTATUS(status
) != 0) {
1582 * Try to open read-only again after creation.
1584 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
, O_RDONLY
, 0);
1585 if (wait_shm_fd
< 0) {
1587 * Real-only open did not work. It's a failure
1588 * that prohibits using shm.
1590 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1594 } else if (pid
== 0) {
1598 create_mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
;
1599 if (sock_info
->global
)
1600 create_mode
|= S_IROTH
| S_IWGRP
| S_IWOTH
;
1602 * We're alone in a child process, so we can modify the
1603 * process-wide umask.
1605 umask(~create_mode
);
1607 * Try creating shm (or get rw access).
1608 * We don't do an exclusive open, because we allow other
1609 * processes to create+ftruncate it concurrently.
1611 wait_shm_fd
= shm_open(sock_info
->wait_shm_path
,
1612 O_RDWR
| O_CREAT
, create_mode
);
1613 if (wait_shm_fd
>= 0) {
1614 ret
= ftruncate(wait_shm_fd
, mmap_size
);
1616 PERROR("ftruncate");
1617 _exit(EXIT_FAILURE
);
1619 _exit(EXIT_SUCCESS
);
1622 * For local shm, we need to have rw access to accept
1623 * opening it: this means the local sessiond will be
1624 * able to wake us up. For global shm, we open it even
1625 * if rw access is not granted, because the root.root
1626 * sessiond will be able to override all rights and wake
1629 if (!sock_info
->global
&& errno
!= EACCES
) {
1630 ERR("Error opening shm %s", sock_info
->wait_shm_path
);
1631 _exit(EXIT_FAILURE
);
1634 * The shm exists, but we cannot open it RW. Report
1637 _exit(EXIT_SUCCESS
);
1642 if (wait_shm_fd
>= 0 && !sock_info
->global
) {
1643 struct stat statbuf
;
1646 * Ensure that our user is the owner of the shm file for
1647 * local shm. If we do not own the file, it means our
1648 * sessiond will not have access to wake us up (there is
1649 * probably a rogue process trying to fake our
1650 * sessiond). Fallback to polling method in this case.
1652 ret
= fstat(wait_shm_fd
, &statbuf
);
1657 if (statbuf
.st_uid
!= getuid())
1663 ret
= close(wait_shm_fd
);
1665 PERROR("Error closing fd");
1671 char *get_map_shm(struct sock_info
*sock_info
)
1674 int wait_shm_fd
, ret
;
1675 char *wait_shm_mmap
;
1677 page_size
= sysconf(_SC_PAGE_SIZE
);
1678 if (page_size
<= 0) {
1682 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1686 lttng_ust_lock_fd_tracker();
1687 wait_shm_fd
= get_wait_shm(sock_info
, page_size
);
1688 if (wait_shm_fd
< 0) {
1689 lttng_ust_unlock_fd_tracker();
1693 ret
= lttng_ust_add_fd_to_tracker(wait_shm_fd
);
1695 ret
= close(wait_shm_fd
);
1697 PERROR("Error closing fd");
1699 lttng_ust_unlock_fd_tracker();
1704 lttng_ust_unlock_fd_tracker();
1706 wait_shm_mmap
= mmap(NULL
, page_size
, PROT_READ
,
1707 MAP_SHARED
, wait_shm_fd
, 0);
1709 /* close shm fd immediately after taking the mmap reference */
1710 lttng_ust_lock_fd_tracker();
1711 ret
= close(wait_shm_fd
);
1713 lttng_ust_delete_fd_from_tracker(wait_shm_fd
);
1715 PERROR("Error closing fd");
1717 lttng_ust_unlock_fd_tracker();
1719 if (wait_shm_mmap
== MAP_FAILED
) {
1720 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1723 return wait_shm_mmap
;
1730 void wait_for_sessiond(struct sock_info
*sock_info
)
1732 /* Use ust_lock to check if we should quit. */
1736 if (wait_poll_fallback
) {
1741 assert(sock_info
->wait_shm_mmap
);
1743 DBG("Waiting for %s apps sessiond", sock_info
->name
);
1744 /* Wait for futex wakeup */
1745 if (uatomic_read((int32_t *) sock_info
->wait_shm_mmap
))
1748 while (lttng_ust_futex_async((int32_t *) sock_info
->wait_shm_mmap
,
1749 FUTEX_WAIT
, 0, NULL
, NULL
, 0)) {
1752 /* Value already changed. */
1755 /* Retry if interrupted by signal. */
1756 break; /* Get out of switch. */
1758 wait_poll_fallback
= 1;
1760 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1761 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1762 "Please upgrade your kernel "
1763 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1764 "mainline). LTTng-UST will use polling mode fallback.");
1765 if (lttng_ust_logging_debug_enabled())
1783 * This thread does not allocate any resource, except within
1784 * handle_message, within mutex protection. This mutex protects against
1786 * The other moment it allocates resources is at socket connection, which
1787 * is also protected by the mutex.
1790 void *ust_listener_thread(void *arg
)
1792 struct sock_info
*sock_info
= arg
;
1793 int sock
, ret
, prev_connect_failed
= 0, has_waited
= 0, fd
;
1796 lttng_ust_alloc_tls();
1798 * If available, add '-ust' to the end of this thread's
1801 ret
= lttng_ust_setustprocname();
1803 ERR("Unable to set UST process name");
1806 /* Restart trying to connect to the session daemon */
1808 if (prev_connect_failed
) {
1809 /* Wait for sessiond availability with pipe */
1810 wait_for_sessiond(sock_info
);
1814 * Sleep for 5 seconds before retrying after a
1815 * sequence of failure / wait / failure. This
1816 * deals with a killed or broken session daemon.
1822 prev_connect_failed
= 0;
1829 if (sock_info
->socket
!= -1) {
1830 /* FD tracker is updated by ustcomm_close_unix_sock() */
1831 ret
= ustcomm_close_unix_sock(sock_info
->socket
);
1833 ERR("Error closing %s ust cmd socket",
1836 sock_info
->socket
= -1;
1838 if (sock_info
->notify_socket
!= -1) {
1839 /* FD tracker is updated by ustcomm_close_unix_sock() */
1840 ret
= ustcomm_close_unix_sock(sock_info
->notify_socket
);
1842 ERR("Error closing %s ust notify socket",
1845 sock_info
->notify_socket
= -1;
1850 * Register. We need to perform both connect and sending
1851 * registration message before doing the next connect otherwise
1852 * we may reach unix socket connect queue max limits and block
1853 * on the 2nd connect while the session daemon is awaiting the
1854 * first connect registration message.
1856 /* Connect cmd socket */
1857 lttng_ust_lock_fd_tracker();
1858 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
,
1859 get_connect_sock_timeout());
1861 lttng_ust_unlock_fd_tracker();
1862 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1863 prev_connect_failed
= 1;
1866 * If we cannot find the sessiond daemon, don't delay
1867 * constructor execution.
1869 ret
= handle_register_failed(sock_info
);
1875 ret
= lttng_ust_add_fd_to_tracker(fd
);
1879 PERROR("close on sock_info->socket");
1882 lttng_ust_unlock_fd_tracker();
1887 sock_info
->socket
= ret
;
1888 lttng_ust_unlock_fd_tracker();
1892 * Unlock/relock ust lock because connect is blocking (with
1893 * timeout). Don't delay constructors on the ust lock for too
1901 * Create only one root handle per listener thread for the whole
1902 * process lifetime, so we ensure we get ID which is statically
1903 * assigned to the root handle.
1905 if (sock_info
->root_handle
== -1) {
1906 ret
= lttng_abi_create_root_handle();
1908 ERR("Error creating root handle");
1911 sock_info
->root_handle
= ret
;
1914 ret
= register_to_sessiond(sock_info
->socket
, LTTNG_UST_CTL_SOCKET_CMD
);
1916 ERR("Error registering to %s ust cmd socket",
1918 prev_connect_failed
= 1;
1920 * If we cannot register to the sessiond daemon, don't
1921 * delay constructor execution.
1923 ret
= handle_register_failed(sock_info
);
1931 * Unlock/relock ust lock because connect is blocking (with
1932 * timeout). Don't delay constructors on the ust lock for too
1939 /* Connect notify socket */
1940 lttng_ust_lock_fd_tracker();
1941 ret
= ustcomm_connect_unix_sock(sock_info
->sock_path
,
1942 get_connect_sock_timeout());
1944 lttng_ust_unlock_fd_tracker();
1945 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info
->name
);
1946 prev_connect_failed
= 1;
1949 * If we cannot find the sessiond daemon, don't delay
1950 * constructor execution.
1952 ret
= handle_register_failed(sock_info
);
1959 ret
= lttng_ust_add_fd_to_tracker(fd
);
1963 PERROR("close on sock_info->notify_socket");
1966 lttng_ust_unlock_fd_tracker();
1971 sock_info
->notify_socket
= ret
;
1972 lttng_ust_unlock_fd_tracker();
1976 * Unlock/relock ust lock because connect is blocking (with
1977 * timeout). Don't delay constructors on the ust lock for too
1984 timeout
= get_notify_sock_timeout();
1987 * Give at least 10ms to sessiond to reply to
1992 ret
= ustcomm_setsockopt_rcv_timeout(sock_info
->notify_socket
,
1995 WARN("Error setting socket receive timeout");
1997 ret
= ustcomm_setsockopt_snd_timeout(sock_info
->notify_socket
,
2000 WARN("Error setting socket send timeout");
2002 } else if (timeout
< -1) {
2003 WARN("Unsupported timeout value %ld", timeout
);
2006 ret
= register_to_sessiond(sock_info
->notify_socket
,
2007 LTTNG_UST_CTL_SOCKET_NOTIFY
);
2009 ERR("Error registering to %s ust notify socket",
2011 prev_connect_failed
= 1;
2013 * If we cannot register to the sessiond daemon, don't
2014 * delay constructor execution.
2016 ret
= handle_register_failed(sock_info
);
2021 sock
= sock_info
->socket
;
2027 struct ustcomm_ust_msg lum
;
2029 len
= ustcomm_recv_unix_sock(sock
, &lum
, sizeof(lum
));
2031 case 0: /* orderly shutdown */
2032 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info
->name
);
2037 * Either sessiond has shutdown or refused us by closing the socket.
2038 * In either case, we don't want to delay construction execution,
2039 * and we need to wait before retry.
2041 prev_connect_failed
= 1;
2043 * If we cannot register to the sessiond daemon, don't
2044 * delay constructor execution.
2046 ret
= handle_register_failed(sock_info
);
2051 print_cmd(lum
.cmd
, lum
.handle
);
2052 ret
= handle_message(sock_info
, sock
, &lum
);
2054 ERR("Error handling message for %s socket",
2057 * Close socket if protocol error is
2065 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len
);
2067 DBG("incorrect message size (%s socket): %zd", sock_info
->name
, len
);
2069 if (len
== -ECONNRESET
) {
2070 DBG("%s remote end closed connection", sock_info
->name
);
2081 /* Cleanup socket handles before trying to reconnect */
2082 lttng_ust_abi_objd_table_owner_cleanup(sock_info
);
2084 goto restart
; /* try to reconnect */
2089 pthread_mutex_lock(&ust_exit_mutex
);
2090 sock_info
->thread_active
= 0;
2091 pthread_mutex_unlock(&ust_exit_mutex
);
2096 * Weak symbol to call when the ust malloc wrapper is not loaded.
2098 __attribute__((weak
))
2099 void lttng_ust_libc_wrapper_malloc_ctor(void)
2104 * Use a symbol of the previous ABI to detect if liblttng-ust.so.0 is loaded in
2105 * the current process.
2107 #define LTTNG_UST_SONAME_0_SYM "ltt_probe_register"
2110 void lttng_ust_check_soname_0(void)
2112 if (!dlsym(RTLD_DEFAULT
, LTTNG_UST_SONAME_0_SYM
))
2115 CRIT("Incompatible library ABIs detected within the same process. "
2116 "The process is likely linked against different major soname of LTTng-UST which is unsupported. "
2117 "The detection was triggered by lookup of ABI 0 symbol \"%s\" in the Global Symbol Table\n",
2118 LTTNG_UST_SONAME_0_SYM
);
2122 * Expose a canary symbol of the previous ABI to ensure we catch uses of a
2123 * liblttng-ust.so.0 dlopen'd after .so.1 has been loaded. Use a different
2124 * symbol than the detection code to ensure we don't detect ourself.
2126 void init_usterr(void);
2127 void init_usterr(void)
2129 CRIT("Incompatible library ABIs detected within the same process. "
2130 "The process is likely linked against different major soname of LTTng-UST which is unsupported. "
2131 "The detection was triggered by canary symbol \"%s\"\n", __func__
);
2135 * sessiond monitoring thread: monitor presence of global and per-user
2136 * sessiond by polling the application common named pipe.
2139 void lttng_ust_ctor(void)
2140 __attribute__((constructor
));
2142 void lttng_ust_ctor(void)
2144 struct timespec constructor_timeout
;
2145 sigset_t sig_all_blocked
, orig_parent_mask
;
2146 pthread_attr_t thread_attr
;
2151 if (uatomic_xchg(&initialized
, 1) == 1)
2155 * Fixup interdependency between TLS allocation mutex (which happens
2156 * to be the dynamic linker mutex) and ust_lock, taken within
2159 lttng_ust_alloc_tls();
2161 lttng_ust_loaded
= 1;
2164 * Check if we find a symbol of the previous ABI in the current process
2165 * as different ABIs of liblttng-ust can't co-exist in a process. If we
2166 * do so, emit a critical log message which will also abort if the
2167 * LTTNG_UST_ABORT_ON_CRITICAL environment variable is set.
2169 lttng_ust_check_soname_0();
2172 * We need to ensure that the liblttng-ust library is not unloaded to avoid
2173 * the unloading of code used by the ust_listener_threads as we can not
2174 * reliably know when they exited. To do that, manually load
2175 * liblttng-ust.so to increment the dynamic loader's internal refcount for
2176 * this library so it never becomes zero, thus never gets unloaded from the
2177 * address space of the process. Since we are already running in the
2178 * constructor of the LTTNG_UST_LIB_SONAME library, calling dlopen will
2179 * simply increment the refcount and no additionnal work is needed by the
2180 * dynamic loader as the shared library is already loaded in the address
2181 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
2182 * unloading of the UST library if its refcount becomes zero (which should
2183 * never happen). Do the return value check but discard the handle at the
2184 * end of the function as it's not needed.
2186 handle
= dlopen(LTTNG_UST_LIB_SONAME
, RTLD_LAZY
| RTLD_NODELETE
);
2188 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME
);
2190 DBG("dlopened liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME
);
2194 * We want precise control over the order in which we construct
2195 * our sub-libraries vs starting to receive commands from
2196 * sessiond (otherwise leading to errors when trying to create
2197 * sessiond before the init functions are completed).
2201 * Both the logging and getenv lazy-initialization uses getenv()
2202 * internally and thus needs to be explicitly initialized in
2203 * liblttng-ust before we start any threads as an unsuspecting normally
2204 * single threaded application using liblttng-ust could be using
2205 * setenv() which is not thread-safe.
2207 lttng_ust_logging_init();
2208 lttng_ust_getenv_init();
2210 /* Call the liblttng-ust-common constructor. */
2211 lttng_ust_common_ctor();
2213 lttng_ust_tp_init();
2214 lttng_ust_statedump_init();
2215 lttng_ust_ring_buffer_clients_init();
2216 lttng_ust_counter_clients_init();
2217 lttng_perf_counter_init();
2219 * Invoke ust malloc wrapper init before starting other threads.
2221 lttng_ust_libc_wrapper_malloc_ctor();
2223 timeout_mode
= get_constructor_timeout(&constructor_timeout
);
2225 get_allow_blocking();
2227 ret
= sem_init(&constructor_wait
, 0, 0);
2232 ret
= setup_global_apps();
2234 assert(global_apps
.allowed
== 0);
2235 DBG("global apps setup returned %d", ret
);
2238 ret
= setup_local_apps();
2240 assert(local_apps
.allowed
== 0);
2241 DBG("local apps setup returned %d", ret
);
2244 /* A new thread created by pthread_create inherits the signal mask
2245 * from the parent. To avoid any signal being received by the
2246 * listener thread, we block all signals temporarily in the parent,
2247 * while we create the listener thread.
2249 sigfillset(&sig_all_blocked
);
2250 ret
= pthread_sigmask(SIG_SETMASK
, &sig_all_blocked
, &orig_parent_mask
);
2252 ERR("pthread_sigmask: %s", strerror(ret
));
2255 ret
= pthread_attr_init(&thread_attr
);
2257 ERR("pthread_attr_init: %s", strerror(ret
));
2259 ret
= pthread_attr_setdetachstate(&thread_attr
, PTHREAD_CREATE_DETACHED
);
2261 ERR("pthread_attr_setdetachstate: %s", strerror(ret
));
2264 if (global_apps
.allowed
) {
2265 pthread_mutex_lock(&ust_exit_mutex
);
2266 ret
= pthread_create(&global_apps
.ust_listener
, &thread_attr
,
2267 ust_listener_thread
, &global_apps
);
2269 ERR("pthread_create global: %s", strerror(ret
));
2271 global_apps
.thread_active
= 1;
2272 pthread_mutex_unlock(&ust_exit_mutex
);
2274 handle_register_done(&global_apps
);
2277 if (local_apps
.allowed
) {
2278 pthread_mutex_lock(&ust_exit_mutex
);
2279 ret
= pthread_create(&local_apps
.ust_listener
, &thread_attr
,
2280 ust_listener_thread
, &local_apps
);
2282 ERR("pthread_create local: %s", strerror(ret
));
2284 local_apps
.thread_active
= 1;
2285 pthread_mutex_unlock(&ust_exit_mutex
);
2287 handle_register_done(&local_apps
);
2289 ret
= pthread_attr_destroy(&thread_attr
);
2291 ERR("pthread_attr_destroy: %s", strerror(ret
));
2294 /* Restore original signal mask in parent */
2295 ret
= pthread_sigmask(SIG_SETMASK
, &orig_parent_mask
, NULL
);
2297 ERR("pthread_sigmask: %s", strerror(ret
));
2300 switch (timeout_mode
) {
2301 case 1: /* timeout wait */
2303 ret
= sem_timedwait(&constructor_wait
,
2304 &constructor_timeout
);
2305 } while (ret
< 0 && errno
== EINTR
);
2309 ERR("Timed out waiting for lttng-sessiond");
2312 PERROR("sem_timedwait");
2315 ERR("Unexpected error \"%s\" returned by sem_timedwait",
2320 case -1:/* wait forever */
2322 ret
= sem_wait(&constructor_wait
);
2323 } while (ret
< 0 && errno
== EINTR
);
2330 ERR("Unexpected error \"%s\" returned by sem_wait",
2335 case 0: /* no timeout */
2341 void lttng_ust_cleanup(int exiting
)
2343 cleanup_sock_info(&global_apps
, exiting
);
2344 cleanup_sock_info(&local_apps
, exiting
);
2345 local_apps
.allowed
= 0;
2346 global_apps
.allowed
= 0;
2348 * The teardown in this function all affect data structures
2349 * accessed under the UST lock by the listener thread. This
2350 * lock, along with the lttng_ust_comm_should_quit flag, ensure
2351 * that none of these threads are accessing this data at this
2354 lttng_ust_abi_exit();
2355 lttng_ust_abi_events_exit();
2356 lttng_perf_counter_exit();
2357 lttng_ust_ring_buffer_clients_exit();
2358 lttng_ust_counter_clients_exit();
2359 lttng_ust_statedump_destroy();
2360 lttng_ust_tp_exit();
2362 /* Reinitialize values for fork */
2363 sem_count
= sem_count_initial_value
;
2364 lttng_ust_comm_should_quit
= 0;
2370 void lttng_ust_exit(void)
2371 __attribute__((destructor
));
2373 void lttng_ust_exit(void)
2378 * Using pthread_cancel here because:
2379 * A) we don't want to hang application teardown.
2380 * B) the thread is not allocating any resource.
2384 * Require the communication thread to quit. Synchronize with
2385 * mutexes to ensure it is not in a mutex critical section when
2386 * pthread_cancel is later called.
2389 lttng_ust_comm_should_quit
= 1;
2392 pthread_mutex_lock(&ust_exit_mutex
);
2393 /* cancel threads */
2394 if (global_apps
.thread_active
) {
2395 ret
= pthread_cancel(global_apps
.ust_listener
);
2397 ERR("Error cancelling global ust listener thread: %s",
2400 global_apps
.thread_active
= 0;
2403 if (local_apps
.thread_active
) {
2404 ret
= pthread_cancel(local_apps
.ust_listener
);
2406 ERR("Error cancelling local ust listener thread: %s",
2409 local_apps
.thread_active
= 0;
2412 pthread_mutex_unlock(&ust_exit_mutex
);
2415 * Do NOT join threads: use of sys_futex makes it impossible to
2416 * join the threads without using async-cancel, but async-cancel
2417 * is delivered by a signal, which could hit the target thread
2418 * anywhere in its code path, including while the ust_lock() is
2419 * held, causing a deadlock for the other thread. Let the OS
2420 * cleanup the threads if there are stalled in a syscall.
2422 lttng_ust_cleanup(1);
2426 void ust_context_ns_reset(void)
2428 lttng_context_pid_ns_reset();
2429 lttng_context_cgroup_ns_reset();
2430 lttng_context_ipc_ns_reset();
2431 lttng_context_mnt_ns_reset();
2432 lttng_context_net_ns_reset();
2433 lttng_context_user_ns_reset();
2434 lttng_context_time_ns_reset();
2435 lttng_context_uts_ns_reset();
2439 void ust_context_vuids_reset(void)
2441 lttng_context_vuid_reset();
2442 lttng_context_veuid_reset();
2443 lttng_context_vsuid_reset();
2447 void ust_context_vgids_reset(void)
2449 lttng_context_vgid_reset();
2450 lttng_context_vegid_reset();
2451 lttng_context_vsgid_reset();
2455 * We exclude the worker threads across fork and clone (except
2456 * CLONE_VM), because these system calls only keep the forking thread
2457 * running in the child. Therefore, we don't want to call fork or clone
2458 * in the middle of an tracepoint or ust tracing state modification.
2459 * Holding this mutex protects these structures across fork and clone.
2461 void lttng_ust_before_fork(sigset_t
*save_sigset
)
2464 * Disable signals. This is to avoid that the child intervenes
2465 * before it is properly setup for tracing. It is safer to
2466 * disable all signals, because then we know we are not breaking
2467 * anything by restoring the original mask.
2472 /* Allocate lttng-ust TLS. */
2473 lttng_ust_alloc_tls();
2475 if (URCU_TLS(lttng_ust_nest_count
))
2477 /* Disable signals */
2478 sigfillset(&all_sigs
);
2479 ret
= sigprocmask(SIG_BLOCK
, &all_sigs
, save_sigset
);
2481 PERROR("sigprocmask");
2484 pthread_mutex_lock(&ust_fork_mutex
);
2487 lttng_ust_urcu_before_fork();
2488 lttng_ust_lock_fd_tracker();
2492 static void ust_after_fork_common(sigset_t
*restore_sigset
)
2496 DBG("process %d", getpid());
2497 lttng_perf_unlock();
2498 lttng_ust_unlock_fd_tracker();
2501 pthread_mutex_unlock(&ust_fork_mutex
);
2503 /* Restore signals */
2504 ret
= sigprocmask(SIG_SETMASK
, restore_sigset
, NULL
);
2506 PERROR("sigprocmask");
2510 void lttng_ust_after_fork_parent(sigset_t
*restore_sigset
)
2512 if (URCU_TLS(lttng_ust_nest_count
))
2514 DBG("process %d", getpid());
2515 lttng_ust_urcu_after_fork_parent();
2516 /* Release mutexes and reenable signals */
2517 ust_after_fork_common(restore_sigset
);
2521 * After fork, in the child, we need to cleanup all the leftover state,
2522 * except the worker thread which already magically disappeared thanks
2523 * to the weird Linux fork semantics. After tyding up, we call
2524 * lttng_ust_ctor() again to start over as a new PID.
2526 * This is meant for forks() that have tracing in the child between the
2527 * fork and following exec call (if there is any).
2529 void lttng_ust_after_fork_child(sigset_t
*restore_sigset
)
2531 if (URCU_TLS(lttng_ust_nest_count
))
2533 lttng_context_vpid_reset();
2534 lttng_context_vtid_reset();
2535 lttng_ust_context_procname_reset();
2536 ust_context_ns_reset();
2537 ust_context_vuids_reset();
2538 ust_context_vgids_reset();
2539 DBG("process %d", getpid());
2540 /* Release urcu mutexes */
2541 lttng_ust_urcu_after_fork_child();
2542 lttng_ust_cleanup(0);
2543 /* Release mutexes and reenable signals */
2544 ust_after_fork_common(restore_sigset
);
2548 void lttng_ust_after_setns(void)
2550 ust_context_ns_reset();
2551 ust_context_vuids_reset();
2552 ust_context_vgids_reset();
2555 void lttng_ust_after_unshare(void)
2557 ust_context_ns_reset();
2558 ust_context_vuids_reset();
2559 ust_context_vgids_reset();
2562 void lttng_ust_after_setuid(void)
2564 ust_context_vuids_reset();
2567 void lttng_ust_after_seteuid(void)
2569 ust_context_vuids_reset();
2572 void lttng_ust_after_setreuid(void)
2574 ust_context_vuids_reset();
2577 void lttng_ust_after_setresuid(void)
2579 ust_context_vuids_reset();
2582 void lttng_ust_after_setgid(void)
2584 ust_context_vgids_reset();
2587 void lttng_ust_after_setegid(void)
2589 ust_context_vgids_reset();
2592 void lttng_ust_after_setregid(void)
2594 ust_context_vgids_reset();
2597 void lttng_ust_after_setresgid(void)
2599 ust_context_vgids_reset();
2602 void lttng_ust_sockinfo_session_enabled(void *owner
)
2604 struct sock_info
*sock_info
= owner
;
2605 sock_info
->statedump_pending
= 1;