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