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