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