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