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