3cebb9811348545bb5c9a9d59556ab60362f5690
[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_fd_tracker_tls();
427 }
428
429 int lttng_get_notify_socket(void *owner)
430 {
431 struct sock_info *info = owner;
432
433 return info->notify_socket;
434 }
435
436 static
437 void print_cmd(int cmd, int handle)
438 {
439 const char *cmd_name = "Unknown";
440
441 if (cmd >= 0 && cmd < LTTNG_ARRAY_SIZE(cmd_name_mapping)
442 && cmd_name_mapping[cmd]) {
443 cmd_name = cmd_name_mapping[cmd];
444 }
445 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
446 cmd_name, cmd,
447 lttng_ust_obj_get_name(handle), handle);
448 }
449
450 static
451 int setup_global_apps(void)
452 {
453 int ret = 0;
454 assert(!global_apps.wait_shm_mmap);
455
456 global_apps.wait_shm_mmap = get_map_shm(&global_apps);
457 if (!global_apps.wait_shm_mmap) {
458 WARN("Unable to get map shm for global apps. Disabling LTTng-UST global tracing.");
459 global_apps.allowed = 0;
460 ret = -EIO;
461 goto error;
462 }
463
464 global_apps.allowed = 1;
465 error:
466 return ret;
467 }
468 static
469 int setup_local_apps(void)
470 {
471 int ret = 0;
472 const char *home_dir;
473 uid_t uid;
474
475 assert(!local_apps.wait_shm_mmap);
476
477 uid = getuid();
478 /*
479 * Disallow per-user tracing for setuid binaries.
480 */
481 if (uid != geteuid()) {
482 assert(local_apps.allowed == 0);
483 ret = 0;
484 goto end;
485 }
486 home_dir = get_lttng_home_dir();
487 if (!home_dir) {
488 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
489 assert(local_apps.allowed == 0);
490 ret = -ENOENT;
491 goto end;
492 }
493 local_apps.allowed = 1;
494 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
495 home_dir,
496 LTTNG_DEFAULT_HOME_RUNDIR,
497 LTTNG_UST_SOCK_FILENAME);
498 snprintf(local_apps.wait_shm_path, PATH_MAX, "/%s-%u",
499 LTTNG_UST_WAIT_FILENAME,
500 uid);
501
502 local_apps.wait_shm_mmap = get_map_shm(&local_apps);
503 if (!local_apps.wait_shm_mmap) {
504 WARN("Unable to get map shm for local apps. Disabling LTTng-UST per-user tracing.");
505 local_apps.allowed = 0;
506 ret = -EIO;
507 goto end;
508 }
509 end:
510 return ret;
511 }
512
513 /*
514 * Get socket timeout, in ms.
515 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
516 */
517 static
518 long get_timeout(void)
519 {
520 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
521
522 if (!got_timeout_env) {
523 str_timeout = lttng_getenv("LTTNG_UST_REGISTER_TIMEOUT");
524 got_timeout_env = 1;
525 }
526 if (str_timeout)
527 constructor_delay_ms = strtol(str_timeout, NULL, 10);
528 /* All negative values are considered as "-1". */
529 if (constructor_delay_ms < -1)
530 constructor_delay_ms = -1;
531 return constructor_delay_ms;
532 }
533
534 /* Timeout for notify socket send and recv. */
535 static
536 long get_notify_sock_timeout(void)
537 {
538 return get_timeout();
539 }
540
541 /* Timeout for connecting to cmd and notify sockets. */
542 static
543 long get_connect_sock_timeout(void)
544 {
545 return get_timeout();
546 }
547
548 /*
549 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
550 */
551 static
552 int get_constructor_timeout(struct timespec *constructor_timeout)
553 {
554 long constructor_delay_ms;
555 int ret;
556
557 constructor_delay_ms = get_timeout();
558
559 switch (constructor_delay_ms) {
560 case -1:/* fall-through */
561 case 0:
562 return constructor_delay_ms;
563 default:
564 break;
565 }
566
567 /*
568 * If we are unable to find the current time, don't wait.
569 */
570 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
571 if (ret) {
572 /* Don't wait. */
573 return 0;
574 }
575 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
576 constructor_timeout->tv_nsec +=
577 (constructor_delay_ms % 1000UL) * 1000000UL;
578 if (constructor_timeout->tv_nsec >= 1000000000UL) {
579 constructor_timeout->tv_sec++;
580 constructor_timeout->tv_nsec -= 1000000000UL;
581 }
582 /* Timeout wait (constructor_delay_ms). */
583 return 1;
584 }
585
586 static
587 void get_allow_blocking(void)
588 {
589 const char *str_allow_blocking =
590 lttng_getenv("LTTNG_UST_ALLOW_BLOCKING");
591
592 if (str_allow_blocking) {
593 DBG("%s environment variable is set",
594 "LTTNG_UST_ALLOW_BLOCKING");
595 lttng_ust_ringbuffer_set_allow_blocking();
596 }
597 }
598
599 static
600 int register_to_sessiond(int socket, enum ustctl_socket_type type)
601 {
602 return ustcomm_send_reg_msg(socket,
603 type,
604 CAA_BITS_PER_LONG,
605 lttng_alignof(uint8_t) * CHAR_BIT,
606 lttng_alignof(uint16_t) * CHAR_BIT,
607 lttng_alignof(uint32_t) * CHAR_BIT,
608 lttng_alignof(uint64_t) * CHAR_BIT,
609 lttng_alignof(unsigned long) * CHAR_BIT);
610 }
611
612 static
613 int send_reply(int sock, struct ustcomm_ust_reply *lur)
614 {
615 ssize_t len;
616
617 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
618 switch (len) {
619 case sizeof(*lur):
620 DBG("message successfully sent");
621 return 0;
622 default:
623 if (len == -ECONNRESET) {
624 DBG("remote end closed connection");
625 return 0;
626 }
627 if (len < 0)
628 return len;
629 DBG("incorrect message size: %zd", len);
630 return -EINVAL;
631 }
632 }
633
634 static
635 void decrement_sem_count(unsigned int count)
636 {
637 int ret;
638
639 assert(uatomic_read(&sem_count) >= count);
640
641 if (uatomic_read(&sem_count) <= 0) {
642 return;
643 }
644
645 ret = uatomic_add_return(&sem_count, -count);
646 if (ret == 0) {
647 ret = sem_post(&constructor_wait);
648 assert(!ret);
649 }
650 }
651
652 static
653 int handle_register_done(struct sock_info *sock_info)
654 {
655 if (sock_info->registration_done)
656 return 0;
657 sock_info->registration_done = 1;
658
659 decrement_sem_count(1);
660 if (!sock_info->statedump_pending) {
661 sock_info->initial_statedump_done = 1;
662 decrement_sem_count(1);
663 }
664
665 return 0;
666 }
667
668 static
669 int handle_register_failed(struct sock_info *sock_info)
670 {
671 if (sock_info->registration_done)
672 return 0;
673 sock_info->registration_done = 1;
674 sock_info->initial_statedump_done = 1;
675
676 decrement_sem_count(2);
677
678 return 0;
679 }
680
681 /*
682 * Only execute pending statedump after the constructor semaphore has
683 * been posted by the current listener thread. This means statedump will
684 * only be performed after the "registration done" command is received
685 * from this thread's session daemon.
686 *
687 * This ensures we don't run into deadlock issues with the dynamic
688 * loader mutex, which is held while the constructor is called and
689 * waiting on the constructor semaphore. All operations requiring this
690 * dynamic loader lock need to be postponed using this mechanism.
691 *
692 * In a scenario with two session daemons connected to the application,
693 * it is possible that the first listener thread which receives the
694 * registration done command issues its statedump while the dynamic
695 * loader lock is still held by the application constructor waiting on
696 * the semaphore. It will however be allowed to proceed when the
697 * second session daemon sends the registration done command to the
698 * second listener thread. This situation therefore does not produce
699 * a deadlock.
700 */
701 static
702 void handle_pending_statedump(struct sock_info *sock_info)
703 {
704 if (sock_info->registration_done && sock_info->statedump_pending) {
705 sock_info->statedump_pending = 0;
706 pthread_mutex_lock(&ust_fork_mutex);
707 lttng_handle_pending_statedump(sock_info);
708 pthread_mutex_unlock(&ust_fork_mutex);
709
710 if (!sock_info->initial_statedump_done) {
711 sock_info->initial_statedump_done = 1;
712 decrement_sem_count(1);
713 }
714 }
715 }
716
717 static
718 int handle_message(struct sock_info *sock_info,
719 int sock, struct ustcomm_ust_msg *lum)
720 {
721 int ret = 0;
722 const struct lttng_ust_objd_ops *ops;
723 struct ustcomm_ust_reply lur;
724 union ust_args args;
725 char ctxstr[LTTNG_UST_SYM_NAME_LEN]; /* App context string. */
726 ssize_t len;
727
728 memset(&lur, 0, sizeof(lur));
729
730 if (ust_lock()) {
731 ret = -LTTNG_UST_ERR_EXITING;
732 goto error;
733 }
734
735 ops = objd_ops(lum->handle);
736 if (!ops) {
737 ret = -ENOENT;
738 goto error;
739 }
740
741 switch (lum->cmd) {
742 case LTTNG_UST_REGISTER_DONE:
743 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
744 ret = handle_register_done(sock_info);
745 else
746 ret = -EINVAL;
747 break;
748 case LTTNG_UST_RELEASE:
749 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
750 ret = -EPERM;
751 else
752 ret = lttng_ust_objd_unref(lum->handle, 1);
753 break;
754 case LTTNG_UST_FILTER:
755 {
756 /* Receive filter data */
757 struct lttng_ust_filter_bytecode_node *bytecode;
758
759 if (lum->u.filter.data_size > FILTER_BYTECODE_MAX_LEN) {
760 ERR("Filter data size is too large: %u bytes",
761 lum->u.filter.data_size);
762 ret = -EINVAL;
763 goto error;
764 }
765
766 if (lum->u.filter.reloc_offset > lum->u.filter.data_size) {
767 ERR("Filter reloc offset %u is not within data",
768 lum->u.filter.reloc_offset);
769 ret = -EINVAL;
770 goto error;
771 }
772
773 bytecode = zmalloc(sizeof(*bytecode) + lum->u.filter.data_size);
774 if (!bytecode) {
775 ret = -ENOMEM;
776 goto error;
777 }
778 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data,
779 lum->u.filter.data_size);
780 switch (len) {
781 case 0: /* orderly shutdown */
782 ret = 0;
783 free(bytecode);
784 goto error;
785 default:
786 if (len == lum->u.filter.data_size) {
787 DBG("filter data received");
788 break;
789 } else if (len < 0) {
790 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
791 if (len == -ECONNRESET) {
792 ERR("%s remote end closed connection", sock_info->name);
793 ret = len;
794 free(bytecode);
795 goto error;
796 }
797 ret = len;
798 free(bytecode);
799 goto error;
800 } else {
801 DBG("incorrect filter data message size: %zd", len);
802 ret = -EINVAL;
803 free(bytecode);
804 goto error;
805 }
806 }
807 bytecode->bc.len = lum->u.filter.data_size;
808 bytecode->bc.reloc_offset = lum->u.filter.reloc_offset;
809 bytecode->bc.seqnum = lum->u.filter.seqnum;
810 if (ops->cmd) {
811 ret = ops->cmd(lum->handle, lum->cmd,
812 (unsigned long) bytecode,
813 &args, sock_info);
814 if (ret) {
815 free(bytecode);
816 }
817 /* don't free bytecode if everything went fine. */
818 } else {
819 ret = -ENOSYS;
820 free(bytecode);
821 }
822 break;
823 }
824 case LTTNG_UST_EXCLUSION:
825 {
826 /* Receive exclusion names */
827 struct lttng_ust_excluder_node *node;
828 unsigned int count;
829
830 count = lum->u.exclusion.count;
831 if (count == 0) {
832 /* There are no names to read */
833 ret = 0;
834 goto error;
835 }
836 node = zmalloc(sizeof(*node) +
837 count * LTTNG_UST_SYM_NAME_LEN);
838 if (!node) {
839 ret = -ENOMEM;
840 goto error;
841 }
842 node->excluder.count = count;
843 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
844 count * LTTNG_UST_SYM_NAME_LEN);
845 switch (len) {
846 case 0: /* orderly shutdown */
847 ret = 0;
848 free(node);
849 goto error;
850 default:
851 if (len == count * LTTNG_UST_SYM_NAME_LEN) {
852 DBG("Exclusion data received");
853 break;
854 } else if (len < 0) {
855 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
856 if (len == -ECONNRESET) {
857 ERR("%s remote end closed connection", sock_info->name);
858 ret = len;
859 free(node);
860 goto error;
861 }
862 ret = len;
863 free(node);
864 goto error;
865 } else {
866 DBG("Incorrect exclusion data message size: %zd", len);
867 ret = -EINVAL;
868 free(node);
869 goto error;
870 }
871 }
872 if (ops->cmd) {
873 ret = ops->cmd(lum->handle, lum->cmd,
874 (unsigned long) node,
875 &args, sock_info);
876 if (ret) {
877 free(node);
878 }
879 /* Don't free exclusion data if everything went fine. */
880 } else {
881 ret = -ENOSYS;
882 free(node);
883 }
884 break;
885 }
886 case LTTNG_UST_CHANNEL:
887 {
888 void *chan_data;
889 int wakeup_fd;
890
891 len = ustcomm_recv_channel_from_sessiond(sock,
892 &chan_data, lum->u.channel.len,
893 &wakeup_fd);
894 switch (len) {
895 case 0: /* orderly shutdown */
896 ret = 0;
897 goto error;
898 default:
899 if (len == lum->u.channel.len) {
900 DBG("channel data received");
901 break;
902 } else if (len < 0) {
903 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
904 if (len == -ECONNRESET) {
905 ERR("%s remote end closed connection", sock_info->name);
906 ret = len;
907 goto error;
908 }
909 ret = len;
910 goto error;
911 } else {
912 DBG("incorrect channel data message size: %zd", len);
913 ret = -EINVAL;
914 goto error;
915 }
916 }
917 args.channel.chan_data = chan_data;
918 args.channel.wakeup_fd = wakeup_fd;
919 if (ops->cmd)
920 ret = ops->cmd(lum->handle, lum->cmd,
921 (unsigned long) &lum->u,
922 &args, sock_info);
923 else
924 ret = -ENOSYS;
925 break;
926 }
927 case LTTNG_UST_STREAM:
928 {
929 /* Receive shm_fd, wakeup_fd */
930 ret = ustcomm_recv_stream_from_sessiond(sock,
931 NULL,
932 &args.stream.shm_fd,
933 &args.stream.wakeup_fd);
934 if (ret) {
935 goto error;
936 }
937
938 if (ops->cmd)
939 ret = ops->cmd(lum->handle, lum->cmd,
940 (unsigned long) &lum->u,
941 &args, sock_info);
942 else
943 ret = -ENOSYS;
944 break;
945 }
946 case LTTNG_UST_CONTEXT:
947 switch (lum->u.context.ctx) {
948 case LTTNG_UST_CONTEXT_APP_CONTEXT:
949 {
950 char *p;
951 size_t ctxlen, recvlen;
952
953 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
954 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
955 if (ctxlen >= LTTNG_UST_SYM_NAME_LEN) {
956 ERR("Application context string length size is too large: %zu bytes",
957 ctxlen);
958 ret = -EINVAL;
959 goto error;
960 }
961 strcpy(ctxstr, "$app.");
962 p = &ctxstr[strlen("$app.")];
963 recvlen = ctxlen - strlen("$app.");
964 len = ustcomm_recv_unix_sock(sock, p, recvlen);
965 switch (len) {
966 case 0: /* orderly shutdown */
967 ret = 0;
968 goto error;
969 default:
970 if (len == recvlen) {
971 DBG("app context data received");
972 break;
973 } else if (len < 0) {
974 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
975 if (len == -ECONNRESET) {
976 ERR("%s remote end closed connection", sock_info->name);
977 ret = len;
978 goto error;
979 }
980 ret = len;
981 goto error;
982 } else {
983 DBG("incorrect app context data message size: %zd", len);
984 ret = -EINVAL;
985 goto error;
986 }
987 }
988 /* Put : between provider and ctxname. */
989 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
990 args.app_context.ctxname = ctxstr;
991 break;
992 }
993 default:
994 break;
995 }
996 if (ops->cmd) {
997 ret = ops->cmd(lum->handle, lum->cmd,
998 (unsigned long) &lum->u,
999 &args, sock_info);
1000 } else {
1001 ret = -ENOSYS;
1002 }
1003 break;
1004 default:
1005 if (ops->cmd)
1006 ret = ops->cmd(lum->handle, lum->cmd,
1007 (unsigned long) &lum->u,
1008 &args, sock_info);
1009 else
1010 ret = -ENOSYS;
1011 break;
1012 }
1013
1014 lur.handle = lum->handle;
1015 lur.cmd = lum->cmd;
1016 lur.ret_val = ret;
1017 if (ret >= 0) {
1018 lur.ret_code = LTTNG_UST_OK;
1019 } else {
1020 /*
1021 * Use -LTTNG_UST_ERR as wildcard for UST internal
1022 * error that are not caused by the transport, except if
1023 * we already have a more precise error message to
1024 * report.
1025 */
1026 if (ret > -LTTNG_UST_ERR) {
1027 /* Translate code to UST error. */
1028 switch (ret) {
1029 case -EEXIST:
1030 lur.ret_code = -LTTNG_UST_ERR_EXIST;
1031 break;
1032 case -EINVAL:
1033 lur.ret_code = -LTTNG_UST_ERR_INVAL;
1034 break;
1035 case -ENOENT:
1036 lur.ret_code = -LTTNG_UST_ERR_NOENT;
1037 break;
1038 case -EPERM:
1039 lur.ret_code = -LTTNG_UST_ERR_PERM;
1040 break;
1041 case -ENOSYS:
1042 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
1043 break;
1044 default:
1045 lur.ret_code = -LTTNG_UST_ERR;
1046 break;
1047 }
1048 } else {
1049 lur.ret_code = ret;
1050 }
1051 }
1052 if (ret >= 0) {
1053 switch (lum->cmd) {
1054 case LTTNG_UST_TRACER_VERSION:
1055 lur.u.version = lum->u.version;
1056 break;
1057 case LTTNG_UST_TRACEPOINT_LIST_GET:
1058 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1059 break;
1060 }
1061 }
1062 DBG("Return value: %d", lur.ret_val);
1063
1064 ust_unlock();
1065
1066 /*
1067 * Performed delayed statedump operations outside of the UST
1068 * lock. We need to take the dynamic loader lock before we take
1069 * the UST lock internally within handle_pending_statedump().
1070 */
1071 handle_pending_statedump(sock_info);
1072
1073 if (ust_lock()) {
1074 ret = -LTTNG_UST_ERR_EXITING;
1075 goto error;
1076 }
1077
1078 ret = send_reply(sock, &lur);
1079 if (ret < 0) {
1080 DBG("error sending reply");
1081 goto error;
1082 }
1083
1084 /*
1085 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1086 * after the reply.
1087 */
1088 if (lur.ret_code == LTTNG_UST_OK) {
1089 switch (lum->cmd) {
1090 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
1091 len = ustcomm_send_unix_sock(sock,
1092 &args.field_list.entry,
1093 sizeof(args.field_list.entry));
1094 if (len < 0) {
1095 ret = len;
1096 goto error;
1097 }
1098 if (len != sizeof(args.field_list.entry)) {
1099 ret = -EINVAL;
1100 goto error;
1101 }
1102 }
1103 }
1104
1105 error:
1106 ust_unlock();
1107
1108 return ret;
1109 }
1110
1111 static
1112 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
1113 {
1114 int ret;
1115
1116 if (sock_info->root_handle != -1) {
1117 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1118 if (ret) {
1119 ERR("Error unref root handle");
1120 }
1121 sock_info->root_handle = -1;
1122 }
1123 sock_info->registration_done = 0;
1124 sock_info->initial_statedump_done = 0;
1125
1126 /*
1127 * wait_shm_mmap, socket and notify socket are used by listener
1128 * threads outside of the ust lock, so we cannot tear them down
1129 * ourselves, because we cannot join on these threads. Leave
1130 * responsibility of cleaning up these resources to the OS
1131 * process exit.
1132 */
1133 if (exiting)
1134 return;
1135
1136 if (sock_info->socket != -1) {
1137 ret = ustcomm_close_unix_sock(sock_info->socket);
1138 if (ret) {
1139 ERR("Error closing ust cmd socket");
1140 }
1141 sock_info->socket = -1;
1142 }
1143 if (sock_info->notify_socket != -1) {
1144 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1145 if (ret) {
1146 ERR("Error closing ust notify socket");
1147 }
1148 sock_info->notify_socket = -1;
1149 }
1150 if (sock_info->wait_shm_mmap) {
1151 long page_size;
1152
1153 page_size = sysconf(_SC_PAGE_SIZE);
1154 if (page_size <= 0) {
1155 if (!page_size) {
1156 errno = EINVAL;
1157 }
1158 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1159 } else {
1160 ret = munmap(sock_info->wait_shm_mmap, page_size);
1161 if (ret) {
1162 ERR("Error unmapping wait shm");
1163 }
1164 }
1165 sock_info->wait_shm_mmap = NULL;
1166 }
1167 }
1168
1169 /*
1170 * Using fork to set umask in the child process (not multi-thread safe).
1171 * We deal with the shm_open vs ftruncate race (happening when the
1172 * sessiond owns the shm and does not let everybody modify it, to ensure
1173 * safety against shm_unlink) by simply letting the mmap fail and
1174 * retrying after a few seconds.
1175 * For global shm, everybody has rw access to it until the sessiond
1176 * starts.
1177 */
1178 static
1179 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
1180 {
1181 int wait_shm_fd, ret;
1182 pid_t pid;
1183
1184 /*
1185 * Try to open read-only.
1186 */
1187 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1188 if (wait_shm_fd >= 0) {
1189 int32_t tmp_read;
1190 ssize_t len;
1191 size_t bytes_read = 0;
1192
1193 /*
1194 * Try to read the fd. If unable to do so, try opening
1195 * it in write mode.
1196 */
1197 do {
1198 len = read(wait_shm_fd,
1199 &((char *) &tmp_read)[bytes_read],
1200 sizeof(tmp_read) - bytes_read);
1201 if (len > 0) {
1202 bytes_read += len;
1203 }
1204 } while ((len < 0 && errno == EINTR)
1205 || (len > 0 && bytes_read < sizeof(tmp_read)));
1206 if (bytes_read != sizeof(tmp_read)) {
1207 ret = close(wait_shm_fd);
1208 if (ret) {
1209 ERR("close wait_shm_fd");
1210 }
1211 goto open_write;
1212 }
1213 goto end;
1214 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1215 /*
1216 * Real-only open did not work, and it's not because the
1217 * entry was not present. It's a failure that prohibits
1218 * using shm.
1219 */
1220 ERR("Error opening shm %s", sock_info->wait_shm_path);
1221 goto end;
1222 }
1223
1224 open_write:
1225 /*
1226 * If the open failed because the file did not exist, or because
1227 * the file was not truncated yet, try creating it ourself.
1228 */
1229 URCU_TLS(lttng_ust_nest_count)++;
1230 pid = fork();
1231 URCU_TLS(lttng_ust_nest_count)--;
1232 if (pid > 0) {
1233 int status;
1234
1235 /*
1236 * Parent: wait for child to return, in which case the
1237 * shared memory map will have been created.
1238 */
1239 pid = wait(&status);
1240 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1241 wait_shm_fd = -1;
1242 goto end;
1243 }
1244 /*
1245 * Try to open read-only again after creation.
1246 */
1247 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1248 if (wait_shm_fd < 0) {
1249 /*
1250 * Real-only open did not work. It's a failure
1251 * that prohibits using shm.
1252 */
1253 ERR("Error opening shm %s", sock_info->wait_shm_path);
1254 goto end;
1255 }
1256 goto end;
1257 } else if (pid == 0) {
1258 int create_mode;
1259
1260 /* Child */
1261 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
1262 if (sock_info->global)
1263 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
1264 /*
1265 * We're alone in a child process, so we can modify the
1266 * process-wide umask.
1267 */
1268 umask(~create_mode);
1269 /*
1270 * Try creating shm (or get rw access).
1271 * We don't do an exclusive open, because we allow other
1272 * processes to create+ftruncate it concurrently.
1273 */
1274 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1275 O_RDWR | O_CREAT, create_mode);
1276 if (wait_shm_fd >= 0) {
1277 ret = ftruncate(wait_shm_fd, mmap_size);
1278 if (ret) {
1279 PERROR("ftruncate");
1280 _exit(EXIT_FAILURE);
1281 }
1282 _exit(EXIT_SUCCESS);
1283 }
1284 /*
1285 * For local shm, we need to have rw access to accept
1286 * opening it: this means the local sessiond will be
1287 * able to wake us up. For global shm, we open it even
1288 * if rw access is not granted, because the root.root
1289 * sessiond will be able to override all rights and wake
1290 * us up.
1291 */
1292 if (!sock_info->global && errno != EACCES) {
1293 ERR("Error opening shm %s", sock_info->wait_shm_path);
1294 _exit(EXIT_FAILURE);
1295 }
1296 /*
1297 * The shm exists, but we cannot open it RW. Report
1298 * success.
1299 */
1300 _exit(EXIT_SUCCESS);
1301 } else {
1302 return -1;
1303 }
1304 end:
1305 if (wait_shm_fd >= 0 && !sock_info->global) {
1306 struct stat statbuf;
1307
1308 /*
1309 * Ensure that our user is the owner of the shm file for
1310 * local shm. If we do not own the file, it means our
1311 * sessiond will not have access to wake us up (there is
1312 * probably a rogue process trying to fake our
1313 * sessiond). Fallback to polling method in this case.
1314 */
1315 ret = fstat(wait_shm_fd, &statbuf);
1316 if (ret) {
1317 PERROR("fstat");
1318 goto error_close;
1319 }
1320 if (statbuf.st_uid != getuid())
1321 goto error_close;
1322 }
1323 return wait_shm_fd;
1324
1325 error_close:
1326 ret = close(wait_shm_fd);
1327 if (ret) {
1328 PERROR("Error closing fd");
1329 }
1330 return -1;
1331 }
1332
1333 static
1334 char *get_map_shm(struct sock_info *sock_info)
1335 {
1336 long page_size;
1337 int wait_shm_fd, ret;
1338 char *wait_shm_mmap;
1339
1340 page_size = sysconf(_SC_PAGE_SIZE);
1341 if (page_size <= 0) {
1342 if (!page_size) {
1343 errno = EINVAL;
1344 }
1345 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1346 goto error;
1347 }
1348
1349 lttng_ust_lock_fd_tracker();
1350 wait_shm_fd = get_wait_shm(sock_info, page_size);
1351 if (wait_shm_fd < 0) {
1352 lttng_ust_unlock_fd_tracker();
1353 goto error;
1354 }
1355
1356 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1357 if (ret < 0) {
1358 ret = close(wait_shm_fd);
1359 if (!ret) {
1360 PERROR("Error closing fd");
1361 }
1362 lttng_ust_unlock_fd_tracker();
1363 goto error;
1364 }
1365
1366 wait_shm_fd = ret;
1367 lttng_ust_unlock_fd_tracker();
1368
1369 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
1370 MAP_SHARED, wait_shm_fd, 0);
1371
1372 /* close shm fd immediately after taking the mmap reference */
1373 lttng_ust_lock_fd_tracker();
1374 ret = close(wait_shm_fd);
1375 if (!ret) {
1376 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1377 } else {
1378 PERROR("Error closing fd");
1379 }
1380 lttng_ust_unlock_fd_tracker();
1381
1382 if (wait_shm_mmap == MAP_FAILED) {
1383 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1384 goto error;
1385 }
1386 return wait_shm_mmap;
1387
1388 error:
1389 return NULL;
1390 }
1391
1392 static
1393 void wait_for_sessiond(struct sock_info *sock_info)
1394 {
1395 /* Use ust_lock to check if we should quit. */
1396 if (ust_lock()) {
1397 goto quit;
1398 }
1399 if (wait_poll_fallback) {
1400 goto error;
1401 }
1402 ust_unlock();
1403
1404 assert(sock_info->wait_shm_mmap);
1405
1406 DBG("Waiting for %s apps sessiond", sock_info->name);
1407 /* Wait for futex wakeup */
1408 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1409 goto end_wait;
1410
1411 while (futex_async((int32_t *) sock_info->wait_shm_mmap,
1412 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1413 switch (errno) {
1414 case EWOULDBLOCK:
1415 /* Value already changed. */
1416 goto end_wait;
1417 case EINTR:
1418 /* Retry if interrupted by signal. */
1419 break; /* Get out of switch. */
1420 case EFAULT:
1421 wait_poll_fallback = 1;
1422 DBG(
1423 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1424 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1425 "Please upgrade your kernel "
1426 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1427 "mainline). LTTng-UST will use polling mode fallback.");
1428 if (ust_debug())
1429 PERROR("futex");
1430 goto end_wait;
1431 }
1432 }
1433 end_wait:
1434 return;
1435
1436 quit:
1437 ust_unlock();
1438 return;
1439
1440 error:
1441 ust_unlock();
1442 return;
1443 }
1444
1445 /*
1446 * This thread does not allocate any resource, except within
1447 * handle_message, within mutex protection. This mutex protects against
1448 * fork and exit.
1449 * The other moment it allocates resources is at socket connection, which
1450 * is also protected by the mutex.
1451 */
1452 static
1453 void *ust_listener_thread(void *arg)
1454 {
1455 struct sock_info *sock_info = arg;
1456 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
1457 long timeout;
1458
1459 lttng_ust_fixup_tls();
1460 lttng_ust_fd_tracker_register_thread();
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 }
2073
2074 static void ust_after_fork_common(sigset_t *restore_sigset)
2075 {
2076 int ret;
2077
2078 DBG("process %d", getpid());
2079 lttng_ust_unlock_fd_tracker();
2080 ust_unlock();
2081
2082 pthread_mutex_unlock(&ust_fork_mutex);
2083
2084 /* Restore signals */
2085 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
2086 if (ret == -1) {
2087 PERROR("sigprocmask");
2088 }
2089 }
2090
2091 void ust_after_fork_parent(sigset_t *restore_sigset)
2092 {
2093 if (URCU_TLS(lttng_ust_nest_count))
2094 return;
2095 DBG("process %d", getpid());
2096 urcu_bp_after_fork_parent();
2097 /* Release mutexes and reenable signals */
2098 ust_after_fork_common(restore_sigset);
2099 }
2100
2101 /*
2102 * After fork, in the child, we need to cleanup all the leftover state,
2103 * except the worker thread which already magically disappeared thanks
2104 * to the weird Linux fork semantics. After tyding up, we call
2105 * lttng_ust_init() again to start over as a new PID.
2106 *
2107 * This is meant for forks() that have tracing in the child between the
2108 * fork and following exec call (if there is any).
2109 */
2110 void ust_after_fork_child(sigset_t *restore_sigset)
2111 {
2112 if (URCU_TLS(lttng_ust_nest_count))
2113 return;
2114 lttng_context_vpid_reset();
2115 lttng_context_vtid_reset();
2116 lttng_context_procname_reset();
2117 DBG("process %d", getpid());
2118 /* Release urcu mutexes */
2119 urcu_bp_after_fork_child();
2120 lttng_ust_cleanup(0);
2121 /* Release mutexes and reenable signals */
2122 ust_after_fork_common(restore_sigset);
2123 lttng_ust_init();
2124 }
2125
2126 void lttng_ust_sockinfo_session_enabled(void *owner)
2127 {
2128 struct sock_info *sock_info = owner;
2129 sock_info->statedump_pending = 1;
2130 }
This page took 0.111481 seconds and 3 git commands to generate.