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