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