Cleanup: apply `include-what-you-use` guideline for `size_t`
[lttng-ust.git] / liblttng-ust / lttng-ust-comm.c
CommitLineData
2691221a
MD
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
80e2814b 22#define _LGPL_SOURCE
5e1b7b8b 23#define _GNU_SOURCE
b4051ad8 24#include <stddef.h>
2691221a
MD
25#include <sys/types.h>
26#include <sys/socket.h>
7fc90dca
MD
27#include <sys/mman.h>
28#include <sys/stat.h>
58d4b2a2
MD
29#include <sys/types.h>
30#include <sys/wait.h>
b2292d85 31#include <dlfcn.h>
7fc90dca 32#include <fcntl.h>
2691221a
MD
33#include <unistd.h>
34#include <errno.h>
d9e99d10 35#include <pthread.h>
11ff9c7d
MD
36#include <semaphore.h>
37#include <time.h>
1ea11eab 38#include <assert.h>
e822f505 39#include <signal.h>
6f97f9c2 40#include <limits.h>
95259bd0 41#include <urcu/uatomic.h>
80e2814b 42#include <urcu/futex.h>
c117fb1b 43#include <urcu/compiler.h>
1ea11eab 44
4318ae1b 45#include <lttng/ust-events.h>
4318ae1b 46#include <lttng/ust-abi.h>
4318ae1b 47#include <lttng/ust.h>
7bc53e94 48#include <lttng/ust-error.h>
74d81a6c 49#include <lttng/ust-ctl.h>
8c90a710 50#include <urcu/tls-compat.h>
44c72f10 51#include <ust-comm.h>
6548fca4 52#include <ust-fd.h>
44c72f10 53#include <usterr-signal-safe.h>
cd54f6d9 54#include <helper.h>
44c72f10 55#include "tracepoint-internal.h"
7dd08bec 56#include "lttng-tracer-core.h"
08114193 57#include "compat.h"
6f97f9c2 58#include "../libringbuffer/rb-init.h"
cf73e0fe 59#include "lttng-ust-statedump.h"
f9364363 60#include "clock.h"
5e1b7b8b 61#include "../libringbuffer/getcpu.h"
13efba44 62#include "getenv.h"
edaa1431 63
b2292d85 64/* Concatenate lttng ust shared library name with its major version number. */
6be9efc1 65#define LTTNG_UST_LIB_SO_NAME "liblttng-ust.so." __ust_stringify(CONFIG_LTTNG_UST_LIBRARY_VERSION_MAJOR)
b2292d85 66
edaa1431
MD
67/*
68 * Has lttng ust comm constructor been called ?
69 */
70static int initialized;
71
1ea11eab 72/*
17dfb34b
MD
73 * The ust_lock/ust_unlock lock is used as a communication thread mutex.
74 * Held when handling a command, also held by fork() to deal with
75 * removal of threads, and by exit path.
3327ac33
MD
76 *
77 * The UST lock is the centralized mutex across UST tracing control and
78 * probe registration.
79 *
80 * ust_exit_mutex must never nest in ust_mutex.
d58d1454 81 *
4770bd47
MD
82 * ust_fork_mutex must never nest in ust_mutex.
83 *
d58d1454
MD
84 * ust_mutex_nest is a per-thread nesting counter, allowing the perf
85 * counter lazy initialization called by events within the statedump,
86 * which traces while the ust_mutex is held.
4770bd47
MD
87 *
88 * ust_lock nests within the dynamic loader lock (within glibc) because
89 * it is taken within the library constructor.
c1be081a
MD
90 *
91 * The ust fd tracker lock nests within the ust_mutex.
3327ac33
MD
92 */
93static pthread_mutex_t ust_mutex = PTHREAD_MUTEX_INITIALIZER;
94
d58d1454 95/* Allow nesting the ust_mutex within the same thread. */
16adecf1 96static DEFINE_URCU_TLS(int, ust_mutex_nest);
d58d1454 97
3327ac33
MD
98/*
99 * ust_exit_mutex protects thread_active variable wrt thread exit. It
100 * cannot be done by ust_mutex because pthread_cancel(), which takes an
101 * internal libc lock, cannot nest within ust_mutex.
102 *
103 * It never nests within a ust_mutex.
1ea11eab 104 */
3327ac33 105static pthread_mutex_t ust_exit_mutex = PTHREAD_MUTEX_INITIALIZER;
1ea11eab 106
458d678c
PW
107/*
108 * ust_fork_mutex protects base address statedump tracing against forks. It
109 * prevents the dynamic loader lock to be taken (by base address statedump
110 * tracing) while a fork is happening, thus preventing deadlock issues with
111 * the dynamic loader lock.
112 */
113static pthread_mutex_t ust_fork_mutex = PTHREAD_MUTEX_INITIALIZER;
114
1ea11eab
MD
115/* Should the ust comm thread quit ? */
116static int lttng_ust_comm_should_quit;
117
07b57e5e
MD
118/*
119 * This variable can be tested by applications to check whether
120 * lttng-ust is loaded. They simply have to define their own
121 * "lttng_ust_loaded" weak symbol, and test it. It is set to 1 by the
122 * library constructor.
123 */
124int lttng_ust_loaded __attribute__((weak));
125
3327ac33 126/*
d58d1454 127 * Return 0 on success, -1 if should quit.
3327ac33 128 * The lock is taken in both cases.
d58d1454 129 * Signal-safe.
3327ac33
MD
130 */
131int ust_lock(void)
132{
d58d1454 133 sigset_t sig_all_blocked, orig_mask;
e446ad80 134 int ret, oldstate;
d58d1454 135
e446ad80
MD
136 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
137 if (ret) {
138 ERR("pthread_setcancelstate: %s", strerror(ret));
139 }
140 if (oldstate != PTHREAD_CANCEL_ENABLE) {
141 ERR("pthread_setcancelstate: unexpected oldstate");
142 }
d58d1454
MD
143 sigfillset(&sig_all_blocked);
144 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
145 if (ret) {
146 ERR("pthread_sigmask: %s", strerror(ret));
147 }
148 if (!URCU_TLS(ust_mutex_nest)++)
149 pthread_mutex_lock(&ust_mutex);
150 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
151 if (ret) {
152 ERR("pthread_sigmask: %s", strerror(ret));
153 }
3327ac33
MD
154 if (lttng_ust_comm_should_quit) {
155 return -1;
156 } else {
157 return 0;
158 }
159}
160
161/*
162 * ust_lock_nocheck() can be used in constructors/destructors, because
163 * they are already nested within the dynamic loader lock, and therefore
164 * have exclusive access against execution of liblttng-ust destructor.
d58d1454 165 * Signal-safe.
3327ac33
MD
166 */
167void ust_lock_nocheck(void)
168{
d58d1454 169 sigset_t sig_all_blocked, orig_mask;
e446ad80 170 int ret, oldstate;
d58d1454 171
e446ad80
MD
172 ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
173 if (ret) {
174 ERR("pthread_setcancelstate: %s", strerror(ret));
175 }
176 if (oldstate != PTHREAD_CANCEL_ENABLE) {
177 ERR("pthread_setcancelstate: unexpected oldstate");
178 }
d58d1454
MD
179 sigfillset(&sig_all_blocked);
180 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
181 if (ret) {
182 ERR("pthread_sigmask: %s", strerror(ret));
183 }
184 if (!URCU_TLS(ust_mutex_nest)++)
185 pthread_mutex_lock(&ust_mutex);
186 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
187 if (ret) {
188 ERR("pthread_sigmask: %s", strerror(ret));
189 }
3327ac33
MD
190}
191
d58d1454
MD
192/*
193 * Signal-safe.
194 */
3327ac33
MD
195void ust_unlock(void)
196{
d58d1454 197 sigset_t sig_all_blocked, orig_mask;
e446ad80 198 int ret, oldstate;
d58d1454
MD
199
200 sigfillset(&sig_all_blocked);
201 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_mask);
202 if (ret) {
203 ERR("pthread_sigmask: %s", strerror(ret));
204 }
205 if (!--URCU_TLS(ust_mutex_nest))
206 pthread_mutex_unlock(&ust_mutex);
207 ret = pthread_sigmask(SIG_SETMASK, &orig_mask, NULL);
208 if (ret) {
209 ERR("pthread_sigmask: %s", strerror(ret));
210 }
e446ad80
MD
211 ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
212 if (ret) {
213 ERR("pthread_setcancelstate: %s", strerror(ret));
214 }
215 if (oldstate != PTHREAD_CANCEL_DISABLE) {
216 ERR("pthread_setcancelstate: unexpected oldstate");
217 }
3327ac33
MD
218}
219
11ff9c7d
MD
220/*
221 * Wait for either of these before continuing to the main
222 * program:
223 * - the register_done message from sessiond daemon
224 * (will let the sessiond daemon enable sessions before main
225 * starts.)
226 * - sessiond daemon is not reachable.
227 * - timeout (ensuring applications are resilient to session
228 * daemon problems).
229 */
230static sem_t constructor_wait;
950aab0c
MD
231/*
232 * Doing this for both the global and local sessiond.
233 */
eb0e6022
GAPG
234enum {
235 sem_count_initial_value = 4,
236};
237
238static int sem_count = sem_count_initial_value;
11ff9c7d 239
e8508a49
MD
240/*
241 * Counting nesting within lttng-ust. Used to ensure that calling fork()
242 * from liblttng-ust does not execute the pre/post fork handlers.
243 */
8c90a710 244static DEFINE_URCU_TLS(int, lttng_ust_nest_count);
e8508a49 245
1ea11eab
MD
246/*
247 * Info about socket and associated listener thread.
248 */
249struct sock_info {
11ff9c7d 250 const char *name;
1ea11eab 251 pthread_t ust_listener; /* listener thread */
46050b1a 252 int root_handle;
eb0e6022 253 int registration_done;
8d20bf54 254 int allowed;
44e073f5 255 int global;
e33f3265 256 int thread_active;
7fc90dca
MD
257
258 char sock_path[PATH_MAX];
259 int socket;
32ce8569 260 int notify_socket;
7fc90dca
MD
261
262 char wait_shm_path[PATH_MAX];
263 char *wait_shm_mmap;
37dddb65
MD
264 /* Keep track of lazy state dump not performed yet. */
265 int statedump_pending;
eb0e6022 266 int initial_statedump_done;
94be38e8
JR
267 /* Keep procname for statedump */
268 char procname[LTTNG_UST_PROCNAME_LEN];
1ea11eab 269};
2691221a
MD
270
271/* Socket from app (connect) to session daemon (listen) for communication */
1ea11eab 272struct sock_info global_apps = {
11ff9c7d 273 .name = "global",
44e073f5 274 .global = 1,
7fc90dca 275
46050b1a 276 .root_handle = -1,
eb0e6022 277 .registration_done = 0,
060577e3 278 .allowed = 0,
e33f3265 279 .thread_active = 0,
7fc90dca 280
32ce8569 281 .sock_path = LTTNG_DEFAULT_RUNDIR "/" LTTNG_UST_SOCK_FILENAME,
7fc90dca 282 .socket = -1,
32ce8569 283 .notify_socket = -1,
7fc90dca 284
32ce8569 285 .wait_shm_path = "/" LTTNG_UST_WAIT_FILENAME,
95c25348 286
37dddb65 287 .statedump_pending = 0,
eb0e6022 288 .initial_statedump_done = 0,
94be38e8 289 .procname[0] = '\0'
1ea11eab 290};
2691221a
MD
291
292/* TODO: allow global_apps_sock_path override */
293
1ea11eab 294struct sock_info local_apps = {
11ff9c7d 295 .name = "local",
44e073f5 296 .global = 0,
46050b1a 297 .root_handle = -1,
eb0e6022 298 .registration_done = 0,
8d20bf54 299 .allowed = 0, /* Check setuid bit first */
e33f3265 300 .thread_active = 0,
7fc90dca
MD
301
302 .socket = -1,
32ce8569 303 .notify_socket = -1,
95c25348 304
37dddb65 305 .statedump_pending = 0,
eb0e6022 306 .initial_statedump_done = 0,
94be38e8 307 .procname[0] = '\0'
1ea11eab 308};
2691221a 309
37ed587a
MD
310static int wait_poll_fallback;
311
74d81a6c
MD
312static const char *cmd_name_mapping[] = {
313 [ LTTNG_UST_RELEASE ] = "Release",
314 [ LTTNG_UST_SESSION ] = "Create Session",
315 [ LTTNG_UST_TRACER_VERSION ] = "Get Tracer Version",
316
317 [ LTTNG_UST_TRACEPOINT_LIST ] = "Create Tracepoint List",
318 [ LTTNG_UST_WAIT_QUIESCENT ] = "Wait for Quiescent State",
319 [ LTTNG_UST_REGISTER_DONE ] = "Registration Done",
320 [ LTTNG_UST_TRACEPOINT_FIELD_LIST ] = "Create Tracepoint Field List",
321
322 /* Session FD commands */
323 [ LTTNG_UST_CHANNEL ] = "Create Channel",
324 [ LTTNG_UST_SESSION_START ] = "Start Session",
325 [ LTTNG_UST_SESSION_STOP ] = "Stop Session",
326
327 /* Channel FD commands */
328 [ LTTNG_UST_STREAM ] = "Create Stream",
329 [ LTTNG_UST_EVENT ] = "Create Event",
330
331 /* Event and Channel FD commands */
332 [ LTTNG_UST_CONTEXT ] = "Create Context",
333 [ LTTNG_UST_FLUSH_BUFFER ] = "Flush Buffer",
334
335 /* Event, Channel and Session commands */
336 [ LTTNG_UST_ENABLE ] = "Enable",
337 [ LTTNG_UST_DISABLE ] = "Disable",
338
339 /* Tracepoint list commands */
340 [ LTTNG_UST_TRACEPOINT_LIST_GET ] = "List Next Tracepoint",
341 [ LTTNG_UST_TRACEPOINT_FIELD_LIST_GET ] = "List Next Tracepoint Field",
342
343 /* Event FD commands */
344 [ LTTNG_UST_FILTER ] = "Create Filter",
75582b3a 345 [ LTTNG_UST_EXCLUSION ] = "Add exclusions to event",
74d81a6c
MD
346};
347
ff517991
MD
348static const char *str_timeout;
349static int got_timeout_env;
350
7dd08bec 351extern void lttng_ring_buffer_client_overwrite_init(void);
34a91bdb 352extern void lttng_ring_buffer_client_overwrite_rt_init(void);
7dd08bec 353extern void lttng_ring_buffer_client_discard_init(void);
34a91bdb 354extern void lttng_ring_buffer_client_discard_rt_init(void);
7dd08bec
MD
355extern void lttng_ring_buffer_metadata_client_init(void);
356extern void lttng_ring_buffer_client_overwrite_exit(void);
34a91bdb 357extern void lttng_ring_buffer_client_overwrite_rt_exit(void);
7dd08bec 358extern void lttng_ring_buffer_client_discard_exit(void);
34a91bdb 359extern void lttng_ring_buffer_client_discard_rt_exit(void);
7dd08bec 360extern void lttng_ring_buffer_metadata_client_exit(void);
edaa1431 361
060577e3
JR
362static char *get_map_shm(struct sock_info *sock_info);
363
405be658
MD
364ssize_t lttng_ust_read(int fd, void *buf, size_t len)
365{
366 ssize_t ret;
367 size_t copied = 0, to_copy = len;
368
369 do {
370 ret = read(fd, buf + copied, to_copy);
371 if (ret > 0) {
372 copied += ret;
373 to_copy -= ret;
374 }
375 } while ((ret > 0 && to_copy > 0)
376 || (ret < 0 && errno == EINTR));
377 if (ret > 0) {
378 ret = copied;
379 }
380 return ret;
381}
3c6f6263
AM
382/*
383 * Returns the HOME directory path. Caller MUST NOT free(3) the returned
384 * pointer.
385 */
386static
387const char *get_lttng_home_dir(void)
388{
389 const char *val;
390
6f626d28 391 val = (const char *) lttng_getenv("LTTNG_HOME");
3c6f6263
AM
392 if (val != NULL) {
393 return val;
394 }
6f626d28 395 return (const char *) lttng_getenv("HOME");
3c6f6263
AM
396}
397
a903623f
MD
398/*
399 * Force a read (imply TLS fixup for dlopen) of TLS variables.
400 */
401static
402void lttng_fixup_nest_count_tls(void)
403{
8c90a710 404 asm volatile ("" : : "m" (URCU_TLS(lttng_ust_nest_count)));
a903623f
MD
405}
406
d58d1454
MD
407static
408void lttng_fixup_ust_mutex_nest_tls(void)
409{
410 asm volatile ("" : : "m" (URCU_TLS(ust_mutex_nest)));
411}
412
1556a549
MD
413/*
414 * Fixup urcu bp TLS.
415 */
416static
417void lttng_fixup_urcu_bp_tls(void)
418{
419 rcu_read_lock();
420 rcu_read_unlock();
421}
422
c362addf
MD
423void lttng_ust_fixup_tls(void)
424{
425 lttng_fixup_urcu_bp_tls();
426 lttng_fixup_ringbuffer_tls();
427 lttng_fixup_vtid_tls();
428 lttng_fixup_nest_count_tls();
429 lttng_fixup_procname_tls();
430 lttng_fixup_ust_mutex_nest_tls();
20142124 431 lttng_ust_fixup_perf_counter_tls();
6548fca4 432 lttng_ust_fixup_fd_tracker_tls();
735bef47
MJ
433 lttng_fixup_cgroup_ns_tls();
434 lttng_fixup_ipc_ns_tls();
435 lttng_fixup_net_ns_tls();
436 lttng_fixup_uts_ns_tls();
c362addf
MD
437}
438
32ce8569
MD
439int lttng_get_notify_socket(void *owner)
440{
441 struct sock_info *info = owner;
442
443 return info->notify_socket;
444}
445
94be38e8
JR
446
447LTTNG_HIDDEN
448char* lttng_ust_sockinfo_get_procname(void *owner)
449{
450 struct sock_info *info = owner;
451
452 return info->procname;
453}
454
74d81a6c
MD
455static
456void print_cmd(int cmd, int handle)
457{
458 const char *cmd_name = "Unknown";
459
fd67a004
MD
460 if (cmd >= 0 && cmd < LTTNG_ARRAY_SIZE(cmd_name_mapping)
461 && cmd_name_mapping[cmd]) {
74d81a6c
MD
462 cmd_name = cmd_name_mapping[cmd];
463 }
fd67a004
MD
464 DBG("Message Received \"%s\" (%d), Handle \"%s\" (%d)",
465 cmd_name, cmd,
74d81a6c
MD
466 lttng_ust_obj_get_name(handle), handle);
467}
468
060577e3
JR
469static
470int setup_global_apps(void)
471{
472 int ret = 0;
473 assert(!global_apps.wait_shm_mmap);
474
475 global_apps.wait_shm_mmap = get_map_shm(&global_apps);
476 if (!global_apps.wait_shm_mmap) {
477 WARN("Unable to get map shm for global apps. Disabling LTTng-UST global tracing.");
478 global_apps.allowed = 0;
479 ret = -EIO;
480 goto error;
481 }
482
483 global_apps.allowed = 1;
94be38e8 484 lttng_ust_getprocname(global_apps.procname);
060577e3
JR
485error:
486 return ret;
487}
2691221a 488static
8d20bf54 489int setup_local_apps(void)
2691221a 490{
060577e3 491 int ret = 0;
2691221a 492 const char *home_dir;
7fc90dca 493 uid_t uid;
2691221a 494
060577e3
JR
495 assert(!local_apps.wait_shm_mmap);
496
7fc90dca 497 uid = getuid();
8d20bf54
MD
498 /*
499 * Disallow per-user tracing for setuid binaries.
500 */
7fc90dca 501 if (uid != geteuid()) {
9ec6895c 502 assert(local_apps.allowed == 0);
060577e3
JR
503 ret = 0;
504 goto end;
8d20bf54 505 }
3c6f6263 506 home_dir = get_lttng_home_dir();
9ec6895c
MD
507 if (!home_dir) {
508 WARN("HOME environment variable not set. Disabling LTTng-UST per-user tracing.");
509 assert(local_apps.allowed == 0);
060577e3
JR
510 ret = -ENOENT;
511 goto end;
9ec6895c
MD
512 }
513 local_apps.allowed = 1;
32ce8569
MD
514 snprintf(local_apps.sock_path, PATH_MAX, "%s/%s/%s",
515 home_dir,
516 LTTNG_DEFAULT_HOME_RUNDIR,
517 LTTNG_UST_SOCK_FILENAME);
518 snprintf(local_apps.wait_shm_path, PATH_MAX, "/%s-%u",
519 LTTNG_UST_WAIT_FILENAME,
520 uid);
060577e3
JR
521
522 local_apps.wait_shm_mmap = get_map_shm(&local_apps);
523 if (!local_apps.wait_shm_mmap) {
524 WARN("Unable to get map shm for local apps. Disabling LTTng-UST per-user tracing.");
525 local_apps.allowed = 0;
526 ret = -EIO;
527 goto end;
528 }
94be38e8
JR
529
530 lttng_ust_getprocname(local_apps.procname);
060577e3
JR
531end:
532 return ret;
2691221a
MD
533}
534
ff517991 535/*
451d66b2 536 * Get socket timeout, in ms.
28515902 537 * -1: wait forever. 0: don't wait. >0: timeout, in ms.
ff517991
MD
538 */
539static
540long get_timeout(void)
541{
542 long constructor_delay_ms = LTTNG_UST_DEFAULT_CONSTRUCTOR_TIMEOUT_MS;
543
544 if (!got_timeout_env) {
6f626d28 545 str_timeout = lttng_getenv("LTTNG_UST_REGISTER_TIMEOUT");
ff517991
MD
546 got_timeout_env = 1;
547 }
548 if (str_timeout)
549 constructor_delay_ms = strtol(str_timeout, NULL, 10);
5cf81d53
MD
550 /* All negative values are considered as "-1". */
551 if (constructor_delay_ms < -1)
552 constructor_delay_ms = -1;
ff517991
MD
553 return constructor_delay_ms;
554}
555
451d66b2 556/* Timeout for notify socket send and recv. */
ff517991
MD
557static
558long get_notify_sock_timeout(void)
559{
560 return get_timeout();
561}
562
451d66b2
MD
563/* Timeout for connecting to cmd and notify sockets. */
564static
565long get_connect_sock_timeout(void)
566{
567 return get_timeout();
568}
569
ff517991 570/*
28515902 571 * Return values: -1: wait forever. 0: don't wait. 1: timeout wait.
ff517991
MD
572 */
573static
574int get_constructor_timeout(struct timespec *constructor_timeout)
575{
576 long constructor_delay_ms;
577 int ret;
578
579 constructor_delay_ms = get_timeout();
580
581 switch (constructor_delay_ms) {
582 case -1:/* fall-through */
583 case 0:
584 return constructor_delay_ms;
585 default:
586 break;
587 }
588
589 /*
590 * If we are unable to find the current time, don't wait.
591 */
592 ret = clock_gettime(CLOCK_REALTIME, constructor_timeout);
593 if (ret) {
28515902
JG
594 /* Don't wait. */
595 return 0;
ff517991
MD
596 }
597 constructor_timeout->tv_sec += constructor_delay_ms / 1000UL;
598 constructor_timeout->tv_nsec +=
599 (constructor_delay_ms % 1000UL) * 1000000UL;
600 if (constructor_timeout->tv_nsec >= 1000000000UL) {
601 constructor_timeout->tv_sec++;
602 constructor_timeout->tv_nsec -= 1000000000UL;
603 }
28515902 604 /* Timeout wait (constructor_delay_ms). */
ff517991
MD
605 return 1;
606}
607
6f97f9c2 608static
b2c5f61a 609void get_allow_blocking(void)
6f97f9c2 610{
b2c5f61a
MD
611 const char *str_allow_blocking =
612 lttng_getenv("LTTNG_UST_ALLOW_BLOCKING");
613
614 if (str_allow_blocking) {
615 DBG("%s environment variable is set",
616 "LTTNG_UST_ALLOW_BLOCKING");
617 lttng_ust_ringbuffer_set_allow_blocking();
6f97f9c2
MD
618 }
619}
620
2691221a 621static
32ce8569 622int register_to_sessiond(int socket, enum ustctl_socket_type type)
2691221a 623{
32ce8569
MD
624 return ustcomm_send_reg_msg(socket,
625 type,
626 CAA_BITS_PER_LONG,
627 lttng_alignof(uint8_t) * CHAR_BIT,
628 lttng_alignof(uint16_t) * CHAR_BIT,
629 lttng_alignof(uint32_t) * CHAR_BIT,
630 lttng_alignof(uint64_t) * CHAR_BIT,
631 lttng_alignof(unsigned long) * CHAR_BIT);
2691221a
MD
632}
633
d9e99d10 634static
57773204 635int send_reply(int sock, struct ustcomm_ust_reply *lur)
d9e99d10 636{
9eb62b9c 637 ssize_t len;
d3a492d1 638
57773204 639 len = ustcomm_send_unix_sock(sock, lur, sizeof(*lur));
d3a492d1 640 switch (len) {
a4be8962 641 case sizeof(*lur):
d3a492d1
MD
642 DBG("message successfully sent");
643 return 0;
7bc53e94
MD
644 default:
645 if (len == -ECONNRESET) {
646 DBG("remote end closed connection");
d3a492d1
MD
647 return 0;
648 }
7bc53e94
MD
649 if (len < 0)
650 return len;
651 DBG("incorrect message size: %zd", len);
652 return -EINVAL;
d3a492d1
MD
653 }
654}
655
656static
eb0e6022 657void decrement_sem_count(unsigned int count)
11ff9c7d
MD
658{
659 int ret;
660
eb0e6022
GAPG
661 assert(uatomic_read(&sem_count) >= count);
662
56cd7e2f 663 if (uatomic_read(&sem_count) <= 0) {
eb0e6022 664 return;
56cd7e2f 665 }
eb0e6022
GAPG
666
667 ret = uatomic_add_return(&sem_count, -count);
95259bd0
MD
668 if (ret == 0) {
669 ret = sem_post(&constructor_wait);
670 assert(!ret);
671 }
eb0e6022
GAPG
672}
673
674static
675int handle_register_done(struct sock_info *sock_info)
676{
677 if (sock_info->registration_done)
678 return 0;
679 sock_info->registration_done = 1;
680
681 decrement_sem_count(1);
04682184
MD
682 if (!sock_info->statedump_pending) {
683 sock_info->initial_statedump_done = 1;
684 decrement_sem_count(1);
685 }
eb0e6022
GAPG
686
687 return 0;
688}
689
690static
691int handle_register_failed(struct sock_info *sock_info)
692{
693 if (sock_info->registration_done)
694 return 0;
695 sock_info->registration_done = 1;
696 sock_info->initial_statedump_done = 1;
697
698 decrement_sem_count(2);
699
11ff9c7d
MD
700 return 0;
701}
702
37dddb65
MD
703/*
704 * Only execute pending statedump after the constructor semaphore has
eb0e6022
GAPG
705 * been posted by the current listener thread. This means statedump will
706 * only be performed after the "registration done" command is received
707 * from this thread's session daemon.
37dddb65
MD
708 *
709 * This ensures we don't run into deadlock issues with the dynamic
710 * loader mutex, which is held while the constructor is called and
711 * waiting on the constructor semaphore. All operations requiring this
712 * dynamic loader lock need to be postponed using this mechanism.
eb0e6022
GAPG
713 *
714 * In a scenario with two session daemons connected to the application,
715 * it is possible that the first listener thread which receives the
716 * registration done command issues its statedump while the dynamic
717 * loader lock is still held by the application constructor waiting on
718 * the semaphore. It will however be allowed to proceed when the
719 * second session daemon sends the registration done command to the
720 * second listener thread. This situation therefore does not produce
721 * a deadlock.
37dddb65
MD
722 */
723static
724void handle_pending_statedump(struct sock_info *sock_info)
725{
eb0e6022 726 if (sock_info->registration_done && sock_info->statedump_pending) {
37dddb65 727 sock_info->statedump_pending = 0;
2932a87f 728 pthread_mutex_lock(&ust_fork_mutex);
37dddb65 729 lttng_handle_pending_statedump(sock_info);
458d678c 730 pthread_mutex_unlock(&ust_fork_mutex);
eb0e6022
GAPG
731
732 if (!sock_info->initial_statedump_done) {
733 sock_info->initial_statedump_done = 1;
734 decrement_sem_count(1);
735 }
37dddb65
MD
736 }
737}
738
11ff9c7d
MD
739static
740int handle_message(struct sock_info *sock_info,
57773204 741 int sock, struct ustcomm_ust_msg *lum)
d3a492d1 742{
1ea11eab 743 int ret = 0;
b61ce3b2 744 const struct lttng_ust_objd_ops *ops;
57773204 745 struct ustcomm_ust_reply lur;
ef9ff354 746 union ust_args args;
8e696cfa 747 char ctxstr[LTTNG_UST_SYM_NAME_LEN]; /* App context string. */
40003310 748 ssize_t len;
1ea11eab 749
46050b1a
MD
750 memset(&lur, 0, sizeof(lur));
751
3327ac33 752 if (ust_lock()) {
74d81a6c 753 ret = -LTTNG_UST_ERR_EXITING;
0dafcd63 754 goto error;
1ea11eab 755 }
9eb62b9c 756
46050b1a
MD
757 ops = objd_ops(lum->handle);
758 if (!ops) {
759 ret = -ENOENT;
0dafcd63 760 goto error;
1ea11eab 761 }
46050b1a
MD
762
763 switch (lum->cmd) {
11ff9c7d
MD
764 case LTTNG_UST_REGISTER_DONE:
765 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
edaa1431 766 ret = handle_register_done(sock_info);
11ff9c7d
MD
767 else
768 ret = -EINVAL;
769 break;
46050b1a
MD
770 case LTTNG_UST_RELEASE:
771 if (lum->handle == LTTNG_UST_ROOT_HANDLE)
772 ret = -EPERM;
773 else
1849ef7c 774 ret = lttng_ust_objd_unref(lum->handle, 1);
d9e99d10 775 break;
2d78951a
MD
776 case LTTNG_UST_FILTER:
777 {
778 /* Receive filter data */
f488575f 779 struct lttng_ust_filter_bytecode_node *bytecode;
2d78951a 780
cd54f6d9 781 if (lum->u.filter.data_size > FILTER_BYTECODE_MAX_LEN) {
7bc53e94 782 ERR("Filter data size is too large: %u bytes",
2d78951a
MD
783 lum->u.filter.data_size);
784 ret = -EINVAL;
785 goto error;
786 }
2734ca65 787
885b1dfd 788 if (lum->u.filter.reloc_offset > lum->u.filter.data_size) {
7bc53e94 789 ERR("Filter reloc offset %u is not within data",
2734ca65
CB
790 lum->u.filter.reloc_offset);
791 ret = -EINVAL;
792 goto error;
793 }
794
cd54f6d9
MD
795 bytecode = zmalloc(sizeof(*bytecode) + lum->u.filter.data_size);
796 if (!bytecode) {
797 ret = -ENOMEM;
798 goto error;
799 }
f488575f 800 len = ustcomm_recv_unix_sock(sock, bytecode->bc.data,
2d78951a
MD
801 lum->u.filter.data_size);
802 switch (len) {
803 case 0: /* orderly shutdown */
804 ret = 0;
cd54f6d9 805 free(bytecode);
2d78951a 806 goto error;
2d78951a
MD
807 default:
808 if (len == lum->u.filter.data_size) {
7bc53e94 809 DBG("filter data received");
2d78951a 810 break;
7bc53e94
MD
811 } else if (len < 0) {
812 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
813 if (len == -ECONNRESET) {
814 ERR("%s remote end closed connection", sock_info->name);
815 ret = len;
816 free(bytecode);
817 goto error;
818 }
819 ret = len;
eb8bf361 820 free(bytecode);
0dafcd63 821 goto error;
2d78951a 822 } else {
7bc53e94 823 DBG("incorrect filter data message size: %zd", len);
2d78951a 824 ret = -EINVAL;
cd54f6d9 825 free(bytecode);
0dafcd63 826 goto error;
2d78951a
MD
827 }
828 }
f488575f
MD
829 bytecode->bc.len = lum->u.filter.data_size;
830 bytecode->bc.reloc_offset = lum->u.filter.reloc_offset;
3f6fd224 831 bytecode->bc.seqnum = lum->u.filter.seqnum;
cd54f6d9 832 if (ops->cmd) {
2d78951a 833 ret = ops->cmd(lum->handle, lum->cmd,
cd54f6d9 834 (unsigned long) bytecode,
f59ed768 835 &args, sock_info);
cd54f6d9
MD
836 if (ret) {
837 free(bytecode);
838 }
839 /* don't free bytecode if everything went fine. */
840 } else {
2d78951a 841 ret = -ENOSYS;
cd54f6d9
MD
842 free(bytecode);
843 }
2d78951a
MD
844 break;
845 }
86e36163
JI
846 case LTTNG_UST_EXCLUSION:
847 {
848 /* Receive exclusion names */
849 struct lttng_ust_excluder_node *node;
850 unsigned int count;
851
852 count = lum->u.exclusion.count;
853 if (count == 0) {
854 /* There are no names to read */
855 ret = 0;
856 goto error;
857 }
858 node = zmalloc(sizeof(*node) +
859 count * LTTNG_UST_SYM_NAME_LEN);
860 if (!node) {
861 ret = -ENOMEM;
862 goto error;
863 }
864 node->excluder.count = count;
865 len = ustcomm_recv_unix_sock(sock, node->excluder.names,
866 count * LTTNG_UST_SYM_NAME_LEN);
867 switch (len) {
868 case 0: /* orderly shutdown */
869 ret = 0;
870 free(node);
871 goto error;
872 default:
873 if (len == count * LTTNG_UST_SYM_NAME_LEN) {
874 DBG("Exclusion data received");
875 break;
876 } else if (len < 0) {
877 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
878 if (len == -ECONNRESET) {
879 ERR("%s remote end closed connection", sock_info->name);
880 ret = len;
881 free(node);
882 goto error;
883 }
884 ret = len;
885 free(node);
0dafcd63 886 goto error;
86e36163
JI
887 } else {
888 DBG("Incorrect exclusion data message size: %zd", len);
889 ret = -EINVAL;
890 free(node);
0dafcd63 891 goto error;
86e36163
JI
892 }
893 }
894 if (ops->cmd) {
895 ret = ops->cmd(lum->handle, lum->cmd,
896 (unsigned long) node,
897 &args, sock_info);
898 if (ret) {
899 free(node);
900 }
901 /* Don't free exclusion data if everything went fine. */
902 } else {
903 ret = -ENOSYS;
904 free(node);
905 }
906 break;
907 }
74d81a6c
MD
908 case LTTNG_UST_CHANNEL:
909 {
910 void *chan_data;
ff0f5728 911 int wakeup_fd;
74d81a6c
MD
912
913 len = ustcomm_recv_channel_from_sessiond(sock,
ff0f5728
MD
914 &chan_data, lum->u.channel.len,
915 &wakeup_fd);
74d81a6c
MD
916 switch (len) {
917 case 0: /* orderly shutdown */
918 ret = 0;
919 goto error;
920 default:
921 if (len == lum->u.channel.len) {
922 DBG("channel data received");
923 break;
924 } else if (len < 0) {
925 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
926 if (len == -ECONNRESET) {
927 ERR("%s remote end closed connection", sock_info->name);
928 ret = len;
929 goto error;
930 }
931 ret = len;
0dafcd63 932 goto error;
74d81a6c
MD
933 } else {
934 DBG("incorrect channel data message size: %zd", len);
935 ret = -EINVAL;
0dafcd63 936 goto error;
74d81a6c
MD
937 }
938 }
939 args.channel.chan_data = chan_data;
ff0f5728 940 args.channel.wakeup_fd = wakeup_fd;
74d81a6c
MD
941 if (ops->cmd)
942 ret = ops->cmd(lum->handle, lum->cmd,
943 (unsigned long) &lum->u,
944 &args, sock_info);
945 else
946 ret = -ENOSYS;
947 break;
948 }
949 case LTTNG_UST_STREAM:
950 {
951 /* Receive shm_fd, wakeup_fd */
952 ret = ustcomm_recv_stream_from_sessiond(sock,
61e520fb 953 NULL,
74d81a6c
MD
954 &args.stream.shm_fd,
955 &args.stream.wakeup_fd);
956 if (ret) {
0dafcd63 957 goto error;
74d81a6c 958 }
973eac63 959
74d81a6c
MD
960 if (ops->cmd)
961 ret = ops->cmd(lum->handle, lum->cmd,
962 (unsigned long) &lum->u,
963 &args, sock_info);
964 else
965 ret = -ENOSYS;
966 break;
967 }
8e696cfa
MD
968 case LTTNG_UST_CONTEXT:
969 switch (lum->u.context.ctx) {
970 case LTTNG_UST_CONTEXT_APP_CONTEXT:
971 {
972 char *p;
973 size_t ctxlen, recvlen;
974
975 ctxlen = strlen("$app.") + lum->u.context.u.app_ctx.provider_name_len - 1
976 + strlen(":") + lum->u.context.u.app_ctx.ctx_name_len;
977 if (ctxlen >= LTTNG_UST_SYM_NAME_LEN) {
978 ERR("Application context string length size is too large: %zu bytes",
979 ctxlen);
980 ret = -EINVAL;
981 goto error;
982 }
983 strcpy(ctxstr, "$app.");
984 p = &ctxstr[strlen("$app.")];
985 recvlen = ctxlen - strlen("$app.");
986 len = ustcomm_recv_unix_sock(sock, p, recvlen);
987 switch (len) {
988 case 0: /* orderly shutdown */
989 ret = 0;
990 goto error;
991 default:
992 if (len == recvlen) {
993 DBG("app context data received");
994 break;
995 } else if (len < 0) {
996 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
997 if (len == -ECONNRESET) {
998 ERR("%s remote end closed connection", sock_info->name);
999 ret = len;
1000 goto error;
1001 }
1002 ret = len;
1003 goto error;
1004 } else {
1005 DBG("incorrect app context data message size: %zd", len);
1006 ret = -EINVAL;
1007 goto error;
1008 }
1009 }
1010 /* Put : between provider and ctxname. */
1011 p[lum->u.context.u.app_ctx.provider_name_len - 1] = ':';
1012 args.app_context.ctxname = ctxstr;
1013 break;
1014 }
1015 default:
1016 break;
1017 }
1018 if (ops->cmd) {
1019 ret = ops->cmd(lum->handle, lum->cmd,
1020 (unsigned long) &lum->u,
1021 &args, sock_info);
1022 } else {
1023 ret = -ENOSYS;
1024 }
1025 break;
d9e99d10 1026 default:
46050b1a
MD
1027 if (ops->cmd)
1028 ret = ops->cmd(lum->handle, lum->cmd,
ef9ff354 1029 (unsigned long) &lum->u,
f59ed768 1030 &args, sock_info);
46050b1a
MD
1031 else
1032 ret = -ENOSYS;
1033 break;
d9e99d10 1034 }
46050b1a 1035
46050b1a
MD
1036 lur.handle = lum->handle;
1037 lur.cmd = lum->cmd;
1038 lur.ret_val = ret;
1039 if (ret >= 0) {
7bc53e94 1040 lur.ret_code = LTTNG_UST_OK;
46050b1a 1041 } else {
7bc53e94
MD
1042 /*
1043 * Use -LTTNG_UST_ERR as wildcard for UST internal
1044 * error that are not caused by the transport, except if
1045 * we already have a more precise error message to
1046 * report.
1047 */
64b2564e
DG
1048 if (ret > -LTTNG_UST_ERR) {
1049 /* Translate code to UST error. */
1050 switch (ret) {
1051 case -EEXIST:
1052 lur.ret_code = -LTTNG_UST_ERR_EXIST;
1053 break;
1054 case -EINVAL:
1055 lur.ret_code = -LTTNG_UST_ERR_INVAL;
1056 break;
1057 case -ENOENT:
1058 lur.ret_code = -LTTNG_UST_ERR_NOENT;
1059 break;
1060 case -EPERM:
1061 lur.ret_code = -LTTNG_UST_ERR_PERM;
1062 break;
1063 case -ENOSYS:
1064 lur.ret_code = -LTTNG_UST_ERR_NOSYS;
1065 break;
1066 default:
1067 lur.ret_code = -LTTNG_UST_ERR;
1068 break;
1069 }
1070 } else {
7bc53e94 1071 lur.ret_code = ret;
64b2564e 1072 }
46050b1a 1073 }
e6ea14c5
MD
1074 if (ret >= 0) {
1075 switch (lum->cmd) {
e6ea14c5
MD
1076 case LTTNG_UST_TRACER_VERSION:
1077 lur.u.version = lum->u.version;
1078 break;
1079 case LTTNG_UST_TRACEPOINT_LIST_GET:
1080 memcpy(&lur.u.tracepoint, &lum->u.tracepoint, sizeof(lur.u.tracepoint));
1081 break;
1082 }
381c0f1e 1083 }
74d81a6c 1084 DBG("Return value: %d", lur.ret_val);
4c62d8d1
MD
1085
1086 ust_unlock();
1087
1088 /*
1089 * Performed delayed statedump operations outside of the UST
1090 * lock. We need to take the dynamic loader lock before we take
1091 * the UST lock internally within handle_pending_statedump().
1092 */
1093 handle_pending_statedump(sock_info);
1094
1095 if (ust_lock()) {
1096 ret = -LTTNG_UST_ERR_EXITING;
1097 goto error;
1098 }
1099
46050b1a 1100 ret = send_reply(sock, &lur);
193183fb 1101 if (ret < 0) {
7bc53e94 1102 DBG("error sending reply");
193183fb
MD
1103 goto error;
1104 }
46050b1a 1105
40003310
MD
1106 /*
1107 * LTTNG_UST_TRACEPOINT_FIELD_LIST_GET needs to send the field
1108 * after the reply.
1109 */
7bc53e94 1110 if (lur.ret_code == LTTNG_UST_OK) {
40003310
MD
1111 switch (lum->cmd) {
1112 case LTTNG_UST_TRACEPOINT_FIELD_LIST_GET:
1113 len = ustcomm_send_unix_sock(sock,
1114 &args.field_list.entry,
1115 sizeof(args.field_list.entry));
7bc53e94
MD
1116 if (len < 0) {
1117 ret = len;
1118 goto error;
1119 }
40003310 1120 if (len != sizeof(args.field_list.entry)) {
7bc53e94 1121 ret = -EINVAL;
40003310
MD
1122 goto error;
1123 }
1124 }
1125 }
ef9ff354 1126
381c0f1e 1127error:
17dfb34b 1128 ust_unlock();
d9e99d10 1129
37dddb65 1130 return ret;
246be17e
PW
1131}
1132
46050b1a 1133static
efe0de09 1134void cleanup_sock_info(struct sock_info *sock_info, int exiting)
46050b1a
MD
1135{
1136 int ret;
1137
5b14aab3
MD
1138 if (sock_info->root_handle != -1) {
1139 ret = lttng_ust_objd_unref(sock_info->root_handle, 1);
1140 if (ret) {
1141 ERR("Error unref root handle");
1142 }
1143 sock_info->root_handle = -1;
1144 }
eb0e6022
GAPG
1145 sock_info->registration_done = 0;
1146 sock_info->initial_statedump_done = 0;
5b14aab3
MD
1147
1148 /*
1149 * wait_shm_mmap, socket and notify socket are used by listener
1150 * threads outside of the ust lock, so we cannot tear them down
1151 * ourselves, because we cannot join on these threads. Leave
1152 * responsibility of cleaning up these resources to the OS
1153 * process exit.
1154 */
1155 if (exiting)
1156 return;
1157
46050b1a 1158 if (sock_info->socket != -1) {
e6973a89 1159 ret = ustcomm_close_unix_sock(sock_info->socket);
46050b1a 1160 if (ret) {
32ce8569 1161 ERR("Error closing ust cmd socket");
46050b1a
MD
1162 }
1163 sock_info->socket = -1;
1164 }
32ce8569
MD
1165 if (sock_info->notify_socket != -1) {
1166 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1167 if (ret) {
1168 ERR("Error closing ust notify socket");
1169 }
1170 sock_info->notify_socket = -1;
1171 }
5b14aab3 1172 if (sock_info->wait_shm_mmap) {
172d6b68
MD
1173 long page_size;
1174
1175 page_size = sysconf(_SC_PAGE_SIZE);
2657d1ba
MD
1176 if (page_size <= 0) {
1177 if (!page_size) {
1178 errno = EINVAL;
1179 }
1180 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
1181 } else {
172d6b68
MD
1182 ret = munmap(sock_info->wait_shm_mmap, page_size);
1183 if (ret) {
1184 ERR("Error unmapping wait shm");
1185 }
7fc90dca
MD
1186 }
1187 sock_info->wait_shm_mmap = NULL;
1188 }
1189}
1190
58d4b2a2 1191/*
33bbeb90
MD
1192 * Using fork to set umask in the child process (not multi-thread safe).
1193 * We deal with the shm_open vs ftruncate race (happening when the
1194 * sessiond owns the shm and does not let everybody modify it, to ensure
1195 * safety against shm_unlink) by simply letting the mmap fail and
1196 * retrying after a few seconds.
1197 * For global shm, everybody has rw access to it until the sessiond
1198 * starts.
58d4b2a2 1199 */
7fc90dca 1200static
58d4b2a2 1201int get_wait_shm(struct sock_info *sock_info, size_t mmap_size)
7fc90dca 1202{
7fc90dca 1203 int wait_shm_fd, ret;
58d4b2a2 1204 pid_t pid;
44e073f5 1205
58d4b2a2 1206 /*
33bbeb90 1207 * Try to open read-only.
58d4b2a2 1208 */
33bbeb90 1209 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
58d4b2a2 1210 if (wait_shm_fd >= 0) {
7aa76730
MD
1211 int32_t tmp_read;
1212 ssize_t len;
1213 size_t bytes_read = 0;
1214
1215 /*
1216 * Try to read the fd. If unable to do so, try opening
1217 * it in write mode.
1218 */
1219 do {
1220 len = read(wait_shm_fd,
1221 &((char *) &tmp_read)[bytes_read],
1222 sizeof(tmp_read) - bytes_read);
1223 if (len > 0) {
1224 bytes_read += len;
1225 }
1226 } while ((len < 0 && errno == EINTR)
1227 || (len > 0 && bytes_read < sizeof(tmp_read)));
1228 if (bytes_read != sizeof(tmp_read)) {
1229 ret = close(wait_shm_fd);
1230 if (ret) {
1231 ERR("close wait_shm_fd");
1232 }
1233 goto open_write;
1234 }
58d4b2a2
MD
1235 goto end;
1236 } else if (wait_shm_fd < 0 && errno != ENOENT) {
1237 /*
33bbeb90
MD
1238 * Real-only open did not work, and it's not because the
1239 * entry was not present. It's a failure that prohibits
1240 * using shm.
58d4b2a2 1241 */
7fc90dca 1242 ERR("Error opening shm %s", sock_info->wait_shm_path);
58d4b2a2 1243 goto end;
7fc90dca 1244 }
7aa76730
MD
1245
1246open_write:
7fc90dca 1247 /*
7aa76730
MD
1248 * If the open failed because the file did not exist, or because
1249 * the file was not truncated yet, try creating it ourself.
7fc90dca 1250 */
8c90a710 1251 URCU_TLS(lttng_ust_nest_count)++;
58d4b2a2 1252 pid = fork();
8c90a710 1253 URCU_TLS(lttng_ust_nest_count)--;
58d4b2a2
MD
1254 if (pid > 0) {
1255 int status;
1256
1257 /*
1258 * Parent: wait for child to return, in which case the
1259 * shared memory map will have been created.
1260 */
1261 pid = wait(&status);
b7d3cb32 1262 if (pid < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
58d4b2a2
MD
1263 wait_shm_fd = -1;
1264 goto end;
7fc90dca 1265 }
58d4b2a2
MD
1266 /*
1267 * Try to open read-only again after creation.
1268 */
33bbeb90 1269 wait_shm_fd = shm_open(sock_info->wait_shm_path, O_RDONLY, 0);
58d4b2a2
MD
1270 if (wait_shm_fd < 0) {
1271 /*
1272 * Real-only open did not work. It's a failure
1273 * that prohibits using shm.
1274 */
1275 ERR("Error opening shm %s", sock_info->wait_shm_path);
1276 goto end;
1277 }
1278 goto end;
1279 } else if (pid == 0) {
1280 int create_mode;
1281
1282 /* Child */
33bbeb90 1283 create_mode = S_IRUSR | S_IWUSR | S_IRGRP;
58d4b2a2 1284 if (sock_info->global)
33bbeb90 1285 create_mode |= S_IROTH | S_IWGRP | S_IWOTH;
58d4b2a2
MD
1286 /*
1287 * We're alone in a child process, so we can modify the
1288 * process-wide umask.
1289 */
33bbeb90 1290 umask(~create_mode);
58d4b2a2 1291 /*
33bbeb90
MD
1292 * Try creating shm (or get rw access).
1293 * We don't do an exclusive open, because we allow other
1294 * processes to create+ftruncate it concurrently.
58d4b2a2
MD
1295 */
1296 wait_shm_fd = shm_open(sock_info->wait_shm_path,
1297 O_RDWR | O_CREAT, create_mode);
1298 if (wait_shm_fd >= 0) {
1299 ret = ftruncate(wait_shm_fd, mmap_size);
1300 if (ret) {
1301 PERROR("ftruncate");
b0c1425d 1302 _exit(EXIT_FAILURE);
58d4b2a2 1303 }
b0c1425d 1304 _exit(EXIT_SUCCESS);
58d4b2a2 1305 }
33bbeb90
MD
1306 /*
1307 * For local shm, we need to have rw access to accept
1308 * opening it: this means the local sessiond will be
1309 * able to wake us up. For global shm, we open it even
1310 * if rw access is not granted, because the root.root
1311 * sessiond will be able to override all rights and wake
1312 * us up.
1313 */
1314 if (!sock_info->global && errno != EACCES) {
58d4b2a2 1315 ERR("Error opening shm %s", sock_info->wait_shm_path);
5d3bc5ed 1316 _exit(EXIT_FAILURE);
58d4b2a2
MD
1317 }
1318 /*
33bbeb90
MD
1319 * The shm exists, but we cannot open it RW. Report
1320 * success.
58d4b2a2 1321 */
5d3bc5ed 1322 _exit(EXIT_SUCCESS);
58d4b2a2
MD
1323 } else {
1324 return -1;
7fc90dca 1325 }
58d4b2a2 1326end:
33bbeb90
MD
1327 if (wait_shm_fd >= 0 && !sock_info->global) {
1328 struct stat statbuf;
1329
1330 /*
1331 * Ensure that our user is the owner of the shm file for
1332 * local shm. If we do not own the file, it means our
1333 * sessiond will not have access to wake us up (there is
1334 * probably a rogue process trying to fake our
1335 * sessiond). Fallback to polling method in this case.
1336 */
1337 ret = fstat(wait_shm_fd, &statbuf);
1338 if (ret) {
1339 PERROR("fstat");
1340 goto error_close;
1341 }
1342 if (statbuf.st_uid != getuid())
1343 goto error_close;
1344 }
58d4b2a2 1345 return wait_shm_fd;
33bbeb90
MD
1346
1347error_close:
1348 ret = close(wait_shm_fd);
1349 if (ret) {
1350 PERROR("Error closing fd");
1351 }
1352 return -1;
58d4b2a2
MD
1353}
1354
1355static
1356char *get_map_shm(struct sock_info *sock_info)
1357{
172d6b68 1358 long page_size;
58d4b2a2
MD
1359 int wait_shm_fd, ret;
1360 char *wait_shm_mmap;
1361
172d6b68 1362 page_size = sysconf(_SC_PAGE_SIZE);
2657d1ba
MD
1363 if (page_size <= 0) {
1364 if (!page_size) {
1365 errno = EINVAL;
1366 }
1367 PERROR("Error in sysconf(_SC_PAGE_SIZE)");
172d6b68
MD
1368 goto error;
1369 }
1370
6548fca4 1371 lttng_ust_lock_fd_tracker();
172d6b68 1372 wait_shm_fd = get_wait_shm(sock_info, page_size);
58d4b2a2 1373 if (wait_shm_fd < 0) {
6548fca4 1374 lttng_ust_unlock_fd_tracker();
58d4b2a2 1375 goto error;
44e073f5 1376 }
f5c453e9
JR
1377
1378 ret = lttng_ust_add_fd_to_tracker(wait_shm_fd);
1379 if (ret < 0) {
1380 ret = close(wait_shm_fd);
1381 if (!ret) {
1382 PERROR("Error closing fd");
1383 }
1384 lttng_ust_unlock_fd_tracker();
1385 goto error;
1386 }
1387
1388 wait_shm_fd = ret;
6548fca4
MD
1389 lttng_ust_unlock_fd_tracker();
1390
172d6b68 1391 wait_shm_mmap = mmap(NULL, page_size, PROT_READ,
7fc90dca 1392 MAP_SHARED, wait_shm_fd, 0);
6548fca4 1393
7fc90dca 1394 /* close shm fd immediately after taking the mmap reference */
6548fca4 1395 lttng_ust_lock_fd_tracker();
7fc90dca 1396 ret = close(wait_shm_fd);
6548fca4
MD
1397 if (!ret) {
1398 lttng_ust_delete_fd_from_tracker(wait_shm_fd);
1399 } else {
33bbeb90
MD
1400 PERROR("Error closing fd");
1401 }
6548fca4
MD
1402 lttng_ust_unlock_fd_tracker();
1403
33bbeb90
MD
1404 if (wait_shm_mmap == MAP_FAILED) {
1405 DBG("mmap error (can be caused by race with sessiond). Fallback to poll mode.");
1406 goto error;
7fc90dca
MD
1407 }
1408 return wait_shm_mmap;
1409
1410error:
1411 return NULL;
1412}
1413
1414static
1415void wait_for_sessiond(struct sock_info *sock_info)
1416{
060577e3 1417 /* Use ust_lock to check if we should quit. */
3327ac33 1418 if (ust_lock()) {
7fc90dca
MD
1419 goto quit;
1420 }
37ed587a
MD
1421 if (wait_poll_fallback) {
1422 goto error;
1423 }
7fc90dca
MD
1424 ust_unlock();
1425
060577e3
JR
1426 assert(sock_info->wait_shm_mmap);
1427
7fc90dca 1428 DBG("Waiting for %s apps sessiond", sock_info->name);
80e2814b 1429 /* Wait for futex wakeup */
ee7fcec8
MD
1430 if (uatomic_read((int32_t *) sock_info->wait_shm_mmap))
1431 goto end_wait;
1432
1433 while (futex_async((int32_t *) sock_info->wait_shm_mmap,
1434 FUTEX_WAIT, 0, NULL, NULL, 0)) {
1435 switch (errno) {
1436 case EWOULDBLOCK:
1437 /* Value already changed. */
1438 goto end_wait;
1439 case EINTR:
1440 /* Retry if interrupted by signal. */
1441 break; /* Get out of switch. */
1442 case EFAULT:
1443 wait_poll_fallback = 1;
1444 DBG(
37ed587a
MD
1445"Linux kernels 2.6.33 to 3.0 (with the exception of stable versions) "
1446"do not support FUTEX_WAKE on read-only memory mappings correctly. "
1447"Please upgrade your kernel "
1448"(fix is commit 9ea71503a8ed9184d2d0b8ccc4d269d05f7940ae in Linux kernel "
1449"mainline). LTTng-UST will use polling mode fallback.");
ee7fcec8
MD
1450 if (ust_debug())
1451 PERROR("futex");
1452 goto end_wait;
80e2814b
MD
1453 }
1454 }
ee7fcec8 1455end_wait:
7fc90dca
MD
1456 return;
1457
1458quit:
1459 ust_unlock();
1460 return;
1461
1462error:
1463 ust_unlock();
7fc90dca 1464 return;
46050b1a
MD
1465}
1466
1ea11eab
MD
1467/*
1468 * This thread does not allocate any resource, except within
1469 * handle_message, within mutex protection. This mutex protects against
1470 * fork and exit.
98bf993f 1471 * The other moment it allocates resources is at socket connection, which
1ea11eab
MD
1472 * is also protected by the mutex.
1473 */
d9e99d10
MD
1474static
1475void *ust_listener_thread(void *arg)
1476{
1ea11eab 1477 struct sock_info *sock_info = arg;
f5c453e9 1478 int sock, ret, prev_connect_failed = 0, has_waited = 0, fd;
ff517991 1479 long timeout;
d9e99d10 1480
c362addf 1481 lttng_ust_fixup_tls();
01f0e40c
RB
1482 /*
1483 * If available, add '-ust' to the end of this thread's
1484 * process name
1485 */
1486 ret = lttng_ust_setustprocname();
1487 if (ret) {
1488 ERR("Unable to set UST process name");
1489 }
1490
9eb62b9c
MD
1491 /* Restart trying to connect to the session daemon */
1492restart:
c0eedf81
MD
1493 if (prev_connect_failed) {
1494 /* Wait for sessiond availability with pipe */
1495 wait_for_sessiond(sock_info);
1496 if (has_waited) {
1497 has_waited = 0;
1498 /*
1499 * Sleep for 5 seconds before retrying after a
1500 * sequence of failure / wait / failure. This
1501 * deals with a killed or broken session daemon.
1502 */
1503 sleep(5);
eacc4aa4
MD
1504 } else {
1505 has_waited = 1;
c0eedf81 1506 }
c0eedf81
MD
1507 prev_connect_failed = 0;
1508 }
9eb62b9c 1509
101dace0
JR
1510 if (ust_lock()) {
1511 goto quit;
1512 }
1513
1ea11eab 1514 if (sock_info->socket != -1) {
6548fca4 1515 /* FD tracker is updated by ustcomm_close_unix_sock() */
e6973a89 1516 ret = ustcomm_close_unix_sock(sock_info->socket);
1ea11eab 1517 if (ret) {
32ce8569
MD
1518 ERR("Error closing %s ust cmd socket",
1519 sock_info->name);
1ea11eab
MD
1520 }
1521 sock_info->socket = -1;
1522 }
32ce8569 1523 if (sock_info->notify_socket != -1) {
6548fca4 1524 /* FD tracker is updated by ustcomm_close_unix_sock() */
32ce8569
MD
1525 ret = ustcomm_close_unix_sock(sock_info->notify_socket);
1526 if (ret) {
1527 ERR("Error closing %s ust notify socket",
1528 sock_info->name);
1529 }
1530 sock_info->notify_socket = -1;
1531 }
46050b1a 1532
6548fca4 1533
321f2351
MD
1534 /*
1535 * Register. We need to perform both connect and sending
1536 * registration message before doing the next connect otherwise
1537 * we may reach unix socket connect queue max limits and block
1538 * on the 2nd connect while the session daemon is awaiting the
1539 * first connect registration message.
1540 */
1541 /* Connect cmd socket */
6548fca4 1542 lttng_ust_lock_fd_tracker();
451d66b2
MD
1543 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1544 get_connect_sock_timeout());
321f2351 1545 if (ret < 0) {
6548fca4 1546 lttng_ust_unlock_fd_tracker();
321f2351
MD
1547 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1548 prev_connect_failed = 1;
5b14aab3 1549
e3426ddc 1550 /*
321f2351
MD
1551 * If we cannot find the sessiond daemon, don't delay
1552 * constructor execution.
e3426ddc 1553 */
eb0e6022 1554 ret = handle_register_failed(sock_info);
321f2351
MD
1555 assert(!ret);
1556 ust_unlock();
1557 goto restart;
27fe9f21 1558 }
f5c453e9
JR
1559 fd = ret;
1560 ret = lttng_ust_add_fd_to_tracker(fd);
1561 if (ret < 0) {
1562 ret = close(fd);
1563 if (ret) {
1564 PERROR("close on sock_info->socket");
1565 }
1566 ret = -1;
1567 lttng_ust_unlock_fd_tracker();
1568 ust_unlock();
1569 goto quit;
1570 }
1571
321f2351 1572 sock_info->socket = ret;
f5c453e9 1573 lttng_ust_unlock_fd_tracker();
27fe9f21 1574
6548fca4
MD
1575 ust_unlock();
1576 /*
1577 * Unlock/relock ust lock because connect is blocking (with
1578 * timeout). Don't delay constructors on the ust lock for too
1579 * long.
1580 */
3327ac33 1581 if (ust_lock()) {
5b14aab3
MD
1582 goto quit;
1583 }
1584
46050b1a
MD
1585 /*
1586 * Create only one root handle per listener thread for the whole
f59ed768
MD
1587 * process lifetime, so we ensure we get ID which is statically
1588 * assigned to the root handle.
46050b1a
MD
1589 */
1590 if (sock_info->root_handle == -1) {
1591 ret = lttng_abi_create_root_handle();
a51070bb 1592 if (ret < 0) {
46050b1a 1593 ERR("Error creating root handle");
46050b1a
MD
1594 goto quit;
1595 }
1596 sock_info->root_handle = ret;
9eb62b9c 1597 }
1ea11eab 1598
32ce8569 1599 ret = register_to_sessiond(sock_info->socket, USTCTL_SOCKET_CMD);
9eb62b9c 1600 if (ret < 0) {
32ce8569
MD
1601 ERR("Error registering to %s ust cmd socket",
1602 sock_info->name);
c0eedf81 1603 prev_connect_failed = 1;
11ff9c7d
MD
1604 /*
1605 * If we cannot register to the sessiond daemon, don't
1606 * delay constructor execution.
1607 */
eb0e6022 1608 ret = handle_register_failed(sock_info);
11ff9c7d 1609 assert(!ret);
17dfb34b 1610 ust_unlock();
9eb62b9c
MD
1611 goto restart;
1612 }
321f2351
MD
1613
1614 ust_unlock();
6548fca4
MD
1615 /*
1616 * Unlock/relock ust lock because connect is blocking (with
1617 * timeout). Don't delay constructors on the ust lock for too
1618 * long.
1619 */
1620 if (ust_lock()) {
1621 goto quit;
1622 }
321f2351
MD
1623
1624 /* Connect notify socket */
6548fca4 1625 lttng_ust_lock_fd_tracker();
451d66b2
MD
1626 ret = ustcomm_connect_unix_sock(sock_info->sock_path,
1627 get_connect_sock_timeout());
321f2351 1628 if (ret < 0) {
6548fca4 1629 lttng_ust_unlock_fd_tracker();
321f2351
MD
1630 DBG("Info: sessiond not accepting connections to %s apps socket", sock_info->name);
1631 prev_connect_failed = 1;
1632
321f2351
MD
1633 /*
1634 * If we cannot find the sessiond daemon, don't delay
1635 * constructor execution.
1636 */
eb0e6022 1637 ret = handle_register_failed(sock_info);
321f2351
MD
1638 assert(!ret);
1639 ust_unlock();
1640 goto restart;
1641 }
f5c453e9
JR
1642
1643 fd = ret;
1644 ret = lttng_ust_add_fd_to_tracker(fd);
1645 if (ret < 0) {
1646 ret = close(fd);
1647 if (ret) {
1648 PERROR("close on sock_info->notify_socket");
1649 }
1650 ret = -1;
1651 lttng_ust_unlock_fd_tracker();
1652 ust_unlock();
1653 goto quit;
1654 }
1655
321f2351 1656 sock_info->notify_socket = ret;
f5c453e9 1657 lttng_ust_unlock_fd_tracker();
321f2351 1658
6548fca4
MD
1659 ust_unlock();
1660 /*
1661 * Unlock/relock ust lock because connect is blocking (with
1662 * timeout). Don't delay constructors on the ust lock for too
1663 * long.
1664 */
1665 if (ust_lock()) {
1666 goto quit;
1667 }
1668
321f2351
MD
1669 timeout = get_notify_sock_timeout();
1670 if (timeout >= 0) {
1671 /*
1672 * Give at least 10ms to sessiond to reply to
1673 * notifications.
1674 */
1675 if (timeout < 10)
1676 timeout = 10;
1677 ret = ustcomm_setsockopt_rcv_timeout(sock_info->notify_socket,
1678 timeout);
1679 if (ret < 0) {
1680 WARN("Error setting socket receive timeout");
1681 }
1682 ret = ustcomm_setsockopt_snd_timeout(sock_info->notify_socket,
1683 timeout);
1684 if (ret < 0) {
1685 WARN("Error setting socket send timeout");
1686 }
1687 } else if (timeout < -1) {
1688 WARN("Unsupported timeout value %ld", timeout);
1689 }
1690
32ce8569
MD
1691 ret = register_to_sessiond(sock_info->notify_socket,
1692 USTCTL_SOCKET_NOTIFY);
1693 if (ret < 0) {
1694 ERR("Error registering to %s ust notify socket",
1695 sock_info->name);
1696 prev_connect_failed = 1;
1697 /*
1698 * If we cannot register to the sessiond daemon, don't
1699 * delay constructor execution.
1700 */
eb0e6022 1701 ret = handle_register_failed(sock_info);
32ce8569
MD
1702 assert(!ret);
1703 ust_unlock();
1704 goto restart;
1705 }
1706 sock = sock_info->socket;
1707
17dfb34b 1708 ust_unlock();
46050b1a 1709
d9e99d10
MD
1710 for (;;) {
1711 ssize_t len;
57773204 1712 struct ustcomm_ust_msg lum;
d9e99d10 1713
57773204 1714 len = ustcomm_recv_unix_sock(sock, &lum, sizeof(lum));
d9e99d10
MD
1715 switch (len) {
1716 case 0: /* orderly shutdown */
7dd08bec 1717 DBG("%s lttng-sessiond has performed an orderly shutdown", sock_info->name);
3327ac33 1718 if (ust_lock()) {
d5e1fea6
MD
1719 goto quit;
1720 }
8236ba10
MD
1721 /*
1722 * Either sessiond has shutdown or refused us by closing the socket.
1723 * In either case, we don't want to delay construction execution,
1724 * and we need to wait before retry.
1725 */
1726 prev_connect_failed = 1;
1727 /*
1728 * If we cannot register to the sessiond daemon, don't
1729 * delay constructor execution.
1730 */
eb0e6022 1731 ret = handle_register_failed(sock_info);
8236ba10
MD
1732 assert(!ret);
1733 ust_unlock();
d9e99d10 1734 goto end;
e7723462 1735 case sizeof(lum):
74d81a6c 1736 print_cmd(lum.cmd, lum.handle);
11ff9c7d 1737 ret = handle_message(sock_info, sock, &lum);
7bc53e94 1738 if (ret) {
0dafcd63
MD
1739 ERR("Error handling message for %s socket",
1740 sock_info->name);
1741 /*
1742 * Close socket if protocol error is
1743 * detected.
1744 */
1745 goto end;
d9e99d10
MD
1746 }
1747 continue;
7bc53e94
MD
1748 default:
1749 if (len < 0) {
1750 DBG("Receive failed from lttng-sessiond with errno %d", (int) -len);
1751 } else {
1752 DBG("incorrect message size (%s socket): %zd", sock_info->name, len);
1753 }
1754 if (len == -ECONNRESET) {
1755 DBG("%s remote end closed connection", sock_info->name);
d9e99d10
MD
1756 goto end;
1757 }
1758 goto end;
d9e99d10
MD
1759 }
1760
1761 }
1762end:
3327ac33 1763 if (ust_lock()) {
d5e1fea6
MD
1764 goto quit;
1765 }
f59ed768
MD
1766 /* Cleanup socket handles before trying to reconnect */
1767 lttng_ust_objd_table_owner_cleanup(sock_info);
1768 ust_unlock();
9eb62b9c 1769 goto restart; /* try to reconnect */
e33f3265 1770
1ea11eab 1771quit:
e33f3265 1772 ust_unlock();
3327ac33
MD
1773
1774 pthread_mutex_lock(&ust_exit_mutex);
1775 sock_info->thread_active = 0;
1776 pthread_mutex_unlock(&ust_exit_mutex);
d9e99d10
MD
1777 return NULL;
1778}
1779
2594a5b4
MD
1780/*
1781 * Weak symbol to call when the ust malloc wrapper is not loaded.
1782 */
1783__attribute__((weak))
1784void lttng_ust_malloc_wrapper_init(void)
1785{
1786}
1787
2691221a
MD
1788/*
1789 * sessiond monitoring thread: monitor presence of global and per-user
1790 * sessiond by polling the application common named pipe.
1791 */
edaa1431 1792void __attribute__((constructor)) lttng_ust_init(void)
2691221a 1793{
11ff9c7d 1794 struct timespec constructor_timeout;
ae6a58bf 1795 sigset_t sig_all_blocked, orig_parent_mask;
1879f67f 1796 pthread_attr_t thread_attr;
cf12a773 1797 int timeout_mode;
2691221a 1798 int ret;
b2292d85 1799 void *handle;
2691221a 1800
edaa1431
MD
1801 if (uatomic_xchg(&initialized, 1) == 1)
1802 return;
1803
eddd8d5d
MD
1804 /*
1805 * Fixup interdependency between TLS fixup mutex (which happens
1806 * to be the dynamic linker mutex) and ust_lock, taken within
1807 * the ust lock.
1808 */
c362addf 1809 lttng_ust_fixup_tls();
eddd8d5d 1810
07b57e5e
MD
1811 lttng_ust_loaded = 1;
1812
b2292d85
FD
1813 /*
1814 * We need to ensure that the liblttng-ust library is not unloaded to avoid
1815 * the unloading of code used by the ust_listener_threads as we can not
1816 * reliably know when they exited. To do that, manually load
1817 * liblttng-ust.so to increment the dynamic loader's internal refcount for
1818 * this library so it never becomes zero, thus never gets unloaded from the
1819 * address space of the process. Since we are already running in the
1820 * constructor of the LTTNG_UST_LIB_SO_NAME library, calling dlopen will
1821 * simply increment the refcount and no additionnal work is needed by the
1822 * dynamic loader as the shared library is already loaded in the address
1823 * space. As a safe guard, we use the RTLD_NODELETE flag to prevent
1824 * unloading of the UST library if its refcount becomes zero (which should
1825 * never happen). Do the return value check but discard the handle at the
1826 * end of the function as it's not needed.
1827 */
1828 handle = dlopen(LTTNG_UST_LIB_SO_NAME, RTLD_LAZY | RTLD_NODELETE);
1829 if (!handle) {
1830 ERR("dlopen of liblttng-ust shared library (%s).", LTTNG_UST_LIB_SO_NAME);
1831 }
1832
edaa1431
MD
1833 /*
1834 * We want precise control over the order in which we construct
1835 * our sub-libraries vs starting to receive commands from
1836 * sessiond (otherwise leading to errors when trying to create
1837 * sessiond before the init functions are completed).
1838 */
2691221a 1839 init_usterr();
6f626d28 1840 lttng_ust_getenv_init(); /* Needs init_usterr() to be completed. */
edaa1431 1841 init_tracepoint();
6548fca4 1842 lttng_ust_init_fd_tracker();
f9364363 1843 lttng_ust_clock_init();
5e1b7b8b 1844 lttng_ust_getcpu_init();
cf73e0fe 1845 lttng_ust_statedump_init();
7dd08bec
MD
1846 lttng_ring_buffer_metadata_client_init();
1847 lttng_ring_buffer_client_overwrite_init();
34a91bdb 1848 lttng_ring_buffer_client_overwrite_rt_init();
7dd08bec 1849 lttng_ring_buffer_client_discard_init();
34a91bdb 1850 lttng_ring_buffer_client_discard_rt_init();
d58d1454 1851 lttng_perf_counter_init();
2594a5b4
MD
1852 /*
1853 * Invoke ust malloc wrapper init before starting other threads.
1854 */
1855 lttng_ust_malloc_wrapper_init();
2691221a 1856
ff517991 1857 timeout_mode = get_constructor_timeout(&constructor_timeout);
11ff9c7d 1858
b2c5f61a 1859 get_allow_blocking();
6f97f9c2 1860
95259bd0 1861 ret = sem_init(&constructor_wait, 0, 0);
8aadb54a
MD
1862 if (ret) {
1863 PERROR("sem_init");
1864 }
11ff9c7d 1865
060577e3
JR
1866 ret = setup_global_apps();
1867 if (ret) {
1868 assert(global_apps.allowed == 0);
1869 DBG("global apps setup returned %d", ret);
1870 }
1871
8d20bf54 1872 ret = setup_local_apps();
2691221a 1873 if (ret) {
060577e3 1874 assert(local_apps.allowed == 0);
9ec6895c 1875 DBG("local apps setup returned %d", ret);
2691221a 1876 }
ae6a58bf
WP
1877
1878 /* A new thread created by pthread_create inherits the signal mask
1879 * from the parent. To avoid any signal being received by the
1880 * listener thread, we block all signals temporarily in the parent,
1881 * while we create the listener thread.
1882 */
1883 sigfillset(&sig_all_blocked);
1884 ret = pthread_sigmask(SIG_SETMASK, &sig_all_blocked, &orig_parent_mask);
1885 if (ret) {
d94d802c 1886 ERR("pthread_sigmask: %s", strerror(ret));
ae6a58bf
WP
1887 }
1888
1879f67f
MG
1889 ret = pthread_attr_init(&thread_attr);
1890 if (ret) {
1891 ERR("pthread_attr_init: %s", strerror(ret));
1892 }
1893 ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
1894 if (ret) {
1895 ERR("pthread_attr_setdetachstate: %s", strerror(ret));
1896 }
1897
060577e3
JR
1898 if (global_apps.allowed) {
1899 pthread_mutex_lock(&ust_exit_mutex);
1900 ret = pthread_create(&global_apps.ust_listener, &thread_attr,
1901 ust_listener_thread, &global_apps);
1902 if (ret) {
1903 ERR("pthread_create global: %s", strerror(ret));
1904 }
1905 global_apps.thread_active = 1;
1906 pthread_mutex_unlock(&ust_exit_mutex);
1907 } else {
1908 handle_register_done(&global_apps);
d94d802c 1909 }
e33f3265 1910
8d20bf54 1911 if (local_apps.allowed) {
c0bbbd5a 1912 pthread_mutex_lock(&ust_exit_mutex);
1879f67f 1913 ret = pthread_create(&local_apps.ust_listener, &thread_attr,
dde70ea0 1914 ust_listener_thread, &local_apps);
d94d802c
MD
1915 if (ret) {
1916 ERR("pthread_create local: %s", strerror(ret));
1917 }
e33f3265 1918 local_apps.thread_active = 1;
c0bbbd5a 1919 pthread_mutex_unlock(&ust_exit_mutex);
8d20bf54
MD
1920 } else {
1921 handle_register_done(&local_apps);
1922 }
1879f67f
MG
1923 ret = pthread_attr_destroy(&thread_attr);
1924 if (ret) {
1925 ERR("pthread_attr_destroy: %s", strerror(ret));
1926 }
8d20bf54 1927
ae6a58bf
WP
1928 /* Restore original signal mask in parent */
1929 ret = pthread_sigmask(SIG_SETMASK, &orig_parent_mask, NULL);
1930 if (ret) {
d94d802c 1931 ERR("pthread_sigmask: %s", strerror(ret));
ae6a58bf
WP
1932 }
1933
cf12a773
MD
1934 switch (timeout_mode) {
1935 case 1: /* timeout wait */
95259bd0
MD
1936 do {
1937 ret = sem_timedwait(&constructor_wait,
1938 &constructor_timeout);
1939 } while (ret < 0 && errno == EINTR);
8aadb54a
MD
1940 if (ret < 0) {
1941 switch (errno) {
1942 case ETIMEDOUT:
1943 ERR("Timed out waiting for lttng-sessiond");
1944 break;
1945 case EINVAL:
1946 PERROR("sem_timedwait");
1947 break;
1948 default:
1949 ERR("Unexpected error \"%s\" returned by sem_timedwait",
1950 strerror(errno));
1951 }
cf12a773
MD
1952 }
1953 break;
7b766b16 1954 case -1:/* wait forever */
95259bd0
MD
1955 do {
1956 ret = sem_wait(&constructor_wait);
1957 } while (ret < 0 && errno == EINTR);
8aadb54a
MD
1958 if (ret < 0) {
1959 switch (errno) {
1960 case EINVAL:
1961 PERROR("sem_wait");
1962 break;
1963 default:
1964 ERR("Unexpected error \"%s\" returned by sem_wait",
1965 strerror(errno));
1966 }
1967 }
cf12a773 1968 break;
7b766b16 1969 case 0: /* no timeout */
cf12a773 1970 break;
11ff9c7d 1971 }
2691221a
MD
1972}
1973
17dfb34b
MD
1974static
1975void lttng_ust_cleanup(int exiting)
1976{
efe0de09 1977 cleanup_sock_info(&global_apps, exiting);
932cfadb 1978 cleanup_sock_info(&local_apps, exiting);
74f98bc9 1979 local_apps.allowed = 0;
060577e3 1980 global_apps.allowed = 0;
efe0de09
MD
1981 /*
1982 * The teardown in this function all affect data structures
1983 * accessed under the UST lock by the listener thread. This
1984 * lock, along with the lttng_ust_comm_should_quit flag, ensure
1985 * that none of these threads are accessing this data at this
1986 * point.
1987 */
17dfb34b 1988 lttng_ust_abi_exit();
003fedf4 1989 lttng_ust_events_exit();
d58d1454 1990 lttng_perf_counter_exit();
34a91bdb 1991 lttng_ring_buffer_client_discard_rt_exit();
7dd08bec 1992 lttng_ring_buffer_client_discard_exit();
34a91bdb 1993 lttng_ring_buffer_client_overwrite_rt_exit();
7dd08bec
MD
1994 lttng_ring_buffer_client_overwrite_exit();
1995 lttng_ring_buffer_metadata_client_exit();
cf73e0fe 1996 lttng_ust_statedump_destroy();
17dfb34b
MD
1997 exit_tracepoint();
1998 if (!exiting) {
1999 /* Reinitialize values for fork */
eb0e6022 2000 sem_count = sem_count_initial_value;
17dfb34b
MD
2001 lttng_ust_comm_should_quit = 0;
2002 initialized = 0;
2003 }
2004}
2005
edaa1431 2006void __attribute__((destructor)) lttng_ust_exit(void)
2691221a
MD
2007{
2008 int ret;
2009
9eb62b9c
MD
2010 /*
2011 * Using pthread_cancel here because:
2012 * A) we don't want to hang application teardown.
2013 * B) the thread is not allocating any resource.
2014 */
1ea11eab
MD
2015
2016 /*
2017 * Require the communication thread to quit. Synchronize with
2018 * mutexes to ensure it is not in a mutex critical section when
2019 * pthread_cancel is later called.
2020 */
3327ac33 2021 ust_lock_nocheck();
1ea11eab 2022 lttng_ust_comm_should_quit = 1;
3327ac33 2023 ust_unlock();
1ea11eab 2024
3327ac33 2025 pthread_mutex_lock(&ust_exit_mutex);
f5f94532 2026 /* cancel threads */
e33f3265
MD
2027 if (global_apps.thread_active) {
2028 ret = pthread_cancel(global_apps.ust_listener);
2029 if (ret) {
2030 ERR("Error cancelling global ust listener thread: %s",
2031 strerror(ret));
2032 } else {
2033 global_apps.thread_active = 0;
2034 }
2691221a 2035 }
e33f3265 2036 if (local_apps.thread_active) {
8d20bf54
MD
2037 ret = pthread_cancel(local_apps.ust_listener);
2038 if (ret) {
d94d802c
MD
2039 ERR("Error cancelling local ust listener thread: %s",
2040 strerror(ret));
e33f3265
MD
2041 } else {
2042 local_apps.thread_active = 0;
8d20bf54 2043 }
8d20bf54 2044 }
3327ac33 2045 pthread_mutex_unlock(&ust_exit_mutex);
e33f3265 2046
efe0de09
MD
2047 /*
2048 * Do NOT join threads: use of sys_futex makes it impossible to
2049 * join the threads without using async-cancel, but async-cancel
2050 * is delivered by a signal, which could hit the target thread
2051 * anywhere in its code path, including while the ust_lock() is
2052 * held, causing a deadlock for the other thread. Let the OS
2053 * cleanup the threads if there are stalled in a syscall.
2054 */
17dfb34b 2055 lttng_ust_cleanup(1);
2691221a 2056}
e822f505 2057
735bef47
MJ
2058static
2059void ust_context_ns_reset(void)
2060{
2061 lttng_context_pid_ns_reset();
2062 lttng_context_cgroup_ns_reset();
2063 lttng_context_ipc_ns_reset();
2064 lttng_context_mnt_ns_reset();
2065 lttng_context_net_ns_reset();
2066 lttng_context_user_ns_reset();
2067 lttng_context_uts_ns_reset();
2068}
2069
fca2f191
MJ
2070static
2071void ust_context_vuids_reset(void)
2072{
2073 lttng_context_vuid_reset();
2074 lttng_context_veuid_reset();
2075 lttng_context_vsuid_reset();
2076}
2077
2078static
2079void ust_context_vgids_reset(void)
2080{
2081 lttng_context_vgid_reset();
2082 lttng_context_vegid_reset();
2083 lttng_context_vsgid_reset();
2084}
2085
e822f505
MD
2086/*
2087 * We exclude the worker threads across fork and clone (except
2088 * CLONE_VM), because these system calls only keep the forking thread
2089 * running in the child. Therefore, we don't want to call fork or clone
2090 * in the middle of an tracepoint or ust tracing state modification.
2091 * Holding this mutex protects these structures across fork and clone.
2092 */
b728d87e 2093void ust_before_fork(sigset_t *save_sigset)
e822f505
MD
2094{
2095 /*
2096 * Disable signals. This is to avoid that the child intervenes
2097 * before it is properly setup for tracing. It is safer to
2098 * disable all signals, because then we know we are not breaking
2099 * anything by restoring the original mask.
2100 */
2101 sigset_t all_sigs;
2102 int ret;
2103
c362addf
MD
2104 /* Fixup lttng-ust TLS. */
2105 lttng_ust_fixup_tls();
2106
8c90a710 2107 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2108 return;
e822f505
MD
2109 /* Disable signals */
2110 sigfillset(&all_sigs);
b728d87e 2111 ret = sigprocmask(SIG_BLOCK, &all_sigs, save_sigset);
e822f505
MD
2112 if (ret == -1) {
2113 PERROR("sigprocmask");
2114 }
458d678c
PW
2115
2116 pthread_mutex_lock(&ust_fork_mutex);
2117
3327ac33 2118 ust_lock_nocheck();
d6ddec3f 2119 urcu_bp_before_fork();
c1be081a 2120 lttng_ust_lock_fd_tracker();
20142124 2121 lttng_perf_lock();
e822f505
MD
2122}
2123
b728d87e 2124static void ust_after_fork_common(sigset_t *restore_sigset)
e822f505
MD
2125{
2126 int ret;
2127
17dfb34b 2128 DBG("process %d", getpid());
20142124 2129 lttng_perf_unlock();
c1be081a 2130 lttng_ust_unlock_fd_tracker();
17dfb34b 2131 ust_unlock();
458d678c
PW
2132
2133 pthread_mutex_unlock(&ust_fork_mutex);
2134
e822f505 2135 /* Restore signals */
23c8854a 2136 ret = sigprocmask(SIG_SETMASK, restore_sigset, NULL);
e822f505
MD
2137 if (ret == -1) {
2138 PERROR("sigprocmask");
2139 }
2140}
2141
b728d87e 2142void ust_after_fork_parent(sigset_t *restore_sigset)
e822f505 2143{
8c90a710 2144 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2145 return;
17dfb34b 2146 DBG("process %d", getpid());
d6ddec3f 2147 urcu_bp_after_fork_parent();
e822f505 2148 /* Release mutexes and reenable signals */
b728d87e 2149 ust_after_fork_common(restore_sigset);
e822f505
MD
2150}
2151
17dfb34b
MD
2152/*
2153 * After fork, in the child, we need to cleanup all the leftover state,
2154 * except the worker thread which already magically disappeared thanks
2155 * to the weird Linux fork semantics. After tyding up, we call
2156 * lttng_ust_init() again to start over as a new PID.
2157 *
2158 * This is meant for forks() that have tracing in the child between the
2159 * fork and following exec call (if there is any).
2160 */
b728d87e 2161void ust_after_fork_child(sigset_t *restore_sigset)
e822f505 2162{
8c90a710 2163 if (URCU_TLS(lttng_ust_nest_count))
e8508a49 2164 return;
06b16a0b 2165 lttng_context_vpid_reset();
8478887d 2166 lttng_context_vtid_reset();
46228a6f 2167 lttng_context_procname_reset();
735bef47 2168 ust_context_ns_reset();
fca2f191
MJ
2169 ust_context_vuids_reset();
2170 ust_context_vgids_reset();
17dfb34b 2171 DBG("process %d", getpid());
e822f505 2172 /* Release urcu mutexes */
d6ddec3f 2173 urcu_bp_after_fork_child();
17dfb34b 2174 lttng_ust_cleanup(0);
e822f505 2175 /* Release mutexes and reenable signals */
b728d87e 2176 ust_after_fork_common(restore_sigset);
318dfea9 2177 lttng_ust_init();
e822f505 2178}
95c25348 2179
735bef47
MJ
2180void ust_after_setns(void)
2181{
2182 ust_context_ns_reset();
fca2f191
MJ
2183 ust_context_vuids_reset();
2184 ust_context_vgids_reset();
735bef47
MJ
2185}
2186
2187void ust_after_unshare(void)
2188{
2189 ust_context_ns_reset();
fca2f191
MJ
2190 ust_context_vuids_reset();
2191 ust_context_vgids_reset();
2192}
2193
2194void ust_after_setuid(void)
2195{
2196 ust_context_vuids_reset();
2197}
2198
2199void ust_after_seteuid(void)
2200{
2201 ust_context_vuids_reset();
2202}
2203
2204void ust_after_setreuid(void)
2205{
2206 ust_context_vuids_reset();
2207}
2208
2209void ust_after_setresuid(void)
2210{
2211 ust_context_vuids_reset();
2212}
2213
2214void ust_after_setgid(void)
2215{
2216 ust_context_vgids_reset();
2217}
2218
2219void ust_after_setegid(void)
2220{
2221 ust_context_vgids_reset();
2222}
2223
2224void ust_after_setregid(void)
2225{
2226 ust_context_vgids_reset();
2227}
2228
2229void ust_after_setresgid(void)
2230{
2231 ust_context_vgids_reset();
735bef47
MJ
2232}
2233
246be17e 2234void lttng_ust_sockinfo_session_enabled(void *owner)
95c25348
PW
2235{
2236 struct sock_info *sock_info = owner;
37dddb65 2237 sock_info->statedump_pending = 1;
95c25348 2238}
This page took 0.161888 seconds and 4 git commands to generate.