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