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