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