Move the getcpu plugin implementation to liblttn-ust-common
[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 "lttng-counter-client.h"
59 #include "lttng-rb-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_ABI_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_ABI_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_ABI_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 {
625 return ustcomm_send_reg_msg(socket,
626 type,
627 CAA_BITS_PER_LONG,
628 lttng_ust_rb_alignof(uint8_t) * CHAR_BIT,
629 lttng_ust_rb_alignof(uint16_t) * CHAR_BIT,
630 lttng_ust_rb_alignof(uint32_t) * CHAR_BIT,
631 lttng_ust_rb_alignof(uint64_t) * CHAR_BIT,
632 lttng_ust_rb_alignof(unsigned long) * CHAR_BIT);
633 }
634
635 static
636 int send_reply(int sock, struct ustcomm_ust_reply *lur)
637 {
638 ssize_t len;
639
640 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
641 switch (len) {
642 case sizeof(*lur):
643 DBG("message successfully sent");
644 return 0;
645 default:
646 if (len == -ECONNRESET) {
647 DBG("remote end closed connection");
648 return 0;
649 }
650 if (len < 0)
651 return len;
652 DBG("incorrect message size: %zd", len);
653 return -EINVAL;
654 }
655 }
656
657 static
658 void decrement_sem_count(unsigned int count)
659 {
660 int ret;
661
662 assert(uatomic_read(&sem_count) >= count);
663
664 if (uatomic_read(&sem_count) <= 0) {
665 return;
666 }
667
668 ret = uatomic_add_return(&sem_count, -count);
669 if (ret == 0) {
670 ret = sem_post(&constructor_wait);
671 assert(!ret);
672 }
673 }
674
675 static
676 int handle_register_done(struct sock_info *sock_info)
677 {
678 if (sock_info->registration_done)
679 return 0;
680 sock_info->registration_done = 1;
681
682 decrement_sem_count(1);
683 if (!sock_info->statedump_pending) {
684 sock_info->initial_statedump_done = 1;
685 decrement_sem_count(1);
686 }
687
688 return 0;
689 }
690
691 static
692 int handle_register_failed(struct sock_info *sock_info)
693 {
694 if (sock_info->registration_done)
695 return 0;
696 sock_info->registration_done = 1;
697 sock_info->initial_statedump_done = 1;
698
699 decrement_sem_count(2);
700
701 return 0;
702 }
703
704 /*
705 * Only execute pending statedump after the constructor semaphore has
706 * been posted by the current listener thread. This means statedump will
707 * only be performed after the "registration done" command is received
708 * from this thread's session daemon.
709 *
710 * This ensures we don't run into deadlock issues with the dynamic
711 * loader mutex, which is held while the constructor is called and
712 * waiting on the constructor semaphore. All operations requiring this
713 * dynamic loader lock need to be postponed using this mechanism.
714 *
715 * In a scenario with two session daemons connected to the application,
716 * it is possible that the first listener thread which receives the
717 * registration done command issues its statedump while the dynamic
718 * loader lock is still held by the application constructor waiting on
719 * the semaphore. It will however be allowed to proceed when the
720 * second session daemon sends the registration done command to the
721 * second listener thread. This situation therefore does not produce
722 * a deadlock.
723 */
724 static
725 void handle_pending_statedump(struct sock_info *sock_info)
726 {
727 if (sock_info->registration_done && sock_info->statedump_pending) {
728 sock_info->statedump_pending = 0;
729 pthread_mutex_lock(&ust_fork_mutex);
730 lttng_handle_pending_statedump(sock_info);
731 pthread_mutex_unlock(&ust_fork_mutex);
732
733 if (!sock_info->initial_statedump_done) {
734 sock_info->initial_statedump_done = 1;
735 decrement_sem_count(1);
736 }
737 }
738 }
739
740 static inline
741 const char *bytecode_type_str(uint32_t cmd)
742 {
743 switch (cmd) {
744 case LTTNG_UST_ABI_CAPTURE:
745 return "capture";
746 case LTTNG_UST_ABI_FILTER:
747 return "filter";
748 default:
749 abort();
750 }
751 }
752
753 static
754 int handle_bytecode_recv(struct sock_info *sock_info,
755 int sock, struct ustcomm_ust_msg *lum)
756 {
757 struct lttng_ust_bytecode_node *bytecode = NULL;
758 enum lttng_ust_bytecode_type type;
759 const struct lttng_ust_abi_objd_ops *ops;
760 uint32_t data_size, data_size_max, reloc_offset;
761 uint64_t seqnum;
762 ssize_t len;
763 int ret = 0;
764
765 switch (lum->cmd) {
766 case LTTNG_UST_ABI_FILTER:
767 type = LTTNG_UST_BYTECODE_TYPE_FILTER;
768 data_size = lum->u.filter.data_size;
769 data_size_max = LTTNG_UST_ABI_FILTER_BYTECODE_MAX_LEN;
770 reloc_offset = lum->u.filter.reloc_offset;
771 seqnum = lum->u.filter.seqnum;
772 break;
773 case LTTNG_UST_ABI_CAPTURE:
774 type = LTTNG_UST_BYTECODE_TYPE_CAPTURE;
775 data_size = lum->u.capture.data_size;
776 data_size_max = LTTNG_UST_ABI_CAPTURE_BYTECODE_MAX_LEN;
777 reloc_offset = lum->u.capture.reloc_offset;
778 seqnum = lum->u.capture.seqnum;
779 break;
780 default:
781 abort();
782 }
783
784 if (data_size > data_size_max) {
785 ERR("Bytecode %s data size is too large: %u bytes",
786 bytecode_type_str(lum->cmd), data_size);
787 ret = -EINVAL;
788 goto end;
789 }
790
791 if (reloc_offset > data_size) {
792 ERR("Bytecode %s reloc offset %u is not within data",
793 bytecode_type_str(lum->cmd), reloc_offset);
794 ret = -EINVAL;
795 goto end;
796 }
797
798 /* Allocate the structure AND the `data[]` field. */
799 bytecode = zmalloc(sizeof(*bytecode) + data_size);
800 if (!bytecode) {
801 ret = -ENOMEM;
802 goto end;
803 }
804
805 bytecode->bc.len = data_size;
806 bytecode->bc.reloc_offset = reloc_offset;
807 bytecode->bc.seqnum = seqnum;
808 bytecode->type = type;
809
810 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data, bytecode->bc.len);
811 switch (len) {
812 case 0: /* orderly shutdown */
813 ret = 0;
814 goto end;
815 default:
816 if (len == bytecode->bc.len) {
817 DBG("Bytecode %s data received",
818 bytecode_type_str(lum->cmd));
819 break;
820 } else if (len < 0) {
821 DBG("Receive failed from lttng-sessiond with errno %d",
822 (int) -len);
823 if (len == -ECONNRESET) {
824 ERR("%s remote end closed connection",
825 sock_info->name);
826 ret = len;
827 goto end;
828 }
829 ret = len;
830 goto end;
831 } else {
832 DBG("Incorrect %s bytecode data message size: %zd",
833 bytecode_type_str(lum->cmd), len);
834 ret = -EINVAL;
835 goto end;
836 }
837 }
838
839 ops = lttng_ust_abi_objd_ops(lum->handle);
840 if (!ops) {
841 ret = -ENOENT;
842 goto end;
843 }
844
845 if (ops->cmd)
846 ret = ops->cmd(lum->handle, lum->cmd,
847 (unsigned long) &bytecode,
848 NULL, sock_info);
849 else
850 ret = -ENOSYS;
851
852 end:
853 free(bytecode);
854 return ret;
855 }
856
857 static
858 int handle_message(struct sock_info *sock_info,
859 int sock, struct ustcomm_ust_msg *lum)
860 {
861 int ret = 0;
862 const struct lttng_ust_abi_objd_ops *ops;
863 struct ustcomm_ust_reply lur;
864 union lttng_ust_abi_args args;
865 char ctxstr[LTTNG_UST_ABI_SYM_NAME_LEN]; /* App context string. */
866 ssize_t len;
867
868 memset(&lur, 0, sizeof(lur));
869
870 if (ust_lock()) {
871 ret = -LTTNG_UST_ERR_EXITING;
872 goto error;
873 }
874
875 ops = lttng_ust_abi_objd_ops(lum->handle);
876 if (!ops) {
877 ret = -ENOENT;
878 goto error;
879 }
880
881 switch (lum->cmd) {
882 case LTTNG_UST_ABI_REGISTER_DONE:
883 if (lum->handle == LTTNG_UST_ABI_ROOT_HANDLE)
884 ret = handle_register_done(sock_info);
885 else
886 ret = -EINVAL;
887 break;
888 case LTTNG_UST_ABI_RELEASE:
889 if (lum->handle == LTTNG_UST_ABI_ROOT_HANDLE)
890 ret = -EPERM;
891 else
892 ret = lttng_ust_abi_objd_unref(lum->handle, 1);
893 break;
894 case LTTNG_UST_ABI_CAPTURE:
895 case LTTNG_UST_ABI_FILTER:
896 ret = handle_bytecode_recv(sock_info, sock, lum);
897 if (ret)
898 goto error;
899 break;
900 case LTTNG_UST_ABI_EXCLUSION:
901 {
902 /* Receive exclusion names */
903 struct lttng_ust_excluder_node *node;
904 unsigned int count;
905
906 count = lum->u.exclusion.count;
907 if (count == 0) {
908 /* There are no names to read */
909 ret = 0;
910 goto error;
911 }
912 node = zmalloc(sizeof(*node) +
913 count * LTTNG_UST_ABI_SYM_NAME_LEN);
914 if (!node) {
915 ret = -ENOMEM;
916 goto error;
917 }
918 node->excluder.count = count;
919 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
920 count * LTTNG_UST_ABI_SYM_NAME_LEN);
921 switch (len) {
922 case 0: /* orderly shutdown */
923 ret = 0;
924 free(node);
925 goto error;
926 default:
927 if (len == count * LTTNG_UST_ABI_SYM_NAME_LEN) {
928 DBG("Exclusion data received");
929 break;
930 } else if (len < 0) {
931 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
932 if (len == -ECONNRESET) {
933 ERR("%s remote end closed connection", sock_info->name);
934 ret = len;
935 free(node);
936 goto error;
937 }
938 ret = len;
939 free(node);
940 goto error;
941 } else {
942 DBG("Incorrect exclusion data message size: %zd", len);
943 ret = -EINVAL;
944 free(node);
945 goto error;
946 }
947 }
948 if (ops->cmd)
949 ret = ops->cmd(lum->handle, lum->cmd,
950 (unsigned long) &node,
951 &args, sock_info);
952 else
953 ret = -ENOSYS;
954 free(node);
955 break;
956 }
957 case LTTNG_UST_ABI_EVENT_NOTIFIER_GROUP_CREATE:
958 {
959 int event_notifier_notif_fd, close_ret;
960
961 len = ustcomm_recv_event_notifier_notif_fd_from_sessiond(sock,
962 &event_notifier_notif_fd);
963 switch (len) {
964 case 0: /* orderly shutdown */
965 ret = 0;
966 goto error;
967 case 1:
968 break;
969 default:
970 if (len < 0) {
971 DBG("Receive failed from lttng-sessiond with errno %d",
972 (int) -len);
973 if (len == -ECONNRESET) {
974 ERR("%s remote end closed connection",
975 sock_info->name);
976 ret = len;
977 goto error;
978 }
979 ret = len;
980 goto error;
981 } else {
982 DBG("Incorrect event notifier fd message size: %zd",
983 len);
984 ret = -EINVAL;
985 goto error;
986 }
987 }
988 args.event_notifier_handle.event_notifier_notif_fd =
989 event_notifier_notif_fd;
990 if (ops->cmd)
991 ret = ops->cmd(lum->handle, lum->cmd,
992 (unsigned long) &lum->u,
993 &args, sock_info);
994 else
995 ret = -ENOSYS;
996 if (args.event_notifier_handle.event_notifier_notif_fd >= 0) {
997 lttng_ust_lock_fd_tracker();
998 close_ret = close(args.event_notifier_handle.event_notifier_notif_fd);
999 lttng_ust_unlock_fd_tracker();
1000 if (close_ret)
1001 PERROR("close");
1002 }
1003 break;
1004 }
1005 case LTTNG_UST_ABI_CHANNEL:
1006 {
1007 void *chan_data;
1008 int wakeup_fd;
1009
1010 len = ustcomm_recv_channel_from_sessiond(sock,
1011 &chan_data, lum->u.channel.len,
1012 &wakeup_fd);
1013 switch (len) {
1014 case 0: /* orderly shutdown */
1015 ret = 0;
1016 goto error;
1017 default:
1018 if (len == lum->u.channel.len) {
1019 DBG("channel 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 goto error;
1027 }
1028 ret = len;
1029 goto error;
1030 } else {
1031 DBG("incorrect channel data message size: %zd", len);
1032 ret = -EINVAL;
1033 goto error;
1034 }
1035 }
1036 args.channel.chan_data = chan_data;
1037 args.channel.wakeup_fd = wakeup_fd;
1038 if (ops->cmd)
1039 ret = ops->cmd(lum->handle, lum->cmd,
1040 (unsigned long) &lum->u,
1041 &args, sock_info);
1042 else
1043 ret = -ENOSYS;
1044 if (args.channel.wakeup_fd >= 0) {
1045 int close_ret;
1046
1047 lttng_ust_lock_fd_tracker();
1048 close_ret = close(args.channel.wakeup_fd);
1049 lttng_ust_unlock_fd_tracker();
1050 args.channel.wakeup_fd = -1;
1051 if (close_ret)
1052 PERROR("close");
1053 }
1054 free(args.channel.chan_data);
1055 break;
1056 }
1057 case LTTNG_UST_ABI_STREAM:
1058 {
1059 int close_ret;
1060
1061 /* Receive shm_fd, wakeup_fd */
1062 ret = ustcomm_recv_stream_from_sessiond(sock,
1063 NULL,
1064 &args.stream.shm_fd,
1065 &args.stream.wakeup_fd);
1066 if (ret) {
1067 goto error;
1068 }
1069
1070 if (ops->cmd)
1071 ret = ops->cmd(lum->handle, lum->cmd,
1072 (unsigned long) &lum->u,
1073 &args, sock_info);
1074 else
1075 ret = -ENOSYS;
1076 if (args.stream.shm_fd >= 0) {
1077 lttng_ust_lock_fd_tracker();
1078 close_ret = close(args.stream.shm_fd);
1079 lttng_ust_unlock_fd_tracker();
1080 args.stream.shm_fd = -1;
1081 if (close_ret)
1082 PERROR("close");
1083 }
1084 if (args.stream.wakeup_fd >= 0) {
1085 lttng_ust_lock_fd_tracker();
1086 close_ret = close(args.stream.wakeup_fd);
1087 lttng_ust_unlock_fd_tracker();
1088 args.stream.wakeup_fd = -1;
1089 if (close_ret)
1090 PERROR("close");
1091 }
1092 break;
1093 }
1094 case LTTNG_UST_ABI_CONTEXT:
1095 switch (lum->u.context.ctx) {
1096 case LTTNG_UST_ABI_CONTEXT_APP_CONTEXT:
1097 {
1098 char *p;
1099 size_t ctxlen, recvlen;
1100
1101 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
1102 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
1103 if (ctxlen >= LTTNG_UST_ABI_SYM_NAME_LEN) {
1104 ERR("Application context string length size is too large: %zu bytes",
1105 ctxlen);
1106 ret = -EINVAL;
1107 goto error;
1108 }
1109 strcpy(ctxstr, "$app.");
1110 p = &ctxstr[strlen("$app.")];
1111 recvlen = ctxlen - strlen("$app.");
1112 len = ustcomm_recv_unix_sock(sock, p, recvlen);
1113 switch (len) {
1114 case 0: /* orderly shutdown */
1115 ret = 0;
1116 goto error;
1117 default:
1118 if (len == recvlen) {
1119 DBG("app context data received");
1120 break;
1121 } else if (len < 0) {
1122 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1123 if (len == -ECONNRESET) {
1124 ERR("%s remote end closed connection", sock_info->name);
1125 ret = len;
1126 goto error;
1127 }
1128 ret = len;
1129 goto error;
1130 } else {
1131 DBG("incorrect app context data message size: %zd", len);
1132 ret = -EINVAL;
1133 goto error;
1134 }
1135 }
1136 /* Put : between provider and ctxname. */
1137 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
1138 args.app_context.ctxname = ctxstr;
1139 break;
1140 }
1141 default:
1142 break;
1143 }
1144 if (ops->cmd) {
1145 ret = ops->cmd(lum->handle, lum->cmd,
1146 (unsigned long) &lum->u,
1147 &args, sock_info);
1148 } else {
1149 ret = -ENOSYS;
1150 }
1151 break;
1152 case LTTNG_UST_ABI_COUNTER:
1153 {
1154 void *counter_data;
1155
1156 len = ustcomm_recv_counter_from_sessiond(sock,
1157 &counter_data, lum->u.counter.len);
1158 switch (len) {
1159 case 0: /* orderly shutdown */
1160 ret = 0;
1161 goto error;
1162 default:
1163 if (len == lum->u.counter.len) {
1164 DBG("counter data received");
1165 break;
1166 } else if (len < 0) {
1167 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1168 if (len == -ECONNRESET) {
1169 ERR("%s remote end closed connection", sock_info->name);
1170 ret = len;
1171 goto error;
1172 }
1173 ret = len;
1174 goto error;
1175 } else {
1176 DBG("incorrect counter data message size: %zd", len);
1177 ret = -EINVAL;
1178 goto error;
1179 }
1180 }
1181 args.counter.counter_data = counter_data;
1182 if (ops->cmd)
1183 ret = ops->cmd(lum->handle, lum->cmd,
1184 (unsigned long) &lum->u,
1185 &args, sock_info);
1186 else
1187 ret = -ENOSYS;
1188 free(args.counter.counter_data);
1189 break;
1190 }
1191 case LTTNG_UST_ABI_COUNTER_GLOBAL:
1192 {
1193 /* Receive shm_fd */
1194 ret = ustcomm_recv_counter_shm_from_sessiond(sock,
1195 &args.counter_shm.shm_fd);
1196 if (ret) {
1197 goto error;
1198 }
1199
1200 if (ops->cmd)
1201 ret = ops->cmd(lum->handle, lum->cmd,
1202 (unsigned long) &lum->u,
1203 &args, sock_info);
1204 else
1205 ret = -ENOSYS;
1206 if (args.counter_shm.shm_fd >= 0) {
1207 int close_ret;
1208
1209 lttng_ust_lock_fd_tracker();
1210 close_ret = close(args.counter_shm.shm_fd);
1211 lttng_ust_unlock_fd_tracker();
1212 args.counter_shm.shm_fd = -1;
1213 if (close_ret)
1214 PERROR("close");
1215 }
1216 break;
1217 }
1218 case LTTNG_UST_ABI_COUNTER_CPU:
1219 {
1220 /* Receive shm_fd */
1221 ret = ustcomm_recv_counter_shm_from_sessiond(sock,
1222 &args.counter_shm.shm_fd);
1223 if (ret) {
1224 goto error;
1225 }
1226
1227 if (ops->cmd)
1228 ret = ops->cmd(lum->handle, lum->cmd,
1229 (unsigned long) &lum->u,
1230 &args, sock_info);
1231 else
1232 ret = -ENOSYS;
1233 if (args.counter_shm.shm_fd >= 0) {
1234 int close_ret;
1235
1236 lttng_ust_lock_fd_tracker();
1237 close_ret = close(args.counter_shm.shm_fd);
1238 lttng_ust_unlock_fd_tracker();
1239 args.counter_shm.shm_fd = -1;
1240 if (close_ret)
1241 PERROR("close");
1242 }
1243 break;
1244 }
1245 case LTTNG_UST_ABI_EVENT_NOTIFIER_CREATE:
1246 {
1247 /* Receive struct lttng_ust_event_notifier */
1248 struct lttng_ust_abi_event_notifier event_notifier;
1249
1250 if (sizeof(event_notifier) != lum->u.event_notifier.len) {
1251 DBG("incorrect event notifier data message size: %u", lum->u.event_notifier.len);
1252 ret = -EINVAL;
1253 goto error;
1254 }
1255 len = ustcomm_recv_unix_sock(sock, &event_notifier, sizeof(event_notifier));
1256 switch (len) {
1257 case 0: /* orderly shutdown */
1258 ret = 0;
1259 goto error;
1260 default:
1261 if (len == sizeof(event_notifier)) {
1262 DBG("event notifier data received");
1263 break;
1264 } else if (len < 0) {
1265 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1266 if (len == -ECONNRESET) {
1267 ERR("%s remote end closed connection", sock_info->name);
1268 ret = len;
1269 goto error;
1270 }
1271 ret = len;
1272 goto error;
1273 } else {
1274 DBG("incorrect event notifier data message size: %zd", len);
1275 ret = -EINVAL;
1276 goto error;
1277 }
1278 }
1279 if (ops->cmd)
1280 ret = ops->cmd(lum->handle, lum->cmd,
1281 (unsigned long) &event_notifier,
1282 &args, sock_info);
1283 else
1284 ret = -ENOSYS;
1285 break;
1286 }
1287
1288 default:
1289 if (ops->cmd)
1290 ret = ops->cmd(lum->handle, lum->cmd,
1291 (unsigned long) &lum->u,
1292 &args, sock_info);
1293 else
1294 ret = -ENOSYS;
1295 break;
1296 }
1297
1298 lur.handle = lum->handle;
1299 lur.cmd = lum->cmd;
1300 lur.ret_val = ret;
1301 if (ret >= 0) {
1302 lur.ret_code = LTTNG_UST_OK;
1303 } else {
1304 /*
1305 * Use -LTTNG_UST_ERR as wildcard for UST internal
1306 * error that are not caused by the transport, except if
1307 * we already have a more precise error message to
1308 * report.
1309 */
1310 if (ret > -LTTNG_UST_ERR) {
1311 /* Translate code to UST error. */
1312 switch (ret) {
1313 case -EEXIST:
1314 lur.ret_code = -LTTNG_UST_ERR_EXIST;
1315 break;
1316 case -EINVAL:
1317 lur.ret_code = -LTTNG_UST_ERR_INVAL;
1318 break;
1319 case -ENOENT:
1320 lur.ret_code = -LTTNG_UST_ERR_NOENT;
1321 break;
1322 case -EPERM:
1323 lur.ret_code = -LTTNG_UST_ERR_PERM;
1324 break;
1325 case -ENOSYS:
1326 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
1327 break;
1328 default:
1329 lur.ret_code = -LTTNG_UST_ERR;
1330 break;
1331 }
1332 } else {
1333 lur.ret_code = ret;
1334 }
1335 }
1336 if (ret >= 0) {
1337 switch (lum->cmd) {
1338 case LTTNG_UST_ABI_TRACER_VERSION:
1339 lur.u.version = lum->u.version;
1340 break;
1341 case LTTNG_UST_ABI_TRACEPOINT_LIST_GET:
1342 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1343 break;
1344 }
1345 }
1346 DBG("Return value: %d", lur.ret_val);
1347
1348 ust_unlock();
1349
1350 /*
1351 * Performed delayed statedump operations outside of the UST
1352 * lock. We need to take the dynamic loader lock before we take
1353 * the UST lock internally within handle_pending_statedump().
1354 */
1355 handle_pending_statedump(sock_info);
1356
1357 if (ust_lock()) {
1358 ret = -LTTNG_UST_ERR_EXITING;
1359 goto error;
1360 }
1361
1362 ret = send_reply(sock, &lur);
1363 if (ret < 0) {
1364 DBG("error sending reply");
1365 goto error;
1366 }
1367
1368 /*
1369 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1370 * after the reply.
1371 */
1372 if (lur.ret_code == LTTNG_UST_OK) {
1373 switch (lum->cmd) {
1374 case LTTNG_UST_ABI_TRACEPOINT_FIELD_LIST_GET:
1375 len = ustcomm_send_unix_sock(sock,
1376 &args.field_list.entry,
1377 sizeof(args.field_list.entry));
1378 if (len < 0) {
1379 ret = len;
1380 goto error;
1381 }
1382 if (len != sizeof(args.field_list.entry)) {
1383 ret = -EINVAL;
1384 goto error;
1385 }
1386 }
1387 }
1388
1389 error:
1390 ust_unlock();
1391
1392 return ret;
1393 }
1394
1395 static
1396 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
1397 {
1398 int ret;
1399
1400 if (sock_info->root_handle != -1) {
1401 ret = lttng_ust_abi_objd_unref(sock_info->root_handle, 1);
1402 if (ret) {
1403 ERR("Error unref root handle");
1404 }
1405 sock_info->root_handle = -1;
1406 }
1407 sock_info->registration_done = 0;
1408 sock_info->initial_statedump_done = 0;
1409
1410 /*
1411 * wait_shm_mmap, socket and notify socket are used by listener
1412 * threads outside of the ust lock, so we cannot tear them down
1413 * ourselves, because we cannot join on these threads. Leave
1414 * responsibility of cleaning up these resources to the OS
1415 * process exit.
1416 */
1417 if (exiting)
1418 return;
1419
1420 if (sock_info->socket != -1) {
1421 ret = ustcomm_close_unix_sock(sock_info->socket);
1422 if (ret) {
1423 ERR("Error closing ust cmd socket");
1424 }
1425 sock_info->socket = -1;
1426 }
1427 if (sock_info->notify_socket != -1) {
1428 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1429 if (ret) {
1430 ERR("Error closing ust notify socket");
1431 }
1432 sock_info->notify_socket = -1;
1433 }
1434 if (sock_info->wait_shm_mmap) {
1435 long page_size;
1436
1437 page_size = LTTNG_UST_PAGE_SIZE;
1438 if (page_size <= 0) {
1439 if (!page_size) {
1440 errno = EINVAL;
1441 }
1442 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1443 } else {
1444 ret = munmap(sock_info->wait_shm_mmap, page_size);
1445 if (ret) {
1446 ERR("Error unmapping wait shm");
1447 }
1448 }
1449 sock_info->wait_shm_mmap = NULL;
1450 }
1451 }
1452
1453 /*
1454 * Using fork to set umask in the child process (not multi-thread safe).
1455 * We deal with the shm_open vs ftruncate race (happening when the
1456 * sessiond owns the shm and does not let everybody modify it, to ensure
1457 * safety against shm_unlink) by simply letting the mmap fail and
1458 * retrying after a few seconds.
1459 * For global shm, everybody has rw access to it until the sessiond
1460 * starts.
1461 */
1462 static
1463 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
1464 {
1465 int wait_shm_fd, ret;
1466 pid_t pid;
1467
1468 /*
1469 * Try to open read-only.
1470 */
1471 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1472 if (wait_shm_fd >= 0) {
1473 int32_t tmp_read;
1474 ssize_t len;
1475 size_t bytes_read = 0;
1476
1477 /*
1478 * Try to read the fd. If unable to do so, try opening
1479 * it in write mode.
1480 */
1481 do {
1482 len = read(wait_shm_fd,
1483 &((char *) &tmp_read)[bytes_read],
1484 sizeof(tmp_read) - bytes_read);
1485 if (len > 0) {
1486 bytes_read += len;
1487 }
1488 } while ((len < 0 && errno == EINTR)
1489 || (len > 0 && bytes_read < sizeof(tmp_read)));
1490 if (bytes_read != sizeof(tmp_read)) {
1491 ret = close(wait_shm_fd);
1492 if (ret) {
1493 ERR("close wait_shm_fd");
1494 }
1495 goto open_write;
1496 }
1497 goto end;
1498 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1499 /*
1500 * Real-only open did not work, and it's not because the
1501 * entry was not present. It's a failure that prohibits
1502 * using shm.
1503 */
1504 ERR("Error opening shm %s", sock_info->wait_shm_path);
1505 goto end;
1506 }
1507
1508 open_write:
1509 /*
1510 * If the open failed because the file did not exist, or because
1511 * the file was not truncated yet, try creating it ourself.
1512 */
1513 URCU_TLS(lttng_ust_nest_count)++;
1514 pid = fork();
1515 URCU_TLS(lttng_ust_nest_count)--;
1516 if (pid > 0) {
1517 int status;
1518
1519 /*
1520 * Parent: wait for child to return, in which case the
1521 * shared memory map will have been created.
1522 */
1523 pid = wait(&status);
1524 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1525 wait_shm_fd = -1;
1526 goto end;
1527 }
1528 /*
1529 * Try to open read-only again after creation.
1530 */
1531 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1532 if (wait_shm_fd < 0) {
1533 /*
1534 * Real-only open did not work. It's a failure
1535 * that prohibits using shm.
1536 */
1537 ERR("Error opening shm %s", sock_info->wait_shm_path);
1538 goto end;
1539 }
1540 goto end;
1541 } else if (pid == 0) {
1542 int create_mode;
1543
1544 /* Child */
1545 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
1546 if (sock_info->global)
1547 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
1548 /*
1549 * We're alone in a child process, so we can modify the
1550 * process-wide umask.
1551 */
1552 umask(~create_mode);
1553 /*
1554 * Try creating shm (or get rw access).
1555 * We don't do an exclusive open, because we allow other
1556 * processes to create+ftruncate it concurrently.
1557 */
1558 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1559 O_RDWR | O_CREAT, create_mode);
1560 if (wait_shm_fd >= 0) {
1561 ret = ftruncate(wait_shm_fd, mmap_size);
1562 if (ret) {
1563 PERROR("ftruncate");
1564 _exit(EXIT_FAILURE);
1565 }
1566 _exit(EXIT_SUCCESS);
1567 }
1568 /*
1569 * For local shm, we need to have rw access to accept
1570 * opening it: this means the local sessiond will be
1571 * able to wake us up. For global shm, we open it even
1572 * if rw access is not granted, because the root.root
1573 * sessiond will be able to override all rights and wake
1574 * us up.
1575 */
1576 if (!sock_info->global && errno != EACCES) {
1577 ERR("Error opening shm %s", sock_info->wait_shm_path);
1578 _exit(EXIT_FAILURE);
1579 }
1580 /*
1581 * The shm exists, but we cannot open it RW. Report
1582 * success.
1583 */
1584 _exit(EXIT_SUCCESS);
1585 } else {
1586 return -1;
1587 }
1588 end:
1589 if (wait_shm_fd >= 0 && !sock_info->global) {
1590 struct stat statbuf;
1591
1592 /*
1593 * Ensure that our user is the owner of the shm file for
1594 * local shm. If we do not own the file, it means our
1595 * sessiond will not have access to wake us up (there is
1596 * probably a rogue process trying to fake our
1597 * sessiond). Fallback to polling method in this case.
1598 */
1599 ret = fstat(wait_shm_fd, &statbuf);
1600 if (ret) {
1601 PERROR("fstat");
1602 goto error_close;
1603 }
1604 if (statbuf.st_uid != getuid())
1605 goto error_close;
1606 }
1607 return wait_shm_fd;
1608
1609 error_close:
1610 ret = close(wait_shm_fd);
1611 if (ret) {
1612 PERROR("Error closing fd");
1613 }
1614 return -1;
1615 }
1616
1617 static
1618 char *get_map_shm(struct sock_info *sock_info)
1619 {
1620 long page_size;
1621 int wait_shm_fd, ret;
1622 char *wait_shm_mmap;
1623
1624 page_size = sysconf(_SC_PAGE_SIZE);
1625 if (page_size <= 0) {
1626 if (!page_size) {
1627 errno = EINVAL;
1628 }
1629 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1630 goto error;
1631 }
1632
1633 lttng_ust_lock_fd_tracker();
1634 wait_shm_fd = get_wait_shm(sock_info, page_size);
1635 if (wait_shm_fd < 0) {
1636 lttng_ust_unlock_fd_tracker();
1637 goto error;
1638 }
1639
1640 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1641 if (ret < 0) {
1642 ret = close(wait_shm_fd);
1643 if (!ret) {
1644 PERROR("Error closing fd");
1645 }
1646 lttng_ust_unlock_fd_tracker();
1647 goto error;
1648 }
1649
1650 wait_shm_fd = ret;
1651 lttng_ust_unlock_fd_tracker();
1652
1653 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
1654 MAP_SHARED, wait_shm_fd, 0);
1655
1656 /* close shm fd immediately after taking the mmap reference */
1657 lttng_ust_lock_fd_tracker();
1658 ret = close(wait_shm_fd);
1659 if (!ret) {
1660 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1661 } else {
1662 PERROR("Error closing fd");
1663 }
1664 lttng_ust_unlock_fd_tracker();
1665
1666 if (wait_shm_mmap == MAP_FAILED) {
1667 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1668 goto error;
1669 }
1670 return wait_shm_mmap;
1671
1672 error:
1673 return NULL;
1674 }
1675
1676 static
1677 void wait_for_sessiond(struct sock_info *sock_info)
1678 {
1679 /* Use ust_lock to check if we should quit. */
1680 if (ust_lock()) {
1681 goto quit;
1682 }
1683 if (wait_poll_fallback) {
1684 goto error;
1685 }
1686 ust_unlock();
1687
1688 assert(sock_info->wait_shm_mmap);
1689
1690 DBG("Waiting for %s apps sessiond", sock_info->name);
1691 /* Wait for futex wakeup */
1692 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1693 goto end_wait;
1694
1695 while (lttng_ust_futex_async((int32_t *) sock_info->wait_shm_mmap,
1696 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1697 switch (errno) {
1698 case EWOULDBLOCK:
1699 /* Value already changed. */
1700 goto end_wait;
1701 case EINTR:
1702 /* Retry if interrupted by signal. */
1703 break; /* Get out of switch. */
1704 case EFAULT:
1705 wait_poll_fallback = 1;
1706 DBG(
1707 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1708 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1709 "Please upgrade your kernel "
1710 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1711 "mainline). LTTng-UST will use polling mode fallback.");
1712 if (lttng_ust_logging_debug_enabled())
1713 PERROR("futex");
1714 goto end_wait;
1715 }
1716 }
1717 end_wait:
1718 return;
1719
1720 quit:
1721 ust_unlock();
1722 return;
1723
1724 error:
1725 ust_unlock();
1726 return;
1727 }
1728
1729 /*
1730 * This thread does not allocate any resource, except within
1731 * handle_message, within mutex protection. This mutex protects against
1732 * fork and exit.
1733 * The other moment it allocates resources is at socket connection, which
1734 * is also protected by the mutex.
1735 */
1736 static
1737 void *ust_listener_thread(void *arg)
1738 {
1739 struct sock_info *sock_info = arg;
1740 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
1741 long timeout;
1742
1743 lttng_ust_alloc_tls();
1744 /*
1745 * If available, add '-ust' to the end of this thread's
1746 * process name
1747 */
1748 ret = lttng_ust_setustprocname();
1749 if (ret) {
1750 ERR("Unable to set UST process name");
1751 }
1752
1753 /* Restart trying to connect to the session daemon */
1754 restart:
1755 if (prev_connect_failed) {
1756 /* Wait for sessiond availability with pipe */
1757 wait_for_sessiond(sock_info);
1758 if (has_waited) {
1759 has_waited = 0;
1760 /*
1761 * Sleep for 5 seconds before retrying after a
1762 * sequence of failure / wait / failure. This
1763 * deals with a killed or broken session daemon.
1764 */
1765 sleep(5);
1766 } else {
1767 has_waited = 1;
1768 }
1769 prev_connect_failed = 0;
1770 }
1771
1772 if (ust_lock()) {
1773 goto quit;
1774 }
1775
1776 if (sock_info->socket != -1) {
1777 /* FD tracker is updated by ustcomm_close_unix_sock() */
1778 ret = ustcomm_close_unix_sock(sock_info->socket);
1779 if (ret) {
1780 ERR("Error closing %s ust cmd socket",
1781 sock_info->name);
1782 }
1783 sock_info->socket = -1;
1784 }
1785 if (sock_info->notify_socket != -1) {
1786 /* FD tracker is updated by ustcomm_close_unix_sock() */
1787 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1788 if (ret) {
1789 ERR("Error closing %s ust notify socket",
1790 sock_info->name);
1791 }
1792 sock_info->notify_socket = -1;
1793 }
1794
1795
1796 /*
1797 * Register. We need to perform both connect and sending
1798 * registration message before doing the next connect otherwise
1799 * we may reach unix socket connect queue max limits and block
1800 * on the 2nd connect while the session daemon is awaiting the
1801 * first connect registration message.
1802 */
1803 /* Connect cmd socket */
1804 lttng_ust_lock_fd_tracker();
1805 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1806 get_connect_sock_timeout());
1807 if (ret < 0) {
1808 lttng_ust_unlock_fd_tracker();
1809 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1810 prev_connect_failed = 1;
1811
1812 /*
1813 * If we cannot find the sessiond daemon, don't delay
1814 * constructor execution.
1815 */
1816 ret = handle_register_failed(sock_info);
1817 assert(!ret);
1818 ust_unlock();
1819 goto restart;
1820 }
1821 fd = ret;
1822 ret = lttng_ust_add_fd_to_tracker(fd);
1823 if (ret < 0) {
1824 ret = close(fd);
1825 if (ret) {
1826 PERROR("close on sock_info->socket");
1827 }
1828 ret = -1;
1829 lttng_ust_unlock_fd_tracker();
1830 ust_unlock();
1831 goto quit;
1832 }
1833
1834 sock_info->socket = ret;
1835 lttng_ust_unlock_fd_tracker();
1836
1837 ust_unlock();
1838 /*
1839 * Unlock/relock ust lock because connect is blocking (with
1840 * timeout). Don't delay constructors on the ust lock for too
1841 * long.
1842 */
1843 if (ust_lock()) {
1844 goto quit;
1845 }
1846
1847 /*
1848 * Create only one root handle per listener thread for the whole
1849 * process lifetime, so we ensure we get ID which is statically
1850 * assigned to the root handle.
1851 */
1852 if (sock_info->root_handle == -1) {
1853 ret = lttng_abi_create_root_handle();
1854 if (ret < 0) {
1855 ERR("Error creating root handle");
1856 goto quit;
1857 }
1858 sock_info->root_handle = ret;
1859 }
1860
1861 ret = register_to_sessiond(sock_info->socket, LTTNG_UST_CTL_SOCKET_CMD);
1862 if (ret < 0) {
1863 ERR("Error registering to %s ust cmd socket",
1864 sock_info->name);
1865 prev_connect_failed = 1;
1866 /*
1867 * If we cannot register to the sessiond daemon, don't
1868 * delay constructor execution.
1869 */
1870 ret = handle_register_failed(sock_info);
1871 assert(!ret);
1872 ust_unlock();
1873 goto restart;
1874 }
1875
1876 ust_unlock();
1877 /*
1878 * Unlock/relock ust lock because connect is blocking (with
1879 * timeout). Don't delay constructors on the ust lock for too
1880 * long.
1881 */
1882 if (ust_lock()) {
1883 goto quit;
1884 }
1885
1886 /* Connect notify socket */
1887 lttng_ust_lock_fd_tracker();
1888 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1889 get_connect_sock_timeout());
1890 if (ret < 0) {
1891 lttng_ust_unlock_fd_tracker();
1892 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1893 prev_connect_failed = 1;
1894
1895 /*
1896 * If we cannot find the sessiond daemon, don't delay
1897 * constructor execution.
1898 */
1899 ret = handle_register_failed(sock_info);
1900 assert(!ret);
1901 ust_unlock();
1902 goto restart;
1903 }
1904
1905 fd = ret;
1906 ret = lttng_ust_add_fd_to_tracker(fd);
1907 if (ret < 0) {
1908 ret = close(fd);
1909 if (ret) {
1910 PERROR("close on sock_info->notify_socket");
1911 }
1912 ret = -1;
1913 lttng_ust_unlock_fd_tracker();
1914 ust_unlock();
1915 goto quit;
1916 }
1917
1918 sock_info->notify_socket = ret;
1919 lttng_ust_unlock_fd_tracker();
1920
1921 ust_unlock();
1922 /*
1923 * Unlock/relock ust lock because connect is blocking (with
1924 * timeout). Don't delay constructors on the ust lock for too
1925 * long.
1926 */
1927 if (ust_lock()) {
1928 goto quit;
1929 }
1930
1931 timeout = get_notify_sock_timeout();
1932 if (timeout >= 0) {
1933 /*
1934 * Give at least 10ms to sessiond to reply to
1935 * notifications.
1936 */
1937 if (timeout < 10)
1938 timeout = 10;
1939 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1940 timeout);
1941 if (ret < 0) {
1942 WARN("Error setting socket receive timeout");
1943 }
1944 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1945 timeout);
1946 if (ret < 0) {
1947 WARN("Error setting socket send timeout");
1948 }
1949 } else if (timeout < -1) {
1950 WARN("Unsupported timeout value %ld", timeout);
1951 }
1952
1953 ret = register_to_sessiond(sock_info->notify_socket,
1954 LTTNG_UST_CTL_SOCKET_NOTIFY);
1955 if (ret < 0) {
1956 ERR("Error registering to %s ust notify socket",
1957 sock_info->name);
1958 prev_connect_failed = 1;
1959 /*
1960 * If we cannot register to the sessiond daemon, don't
1961 * delay constructor execution.
1962 */
1963 ret = handle_register_failed(sock_info);
1964 assert(!ret);
1965 ust_unlock();
1966 goto restart;
1967 }
1968 sock = sock_info->socket;
1969
1970 ust_unlock();
1971
1972 for (;;) {
1973 ssize_t len;
1974 struct ustcomm_ust_msg lum;
1975
1976 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1977 switch (len) {
1978 case 0: /* orderly shutdown */
1979 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
1980 if (ust_lock()) {
1981 goto quit;
1982 }
1983 /*
1984 * Either sessiond has shutdown or refused us by closing the socket.
1985 * In either case, we don't want to delay construction execution,
1986 * and we need to wait before retry.
1987 */
1988 prev_connect_failed = 1;
1989 /*
1990 * If we cannot register to the sessiond daemon, don't
1991 * delay constructor execution.
1992 */
1993 ret = handle_register_failed(sock_info);
1994 assert(!ret);
1995 ust_unlock();
1996 goto end;
1997 case sizeof(lum):
1998 print_cmd(lum.cmd, lum.handle);
1999 ret = handle_message(sock_info, sock, &lum);
2000 if (ret) {
2001 ERR("Error handling message for %s socket",
2002 sock_info->name);
2003 /*
2004 * Close socket if protocol error is
2005 * detected.
2006 */
2007 goto end;
2008 }
2009 continue;
2010 default:
2011 if (len < 0) {
2012 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
2013 } else {
2014 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
2015 }
2016 if (len == -ECONNRESET) {
2017 DBG("%s remote end closed connection", sock_info->name);
2018 goto end;
2019 }
2020 goto end;
2021 }
2022
2023 }
2024 end:
2025 if (ust_lock()) {
2026 goto quit;
2027 }
2028 /* Cleanup socket handles before trying to reconnect */
2029 lttng_ust_abi_objd_table_owner_cleanup(sock_info);
2030 ust_unlock();
2031 goto restart; /* try to reconnect */
2032
2033 quit:
2034 ust_unlock();
2035
2036 pthread_mutex_lock(&ust_exit_mutex);
2037 sock_info->thread_active = 0;
2038 pthread_mutex_unlock(&ust_exit_mutex);
2039 return NULL;
2040 }
2041
2042 /*
2043 * Weak symbol to call when the ust malloc wrapper is not loaded.
2044 */
2045 __attribute__((weak))
2046 void lttng_ust_libc_wrapper_malloc_ctor(void)
2047 {
2048 }
2049
2050 /*
2051 * sessiond monitoring thread: monitor presence of global and per-user
2052 * sessiond by polling the application common named pipe.
2053 */
2054 static
2055 void lttng_ust_ctor(void)
2056 __attribute__((constructor));
2057 static
2058 void lttng_ust_ctor(void)
2059 {
2060 struct timespec constructor_timeout;
2061 sigset_t sig_all_blocked, orig_parent_mask;
2062 pthread_attr_t thread_attr;
2063 int timeout_mode;
2064 int ret;
2065 void *handle;
2066
2067 if (uatomic_xchg(&initialized, 1) == 1)
2068 return;
2069
2070 /*
2071 * Fixup interdependency between TLS allocation mutex (which happens
2072 * to be the dynamic linker mutex) and ust_lock, taken within
2073 * the ust lock.
2074 */
2075 lttng_ust_alloc_tls();
2076
2077 lttng_ust_loaded = 1;
2078
2079 /*
2080 * We need to ensure that the liblttng-ust library is not unloaded to avoid
2081 * the unloading of code used by the ust_listener_threads as we can not
2082 * reliably know when they exited. To do that, manually load
2083 * liblttng-ust.so to increment the dynamic loader's internal refcount for
2084 * this library so it never becomes zero, thus never gets unloaded from the
2085 * address space of the process. Since we are already running in the
2086 * constructor of the LTTNG_UST_LIB_SONAME library, calling dlopen will
2087 * simply increment the refcount and no additionnal work is needed by the
2088 * dynamic loader as the shared library is already loaded in the address
2089 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
2090 * unloading of the UST library if its refcount becomes zero (which should
2091 * never happen). Do the return value check but discard the handle at the
2092 * end of the function as it's not needed.
2093 */
2094 handle = dlopen(LTTNG_UST_LIB_SONAME, RTLD_LAZY | RTLD_NODELETE);
2095 if (!handle) {
2096 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SONAME);
2097 }
2098
2099 /*
2100 * We want precise control over the order in which we construct
2101 * our sub-libraries vs starting to receive commands from
2102 * sessiond (otherwise leading to errors when trying to create
2103 * sessiond before the init functions are completed).
2104 */
2105
2106 /*
2107 * Both the logging and getenv lazy-initialization uses getenv()
2108 * internally and thus needs to be explicitly initialized in
2109 * liblttng-ust before we start any threads as an unsuspecting normally
2110 * single threaded application using liblttng-ust could be using
2111 * setenv() which is not thread-safe.
2112 */
2113 lttng_ust_logging_init();
2114 lttng_ust_getenv_init();
2115
2116 /* Call the liblttng-ust-common constructor. */
2117 lttng_ust_common_ctor();
2118
2119 lttng_ust_tp_init();
2120 lttng_ust_statedump_init();
2121 lttng_ust_ring_buffer_clients_init();
2122 lttng_ust_counter_clients_init();
2123 lttng_perf_counter_init();
2124 /*
2125 * Invoke ust malloc wrapper init before starting other threads.
2126 */
2127 lttng_ust_libc_wrapper_malloc_ctor();
2128
2129 timeout_mode = get_constructor_timeout(&constructor_timeout);
2130
2131 get_allow_blocking();
2132
2133 ret = sem_init(&constructor_wait, 0, 0);
2134 if (ret) {
2135 PERROR("sem_init");
2136 }
2137
2138 ret = setup_global_apps();
2139 if (ret) {
2140 assert(global_apps.allowed == 0);
2141 DBG("global apps setup returned %d", ret);
2142 }
2143
2144 ret = setup_local_apps();
2145 if (ret) {
2146 assert(local_apps.allowed == 0);
2147 DBG("local apps setup returned %d", ret);
2148 }
2149
2150 /* A new thread created by pthread_create inherits the signal mask
2151 * from the parent. To avoid any signal being received by the
2152 * listener thread, we block all signals temporarily in the parent,
2153 * while we create the listener thread.
2154 */
2155 sigfillset(&sig_all_blocked);
2156 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
2157 if (ret) {
2158 ERR("pthread_sigmask: %s", strerror(ret));
2159 }
2160
2161 ret = pthread_attr_init(&thread_attr);
2162 if (ret) {
2163 ERR("pthread_attr_init: %s", strerror(ret));
2164 }
2165 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
2166 if (ret) {
2167 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
2168 }
2169
2170 if (global_apps.allowed) {
2171 pthread_mutex_lock(&ust_exit_mutex);
2172 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
2173 ust_listener_thread, &global_apps);
2174 if (ret) {
2175 ERR("pthread_create global: %s", strerror(ret));
2176 }
2177 global_apps.thread_active = 1;
2178 pthread_mutex_unlock(&ust_exit_mutex);
2179 } else {
2180 handle_register_done(&global_apps);
2181 }
2182
2183 if (local_apps.allowed) {
2184 pthread_mutex_lock(&ust_exit_mutex);
2185 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
2186 ust_listener_thread, &local_apps);
2187 if (ret) {
2188 ERR("pthread_create local: %s", strerror(ret));
2189 }
2190 local_apps.thread_active = 1;
2191 pthread_mutex_unlock(&ust_exit_mutex);
2192 } else {
2193 handle_register_done(&local_apps);
2194 }
2195 ret = pthread_attr_destroy(&thread_attr);
2196 if (ret) {
2197 ERR("pthread_attr_destroy: %s", strerror(ret));
2198 }
2199
2200 /* Restore original signal mask in parent */
2201 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
2202 if (ret) {
2203 ERR("pthread_sigmask: %s", strerror(ret));
2204 }
2205
2206 switch (timeout_mode) {
2207 case 1: /* timeout wait */
2208 do {
2209 ret = sem_timedwait(&constructor_wait,
2210 &constructor_timeout);
2211 } while (ret < 0 && errno == EINTR);
2212 if (ret < 0) {
2213 switch (errno) {
2214 case ETIMEDOUT:
2215 ERR("Timed out waiting for lttng-sessiond");
2216 break;
2217 case EINVAL:
2218 PERROR("sem_timedwait");
2219 break;
2220 default:
2221 ERR("Unexpected error \"%s\" returned by sem_timedwait",
2222 strerror(errno));
2223 }
2224 }
2225 break;
2226 case -1:/* wait forever */
2227 do {
2228 ret = sem_wait(&constructor_wait);
2229 } while (ret < 0 && errno == EINTR);
2230 if (ret < 0) {
2231 switch (errno) {
2232 case EINVAL:
2233 PERROR("sem_wait");
2234 break;
2235 default:
2236 ERR("Unexpected error \"%s\" returned by sem_wait",
2237 strerror(errno));
2238 }
2239 }
2240 break;
2241 case 0: /* no timeout */
2242 break;
2243 }
2244 }
2245
2246 static
2247 void lttng_ust_cleanup(int exiting)
2248 {
2249 cleanup_sock_info(&global_apps, exiting);
2250 cleanup_sock_info(&local_apps, exiting);
2251 local_apps.allowed = 0;
2252 global_apps.allowed = 0;
2253 /*
2254 * The teardown in this function all affect data structures
2255 * accessed under the UST lock by the listener thread. This
2256 * lock, along with the lttng_ust_comm_should_quit flag, ensure
2257 * that none of these threads are accessing this data at this
2258 * point.
2259 */
2260 lttng_ust_abi_exit();
2261 lttng_ust_abi_events_exit();
2262 lttng_perf_counter_exit();
2263 lttng_ust_ring_buffer_clients_exit();
2264 lttng_ust_counter_clients_exit();
2265 lttng_ust_statedump_destroy();
2266 lttng_ust_tp_exit();
2267 if (!exiting) {
2268 /* Reinitialize values for fork */
2269 sem_count = sem_count_initial_value;
2270 lttng_ust_comm_should_quit = 0;
2271 initialized = 0;
2272 }
2273 }
2274
2275 static
2276 void lttng_ust_exit(void)
2277 __attribute__((destructor));
2278 static
2279 void lttng_ust_exit(void)
2280 {
2281 int ret;
2282
2283 /*
2284 * Using pthread_cancel here because:
2285 * A) we don't want to hang application teardown.
2286 * B) the thread is not allocating any resource.
2287 */
2288
2289 /*
2290 * Require the communication thread to quit. Synchronize with
2291 * mutexes to ensure it is not in a mutex critical section when
2292 * pthread_cancel is later called.
2293 */
2294 ust_lock_nocheck();
2295 lttng_ust_comm_should_quit = 1;
2296 ust_unlock();
2297
2298 pthread_mutex_lock(&ust_exit_mutex);
2299 /* cancel threads */
2300 if (global_apps.thread_active) {
2301 ret = pthread_cancel(global_apps.ust_listener);
2302 if (ret) {
2303 ERR("Error cancelling global ust listener thread: %s",
2304 strerror(ret));
2305 } else {
2306 global_apps.thread_active = 0;
2307 }
2308 }
2309 if (local_apps.thread_active) {
2310 ret = pthread_cancel(local_apps.ust_listener);
2311 if (ret) {
2312 ERR("Error cancelling local ust listener thread: %s",
2313 strerror(ret));
2314 } else {
2315 local_apps.thread_active = 0;
2316 }
2317 }
2318 pthread_mutex_unlock(&ust_exit_mutex);
2319
2320 /*
2321 * Do NOT join threads: use of sys_futex makes it impossible to
2322 * join the threads without using async-cancel, but async-cancel
2323 * is delivered by a signal, which could hit the target thread
2324 * anywhere in its code path, including while the ust_lock() is
2325 * held, causing a deadlock for the other thread. Let the OS
2326 * cleanup the threads if there are stalled in a syscall.
2327 */
2328 lttng_ust_cleanup(1);
2329 }
2330
2331 static
2332 void ust_context_ns_reset(void)
2333 {
2334 lttng_context_pid_ns_reset();
2335 lttng_context_cgroup_ns_reset();
2336 lttng_context_ipc_ns_reset();
2337 lttng_context_mnt_ns_reset();
2338 lttng_context_net_ns_reset();
2339 lttng_context_user_ns_reset();
2340 lttng_context_time_ns_reset();
2341 lttng_context_uts_ns_reset();
2342 }
2343
2344 static
2345 void ust_context_vuids_reset(void)
2346 {
2347 lttng_context_vuid_reset();
2348 lttng_context_veuid_reset();
2349 lttng_context_vsuid_reset();
2350 }
2351
2352 static
2353 void ust_context_vgids_reset(void)
2354 {
2355 lttng_context_vgid_reset();
2356 lttng_context_vegid_reset();
2357 lttng_context_vsgid_reset();
2358 }
2359
2360 /*
2361 * We exclude the worker threads across fork and clone (except
2362 * CLONE_VM), because these system calls only keep the forking thread
2363 * running in the child. Therefore, we don't want to call fork or clone
2364 * in the middle of an tracepoint or ust tracing state modification.
2365 * Holding this mutex protects these structures across fork and clone.
2366 */
2367 void lttng_ust_before_fork(sigset_t *save_sigset)
2368 {
2369 /*
2370 * Disable signals. This is to avoid that the child intervenes
2371 * before it is properly setup for tracing. It is safer to
2372 * disable all signals, because then we know we are not breaking
2373 * anything by restoring the original mask.
2374 */
2375 sigset_t all_sigs;
2376 int ret;
2377
2378 /* Allocate lttng-ust TLS. */
2379 lttng_ust_alloc_tls();
2380
2381 if (URCU_TLS(lttng_ust_nest_count))
2382 return;
2383 /* Disable signals */
2384 sigfillset(&all_sigs);
2385 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
2386 if (ret == -1) {
2387 PERROR("sigprocmask");
2388 }
2389
2390 pthread_mutex_lock(&ust_fork_mutex);
2391
2392 ust_lock_nocheck();
2393 lttng_ust_urcu_before_fork();
2394 lttng_ust_lock_fd_tracker();
2395 lttng_perf_lock();
2396 }
2397
2398 static void ust_after_fork_common(sigset_t *restore_sigset)
2399 {
2400 int ret;
2401
2402 DBG("process %d", getpid());
2403 lttng_perf_unlock();
2404 lttng_ust_unlock_fd_tracker();
2405 ust_unlock();
2406
2407 pthread_mutex_unlock(&ust_fork_mutex);
2408
2409 /* Restore signals */
2410 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
2411 if (ret == -1) {
2412 PERROR("sigprocmask");
2413 }
2414 }
2415
2416 void lttng_ust_after_fork_parent(sigset_t *restore_sigset)
2417 {
2418 if (URCU_TLS(lttng_ust_nest_count))
2419 return;
2420 DBG("process %d", getpid());
2421 lttng_ust_urcu_after_fork_parent();
2422 /* Release mutexes and reenable signals */
2423 ust_after_fork_common(restore_sigset);
2424 }
2425
2426 /*
2427 * After fork, in the child, we need to cleanup all the leftover state,
2428 * except the worker thread which already magically disappeared thanks
2429 * to the weird Linux fork semantics. After tyding up, we call
2430 * lttng_ust_ctor() again to start over as a new PID.
2431 *
2432 * This is meant for forks() that have tracing in the child between the
2433 * fork and following exec call (if there is any).
2434 */
2435 void lttng_ust_after_fork_child(sigset_t *restore_sigset)
2436 {
2437 if (URCU_TLS(lttng_ust_nest_count))
2438 return;
2439 lttng_context_vpid_reset();
2440 lttng_context_vtid_reset();
2441 lttng_ust_context_procname_reset();
2442 ust_context_ns_reset();
2443 ust_context_vuids_reset();
2444 ust_context_vgids_reset();
2445 DBG("process %d", getpid());
2446 /* Release urcu mutexes */
2447 lttng_ust_urcu_after_fork_child();
2448 lttng_ust_cleanup(0);
2449 /* Release mutexes and reenable signals */
2450 ust_after_fork_common(restore_sigset);
2451 lttng_ust_ctor();
2452 }
2453
2454 void lttng_ust_after_setns(void)
2455 {
2456 ust_context_ns_reset();
2457 ust_context_vuids_reset();
2458 ust_context_vgids_reset();
2459 }
2460
2461 void lttng_ust_after_unshare(void)
2462 {
2463 ust_context_ns_reset();
2464 ust_context_vuids_reset();
2465 ust_context_vgids_reset();
2466 }
2467
2468 void lttng_ust_after_setuid(void)
2469 {
2470 ust_context_vuids_reset();
2471 }
2472
2473 void lttng_ust_after_seteuid(void)
2474 {
2475 ust_context_vuids_reset();
2476 }
2477
2478 void lttng_ust_after_setreuid(void)
2479 {
2480 ust_context_vuids_reset();
2481 }
2482
2483 void lttng_ust_after_setresuid(void)
2484 {
2485 ust_context_vuids_reset();
2486 }
2487
2488 void lttng_ust_after_setgid(void)
2489 {
2490 ust_context_vgids_reset();
2491 }
2492
2493 void lttng_ust_after_setegid(void)
2494 {
2495 ust_context_vgids_reset();
2496 }
2497
2498 void lttng_ust_after_setregid(void)
2499 {
2500 ust_context_vgids_reset();
2501 }
2502
2503 void lttng_ust_after_setresgid(void)
2504 {
2505 ust_context_vgids_reset();
2506 }
2507
2508 void lttng_ust_sockinfo_session_enabled(void *owner)
2509 {
2510 struct sock_info *sock_info = owner;
2511 sock_info->statedump_pending = 1;
2512 }
This page took 0.118762 seconds and 4 git commands to generate.