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