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