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