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