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