Force tracked fd to be bigger than STDERR_FILENO
[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_getenv("LTTNG_HOME");
369 if (val != NULL) {
370 return val;
371 }
372 return (const char *) lttng_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 = lttng_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
960 ust_unlock();
961
962 /*
963 * Performed delayed statedump operations outside of the UST
964 * lock. We need to take the dynamic loader lock before we take
965 * the UST lock internally within handle_pending_statedump().
966 */
967 handle_pending_statedump(sock_info);
968
969 if (ust_lock()) {
970 ret = -LTTNG_UST_ERR_EXITING;
971 goto error;
972 }
973
974 ret = send_reply(sock, &lur);
975 if (ret < 0) {
976 DBG("error sending reply");
977 goto error;
978 }
979
980 /*
981 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
982 * after the reply.
983 */
984 if (lur.ret_code == LTTNG_UST_OK) {
985 switch (lum->cmd) {
986 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
987 len = ustcomm_send_unix_sock(sock,
988 &args.field_list.entry,
989 sizeof(args.field_list.entry));
990 if (len < 0) {
991 ret = len;
992 goto error;
993 }
994 if (len != sizeof(args.field_list.entry)) {
995 ret = -EINVAL;
996 goto error;
997 }
998 }
999 }
1000
1001 error:
1002 ust_unlock();
1003
1004 return ret;
1005 }
1006
1007 static
1008 void cleanup_sock_info(struct sock_info *sock_info, int exiting)
1009 {
1010 int ret;
1011
1012 if (sock_info->root_handle != -1) {
1013 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1014 if (ret) {
1015 ERR("Error unref root handle");
1016 }
1017 sock_info->root_handle = -1;
1018 }
1019 sock_info->constructor_sem_posted = 0;
1020
1021 /*
1022 * wait_shm_mmap, socket and notify socket are used by listener
1023 * threads outside of the ust lock, so we cannot tear them down
1024 * ourselves, because we cannot join on these threads. Leave
1025 * responsibility of cleaning up these resources to the OS
1026 * process exit.
1027 */
1028 if (exiting)
1029 return;
1030
1031 if (sock_info->socket != -1) {
1032 ret = ustcomm_close_unix_sock(sock_info->socket);
1033 if (ret) {
1034 ERR("Error closing ust cmd socket");
1035 }
1036 sock_info->socket = -1;
1037 }
1038 if (sock_info->notify_socket != -1) {
1039 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1040 if (ret) {
1041 ERR("Error closing ust notify socket");
1042 }
1043 sock_info->notify_socket = -1;
1044 }
1045 if (sock_info->wait_shm_mmap) {
1046 long page_size;
1047
1048 page_size = sysconf(_SC_PAGE_SIZE);
1049 if (page_size <= 0) {
1050 if (!page_size) {
1051 errno = EINVAL;
1052 }
1053 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1054 } else {
1055 ret = munmap(sock_info->wait_shm_mmap, page_size);
1056 if (ret) {
1057 ERR("Error unmapping wait shm");
1058 }
1059 }
1060 sock_info->wait_shm_mmap = NULL;
1061 }
1062 }
1063
1064 /*
1065 * Using fork to set umask in the child process (not multi-thread safe).
1066 * We deal with the shm_open vs ftruncate race (happening when the
1067 * sessiond owns the shm and does not let everybody modify it, to ensure
1068 * safety against shm_unlink) by simply letting the mmap fail and
1069 * retrying after a few seconds.
1070 * For global shm, everybody has rw access to it until the sessiond
1071 * starts.
1072 */
1073 static
1074 int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
1075 {
1076 int wait_shm_fd, ret;
1077 pid_t pid;
1078
1079 /*
1080 * Try to open read-only.
1081 */
1082 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1083 if (wait_shm_fd >= 0) {
1084 int32_t tmp_read;
1085 ssize_t len;
1086 size_t bytes_read = 0;
1087
1088 /*
1089 * Try to read the fd. If unable to do so, try opening
1090 * it in write mode.
1091 */
1092 do {
1093 len = read(wait_shm_fd,
1094 &((char *) &tmp_read)[bytes_read],
1095 sizeof(tmp_read) - bytes_read);
1096 if (len > 0) {
1097 bytes_read += len;
1098 }
1099 } while ((len < 0 && errno == EINTR)
1100 || (len > 0 && bytes_read < sizeof(tmp_read)));
1101 if (bytes_read != sizeof(tmp_read)) {
1102 ret = close(wait_shm_fd);
1103 if (ret) {
1104 ERR("close wait_shm_fd");
1105 }
1106 goto open_write;
1107 }
1108 goto end;
1109 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1110 /*
1111 * Real-only open did not work, and it's not because the
1112 * entry was not present. It's a failure that prohibits
1113 * using shm.
1114 */
1115 ERR("Error opening shm %s", sock_info->wait_shm_path);
1116 goto end;
1117 }
1118
1119 open_write:
1120 /*
1121 * If the open failed because the file did not exist, or because
1122 * the file was not truncated yet, try creating it ourself.
1123 */
1124 URCU_TLS(lttng_ust_nest_count)++;
1125 pid = fork();
1126 URCU_TLS(lttng_ust_nest_count)--;
1127 if (pid > 0) {
1128 int status;
1129
1130 /*
1131 * Parent: wait for child to return, in which case the
1132 * shared memory map will have been created.
1133 */
1134 pid = wait(&status);
1135 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1136 wait_shm_fd = -1;
1137 goto end;
1138 }
1139 /*
1140 * Try to open read-only again after creation.
1141 */
1142 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
1143 if (wait_shm_fd < 0) {
1144 /*
1145 * Real-only open did not work. It's a failure
1146 * that prohibits using shm.
1147 */
1148 ERR("Error opening shm %s", sock_info->wait_shm_path);
1149 goto end;
1150 }
1151 goto end;
1152 } else if (pid == 0) {
1153 int create_mode;
1154
1155 /* Child */
1156 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
1157 if (sock_info->global)
1158 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
1159 /*
1160 * We're alone in a child process, so we can modify the
1161 * process-wide umask.
1162 */
1163 umask(~create_mode);
1164 /*
1165 * Try creating shm (or get rw access).
1166 * We don't do an exclusive open, because we allow other
1167 * processes to create+ftruncate it concurrently.
1168 */
1169 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1170 O_RDWR | O_CREAT, create_mode);
1171 if (wait_shm_fd >= 0) {
1172 ret = ftruncate(wait_shm_fd, mmap_size);
1173 if (ret) {
1174 PERROR("ftruncate");
1175 _exit(EXIT_FAILURE);
1176 }
1177 _exit(EXIT_SUCCESS);
1178 }
1179 /*
1180 * For local shm, we need to have rw access to accept
1181 * opening it: this means the local sessiond will be
1182 * able to wake us up. For global shm, we open it even
1183 * if rw access is not granted, because the root.root
1184 * sessiond will be able to override all rights and wake
1185 * us up.
1186 */
1187 if (!sock_info->global && errno != EACCES) {
1188 ERR("Error opening shm %s", sock_info->wait_shm_path);
1189 _exit(EXIT_FAILURE);
1190 }
1191 /*
1192 * The shm exists, but we cannot open it RW. Report
1193 * success.
1194 */
1195 _exit(EXIT_SUCCESS);
1196 } else {
1197 return -1;
1198 }
1199 end:
1200 if (wait_shm_fd >= 0 && !sock_info->global) {
1201 struct stat statbuf;
1202
1203 /*
1204 * Ensure that our user is the owner of the shm file for
1205 * local shm. If we do not own the file, it means our
1206 * sessiond will not have access to wake us up (there is
1207 * probably a rogue process trying to fake our
1208 * sessiond). Fallback to polling method in this case.
1209 */
1210 ret = fstat(wait_shm_fd, &statbuf);
1211 if (ret) {
1212 PERROR("fstat");
1213 goto error_close;
1214 }
1215 if (statbuf.st_uid != getuid())
1216 goto error_close;
1217 }
1218 return wait_shm_fd;
1219
1220 error_close:
1221 ret = close(wait_shm_fd);
1222 if (ret) {
1223 PERROR("Error closing fd");
1224 }
1225 return -1;
1226 }
1227
1228 static
1229 char *get_map_shm(struct sock_info *sock_info)
1230 {
1231 long page_size;
1232 int wait_shm_fd, ret;
1233 char *wait_shm_mmap;
1234
1235 page_size = sysconf(_SC_PAGE_SIZE);
1236 if (page_size <= 0) {
1237 if (!page_size) {
1238 errno = EINVAL;
1239 }
1240 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1241 goto error;
1242 }
1243
1244 lttng_ust_lock_fd_tracker();
1245 wait_shm_fd = get_wait_shm(sock_info, page_size);
1246 if (wait_shm_fd < 0) {
1247 lttng_ust_unlock_fd_tracker();
1248 goto error;
1249 }
1250
1251 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1252 if (ret < 0) {
1253 ret = close(wait_shm_fd);
1254 if (!ret) {
1255 PERROR("Error closing fd");
1256 }
1257 lttng_ust_unlock_fd_tracker();
1258 goto error;
1259 }
1260
1261 wait_shm_fd = ret;
1262 lttng_ust_unlock_fd_tracker();
1263
1264 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
1265 MAP_SHARED, wait_shm_fd, 0);
1266
1267 /* close shm fd immediately after taking the mmap reference */
1268 lttng_ust_lock_fd_tracker();
1269 ret = close(wait_shm_fd);
1270 if (!ret) {
1271 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1272 } else {
1273 PERROR("Error closing fd");
1274 }
1275 lttng_ust_unlock_fd_tracker();
1276
1277 if (wait_shm_mmap == MAP_FAILED) {
1278 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1279 goto error;
1280 }
1281 return wait_shm_mmap;
1282
1283 error:
1284 return NULL;
1285 }
1286
1287 static
1288 void wait_for_sessiond(struct sock_info *sock_info)
1289 {
1290 if (ust_lock()) {
1291 goto quit;
1292 }
1293 if (wait_poll_fallback) {
1294 goto error;
1295 }
1296 if (!sock_info->wait_shm_mmap) {
1297 sock_info->wait_shm_mmap = get_map_shm(sock_info);
1298 if (!sock_info->wait_shm_mmap)
1299 goto error;
1300 }
1301 ust_unlock();
1302
1303 DBG("Waiting for %s apps sessiond", sock_info->name);
1304 /* Wait for futex wakeup */
1305 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1306 goto end_wait;
1307
1308 while (futex_async((int32_t *) sock_info->wait_shm_mmap,
1309 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1310 switch (errno) {
1311 case EWOULDBLOCK:
1312 /* Value already changed. */
1313 goto end_wait;
1314 case EINTR:
1315 /* Retry if interrupted by signal. */
1316 break; /* Get out of switch. */
1317 case EFAULT:
1318 wait_poll_fallback = 1;
1319 DBG(
1320 "Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1321 "do not support FUTEX_WAKE on read-only memory mappings correctly. "
1322 "Please upgrade your kernel "
1323 "(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1324 "mainline). LTTng-UST will use polling mode fallback.");
1325 if (ust_debug())
1326 PERROR("futex");
1327 goto end_wait;
1328 }
1329 }
1330 end_wait:
1331 return;
1332
1333 quit:
1334 ust_unlock();
1335 return;
1336
1337 error:
1338 ust_unlock();
1339 return;
1340 }
1341
1342 /*
1343 * This thread does not allocate any resource, except within
1344 * handle_message, within mutex protection. This mutex protects against
1345 * fork and exit.
1346 * The other moment it allocates resources is at socket connection, which
1347 * is also protected by the mutex.
1348 */
1349 static
1350 void *ust_listener_thread(void *arg)
1351 {
1352 struct sock_info *sock_info = arg;
1353 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
1354 long timeout;
1355
1356 lttng_ust_fixup_tls();
1357 /*
1358 * If available, add '-ust' to the end of this thread's
1359 * process name
1360 */
1361 ret = lttng_ust_setustprocname();
1362 if (ret) {
1363 ERR("Unable to set UST process name");
1364 }
1365
1366 /* Restart trying to connect to the session daemon */
1367 restart:
1368 if (prev_connect_failed) {
1369 /* Wait for sessiond availability with pipe */
1370 wait_for_sessiond(sock_info);
1371 if (has_waited) {
1372 has_waited = 0;
1373 /*
1374 * Sleep for 5 seconds before retrying after a
1375 * sequence of failure / wait / failure. This
1376 * deals with a killed or broken session daemon.
1377 */
1378 sleep(5);
1379 } else {
1380 has_waited = 1;
1381 }
1382 prev_connect_failed = 0;
1383 }
1384
1385 if (sock_info->socket != -1) {
1386 /* FD tracker is updated by ustcomm_close_unix_sock() */
1387 ret = ustcomm_close_unix_sock(sock_info->socket);
1388 if (ret) {
1389 ERR("Error closing %s ust cmd socket",
1390 sock_info->name);
1391 }
1392 sock_info->socket = -1;
1393 }
1394 if (sock_info->notify_socket != -1) {
1395 /* FD tracker is updated by ustcomm_close_unix_sock() */
1396 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1397 if (ret) {
1398 ERR("Error closing %s ust notify socket",
1399 sock_info->name);
1400 }
1401 sock_info->notify_socket = -1;
1402 }
1403
1404 if (ust_lock()) {
1405 goto quit;
1406 }
1407
1408 /*
1409 * Register. We need to perform both connect and sending
1410 * registration message before doing the next connect otherwise
1411 * we may reach unix socket connect queue max limits and block
1412 * on the 2nd connect while the session daemon is awaiting the
1413 * first connect registration message.
1414 */
1415 /* Connect cmd socket */
1416 lttng_ust_lock_fd_tracker();
1417 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1418 get_connect_sock_timeout());
1419 if (ret < 0) {
1420 lttng_ust_unlock_fd_tracker();
1421 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1422 prev_connect_failed = 1;
1423
1424 /*
1425 * If we cannot find the sessiond daemon, don't delay
1426 * constructor execution.
1427 */
1428 ret = handle_register_done(sock_info);
1429 assert(!ret);
1430 ust_unlock();
1431 goto restart;
1432 }
1433 fd = ret;
1434 ret = lttng_ust_add_fd_to_tracker(fd);
1435 if (ret < 0) {
1436 ret = close(fd);
1437 if (ret) {
1438 PERROR("close on sock_info->socket");
1439 }
1440 ret = -1;
1441 lttng_ust_unlock_fd_tracker();
1442 ust_unlock();
1443 goto quit;
1444 }
1445
1446 sock_info->socket = ret;
1447 lttng_ust_unlock_fd_tracker();
1448
1449 ust_unlock();
1450 /*
1451 * Unlock/relock ust lock because connect is blocking (with
1452 * timeout). Don't delay constructors on the ust lock for too
1453 * long.
1454 */
1455 if (ust_lock()) {
1456 goto quit;
1457 }
1458
1459 /*
1460 * Create only one root handle per listener thread for the whole
1461 * process lifetime, so we ensure we get ID which is statically
1462 * assigned to the root handle.
1463 */
1464 if (sock_info->root_handle == -1) {
1465 ret = lttng_abi_create_root_handle();
1466 if (ret < 0) {
1467 ERR("Error creating root handle");
1468 goto quit;
1469 }
1470 sock_info->root_handle = ret;
1471 }
1472
1473 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
1474 if (ret < 0) {
1475 ERR("Error registering to %s ust cmd socket",
1476 sock_info->name);
1477 prev_connect_failed = 1;
1478 /*
1479 * If we cannot register to the sessiond daemon, don't
1480 * delay constructor execution.
1481 */
1482 ret = handle_register_done(sock_info);
1483 assert(!ret);
1484 ust_unlock();
1485 goto restart;
1486 }
1487
1488 ust_unlock();
1489 /*
1490 * Unlock/relock ust lock because connect is blocking (with
1491 * timeout). Don't delay constructors on the ust lock for too
1492 * long.
1493 */
1494 if (ust_lock()) {
1495 goto quit;
1496 }
1497
1498 /* Connect notify socket */
1499 lttng_ust_lock_fd_tracker();
1500 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1501 get_connect_sock_timeout());
1502 if (ret < 0) {
1503 lttng_ust_unlock_fd_tracker();
1504 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1505 prev_connect_failed = 1;
1506
1507 /*
1508 * If we cannot find the sessiond daemon, don't delay
1509 * constructor execution.
1510 */
1511 ret = handle_register_done(sock_info);
1512 assert(!ret);
1513 ust_unlock();
1514 goto restart;
1515 }
1516
1517 fd = ret;
1518 ret = lttng_ust_add_fd_to_tracker(fd);
1519 if (ret < 0) {
1520 ret = close(fd);
1521 if (ret) {
1522 PERROR("close on sock_info->notify_socket");
1523 }
1524 ret = -1;
1525 lttng_ust_unlock_fd_tracker();
1526 ust_unlock();
1527 goto quit;
1528 }
1529
1530 sock_info->notify_socket = ret;
1531 lttng_ust_unlock_fd_tracker();
1532
1533 ust_unlock();
1534 /*
1535 * Unlock/relock ust lock because connect is blocking (with
1536 * timeout). Don't delay constructors on the ust lock for too
1537 * long.
1538 */
1539 if (ust_lock()) {
1540 goto quit;
1541 }
1542
1543 timeout = get_notify_sock_timeout();
1544 if (timeout >= 0) {
1545 /*
1546 * Give at least 10ms to sessiond to reply to
1547 * notifications.
1548 */
1549 if (timeout < 10)
1550 timeout = 10;
1551 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1552 timeout);
1553 if (ret < 0) {
1554 WARN("Error setting socket receive timeout");
1555 }
1556 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1557 timeout);
1558 if (ret < 0) {
1559 WARN("Error setting socket send timeout");
1560 }
1561 } else if (timeout < -1) {
1562 WARN("Unsupported timeout value %ld", timeout);
1563 }
1564
1565 ret = register_to_sessiond(sock_info->notify_socket,
1566 USTCTL_SOCKET_NOTIFY);
1567 if (ret < 0) {
1568 ERR("Error registering to %s ust notify socket",
1569 sock_info->name);
1570 prev_connect_failed = 1;
1571 /*
1572 * If we cannot register to the sessiond daemon, don't
1573 * delay constructor execution.
1574 */
1575 ret = handle_register_done(sock_info);
1576 assert(!ret);
1577 ust_unlock();
1578 goto restart;
1579 }
1580 sock = sock_info->socket;
1581
1582 ust_unlock();
1583
1584 for (;;) {
1585 ssize_t len;
1586 struct ustcomm_ust_msg lum;
1587
1588 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
1589 switch (len) {
1590 case 0: /* orderly shutdown */
1591 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
1592 if (ust_lock()) {
1593 goto quit;
1594 }
1595 /*
1596 * Either sessiond has shutdown or refused us by closing the socket.
1597 * In either case, we don't want to delay construction execution,
1598 * and we need to wait before retry.
1599 */
1600 prev_connect_failed = 1;
1601 /*
1602 * If we cannot register to the sessiond daemon, don't
1603 * delay constructor execution.
1604 */
1605 ret = handle_register_done(sock_info);
1606 assert(!ret);
1607 ust_unlock();
1608 goto end;
1609 case sizeof(lum):
1610 print_cmd(lum.cmd, lum.handle);
1611 ret = handle_message(sock_info, sock, &lum);
1612 if (ret) {
1613 ERR("Error handling message for %s socket",
1614 sock_info->name);
1615 /*
1616 * Close socket if protocol error is
1617 * detected.
1618 */
1619 goto end;
1620 }
1621 continue;
1622 default:
1623 if (len < 0) {
1624 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1625 } else {
1626 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1627 }
1628 if (len == -ECONNRESET) {
1629 DBG("%s remote end closed connection", sock_info->name);
1630 goto end;
1631 }
1632 goto end;
1633 }
1634
1635 }
1636 end:
1637 if (ust_lock()) {
1638 goto quit;
1639 }
1640 /* Cleanup socket handles before trying to reconnect */
1641 lttng_ust_objd_table_owner_cleanup(sock_info);
1642 ust_unlock();
1643 goto restart; /* try to reconnect */
1644
1645 quit:
1646 ust_unlock();
1647
1648 pthread_mutex_lock(&ust_exit_mutex);
1649 sock_info->thread_active = 0;
1650 pthread_mutex_unlock(&ust_exit_mutex);
1651 return NULL;
1652 }
1653
1654 /*
1655 * Weak symbol to call when the ust malloc wrapper is not loaded.
1656 */
1657 __attribute__((weak))
1658 void lttng_ust_malloc_wrapper_init(void)
1659 {
1660 }
1661
1662 /*
1663 * sessiond monitoring thread: monitor presence of global and per-user
1664 * sessiond by polling the application common named pipe.
1665 */
1666 void __attribute__((constructor)) lttng_ust_init(void)
1667 {
1668 struct timespec constructor_timeout;
1669 sigset_t sig_all_blocked, orig_parent_mask;
1670 pthread_attr_t thread_attr;
1671 int timeout_mode;
1672 int ret;
1673
1674 if (uatomic_xchg(&initialized, 1) == 1)
1675 return;
1676
1677 /*
1678 * Fixup interdependency between TLS fixup mutex (which happens
1679 * to be the dynamic linker mutex) and ust_lock, taken within
1680 * the ust lock.
1681 */
1682 lttng_ust_fixup_tls();
1683
1684 lttng_ust_loaded = 1;
1685
1686 /*
1687 * We want precise control over the order in which we construct
1688 * our sub-libraries vs starting to receive commands from
1689 * sessiond (otherwise leading to errors when trying to create
1690 * sessiond before the init functions are completed).
1691 */
1692 init_usterr();
1693 lttng_ust_getenv_init(); /* Needs init_usterr() to be completed. */
1694 init_tracepoint();
1695 lttng_ust_init_fd_tracker();
1696 lttng_ust_clock_init();
1697 lttng_ust_getcpu_init();
1698 lttng_ust_statedump_init();
1699 lttng_ring_buffer_metadata_client_init();
1700 lttng_ring_buffer_client_overwrite_init();
1701 lttng_ring_buffer_client_overwrite_rt_init();
1702 lttng_ring_buffer_client_discard_init();
1703 lttng_ring_buffer_client_discard_rt_init();
1704 lttng_perf_counter_init();
1705 /*
1706 * Invoke ust malloc wrapper init before starting other threads.
1707 */
1708 lttng_ust_malloc_wrapper_init();
1709
1710 timeout_mode = get_constructor_timeout(&constructor_timeout);
1711
1712 ret = sem_init(&constructor_wait, 0, 0);
1713 if (ret) {
1714 PERROR("sem_init");
1715 }
1716
1717 ret = setup_local_apps();
1718 if (ret) {
1719 DBG("local apps setup returned %d", ret);
1720 }
1721
1722 /* A new thread created by pthread_create inherits the signal mask
1723 * from the parent. To avoid any signal being received by the
1724 * listener thread, we block all signals temporarily in the parent,
1725 * while we create the listener thread.
1726 */
1727 sigfillset(&sig_all_blocked);
1728 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1729 if (ret) {
1730 ERR("pthread_sigmask: %s", strerror(ret));
1731 }
1732
1733 ret = pthread_attr_init(&thread_attr);
1734 if (ret) {
1735 ERR("pthread_attr_init: %s", strerror(ret));
1736 }
1737 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1738 if (ret) {
1739 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1740 }
1741
1742 pthread_mutex_lock(&ust_exit_mutex);
1743 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1744 ust_listener_thread, &global_apps);
1745 if (ret) {
1746 ERR("pthread_create global: %s", strerror(ret));
1747 }
1748 global_apps.thread_active = 1;
1749 pthread_mutex_unlock(&ust_exit_mutex);
1750
1751 if (local_apps.allowed) {
1752 pthread_mutex_lock(&ust_exit_mutex);
1753 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
1754 ust_listener_thread, &local_apps);
1755 if (ret) {
1756 ERR("pthread_create local: %s", strerror(ret));
1757 }
1758 local_apps.thread_active = 1;
1759 pthread_mutex_unlock(&ust_exit_mutex);
1760 } else {
1761 handle_register_done(&local_apps);
1762 }
1763 ret = pthread_attr_destroy(&thread_attr);
1764 if (ret) {
1765 ERR("pthread_attr_destroy: %s", strerror(ret));
1766 }
1767
1768 /* Restore original signal mask in parent */
1769 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1770 if (ret) {
1771 ERR("pthread_sigmask: %s", strerror(ret));
1772 }
1773
1774 switch (timeout_mode) {
1775 case 1: /* timeout wait */
1776 do {
1777 ret = sem_timedwait(&constructor_wait,
1778 &constructor_timeout);
1779 } while (ret < 0 && errno == EINTR);
1780 if (ret < 0) {
1781 switch (errno) {
1782 case ETIMEDOUT:
1783 ERR("Timed out waiting for lttng-sessiond");
1784 break;
1785 case EINVAL:
1786 PERROR("sem_timedwait");
1787 break;
1788 default:
1789 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1790 strerror(errno));
1791 }
1792 }
1793 break;
1794 case -1:/* wait forever */
1795 do {
1796 ret = sem_wait(&constructor_wait);
1797 } while (ret < 0 && errno == EINTR);
1798 if (ret < 0) {
1799 switch (errno) {
1800 case EINVAL:
1801 PERROR("sem_wait");
1802 break;
1803 default:
1804 ERR("Unexpected error \"%s\" returned by sem_wait",
1805 strerror(errno));
1806 }
1807 }
1808 break;
1809 case 0: /* no timeout */
1810 break;
1811 }
1812 }
1813
1814 static
1815 void lttng_ust_cleanup(int exiting)
1816 {
1817 cleanup_sock_info(&global_apps, exiting);
1818 cleanup_sock_info(&local_apps, exiting);
1819 local_apps.allowed = 0;
1820 /*
1821 * The teardown in this function all affect data structures
1822 * accessed under the UST lock by the listener thread. This
1823 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1824 * that none of these threads are accessing this data at this
1825 * point.
1826 */
1827 lttng_ust_abi_exit();
1828 lttng_ust_events_exit();
1829 lttng_perf_counter_exit();
1830 lttng_ring_buffer_client_discard_rt_exit();
1831 lttng_ring_buffer_client_discard_exit();
1832 lttng_ring_buffer_client_overwrite_rt_exit();
1833 lttng_ring_buffer_client_overwrite_exit();
1834 lttng_ring_buffer_metadata_client_exit();
1835 lttng_ust_statedump_destroy();
1836 exit_tracepoint();
1837 if (!exiting) {
1838 /* Reinitialize values for fork */
1839 sem_count = 2;
1840 lttng_ust_comm_should_quit = 0;
1841 initialized = 0;
1842 }
1843 }
1844
1845 void __attribute__((destructor)) lttng_ust_exit(void)
1846 {
1847 int ret;
1848
1849 /*
1850 * Using pthread_cancel here because:
1851 * A) we don't want to hang application teardown.
1852 * B) the thread is not allocating any resource.
1853 */
1854
1855 /*
1856 * Require the communication thread to quit. Synchronize with
1857 * mutexes to ensure it is not in a mutex critical section when
1858 * pthread_cancel is later called.
1859 */
1860 ust_lock_nocheck();
1861 lttng_ust_comm_should_quit = 1;
1862 ust_unlock();
1863
1864 pthread_mutex_lock(&ust_exit_mutex);
1865 /* cancel threads */
1866 if (global_apps.thread_active) {
1867 ret = pthread_cancel(global_apps.ust_listener);
1868 if (ret) {
1869 ERR("Error cancelling global ust listener thread: %s",
1870 strerror(ret));
1871 } else {
1872 global_apps.thread_active = 0;
1873 }
1874 }
1875 if (local_apps.thread_active) {
1876 ret = pthread_cancel(local_apps.ust_listener);
1877 if (ret) {
1878 ERR("Error cancelling local ust listener thread: %s",
1879 strerror(ret));
1880 } else {
1881 local_apps.thread_active = 0;
1882 }
1883 }
1884 pthread_mutex_unlock(&ust_exit_mutex);
1885
1886 /*
1887 * Do NOT join threads: use of sys_futex makes it impossible to
1888 * join the threads without using async-cancel, but async-cancel
1889 * is delivered by a signal, which could hit the target thread
1890 * anywhere in its code path, including while the ust_lock() is
1891 * held, causing a deadlock for the other thread. Let the OS
1892 * cleanup the threads if there are stalled in a syscall.
1893 */
1894 lttng_ust_cleanup(1);
1895 }
1896
1897 /*
1898 * We exclude the worker threads across fork and clone (except
1899 * CLONE_VM), because these system calls only keep the forking thread
1900 * running in the child. Therefore, we don't want to call fork or clone
1901 * in the middle of an tracepoint or ust tracing state modification.
1902 * Holding this mutex protects these structures across fork and clone.
1903 */
1904 void ust_before_fork(sigset_t *save_sigset)
1905 {
1906 /*
1907 * Disable signals. This is to avoid that the child intervenes
1908 * before it is properly setup for tracing. It is safer to
1909 * disable all signals, because then we know we are not breaking
1910 * anything by restoring the original mask.
1911 */
1912 sigset_t all_sigs;
1913 int ret;
1914
1915 /* Fixup lttng-ust TLS. */
1916 lttng_ust_fixup_tls();
1917
1918 if (URCU_TLS(lttng_ust_nest_count))
1919 return;
1920 /* Disable signals */
1921 sigfillset(&all_sigs);
1922 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
1923 if (ret == -1) {
1924 PERROR("sigprocmask");
1925 }
1926
1927 pthread_mutex_lock(&ust_fork_mutex);
1928
1929 ust_lock_nocheck();
1930 rcu_bp_before_fork();
1931 }
1932
1933 static void ust_after_fork_common(sigset_t *restore_sigset)
1934 {
1935 int ret;
1936
1937 DBG("process %d", getpid());
1938 ust_unlock();
1939
1940 pthread_mutex_unlock(&ust_fork_mutex);
1941
1942 /* Restore signals */
1943 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
1944 if (ret == -1) {
1945 PERROR("sigprocmask");
1946 }
1947 }
1948
1949 void ust_after_fork_parent(sigset_t *restore_sigset)
1950 {
1951 if (URCU_TLS(lttng_ust_nest_count))
1952 return;
1953 DBG("process %d", getpid());
1954 rcu_bp_after_fork_parent();
1955 /* Release mutexes and reenable signals */
1956 ust_after_fork_common(restore_sigset);
1957 }
1958
1959 /*
1960 * After fork, in the child, we need to cleanup all the leftover state,
1961 * except the worker thread which already magically disappeared thanks
1962 * to the weird Linux fork semantics. After tyding up, we call
1963 * lttng_ust_init() again to start over as a new PID.
1964 *
1965 * This is meant for forks() that have tracing in the child between the
1966 * fork and following exec call (if there is any).
1967 */
1968 void ust_after_fork_child(sigset_t *restore_sigset)
1969 {
1970 if (URCU_TLS(lttng_ust_nest_count))
1971 return;
1972 lttng_context_vtid_reset();
1973 DBG("process %d", getpid());
1974 /* Release urcu mutexes */
1975 rcu_bp_after_fork_child();
1976 lttng_ust_cleanup(0);
1977 /* Release mutexes and reenable signals */
1978 ust_after_fork_common(restore_sigset);
1979 lttng_ust_init();
1980 }
1981
1982 void lttng_ust_sockinfo_session_enabled(void *owner)
1983 {
1984 struct sock_info *sock_info = owner;
1985 sock_info->statedump_pending = 1;
1986 }
This page took 0.087986 seconds and 5 git commands to generate.