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