Revert "Fix: fd tracker: do not allow signal handlers to close lttng-ust FDs"
[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 /*
1461 * If available, add '-ust' to the end of this thread's
1462 * process name
1463 */
1464 ret = lttng_ust_setustprocname();
1465 if (ret) {
1466 ERR("Unable to set UST process name");
1467 }
1468
1469 /* Restart trying to connect to the session daemon */
1470 restart:
1471 if (prev_connect_failed) {
1472 /* Wait for sessiond availability with pipe */
1473 wait_for_sessiond(sock_info);
1474 if (has_waited) {
1475 has_waited = 0;
1476 /*
1477 * Sleep for 5 seconds before retrying after a
1478 * sequence of failure / wait / failure. This
1479 * deals with a killed or broken session daemon.
1480 */
1481 sleep(5);
1482 } else {
1483 has_waited = 1;
1484 }
1485 prev_connect_failed = 0;
1486 }
1487
1488 if (ust_lock()) {
1489 goto quit;
1490 }
1491
1492 if (sock_info->socket != -1) {
1493 /* FD tracker is updated by ustcomm_close_unix_sock() */
1494 ret = ustcomm_close_unix_sock(sock_info->socket);
1495 if (ret) {
1496 ERR("Error closing %s ust cmd socket",
1497 sock_info->name);
1498 }
1499 sock_info->socket = -1;
1500 }
1501 if (sock_info->notify_socket != -1) {
1502 /* FD tracker is updated by ustcomm_close_unix_sock() */
1503 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1504 if (ret) {
1505 ERR("Error closing %s ust notify socket",
1506 sock_info->name);
1507 }
1508 sock_info->notify_socket = -1;
1509 }
1510
1511
1512 /*
1513 * Register. We need to perform both connect and sending
1514 * registration message before doing the next connect otherwise
1515 * we may reach unix socket connect queue max limits and block
1516 * on the 2nd connect while the session daemon is awaiting the
1517 * first connect registration message.
1518 */
1519 /* Connect cmd socket */
1520 lttng_ust_lock_fd_tracker();
1521 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1522 get_connect_sock_timeout());
1523 if (ret < 0) {
1524 lttng_ust_unlock_fd_tracker();
1525 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1526 prev_connect_failed = 1;
1527
1528 /*
1529 * If we cannot find the sessiond daemon, don't delay
1530 * constructor execution.
1531 */
1532 ret = handle_register_failed(sock_info);
1533 assert(!ret);
1534 ust_unlock();
1535 goto restart;
1536 }
1537 fd = ret;
1538 ret = lttng_ust_add_fd_to_tracker(fd);
1539 if (ret < 0) {
1540 ret = close(fd);
1541 if (ret) {
1542 PERROR("close on sock_info->socket");
1543 }
1544 ret = -1;
1545 lttng_ust_unlock_fd_tracker();
1546 ust_unlock();
1547 goto quit;
1548 }
1549
1550 sock_info->socket = ret;
1551 lttng_ust_unlock_fd_tracker();
1552
1553 ust_unlock();
1554 /*
1555 * Unlock/relock ust lock because connect is blocking (with
1556 * timeout). Don't delay constructors on the ust lock for too
1557 * long.
1558 */
1559 if (ust_lock()) {
1560 goto quit;
1561 }
1562
1563 /*
1564 * Create only one root handle per listener thread for the whole
1565 * process lifetime, so we ensure we get ID which is statically
1566 * assigned to the root handle.
1567 */
1568 if (sock_info->root_handle == -1) {
1569 ret = lttng_abi_create_root_handle();
1570 if (ret < 0) {
1571 ERR("Error creating root handle");
1572 goto quit;
1573 }
1574 sock_info->root_handle = ret;
1575 }
1576
1577 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
1578 if (ret < 0) {
1579 ERR("Error registering to %s ust cmd socket",
1580 sock_info->name);
1581 prev_connect_failed = 1;
1582 /*
1583 * If we cannot register to the sessiond daemon, don't
1584 * delay constructor execution.
1585 */
1586 ret = handle_register_failed(sock_info);
1587 assert(!ret);
1588 ust_unlock();
1589 goto restart;
1590 }
1591
1592 ust_unlock();
1593 /*
1594 * Unlock/relock ust lock because connect is blocking (with
1595 * timeout). Don't delay constructors on the ust lock for too
1596 * long.
1597 */
1598 if (ust_lock()) {
1599 goto quit;
1600 }
1601
1602 /* Connect notify socket */
1603 lttng_ust_lock_fd_tracker();
1604 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1605 get_connect_sock_timeout());
1606 if (ret < 0) {
1607 lttng_ust_unlock_fd_tracker();
1608 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1609 prev_connect_failed = 1;
1610
1611 /*
1612 * If we cannot find the sessiond daemon, don't delay
1613 * constructor execution.
1614 */
1615 ret = handle_register_failed(sock_info);
1616 assert(!ret);
1617 ust_unlock();
1618 goto restart;
1619 }
1620
1621 fd = ret;
1622 ret = lttng_ust_add_fd_to_tracker(fd);
1623 if (ret < 0) {
1624 ret = close(fd);
1625 if (ret) {
1626 PERROR("close on sock_info->notify_socket");
1627 }
1628 ret = -1;
1629 lttng_ust_unlock_fd_tracker();
1630 ust_unlock();
1631 goto quit;
1632 }
1633
1634 sock_info->notify_socket = ret;
1635 lttng_ust_unlock_fd_tracker();
1636
1637 ust_unlock();
1638 /*
1639 * Unlock/relock ust lock because connect is blocking (with
1640 * timeout). Don't delay constructors on the ust lock for too
1641 * long.
1642 */
1643 if (ust_lock()) {
1644 goto quit;
1645 }
1646
1647 timeout = get_notify_sock_timeout();
1648 if (timeout >= 0) {
1649 /*
1650 * Give at least 10ms to sessiond to reply to
1651 * notifications.
1652 */
1653 if (timeout < 10)
1654 timeout = 10;
1655 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1656 timeout);
1657 if (ret < 0) {
1658 WARN("Error setting socket receive timeout");
1659 }
1660 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1661 timeout);
1662 if (ret < 0) {
1663 WARN("Error setting socket send timeout");
1664 }
1665 } else if (timeout < -1) {
1666 WARN("Unsupported timeout value %ld", timeout);
1667 }
1668
1669 ret = register_to_sessiond(sock_info->notify_socket,
1670 USTCTL_SOCKET_NOTIFY);
1671 if (ret < 0) {
1672 ERR("Error registering to %s ust notify socket",
1673 sock_info->name);
1674 prev_connect_failed = 1;
1675 /*
1676 * If we cannot register to the sessiond daemon, don't
1677 * delay constructor execution.
1678 */
1679 ret = handle_register_failed(sock_info);
1680 assert(!ret);
1681 ust_unlock();
1682 goto restart;
1683 }
1684 sock = sock_info->socket;
1685
1686 ust_unlock();
1687
1688 for (;;) {
1689 ssize_t len;
1690 struct ustcomm_ust_msg lum;
1691
1692 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1693 switch (len) {
1694 case 0: /* orderly shutdown */
1695 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
1696 if (ust_lock()) {
1697 goto quit;
1698 }
1699 /*
1700 * Either sessiond has shutdown or refused us by closing the socket.
1701 * In either case, we don't want to delay construction execution,
1702 * and we need to wait before retry.
1703 */
1704 prev_connect_failed = 1;
1705 /*
1706 * If we cannot register to the sessiond daemon, don't
1707 * delay constructor execution.
1708 */
1709 ret = handle_register_failed(sock_info);
1710 assert(!ret);
1711 ust_unlock();
1712 goto end;
1713 case sizeof(lum):
1714 print_cmd(lum.cmd, lum.handle);
1715 ret = handle_message(sock_info, sock, &lum);
1716 if (ret) {
1717 ERR("Error handling message for %s socket",
1718 sock_info->name);
1719 /*
1720 * Close socket if protocol error is
1721 * detected.
1722 */
1723 goto end;
1724 }
1725 continue;
1726 default:
1727 if (len < 0) {
1728 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1729 } else {
1730 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1731 }
1732 if (len == -ECONNRESET) {
1733 DBG("%s remote end closed connection", sock_info->name);
1734 goto end;
1735 }
1736 goto end;
1737 }
1738
1739 }
1740 end:
1741 if (ust_lock()) {
1742 goto quit;
1743 }
1744 /* Cleanup socket handles before trying to reconnect */
1745 lttng_ust_objd_table_owner_cleanup(sock_info);
1746 ust_unlock();
1747 goto restart; /* try to reconnect */
1748
1749 quit:
1750 ust_unlock();
1751
1752 pthread_mutex_lock(&ust_exit_mutex);
1753 sock_info->thread_active = 0;
1754 pthread_mutex_unlock(&ust_exit_mutex);
1755 return NULL;
1756 }
1757
1758 /*
1759 * Weak symbol to call when the ust malloc wrapper is not loaded.
1760 */
1761 __attribute__((weak))
1762 void lttng_ust_malloc_wrapper_init(void)
1763 {
1764 }
1765
1766 /*
1767 * sessiond monitoring thread: monitor presence of global and per-user
1768 * sessiond by polling the application common named pipe.
1769 */
1770 void __attribute__((constructor)) lttng_ust_init(void)
1771 {
1772 struct timespec constructor_timeout;
1773 sigset_t sig_all_blocked, orig_parent_mask;
1774 pthread_attr_t thread_attr;
1775 int timeout_mode;
1776 int ret;
1777 void *handle;
1778
1779 if (uatomic_xchg(&initialized, 1) == 1)
1780 return;
1781
1782 /*
1783 * Fixup interdependency between TLS fixup mutex (which happens
1784 * to be the dynamic linker mutex) and ust_lock, taken within
1785 * the ust lock.
1786 */
1787 lttng_ust_fixup_tls();
1788
1789 lttng_ust_loaded = 1;
1790
1791 /*
1792 * We need to ensure that the liblttng-ust library is not unloaded to avoid
1793 * the unloading of code used by the ust_listener_threads as we can not
1794 * reliably know when they exited. To do that, manually load
1795 * liblttng-ust.so to increment the dynamic loader's internal refcount for
1796 * this library so it never becomes zero, thus never gets unloaded from the
1797 * address space of the process. Since we are already running in the
1798 * constructor of the LTTNG_UST_LIB_SO_NAME library, calling dlopen will
1799 * simply increment the refcount and no additionnal work is needed by the
1800 * dynamic loader as the shared library is already loaded in the address
1801 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
1802 * unloading of the UST library if its refcount becomes zero (which should
1803 * never happen). Do the return value check but discard the handle at the
1804 * end of the function as it's not needed.
1805 */
1806 handle = dlopen(LTTNG_UST_LIB_SO_NAME, RTLD_LAZY | RTLD_NODELETE);
1807 if (!handle) {
1808 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SO_NAME);
1809 }
1810
1811 /*
1812 * We want precise control over the order in which we construct
1813 * our sub-libraries vs starting to receive commands from
1814 * sessiond (otherwise leading to errors when trying to create
1815 * sessiond before the init functions are completed).
1816 */
1817 init_usterr();
1818 lttng_ust_getenv_init(); /* Needs init_usterr() to be completed. */
1819 init_tracepoint();
1820 lttng_ust_init_fd_tracker();
1821 lttng_ust_clock_init();
1822 lttng_ust_getcpu_init();
1823 lttng_ust_statedump_init();
1824 lttng_ring_buffer_metadata_client_init();
1825 lttng_ring_buffer_client_overwrite_init();
1826 lttng_ring_buffer_client_overwrite_rt_init();
1827 lttng_ring_buffer_client_discard_init();
1828 lttng_ring_buffer_client_discard_rt_init();
1829 lttng_perf_counter_init();
1830 /*
1831 * Invoke ust malloc wrapper init before starting other threads.
1832 */
1833 lttng_ust_malloc_wrapper_init();
1834
1835 timeout_mode = get_constructor_timeout(&constructor_timeout);
1836
1837 get_allow_blocking();
1838
1839 ret = sem_init(&constructor_wait, 0, 0);
1840 if (ret) {
1841 PERROR("sem_init");
1842 }
1843
1844 ret = setup_global_apps();
1845 if (ret) {
1846 assert(global_apps.allowed == 0);
1847 DBG("global apps setup returned %d", ret);
1848 }
1849
1850 ret = setup_local_apps();
1851 if (ret) {
1852 assert(local_apps.allowed == 0);
1853 DBG("local apps setup returned %d", ret);
1854 }
1855
1856 /* A new thread created by pthread_create inherits the signal mask
1857 * from the parent. To avoid any signal being received by the
1858 * listener thread, we block all signals temporarily in the parent,
1859 * while we create the listener thread.
1860 */
1861 sigfillset(&sig_all_blocked);
1862 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1863 if (ret) {
1864 ERR("pthread_sigmask: %s", strerror(ret));
1865 }
1866
1867 ret = pthread_attr_init(&thread_attr);
1868 if (ret) {
1869 ERR("pthread_attr_init: %s", strerror(ret));
1870 }
1871 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1872 if (ret) {
1873 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1874 }
1875
1876 if (global_apps.allowed) {
1877 pthread_mutex_lock(&ust_exit_mutex);
1878 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1879 ust_listener_thread, &global_apps);
1880 if (ret) {
1881 ERR("pthread_create global: %s", strerror(ret));
1882 }
1883 global_apps.thread_active = 1;
1884 pthread_mutex_unlock(&ust_exit_mutex);
1885 } else {
1886 handle_register_done(&global_apps);
1887 }
1888
1889 if (local_apps.allowed) {
1890 pthread_mutex_lock(&ust_exit_mutex);
1891 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
1892 ust_listener_thread, &local_apps);
1893 if (ret) {
1894 ERR("pthread_create local: %s", strerror(ret));
1895 }
1896 local_apps.thread_active = 1;
1897 pthread_mutex_unlock(&ust_exit_mutex);
1898 } else {
1899 handle_register_done(&local_apps);
1900 }
1901 ret = pthread_attr_destroy(&thread_attr);
1902 if (ret) {
1903 ERR("pthread_attr_destroy: %s", strerror(ret));
1904 }
1905
1906 /* Restore original signal mask in parent */
1907 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1908 if (ret) {
1909 ERR("pthread_sigmask: %s", strerror(ret));
1910 }
1911
1912 switch (timeout_mode) {
1913 case 1: /* timeout wait */
1914 do {
1915 ret = sem_timedwait(&constructor_wait,
1916 &constructor_timeout);
1917 } while (ret < 0 && errno == EINTR);
1918 if (ret < 0) {
1919 switch (errno) {
1920 case ETIMEDOUT:
1921 ERR("Timed out waiting for lttng-sessiond");
1922 break;
1923 case EINVAL:
1924 PERROR("sem_timedwait");
1925 break;
1926 default:
1927 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1928 strerror(errno));
1929 }
1930 }
1931 break;
1932 case -1:/* wait forever */
1933 do {
1934 ret = sem_wait(&constructor_wait);
1935 } while (ret < 0 && errno == EINTR);
1936 if (ret < 0) {
1937 switch (errno) {
1938 case EINVAL:
1939 PERROR("sem_wait");
1940 break;
1941 default:
1942 ERR("Unexpected error \"%s\" returned by sem_wait",
1943 strerror(errno));
1944 }
1945 }
1946 break;
1947 case 0: /* no timeout */
1948 break;
1949 }
1950 }
1951
1952 static
1953 void lttng_ust_cleanup(int exiting)
1954 {
1955 cleanup_sock_info(&global_apps, exiting);
1956 cleanup_sock_info(&local_apps, exiting);
1957 local_apps.allowed = 0;
1958 global_apps.allowed = 0;
1959 /*
1960 * The teardown in this function all affect data structures
1961 * accessed under the UST lock by the listener thread. This
1962 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1963 * that none of these threads are accessing this data at this
1964 * point.
1965 */
1966 lttng_ust_abi_exit();
1967 lttng_ust_events_exit();
1968 lttng_perf_counter_exit();
1969 lttng_ring_buffer_client_discard_rt_exit();
1970 lttng_ring_buffer_client_discard_exit();
1971 lttng_ring_buffer_client_overwrite_rt_exit();
1972 lttng_ring_buffer_client_overwrite_exit();
1973 lttng_ring_buffer_metadata_client_exit();
1974 lttng_ust_statedump_destroy();
1975 exit_tracepoint();
1976 if (!exiting) {
1977 /* Reinitialize values for fork */
1978 sem_count = sem_count_initial_value;
1979 lttng_ust_comm_should_quit = 0;
1980 initialized = 0;
1981 }
1982 }
1983
1984 void __attribute__((destructor)) lttng_ust_exit(void)
1985 {
1986 int ret;
1987
1988 /*
1989 * Using pthread_cancel here because:
1990 * A) we don't want to hang application teardown.
1991 * B) the thread is not allocating any resource.
1992 */
1993
1994 /*
1995 * Require the communication thread to quit. Synchronize with
1996 * mutexes to ensure it is not in a mutex critical section when
1997 * pthread_cancel is later called.
1998 */
1999 ust_lock_nocheck();
2000 lttng_ust_comm_should_quit = 1;
2001 ust_unlock();
2002
2003 pthread_mutex_lock(&ust_exit_mutex);
2004 /* cancel threads */
2005 if (global_apps.thread_active) {
2006 ret = pthread_cancel(global_apps.ust_listener);
2007 if (ret) {
2008 ERR("Error cancelling global ust listener thread: %s",
2009 strerror(ret));
2010 } else {
2011 global_apps.thread_active = 0;
2012 }
2013 }
2014 if (local_apps.thread_active) {
2015 ret = pthread_cancel(local_apps.ust_listener);
2016 if (ret) {
2017 ERR("Error cancelling local ust listener thread: %s",
2018 strerror(ret));
2019 } else {
2020 local_apps.thread_active = 0;
2021 }
2022 }
2023 pthread_mutex_unlock(&ust_exit_mutex);
2024
2025 /*
2026 * Do NOT join threads: use of sys_futex makes it impossible to
2027 * join the threads without using async-cancel, but async-cancel
2028 * is delivered by a signal, which could hit the target thread
2029 * anywhere in its code path, including while the ust_lock() is
2030 * held, causing a deadlock for the other thread. Let the OS
2031 * cleanup the threads if there are stalled in a syscall.
2032 */
2033 lttng_ust_cleanup(1);
2034 }
2035
2036 /*
2037 * We exclude the worker threads across fork and clone (except
2038 * CLONE_VM), because these system calls only keep the forking thread
2039 * running in the child. Therefore, we don't want to call fork or clone
2040 * in the middle of an tracepoint or ust tracing state modification.
2041 * Holding this mutex protects these structures across fork and clone.
2042 */
2043 void ust_before_fork(sigset_t *save_sigset)
2044 {
2045 /*
2046 * Disable signals. This is to avoid that the child intervenes
2047 * before it is properly setup for tracing. It is safer to
2048 * disable all signals, because then we know we are not breaking
2049 * anything by restoring the original mask.
2050 */
2051 sigset_t all_sigs;
2052 int ret;
2053
2054 /* Fixup lttng-ust TLS. */
2055 lttng_ust_fixup_tls();
2056
2057 if (URCU_TLS(lttng_ust_nest_count))
2058 return;
2059 /* Disable signals */
2060 sigfillset(&all_sigs);
2061 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
2062 if (ret == -1) {
2063 PERROR("sigprocmask");
2064 }
2065
2066 pthread_mutex_lock(&ust_fork_mutex);
2067
2068 ust_lock_nocheck();
2069 urcu_bp_before_fork();
2070 lttng_ust_lock_fd_tracker();
2071 }
2072
2073 static void ust_after_fork_common(sigset_t *restore_sigset)
2074 {
2075 int ret;
2076
2077 DBG("process %d", getpid());
2078 lttng_ust_unlock_fd_tracker();
2079 ust_unlock();
2080
2081 pthread_mutex_unlock(&ust_fork_mutex);
2082
2083 /* Restore signals */
2084 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
2085 if (ret == -1) {
2086 PERROR("sigprocmask");
2087 }
2088 }
2089
2090 void ust_after_fork_parent(sigset_t *restore_sigset)
2091 {
2092 if (URCU_TLS(lttng_ust_nest_count))
2093 return;
2094 DBG("process %d", getpid());
2095 urcu_bp_after_fork_parent();
2096 /* Release mutexes and reenable signals */
2097 ust_after_fork_common(restore_sigset);
2098 }
2099
2100 /*
2101 * After fork, in the child, we need to cleanup all the leftover state,
2102 * except the worker thread which already magically disappeared thanks
2103 * to the weird Linux fork semantics. After tyding up, we call
2104 * lttng_ust_init() again to start over as a new PID.
2105 *
2106 * This is meant for forks() that have tracing in the child between the
2107 * fork and following exec call (if there is any).
2108 */
2109 void ust_after_fork_child(sigset_t *restore_sigset)
2110 {
2111 if (URCU_TLS(lttng_ust_nest_count))
2112 return;
2113 lttng_context_vpid_reset();
2114 lttng_context_vtid_reset();
2115 lttng_context_procname_reset();
2116 DBG("process %d", getpid());
2117 /* Release urcu mutexes */
2118 urcu_bp_after_fork_child();
2119 lttng_ust_cleanup(0);
2120 /* Release mutexes and reenable signals */
2121 ust_after_fork_common(restore_sigset);
2122 lttng_ust_init();
2123 }
2124
2125 void lttng_ust_sockinfo_session_enabled(void *owner)
2126 {
2127 struct sock_info *sock_info = owner;
2128 sock_info->statedump_pending = 1;
2129 }
This page took 0.105761 seconds and 4 git commands to generate.