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