Custom upgrade: suffix lttng_ust_loaded with 1
[lttng-ust.git] / src / lib / lttng-ust / lttng-ust-comm.c
1 /*
2 * SPDX-License-Identifier: LGPL-2.1-only
3 *
4 * Copyright (C) 2011 EfficiOS Inc.
5 * Copyright (C) 2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
6 */
7
8 #define _LGPL_SOURCE
9 #include <stddef.h>
10 #include <stdint.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <sys/mman.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <sys/wait.h>
17 #include <dlfcn.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20 #include <errno.h>
21 #include <pthread.h>
22 #include <semaphore.h>
23 #include <time.h>
24 #include <assert.h>
25 #include <signal.h>
26 #include <limits.h>
27 #include <urcu/uatomic.h>
28 #include <urcu/compiler.h>
29 #include <lttng/urcu/urcu-ust.h>
30
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"
62
63 /*
64 * Has lttng ust comm constructor been called ?
65 */
66 static int initialized;
67
68 /*
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.
72 *
73 * The UST lock is the centralized mutex across UST tracing control and
74 * probe registration.
75 *
76 * ust_exit_mutex must never nest in ust_mutex.
77 *
78 * ust_fork_mutex must never nest in ust_mutex.
79 *
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.
83 *
84 * ust_lock nests within the dynamic loader lock (within glibc) because
85 * it is taken within the library constructor.
86 *
87 * The ust fd tracker lock nests within the ust_mutex.
88 */
89 static pthread_mutex_t ust_mutex = PTHREAD_MUTEX_INITIALIZER;
90
91 /* Allow nesting the ust_mutex within the same thread. */
92 static DEFINE_URCU_TLS(int, ust_mutex_nest);
93
94 /*
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.
98 *
99 * It never nests within a ust_mutex.
100 */
101 static pthread_mutex_t ust_exit_mutex = PTHREAD_MUTEX_INITIALIZER;
102
103 /*
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.
108 */
109 static pthread_mutex_t ust_fork_mutex = PTHREAD_MUTEX_INITIALIZER;
110
111 /* Should the ust comm thread quit ? */
112 static int lttng_ust_comm_should_quit;
113
114 /*
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.
119 */
120 static int lttng_ust_loaded_orig;
121
122 /*
123 * Notes on async-signal-safety of ust lock: a few libc functions are used
124 * which are not strictly async-signal-safe:
125 *
126 * - pthread_setcancelstate
127 * - pthread_mutex_lock
128 * - pthread_mutex_unlock
129 *
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.
135 *
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.
142 */
143
144 /*
145 * Return 0 on success, -1 if should quit.
146 * The lock is taken in both cases.
147 * Signal-safe.
148 */
149 int ust_lock(void)
150 {
151 sigset_t sig_all_blocked, orig_mask;
152 int ret;
153
154 if (lttng_ust_cancelstate_disable_push()) {
155 ERR("lttng_ust_cancelstate_disable_push");
156 }
157 sigfillset(&sig_all_blocked);
158 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
159 if (ret) {
160 ERR("pthread_sigmask: ret=%d", ret);
161 }
162 if (!URCU_TLS(ust_mutex_nest)++)
163 pthread_mutex_lock(&ust_mutex);
164 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
165 if (ret) {
166 ERR("pthread_sigmask: ret=%d", ret);
167 }
168 if (lttng_ust_comm_should_quit) {
169 return -1;
170 } else {
171 return 0;
172 }
173 }
174
175 /*
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.
179 * Signal-safe.
180 */
181 void ust_lock_nocheck(void)
182 {
183 sigset_t sig_all_blocked, orig_mask;
184 int ret;
185
186 if (lttng_ust_cancelstate_disable_push()) {
187 ERR("lttng_ust_cancelstate_disable_push");
188 }
189 sigfillset(&sig_all_blocked);
190 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
191 if (ret) {
192 ERR("pthread_sigmask: ret=%d", ret);
193 }
194 if (!URCU_TLS(ust_mutex_nest)++)
195 pthread_mutex_lock(&ust_mutex);
196 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
197 if (ret) {
198 ERR("pthread_sigmask: ret=%d", ret);
199 }
200 }
201
202 /*
203 * Signal-safe.
204 */
205 void ust_unlock(void)
206 {
207 sigset_t sig_all_blocked, orig_mask;
208 int ret;
209
210 sigfillset(&sig_all_blocked);
211 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
212 if (ret) {
213 ERR("pthread_sigmask: ret=%d", ret);
214 }
215 if (!--URCU_TLS(ust_mutex_nest))
216 pthread_mutex_unlock(&ust_mutex);
217 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
218 if (ret) {
219 ERR("pthread_sigmask: ret=%d", ret);
220 }
221 if (lttng_ust_cancelstate_disable_pop()) {
222 ERR("lttng_ust_cancelstate_disable_pop");
223 }
224 }
225
226 /*
227 * Wait for either of these before continuing to the main
228 * program:
229 * - the register_done message from sessiond daemon
230 * (will let the sessiond daemon enable sessions before main
231 * starts.)
232 * - sessiond daemon is not reachable.
233 * - timeout (ensuring applications are resilient to session
234 * daemon problems).
235 */
236 static sem_t constructor_wait;
237 /*
238 * Doing this for both the global and local sessiond.
239 */
240 enum {
241 sem_count_initial_value = 4,
242 };
243
244 static int sem_count = sem_count_initial_value;
245
246 /*
247 * Counting nesting within lttng-ust. Used to ensure that calling fork()
248 * from liblttng-ust does not execute the pre/post fork handlers.
249 */
250 static DEFINE_URCU_TLS(int, lttng_ust_nest_count);
251
252 /*
253 * Info about socket and associated listener thread.
254 */
255 struct sock_info {
256 const char *name;
257 pthread_t ust_listener; /* listener thread */
258 int root_handle;
259 int registration_done;
260 int allowed;
261 int global;
262 int thread_active;
263
264 char sock_path[PATH_MAX];
265 int socket;
266 int notify_socket;
267
268 char wait_shm_path[PATH_MAX];
269 char *wait_shm_mmap;
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];
275 };
276
277 /* Socket from app (connect) to session daemon (listen) for communication */
278 static struct sock_info global_apps = {
279 .name = "global",
280 .global = 1,
281
282 .root_handle = -1,
283 .registration_done = 0,
284 .allowed = 0,
285 .thread_active = 0,
286
287 .sock_path = LTTNG_DEFAULT_RUNDIR "/" LTTNG_UST_SOCK_FILENAME,
288 .socket = -1,
289 .notify_socket = -1,
290
291 .wait_shm_path = "/" LTTNG_UST_WAIT_FILENAME,
292
293 .statedump_pending = 0,
294 .initial_statedump_done = 0,
295 .procname[0] = '\0'
296 };
297
298 /* TODO: allow global_apps_sock_path override */
299
300 static struct sock_info local_apps = {
301 .name = "local",
302 .global = 0,
303 .root_handle = -1,
304 .registration_done = 0,
305 .allowed = 0, /* Check setuid bit first */
306 .thread_active = 0,
307
308 .socket = -1,
309 .notify_socket = -1,
310
311 .statedump_pending = 0,
312 .initial_statedump_done = 0,
313 .procname[0] = '\0'
314 };
315
316 static int wait_poll_fallback;
317
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",
322
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",
327
328 [ LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE ] = "Create event notifier group",
329
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",
334
335 /* Channel FD commands */
336 [ LTTNG_UST_ABI_STREAM ] = "Create Stream",
337 [ LTTNG_UST_ABI_EVENT ] = "Create Event",
338
339 /* Event and Channel FD commands */
340 [ LTTNG_UST_ABI_CONTEXT ] = "Create Context",
341 [ LTTNG_UST_ABI_FLUSH_BUFFER ] = "Flush Buffer",
342
343 /* Event, Channel and Session commands */
344 [ LTTNG_UST_ABI_ENABLE ] = "Enable",
345 [ LTTNG_UST_ABI_DISABLE ] = "Disable",
346
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",
350
351 /* Event FD commands */
352 [ LTTNG_UST_ABI_FILTER ] = "Create Filter",
353 [ LTTNG_UST_ABI_EXCLUSION ] = "Add exclusions to event",
354
355 /* Event notifier group commands */
356 [ LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE ] = "Create event notifier",
357
358 /* Session and event notifier group commands */
359 [ LTTNG_UST_ABI_COUNTER ] = "Create Counter",
360
361 /* Counter commands */
362 [ LTTNG_UST_ABI_COUNTER_GLOBAL ] = "Create Counter Global",
363 [ LTTNG_UST_ABI_COUNTER_CPU ] = "Create Counter CPU",
364 };
365
366 static const char *str_timeout;
367 static int got_timeout_env;
368
369 static char *get_map_shm(struct sock_info *sock_info);
370
371 /*
372 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
373 * pointer.
374 */
375 static
376 const char *get_lttng_home_dir(void)
377 {
378 const char *val;
379
380 val = (const char *) lttng_ust_getenv("LTTNG_HOME");
381 if (val != NULL) {
382 return val;
383 }
384 return (const char *) lttng_ust_getenv("HOME");
385 }
386
387 /*
388 * Force a read (imply TLS allocation for dlopen) of TLS variables.
389 */
390 static
391 void lttng_nest_count_alloc_tls(void)
392 {
393 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count)));
394 }
395
396 static
397 void lttng_ust_mutex_nest_alloc_tls(void)
398 {
399 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest)));
400 }
401
402 /*
403 * Allocate lttng-ust urcu TLS.
404 */
405 static
406 void lttng_lttng_ust_urcu_alloc_tls(void)
407 {
408 (void) lttng_ust_urcu_read_ongoing();
409 }
410
411 void lttng_ust_alloc_tls(void)
412 {
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();
430 }
431
432 /*
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.
437 *
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().
442 */
443 void lttng_ust_init_thread(void)
444 {
445 /*
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.
449 */
450 lttng_ust_alloc_tls();
451 }
452
453 int lttng_get_notify_socket(void *owner)
454 {
455 struct sock_info *info = owner;
456
457 return info->notify_socket;
458 }
459
460
461 char* lttng_ust_sockinfo_get_procname(void *owner)
462 {
463 struct sock_info *info = owner;
464
465 return info->procname;
466 }
467
468 static
469 void print_cmd(int cmd, int handle)
470 {
471 const char *cmd_name = "Unknown";
472
473 if (cmd >= 0 && cmd < LTTNG_ARRAY_SIZE(cmd_name_mapping)
474 && cmd_name_mapping[cmd]) {
475 cmd_name = cmd_name_mapping[cmd];
476 }
477 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
478 cmd_name, cmd,
479 lttng_ust_obj_get_name(handle), handle);
480 }
481
482 static
483 int setup_global_apps(void)
484 {
485 int ret = 0;
486 assert(!global_apps.wait_shm_mmap);
487
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;
492 ret = -EIO;
493 goto error;
494 }
495
496 global_apps.allowed = 1;
497 lttng_pthread_getname_np(global_apps.procname, LTTNG_UST_CONTEXT_PROCNAME_LEN);
498 error:
499 return ret;
500 }
501 static
502 int setup_local_apps(void)
503 {
504 int ret = 0;
505 const char *home_dir;
506 uid_t uid;
507
508 assert(!local_apps.wait_shm_mmap);
509
510 uid = getuid();
511 /*
512 * Disallow per-user tracing for setuid binaries.
513 */
514 if (uid != geteuid()) {
515 assert(local_apps.allowed == 0);
516 ret = 0;
517 goto end;
518 }
519 home_dir = get_lttng_home_dir();
520 if (!home_dir) {
521 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
522 assert(local_apps.allowed == 0);
523 ret = -ENOENT;
524 goto end;
525 }
526 local_apps.allowed = 1;
527 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
528 home_dir,
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,
533 uid);
534
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;
539 ret = -EIO;
540 goto end;
541 }
542
543 lttng_pthread_getname_np(local_apps.procname, LTTNG_UST_CONTEXT_PROCNAME_LEN);
544 end:
545 return ret;
546 }
547
548 /*
549 * Get socket timeout, in ms.
550 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
551 */
552 static
553 long get_timeout(void)
554 {
555 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
556
557 if (!got_timeout_env) {
558 str_timeout = lttng_ust_getenv("LTTNG_UST_REGISTER_TIMEOUT");
559 got_timeout_env = 1;
560 }
561 if (str_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;
567 }
568
569 /* Timeout for notify socket send and recv. */
570 static
571 long get_notify_sock_timeout(void)
572 {
573 return get_timeout();
574 }
575
576 /* Timeout for connecting to cmd and notify sockets. */
577 static
578 long get_connect_sock_timeout(void)
579 {
580 return get_timeout();
581 }
582
583 /*
584 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
585 */
586 static
587 int get_constructor_timeout(struct timespec *constructor_timeout)
588 {
589 long constructor_delay_ms;
590 int ret;
591
592 constructor_delay_ms = get_timeout();
593
594 switch (constructor_delay_ms) {
595 case -1:/* fall-through */
596 case 0:
597 return constructor_delay_ms;
598 default:
599 break;
600 }
601
602 /*
603 * If we are unable to find the current time, don't wait.
604 */
605 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
606 if (ret) {
607 /* Don't wait. */
608 return 0;
609 }
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;
616 }
617 /* Timeout wait (constructor_delay_ms). */
618 return 1;
619 }
620
621 static
622 void get_allow_blocking(void)
623 {
624 const char *str_allow_blocking =
625 lttng_ust_getenv("LTTNG_UST_ALLOW_BLOCKING");
626
627 if (str_allow_blocking) {
628 DBG("%s environment variable is set",
629 "LTTNG_UST_ALLOW_BLOCKING");
630 lttng_ust_ringbuffer_set_allow_blocking();
631 }
632 }
633
634 static
635 int register_to_sessiond(int socket, enum lttng_ust_ctl_socket_type type,
636 const char *procname)
637 {
638 return ustcomm_send_reg_msg(socket,
639 type,
640 CAA_BITS_PER_LONG,
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,
646 procname);
647 }
648
649 static
650 int send_reply(int sock, struct ustcomm_ust_reply *lur)
651 {
652 ssize_t len;
653
654 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
655 switch (len) {
656 case sizeof(*lur):
657 DBG("message successfully sent");
658 return 0;
659 default:
660 if (len == -ECONNRESET) {
661 DBG("remote end closed connection");
662 return 0;
663 }
664 if (len < 0)
665 return len;
666 DBG("incorrect message size: %zd", len);
667 return -EINVAL;
668 }
669 }
670
671 static
672 void decrement_sem_count(unsigned int count)
673 {
674 int ret;
675
676 assert(uatomic_read(&sem_count) >= count);
677
678 if (uatomic_read(&sem_count) <= 0) {
679 return;
680 }
681
682 ret = uatomic_add_return(&sem_count, -count);
683 if (ret == 0) {
684 ret = sem_post(&constructor_wait);
685 assert(!ret);
686 }
687 }
688
689 static
690 int handle_register_done(struct sock_info *sock_info)
691 {
692 if (sock_info->registration_done)
693 return 0;
694 sock_info->registration_done = 1;
695
696 decrement_sem_count(1);
697 if (!sock_info->statedump_pending) {
698 sock_info->initial_statedump_done = 1;
699 decrement_sem_count(1);
700 }
701
702 return 0;
703 }
704
705 static
706 int handle_register_failed(struct sock_info *sock_info)
707 {
708 if (sock_info->registration_done)
709 return 0;
710 sock_info->registration_done = 1;
711 sock_info->initial_statedump_done = 1;
712
713 decrement_sem_count(2);
714
715 return 0;
716 }
717
718 /*
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.
723 *
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.
728 *
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
736 * a deadlock.
737 */
738 static
739 void handle_pending_statedump(struct sock_info *sock_info)
740 {
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);
746
747 if (!sock_info->initial_statedump_done) {
748 sock_info->initial_statedump_done = 1;
749 decrement_sem_count(1);
750 }
751 }
752 }
753
754 static inline
755 const char *bytecode_type_str(uint32_t cmd)
756 {
757 switch (cmd) {
758 case LTTNG_UST_ABI_CAPTURE:
759 return "capture";
760 case LTTNG_UST_ABI_FILTER:
761 return "filter";
762 default:
763 abort();
764 }
765 }
766
767 static
768 int handle_bytecode_recv(struct sock_info *sock_info,
769 int sock, struct ustcomm_ust_msg *lum)
770 {
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;
775 uint64_t seqnum;
776 ssize_t len;
777 int ret = 0;
778
779 switch (lum->cmd) {
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;
786 break;
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;
793 break;
794 default:
795 abort();
796 }
797
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);
801 ret = -EINVAL;
802 goto end;
803 }
804
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);
808 ret = -EINVAL;
809 goto end;
810 }
811
812 /* Allocate the structure AND the `data[]` field. */
813 bytecode = zmalloc(sizeof(*bytecode) + data_size);
814 if (!bytecode) {
815 ret = -ENOMEM;
816 goto end;
817 }
818
819 bytecode->bc.len = data_size;
820 bytecode->bc.reloc_offset = reloc_offset;
821 bytecode->bc.seqnum = seqnum;
822 bytecode->type = type;
823
824 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data, bytecode->bc.len);
825 switch (len) {
826 case 0: /* orderly shutdown */
827 ret = 0;
828 goto end;
829 default:
830 if (len == bytecode->bc.len) {
831 DBG("Bytecode %s data received",
832 bytecode_type_str(lum->cmd));
833 break;
834 } else if (len < 0) {
835 DBG("Receive failed from lttng-sessiond with errno %d",
836 (int) -len);
837 if (len == -ECONNRESET) {
838 ERR("%s remote end closed connection",
839 sock_info->name);
840 ret = len;
841 goto end;
842 }
843 ret = len;
844 goto end;
845 } else {
846 DBG("Incorrect %s bytecode data message size: %zd",
847 bytecode_type_str(lum->cmd), len);
848 ret = -EINVAL;
849 goto end;
850 }
851 }
852
853 ops = lttng_ust_abi_objd_ops(lum->handle);
854 if (!ops) {
855 ret = -ENOENT;
856 goto end;
857 }
858
859 if (ops->cmd)
860 ret = ops->cmd(lum->handle, lum->cmd,
861 (unsigned long) &bytecode,
862 NULL, sock_info);
863 else
864 ret = -ENOSYS;
865
866 end:
867 free(bytecode);
868 return ret;
869 }
870
871 static
872 void prepare_cmd_reply(struct ustcomm_ust_reply *lur, uint32_t handle, uint32_t cmd, int ret)
873 {
874 lur->handle = handle;
875 lur->cmd = cmd;
876 lur->ret_val = ret;
877 if (ret >= 0) {
878 lur->ret_code = LTTNG_UST_OK;
879 } else {
880 /*
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
884 * report.
885 */
886 if (ret > -LTTNG_UST_ERR) {
887 /* Translate code to UST error. */
888 switch (ret) {
889 case -EEXIST:
890 lur->ret_code = -LTTNG_UST_ERR_EXIST;
891 break;
892 case -EINVAL:
893 lur->ret_code = -LTTNG_UST_ERR_INVAL;
894 break;
895 case -ENOENT:
896 lur->ret_code = -LTTNG_UST_ERR_NOENT;
897 break;
898 case -EPERM:
899 lur->ret_code = -LTTNG_UST_ERR_PERM;
900 break;
901 case -ENOSYS:
902 lur->ret_code = -LTTNG_UST_ERR_NOSYS;
903 break;
904 default:
905 lur->ret_code = -LTTNG_UST_ERR;
906 break;
907 }
908 } else {
909 lur->ret_code = ret;
910 }
911 }
912 }
913
914 static
915 int handle_message(struct sock_info *sock_info,
916 int sock, struct ustcomm_ust_msg *lum)
917 {
918 int ret = 0;
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. */
923 ssize_t len;
924
925 memset(&lur, 0, sizeof(lur));
926
927 if (ust_lock()) {
928 ret = -LTTNG_UST_ERR_EXITING;
929 goto error;
930 }
931
932 ops = lttng_ust_abi_objd_ops(lum->handle);
933 if (!ops) {
934 ret = -ENOENT;
935 goto error;
936 }
937
938 switch (lum->cmd) {
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:
944 /*
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.
954 */
955 break;
956
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:
963 /*
964 * Those commands expect a reply to the struct ustcomm_ust_msg
965 * before sending additional payload.
966 */
967 prepare_cmd_reply(&lur, lum->handle, lum->cmd, 0);
968
969 ret = send_reply(sock, &lur);
970 if (ret < 0) {
971 DBG("error sending reply");
972 goto error;
973 }
974 break;
975
976 default:
977 /*
978 * Other commands either don't send additional payload, or are
979 * unknown.
980 */
981 break;
982 }
983
984 switch (lum->cmd) {
985 case LTTNG_UST_ABI_REGISTER_DONE:
986 if (lum->handle == LTTNG_UST_ABI_ROOT_HANDLE)
987 ret = handle_register_done(sock_info);
988 else
989 ret = -EINVAL;
990 break;
991 case LTTNG_UST_ABI_RELEASE:
992 if (lum->handle == LTTNG_UST_ABI_ROOT_HANDLE)
993 ret = -EPERM;
994 else
995 ret = lttng_ust_abi_objd_unref(lum->handle, 1);
996 break;
997 case LTTNG_UST_ABI_CAPTURE:
998 case LTTNG_UST_ABI_FILTER:
999 ret = handle_bytecode_recv(sock_info, sock, lum);
1000 if (ret)
1001 goto error;
1002 break;
1003 case LTTNG_UST_ABI_EXCLUSION:
1004 {
1005 /* Receive exclusion names */
1006 struct lttng_ust_excluder_node *node;
1007 unsigned int count;
1008
1009 count = lum->u.exclusion.count;
1010 if (count == 0) {
1011 /* There are no names to read */
1012 ret = 0;
1013 goto error;
1014 }
1015 node = zmalloc(sizeof(*node) +
1016 count * LTTNG_UST_ABI_SYM_NAME_LEN);
1017 if (!node) {
1018 ret = -ENOMEM;
1019 goto error;
1020 }
1021 node->excluder.count = count;
1022 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
1023 count * LTTNG_UST_ABI_SYM_NAME_LEN);
1024 switch (len) {
1025 case 0: /* orderly shutdown */
1026 ret = 0;
1027 free(node);
1028 goto error;
1029 default:
1030 if (len == count * LTTNG_UST_ABI_SYM_NAME_LEN) {
1031 DBG("Exclusion data received");
1032 break;
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);
1037 ret = len;
1038 free(node);
1039 goto error;
1040 }
1041 ret = len;
1042 free(node);
1043 goto error;
1044 } else {
1045 DBG("Incorrect exclusion data message size: %zd", len);
1046 ret = -EINVAL;
1047 free(node);
1048 goto error;
1049 }
1050 }
1051 if (ops->cmd)
1052 ret = ops->cmd(lum->handle, lum->cmd,
1053 (unsigned long) &node,
1054 &args, sock_info);
1055 else
1056 ret = -ENOSYS;
1057 free(node);
1058 break;
1059 }
1060 case LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE:
1061 {
1062 int event_notifier_notif_fd, close_ret;
1063
1064 len = ustcomm_recv_event_notifier_notif_fd_from_sessiond(sock,
1065 &event_notifier_notif_fd);
1066 switch (len) {
1067 case 0: /* orderly shutdown */
1068 ret = 0;
1069 goto error;
1070 case 1:
1071 break;
1072 default:
1073 if (len < 0) {
1074 DBG("Receive failed from lttng-sessiond with errno %d",
1075 (int) -len);
1076 if (len == -ECONNRESET) {
1077 ERR("%s remote end closed connection",
1078 sock_info->name);
1079 ret = len;
1080 goto error;
1081 }
1082 ret = len;
1083 goto error;
1084 } else {
1085 DBG("Incorrect event notifier fd message size: %zd",
1086 len);
1087 ret = -EINVAL;
1088 goto error;
1089 }
1090 }
1091 args.event_notifier_handle.event_notifier_notif_fd =
1092 event_notifier_notif_fd;
1093 if (ops->cmd)
1094 ret = ops->cmd(lum->handle, lum->cmd,
1095 (unsigned long) &lum->u,
1096 &args, sock_info);
1097 else
1098 ret = -ENOSYS;
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();
1103 if (close_ret)
1104 PERROR("close");
1105 }
1106 break;
1107 }
1108 case LTTNG_UST_ABI_CHANNEL:
1109 {
1110 void *chan_data;
1111 int wakeup_fd;
1112
1113 len = ustcomm_recv_channel_from_sessiond(sock,
1114 &chan_data, lum->u.channel.len,
1115 &wakeup_fd);
1116 switch (len) {
1117 case 0: /* orderly shutdown */
1118 ret = 0;
1119 goto error;
1120 default:
1121 if (len == lum->u.channel.len) {
1122 DBG("channel data received");
1123 break;
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);
1128 ret = len;
1129 goto error;
1130 }
1131 ret = len;
1132 goto error;
1133 } else {
1134 DBG("incorrect channel data message size: %zd", len);
1135 ret = -EINVAL;
1136 goto error;
1137 }
1138 }
1139 args.channel.chan_data = chan_data;
1140 args.channel.wakeup_fd = wakeup_fd;
1141 if (ops->cmd)
1142 ret = ops->cmd(lum->handle, lum->cmd,
1143 (unsigned long) &lum->u,
1144 &args, sock_info);
1145 else
1146 ret = -ENOSYS;
1147 if (args.channel.wakeup_fd >= 0) {
1148 int close_ret;
1149
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;
1154 if (close_ret)
1155 PERROR("close");
1156 }
1157 free(args.channel.chan_data);
1158 break;
1159 }
1160 case LTTNG_UST_ABI_STREAM:
1161 {
1162 int close_ret;
1163
1164 /* Receive shm_fd, wakeup_fd */
1165 ret = ustcomm_recv_stream_from_sessiond(sock,
1166 NULL,
1167 &args.stream.shm_fd,
1168 &args.stream.wakeup_fd);
1169 if (ret) {
1170 goto error;
1171 }
1172
1173 if (ops->cmd)
1174 ret = ops->cmd(lum->handle, lum->cmd,
1175 (unsigned long) &lum->u,
1176 &args, sock_info);
1177 else
1178 ret = -ENOSYS;
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;
1184 if (close_ret)
1185 PERROR("close");
1186 }
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;
1192 if (close_ret)
1193 PERROR("close");
1194 }
1195 break;
1196 }
1197 case LTTNG_UST_ABI_CONTEXT:
1198 switch (lum->u.context.ctx) {
1199 case LTTNG_UST_ABI_CONTEXT_APP_CONTEXT:
1200 {
1201 char *p;
1202 size_t ctxlen, recvlen;
1203
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",
1208 ctxlen);
1209 ret = -EINVAL;
1210 goto error;
1211 }
1212 strcpy(ctxstr, "$app.");
1213 p = &ctxstr[strlen("$app.")];
1214 recvlen = ctxlen - strlen("$app.");
1215 len = ustcomm_recv_unix_sock(sock, p, recvlen);
1216 switch (len) {
1217 case 0: /* orderly shutdown */
1218 ret = 0;
1219 goto error;
1220 default:
1221 if (len == recvlen) {
1222 DBG("app context data received");
1223 break;
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);
1228 ret = len;
1229 goto error;
1230 }
1231 ret = len;
1232 goto error;
1233 } else {
1234 DBG("incorrect app context data message size: %zd", len);
1235 ret = -EINVAL;
1236 goto error;
1237 }
1238 }
1239 /* Put : between provider and ctxname. */
1240 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
1241 args.app_context.ctxname = ctxstr;
1242 break;
1243 }
1244 default:
1245 break;
1246 }
1247 if (ops->cmd) {
1248 ret = ops->cmd(lum->handle, lum->cmd,
1249 (unsigned long) &lum->u,
1250 &args, sock_info);
1251 } else {
1252 ret = -ENOSYS;
1253 }
1254 break;
1255 case LTTNG_UST_ABI_COUNTER:
1256 {
1257 void *counter_data;
1258
1259 len = ustcomm_recv_counter_from_sessiond(sock,
1260 &counter_data, lum->u.counter.len);
1261 switch (len) {
1262 case 0: /* orderly shutdown */
1263 ret = 0;
1264 goto error;
1265 default:
1266 if (len == lum->u.counter.len) {
1267 DBG("counter data received");
1268 break;
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);
1273 ret = len;
1274 goto error;
1275 }
1276 ret = len;
1277 goto error;
1278 } else {
1279 DBG("incorrect counter data message size: %zd", len);
1280 ret = -EINVAL;
1281 goto error;
1282 }
1283 }
1284 args.counter.counter_data = counter_data;
1285 if (ops->cmd)
1286 ret = ops->cmd(lum->handle, lum->cmd,
1287 (unsigned long) &lum->u,
1288 &args, sock_info);
1289 else
1290 ret = -ENOSYS;
1291 free(args.counter.counter_data);
1292 break;
1293 }
1294 case LTTNG_UST_ABI_COUNTER_GLOBAL:
1295 {
1296 /* Receive shm_fd */
1297 ret = ustcomm_recv_counter_shm_from_sessiond(sock,
1298 &args.counter_shm.shm_fd);
1299 if (ret) {
1300 goto error;
1301 }
1302
1303 if (ops->cmd)
1304 ret = ops->cmd(lum->handle, lum->cmd,
1305 (unsigned long) &lum->u,
1306 &args, sock_info);
1307 else
1308 ret = -ENOSYS;
1309 if (args.counter_shm.shm_fd >= 0) {
1310 int close_ret;
1311
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;
1316 if (close_ret)
1317 PERROR("close");
1318 }
1319 break;
1320 }
1321 case LTTNG_UST_ABI_COUNTER_CPU:
1322 {
1323 /* Receive shm_fd */
1324 ret = ustcomm_recv_counter_shm_from_sessiond(sock,
1325 &args.counter_shm.shm_fd);
1326 if (ret) {
1327 goto error;
1328 }
1329
1330 if (ops->cmd)
1331 ret = ops->cmd(lum->handle, lum->cmd,
1332 (unsigned long) &lum->u,
1333 &args, sock_info);
1334 else
1335 ret = -ENOSYS;
1336 if (args.counter_shm.shm_fd >= 0) {
1337 int close_ret;
1338
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;
1343 if (close_ret)
1344 PERROR("close");
1345 }
1346 break;
1347 }
1348 case LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE:
1349 {
1350 /* Receive struct lttng_ust_event_notifier */
1351 struct lttng_ust_abi_event_notifier event_notifier;
1352
1353 if (sizeof(event_notifier) != lum->u.event_notifier.len) {
1354 DBG("incorrect event notifier data message size: %u", lum->u.event_notifier.len);
1355 ret = -EINVAL;
1356 goto error;
1357 }
1358 len = ustcomm_recv_unix_sock(sock, &event_notifier, sizeof(event_notifier));
1359 switch (len) {
1360 case 0: /* orderly shutdown */
1361 ret = 0;
1362 goto error;
1363 default:
1364 if (len == sizeof(event_notifier)) {
1365 DBG("event notifier data received");
1366 break;
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);
1371 ret = len;
1372 goto error;
1373 }
1374 ret = len;
1375 goto error;
1376 } else {
1377 DBG("incorrect event notifier data message size: %zd", len);
1378 ret = -EINVAL;
1379 goto error;
1380 }
1381 }
1382 if (ops->cmd)
1383 ret = ops->cmd(lum->handle, lum->cmd,
1384 (unsigned long) &event_notifier,
1385 &args, sock_info);
1386 else
1387 ret = -ENOSYS;
1388 break;
1389 }
1390
1391 default:
1392 if (ops->cmd)
1393 ret = ops->cmd(lum->handle, lum->cmd,
1394 (unsigned long) &lum->u,
1395 &args, sock_info);
1396 else
1397 ret = -ENOSYS;
1398 break;
1399 }
1400
1401 prepare_cmd_reply(&lur, lum->handle, lum->cmd, ret);
1402
1403 if (ret >= 0) {
1404 switch (lum->cmd) {
1405 case LTTNG_UST_ABI_TRACER_VERSION:
1406 lur.u.version = lum->u.version;
1407 break;
1408 case LTTNG_UST_ABI_TRACEPOINT_LIST_GET:
1409 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1410 break;
1411 }
1412 }
1413 DBG("Return value: %d", lur.ret_val);
1414
1415 ust_unlock();
1416
1417 /*
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().
1421 */
1422 handle_pending_statedump(sock_info);
1423
1424 if (ust_lock()) {
1425 ret = -LTTNG_UST_ERR_EXITING;
1426 goto error;
1427 }
1428
1429 ret = send_reply(sock, &lur);
1430 if (ret < 0) {
1431 DBG("error sending reply");
1432 goto error;
1433 }
1434
1435 /*
1436 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1437 * after the reply.
1438 */
1439 if (lur.ret_code == LTTNG_UST_OK) {
1440 switch (lum->cmd) {
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));
1445 if (len < 0) {
1446 ret = len;
1447 goto error;
1448 }
1449 if (len != sizeof(args.field_list.entry)) {
1450 ret = -EINVAL;
1451 goto error;
1452 }
1453 }
1454 }
1455
1456 error:
1457 ust_unlock();
1458
1459 return ret;
1460 }
1461
1462 static
1463 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
1464 {
1465 int ret;
1466
1467 if (sock_info->root_handle != -1) {
1468 ret = lttng_ust_abi_objd_unref(sock_info->root_handle, 1);
1469 if (ret) {
1470 ERR("Error unref root handle");
1471 }
1472 sock_info->root_handle = -1;
1473 }
1474
1475
1476 /*
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
1481 * process exit.
1482 */
1483 if (exiting)
1484 return;
1485
1486 sock_info->registration_done = 0;
1487 sock_info->initial_statedump_done = 0;
1488
1489 if (sock_info->socket != -1) {
1490 ret = ustcomm_close_unix_sock(sock_info->socket);
1491 if (ret) {
1492 ERR("Error closing ust cmd socket");
1493 }
1494 sock_info->socket = -1;
1495 }
1496 if (sock_info->notify_socket != -1) {
1497 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1498 if (ret) {
1499 ERR("Error closing ust notify socket");
1500 }
1501 sock_info->notify_socket = -1;
1502 }
1503 if (sock_info->wait_shm_mmap) {
1504 long page_size;
1505
1506 page_size = LTTNG_UST_PAGE_SIZE;
1507 if (page_size <= 0) {
1508 if (!page_size) {
1509 errno = EINVAL;
1510 }
1511 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1512 } else {
1513 ret = munmap(sock_info->wait_shm_mmap, page_size);
1514 if (ret) {
1515 ERR("Error unmapping wait shm");
1516 }
1517 }
1518 sock_info->wait_shm_mmap = NULL;
1519 }
1520 }
1521
1522 /*
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
1529 * starts.
1530 */
1531 static
1532 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
1533 {
1534 int wait_shm_fd, ret;
1535 pid_t pid;
1536
1537 /*
1538 * Try to open read-only.
1539 */
1540 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1541 if (wait_shm_fd >= 0) {
1542 int32_t tmp_read;
1543 ssize_t len;
1544 size_t bytes_read = 0;
1545
1546 /*
1547 * Try to read the fd. If unable to do so, try opening
1548 * it in write mode.
1549 */
1550 do {
1551 len = read(wait_shm_fd,
1552 &((char *) &tmp_read)[bytes_read],
1553 sizeof(tmp_read) - bytes_read);
1554 if (len > 0) {
1555 bytes_read += len;
1556 }
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);
1561 if (ret) {
1562 ERR("close wait_shm_fd");
1563 }
1564 goto open_write;
1565 }
1566 goto end;
1567 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1568 /*
1569 * Real-only open did not work, and it's not because the
1570 * entry was not present. It's a failure that prohibits
1571 * using shm.
1572 */
1573 ERR("Error opening shm %s", sock_info->wait_shm_path);
1574 goto end;
1575 }
1576
1577 open_write:
1578 /*
1579 * If the open failed because the file did not exist, or because
1580 * the file was not truncated yet, try creating it ourself.
1581 */
1582 URCU_TLS(lttng_ust_nest_count)++;
1583 pid = fork();
1584 URCU_TLS(lttng_ust_nest_count)--;
1585 if (pid > 0) {
1586 int status, wait_ret;
1587
1588 /*
1589 * Parent: wait for child to return, in which case the
1590 * shared memory map will have been created.
1591 */
1592 wait_ret = waitpid(pid, &status, 0);
1593 if (wait_ret < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1594 wait_shm_fd = -1;
1595 goto end;
1596 }
1597 /*
1598 * Try to open read-only again after creation.
1599 */
1600 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1601 if (wait_shm_fd < 0) {
1602 /*
1603 * Real-only open did not work. It's a failure
1604 * that prohibits using shm.
1605 */
1606 ERR("Error opening shm %s", sock_info->wait_shm_path);
1607 goto end;
1608 }
1609 goto end;
1610 } else if (pid == 0) {
1611 int create_mode;
1612
1613 /* Child */
1614 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
1615 if (sock_info->global)
1616 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
1617 /*
1618 * We're alone in a child process, so we can modify the
1619 * process-wide umask.
1620 */
1621 umask(~create_mode);
1622 /*
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.
1626 */
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);
1631 if (ret) {
1632 PERROR("ftruncate");
1633 _exit(EXIT_FAILURE);
1634 }
1635 _exit(EXIT_SUCCESS);
1636 }
1637 /*
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
1643 * us up.
1644 */
1645 if (!sock_info->global && errno != EACCES) {
1646 ERR("Error opening shm %s", sock_info->wait_shm_path);
1647 _exit(EXIT_FAILURE);
1648 }
1649 /*
1650 * The shm exists, but we cannot open it RW. Report
1651 * success.
1652 */
1653 _exit(EXIT_SUCCESS);
1654 } else {
1655 return -1;
1656 }
1657 end:
1658 if (wait_shm_fd >= 0 && !sock_info->global) {
1659 struct stat statbuf;
1660
1661 /*
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.
1667 */
1668 ret = fstat(wait_shm_fd, &statbuf);
1669 if (ret) {
1670 PERROR("fstat");
1671 goto error_close;
1672 }
1673 if (statbuf.st_uid != getuid())
1674 goto error_close;
1675 }
1676 return wait_shm_fd;
1677
1678 error_close:
1679 ret = close(wait_shm_fd);
1680 if (ret) {
1681 PERROR("Error closing fd");
1682 }
1683 return -1;
1684 }
1685
1686 static
1687 char *get_map_shm(struct sock_info *sock_info)
1688 {
1689 long page_size;
1690 int wait_shm_fd, ret;
1691 char *wait_shm_mmap;
1692
1693 page_size = sysconf(_SC_PAGE_SIZE);
1694 if (page_size <= 0) {
1695 if (!page_size) {
1696 errno = EINVAL;
1697 }
1698 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1699 goto error;
1700 }
1701
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();
1706 goto error;
1707 }
1708
1709 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1710 if (ret < 0) {
1711 ret = close(wait_shm_fd);
1712 if (!ret) {
1713 PERROR("Error closing fd");
1714 }
1715 lttng_ust_unlock_fd_tracker();
1716 goto error;
1717 }
1718
1719 wait_shm_fd = ret;
1720 lttng_ust_unlock_fd_tracker();
1721
1722 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
1723 MAP_SHARED, wait_shm_fd, 0);
1724
1725 /* close shm fd immediately after taking the mmap reference */
1726 lttng_ust_lock_fd_tracker();
1727 ret = close(wait_shm_fd);
1728 if (!ret) {
1729 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1730 } else {
1731 PERROR("Error closing fd");
1732 }
1733 lttng_ust_unlock_fd_tracker();
1734
1735 if (wait_shm_mmap == MAP_FAILED) {
1736 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1737 goto error;
1738 }
1739 return wait_shm_mmap;
1740
1741 error:
1742 return NULL;
1743 }
1744
1745 static
1746 void wait_for_sessiond(struct sock_info *sock_info)
1747 {
1748 /* Use ust_lock to check if we should quit. */
1749 if (ust_lock()) {
1750 goto quit;
1751 }
1752 if (wait_poll_fallback) {
1753 goto error;
1754 }
1755 ust_unlock();
1756
1757 assert(sock_info->wait_shm_mmap);
1758
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)) {
1763 /*
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
1769 * differs from 0.
1770 */
1771 continue;
1772 }
1773 switch (errno) {
1774 case EAGAIN:
1775 /* Value already changed. */
1776 goto end_wait;
1777 case EINTR:
1778 /* Retry if interrupted by signal. */
1779 break; /* Get out of switch. Check again. */
1780 case EFAULT:
1781 wait_poll_fallback = 1;
1782 DBG(
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())
1789 PERROR("futex");
1790 goto end_wait;
1791 }
1792 }
1793 end_wait:
1794 return;
1795
1796 quit:
1797 ust_unlock();
1798 return;
1799
1800 error:
1801 ust_unlock();
1802 return;
1803 }
1804
1805 /*
1806 * This thread does not allocate any resource, except within
1807 * handle_message, within mutex protection. This mutex protects against
1808 * fork and exit.
1809 * The other moment it allocates resources is at socket connection, which
1810 * is also protected by the mutex.
1811 */
1812 static
1813 void *ust_listener_thread(void *arg)
1814 {
1815 struct sock_info *sock_info = arg;
1816 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
1817 long timeout;
1818
1819 lttng_ust_alloc_tls();
1820 /*
1821 * If available, add '-ust' to the end of this thread's
1822 * process name
1823 */
1824 ret = lttng_ust_setustprocname();
1825 if (ret) {
1826 ERR("Unable to set UST process name");
1827 }
1828
1829 /* Restart trying to connect to the session daemon */
1830 restart:
1831 if (prev_connect_failed) {
1832 /* Wait for sessiond availability with pipe */
1833 wait_for_sessiond(sock_info);
1834 if (has_waited) {
1835 has_waited = 0;
1836 /*
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.
1840 */
1841 sleep(5);
1842 } else {
1843 has_waited = 1;
1844 }
1845 prev_connect_failed = 0;
1846 }
1847
1848 if (ust_lock()) {
1849 goto quit;
1850 }
1851
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);
1855 if (ret) {
1856 ERR("Error closing %s ust cmd socket",
1857 sock_info->name);
1858 }
1859 sock_info->socket = -1;
1860 }
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);
1864 if (ret) {
1865 ERR("Error closing %s ust notify socket",
1866 sock_info->name);
1867 }
1868 sock_info->notify_socket = -1;
1869 }
1870
1871
1872 /*
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.
1878 */
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());
1883 if (ret < 0) {
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;
1887
1888 /*
1889 * If we cannot find the sessiond daemon, don't delay
1890 * constructor execution.
1891 */
1892 ret = handle_register_failed(sock_info);
1893 assert(!ret);
1894 ust_unlock();
1895 goto restart;
1896 }
1897 fd = ret;
1898 ret = lttng_ust_add_fd_to_tracker(fd);
1899 if (ret < 0) {
1900 ret = close(fd);
1901 if (ret) {
1902 PERROR("close on sock_info->socket");
1903 }
1904 ret = -1;
1905 lttng_ust_unlock_fd_tracker();
1906 ust_unlock();
1907 goto quit;
1908 }
1909
1910 sock_info->socket = ret;
1911 lttng_ust_unlock_fd_tracker();
1912
1913 ust_unlock();
1914 /*
1915 * Unlock/relock ust lock because connect is blocking (with
1916 * timeout). Don't delay constructors on the ust lock for too
1917 * long.
1918 */
1919 if (ust_lock()) {
1920 goto quit;
1921 }
1922
1923 /*
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.
1927 */
1928 if (sock_info->root_handle == -1) {
1929 ret = lttng_abi_create_root_handle();
1930 if (ret < 0) {
1931 ERR("Error creating root handle");
1932 goto quit;
1933 }
1934 sock_info->root_handle = ret;
1935 }
1936
1937 ret = register_to_sessiond(sock_info->socket, LTTNG_UST_CTL_SOCKET_CMD,
1938 sock_info->procname);
1939 if (ret < 0) {
1940 ERR("Error registering to %s ust cmd socket",
1941 sock_info->name);
1942 prev_connect_failed = 1;
1943 /*
1944 * If we cannot register to the sessiond daemon, don't
1945 * delay constructor execution.
1946 */
1947 ret = handle_register_failed(sock_info);
1948 assert(!ret);
1949 ust_unlock();
1950 goto restart;
1951 }
1952
1953 ust_unlock();
1954 /*
1955 * Unlock/relock ust lock because connect is blocking (with
1956 * timeout). Don't delay constructors on the ust lock for too
1957 * long.
1958 */
1959 if (ust_lock()) {
1960 goto quit;
1961 }
1962
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());
1967 if (ret < 0) {
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;
1971
1972 /*
1973 * If we cannot find the sessiond daemon, don't delay
1974 * constructor execution.
1975 */
1976 ret = handle_register_failed(sock_info);
1977 assert(!ret);
1978 ust_unlock();
1979 goto restart;
1980 }
1981
1982 fd = ret;
1983 ret = lttng_ust_add_fd_to_tracker(fd);
1984 if (ret < 0) {
1985 ret = close(fd);
1986 if (ret) {
1987 PERROR("close on sock_info->notify_socket");
1988 }
1989 ret = -1;
1990 lttng_ust_unlock_fd_tracker();
1991 ust_unlock();
1992 goto quit;
1993 }
1994
1995 sock_info->notify_socket = ret;
1996 lttng_ust_unlock_fd_tracker();
1997
1998 ust_unlock();
1999 /*
2000 * Unlock/relock ust lock because connect is blocking (with
2001 * timeout). Don't delay constructors on the ust lock for too
2002 * long.
2003 */
2004 if (ust_lock()) {
2005 goto quit;
2006 }
2007
2008 timeout = get_notify_sock_timeout();
2009 if (timeout >= 0) {
2010 /*
2011 * Give at least 10ms to sessiond to reply to
2012 * notifications.
2013 */
2014 if (timeout < 10)
2015 timeout = 10;
2016 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
2017 timeout);
2018 if (ret < 0) {
2019 WARN("Error setting socket receive timeout");
2020 }
2021 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
2022 timeout);
2023 if (ret < 0) {
2024 WARN("Error setting socket send timeout");
2025 }
2026 } else if (timeout < -1) {
2027 WARN("Unsupported timeout value %ld", timeout);
2028 }
2029
2030 ret = register_to_sessiond(sock_info->notify_socket,
2031 LTTNG_UST_CTL_SOCKET_NOTIFY, sock_info->procname);
2032 if (ret < 0) {
2033 ERR("Error registering to %s ust notify socket",
2034 sock_info->name);
2035 prev_connect_failed = 1;
2036 /*
2037 * If we cannot register to the sessiond daemon, don't
2038 * delay constructor execution.
2039 */
2040 ret = handle_register_failed(sock_info);
2041 assert(!ret);
2042 ust_unlock();
2043 goto restart;
2044 }
2045 sock = sock_info->socket;
2046
2047 ust_unlock();
2048
2049 for (;;) {
2050 ssize_t len;
2051 struct ustcomm_ust_msg lum;
2052
2053 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
2054 switch (len) {
2055 case 0: /* orderly shutdown */
2056 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
2057 if (ust_lock()) {
2058 goto quit;
2059 }
2060 /*
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.
2064 */
2065 prev_connect_failed = 1;
2066 /*
2067 * If we cannot register to the sessiond daemon, don't
2068 * delay constructor execution.
2069 */
2070 ret = handle_register_failed(sock_info);
2071 assert(!ret);
2072 ust_unlock();
2073 goto end;
2074 case sizeof(lum):
2075 print_cmd(lum.cmd, lum.handle);
2076 ret = handle_message(sock_info, sock, &lum);
2077 if (ret) {
2078 ERR("Error handling message for %s socket",
2079 sock_info->name);
2080 /*
2081 * Close socket if protocol error is
2082 * detected.
2083 */
2084 goto end;
2085 }
2086 continue;
2087 default:
2088 if (len < 0) {
2089 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
2090 } else {
2091 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
2092 }
2093 if (len == -ECONNRESET) {
2094 DBG("%s remote end closed connection", sock_info->name);
2095 goto end;
2096 }
2097 goto end;
2098 }
2099
2100 }
2101 end:
2102 if (ust_lock()) {
2103 goto quit;
2104 }
2105 /* Cleanup socket handles before trying to reconnect */
2106 lttng_ust_abi_objd_table_owner_cleanup(sock_info);
2107 ust_unlock();
2108 goto restart; /* try to reconnect */
2109
2110 quit:
2111 ust_unlock();
2112
2113 pthread_mutex_lock(&ust_exit_mutex);
2114 sock_info->thread_active = 0;
2115 pthread_mutex_unlock(&ust_exit_mutex);
2116 return NULL;
2117 }
2118
2119 /*
2120 * Weak symbol to call when the ust malloc wrapper is not loaded.
2121 */
2122 __attribute__((weak))
2123 void lttng_ust_libc_wrapper_malloc_ctor(void)
2124 {
2125 }
2126
2127 /*
2128 * Use a symbol of the previous ABI to detect if liblttng-ust.so.0 is loaded in
2129 * the current process.
2130 */
2131 #define LTTNG_UST_SONAME_0_SYM "ltt_probe_register"
2132
2133 static
2134 void lttng_ust_check_soname_0(void)
2135 {
2136 if (!dlsym(RTLD_DEFAULT, LTTNG_UST_SONAME_0_SYM))
2137 return;
2138
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);
2143 }
2144
2145 /*
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.
2149 *
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.
2153 */
2154 void init_usterr(void);
2155 void init_usterr(void)
2156 {
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__);
2160 }
2161
2162 /*
2163 * sessiond monitoring thread: monitor presence of global and per-user
2164 * sessiond by polling the application common named pipe.
2165 */
2166 static
2167 void lttng_ust_ctor(void)
2168 __attribute__((constructor));
2169 static
2170 void lttng_ust_ctor(void)
2171 {
2172 struct timespec constructor_timeout;
2173 sigset_t sig_all_blocked, orig_parent_mask;
2174 pthread_attr_t thread_attr;
2175 int timeout_mode;
2176 int ret;
2177 void *handle;
2178
2179 if (uatomic_xchg(&initialized, 1) == 1)
2180 return;
2181
2182 /*
2183 * Fixup interdependency between TLS allocation mutex (which happens
2184 * to be the dynamic linker mutex) and ust_lock, taken within
2185 * the ust lock.
2186 */
2187 lttng_ust_alloc_tls();
2188
2189 lttng_ust_loaded_orig = 1;
2190
2191 /*
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.
2196 */
2197 lttng_ust_check_soname_0();
2198
2199 /*
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.
2213 */
2214 handle = dlopen(LTTNG_UST_LIB_SONAME, RTLD_LAZY | RTLD_NODELETE);
2215 if (!handle) {
2216 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME);
2217 } else {
2218 DBG("dlopened liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME);
2219 }
2220
2221 /*
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).
2226 */
2227
2228 /*
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.
2234 */
2235 lttng_ust_logging_init();
2236 lttng_ust_getenv_init();
2237
2238 /* Call the liblttng-ust-common constructor. */
2239 lttng_ust_common_ctor();
2240
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();
2246 /*
2247 * Invoke ust malloc wrapper init before starting other threads.
2248 */
2249 lttng_ust_libc_wrapper_malloc_ctor();
2250
2251 timeout_mode = get_constructor_timeout(&constructor_timeout);
2252
2253 get_allow_blocking();
2254
2255 ret = sem_init(&constructor_wait, 0, 0);
2256 if (ret) {
2257 PERROR("sem_init");
2258 }
2259
2260 ret = setup_global_apps();
2261 if (ret) {
2262 assert(global_apps.allowed == 0);
2263 DBG("global apps setup returned %d", ret);
2264 }
2265
2266 ret = setup_local_apps();
2267 if (ret) {
2268 assert(local_apps.allowed == 0);
2269 DBG("local apps setup returned %d", ret);
2270 }
2271
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.
2276 */
2277 sigfillset(&sig_all_blocked);
2278 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
2279 if (ret) {
2280 ERR("pthread_sigmask: %s", strerror(ret));
2281 }
2282
2283 ret = pthread_attr_init(&thread_attr);
2284 if (ret) {
2285 ERR("pthread_attr_init: %s", strerror(ret));
2286 }
2287 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
2288 if (ret) {
2289 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
2290 }
2291
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);
2296 if (ret) {
2297 ERR("pthread_create global: %s", strerror(ret));
2298 }
2299 global_apps.thread_active = 1;
2300 pthread_mutex_unlock(&ust_exit_mutex);
2301 } else {
2302 handle_register_done(&global_apps);
2303 }
2304
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);
2309 if (ret) {
2310 ERR("pthread_create local: %s", strerror(ret));
2311 }
2312 local_apps.thread_active = 1;
2313 pthread_mutex_unlock(&ust_exit_mutex);
2314 } else {
2315 handle_register_done(&local_apps);
2316 }
2317 ret = pthread_attr_destroy(&thread_attr);
2318 if (ret) {
2319 ERR("pthread_attr_destroy: %s", strerror(ret));
2320 }
2321
2322 /* Restore original signal mask in parent */
2323 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
2324 if (ret) {
2325 ERR("pthread_sigmask: %s", strerror(ret));
2326 }
2327
2328 switch (timeout_mode) {
2329 case 1: /* timeout wait */
2330 do {
2331 ret = sem_timedwait(&constructor_wait,
2332 &constructor_timeout);
2333 } while (ret < 0 && errno == EINTR);
2334 if (ret < 0) {
2335 switch (errno) {
2336 case ETIMEDOUT:
2337 ERR("Timed out waiting for lttng-sessiond");
2338 break;
2339 case EINVAL:
2340 PERROR("sem_timedwait");
2341 break;
2342 default:
2343 ERR("Unexpected error \"%s\" returned by sem_timedwait",
2344 strerror(errno));
2345 }
2346 }
2347 break;
2348 case -1:/* wait forever */
2349 do {
2350 ret = sem_wait(&constructor_wait);
2351 } while (ret < 0 && errno == EINTR);
2352 if (ret < 0) {
2353 switch (errno) {
2354 case EINVAL:
2355 PERROR("sem_wait");
2356 break;
2357 default:
2358 ERR("Unexpected error \"%s\" returned by sem_wait",
2359 strerror(errno));
2360 }
2361 }
2362 break;
2363 case 0: /* no timeout */
2364 break;
2365 }
2366 }
2367
2368 static
2369 void lttng_ust_cleanup(int exiting)
2370 {
2371 cleanup_sock_info(&global_apps, exiting);
2372 cleanup_sock_info(&local_apps, exiting);
2373 local_apps.allowed = 0;
2374 global_apps.allowed = 0;
2375 /*
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
2380 * point.
2381 */
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();
2389 if (!exiting) {
2390 /* Reinitialize values for fork */
2391 sem_count = sem_count_initial_value;
2392 lttng_ust_comm_should_quit = 0;
2393 initialized = 0;
2394 }
2395 }
2396
2397 static
2398 void lttng_ust_exit(void)
2399 __attribute__((destructor));
2400 static
2401 void lttng_ust_exit(void)
2402 {
2403 int ret;
2404
2405 /*
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.
2409 */
2410
2411 /*
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.
2415 */
2416 ust_lock_nocheck();
2417 lttng_ust_comm_should_quit = 1;
2418 ust_unlock();
2419
2420 pthread_mutex_lock(&ust_exit_mutex);
2421 /* cancel threads */
2422 if (global_apps.thread_active) {
2423 ret = pthread_cancel(global_apps.ust_listener);
2424 if (ret) {
2425 ERR("Error cancelling global ust listener thread: %s",
2426 strerror(ret));
2427 } else {
2428 global_apps.thread_active = 0;
2429 }
2430 }
2431 if (local_apps.thread_active) {
2432 ret = pthread_cancel(local_apps.ust_listener);
2433 if (ret) {
2434 ERR("Error cancelling local ust listener thread: %s",
2435 strerror(ret));
2436 } else {
2437 local_apps.thread_active = 0;
2438 }
2439 }
2440 pthread_mutex_unlock(&ust_exit_mutex);
2441
2442 /*
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.
2449 */
2450 lttng_ust_cleanup(1);
2451 }
2452
2453 static
2454 void ust_context_ns_reset(void)
2455 {
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();
2464 }
2465
2466 static
2467 void ust_context_vuids_reset(void)
2468 {
2469 lttng_context_vuid_reset();
2470 lttng_context_veuid_reset();
2471 lttng_context_vsuid_reset();
2472 }
2473
2474 static
2475 void ust_context_vgids_reset(void)
2476 {
2477 lttng_context_vgid_reset();
2478 lttng_context_vegid_reset();
2479 lttng_context_vsgid_reset();
2480 }
2481
2482 /*
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.
2488 */
2489 void lttng_ust_before_fork(sigset_t *save_sigset)
2490 {
2491 /*
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.
2496 */
2497 sigset_t all_sigs;
2498 int ret;
2499
2500 /* Allocate lttng-ust TLS. */
2501 lttng_ust_alloc_tls();
2502
2503 if (URCU_TLS(lttng_ust_nest_count))
2504 return;
2505 /* Disable signals */
2506 sigfillset(&all_sigs);
2507 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
2508 if (ret == -1) {
2509 PERROR("sigprocmask");
2510 }
2511
2512 pthread_mutex_lock(&ust_fork_mutex);
2513
2514 ust_lock_nocheck();
2515 lttng_ust_urcu_before_fork();
2516 lttng_ust_lock_fd_tracker();
2517 lttng_perf_lock();
2518 }
2519
2520 static void ust_after_fork_common(sigset_t *restore_sigset)
2521 {
2522 int ret;
2523
2524 DBG("process %d", getpid());
2525 lttng_perf_unlock();
2526 lttng_ust_unlock_fd_tracker();
2527 ust_unlock();
2528
2529 pthread_mutex_unlock(&ust_fork_mutex);
2530
2531 /* Restore signals */
2532 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
2533 if (ret == -1) {
2534 PERROR("sigprocmask");
2535 }
2536 }
2537
2538 void lttng_ust_after_fork_parent(sigset_t *restore_sigset)
2539 {
2540 if (URCU_TLS(lttng_ust_nest_count))
2541 return;
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);
2546 }
2547
2548 /*
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.
2553 *
2554 * This is meant for forks() that have tracing in the child between the
2555 * fork and following exec call (if there is any).
2556 */
2557 void lttng_ust_after_fork_child(sigset_t *restore_sigset)
2558 {
2559 if (URCU_TLS(lttng_ust_nest_count))
2560 return;
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);
2573 lttng_ust_ctor();
2574 }
2575
2576 void lttng_ust_after_setns(void)
2577 {
2578 ust_context_ns_reset();
2579 ust_context_vuids_reset();
2580 ust_context_vgids_reset();
2581 }
2582
2583 void lttng_ust_after_unshare(void)
2584 {
2585 ust_context_ns_reset();
2586 ust_context_vuids_reset();
2587 ust_context_vgids_reset();
2588 }
2589
2590 void lttng_ust_after_setuid(void)
2591 {
2592 ust_context_vuids_reset();
2593 }
2594
2595 void lttng_ust_after_seteuid(void)
2596 {
2597 ust_context_vuids_reset();
2598 }
2599
2600 void lttng_ust_after_setreuid(void)
2601 {
2602 ust_context_vuids_reset();
2603 }
2604
2605 void lttng_ust_after_setresuid(void)
2606 {
2607 ust_context_vuids_reset();
2608 }
2609
2610 void lttng_ust_after_setgid(void)
2611 {
2612 ust_context_vgids_reset();
2613 }
2614
2615 void lttng_ust_after_setegid(void)
2616 {
2617 ust_context_vgids_reset();
2618 }
2619
2620 void lttng_ust_after_setregid(void)
2621 {
2622 ust_context_vgids_reset();
2623 }
2624
2625 void lttng_ust_after_setresgid(void)
2626 {
2627 ust_context_vgids_reset();
2628 }
2629
2630 void lttng_ust_sockinfo_session_enabled(void *owner)
2631 {
2632 struct sock_info *sock_info = owner;
2633 sock_info->statedump_pending = 1;
2634 }
2635
2636 /* Custom upgrade 2.12 to 2.13 */
2637 extern int lttng_ust_loaded1 __attribute__((weak, alias("lttng_ust_loaded_orig")));
2638
2639 #ifdef LTTNG_UST_CUSTOM_UPGRADE_CONFLICTING_SYMBOLS
2640 extern int lttng_ust_loaded __attribute__((weak, alias("lttng_ust_loaded_orig")));
2641 #endif
This page took 0.086348 seconds and 6 git commands to generate.