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