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