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