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