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