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